_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d11801 | train | Below example will help you to "Get Multiple Parameters with same name from a URL in PHP". | unknown | |
d11802 | train | The accordion-group template uses the uib-collapse directive to open/close the panels, see here Removing the uib-collapse directive will bypass some of the unexpected behavior you are seeing, but I think you will need to manage closing/opening the panels. | unknown | |
d11803 | train | As of now, Copyleaks API not arriving from fixed list of IP addresses. But, you have other alternatives to securing your endpoints. The options described here:
https://api.copyleaks.com/documentation/v3/webhooks/security
Another option you have to secure your endpoints is to add "Authentication" header to the webhook request with a private secret in its value. With Copyleaks API you have the ability to specify the headers that will arrive to your endpoints. | unknown | |
d11804 | train | Your problem is in (*pos << 24) | (*(pos+1) << 16) | (*(pos+2) << 8) | *(pos+3).
If any of the values in pos[0,...,3] is negative, then the entire expression is negative. | unknown | |
d11805 | train | First of all: Java !== Javascript
Java and Javascript are similar like Car and Carpet are similar.
Source: https://stackoverflow.com/a/245068/3119231
-
To redirect an user to another location you may use:
// Simulate a mouse click:
setTimeout(function() { // timer
window.location.href = url;
}, 10000); // 10000 ms = 10 seconds
// Simulate an HTTP redirect:
setTimeout(function() { // timer
window.location.replace(url);
}, 10000); // 10000 ms = 10 seconds
Place it in the documents you like.
Source: https://www.w3schools.com/howto/howto_js_redirect_webpage.asp
Bonus (CaitLAN Jenner): You need to prevent your documents from redirecting in an infinite loop. Your visitors would get pushed from one site to another every 10 seconds.
A: @Maurice mentioned how to perform a HTTP redirect in JavaScript. If you do this on both pages, however, then you will find yourself in an infinite redirect loop, which is very bad. To expand on that answer here is some PHP to dynamically disable the second redirect from the original page through the use of a query string parameter (see https://en.wikipedia.org/wiki/Query_string).
First, you need to include the following PHP code at the top of your document. If you have other PHP code, just put the inside of this code below it. This will accept the redirect query string.
<?php
$redirect = 1
if (isset($_GET['redirect'])) {
$redirect = htmlspecialchars($_GET["redirect"]);
}
?>
Now, later in the document (preferably at the end of body or within head) you need to dynamically generate the JavaScript using PHP as such.
<?php
if ($redirect == 1)
{
echo "<script>";
echo "// Simulate an HTTP redirect:";
echo "setTimeout(function() { // timer";
echo "window.location.replace(url);";
echo "}, 10000); // 10000 ms = 10 seconds";
echo "</script";
}
?>
Note that you will need to replace "url" here with the appropriate url, which may require properly escaping quotations (see https://www.php.net/manual/en/function.addslashes.php)
As a final note, you need to set the "redirect" query string appropriately on the page that redirects back to the original. You can do so with something like this:
mydomain.net/games/?game=PUBG+Mobile&Rating=5&redirect=0
UPDATE PER REQUEST
On the second page you don't need the PHP logic mentioned above. You simply need a JavaScript 10 second redirect. Something like this should work.
<script>
url = "mydomain.net/games/?game=PUBG+Mobile&Rating=5&redirect=0";
// Simulate an HTTP redirect:
setTimeout(function() { // timer
window.location.replace(url);
}, 10000); // 10000 ms = 10 seconds
</script>
Note that here I've used a static URL. If you want this URL to be dynamic you can use the exact same approach I've mentioned for solving the infinite redirect. In other words, pass the original URL as a query string parameter to the ad page, parse it on the ad page through PHP, and use PHP to dynamically create the url in the code above. | unknown | |
d11806 | train | This is not perfect but I've corrected it by setting the layout of the dialog relative to the default display.
dialog = new Dialog(this, R.style.AlertDialogTheme);
dialog.setContentView(layout);
Window window = dialog.getWindow();
window.setLayout(
(int)(window.getWindowManager().getDefaultDisplay().getWidth() * .90),
(int)(window.getWindowManager().getDefaultDisplay().getHeight() * .90 ));
dialog.setCancelable(false);
Just tweak the ".90" values until it feels right.
A: Here is the solution:
*
*You should add a Linearlayout at the outside of your dialog's xml file
*Then set this Linearlayout's gravity as "center"
*the last step is creating a LayoutParams and set it to the dialog
android.view.WindowManager.LayoutParams lp = new android.view.WindowManager.LayoutParams();
lp.width = android.view.WindowManager.LayoutParams.FILL_PARENT;
lp.height = android.view.WindowManager.LayoutParams.FILL_PARENT;
alertDialog.getWindow().setAttributes(lp); | unknown | |
d11807 | train | As a matter of interest, when using EF Core with Oracle, multiple parallel operations like the post here using a single DB context work without issue (despite Microsoft's documentation). The limitation is in the Microsoft.EntityFrameworkCore.SqlServer.dll driver, and is not a generalized EF issue. The corresponding Oracle.EntityFrameworkCore.dll driver doesn't have this limitation.
A: The problem is this:
EF doesn't support processing multiple requests through the same DbContext object. If your second asynchronous request on the same DbContext instance starts before the first request finishes (and that's the whole point), you'll get an error message that your request is processing against an open DataReader.
Source: https://visualstudiomagazine.com/articles/2014/04/01/async-processing.aspx
You will need to modify your code to something like this:
async Task<List<E1Entity>> GetE1Data()
{
using(var MyCtx = new MyCtx())
{
return await MyCtx.E1.Where(bla bla bla).ToListAsync();
}
}
async Task<List<E2Entity>> GetE2Data()
{
using(var MyCtx = new MyCtx())
{
return await MyCtx.E2.Where(bla bla bla).ToListAsync();
}
}
async Task DoSomething()
{
var t1 = GetE1Data();
var t2 = GetE2Data();
await Task.WhenAll(t1,t2);
DoSomething(t1.Result, t2.Result);
}
A: Check out https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/enabling-multiple-active-result-sets
From the documentation:
Statement interleaving of SELECT and BULK INSERT statements is
allowed. However, data manipulation language (DML) and data definition
language (DDL) statements execute atomically.
Then your above code works and you get the performance benefits for reading data. | unknown | |
d11808 | train | The cause
The form disappears because when the user clicks the button labeled Query Domain, the form is submitted. Because the form has no action method, it basically reloads index.php.
Changes
As have been pointed out in comments, there are a few things that need to be changed in order to get it working:
*
*in the form submission handler - prevent the default form submission by either
*
*calling preventDefault() on the event object (i.e. e in the example below), which is passed to the callback function:
$( ".form" ).submit(function(e)
{
//stop form submission
e.preventDefault();
*returning false at the end of the function
*pass the value of the input to the diagnostics results by appending it to the query string (e.g. use jQuery's $.val()):
$(".domain-d-container").load("domaindiagnosticsresults.php",
{
d: $('#domainName').val()
*there was an excess closing div tag (i.e. </div>) that should be removed after <div class="domain-d-container"></div> in the domaindiagnostics.php page.
*The (closing) </html> and </body> tags should be removed from the nested pages (e.g. domaindiagnostics.php), lest those tags exist as child tags of the body of the index page (those would not be permitted content of a <div> - only flow content is allowed).
See it demonstrated in this phpfiddle. Bear in mind that only one PHP page is allowed in that environment so I had to combine the three pages and use $_SERVER['PHP_SELF'] for the URLs and pass data via the query string, so some of the checks on $_POST were converted to checks on $_GET.
A: Maybe this link con help you. https://dailygit.com/create-a-simple-ajax-contact-form-with-jquery-and-php/
Remove the "send mail" part and focus on the form submission part. as said in other comments, prevent default is really important and the DOM structure must be cleaner as possible. | unknown | |
d11809 | train | This is not related to django, this is related to python in general. When you want to access a class property within the class you always have to call self before!
class Tree:
fruits = 5
@property
def leafes(self):
return self.fruits * 5
def show_tree(self):
print(self.fruits)
print(self.leafes)
print(leafes) # THIS LINE WOULD ERROR
Edit after comment of OP
I don't know how to phrase this properly. Anyhow this keeps being a problem related to python and not to django. The reason is how classes work.
You probably know the def __init__(self): function. That is called when the class gets instanciated. After that function got called your class can use all the self attributes (class attributes). But class attributes like my fruits = 5 get assigned even before that def __init__(self) method is called. So all your assignments directly inside the body of the class do not have self yet.
class Tree:
fruits = 5
def __init__(self):
self.twigs = 10
self.weight = self.twigs + self.fruits # THIS WORKS
class Tree:
fruits = 5
weight = self.twigs + fruits # THIS DOES NOT WORK
def __init__(self):
self.twigs = 10
Last example does not work because at the moment you want to assign weight = self.twigs + fruits your class's __init__ function was not called yet. So you can not use self at that place. | unknown | |
d11810 | train | First of all you can create DataGridViewCheckBoxColumn outside of loadData method, Maybe in constructor. So it will be created only once.
To retain Checkbox selection, you can add boolean field in datatable or in database. Everytime you click on a row , just update that flag.
When you have DataGridViewCheckBoxColumn , when rebinding datasource, this column is automatically checked or unchecked according to boolean flag | unknown | |
d11811 | train | The problem is a variation of the Knapsack problem; instead of choosing whether an item is to be included in the solution, a choice must be made which item to take from each category. Although not explicitly stated in the Wikipedia article, the formulation in the question can be solved within a pseudopolynomial runtime bound via Dynamic programming by modifying the recurrence relation for the basic formulation.
A: Just a fun with Python's itertools:
import itertools
def solutions(dicts, value):
return [keys for keys in itertools.product(*dicts) if sum(d[k] for d, k in zip(dicts, keys)) == value]
Shirt = {"shirtA": 20, "shirtB": 15, "shirtC": 10}
Pants = {"pantsA": 30, "pantsB": 25, "pantsC": 20}
Shoes = {"shoesA": 20, "shoesB": 15, "shoesC": 10}
print solutions([Shirt, Pants, Shoes], 60)
We generate all allowed combinations (one piece from each category) but we keep only these that give the required sum. | unknown | |
d11812 | train | The way the API limits would work for you is that:
Every user would have a limit of 100 requests per 100 seconds per user, since you are performing these requests on the behalf of the user.
If you application was performing these requests instead, then you would reach the 500 requests per 100 seconds.
Hope this clarifies it! | unknown | |
d11813 | train | There is at least one way to do this; I'll outline an approach below. First a few things to think about:
Depending on the nature of the changes that occur, you might want to see if frequent packing of the database might help; git is pretty good at avoiding wasted space (for text files, at least).
Of course with the commit load you describe - 1440 commits per day, give or take? - the history will tend to grow. Still, unless the changes are dramatic on every commit, it seems like it could be made better than "many GB in a few days"; and maybe you'd reach a level where a compromise archiving strategy would become practical.
It's always worth thinking, too, about whether "all the data I need to keep" is bigger than "all the data I need regular access to"; because then you can consider whether some of the data should be preserved in archive repos, possibly on backup media of some form, rather than as part of the live repo.
And, as you allude in your question, you might want to consider whether git is the best tool for the job. Your described usage doesn't use most of git's capabilities; nor does it exercise the features that really make git excel. And conversely, other tools might make it easier to progressively thin out the history.
But with all of that said, you still might reach the decision to start with "per minute" data, then eventually drop it to "per hour", and maybe still later reduce to *per week".
(I'd discourage defining too many levels of granularity; the most "bang for your buck" will come with discarding sub-hourly snapshots. Hour->day would be borderline, day->week would probably be wasteful. If you get down to weekly, that's surely sparse enough...)
So when some data "ages out", what to do? I suggest that you could use some combination of rebasing (and/or related operations), depth limits, and replacements (depending on your needs). Depending on how you combine these, you could keep the illusion of a seamless history without changing the SHA ID of any "current" commit. (With more complex techniques, you could even arrange to never change a SHA ID; but this is noticeably harder and will reduce the space savings somewhat.)
So in the following diagrams, there is a root commit identified as 'O'. Subsequent commits (the minutely changes) are identified by a letter and a number. The letter indicates the day the commit was created, the numbers sequentially mark off minutes.
You create your initial commit and place branches on it for each granularity of history you'll eventually use. (As changes accumulate each minute, they'll just go on master.)
O <--(master)(hourly)(weekly)
After a couple days you have
O <-(hourly)(weekly)
\
A1 - A2 - A3 - ... - A1439 - A1440 - B1 - B2 - ... - B1439 - B1440 - C1 <--(master)
And maybe you've decided that at midnight, any sub-hour snapshot that's 24 hours old can be discarded.
So as day C starts, the A snapshots are older than 24 hours and should be reduced to hourly snapshots. First we must create the hourly snapshots
git checkout hourly
git merge --squash A60
git commit -m 'Day A 1-60'
git merge --squash A120
git commit -m 'Day A 61-120'
...
And this gives you
O <-(weekly)
|\
| A60' - A120' - ... - A1380' - A1440' <-(hourly)
\
A1 - A2 - A3 - ... - A1439 - A1440 - B1 - B2 - ... - B1439 - B1440 - C1 <--(master)
Here A1440' is a rewrite of A1440, but with a different parentage (such that its direct parent is "an hour ago" instead of "a minute ago").
Next, to make the history seamless you would have B1 identify A1440' as its parent. If you don't care about changing the SHA ID of every commit (including current ones), a rebase will work
git rebase --onto A1440' A1440 master
Or in this case (since the TREEs at A1440 and A1440' are the same) it would be equivalent to re-parent B1 - see the git filter-branch docs for details of that approach. Either way you would end up with
O <-(weekly)
|\
| A60' - A120' - ... - A1380' - A1440' <-(hourly)
| \
| B1' - B2' - ... - B1439' - B1440' - C1' <-(master)
\
A1 - A2 - A3 - ... - A1439 - A1440 - B1 - B2 - ... - B1439 - B1440 - C1
Note that even though the granularity of changes in the B and C commits is unchanged, these are still "rewritten" commits (hence the ' notation); and in fact the original commits have not yet been physically deleted. They are unreachable, though, so they'll eventually be cleaned up by gc; if it's an issue, you can expedite this by discarding reflogs that are more than 24 hours old and then manually running gc.
Alternatively, if you want to preserve SHA ID's for the B and C commits, you could use git replace.
git replace A1440 A1440'
This has a number of drawbacks, though. There are a few known quirks with replacements. Also in this scenario the original commits are not unreachable (even though they aren't shown by default); you would have to shallow the master branch to get rid of them. The simplest way to shallow a branch is to clone the repo, but then you have to jump through extra hoops to propagate the replacement refs. So this is an option if you never want the master ref to "realize" it's moving in an abnormal way, but not as simple. | unknown | |
d11814 | train | This is pretty close:
// globals
var pairs = {
{ div : 'div1', url : 'http://some.net/address?client=Some+Client' } ,
{ div : 'div2', url : 'http://some.net/otheraddress?client=Some+Client' } ,
};
var since_record_id; //?? not sure what this is
var intervals = [];
// window onload
window.onload(){ // I don't think this is gonna work
for(var i; i<pairs.length; i++) {
getRecent(pairs[i]);
intervals.push(setInterval(function(){
pollForNew(map[i]);
}, 300000));
}
}
function getRecent(map){
var url = map.url + '&recent=20';
// do stuff here to retrieve the resource
var content = loadResoucrce(url); // must define this
var elt = document.getElementById(map.div);
elt.innerHTML = content;
}
function pollForNew(map){
var url = map.url + '&since_record_id=' + since_record_id;
var content = loadResoucrce(url); // returns an html fragment
var elt = document.getElementById(map.div);
elt.innerHTML = content;
}
and the html obviously needs two divs:
<div id='div1' class='data_div'></div>
<div id='div2' class='data_div'></div>
Your 'window.onload` - I don't think that's gonna work, but maybe you have it set up correctly and didn't want to bother putting in all the code.
About my suggested code - it defines an array in the global scope, an array of objects. Each object is a map, a dictionary if you like. These are the params for each div. It supplies the div id, and the url stub. If you have other params that vary according to div, put them in the map.
Then, call getRecent() once for each map object. Inside the function you can unwrap the map object and get at its parameters.
You also want to set up that interval within the loop, using the same parameterization. I myself would prefer to use setTimeout(), but that's just me.
You need to supply the loadResource() function that accepts a URL (string) and returns the HTML available at that URL.
This solves the problem of modularity, but it is not "an object" or class-based approach to the problem. I'm not sure why you'd want one with such a simple task. Here's a crack an an object that does what you want:
(function() {
var getRecent = function(url, div){
url = url + '&recent=20';
// do stuff here to retrieve the resource
var content = loadResoucrce(url); // must define this
var elt = document.getElementById(div);
elt.innerHTML = content;
}
var pollForNew = function(url, div){
url = url + '&since_record_id=' + since_record_id;
var content = loadResoucrce(url); // returns an html fragment
var elt = document.getElementById(div);
elt.innerHTML = content;
}
UpdatingDataDiv = function(map) {
if (! (this instanceof arguments.callee) ) {
var error = new Error("you must use new to instantiate this class");
error.source = "UpdatingDataDiv";
throw error;
}
this.url = map.url;
this.div = map.div;
this.interval = map.interval || 30000; // default 30s
var self = this;
getRecent(this.url, this.div);
this.intervalId = setInterval(function(){
pollForNew(self.url, self.div);
}, this.interval);
};
UpdatingDataDiv.prototype.cancel = function() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
})();
var d1= new UpdatingDataDiv('div1','http://some.net/address?client=Some+Client');
var d2= new UpdatingDataDiv('div2','http://some.net/otheraddress?client=Some+Client');
...
d1.cancel();
But there's not a lot you can do with d1 and d2. You can invoke cancel() to stop the updating. I guess you could add more functions to extend its capability.
A: OK, figured out what I needed. It's pretty straight forward.
First off disregard window.onload, the object is defined as a function and when you instantiate a new object it runs the function. Do your setup in the function.
Second, for global variables that you wish to make local to your object, simply define them as this.variable_name; within the object. Those variables are visible throughout the object, and its member functions.
Third, define your member functions as object.prototype.function = function(){};
Fourth, for my case, the object function should return this; This allows regular program flow to examine the variables of the object using dot notation.
This is the answer I was looking for. It takes my non-functional example code, and repackages it as an object...
function ServerObject(url){
// global to the object
this.server_url = url;
this.data = new Object();
this.since_record_id;
this.interval_id;
// do the onload functions
this.getRecent();
this.interval_id = setInterval(function(){
this.pollForNew();
}, 300000);
// do other stuff to setup the object
return this;
}
// define the getRecent function
ServerObject.prototype.getRecent = function(){
// do getRecent(); stuff
// reference object variables as this.variable;
}
// same for pollForNew();
ServerObject.prototype.pollForNew = function(){
// do pollForNew(); stuff here.
// reference object variables as this.variable;
}
Then in your program flow you do something like...
var server = new ServerObject("http://some.net/address");
server.variable = newValue; // access object variables
I mentioned the ADD in the first post. I'm smart enough to know how complex objects can be, and when I look for examples and explanations they expose certain layers of those complexities that cause my mind to just swim. It is difficult to drill down to the simple rules that get you started on the ground floor. What's the scope of 'this'? Sure I'll figure that out someday, but the simple truth is, you gotta reference 'this'.
Thanks
I wish I had more to offer.
Skip | unknown | |
d11815 | train | I get the function instead of data
console.log(response);
This prints out the function instead of the response data, because response is the name of your function, not the name of the argument passed to the function. Consider the change below:
function TestAPI() {
FB.api('/me?fields=id,name,email', function(response) {
if (response && !response.error) {
console.log(response);
buildProfile (response);
}
});
}
TypeError: Cannot set property 'innerHTML' of null
This means that document.getElementById('profile') is returning null, it's possible that an element with this id does not exist in your DOM, but this is difficult to confirm without you sharing a code excerpt of the HTML you're trying to modify. You should have an element that looks something like this:
<div id="profile"></div> | unknown | |
d11816 | train | The section marked 'If you were NOT previously asking for offline_access' in that document explains how to exchange that 2 hour token for a 60 day token: (note that the 2 hours and 60 days values could change in future)
https://developers.facebook.com/roadmap/offline-access-removal/#extend_token
Just access
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
And the token returned will have a longer expiry (it may be the same token with a longer expiry or a new token, you should handle both cases) | unknown | |
d11817 | train | For this use case it’s probably best to use HTL templates:
<sly data-sly-use.common="common.html" data-sly-call="${common.myTemplate @ buttonClass='myClassA'}"></sly>
A: You can make use of requestAttributes (refer here)
Component A (passing the value):
Sightly :
<sly data-sly-use.compA = "com.mysite.core.models.CompA"/>
<div
data-sly-resource="${ 'abc' @ resourceType = 'btplayer-cms/components/content/some-common-component', requestAttributes = compA.attribute }">
</div>
Sling Model :
package com.realogy.sir.core.models;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Model;
@Model(adaptables = SlingHttpServletRequest.class)
public class CompA {
public Map<String, Object> attribute = new HashMap<>();
@PostConstruct
protected void init() {
attribute.put("attributeVal", "componenta");
}
}
Component B (passing the value):
Sightly :
<sly data-sly-use.compB = "com.mysite.core.models.CompB"/>
<div
data-sly-resource="${ 'xyz' @ resourceType = 'btplayer-cms/components/content/some-common-component', requestAttributes = compB.attribute }">
</div>
Sling Model :
package com.realogy.sir.core.models;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Model;
@Model(adaptables = SlingHttpServletRequest.class)
public class CompB {
public Map<String, Object> attribute = new HashMap<>();
@PostConstruct
protected void init() {
attribute.put("attributeVal", "componentb");
}
}
Common Component (consuming the value):
Sightly :
<sly data-sly-use.commonComp= "com.mysite.core.models.CommonComp"/>
<div class="${[commonComp.attributeVal, 'button'] @ join='-'}"></div>
Sling Model:
package com.mysite.core.models;
import javax.inject.Inject;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Model;
@Model(adaptables = SlingHttpServletRequest.class)
public class CommonComp {
@Inject @Optional @Default(values="component")
private String attributeVal;
public String getAttributeVal() {
return attributeVal;
}
} | unknown | |
d11818 | train | Glad you are learning. Apologies if my response comes across in a different plane than your current level.
When you run JS, you're executing the code in the current state of the content. It appears that you are hoping for the icon to change from a + to a - and vice verse when the accordion is expanded/collapsed.
What you need to do, is watch the page for changes to the accordion - these are called event listeners. Bootstrap has some really convenient ones that you can use for this. Since the Accordion uses collapse events API. From there, you can watch the page for changes, and execute the change you want whenever that change happens.
const myCollapsible = document.getElementById('myCollapsible')
myCollapsible.addEventListener('hidden.bs.collapse', event => {
// do something...
}) | unknown | |
d11819 | train | This worked for me:
XAML:
...
<r:RibbonComboBox IsEditable="True">
<r:RibbonGallery >
<r:RibbonGalleryCategory ItemsSource="{Binding}" Name="userBox" />
</r:RibbonGallery>
</r:RibbonComboBox>
...
C#
...
userBox.ItemsSource = LoadComboBoxUser();
... | unknown | |
d11820 | train | Put this in E2 and copy/drag down:
=IF(D2<>"",IF(SUM($D$1:D2)>40,MIN(D2,SUM($D$1:D2)-40),0),"") | unknown | |
d11821 | train | <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_below="@id/imgEmpty"
android:text="Sorry, no list available"/>
Insert it below your ImageView of RelativeLayout!
A: Replace your Relative layout with this.
<RelativeLayout
android:id="@+id/huhu"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recylcerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:visibility="gone" />
<ImageView
android:id="@+id/imgEmpty"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:src="@drawable/empty"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_below="@id/imgEmpty"
android:text="Sorry, no list available"/>
A: Add this below imgEmpty. Use android:layout_below to place the text below image,android:layout_centerInParent="true" to move text to center.
<TextView
android:layout_marginTop="20dp"
android:layout_centerInParent="true"
android:text = "Sorry, no list available"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imgEmpty"/>
Here the output
A: in relative layout you can use below/above to put view below/above its sibling
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/imgEmpty"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:text="TextView"/> | unknown | |
d11822 | train | I am mostly confused by the introduction of [k] in the equation as I don't know how it changes the list.
someList[k] is an item accessor for the kth item of the list. So for a list a = [2, 3, 5, 7], a[k] will return the kth number. For example:
>>> a = [2, 3, 5, 7]
>>> a[0]
2
>>> a[1]
3
>>> k = 3
>>> a[k]
7
Using the accessor alone will just read the value without affecting the list. Python however does allow you to also assign a value to it. Doing so will change the list’s item at that index:
>>> a = [2, 3, 5, 7]
>>> a[2]
5
>>> a[2] = 13 # we change the value
>>> a[2]
13
>>> a # the original list was modified
[2, 3, 13, 7]
So in your loop, when you have a[k] = a[k] + something, you get the value at the kth index, add something to it, and then update the original list at the same index. Since function parameters are passed by references, this updates your original list (and you later return the identical list object from your function).
As for the “something” part, you are doing this: b[len(b)-1-k]. Again, you are using an index to access a single item of the list b. But this time, the index is not a constant or a single variable, but a more complex expression: len(b) - 1 - k. len(b) will return the length of the list b, so ultimaltely, as you iterate through the a list from the beginning, you are iterating b from the end (assuming the same length for both lists). Python will execute the expression first, so in the end it will access b’s item at the index that results from that expression. | unknown | |
d11823 | train | If you are happy to do it with jQuery:
$("#sideBar").css("position", "fixed");
and then to change it back:
$("#sideBar").css("position", ""); | unknown | |
d11824 | train | Find the names of the variables that you want to put in the list:
dataVars <- ls(pattern = "^data[[:digit:]]+$)
Use mget to retrieve them as a list.
dataList <- mget(dataVars, envir = parent.frame()) | unknown | |
d11825 | train | The error message undefined method '<' for nil:NilClass means that you are trying to call < on something that is nil.
In your example that must be the if arr[cntr] < arr[cntr + 1] comparison. In a next step we need to find out why arr[cntr] is nil. One reason could be that there is no element in the arr array at the cntr index, another reason might be that the index cntr is out of bounds of the array. In your example it is the second reason that is causing the problem.
Why is the index out of bounds? Let's have a closer look how the loop is build and use an example array [a, b, c] to do so:
length = arr.length # length = 3 # [a, b, c].length
length.downto(0) do |cntr| # 3.downto(0) do |cntr|
if arr[cntr] < arr[cntr + 1] # if arr[3] < arr[4] # in the first iteration
Ops, there aren't not indexes 3 and 4 in the arr array, because indexes start counting with 0 and there are only 3 elements in my example (that makes the last element's index 2).
The fix:
def bubble_sort(array)
(array.length - 2).downto(0).each do |index|
if array[index] < array[index + 1]
# ...
end
end
end
A:
does anyone know what does that mean?
It means that arr[cntr] is nil in this expression
if arr[cntr] < arr[cntr + 1]
Oh, and if this one is nil, then arr[cntr + 1] is definitely nil.
Hint: you're accessing elements out of bounds of the array.
A: In your code length variable value will be 6(length = arr.length).
When you iterate it down to 0 ... in the first iteration cntr variable value will be 6.
so arr[cntr] is getting nil value because you are accessing elements out of bounds of the array. That's why you are getting undefined method < for nil:NilClass (NoMethodError) error. | unknown | |
d11826 | train | In .NET, the convention is to store connectionstrings in a separate config file.
Thereon, the config file can be encrypted.
If you are using Microsoft SQL Server, this all becomes irrelevant if you use a domain account to run the application, which then uses a trusted connection to the database. The connectionstring will not contain any usernames and passwords in that case.
A: You can store the connection string in Web.config or App.config file and encrypt the section that holds it. Here's a very good article I used in a previous project to encrypt the connection string:
http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html
A: I can recommend these techniques for .NET programmers:
*
*Encrypt password\connection string in config file
*Setup trusted connection between client and server (i.e. use windows auth, etc)
Here is useful articles from CodeProject:
*
*Encrypt and Decrypt of ConnectionString in app.config and/or web.config
A: Unless I am missing the point the connection should be managed by the server via a connection pool, therefore the connection credentials are held by the server and not by the app.
Taking this further I generally build to a convention where the frontend web application (in a DMZ) only talks to the DB via a web service (in domain), therefore providing complete separation and enhanced DB security.
Also, never give priviliges to the db account over or above what is essentially needed.
An alternative approach is to perform all operations via stored procedures, and grant the application user access only to these procs.
A: Assuming that you are using MS SQL, you can take advantage of windows authentication which requires no ussername/pass anywhere in source code. Otherwise I would have to agree with the other posters recommending app.config + encryption.
A: *
*Create an O/S user
*Put the password in an O/S environment variable for that user
*Run the program as that user
Advantages:
*
*Only root or that user can view that user's O/S environment variables
*Survives reboot
*You never accidentally check password in to source control
*You don't need to worry about screwing up file permissions
*You don't need to worry about where you store an encryption key
*Works x-platform | unknown | |
d11827 | train | In python2, your code produces:
In [4]: val = str(''.join(map(chr, list(range(0, 256, 8))))) ; val
Out[4]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
In [5]: x = str(val).encode('hex') ; x
Out[5]: '0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'
In [6]: x.decode('hex')
Out[6]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
To get the similar output in python3:
In [19]: import codecs
In [20]: val = ''.join(map(chr, range(0, 256, 8))) ; val
Out[20]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0¨°¸ÀÈÐØàèðø'
In [21]: x = codecs.encode(val.encode('latin-1'), 'hex_codec') ; x
Out[21]: b'0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'
In [22]: codecs.decode(x, 'hex_codec')
Out[22]: b'\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
Notes:
*
*The python3 version of x above is a byte-string. Since it is entirely ASCII, it can be converted to unicode simply via x.decode().
*The display of val toward the end of the string in the python3 code above does not match the python2 version. For a method of creating val which does match, see the next section.
Alternatives
Use bytes to create the string. Use binascii.hexlify to convert it to hex:
In [15]: val = bytes(range(0, 256, 8))
In [16]: val
Out[16]: b'\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
In [17]: binascii.hexlify(val)
Out[17]: b'0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'
More on unicode and character 0xf8
You wanted ø to be 0xf8. Here is how to make that work:
>>> s = chr( int('f8', 16) )
>>> s
'ø'
And, to convert s back to a hex number:
>>> hex(ord(s))
'0xf8'
Note that 0xf8' is the unicode code point of 'ø' and that that is not the same as the byte string representing the unicode character 'ø' which is:
>>> s.encode('utf8')
b'\xc3\xb8'
So, 'ø' is the 248th (0xf8) character in the unicode set and its byte-string representation is b'\xc3\xb8'.
A: Your Python 2 code:
val = str(''.join(map(chr, list(range(0, 256, 8)))))
x = str(val).encode('hex')
x.decode('hex')
Let's make version that works on both Python 2 and 3:
import binascii
val = bytearray(range(0, 0x100, 8))
x = binascii.hexlify(val)
binascii.unhexlify(x) | unknown | |
d11828 | train | Easy solution: You can implement singleton, manager that will be responsible for this. e.g.
class AnimalManager: NSObject {
static let shared = AnimalManager()
private var animals = [Animal]()
private var currentIndex: Int?
.....
}
Now you can implement such methods like: current animal, next animal, revious, etc. | unknown | |
d11829 | train | Blueprints have register method which called when you register blueprint. So you can override this method or use record decorator to describe logic which depends from app.
A: The current_app approach is fine but you must have some request context. If you don't have one (some pre-work like testing, e.g.) you'd better place
with app.test_request_context('/'):
before this current_app call.
You will have RuntimeError: working outside of application context , instead.
A: Overloading record method seems to be quite easy:
api_blueprint = Blueprint('xxx.api', __name__, None)
api_blueprint.config = {}
@api_blueprint.record
def record_params(setup_state):
app = setup_state.app
api_blueprint.config = dict([(key,value) for (key,value) in app.config.iteritems()])
A: Use flask.current_app in place of app in the blueprint view.
from flask import current_app
@api.route("/info")
def get_account_num():
num = current_app.config["INFO"]
The current_app proxy is only available in the context of a request.
A: You either need to import the main app variable (or whatever you have called it) that is returned by Flask():
from someplace import app
app.config.get('CLIENT_ID')
Or do that from within a request:
@api.route('/authorisation_url')
def authorisation_url():
client_id = current_app.config.get('CLIENT_ID')
url = auth.get_authorisation_url()
return str(url)
A: To build on tbicr's answer, here's an example overriding the register method example:
from flask import Blueprint
auth = None
class RegisteringExampleBlueprint(Blueprint):
def register(self, app, options, first_registration=False):
global auth
config = app.config
client_id = config.get('CLIENT_ID')
client_secret = config.get('CLIENT_SECRET')
scope = config.get('SCOPE')
callback = config.get('CALLBACK')
auth = OauthAdapter(client_id, client_secret, scope, callback)
super(RegisteringExampleBlueprint,
self).register(app, options, first_registration)
the_blueprint = RegisteringExampleBlueprint('example', __name__)
And an example using the record decorator:
from flask import Blueprint
from api import api_blueprint as api
auth = None
# Note there's also a record_once decorator
@api.record
def record_auth(setup_state):
global auth
config = setup_state.app.config
client_id = config.get('CLIENT_ID')
client_secret = config.get('CLIENT_SECRET')
scope = config.get('SCOPE')
callback = config.get('CALLBACK')
auth = OauthAdapter(client_id, client_secret, scope, callback)
A: You could also wrap the blueprint in a function and pass the app as an argument:
Blueprint:
def get_blueprint(app):
bp = Blueprint()
return bp
Main:
from . import my_blueprint
app.register_blueprint(my_blueprint.get_blueprint(app))
A: I know this is an old thread. But while writing a flask service, I used a method like this to do it. It's longer than the solutions above but it gives you the possibility to use customized class yourself. And frankly, I like to write services like this.
Step 1:
I added a struct in a different module file where we can make the class structs singleton. And I got this class structure from this thread already discussed. Creating a singleton in Python
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
else:
cls._instances[cls].__init__(*args, **kwargs)
return cls._instances[cls]
Step 2:
Then I created a Singleton EnvironmentService class from our Singleton class that we defined above, just for our purpose. Instead of recreating such classes, create them once and use them in other modules, routes, etc. import. We can access the class with the same reference.
from flask import Config
from src.core.metaclass.Singleton import Singleton
class EnvironmentService(metaclass=Singleton):
__env: Config = None
def initialize(self, env):
self.__env = env
return EnvironmentService()
def get_all(self):
return self.__env.copy()
def get_one(self, key):
return self.__env.get(key)
Step 3:
Now we include the service in the application in our project root directory. This process should be applied before the routes.
from flask import Flask
from src.services.EnvironmentService import EnvironmentService
app = Flask(__name__)
# Here is our service
env = EnvironmentService().initialize(app.config)
# Your routes...
Usage:
Yes, we can now access our service from other routes.
from src.services.EnvironmentService import EnvironmentService
key = EnvironmentService().get_one("YOUR_KEY") | unknown | |
d11830 | train | You need the Posting class to inherit from ActiveRecord::Base and not just ActiveRecord:: | unknown | |
d11831 | train | A base solution:
lapply(mtcars, unique)
Here, unique() accepts a vector x and returns a (possibly shorter) vector consisting of the unique values. As you noted, the lengths of each unique collection will differ, so we use lapply() to obtain the answer as a list.
Given what I think you're trying to do, this might be a more sensible approach than padding NA entries, because it seems like the only thing you want is the list of unique values.
A: If I understand correct you are looking for this:
To achieve your aim first transform the dataframe columns to list of vectors.
Then replace the duplicates with NA to get the same length and wrap it around map_dfr:
library(tidyverse)
mtcars %>%
dplyr::select(mpg,cyl,disp,hp) %>%
as.list() %>%
map_dfr(~replace(., duplicated(.), NA))
mpg cyl disp hp
<dbl> <dbl> <dbl> <dbl>
1 21 6 160 110
2 NA NA NA NA
3 22.8 4 108 93
4 21.4 NA 258 NA
5 18.7 8 360 175
6 18.1 NA 225 105
7 14.3 NA NA 245
8 24.4 NA 147. 62
9 NA NA 141. 95
10 19.2 NA 168. 123
# ... with 22 more rows | unknown | |
d11832 | train | I can say with certainty that this was never an intended use case for profiles :)
docker-compose has no native way to pass the current profile down to a service. As a workaround you could pass the COMPOSE_PROFILES environment variable to the container. But this does not work when specifying the profiles with the --profiles flag on the command line.
Also you had to manually handle having multiple active profiles corretly.
The best solution for your specific issue would be to have different services for each profile:
services:
webapp-prod:
profiles: ["prod"]
#...
env_file:
- .env
db-service:
image: db-image
profiles: ["test"]
#...
webapp-test:
profiles: ["test"]
#...
environment:
- DATABASE_HOST=db-service:1234
This only has the downside of different service names for "the same" service with different configurations and they both need assigned profile(s) so none of them will start by default, i.e. with every profile.
Also it has some duplicate code for the two service definitions. If you want to share the definition in the file you could use yaml anchors and aliases:
services:
webapp-prod: &webapp
profiles: ["prod"]
#...
env_file:
- .env
webapp-test:
<<: *webapp
profiles: ["test"]
environment:
- DATABASE_HOST=db-service:1234
db-service:
image: db-image
profiles: ["test"]
#...
Another alternative could be using multiple compose files:
# docker-compose.yml
services:
webapp:
#...
env_file:
- .env
# docker-compose.test.yml
services:
db-service:
image: db-image
#...
webapp:
environment:
- DATABASE_HOST=db-service:1234
This way you can start the production service normally and the instances by passing and merging the compose files:
docker-compose up # start the production version
docker-compose -f docker-compose.yml -f docker-compose.test.yml # start the test version
A: Arcan's answers has a lot of good ideas.
I think another solution is to just pass a variable next to your --profile tag on your docker commands. You can then for instance set an -e TESTING=.env.testing in your docker-compose command and use env_file:${TESTING:-.env.default} in your file. This allows you to have a default env file added on any none profile actions and runs the given file when needed.
Since I have a slightly different setup I am adding a single variable to a container in my docker-compose so I did not test if it works on the env-file: attribute but I think it should work. | unknown | |
d11833 | train | CSV files doesn't have any cell length defintion
They are text files, with Comma Seperated Values (CSV ...)
xlsx files however DO hold such a feature
They are basically xml zipped
You can either look for a php excel library with a function ready or parse the XML yourself...
XML sturcture is reffred to here
Looking for a clear description of Excel's .xlsx XML format
A: Worksheets("Sheet1").Columns("A:D").AutoFit | unknown | |
d11834 | train | PackageMaker always was buggy has hell, and got deprecated with Mac OS X 10.6 Snow Leopard.
You should use pkgbuild together with productbuild.
A: This Mac Installers Blog has some useful posts about Packagemaker including details about the usage and solutions to common problems. Hope it will help.
A: Check out the Luggage - it's a Makefile helper file that lets you create OS X packages with sane Makefiles. Disclaimer: I am the original author for it, though there are a lot of other people's contributions in it now. | unknown | |
d11835 | train | You can use
Channel: DAHDI/g0/09*********
MaxRetries: 1
RetryTime: 600
WaitTime: 30
Context: outgoing
Extension: 10
Priority: 1
Callerid: 12345
Note, dahdi g0 have be digital trunk and ALLOW change of callerid.
A: You just add the parameter on your .call file
Callerid: <your_callerid> | unknown | |
d11836 | train | You are totally free to organise your code however you wish. This is unrelated to hexagonal architecture.
With that being said, if you want to use hexagonal architecture efficiently, you should probably follow a domain-driven design, that is to say, you should organise your code based on domain/business logic, and not based on technical similarities.
For example, instead of having the following structure:
controller
product
cart
customer
service
product
cart
customer
repository
product
cart
customer
DDD recommends the following structure:
product
controller
service
repository
cart
controller
service
repository
customer
controller
service
repository
Once you've done this, if it helps, you could wrap these in three packages for the differents parts of the hexagonal architecture: user side, business logic and server side. This is something I've done in the past; it helps me keep the different layers clear.
userside
product
controller
cart
controller
customer
controller
businesslogic
product
service
cart
service
customer
service
serverside
product
service
cart
repository
customer
repository
Again, the structure of your packages is not the most important concept. The hexagonal architecture focuses on three principles:
*
*Explicitly separate user side, business logic, and server side layers. A clear package structure helps, but you can separate these layers in other ways.
*Dependencies go from user side and server side layers to the business logic. This is done by defining interfaces and adapters in the business logic (see below). The goal is that code in the user side and server side may be changed without impacting the business logic layer. For example, if you wish to change your repository from a MySQL implementation to a PostgreSQL implementation (in the server side layer), this change should not impact your business logic: the new implementation need only comply with the interface in the business logic.
*Dependency injection: the business logic defines interfaces (commonly called "ports") and transformers ("adapters") with which the user side and server side layers must comply for communication.
It's a very DDD oriented architecture; the idea is that the business logic remain as close to the domain as possible, and unadulterated by technical requirements.
A: Hexagonal architecture doesn't say snything about how to organize the hexagon code (business logic). You can implement however you want to.
Take a look at these articles:
https://jmgarridopaz.github.io/content/articles.html | unknown | |
d11837 | train | I figured it out. The answer is no. | unknown | |
d11838 | train | use (lldb) and po to print or display anything you want to console.
A: In case anyone runs into this, the problem is that the logging is happening from the main app, one solution is to run the extension, and all the print logs work as expected. Otherwise, you can also change debug settings. | unknown | |
d11839 | train | If you are in a Unix environment, you can use the file /dev/random to pull as many megabytes as you want from it.
A: How about just creating a very long string if you have the memory available anyways?
That should not take all that long :)
$x = str_repeat(
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sollicitudin turpis ut augue lacinia at ullamcorper dolor condimentum. Nunc elementum suscipit laoreet. Phasellus vel sem justo, a vulputate arcu. Sed rutrum elit nec elit lobortis ultrices. Quisque elit nulla, rutrum et varius sit amet, pulvinar eget purus. Aliquam erat volutpat. Fusce turpis lectus, vestibulum sed ornare sed, facilisis sit amet lacus. Nunc lobortis posuere ultricies. Phasellus aliquet cursus gravida. Curabitur eu erat ac augue rutrum mattis. Suspendisse sit amet urna nec velit commodo feugiat. Maecenas vulputate dictum diam, eu tempor erat volutpat in. Donec id nulla tortor, nec iaculis nibh. Pellentesque scelerisque nisl sit amet ligula dictum commodo. Donec porta mi in lorem porttitor id suscipit lacus auctor.',
125000
);
You could of course just write that to a file one but creating it in memory doesn't really take all that long.
The code above produces an 98MB string in about 100ms and creating a 200MB string takes about 170ms on my box. That should be good enough for most cases.
As noted in the comment below: You might have to change your php.ini setting if you limit the amount of memory your script is allowed to consume (or change it via memory_limit('...');). Also strings > 1.5gb might cause issues but thats not a concern here I'd say.
A: Well, if you want random text, then you can use a dictionary with the words and another dictionary with the punctuation, and then generate the return string with random elements from the word dictionary, with a certain probability of random elements from the punctuation dictionary.
Like this you only need the dictionary's in memory, but it will be heavier on the server's CPU.
You can also use this method in conjunction with what you purposed, having a small dictionary with sentences, and randomly selecting sentences or even paragraphs.
A: Why not use an actual lipsum generator script, such as this one?
A: On linux you could read from /dev/random and I'm not fully sure but you could use http://php.net/manual/en/function.fseek.php to read a certain amount or use http://php.net/manual/en/function.exec.php to create the file and then read it. | unknown | |
d11840 | train | To answer my own question - in the hope that it assists someone else.
The file VS reports as "output file ''", appears to relate to the output dll/pdb files in the bin folder, but also to the obj/$(Configuration) files that get built during the compilation process.
So, if I perform:
touch obj\Debug\myProj.dll obj\Debug\myProj.pdb
touch bin\myProj.dll bin\myProj.pdb
within my post-build task, then this seems to solve the problem and gets the compiler back to what I'd expect:
========== Build: 0 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========
A: I just deleted .vs folder & cleaned solution then worked fine. | unknown | |
d11841 | train | I'm not 100% sure, since I haven't used LG Polls before, but try adding in dynamic="off" to your exp:weblog:entries opening tag. That will prevent EE from trying to find entries within the weblog you're calling based on the URL. See the link below:
http://expressionengine.com/legacy_docs/modules/weblog/parameters.html#par_dynamic | unknown | |
d11842 | train | By just adding position:absolute and width:100% to your introtextcontainer container it seems to work:
#introtextcontainer {
margin: 0px auto 0px auto;
height: 100px;
text-align:center;
font-color: black;
position:absolute;
width:100%;
}
jsFiddle example
Note that there is no such float:middle; property (left or right only).
A: You could also position:absolute the #linecontainer to slide up behind the text (I also centered it with left:50%; margin-left:- 0.5 * width ). You might have to give the text a position:relative; z-index:1; to force it on top.
#introtextcontainer {
margin: 0px auto 0px auto;
height: 100px;
text-align:center;
font-color: black;
position:relative;
width:100%;
z-index:1;
}
#linecontainer {
margin: 0 0 0 -250px;
width: 500px;
height: 3000px;
position:absolute;
top:0;
left:50%;
}
Or even better, use a gradient generator, remove the 3 divs and make the bars a background: http://www.colorzilla.com/gradient-editor/
#introtextcontainer {
margin: 0px auto 0px auto;
height: 100px;
text-align:center;
font-color: black;
position:absolute;
width:100%;
background: rgb(0,167,176); /* Old browsers */
/* IE9 SVG, needs conditional override of 'filter' to 'none' */
background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIzMyUiIHN0b3AtY29sb3I9IiMwMGE3YjAiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSIzMyUiIHN0b3AtY29sb3I9IiNkMWRlM2UiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSIzNCUiIHN0b3AtY29sb3I9IiNkMWRlM2UiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSI2NiUiIHN0b3AtY29sb3I9IiNkMWRlM2UiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSI2NiUiIHN0b3AtY29sb3I9IiNkZTAwNmIiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
background: -moz-linear-gradient(left, rgba(0,167,176,1) 33%, rgba(209,222,62,1) 33%, rgba(209,222,62,1) 34%, rgba(209,222,62,1) 66%, rgba(222,0,107,1) 66%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, right top, color-stop(33%,rgba(0,167,176,1)), color-stop(33%,rgba(209,222,62,1)), color-stop(34%,rgba(209,222,62,1)), color-stop(66%,rgba(209,222,62,1)), color-stop(66%,rgba(222,0,107,1))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(left, rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(left, rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* Opera 11.10+ */
background: -ms-linear-gradient(left, rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* IE10+ */
background: linear-gradient(to right, rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00a7b0', endColorstr='#de006b',GradientType=1 ); /* IE6-8 */
} | unknown | |
d11843 | train | I'd like in case of a error to catch it but allow the for loop to
continue
Promise constructor should treat errors thrown inside executor as promise rejection.
MDN If an error is thrown in the executor function, the promise is
rejected.
So moving try-catch inside for loop should work.
.
'use strict'
co(function*() {
for (let item of [1, 2, 3, 4]) {
try {
const newValue = yield myFunction(item)
console.log(newValue)
} catch (e) {
console.error(e.message)
}
}
})
function callMethod(param, cb) {
if (param % 2) cb('Success')
throw new Error(`Invalid param ${param}`)
}
function myFunction(param) {
return new Promise(function(resolve, reject) {
callMethod(param, function(result) {
if (result) {
resolve(result)
} else {
reject('err')
}
})
})
}
<script>
const module = {}
</script>
<script src="https://unpkg.com/[email protected]/index.js"></script> | unknown | |
d11844 | train | If your fonts don't need to be shared across multiple applications, you may try private font deployment instead of installing them in OS. In that case your app don't need to use administrator account.
There is the good solution for private deploment: Embedding/deploying custom font in .NET app | unknown | |
d11845 | train | As per my knowledge you should do it from admin panel. Joomla provide custom settings of fields for virtuemart user registration.
You also can refer below link for that.
http://virtuemart.net/documentation/User_Manual/User_Registration_Fields.html
I think this would be helpful to you.
Let me know if anything new you get.
Thanks. | unknown | |
d11846 | train | I like to think that you're not writing unit tests because of the slow turnaround cycle but for other reasons. The moment the turnaround cycle goes to zero there is still benefits of unit tests.
A: I think that would be a big mistake. Sure it is faster, but you have no assurance that you aren't breaking things.
So it is faster to do manual unit testing, but the disadvantages aren't just about speed. You can't retest everything on every change without automated tests.
JRebel does make in-container unit tests more viable, though.
A: I tend to think that writing and running unit tests is a good way to compile the appropriate classes so that JRebel can reload them. | unknown | |
d11847 | train | I would suggest you just use a separate NSDictionary instance keyed off the same identifier you use when constructing your CLBeaconRegion.
Like this:
// Make this a class variable, or make it part of a singleton object
NSDictionary *beaconRegionData = [[NSDictionary alloc] init];
// Here is the data you want to attach to the region
NSMutableArray *myArray = [[[NSMutableArray] alloc] init];
// and here is your region
_advertRegion = [[CLBeaconRegion alloc] initWithProximityUUID:_uuid identifier:@"003-002-001"];
// attach your data to the NSDictionary instead
[beaconRegionData setValue:myArray forKey:_advertRegion.identifier];
// and you can get it like this
NSLog(@"Here is my array: %@", [beaconRegionData valueForKey:_advertRegion.identifier]); | unknown | |
d11848 | train | Once you have loaded your entity, you simply need to update its properties and call SaveChanges on your DbContext.
if (accounnt == null)
{
}
else
{
account.balance = 1000;
}
db.SaveChanges(); | unknown | |
d11849 | train | This would work, for start:
foreach (string key in rowsDictionary.Keys)
{
List<EmployeeSummary> empList = rowsDictionary[key];
foreach (EmployeeSummary emp in empList)
{
string combinedKey = emp.LastName.Trim().ToUpper() +
emp.FirstName.Trim().ToUpper();
string delivery_system = emp.Delivery_System;
List<string> systems = null;
// check if the dictionary contains the list
if (!deliverySystemFinder.TryGetValue(combinedKey, out systems))
{
// if not, create it and add it
systems = new List<string>();
deliverySystemFinder[combinedKey] = systems;
}
// check if the list contains the value and add it
if (!systems.Contains(delivery_system))
systems.Add(delivery_system);
}
}
Now, a couple of remarks:
*
*It doesn't make sense to iterate through Keys, and then do a lookup in each iteration. You can directly iterate KeyValuePairs using a foreach loop.
*Using concatenated strings as unique keys often fails. In this case, what happens if you have users { LastName="Some", FirstName="Body" } and { LastName="So", FirstName="Mebody" } in your list?
*Checking if a List contains a value is a O(n) operation. You would greatly improve performance if you used a HashSet<string> instead.
Finally, the simplest way to achieve what you're trying to do is to ditch those loops and simply use:
// returns a Dictionary<EmployeeSummary, List<string>>
// which maps each distinct EmployeeSummary into a list of
// distinct delivery systems
var groupByEmployee = rowsDictionary
.SelectMany(kvp => kvp.Value)
.GroupBy(s => s, new EmployeeSummaryEqualityComparer())
.ToDictionary(
s => s.Key,
s => s.Select(x => x.Delivery_System).Distinct().ToList());
With EmployeeSummaryEqualityComparer defined something like:
class EmployeeSummaryEqualityComparer : IEqualityComparer<EmployeeSummary>
{
public bool Equals(EmployeeSummary x, EmployeeSummary y)
{
if (object.ReferenceEquals(x, null))
return object.ReferenceEquals(y, null);
return
x.FirstName == y.FirstName &&
x.LastName == y.LastName &&
... (depending on what constitutes 'equal' for you)
}
public int GetHashCode(EmployeeSummary x)
{
unchecked
{
var h = 31; // null checks might not be necessary?
h = h * 7 + (x.FirstName != null ? x.FirstName.GetHashCode() : 0);
h = h * 7 + (x.LastName != null ? x.LastName.GetHashCode() : 0);
... other properties similarly ...
return h;
}
}
}
If you really think that using the string key will work in all your cases, you can do it without the custom equality comparer:
// returns a Dictionary<string, List<string>>
var groupByEmployee = rowsDictionary
.SelectMany(kvp => kvp.Value)
.GroupBy(s => s.LastName.ToUpper() + s.FirstName.ToUpper())
.ToDictionary(
s => s.Key,
s => s.Select(x => x.Delivery_System).Distinct().ToList()); | unknown | |
d11850 | train | Are you doing render transform, or layout transform? You should be doing the latter. | unknown | |
d11851 | train | searchEditText.setGravity(Gravity.CENTER | Gravity.LEFT);
This might help
A: Try reducing your font size. For whatever reasons, I have found if your font size is too large, even if it appears to you the EditText should be tall enough to hold the text, the text will appear to be higher than properly centered vertically.
Adjust your font size down, or specify a font size if you are using default value, until you find a font size value small enough for it to appear properly centered.
A: I'm seeing the same issue. Programmatically creating an EditText resulted in the gravity being vertically forced to TOP (while horizontal centering still works) ... until I commented out the calls that set the background! In this case, vertical and horizontal gravity are both honored.
Here is my code:
inputField.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
inputField.setLinksClickable(false);
inputField.setInputType(ie.getInputType());
inputField.setFadingEdgeLength(0);
inputField.setHorizontalFadingEdgeEnabled(false);
inputField.setPadding(borderWidth.left,borderWidth.top,borderWidth.right,borderWidth.bottom);
inputField.setOnEditorActionListener(this);
inputField.setHint(hint);
inputField.setCompoundDrawables(null, null, null, null);
// comment out the next two lines to see gravity working fine
inputField.setBackgroundDrawable(null);
inputField.setBackgroundColor(Color.WHITE);
inputField.setTextColor(Color.BLACK);
inputField.setTextSize(TypedValue.COMPLEX_UNIT_PX, 20);
inputField.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
Now, step tracing in the OS source code reveals that the computation for vertical centering strangely relies on the height reported by the background. Defaut in EditText is a NinePatchDrawable with a 64 pixels high default bitmap. If your EditText is this height, your text will be centered. Otherwise, it will be closer to top than it should. Setting a background color will internally use a ColorDrawable which reports an intrinsic height of zero, therefore only using the text height and vertically aligning it to TOP.
The way to fix this issue is to create your own Drawable subclass, set it as the background of the EditText instance, make sure you call setBounds() on the drawable so it has a height to report, and override the getIntrinsicHeight() method of the drawable to report the height that was set using setBounds(). | unknown | |
d11852 | train | list.subList(2, 6).clear()
does the job in one step.
A: Create a loop counting backward from 5 to 2 and remove the elements.
for(int i = 5; i >= 2; i--) ...
A: void method(int startindex , int endindex)
{
for(int i = 0 ; i < endindex - startindex ; i++)//in your example startindex = 2 end.. = 6
{
list.remove(startindex);
}
}
modify your code accordingly.Hope this may solve your problem.
A: Create a loop at same position, removing elements a certain number of times.
For example, if you wanted to call
list.remove(a,b)
Your code would be:
for (int i = 0; i <= b - a; i++) {
list.remove(a);
} | unknown | |
d11853 | train | for i in range(len(text)):
print(alphabet.index(text.lower()[i]))
just add lower() and it will work
A: As stated by Kevin in comments, you are probably missing uppercase.
You can use alphabet[ord(text[i].lower()) - ord('a')] instead of index. | unknown | |
d11854 | train | If you are willing to pay, this SaaS site called bouncely seems to provide an interface and an api wrapper around SES bounces.
A: send_email() returns a response object which can be interrogated for the response metadata.
Compare the status of this with the code you are interested in, perhaps a 550.
A: I couldn't find any clean existing solution for this, so I wrote a gem (email_events) that allows you to put a email event handler method (including for bounce events) right in your mailer class: https://github.com/85x14/email_events. It supports SES and Sendgrid, so should work for you if you still need it. | unknown | |
d11855 | train | because it is asynchroniuos code. it is expected that sync code will be executed earlier than async.
correct code would be like this
downloadFilesAndConcatenate(): Observable<string> {
return forkJoin(this.fileIDs.map(id => this.restService.getFile(id))).pipe(
map(responses => '\r\n'+responses.map(r => atob(r.result.fileBytes)).join(''))
catchError(e => this.message = e.error.message)
);
} | unknown | |
d11856 | train | There's a misconception here between your two examples. In the 2nd example with f, you are deducing reference arguments to a function. In the 1st example with g, you are deducing reference template parameters to an argument to a function. The latter must match exactly, but the former is deduced against the referred types. They are not the same.
In your fist example,
g(Tuple<int, float>());
cannot call g(Tuple<T1, Types&...>). The template deduction process is about picking a deduced argument type that is identical to the called argument type. There are some exceptions (for referenced cv-qualifications, pointers, derived classes, arrays, functions), but none of those apply here. We simply need to pick T1 and Types... such that Tuple<T1, Types&...> is the same type as Tuple<int, float>. This is impossible as there is no such pack Types... for which Types&... is {float}, since float is not a reference!
So once you comment out (2), there's only one viable candidate: (1).
On the other hand,
template<class ... Types> void f(Types& ...);
void h(int x, float& y) {
const int z = x;
f(x, y, z);
}
Here, Types&... is actually the type of the parameter itself (rather than a template argument of it), so (temp.deduct.call):
If P is a reference type, the type referred to by P is used for type deduction.
We deduce Types... to match the arguments. This succeeds because all the arguments are lvalues, and we simply pick {int, float, const int}. | unknown | |
d11857 | train | This error's cause is due to script running more than 6 minutes.
A possible solution is to limit the time-consuming part of your script (which is the for loop) to only 5 minutes. Then create a trigger and continue the loop into another instance if it still isn't done.
Script:
function addressToPosition() {
// Select a cell with an address and two blank spaces after it
var sheet = SpreadsheetApp.getActiveSheet();
...
var options = {
muteHttpExceptions: true,
contentType: "application/json",
};
// if lastRow is set, get value, else 0
var continueRow = ScriptProperties.getProperty("lastRow") || 0;
var startTime = Date.now();
var resume = true;
for (addressRow = ++continueRow; addressRow <= cells.getNumRows(); ++addressRow) {
var address = cells.getCell(addressRow, addressColumn).getValue();
...
// if 5 minutes is done
if ((Date.now() - startTime) >= 300000) {
// save what's the last row you processed then exit loop
ScriptProperties.setProperty("lastRow", addressRow)
break;
}
// if you reached last row, assign flag as false to prevent triggering the next run
else if (addressRow == cells.getNumRows())
resume = false;
}
// if addressRow is less than getNumRows()
if (resume) {
// after execution of loop, prepare the trigger for the same function
var next = ScriptApp.newTrigger("addressToPosition").timeBased();
// run script after 1 second to continue where you left off (on another instance)
next.after(1000).create();
}
}
Do the same thing with your other functions. | unknown | |
d11858 | train | You need to Rebind the grid with disabled control, but also you need to check the status in itembound event and disable. For that you can use session or hidden field.
protected void rg_OnItemCommand(object source, GridCommandEventArgs e)
{
// your logic
hdFlag.value = "val" // id of the data item to hide if more than one use array
// rebind logic for gird
}
protected void rg_ItemDataBound(object sender, GridItemEventArgs e)
{
if(hdFlag.value == "id")
{
// Find the control and hide
}
}
A: Well you haven't shown your aspx link button so i assuming that your link button is this
<asp:LinkButton id="linkBtn" runat="server" text="Approve" OnClientClick="Disable(this);"/>
Now you should add a javascript function like this on the page::
<script>
function Disable(link)
{
link.disabled = result;
}
</script>
Now when you click on the page your button will get disabled.
A: try this
LinkButton lbApprove = (LinkButton)e.Row.Cells[0].Controls[0]; | unknown | |
d11859 | train | As hinted to by @Vlad Feinstein's comment, CMenu MyMainMenu; should not have been declared inside the function... That fix allowed me to get past the assertion, but the new menu items were still not appearing. I began catching and logging the return values from the creation and deletion functions which lead me to realize that because I already had an existing menu, I needed to use a pointer to that menu(as opposed to creating my own that I then left un-used).
My final function ended up looking like this:
void SoftwareDlg::DynamicAppMenu(){
CMenu* MainMenu = GetMenu();
CMenu* SettingsMenu = MainMenu->GetSubMenu(1);
CMenu* TargetAppMenu = SettingsMenu->GetSubMenu(5);
if (TargetAppMenu)
{
BOOL appended = false;
BOOL deleted = false;
for (auto i = 0; i < Client::m_vszAppArr.size(); i++)
{
appended = TargetAppMenu->AppendMenu(MF_STRING, 14000+i, Client::m_vszAppArr[i].c_str());
}
deleted = TargetAppMenu->DeleteMenu(ID_TARGETWINDOW_PLACEHOLDER, MF_BYCOMMAND);
OutputDebugString(("String appended: " + std::to_string(appended)).c_str());
OutputDebugString(("Placeholder deleted: " + std::to_string(deleted)).c_str());
}
} | unknown | |
d11860 | train | The issue is simpler than you're making it. The Visual Studio compiler's error message is actually quite clear. arr is not a valid template argument because it is not a compile-time constant.
In order to use a string as a template non-type parameter, it must be a variable with external linkage (although C++11 does, I believe, remove this requirement—see Columbo's answer). So you could change your code to the following, and it would work:
template <const char* T>
class A
{
// ...
};
extern const char arr[] = "hello world";
int main()
{
A<arr> obj;
}
Note how the declaration of arr has changed. The variable is now a named object with external linkage, and so it can be used as a template non-type parameter.
Basically, what happens is its address is passed to the template. This means that it is not the content of the string that determines its uniqueness, but the object itself. In other words, if you had two different variables that held exactly the same string, they would nevertheless have different types and create two different instantiations of the template class.
A: Template parameters of pointer type are not allowed to refer to string literals ([temp.arg.nontype]/(1.3)). Instead, declare a global array:
constexpr char arr[] = "hello world"; // Or use const only, but won't be able to
// use it inside the template
This can be used as a template argument, since it can appear in constant expressions and has static storage duration, making it a permitted result of a constant expression ([expr.const]/5). | unknown | |
d11861 | train | You have Bundler 2.1.4, and Rails 4.2 does not work with Bundler 2 and above.
You need to install a supported bundler version like this:
gem install bundler:1.17.3
To use the newly installed version run:
bundle _1.17.3_ install | unknown | |
d11862 | train | There are many ways like ssis transfer,select * into ,but i prefer below way if you are just transferring data
create a linked server on source server for destination server,then you could refer destination server with four part name
Assuming linked server of source is A and destination server is B,data moving is as simple as
insert into B.databasename.Schema.Table
select * from table---this is in source server and db
if data is huge and you may worry about time outs,you can write a simple script which can do in batches like
While (1=1)
begin
insert into B.databasename.Schema.Table
select top 10000* from table---this is in source server and db
if (@@rowcount=0)
break
end
Creating linked server ,you can follow this
A: You have the following options available to you. Not all of these will work, depending on your exact requirements and the networking arrangements between the servers.
*
*SQL Server Management Studio - Import & Export Wizard: this is accessed from the right-click menu for a database > Tasks > Import Data (or Export Data).
*SQL query using a Linked Server: a Linked Server configured between the two servers allows you to reference databases on one from the other, in much the same way as if they were on the same server. Any valid SQL query approach for transferring data between two tables within one database will then work, provided you fully-qualify the table names as Server.Database.Schema.Table.
*SSIS: create an SSIS package with both servers as connections, and a simple workflow to move the data from one to the other. There is plenty of information available online on how to use SSIS.
*Export to flat-file format then import: this could be done using the Import/Export Wizard above or SSIS, but instead of piping the data directly between the two servers, you would output the data from the source table into a suitable flat-file format on the filesystem. CSV is the most commonly used format for this. This file can then be moved to the destination server using any file transfer approach (compressed e.g. to a Zip file if desired), and imported into the destination table.
*Database backup and restore: Similar to (4), but instead of using a flat file, you could create a backup of the source database via Tasks > Back Up... You then move that backup as a file (just like the CSV approach), and restore it onto the destination server. Now you have two databases on the destination server, and can move data from one to the other locally.
A: I hope, this query helps you!!!
INSERT INTO [dbo].[tablename] (Column1, Column2,Column3)
(select Column1, Column2,Column3, from [Database1].[dbo].[tablename]
Thanks!!! | unknown | |
d11863 | train | It looks like you're using XPath 1.0: in 1.0, if you supply a node-set as the first argument to contains(), it takes the first node in the node-set. The order of attributes is completely unpredictable, so there's no way of knowing whether contains(@*, 'close') will succeed or not. In 2.0+, this gives you an error.
In both 1.0 and 2.0, @*[contains(., 'close')] returns true if any attribute contains "close" as a substring.
A: This expression works:
//button[attribute::*[contains(.,"close")] and attribute::*[contains(.,"modal")]]
Given this html
<button data-button-id="close" class="modal__cross modal__cross-web"></button>
<button key="close" last="xyz_modal"></button>
Testing with xmllint
echo -e 'cat //button[attribute::*[contains(.,"close")] and attribute::*[contains(.,"modal")]]\nbye' | xmllint --html --shell test.html
/ > cat //button[attribute::*[contains(.,"close")] and attribute::*[contains(.,"modal")]]
-------
<button data-button-id="close" class="modal__cross modal__cross-web"></button>
-------
<button key="close" last="xyz_modal"></button>
/ > bye
A: Try this one to select required element:
//button[@*[contains(., 'close')] and @*[contains(., 'modal')]] | unknown | |
d11864 | train | The problem is likely with your server configuration. You have to configure your server to rewrite unknown paths to your index.php script.
For example, when I've used yii2 with apache, I have the following web/.htaccess file:
# use mod_rewrite for pretty URL support
RewriteEngine on
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php
# ...other settings...
Options +FollowSymLinks
Of course, a lot of the details are dependent on your hosting and server configuration (e.g. are .htaccess files allowed). Yii's docs have more information on configuring different web servers here.
A: Okay turned out there was an extra space in the request. The code is fine. | unknown | |
d11865 | train | Here is a little example:
DECLARE @DIM_AM TABLE([AM_ID] INT, [AMI_ID] int, [Parent_AMI_ID] INT, [AMI_Code] VARCHAR(20))
DECLARE @DIM_AMI TABLE([AMI_ID] INT, [AMI_Name] VARCHAR(20))
INSERT INTO @DIM_AMI VALUES
(1, 'AMI1'),
(2, 'AMI2'),
(3, 'AMI3'),
(4, 'AMI4')
INSERT INTO @DIM_AM VALUES
(1, 1, NULL, 'CODE_AMI1'),
(2, 2, 1, 'CODE_AMI2'),
(3, 3, 1, 'CODE_AMI3'),
(4, 4, 3, 'CODE_AMI4')
;WITH cte AS(SELECT *, 0 AS Level FROM @DIM_AM WHERE Parent_AMI_ID IS NULL
UNION ALL
SELECT d.*, c.Level + 1 FROM cte c
JOIN @DIM_AM d ON c.AMI_ID = d.Parent_AMI_ID)
SELECT c.Level, c.AMI_Code, d.AMI_Name FROM cte c
JOIN @DIM_AMI d ON d.AMI_ID = c.AMI_ID
Output:
Level AMI_Code AMI_Name
0 CODE_AMI1 AMI1
1 CODE_AMI2 AMI2
1 CODE_AMI3 AMI3
2 CODE_AMI4 AMI4
This is recursive common table expression(cte):
;WITH cte AS(SELECT *, 0 AS Level FROM @DIM_AM WHERE Parent_AMI_ID IS NULL
UNION ALL
SELECT d.*, c.Level + 1 FROM cte c
JOIN @DIM_AM d ON c.AMI_ID = d.Parent_AMI_ID)
First part is starting point where you select top level elements(WHERE Parent_AMI_ID IS NULL):
SELECT *, 0 AS Level FROM @DIM_AM WHERE Parent_AMI_ID IS NULL
Then by syntax you need union all.
Then comes recursive part that selects children of previous select:
SELECT d.*, c.Level + 1 FROM cte c
JOIN @DIM_AM d ON c.AMI_ID = d.Parent_AMI_ID | unknown | |
d11866 | train | Because there is no good reason to do so.
The c++ standard generally only defines what is necessary and leaves the rest up to implementers.
This is why it produces fast code and can be compiled for many platforms. | unknown | |
d11867 | train | 1 in range(2) == True is an operator chain, just like when you do 0 < 10 < 20
For it to be true you would need
1 in range(2)
and
range(2) == True
to be both true. The latter is false, hence the result. Adding parenthesis doesn't make an operator chaining anymore (some operators are in the parentheses), which explains (1 in range(2)) == True works.
Try:
>>> 1 in range(2) == range(2)
True
Once again, a good lesson learned about not equalling things with == True or != False which are redundant at best, and toxic at worst.
A: Try to write
(1 in range(2)) == True
It has to do with parsing and how the expression is evaluated. | unknown | |
d11868 | train | Your event is binded to your submit event, not to an ajax call at this point.
However, if you wanted to implement a check to see what this submit is supposed to do, you could:
Have this in your markup:
<form id="my-id" class="my-forms" method="GET">
<button type="submit"></button>
</form>
And this in your js:
$('#my-id').on('submit', function(e) {
e.preventDefault();
var method = this.method;
if (method === 'GET') {
console.log(method);
// do your ajax.get
}
if (method === 'POST') {
console.log(method);
// do your ajax.post
}
});
Of course, this example is contrived as this.method on $('#my-id') would always be 'GET'. However, you could instead change your selector to $('.my-forms') to intercept this event among all elements with the .my-forms class.
A: According to your description it is not going to be an ajax request because you are using on('submit', function(){}); which is invoked when you submit html form and it would be an html request to server.
If you still want to check type of if the request is GET or POST, you can check form's method attribute.
$(document).on('submit', 'form', function(e) {
e.preventDefault();
var method = this.method;
if(method=='GET')
//do something
if(method=='POST')
//do something
}); | unknown | |
d11869 | train | It should be:
apply plugin: 'com.android.application'
with a colon. | unknown | |
d11870 | train | If getting the values of the fields is your issue, this code snippet should help:
s := reflect.ValueOf(a)
ret := make([]interface{}, s.NumField())
for i := 0; i < s.NumField(); i++ {
ret[i] = s.Field(i).Interface()
}
A: If creating the []interface{} value is your problem, using reflect's slice creation mechanisms should work nicely:
slc := reflect.MakeSlice(InterfaceType, len, cap) // See the link below for creating InterfaceType
slc.Index(0).Set(TargetValue)
return slc.Interface()
(Here's the above-mentioned link).
Modifying the above code to loop over the values in the struct instead of just the 0th index shouldn't be too bad. | unknown | |
d11871 | train | You look to be generating the key and IV for the Rijndael decryption by signing your signBytes array using SHA1/RSA, however from the code you've given, you don't initialize the RSACryptoServiceProvider used in the signing process with a key pair, as such it will have a randomly generated key, and so the result of the signing process will be different every time. Consequently the key/IV being used in the Rijndael decryption are not going to be the same as that used to encrypt the hiddenData when you created the license key.
There are a number of other issues with the method you're using in itself, but that falls outside the scope of your question. | unknown | |
d11872 | train | karma-webpack has a peer dependency of webpack. I don't see webpack in your package.json that you listed (unless that's not the full list). You need to also install webpack:
npm install --save-dev webpack
A: You need to upgrade to the newer version of angular CLI. You can delete the project folder which you already created using ng new my-app
Uninstall the older angular-cli
npm uninstall angular-cli -g
Install the new @angular-cli
npm install @angular/cli -g
Start a new project again
ng new my-app
Then, run the test
ng test
A: I found this solution
add these in your package.json in dependencies
{
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^2.0.3",
}
and then npm i
and then-: npm run test | unknown | |
d11873 | train | I found how to solve it, by adding Transformer in step definition that should be as follows:
@DataTableType
public Config entryTransformer(Map<String, String> row) {
return Config.builder()
.id(Integer.parseInt(row.get("id")))
.active(row.get("active"))
.build();
} | unknown | |
d11874 | train | You need to recalculate just width of a magicline, not its left position - it's always = 0;
$magicLine.stop().animate({
left: 0,
width: leftPos+newWidth
});
demo
A: You can do this by CSS and some JavaScript :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
</head>
<body>
<div class="carousel">
<div class="carousel-info">
<div class="container">
<div style="display:inline-block; position:relative;">
<ul>
<li class="slick-current" onmouseover="$('#line').css('width','34%');">
<div class="c-header">About Us</div>
<div class="c-container">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut tristique lorem, et volutpat elit. Morbi leo ipsum, fermentum ut volutpat ac, pharetra eget mauris.</div>
</li>
<li onmouseover="$('#line').css('width','68%');">
<div class="c-header">Others</div>
<div class="c-container">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut tristique lorem, et volutpat elit. Morbi leo ipsum, fermentum ut volutpat ac, pharetra eget mauris.</div>
</li>
<li onmouseover="$('#line').css('width','100%');">
<div class="c-header">Main</div>
<div class="c-container">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut tristique lorem, et volutpat elit. Morbi leo ipsum, fermentum ut volutpat ac, pharetra eget mauris.</div>
</li>
</ul>
<div id="line" style="position:absolute; bottom:0; left:0; width:34%; height:2px; background:red; transition:all 0.2s;"></div>
</div>
</div>
</div>
</div>
</body>
</html>
I've created an absolute div with transition, when mouse over on one of your elements the width will increase, that's it! | unknown | |
d11875 | train | I think maybe port 9000 is already being used, so php5-fpm can't bind with that port and fails to start.
in the fpm pool settings swap the line of port 9000 with the line with the sock file, then try to start php5-fpm like you were doing, if it works then all you need is to update the nginx configuratuin to proxy pass to the sock file instead of the port. | unknown | |
d11876 | train | You need to set the android:scaleType and optionally android:adjustViewBounds. Play around with these two attributes to get the desired effect.
http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType
A: Use this code to add your ImageView to the xml file
<shush.android.util.AspectImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/header" />
Add this class:
package shush.android.util;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
/**
* @author Sherif elKhatib
*
*/
public class AspectImageView extends View {
public AspectImageView(Context context) {
super(context);
}
public AspectImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AspectImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * getBackground().getIntrinsicHeight()
/ getBackground().getIntrinsicWidth();
setMeasuredDimension(width, height);
}
}
A: try this
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res/aaa.bbb"
android:id="@+id/db1_root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background">
<ImageView
android:src="@drawable/header"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="top"
>
</ImageView> | unknown | |
d11877 | train | This should do it.
try
{
int a = Integer.parseInt(gotBasket.getString("lol"));
textView.setText("" + a);
}
catch (NumberFormatException e)
{
// handle the exception
}
A: You're doing the conversion right, but you're not saving the value anywhere.
int lulz = Integer.parseInt(gotBasket.getString("lol"));
Also, why do you want to convert it to an int to display it in a TextView? | unknown | |
d11878 | train | If you're trying to run from a .jar file and it's giving you this issue but not from the IDE, you should just be able to open the jar file with winrar or another similar program and just copy/paste the whole res directory into the jar file.
You then use the following code to retrieve your file in the program (instead of where you're retrieving from "C:\lwjgl\lwjgl-2.8.5\res":
ResourceLoader.getResource(stringLocationToResource);
This will return the resource that you were trying to get.
The file has to be next to your src file, and not in it. | unknown | |
d11879 | train | For these (Boolean, Integer) and other simple types, you could initialize with TVarData and typecast back to Variant:
type
TValues = record
Name: WideString;
Value: TVarData;
end;
const
coarrType1Properties : array[0..5] of TValues = (
(Name: 'HARDWARE'; Value: (VType: varBoolean; VBoolean: True)),
(Name: 'SOFTWARE'; Value: (VType: varBoolean; VBoolean: True)),
(Name: 'TAG'; Value: (VType: varBoolean; VBoolean: True)),
(Name: 'AUTHORIZED'; Value: (VType: varBoolean; VBoolean: True)),
(Name: 'ID'; Value: (VType: varInteger; VInteger: 700)),
(Name: 'CODE'; Value: (VType: varInteger; VInteger: 0))
);
procedure Test;
var
I: Integer;
begin
for I := Low(coarrType1Properties) to High(coarrType1Properties) do
Writeln(Format('coarrType1Properties[%d]: ''%s'', %s', [I, coarrType1Properties[I].Name, VarToStr(Variant(coarrType1Properties[I].Value))]));
end;
A: The documentation states:
File types (including type Text), and the type Variant cannot be initialized, that is, you cannot declare typed constants or initialized variables of these types.
So your problem is with your variant record member. This means that you need a different approach and you will have to abandon the use of a constant array.
function Values(const Name: WideString; const Value: Variant): TValues;
begin
Result.Name := Name;
Result.Value := Value;
end;
type
TValuesArray = array of TValues;
function ValuesArray(const Values: array of TValues): TValuesArray;
var
i: Integer;
begin
SetLength(Result, Length(Values));
for i := 0 to high(Result) do
Result[i] := Values[i];
end;
var
coarrType1Properties: TValuesArray;
initialization
coarrType1Properties := ValuesArray([
Values('HARDWARE', TRUE),
Values('SOFTWARE', TRUE),
Values('TAG', TRUE),
Values('AUTHORIZED', TRUE),
Values('ID', 700),
Values('CODE', 0)
]);
A: E2071: Variants can not be initialized with a constant expression.
A: Form D2007 help:
E2071: This type cannot be initialized
File types (including type Text), and the type Variant cannot be initialized, that is, you cannot declare typed constants or initialized variables of these types.
program Produce;
var
V: Variant = 0;
begin
end.
// The example tries to declare an initialized variable of type Variant, which illegal.
program Solve;
var
V: Variant;
begin
V := 0;
end.
The solution is to initialize a normal variable with an assignment statement. | unknown | |
d11880 | train | similiar problem here. I load the list of all apps and add them to a recyclerview, i had to wait some seconds before it was loaded so i timed the loading time. What i noticed is that loading icons and labels with 70 apps i needed around 2.6 seconds to load the apps, without loading icons and label ... an astonishing 61ms! YEAH milliseconds!
For now i am using a temporary solution, i will probably improve it in the future. What i did is create a model object that loads labels and icons in a background thread.
public class AppModel {
ComponentName componentName;
Drawable icon = null;
String appName = "";
public AppModel(ComponentName componentName) {
this.componentName = componentName;
}
public void init(ActivityInfo ai, PackageManager pm) {
new Thread(new Runnable() {
@Override
public void run() {
appName = (String) ai.loadLabel(pm);
icon = ai.loadIcon(pm);
}
}).start();
}
...
...
}
when i load the apps i do the following:
AppModel appModel = new AppModel(componentName);
appModel.init(ai, pm);
// other stuff
I needed a fast and working hotfix, in this way while the app is added to the recyclerview the labels and icons get loaded in background, cutting down the loading time by a lot!
A future solution i am considering is to load those icons and labels in multithreading.
Hope it helps. | unknown | |
d11881 | train | None of your tests seem to include the one query you've shown to be working:
$GLOBALS['wpdb']->get_results(
"SELECT guid FROM wp_posts WHERE post_parent = $nn",
OBJECT
);
There's no need to do any type conversions, especially not to string. $nn should contain int 526.
full disclosure: I'm not a WP dev and I have no idea how you got from '{{ post_data:ID }}' to 256, also string(18) "526" seems like a very weird output to me. (groetjes aan de daddykaters!) | unknown | |
d11882 | train | field is your package, that's why you can not do field.test(). So you have to choose another name of your Field instance. You can do like this :
var _field:Field = new Field();
addChild(_field);
_field.test();
Hope that can help. | unknown | |
d11883 | train | Answered in this issue: https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2382
For Entity Framework Core
Override OnModelCreating and call modelBuilder.ChangeAbpTablePrefix. Example:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ChangeAbpTablePrefix<Tenant, Role, User>(""); // Removes table prefixes. You can specify another prefix.
}
Remember to add using Abp.Zero.EntityFrameworkCore; to your code file in order to access ChangeAbpTablePrefix extension method. | unknown | |
d11884 | train | Try to import quopri, and then when you get the content of the email body (or whatever text that has the =20s inside), you can use quopri.decodestring()
I do it like this
quopri.decodestring(part.get_payload())
But do keep in mind that this is if you quite specifically want to decode from quoted-printable. Normally I would say the answer of @jfs is neater.
A: Here's a complete code example of how a simple email (that contains both a literal =20 as well as =20 sequence that should be replaced by a space) could be decoded:
#!/usr/bin/env python3
import email.policy
email_text = """Subject: =?UTF-8?B?dGVzdCDwn5OnID0yMA==?=
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable
loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo=
oooooooooooooooooooooooooooooong=20word
=3D20
^ line starts with =3D20
emoji: <=F0=9F=93=A7>"""
msg = email.message_from_string(
email_text, policy=email.policy.default
)
print("Subject: <{subject}>".format_map(msg))
assert not msg.is_multipart()
print(msg.get_content())
Output
Subject: <test =20>
loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word
=20
^ line starts with =20
emoji: <>
msg.walk(), part.get_payload(decode=True) could be used to traverse more complex EmailMessage objects. See email Examples. | unknown | |
d11885 | train | Just use an overlay; <object>s can act funny.
HTML:
<div id="obj_container">
<object id="obj" src="blablabla.pdf"></object>
<div id="obj_overlay"></div>
</div>
CSS:
#obj_container{
position:relative;
}
#obj{
position:absolute;top:0;left:0;
z-index:2;cursor:none;
}
See this JSFiddle demo for more complete code.
A: Yes try using div:
Your HTML:
<div style="cursor:none;">
<object id="obj" class="obj" data='bla-bla.pdf' type='application/pdf'
width='1000px' height='640px'>
</div>
A: How about something like this: http://jsfiddle.net/ZBv22/
It applies a mask over the object element where you specify cursor:none.
The only issue is if you need the object to be clickable/interacted with. Depending on your targeted browsers (modern, IE11+), you could add pointer-events: none to address that.
http://caniuse.com/pointer-events | unknown | |
d11886 | train | I solved the problem myself.
I used webtorrent npm package and also created an algorithm to loop through the whole database and added the magnet link in the download task. once the client gets metadata, I just saved it to the torrent file and canceled the download.
Well, The code is not yet fully production ready. I'll Post The Code Snippet here afterward. Thank You!
UPDATE: I am using this class to download Torrent file from magnet
const Discovery = require('torrent-discovery');
const Protocol = require('bittorrent-protocol');
const ut_metadata = require('ut_metadata');
const addrToIPPort = require('addr-to-ip-port');
const net = require('net');
class TorrentDownloader {
constructor(port, trackers, timeout) {
this.SELF_HASH = '4290a5ff50130a90f1de64b1d9cc7822799affd5';
this.port = port | 6881;
this.trackers = trackers;
this.timeout = timeout | 80000;
}
downloadTorrent(infoHash) {
let self = this;
return new Promise((resolve, reject) => {
let dis = new Discovery({infoHash: infoHash, peerId: this.SELF_HASH, port: this.port, dht: true, announce: this.trackers})
.on('peer', function (peer) {
const peerAddress = {address: addrToIPPort(peer)[0], port: addrToIPPort(peer)[1]};
// console.log(`download metadata from peer ${peerAddress.address}:${peerAddress.port}`);
self.getMetadata(peerAddress, infoHash, resolve);
});
setTimeout(() => {
dis.destroy();
reject(new Error("Torrent Timeout"))
}, this.timeout)
})
}
getMetadata(peerAddress, infoHash, resolve) {
const socket = new net.Socket();
socket.setTimeout(this.timeout);
socket.connect(peerAddress.port, peerAddress.address, () => {
const wire = new Protocol();
socket.pipe(wire).pipe(socket);
wire.use(ut_metadata());
wire.handshake(infoHash, this.SELF_HASH, {dht: true});
wire.on('handshake', function (infoHash, peerId) {
wire.ut_metadata.fetch();
});
wire.ut_metadata.on('metadata', function (rawMetadata) {
resolve(rawMetadata);
wire.destroy();
socket.destroy()
})
});
socket.on('error', err => {
socket.destroy();
});
}
}
module.exports = TorrentDownloader;
A: Given just an infohash, e.g.:
*
*463e408429535139a0bbb5dd676db10d5963bf05
you can use:
BEP: 9 - Extension for Peers to Send Metadata Files
The purpose of this extension is to allow clients to join a swarm and complete a download without the need of downloading a .torrent file first. This extension instead allows clients to download the metadata from peers. It makes it possible to support magnet links, a link on a web page only containing enough information to join the swarm (the info hash).
You use DHT to find the distributed trackers.
Then you use the distributed trackers to find the peers who have the torrent.
Then you can download the torrent metadata from a peer.
You send the bencoded metadata request to the peer:
{
"msg_type": 0, ; 0==>request
"piece": 0
} | unknown | |
d11887 | train | Actually I got it :
the error was coming from the server side: I was missing one line of code res.end()
which ends each request
Modified server side code :
app.post('/switchOnOff', function (req, res) {
coul = req.body['couleur'];
console.log('working!');
var val = !allumer ? 1 : 0;
if (coul == 'bleu'){
led14.writeSync(val);}
led14.watch((err, mess) => {
if (err){throw err }})
allumer = !allumer;
}
//#########solving line##########
res.end
}); | unknown | |
d11888 | train | While the code in your self-answer looks like it ought to work, it's not particularly elegant:
*
*You should really be using a with block to work with files.
*Your variable line is misnamed: it doesn't contain a line at all, but the entire contents of your input file.
*Your script reads in the entire file at once, which may be problematic for large files in terms of memory use.
Here's an alternative:
def excise(filename, start, end):
with open(filename) as infile, open(filename + ".out", "w") as outfile:
for line in infile:
if line.strip() == start:
break
outfile.write(line)
for line in infile:
if line.strip() == end:
break
for line in infile:
outfile.write(line)
This function uses with open(...) (scroll down to the paragraph starting "It is good practice to use the with keyword ...") to ensure that files will be properly closed even if you hit an error of some kind, as well as reading and writing one line at a time to conserve memory.
If you have a file example.txt with the following content:
one
two
three
//StartBB
four
five
six
//EndBB
seven
eight
nine
... then calling excise() as follows ...
excise("example.txt", "//StartBB", "//EndBB")
... will do what you want:
example.txt.out
one
two
three
seven
eight
nine
A: CREDITS FOR THIS ANSWER GOES TO lazy1 and his comment solution:
fL is a list of lines. and fL.index will fine a line not part of it.
Do you need to delete for every line or for the whole file? In any
case, use string index to find start and end then slice away.
Something like: i = line.find(DelStart) j = line.find(DelEnd) print
line[:i] + line[j+len(DelEnd):]
# These Are the Variables for our file path and the start and ending points of what I want to delete.
#----------------------------------------------------------------------------------------------------
DelStart = "//StartBB" #Replace This With Proper Start Que
DelEnd = "//EndBB" #Replace this with the proper End Que
FilePath = "FILEPATH GOES HERE"
#----------------------------------------------------------------------------------------------------
#Sets Line to open our filepath and read it
line = open(FilePath).read()
#i finds our start place j finds our ending place
i = line.find(DelStart)
j = line.find(DelEnd)
#sets text as finding start and end and deleting them + everything inbetween
text = line[:i] + line[j+len(DelEnd):]
#Creates our out file and writes it with our filter removed
out = open(FilePath + '.out', 'w')
out.write(text)
#Closes Our New File
out.close()
#Ends Script
Script.close()
A: This uses only built-in string functions:
string = "This is the string"
stringA = "This"
stringB = " string"
stringC = stringA + stringB
stringD = stringC.replace(string, stringC)
A: A rewrite of the important part of @KennethDWhite 's answer, as a function. I would simply have posted it as a comment to his answer, but that would not format correctly.
# ToDo: this also deletes the delimiters. Perhaps add a parameeter to indicuate
# whether to do so,or just to delete the text between them?
def DeleteStringBetween(string, startDelimiter, endDelimiter):
startPos = string.find(startDelimiter)
endPos = string.find(endDelimiter)
# If either delimiter was not found, return the string unchanged.
if (startPos == -1) or (endPos == -1):
return string
return string[:startPos] + string[endPos + len(endDelimiter):] | unknown | |
d11889 | train | You're checking for VMs with the exact name "ABCDE". To check for VMs whose name begins with "ABCDE" use the -like operator and a wildcard:
Get-VM | Where { $_.Name -notlike 'ABCDE*' } | ...
Make the pattern *ABCDE* if you want to exclude VMs with the substring "ABCDE" anywhere in their name (not just the beginning). | unknown | |
d11890 | train | I believe you can try change event on ColumnChart as:
<mx:ColumnChart id="columnChart" width="100%" height="100%" change="handleChange(event)">
</mx:ColumnChart>
Then in the method handleChangeyou can do all the work. | unknown | |
d11891 | train | Your SQL statement is on multiple lines, but you're not using the correct multi-line syntax. The correct syntax would be:
someLongString := "Line 1 " + // Don't forget the trailing space
"Second line." // This is on the next line.
Currently you're just trying to stuff everything between a set of quotes on different lines.
EDIT: Per as @Kaedys says below, the following also works and may be more performant.
someLongString := `Line 1
Second line.`
A: change both your first and last "\"" to "`", or quote your each line of the query string and then add a "+" between each line like
"select" +
" *" +
" from" +
" table" | unknown | |
d11892 | train | When using authentication you should remember to add useHeaderAuthentication : true to your proxies to know that they should include authentication data to their headers. | unknown | |
d11893 | train | You can use map.forEachLayerAtPixel, which will call your callback for any raster layers that are not transparent on the given pixel. | unknown | |
d11894 | train | I am posting @ShreeGrossOptum's answer from the comments for better visibility and due to lack of response from the OP:
Sir please check once about attributes I hope you ll get your
answers like why mostly attributes are unknown and empty. | unknown | |
d11895 | train | Update *? That is not valid syntax. I think the rest is basically ok:
Update mytable
set outofdate = lastmodification + interval 10 day;
WHERE outofdate < NOW( )
LIMIT 0, 100;
Note that the number of seconds in a day is not 84,500. Also, for date/time data types, use date_add() or interval addition. | unknown | |
d11896 | train | Whenever you need to access any UI element from a non-activity class, you need to pass the context to your class. A rough method is:
in your activity's onCreate() method:
myInstance.setContext(this);
and in your Class, you have:
Context mContext;
public void setContext(Context c){
mContext = c;
}
A:
I am wondering if it is possible to access a button from a
non-activity class using an activity class?
Yes, it's possible if the non-activity class can access the methods of an activity class. This can be done by passing the reference of an activity to that non-activity class in the onCreate() method. But remember to release that reference and any other reference to the activity Views when the Activity is destroyed, that is when it's onDestroy() method being called.
The button is in a different xml file than the one of the activity
class.
A button that is not added to an Activity's View Tree can be accessed. You can inflate the layout that contains the button and add the inflated View root to your Activity's ViewGroup.
Also, is it possible to create options menu in the non-activity class?
Yes, it's possible if the non-activity class can access the methods of an activity class.
A: Anyone can correct me if I'm wrong. But my assumption answer to your question and how I understand what you trying to achieve. Android has made it easy to access controls in other xml files. You have the < include> which you can include other non-activity(fragments) in your activity. Actually it's pretty easy to do this that is the first way to do it. I know they is another way still playing around with your xml files. There is resource to bring non-activity controls to activity layouts with having to do much programmatically. Look at resources available to you on your layout builder. | unknown | |
d11897 | train | Indeed, it's not supported to cover all series. Here you can find workarund.
With demo: http://jsfiddle.net/highcharts/SD4XN/
In short: in callback add series to the navigator on your own:
function (chart) {
chart.addSeries({
data: seriesOptions[2].data,
xAxis: 1,
yAxis: 1
});
}
A: The scrollbar you refer to is called navigator.
There is a property in navigator called series which is defined as:
series: Object
Options for the navigator series. Available options are the same as
any series, documented at plotOptions and series.
Unless data is explicitly defined on navigator.series, the data is
borrowed from the first series in the chart.
You can see it here.
Im not sure if you can build your navigator from multiple series, i suppose it is posibles. In case it is not build build the navigator with the largest. | unknown | |
d11898 | train | You could use a DataTrigger in an inner border Style with FindAncestor or ElementName binding to get the IsMouseOver of your outer border.
i.e.
<Border.Style>
<Style TargetType="Border">
<Setter Property="RenderTransform">
<Setter.Value>
<RotateTransform Angle="3"/>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=IsMouseOver}" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<RotateTransform Angle="6"/>
</Setter.Value>
</Setter>
</DataTrigger >
</Style.Triggers>
</Style>
</Border.Style> | unknown | |
d11899 | train | You probably have a Task<T>.Result or Task.Wait call further up your call stack. This will cause a deadlock on ASP.NET that I describe in more detail on my blog.
In summary, await will capture a "context" - in this case, an ASP.NET request context, which only allows one running thread at a time. When its awaitable completes (that is, when the POST finishes), the async method will continue in that context. If your code is blocking further up the call stack (e.g., Result or Wait), then it will block a thread in that ASP.NET request context, and the async method cannot enter that context to continue executing.
You don't see the deadlock in the Console app because there's no context being captured, so the async method resumes on a thread pool thread instead. | unknown | |
d11900 | train | Actually, if you are talking about this log statement here:
// Some fake testing data
console.log(this.result);
The reason why this.result doesn't have the same data is because the Promise is probably still pending (fulfilling the promise).
I suspect when you see these console logs, you see the one outside the Promise display first. This is to be expected.
Also, your block scope is different, meaning this.result can be different inside that Promise context.
Try changing:
this.result = {};
to:
var result = {};
And also change
var1.then(function (data){
result = data;
console.log(result);
}); | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.