id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23532900
|
I have been struggling to query this via JObject/JArray and wanted to know if there is a way to do it. Here is my JSON file that I am querying from:
"products":[{
"id":124534,
"handle": "Data1",
"variants":[
{
"barcode":null,
"sku":"M11-168-EN-NFNE-0",
"price":1.5
},
{
"barcode":null,
"sku":"M11-168-EN-NFNE-0",
"price":1.5
}]
},
{
"id":548562,
"handle": "Data2",
"variants":[
{
"barcode":null,
"sku":"M11-168-EN-NFNE-0",
"price":1.4,
}]
}]
Any help on this would be very much appreciated.
A: Let's suppose that these are your model classes:
public class Product
{
public int Id { get; set; }
public string Handle { get; set; }
public Variant[] Variants { get; set; }
}
public class Variant
{
public string Barcode { get; set; }
public string SKU { get; set; }
public double Price { get; set; }
}
Then the LINQ query would look like this:
static string GetTheFirstProductWhereOneOfItsVariantHasAGivenPrice(IEnumerable<Product> products, double expectedPrice)
{
var product = products
.FirstOrDefault(p => p.Variants.Any(variant => Math.Abs(variant.Price - expectedPrice) < 0.05));
return product?.Handle ?? "Not Found";
}
*
*It tries to find the first Product (if any) << products.FirstOrDefault
*where there is a variant with a given price (inside the error margin) << Variants.Any
*If there is one then it returns with its Handle property otherwise with Not Found
The usage would look like this:
static void Main(string[] args)
{
const double expectedPrice = 1.4;
string secondProductWithTheGivenPrice =
"[{\r\n \"id\":124534,\r\n \"handle\": \"Data1\", \r\n \"variants\":[\r\n {\r\n \"barcode\":null,\r\n \"sku\":\"M11-168-EN-NFNE-0\",\r\n \"price\":1.5\r\n },\r\n {\r\n \"barcode\":null,\r\n \"sku\":\"M11-168-EN-NFNE-0\",\r\n \"price\":1.5\r\n }]\r\n},\r\n{\r\n \"id\":548562,\r\n \"handle\": \"Data2\", \r\n \"variants\":[\r\n {\r\n \"barcode\":null,\r\n \"sku\":\"M11-168-EN-NFNE-0\",\r\n \"price\":1.4,\r\n }]\r\n}]";
var products = JsonConvert.DeserializeObject<Product[]>(secondProductWithTheGivenPrice);
Console.WriteLine(GetTheFirstProductWhereOneOfItsVariantHasAGivenPrice(products, expectedPrice));
string firstProductWithTheGivenPrice =
"[{\r\n \"id\":124534,\r\n \"handle\": \"Data1\", \r\n \"variants\":[\r\n {\r\n \"barcode\":null,\r\n \"sku\":\"M11-168-EN-NFNE-0\",\r\n \"price\":1.5\r\n },\r\n {\r\n \"barcode\":null,\r\n \"sku\":\"M11-168-EN-NFNE-0\",\r\n \"price\":1.4\r\n }]\r\n},\r\n{\r\n \"id\":548562,\r\n \"handle\": \"Data2\", \r\n \"variants\":[\r\n {\r\n \"barcode\":null,\r\n \"sku\":\"M11-168-EN-NFNE-0\",\r\n \"price\":1.4,\r\n }]\r\n}]";
products = JsonConvert.DeserializeObject<Product[]>(firstProductWithTheGivenPrice);
Console.WriteLine(GetTheFirstProductWhereOneOfItsVariantHasAGivenPrice(products, expectedPrice));
string withoutGivenPrice =
"[{\r\n \"id\":124534,\r\n \"handle\": \"Data1\", \r\n \"variants\":[\r\n {\r\n \"barcode\":null,\r\n \"sku\":\"M11-168-EN-NFNE-0\",\r\n \"price\":1.5\r\n },\r\n {\r\n \"barcode\":null,\r\n \"sku\":\"M11-168-EN-NFNE-0\",\r\n \"price\":1.6\r\n }]\r\n},\r\n{\r\n \"id\":548562,\r\n \"handle\": \"Data2\", \r\n \"variants\":[\r\n {\r\n \"barcode\":null,\r\n \"sku\":\"M11-168-EN-NFNE-0\",\r\n \"price\":1.3,\r\n }]\r\n}]";
products = JsonConvert.DeserializeObject<Product[]>(withoutGivenPrice);
Console.WriteLine(GetTheFirstProductWhereOneOfItsVariantHasAGivenPrice(products, expectedPrice));
}
The output would look like this:
Data2
Data1
Not Found
| |
doc_23532901
|
Now i want those organizations to be deleted from xx_org whose org_id is not in xx_asg and the person id in xx_people who have a column value extra_info as 'ITEM_OTB'.
XX_ORG XX_PEOPLE XX_ASG
ORG_ID PERSON_ID ASG_ID
ORG_NAME PERSON_NAME ASG_NAME
LEGAL_ENTITY PERSON_NUMBER ORG_ID
ASG_ID
EXTRA_INFO
DELETE FROM XX_ORG WHERE
ORG_ID NOT IN (SELECT DISTINCT ORG_ID FROM XX_ORG);
How do i incorporate my second requirement in this one that is thsoe people from xx_person who do have extra_info as 'ITEM_OTB' , Those people's org ids should also be deleted
A: If I understood you correctly, we want to delete all orgs except those that exist in asg who have people with extra info equal to ITEM_OTB.
DELETE
FROM XX_ORG
WHERE ORG_ID NOT IN (
SELECT DISTINCT a.ORG_ID
FROM XX_ASG a
INNER JOIN XX_PEOPLE p ON a.ASG_ID = p.ASG_ID
WHERE p.EXTRA_INFO = 'ITEM_OTB');
| |
doc_23532902
|
An example would be:
If i select the "Free International Shipping" the "Cash" paymend option must be removed or inactive.
A: I think you can do using observer. First of all you have to create one module(I'm assuming you already know how to create module)
In your config.xml from app>code>your_codepol>Namespace>module>etc>config.xml
<frontend>
<events>
<payment_method_is_active>
<observers>
<paymentfilter_payment_method_is_active>
<type>singleton</type>
<class>YOUR_CLASS_observer</class>
<method>paymentMethodIsActive</method>
</paymentfilter_payment_method_is_active>
</observers>
</payment_method_is_active>
</events>
</frontend>
and create your observer and write this code in your observer.php
public function paymentMethodIsActive(Varien_Event_Observer $observer) {
$event = $observer->getEvent();
$method = $event->getMethodInstance();
$result = $event->getResult();
$quote = $observer->getEvent()->getQuote();
$shippingMethod = $quote->getShippingAddress()->getShippingMethod();
if($shippingMethod=="Free International Shipping"){
if($method->getCode() == 'cashondelivery' ){ // to hide this method
$result->isAvailable = false; // false means payment method is disable
}
}
}
Where cashondelivery is payment method name. You can write any payment name like
*
*ccsave(Credit Card (saved))
*checkmo(Check / Money order)
*purchaseorder(Purchase Order)
*banktransfer(Bank Transfer Payment)
*cashondelivery(Cash On Delivery)
etc..
Let me know if you have any query
| |
doc_23532903
|
I know that I can do it through API, but wondering if there is a way to use query string parameters or something like that.
Wondering if there is a way to do that?
| |
doc_23532904
|
I know that with $this->redirect() I can use $this->redirect(array(controller/action)), but is always showing the index action.
A: In your main.php, you should have these default rules in urlManager section:
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
Simply add this above the existing rules:
'<controller:\w+>/' => '<controller>/index',
| |
doc_23532905
|
Previously, the azure function is deployed as stand alone service. I can get a publishProfile. So I'm authorized to call
GET /admin/functions/{functionname}/keys
But in k8s, the call returns 401, because I can't get publishProfile. Is there anything equivalent to publishProfile in k8s?
A: When deploying your Azure Function inside Kubernetes, they are now running as Kubernetes Pods and will not show up in Azure Functions anymore.
see this for instruction on how to see your running functions(pods)
https://github.com/kedacore/sample-hello-world-azure-functions#10-add-a-queue-message-and-validate-the-function-app-scales-with-keda
A: Azure Functions are open source. They can be hosted anywhere (even on GCP or AWS). Azure Cloud provides you a managed version of Azure Functions. When you create an azure function app through the portal (or azure cloud SDK) you can see it in the portal.
Now when you deploy Azure Functions in a Kubernetes Cluster, it is equivalent to deploying/hosting Azure Functions on your local machine (or any other cloud provider). Thus, azure functions deployed in Kubernetes Cluster are not part your azure cloud and hence cannot be accessed as a service that azure provides.
| |
doc_23532906
|
public class MainActivity extends Activity {
public static String dampfhammerData = "dampfhammerData";
SharedPreferences DampfhammerData;
public int nextCard;
public int lastCard = 0;
public int all=3;
public int buddy=3;
public int dampfhammer=3;
public int frauen=3;
public int links=3;
public int rechts=3;
public int maenner=3;
public int questionmaster=3;
public int regel=3;
public int themenrunde=3;
public int zaehlen=3;
public int deck = 44;
public String version;
ImageView Karte;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void changeCard(View view) {
selectCard();
}
public void selectCard(){
lastCard = nextCard;
if(deck > 0) {
Random rand = new Random();
nextCard = (rand.nextInt(10));
if(nextCard != lastCard) {
checkCardDeck();
}else {
selectCard();
}
}else {
Intent intent = new Intent(this, End.class);
startActivity(intent);
}
}
public void checkCardDeck(){
Karte = (ImageView) findViewById(R.id.karte);
switch (nextCard) {
case 0:
if(all > 0){
all--;
deck--;
Karte.setBackgroundResource(R.drawable.all);
}else {
selectCard();
}
break;
case 1:
if(zaehlen > 0){
zaehlen--;
deck--;
Karte.setBackgroundResource(R.drawable.zaehlen);
}else {
selectCard();
}
break;
case 2:
if(buddy > 0){
buddy--;
deck--;
Karte.setBackgroundResource(R.drawable.buddie);
}else {
selectCard();
}
break;
case 3:
if(themenrunde > 0){
themenrunde--;
deck--;
Karte.setBackgroundResource(R.drawable.themenrunde);
}else {
selectCard();
}
break;
case 4:
if(dampfhammer > 0){
dampfhammer--;
deck--;
Karte.setBackgroundResource(R.drawable.dampfhammer);
}else {
selectCard();
}
break;
case 5:
if(links > 0){
links--;
deck--;
Karte.setBackgroundResource(R.drawable.links);
}else {
selectCard();
}
break;
case 6:
if(rechts > 0){
rechts--;
deck--;
Karte.setBackgroundResource(R.drawable.rechts);
}else {
selectCard();
}
break;
case 7:
if(frauen > 0){
frauen--;
deck--;
Karte.setBackgroundResource(R.drawable.frauen);
}else {
selectCard();
}
break;
case 8:
if(maenner > 0){
maenner--;
deck--;
Karte.setBackgroundResource(R.drawable.maenner);
}else {
selectCard();
}
break;
case 9:
if(questionmaster > 0){
questionmaster--;
deck--;
Karte.setBackgroundResource(R.drawable.questionmaster);
}else {
selectCard();
}
break;
case 10:
if(regel > 0){
regel--;
deck--;
Karte.setBackgroundResource(R.drawable.regel);
}else {
selectCard();
}
break;
}
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Wollen sie das Spiel verlassen?") //
.setMessage("Das aktuelle Spiel wird abgebrochen und sie kehren zum Startbildschirm zurück, wollen sie das wirklich?") //
.setPositiveButton(("Ja"), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton(("Nein"), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.show();
}
}
Thanks for your help!
A: If your deck of cards consists of 11 cards that each appear four times (I think that's right based on looking at the code), you can create a random shuffle like this:
ArrayList<Integer> deckList = new ArrayList<Integer>();
for (int i=0; i<11; i++) {
deckList.add(i); deckList.add(i); deckList.add(i); deckList.add(i);
}
Collections.shuffle(deckList);
By instead picking a random next card and retrying when it's a repeat, you're using a very inefficient and unpredictable process, especially since the retries are recursive, increasing the size of the call stack.
You will of course have to make other changes to use my deck in your code, but it should be quite a bit faster.
| |
doc_23532907
|
Is there a way to protect app source code from being read?
| |
doc_23532908
|
I have read about adding border to each cell, table row, etc. But I need to have a border (kind of a box) around some set of rows.
Lets assume that a table has 5 rows, but i want to enclose 3 rows in a separate box and the other 2 rows in a separate box.
I want to do it programmatically from java code behind; is it possible?
The rectangles having sphere in it are the elements of tablerow and i have set a green and red background to some set of tablerows. I want it to be shown just like border, like a box containing the set of rows instead of a complete red and green background. I hope I am clear with my question. Need your suggestions..
A: you can do it by set background and padding for your rows.of course I think still other ways exist.
<TableLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TableRow
android:id="@+id/t1"
android:background="#00f"
android:padding="2dp"
android:layout_margin="5dp">
<TextView
android:text=" blue border "
android:gravity="center"
android:textColor="#000"
android:background="#fff"
android:padding="5dp"/>
</TableRow>
<TableRow
android:id="@+id/t2"
android:background="#f00"
android:padding="2dp"
android:layout_margin="5dp">
<TextView
android:text="red border"
android:textColor="#000"
android:gravity="center"
android:background="#fff"
android:padding="5dp"/>
</TableRow>
<TableRow
android:id="@+id/t3"
android:background="#0f0"
android:padding="2dp"
android:layout_margin="5dp">
<TextView
android:text="green border"
android:textColor="#000"
android:gravity="center"
android:background="#fff"
android:padding="5dp"/>
</TableRow>
</TableLayout>
UPDATE:
in your activity you can change border color by TabaleRow id:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TableRow row1 = (TableRow) findViewById(R.id.t1);
row1.setBackgroundColor(Color.BLUE);
TableRow row2 = (TableRow) findViewById(R.id.t2);
row2.setBackgroundColor(Color.BLUE);
TableRow row3 = (TableRow) findViewById(R.id.t3);
row3.setBackgroundColor(Color.RED);
}
| |
doc_23532909
|
filters the text and checks if that movie name is present in movies Array. I would like to display the result in resultContainer.
I am able to read the text entered in input box and pass it to SearchMovies function but not sure how to handle the promise resolve and reject.
How shall I use the output of promise and assign it to resultsContainer?
class MovieSearch {
constructor(searchInput, resultsContainer) {
this.searchInput = searchInput;
this.resultsContainer = resultsContainer;
}
//helper function to debounce (only call it after there has been a "cool off" period) a function
_debounce(fn) {
let timeout = undefined;
return (...args) => {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
fn(...args);
}, 200);
};
}
}
// use this function to search the movie.
function searchMovies(searchText) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const regex = new RegExp(`${searchText}`, "i");
try {
resolve(movies.filter((movie) => regex.test(movie)));
} catch (e) {
reject(e);
}
}, 800);
});
}
const search = new MovieSearch(
document.querySelector(".search-input"), //input text area
document.querySelector(".search-results") //display the result here
);
//call searchMovies and pass the input entered in text box
var progress = search._debounce(searchMovies)
search.searchInput.addEventListener('input', function(){
progress(search.searchInput.value);
});
const movies = [
"Nomadland",
"Minari",
"Judas and the Black Messiah",
"The Trial of the Chicago 7",
];
At what point should I assign the result to resultContainer ? Do I need to call SearchMovies function twice ?
| |
doc_23532910
|
I suspect this involves the skipIf decorator, but I don't see what to check against. Through debugging, I can see that some of the unittest classes hold this info, but it's not passed to my code.
So far, I see two ways to sort of do this:
1) Have setUp() increment a counter per test. If the test is not the first one, skip. This is close, but means I need to be careful about the name to keep it from being run first.
2) Put a flag in the file, and check against it. The main problem is that involves code changes whenever I want to run the test, with all that implies.
| |
doc_23532911
|
xtype: 'filefield',
id: 'image',
emptyText: '-- Choose Image --',
fieldLabel: 'Photo',
name: 'image',
anchor: "82%",
buttonText: 'Browse',
buttonConfig: {
iconCls: ''
},
change: function() {
// this is get component
var valueElement = Ext.getCmp("component_image_upload").getValue();
// function upload image full path and encode to base64
// function here
// result to encode base64
var GenEncoded = valueElement;
Ext.getCmp("component_textarea").setValue( GenEncoded );
I try to add btoa function but it just convert the string on the filefield, not for uploading image :
// result to encode base64
var GenEncoded = btoa(valueElement);
Ext.getCmp("ttransdelivery_module_manualreceive_form_receive_ar_1_general_blk_i_form_text_2031").setValue( GenEncoded );
Thank you
A: You could use FileAPI for this. But keep in mind that it's not supported in all browsers. Check caniuse for support.
This should work:
change: function() {
var valueElement = Ext.getCmp("component_image_upload").getValue();
var reader = new FileReader();
reader.onload = function(e) {
Ext.getCmp("component_textarea").setValue(e.target.result);
};
reader.onerror = function(e) {
//error reading file
};
reader.readAsDataURL(valueElement.el);
}
Check the api of FileReader for more info.
A: Thank you for helping, this is my listener code. This code work :
change: function() {
var valueElement = Ext.getCmp('image').getEl().down('input[type=file]').dom.files[0];
var reader = new FileReader();
reader.onload = function(e) {
Ext.getCmp("ttransdelivery_module_manualreceive_form_receive_ar_1_general_blk_i_form_text_2031").setValue(e.target.result);
};
reader.onerror = function(e) {
alert('The File APIs are not fully supported in this browser.');
};
reader.readAsDataURL(valueElement);
}
Thanks for help mate
| |
doc_23532912
|
It says:
For this version, we use a standard HMAC-SHA512 signing. Append apikey and nonce to your request and calculate the HMAC hash and include it under an apisign header. Note: the nonce is not respected right now but will be enforced later.
$apikey='xxx';
$apisecret='xxx';
$nonce=time();
$uri='https://bittrex.com/api/v1.1/market/getopenorders?
apikey='.$apikey.'&nonce='.$nonce;
$sign=hash_hmac('sha512',$uri,$apisecret);
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult);
Can i do it without knowing PHP?
Or it's not PHP?
Or what to do with this actually?
A: Yes, this is PHP code and I really doubt that you should execute it on your phone. You should execute it on some server and when called it will return JSON object. So your android app should call it, get JSON object, unpack it and use data from it.
Or, you can make equivalent in Java or what ever you use for coding android app and use the same technique like in this PHP example to call this bittrex api and acquire data.
Basically this code is making (I would say GET) request to bittrex api end-point. It's passing apikey and nounce so you must get real values to run it.
Then it makes sign out of api secret with PHP hash_hmac() funciton:
http://php.net/manual/en/function.hash-hmac.php
So you must find some equivalent for your programming language. The it's passed as "apisign" header parameter.
| |
doc_23532913
|
For Firefox and Chrome, when I use padding, this is added to the total width of the div. For IE, padding values are ignored so the CSS doesn't work uniformly. This seems to be a new development because they've always worked the same. EG
#header
{
width:280;
padding-left:10px;
padding-right:10px;
}
This gives a total of 300px in Firefox and Chrome but the width doesn't change in IE.
How do I handle this issue?
A: What you're dealing with here is a known problem in IE.
In short, when there's a problem with your HTML, IE drops into Quirks Mode as it tries to figure out how to resolve those problems. When it does this, its interpretation of the CSS Box Model (the thing that determines how to handle width, padding, border and margin) breaks away from the W3C standard.
So, odds are, there's a problem with your HTML and your first port of call should be the W3C Markup Validation Service. Use this to validate your HTML. Once your HTML validates, try again with your CSS. If it's still broken, head back here.
A: Adding a doctype and modifying my html tag helped me fix the problem. This is the new change below.
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
Of course, I used opening and closing tags but there's not displaying properly as code blocks
| |
doc_23532914
|
var downloadUrl = buildRequestUrl();
window.open(downloadUrl, '_self');
That is working fine, but I need to pass some custom headers with the request, so I am using ajax, like this:
$.ajax(downloadUrl, {
headers: { 'custom-header': 'custom-header-value'},
type: 'GET',
contentType: 'application/octet-stream'
}).done(function (data) {
var blob = new Blob([data], { type: 'application/pdf' });
var link = window.document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = '';
link.click();
});
The file get downloaded, but the content is empty (3 blank pdf pages). What I am doing wrong ?
| |
doc_23532915
|
As part of our build process, I would like to automate the generation of Excel files during the Visual Studio build. [Then, I will compare the file to an approved version to ensure no regression errors have occurred.]
I would prefer not to use RS.exe, as all report developers would not have SSRS installed. I am looking for a local option, so that we don't have to deploy to an SSRS server and render from there.
How can I generate exports from the RDL files during the local build process?
A: One option is to create your own build tool, like a console application that has references to the Microsoft.ReportViewer.Common and Microsoft.ReportViewer.WinForms. In order to get the correct assemblies, install the Microsoft Report Viewer Controls (Redistributable Package) from:
https://msdn.microsoft.com/en-us/library/ms251723(v=vs.120).aspx
This tool could spin up an instance of a report viewer control, process the report in local processing mode, and return the excel byte stream that can be saved as a file output.
| |
doc_23532916
|
This is how I am populating the ViewBag:
public IEnumerable<SelectListItem> GetGradeLevelItems(int selectedGradeLevelId = 0)
{
var allGradeLevels = _courseRepository.GetAllGradeLevels();
var gradeLevelItems = new List<SelectListItem>();
if (selectedGradeLevelId == 0) //if 0, we're creating a new course. Let's add a default option to the list
{
gradeLevelItems.Add(new SelectListItem() { Value = "0", Text = "--Choose--", Selected = true });
}
else if (allGradeLevels != null && allGradeLevels.All(gl => gl.GradeLevelId != selectedGradeLevelId)) //if the selected grade level is not in the table
{
selectedGradeLevelId = allGradeLevels?.Min(gl => gl.GradeLevelId) ?? 0;
}
allGradeLevels?.ForEach(gl => gradeLevelItems.Add(new SelectListItem(){
Text = gl.GradeLevelName,
Value = gl.GradeLevelId.ToString(),
Selected = (gl.GradeLevelId == selectedGradeLevelId)
}));
return gradeLevelItems;
}
Here's the code I have at the moment:
<div class="form-group">
@Html.LabelFor(m => m.GradeLevelId, new {@class = "row control-label details-label"})
<div class="row">
<input class="form-control" type="text" disabled value=@ViewBag.GradeList[(int)(@Model.GradeLevelId ?? 0)].Text />
</div>
</div>
Anyone see where I'm going wrong here? Thanks in advance for any help!
A: You need to add quotes around the attribute value
<input class="form-control" type="text" disabled value="@ViewBag.GradeList[(int)(@Model.GradeLevelId ?? 0)].Text" />
| |
doc_23532917
|
Inside the auction show view, I am displaying a list off all bids with the regarding bidder (=User who have placed the bid). When placing a new bid, the user_id is successfully saved within the bid table.
I want to display the bidders name instead of his ID. (with @bidder = User.find(@bid.user_id))
bids_controller.rb:
class BidsController < ApplicationController
# Create new bid
def create
# find Auction related to new Bid
@auction = Auction.find(params[:auction_id])
@bid = @auction.bids.create(bid_params)
@bid.user_id = current_user.id
# Find the bidder within User Table
@bidder = User.find(@bid.user_id)
@bid.save
redirect_to auction_path(@auction), :notice => "Bid placed"
end
Bids Partial view: views\bids\ _bid.html.erb
<p>
<strong>Bidder:</strong>
<%= @bidder.name %>
</p>
<p>
<strong>Bid-Amount:</strong>
<%= bid.amount %>
</p>
<p>
<%= link_to 'Destroy Bid', [bid.auction, bid],
method: :delete,
data: { confirm: 'Are you sure?' } %>
</p>
The whole thing is displayed within the Auctions Show View:
views\auctions\show.html.erb
<h2>Bids</h2>
<%= render @auction.bids %>
<h2>Place a Bid:</h2>
<%= render 'bids/form' %>
<h2>Comments</h2>
<%= render @auction.comments %>
<h2>Add a comment:</h2>
<%= render 'comments/form' %>
The Error:
NoMethodError in Auctions#show Showing
C:/Users/santa/Documents/rails/app/views/bids/_bid.html.erb
where line #3 raised:
undefined method `name' for nil:NilClass Extracted source (around line
3): 1 2 3 4 5 6
<p>
<strong>Bidder:</strong>
<%= @bidder.name %> </p>
<p>
Trace of template inclusion: app/views/auctions/show.html.erb
name exists in Users table
A: Instead of <%= @bidder.name %> try add <%= bid.user.name %>. If user_id saving properly in bid table then clearly there is has_many and belongs_to association there.
Just replace <%= @bidder.name %> to <%= bid.user.name %>
| |
doc_23532918
|
An exception occurred while executing 'DROP INDEX IDX_E98F2859A074D5D7 ON contract':
SQLSTATE[HY000]: General error: 1553 Cannot drop index 'IDX_E98F2859A074D5D7': needed in a foreign key constraint
This is trivial to resolve according to another SO question. The table has:
KEY `IDX_E98F2859A074D5D7` (`some_table_id`),
CONSTRAINT `FK_E98F2859A074D5D7` FOREIGN KEY (`some_table_id`) REFERENCES `some_table` (`id`)
So this can be resolved manually by dropping the matching constraint. But is there a way to do it automatically?
A: If you use the information schema, you can easily construct the necessary ALTER TABLE commands; the relevant tables are here: SCHEMA KEY_COLUMN_USAGE and STATISTICS.
Following is an example for a query which generates the DDL statements:
SELECT CONCAT('ALTER TABLE ',kcu.TABLE_NAME,' DROP FOREIGN KEY ', kcu.CONSTRAINT_NAME,';') AS ddl
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu, INFORMATION_SCHEMA.STATISTICS stat
WHERE stat.table_schema = 'your_schema'
AND kcu.TABLE_NAME = stat.TABLE_NAME
AND kcu.COLUMN_NAME = stat.COLUMN_NAME
AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
INTO OUTFILE '/tmp/ddl.sql';
And you can run it after reviewing it by running this statement:
SOURCE '/tmp/ddl.sql';
Above statement will look up constraint name and corresponding table name for every foreign key constraint, where an index exists on the same foreign key column in the same table. The result is stored in the file given by INTO OUTFILE.
Please review above statement carefully before running the generated ddl.
| |
doc_23532919
|
Therefore, I just added those two properties to my entity. I expected a crash, because of pending migrations, so I created an extra migration. Now, these changes I made don't show up in my Realm database on my filesystem.
The code I use to migrate is the following:
func migrate() {
let defaultPath = Realm.Configuration.defaultConfiguration.fileURL!
let realmPath = Bundle.main.url(forResource: "compactedNulTien", withExtension: "realm")
if let bundledRealm = realmPath {
do {
try FileManager.default.removeItem(at: defaultPath)
try FileManager.default.copyItem(at: bundledRealm, to: defaultPath)
} catch {}
}
let config = Realm.Configuration(schemaVersion: 4, migrationBlock: { migration, oldSchema in
if oldSchema < 1 {
migration.enumerateObjects(ofType: PointOfInterest.className(), { (old, new) in
new!["index"] = 0
})
} else if oldSchema < 2 {
migration.enumerateObjects(ofType: PointOfInterest.className(), { (old, new) in
new!["place"] = ""
})
} else if oldSchema < 3 {
migration.enumerateObjects(ofType: PointOfInterest.className(), { (old, new) in
new!["contentImage"] = ""
new!["contentExtension"] = ""
})
}
})
Realm.Configuration.defaultConfiguration = config
do {
realm = try Realm()
} catch(let error) {
Crashlytics().recordError(error)
}
}
This is how I have the realm file in my project, so I expected that one to be upgraded. How do I get the new properties in my local realm database so I can fill them?
A: Right, I forget (probably) that the .realm is copied again to the Documents folder in the Simulator. So I picked it from there with help from print(realm.configuration.fileURL ?? "No URL Found") call. I exported it again to a compacted version, filled it and then I've replaced in Xcode, ran the app again, migrations worked fine, done.
| |
doc_23532920
|
In order to run the same program on Linux machine, which is an 8 core 32 GB machine, i FTPed the generated class files and scala + akka jars to the Linux machine.
the Linux machine is using Server Edition Java and windows machine is using Client edition Java.
When i run the same program on Linux machine with all the paths set properly, i get poor performance than windows machine.
Why is this so? the program is able to run fine but performs poorly on a higher-end machine and on server edition.
Is it due to compilation and run environment differences? What all i can do to investigate the reason for this behavior.
EDIT: The windows env where compilation is done 32 bit, and the java on the linux machine is 64 bit server. does that make any difference to the performance?
A: It would be helpful if you post the Java configurations on both machines, i.e. the JVM version and all the flags passed to the java command on both environments.
Also, how do you measure the performance, and what values do you get? Is there anything else involved, such as I/O, network traffic etc.? If not, what algorithms are being used in your program? Is it a program that calculates and then terminates, or is it a server program that runs until shut down?
You should put a special focus on memory configuration (as suggested by @alex23) and the -server flag. Also, make sure that your Linux environment is using a JVM from the same manufacturer as the Windows environment. Windows typically comes with the Sun JVM, whereas some Linuxes may still have the old Oracle JVM. Try java -version on the command line.
Also, instead of comparing the results of a complex program, try a simpler program first. Try to determine the overhead of booting up the JVM, versus the effective runtime of your Java/Scala code.
The idea that a Windows-based build causes performance issues on a Linux machine sounds highly improbable. You can easily check this by compiling your software on the Linux machine and then running it.
| |
doc_23532921
|
But When I call ABC I am losing XYZcontrol
What I want is
-On XYZ user selects option to load product data
-IF mismatch found XYZ calls ABC
-In ABC -user correct mismatch and closes ABC frame
Now I want my program should continue from where it called ABC
Currently It calls ABC and XYZ get executed How I can achieve this ?
And I am using below code
if (frmUpdateData == null || frmUpdateData.isClosed()){
frmUpdateData = new FrmUpdateData();
JDesktopPane desktopPane = getDesktopPane();
desktopPane.add(frmUpdateData);
frmUpdateData.setVisible(true);
frmUpdateData.setLocation(this.getWidth()/2- frmUpdateData.getWidth()/2, this.getHeight()/2-frmUpdateData.getHeight()/2);
}
A: You show use a Modal dialog:
final JDialog frame = new JDialog(parentFrame, frameTitle, true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
When you show a modal dialog, the code that called the modal, is waiting for modal dialog to be closed to continue execution. It is like alert in JavaScript.
If you dont wana use JDialog, you can try this:
JInternalFrame frmUpdateData = null;
frmUpdateData = new JInternalFrame("Test", true, true);
frmUpdateData.setBounds(0, 0, 200, 200);
JDesktopPane desktopPane = new JDesktopPane();
desktopPane.setBounds(0, 0, 600, 600);
desktopPane.add(frmUpdateData);
desktopPane.setVisible(true);
frmUpdateData.setVisible(true);
JFrame frame = new JFrame();
frame.setBounds(0, 0, 600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(desktopPane);
frame.setVisible(true);
while (frmUpdateData != null && !frmUpdateData.isClosed()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
JOptionPane.showMessageDialog(null, "Done");
Reference: Stackoverflow
| |
doc_23532922
|
This works perfectly for a single post that has a custom post type (not "post" or "page"), but when I try to use the same script on a normal Wordpress "page", it runs the function as well (and sends the email), but then it throws a 404 error. The URL in the browser address bar is unchanged (shows the permalink of the page), but it doesn't seem to find the page.
Then, if I refresh the page (without sending POST data again), i.e. by clicking on the browser address bar and hitting Enter), it shows the right page again as usual.
I'm stumped. Why would it do that?
Edit: found the solution here: https://wordpress.stackexchange.com/questions/11749/why-when-i-submit-a-form-in-wordpress-it-loads-a-404-page-though-url-is-correct thanks to @DigitalDesignDj's suggestion to look there.
A: It sounds like your function is returning a value for display on the page, but only when it succeeds in sending an email. You need to suppress the output of the function, because I am guessing it happens above wp_head and interferes with the calls that start the template process up.
This is a guess, but go look for that output, it's all I can think of.
You might have better luck asking at https://wordpress.stackexchange.com/
| |
doc_23532923
|
I've created an html form and I want to send data using ajax but it still
POST http://localhost/Home.php 500 (Internal Server Error)
In particular I want to create a button for every table in a database which I'm using for testing, when I push a button it will show all lines from the database (I've not implemented it yet, I'm only trying to understend how php and ajax communicate)
This is my form (Home.php)
<?php
session_start();
if(!isset($_SESSION['login'])) {
header("Location: Login.php");
unset($_REQUEST);
}
else echo "<span class=\"welcome\"><strong>Benvenuto</strong> <em>" . $_SESSION['username'] . "</em></span>";
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='jquery-1.11.3.js'></script>
<script src='Script.js'></script>
</head>
<body>
<div id="functions">
<button id="createTable">CREATE</button>
<button id="displayTable">DISPLAY</button>
</div>
<div id="createForm">
<form id="queryForm" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input class ="text" name="query" type="text" size="50">
<input type="submit" class="submit" name="createQuery">
</form>
</div>
<div id="displayForm">
<form method="post" id="selectForm">
<?php
include ("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$Tables = $Database->countTable();
foreach($Tables as $column) {
echo "<input type=\"radio\" class=\"submit\" id=\"selectQuery\" name=\"selectQuery\" value=\"". $column . "\"> " . $column;
}
?>
<input type="submit" class="submit" name="createSelect">
</div>
<div style="position:absolute; bottom:10px; left:50%; font-size: 15pt"></span><em>...</em> <a href="Logout.php">Logout</a></div>
</body>
</html>
<?php
if(isset($_POST['createQuery'])) {
include ("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$Database->createTable($_POST["query"]);
header("Location:Home.php");
}
?>
And this is my ajax file
$(document).ready(
function() {
$("#createTable").click(goCreate);
$("#displayTable").click(goDisplay);
$('#selectForm').submit(goSelect);
$("#createForm").hide();
$("#displayForm").hide();
}
);
function goCreate(data) {
$("#createForm").show();
$("#functions").hide();
}
function goDisplay(data) {
$("#displayForm").show();
$("#functions").hide();
}
function goSelect() {
var selectedTable = $("#selectQuery:checked").val();
console.log($("#selectQuery:checked").val());
$.ajax({
url: "Prova.php",
type: "POST",
dataType: "html",
data: {
'select': 'display',
'table': selectedTable
},
success: function(msg) {
console.log(msg);
},
error: function(xhr, desc, err) {
console.log("error");
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
return false;
};
And this is Prova.php where I managed ajax call
<?php
include 'ChromePhp.php';
ChromePhp::log("corretto");
echo "ok belo";
?>
| |
doc_23532924
|
Source:
public string insert_details(bisuness_object user_details)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("insert into tbl_rgsthome values(@firstname,@lastname,@emailid,@password,@address,@upload)", con);
try
{
cmd.Parameters.AddWithValue("@firstname", user_details.firstname_value);
cmd.Parameters.AddWithValue("@lastname", user_details.lastname_value);
cmd.Parameters.AddWithValue("@emailid", user_details.emailid_value);
cmd.Parameters.AddWithValue("@password", user_details.pass_value);
cmd.Parameters.AddWithValue("@address", user_details.addr_value);
cmd.Parameters.AddWithValue("@upload", user_details.fileupl_value);
//cmd.Parameters.AddWithValue("@imagepath", user_details.imgpth_value);
return cmd.ExecuteNonQuery().ToString();
}
catch (Exception show_error)
{
throw show_error;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
home.aspx:
public string getimage(object ob)
{
string img = @"/image/" + ob.ToString();
return img;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);
bisuness_object bo = new bisuness_object();
// cmd.Parameters.AddWithValue("@imagepath", ("@uploadimage") + filename);
bo.firstname_value = TextBox1.Text;
bo.lastname_value = TextBox2.Text;
bo.emailid_value = TextBox3.Text;
bo.pass_value = TextBox4.Text;
bo.addr_value = TextBox6.Text;
bo.fileupl_value = FileUpload1.FileName.ToString();
bisuness_layer bl = new bisuness_layer();
bind();
try
{
string result = bl.record_insert(bo);
}
catch (Exception info)
{
throw info;
}
finally
{
bo = null;
bl = null;
bind();
}
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox6.Text = "";
}
}
how to solve it.....please help me
i want to image in gridview
A: bind the image tag inside the gridview dynamically
by giving the path dynamically
<asp:Image ID="image" Style="width:100px; height:100px;" runat="server" ImageUrl='<%# "~/folder/subfolder/" + Eval("id") +"."+ Eval("imagetype") %>' />
and the method for binding the gridview
protected void GetDayoffer()
{
gridview1.DataSource = bl.method();
gridview1.DataBind();
}
hope this will help you or recovert the bytes into image again and bind it into gridview
| |
doc_23532925
|
Basically what i want to achieve is; when the power is 'on' (true), it will dispatch an action to display a blinking "-LOADING PRESETS-" for a short period of time like 2 seconds then fire another dispatch action to display the default settings like "Drums" that doesn't blink
When the power is off it will reset everything to the initial state. I used the useEffect with 2 functions that returns a promise to simulate an asynchronous steps.
I got almost everything right and going; the drum pads, audio and lights are all working except for the loading feature. The problem is it skips displaying the blinking "LOADING PRESETS" and automatically resolve to display the default settings "Drums" that blinks (it shouldn't). I am attaching a class to make the text blink and removing the class after the 2 seconds delay expires. I'm not sure how and where to clean up / clear setTimeout so i commented it out for now. Need help!
Here's the App.js code:
const initialState = {
power: false,
display: '...',
sound_mode: '...',
volume_lvl: 0.4
};
const stateReducer = (state = initialState, action) => {
switch (action.type) {
case 'TOGGLE_POWER':
return { ...state, power: !state.power };
case 'ADJUST_VOLUME':
return { ...state, volume_lvl: action.volume };
case 'SWITCH_TO_SYNTH_MODE':
return {
...state,
display: action.display,
sound_mode: action.sound_mode
};
case 'SWITCH_TO_DRUM_MODE':
return {
...state,
display: action.display,
sound_mode: action.sound_mode
};
case 'CHANGE_DISPLAY':
return { ...state, display: action.display };
case 'LOAD_SETTINGS':
return {
...state,
display: 'Kick',
sound_mode: 'Drums',
volume_lvl: 0.4
};
case 'RESET_DEFAULTS':
return {
...state,
power: false,
display: '...',
sound_mode: '...',
volume_lvl: 0.4
};
default:
return state;
}
};
function App() {
const [appState, dispatch] = useReducer(stateReducer, initialState);
return (
<AppContext.Provider value={{ appState, dispatch }}>
<div className='DrumApp'>
<Header />
<DrumInterface />
<Footer />
</div>
</AppContext.Provider>
);
}
The Header section where the power button is:
function Header() {
const { appState, dispatch } = useContext(AppContext);
const { power } = appState;
const powerAudioRef = useRef();
const displayRef = useRef();
useEffect(() => {
function loadPrompt(power) {
return new Promise((resolve, reject) => {
if (power === true) {
displayRef.current = setTimeout(() => {
resolve([
dispatch({
type: 'CHANGE_DISPLAY',
display: '--loading preset--'
}),
document.getElementById('preset-status').classList.add('loading')
]);
}, 2000);
}
});
}
function loadSettings() {
return new Promise((resolve, reject) => {
resolve([
//document.getElementById('preset-status').classList.remove('loading'),
dispatch({ type: 'LOAD_SETTINGS' }),
clearTimeout(displayRef.current)
]);
});
}
async function loadPresetSettings() {
await loadPrompt(power);
await loadSettings();
}
loadPresetSettings();
// return () => {
// clearTimeout(displayRef.current);
// };
}, [power, dispatch]);
useEffect(() => {
if (power === false) {
dispatch({ type: 'RESET_DEFAULTS' });
}
}, [power, dispatch]);
const handlePower = () => {
dispatch({ type: 'TOGGLE_POWER' });
handlePowerSound();
};
const handlePowerSound = () => {
document.getElementById('power-btn-audio').play();
document.getElementById('power-btn-audio').currentTime = 0;
};
return (
<header id='App-header'>
<div id='logo'>
<h1>
<span className='orange'>Drum</span>Machine
</h1>{' '}
<p className='small'>
Powered by:{' '}
<FaReact
className={power === true ? 'react-icon spin' : 'react-icon'}
/>{' '}
React
</p>
</div>
<div id='power'>
<button
id='power-btn'
className={power === true ? 'on' : null}
onClick={handlePower}
>
<FaPowerOff />
</button>
<audio
ref={powerAudioRef}
id='power-btn-audio'
src='https://res.cloudinary.com/dzsmdyknz/video/upload/v1532750168/sample-swap/sfx-and-unusual-sounds/bleeps-blips-blonks-blarts-and-zaps/boip.mp3'
className='btn-audio-efx'
>
Your browser does not support the audio element.
</audio>
</div>
</header>
);
}
A: UPDATE:
Finally, I am able to solve the problem of simulating asynchronous processes, here's my code:
useEffect(() => {
/* Display the loading preset and add a classname to make it blink */
function promptLoadingStart() {
return new Promise((resolve, reject) => {
let wait = setTimeout(() => {
dispatch({ type: 'CHANGE_DISPLAY', display: '--loading preset--' });
document.getElementById('preset-status').classList.add('loading');
clearTimeout(wait);
resolve('prompt loading started');
}, 2000);
});
}
/* Remove the classname for blinking text */
function prompLoadingEnd() {
return new Promise((resolve, reject) => {
let wait = setTimeout(() => {
document.getElementById('preset-status').classList.remove('loading');
clearTimeout(wait);
resolve('prompt loading ended');
}, 1000);
});
}
/* Display the initial settings */
function loadSettings() {
return new Promise((resolve, reject) => {
let wait = setTimeout(() => {
dispatch({ type: 'LOAD_SETTINGS' });
handlePowerSound();
clearTimeout(wait);
resolve('load settings done');
}, 200);
});
}
async function loadPreset() {
const step_one = await promptLoadingStart();
console.log(step_one);
const step_two = await prompLoadingEnd();
console.log(step_two);
const step_three = await loadSettings();
console.log(step_three);
}
if (power === true) {
loadPreset();
}
}, [power, dispatch]);
Guys if you have a much better solution I want to know how. Thanks!
| |
doc_23532926
|
vampire's curse
vampire lord
shadow vampire
I created a search form. It will search for cards that contains letters user typed. For example 3 values in my database. If user type "vampire" then press submit, it will show up the values.But it don't know how to compare value in database with a part of a string. Here my code ( I haven't finished yet).
search_form.php
<?php
echo "<h2> Search your card </h2>";
echo "<h3> type your card name fully or partly here </h3>";
echo "<form action='SearchData.php' method='POST'>";
echo "Card name (full or part) <input type='text' name='CardName'/>";
echo "<input type='submit' values='search for card(s)'/>";
?>
SearchData.php
<?php
include('connect.inc');
$connect=mysqli_connect($host,$username,$password,$dbname) or die("can't connect to server");
if(isset($_POST['CardName']) and !empty($_POST['CardName']))
{
$data=mysqli_real_escape_string($connect,$_POST['CardName']);
$query="SELECT CardName FROM dragon WHERE CardName='";
// Iam stucked at here !
}
else
{
echo "search form can not be empty !";
include("search_form.php");
}
?>
A: Have a look at the LIKE function
SELECT id, name FROM cards WHERE name LIKE '%vampire%';
A: For the reference, you can also use REGEXP if you want.
SELECT id, name FROM cards WHERE name REGEXP 'vampire';
A: $search = "%".$_POST['search']."%";
$read = new mysqli($db_hostname,$db_rUsername,$db_rPassword,$db_database);
$stmt = $read->prepare("SELECT `CardName` FROM dragon WHERE `cardname` LIKE ?");
$stmt->bind_param('s',$search);
$stmt->execute();
$stmt->bind_result($cardnameDb);
while ( $stmt->fetch() ) {
$cardName[] = $cardnameDB;
}
$stmt->close();
This returns an array of cards which match the searched term.
Note that the search term has % before and after it, this just acts like a wildcard. I have a non prepared statement one too if you would like to see it however it's not recommended that you use this.
If you have any questions feel free to ask me! Note that he LIKE operator is what you are looking for.
| |
doc_23532927
|
template<class C, class V, Test V::*>
class Test {
};
it gives me compiler error:
unknown type name 'Test'
It's a self-referencing template for now, which doesn't seem possible. What could possibly be done to make it work?
EDIT:
Here's what I'd need this for. I want to implement a bi-directional (think parent-child) relationship schema with the least minimum coding effort.
template <class O, class T, Reference<T, O, Reference O::*> T::* opposite>
class Reference
{
T **data;
int count;
public:
Reference(): data(new T*[N]), count(0) {}
~Reference() {delete[] data;}
Reference &add(T *t) {
handleOtherSide();
return link(t);
}
// a lot of stuff to implement this
};
That's the collection class. Here's how it would be used:
class Partner
{
public:
Reference<Partner, Address, &Address::partner> addresses;
};
class Address
{
public:
Reference<Address, Partner, &Partner::addresses> partner;
};
My goal is to have everything necessary for Reference to work be supplied as template argument, so that there is no need to provide constructors for classes like Partner and Address (currently I supply the opposite member pointer as a constructor arg but this requires me to have explicit constructors for the participant classes). I would also need to pass in or calculate an "owner" pointer to the Reference class. I left this problem out here because I want to focus on the self-referencing template aspect.
The easiest way to think of this is boost::bimap. But the problem with bimap is that I don't want the enclosing bimap but just the left and right part of it. bimap is also not feasible because it would lead to one single bimap managing all associations of a specific relationship. It would possibly hold a large number of objects slowing down operations on it.
A: Are you looking for something like this? It's not self-referencing template, but you can specify derived class as a template type for base class and base class can call derived methods etc.:
template< typename PType, typename PDerived >
class TBase
{
//do stuff with TDerived
public:
bool foo( void )
{
return ( static_cast< PDerived* > ( this )->bar() );
}
};
template< typename PType >
class TDerived : public TBase< PType, TDerived< PType > >
{
friend class TBase< PType, TDerived< PType > > ;
//do stuff
protected:
bool bar( void )
{
return ( true );
}
};
EDIT: Once again, I'm not sure what's your final goal. Here is a solution to what I think you want, or, at least, some hint to what you might use to implement your design. The only requirement that I put is that both TAddress and TPartner have function with same name. See if that's what you need. In principle, you can make a helper class and use CRTP to access member function through a pointer, but I don't think you actually need it.
template< typename PType1, typename PType2 >
class TReference
{
public:
int mFlag;
TReference() :
mFlag( 0 )
{
}
TReference( int fFlag ) :
mFlag( fFlag )
{
std::cout << "Creating reference " << PType1::sName << " -> " << PType2::sName << "." << std::endl;
}
TReference< PType2, PType1 > AccessOpposite( void )
{
PType2 lTmp;
lTmp.Opposite();
return TReference< PType2, PType1 > ( -1 );
}
};
class TPartner;
class TAddress
{
public:
static const char* sName;
TReference< TAddress, TPartner > mRef;
void Opposite( void )
{
std::cout << sName << "::Opposite" << std::endl;
}
};
class TPartner
{
public:
static const char* sName;
TReference< TPartner, TAddress > mRef;
TReference< TAddress, TPartner > Opposite( void )
{
std::cout << sName << "::Opposite" << std::endl;
}
};
const char* TAddress::sName = "TAddress";
const char* TPartner::sName = "TPartner";
int main( void )
{
TAddress lAddress;
TPartner lPartner;
std::cout << lAddress.mRef.mFlag << " " << lPartner.mRef.mFlag << std::endl;
lPartner.mRef = lAddress.mRef.AccessOpposite();
std::cout << lAddress.mRef.mFlag << " " << lPartner.mRef.mFlag << std::endl;
return ( 0 );
}
A: The problem is, what I want to achieve is not possible in C++, at least not with templates and the amount of code and classes I am aiming at (read: single line of code per member). It starts with the compiler needing forward declarations and fully defined types, which is making by-value members and template arguments of such impossible (in case of cyclic dependencies). Then it is not possible to have a member pointer as a template arg when the class of that member is not yet fully defined. The root cause of all this is how the compiler works: it is single pass. And there is nothing I can do about that.
The solution is to use by-reference members or an OO style base class or a boost::any style container to avoid the templates. With the latter 2 it might be possible to have by-value members.
| |
doc_23532928
|
*
*org1 with peer0.org1.com + 1 CA org1 + CLI org1 + orderer.example.com from ordererOrg on PC1
*org2 with peer0.org2.com + 1 CA org2 on PC2
It seems that my network is working, but once a chaincode is instantiated on a peer then invoked, the operation is not propagated. E.g I insert data into the ledger, the chaincode container logs show that they process the data, the peer container used to invoke the chaincode seems to have correctly endorsed and simulated the query too. All of this using commands manually from inside the CLI.
peer0.org1.com container logs
2019-07-09 08:52:08.753 UTC [endorser] EndorseWithPlugin -> DEBU 3784 Entering endorsement for {plugin: escc, channel: mychannel, tx: 50732326bbe19c9eb8de42fa327ee67fc2c8102337ef96cdf9ca49fb7a0b7703, chaincode: fabcar}
2019-07-09 08:52:08.753 UTC [msp.identity] Sign -> DEBU 3785 Sign: plaintext: 0A2040CDC0100B7F12FA1505C311EF86...455254494649434154452D2D2D2D2D0A
2019-07-09 08:52:08.753 UTC [msp.identity] Sign -> DEBU 3786 Sign: digest: 5E7E6A043E851C3316B08F5CB4A05D31840D213793C55BF14EBE64213E852F84
2019-07-09 08:52:08.756 UTC [endorser] EndorseWithPlugin -> DEBU 3787 Exiting {plugin: escc, channel: mychannel, tx: 50732326bbe19c9eb8de42fa327ee67fc2c8102337ef96cdf9ca49fb7a0b7703, chaincode: fabcar}
2019-07-09 08:52:08.756 UTC [endorser] endorseProposal -> DEBU 3788 [mychannel][50732326] Exit
2019-07-09 08:52:08.756 UTC [lockbasedtxmgr] Done -> DEBU 3789 Done with transaction simulation / query execution [50732326bbe19c9eb8de42fa327ee67fc2c8102337ef96cdf9ca49fb7a0b7703]
2019-07-09 08:52:08.756 UTC [endorser] func1 -> DEBU 378a Exit: request from 10.0.0.4:34978
2019-07-09 08:52:08.756 UTC [comm.grpc.server] 1 -> INFO 378b unary call completed grpc.service=protos.Endorser grpc.method=ProcessProposal grpc.peer_address=10.0.0.4:34978 grpc.code=OK grpc.call_duration=8.895639ms
A (successfully executed) query on the ledger then shows that the ledger state didn't change.
However, if I use the node SDK provided in the fabcar example from the official samples repo (invoke.js) to invoke the same chaincode operation I get an error:
node sdk error with node invoke.js
2019-07-09T09:22:03.277Z - warn: [DiscoveryEndorsementHandler]: _build_endorse_group_member >> G0:1 - endorsement failed - Error: failed to execute transaction a0a2570dd9a4ce0c696ab08263320927382c6f3db046843dca70a96b63a97da9: error sending: txid: a0a2570dd9a4ce0c696ab08263320927382c6f3db046843dca70a96b63a97da9(mychannel) exists
Failed to submit transaction: Error: Endorsement has failed
peer0.org1.com container logs after node invoke
2019-07-09 09:22:03.273 UTC [endorser] callChaincode -> INFO 15480 [mychannel][a0a2570d] Entry chaincode: name:"fabcar"
2019-07-09 09:22:03.273 UTC [chaincode] Execute -> DEBU 15481 Entry
2019-07-09 09:22:03.273 UTC [chaincode] Execute -> DEBU 15482 Exit
2019-07-09 09:22:03.273 UTC [endorser] callChaincode -> INFO 15483 [mychannel][a0a2570d] Exit chaincode: name:"fabcar" (0ms)
2019-07-09 09:22:03.273 UTC [chaincode] handleMessage -> DEBU 15484 [a0a2570d] Fabric side handling ChaincodeMessage of type: PUT_STATE in state ready
2019-07-09 09:22:03.273 UTC [endorser] SimulateProposal -> ERRO 15485 [mychannel][a0a2570d] failed to invoke chaincode name:"fabcar" , error: txid: a0a2570dd9a4ce0c696ab08263320927382c6f3db046843dca70a96b63a97da9(mychannel) exists
github.com/hyperledger/fabric/core/chaincode.(*TransactionContexts).Create
/opt/gopath/src/github.com/hyperledger/fabric/core/chaincode/transaction_contexts.go:59
github.com/hyperledger/fabric/core/chaincode.(*Handler).Execute
/opt/gopath/src/github.com/hyperledger/fabric/core/chaincode/handler.go:1207
github.com/hyperledger/fabric/core/chaincode.(*ChaincodeSupport).execute
/opt/gopath/src/github.com/hyperledger/fabric/core/chaincode/chaincode_support.go:313
github.com/hyperledger/fabric/core/chaincode.(*ChaincodeSupport).Invoke
/opt/gopath/src/github.com/hyperledger/fabric/core/chaincode/chaincode_support.go:302
github.com/hyperledger/fabric/core/chaincode.(*ChaincodeSupport).Execute
/opt/gopath/src/github.com/hyperledger/fabric/core/chaincode/chaincode_support.go:239
github.com/hyperledger/fabric/core/endorser.(*SupportImpl).Execute
/opt/gopath/src/github.com/hyperledger/fabric/core/endorser/support.go:147
github.com/hyperledger/fabric/core/endorser.(*Endorser).callChaincode
/opt/gopath/src/github.com/hyperledger/fabric/core/endorser/endorser.go:146
github.com/hyperledger/fabric/core/endorser.(*Endorser).SimulateProposal
/opt/gopath/src/github.com/hyperledger/fabric/core/endorser/endorser.go:247
github.com/hyperledger/fabric/core/endorser.(*Endorser).ProcessProposal
/opt/gopath/src/github.com/hyperledger/fabric/core/endorser/endorser.go:500
github.com/hyperledger/fabric/core/handlers/auth/filter.(*expirationCheckFilter).ProcessProposal
/opt/gopath/src/github.com/hyperledger/fabric/core/handlers/auth/filter/expiration.go:61
github.com/hyperledger/fabric/core/handlers/auth/filter.(*filter).ProcessProposal
/opt/gopath/src/github.com/hyperledger/fabric/core/handlers/auth/filter/filter.go:32
github.com/hyperledger/fabric/protos/peer._Endorser_ProcessProposal_Handler.func1
/opt/gopath/src/github.com/hyperledger/fabric/protos/peer/peer.pb.go:169
github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1.1
/opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware/chain.go:31
github.com/hyperledger/fabric/core/comm.(*Throttle).UnaryServerIntercptor
/opt/gopath/src/github.com/hyperledger/fabric/core/comm/throttle.go:54
github.com/hyperledger/fabric/core/comm.(*Throttle).UnaryServerIntercptor-fm
/opt/gopath/src/github.com/hyperledger/fabric/peer/node/start.go:224
github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1.1
/opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware/chain.go:34
github.com/hyperledger/fabric/common/grpclogging.UnaryServerInterceptor.func1
/opt/gopath/src/github.com/hyperledger/fabric/common/grpclogging/server.go:91
github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1.1
/opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware/chain.go:34
github.com/hyperledger/fabric/common/grpcmetrics.UnaryServerInterceptor.func1
/opt/gopath/src/github.com/hyperledger/fabric/common/grpcmetrics/interceptor.go:30
github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1
/opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware/chain.go:39
github.com/hyperledger/fabric/protos/peer._Endorser_ProcessProposal_Handler
/opt/gopath/src/github.com/hyperledger/fabric/protos/peer/peer.pb.go:171
github.com/hyperledger/fabric/vendor/google.golang.org/grpc.(*Server).processUnaryRPC
/opt/gopath/src/github.com/hyperledger/fabric/vendor/google.golang.org/grpc/server.go:982
github.com/hyperledger/fabric/vendor/google.golang.org/grpc.(*Server).handleStream
/opt/gopath/src/github.com/hyperledger/fabric/vendor/google.golang.org/grpc/server.go:1208
github.com/hyperledger/fabric/vendor/google.golang.org/grpc.(*Server).serveStreams.func1.1
/opt/gopath/src/github.com/hyperledger/fabric/vendor/google.golang.org/grpc/server.go:686
runtime.goexit
/opt/go/src/runtime/asm_amd64.s:1333
error sending
failed to execute transaction a0a2570dd9a4ce0c696ab08263320927382c6f3db046843dca70a96b63a97da9
github.com/hyperledger/fabric/core/chaincode.processChaincodeExecutionResult
/opt/gopath/src/github.com/hyperledger/fabric/core/chaincode/chaincode_support.go:245
github.com/hyperledger/fabric/core/chaincode.(*ChaincodeSupport).Execute
/opt/gopath/src/github.com/hyperledger/fabric/core/chaincode/chaincode_support.go:240
github.com/hyperledger/fabric/core/endorser.(*SupportImpl).Execute
/opt/gopath/src/github.com/hyperledger/fabric/core/endorser/support.go:147
github.com/hyperledger/fabric/core/endorser.(*Endorser).callChaincode
/opt/gopath/src/github.com/hyperledger/fabric/core/endorser/endorser.go:146
github.com/hyperledger/fabric/core/endorser.(*Endorser).SimulateProposal
/opt/gopath/src/github.com/hyperledger/fabric/core/endorser/endorser.go:247
github.com/hyperledger/fabric/core/endorser.(*Endorser).ProcessProposal
/opt/gopath/src/github.com/hyperledger/fabric/core/endorser/endorser.go:500
github.com/hyperledger/fabric/core/handlers/auth/filter.(*expirationCheckFilter).ProcessProposal
/opt/gopath/src/github.com/hyperledger/fabric/core/handlers/auth/filter/expiration.go:61
github.com/hyperledger/fabric/core/handlers/auth/filter.(*filter).ProcessProposal
/opt/gopath/src/github.com/hyperledger/fabric/core/handlers/auth/filter/filter.go:32
github.com/hyperledger/fabric/protos/peer._Endorser_ProcessProposal_Handler.func1
/opt/gopath/src/github.com/hyperledger/fabric/protos/peer/peer.pb.go:169
github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1.1
/opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware/chain.go:31
github.com/hyperledger/fabric/core/comm.(*Throttle).UnaryServerIntercptor
/opt/gopath/src/github.com/hyperledger/fabric/core/comm/throttle.go:54
github.com/hyperledger/fabric/core/comm.(*Throttle).UnaryServerIntercptor-fm
/opt/gopath/src/github.com/hyperledger/fabric/peer/node/start.go:224
github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1.1
/opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware/chain.go:34
github.com/hyperledger/fabric/common/grpclogging.UnaryServerInterceptor.func1
/opt/gopath/src/github.com/hyperledger/fabric/common/grpclogging/server.go:91
github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1.1
/opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware/chain.go:34
github.com/hyperledger/fabric/common/grpcmetrics.UnaryServerInterceptor.func1
/opt/gopath/src/github.com/hyperledger/fabric/common/grpcmetrics/interceptor.go:30
github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware.ChainUnaryServer.func1
/opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/grpc-ecosystem/go-grpc-middleware/chain.go:39
github.com/hyperledger/fabric/protos/peer._Endorser_ProcessProposal_Handler
/opt/gopath/src/github.com/hyperledger/fabric/protos/peer/peer.pb.go:171
github.com/hyperledger/fabric/vendor/google.golang.org/grpc.(*Server).processUnaryRPC
/opt/gopath/src/github.com/hyperledger/fabric/vendor/google.golang.org/grpc/server.go:982
github.com/hyperledger/fabric/vendor/google.golang.org/grpc.(*Server).handleStream
/opt/gopath/src/github.com/hyperledger/fabric/vendor/google.golang.org/grpc/server.go:1208
github.com/hyperledger/fabric/vendor/google.golang.org/grpc.(*Server).serveStreams.func1.1
/opt/gopath/src/github.com/hyperledger/fabric/vendor/google.golang.org/grpc/server.go:686
runtime.goexit
/opt/go/src/runtime/asm_amd64.s:1333
2019-07-09 09:22:03.273 UTC [endorser] SimulateProposal -> DEBU 15486 [mychannel][a0a2570d] Exit
2019-07-09 09:22:03.273 UTC [lockbasedtxmgr] Done -> DEBU 15487 Done with transaction simulation / query execution [a0a2570dd9a4ce0c696ab08263320927382c6f3db046843dca70a96b63a97da9]
2019-07-09 09:22:03.273 UTC [endorser] func1 -> DEBU 15488 Exit: request from 172.18.0.1:51702
2019-07-09 09:22:03.273 UTC [chaincode] HandleTransaction -> DEBU 15489 [a0a2570d] handling PUT_STATE from chaincode
2019-07-09 09:22:03.273 UTC [comm.grpc.server] 1 -> INFO 1548a unary call completed grpc.service=protos.Endorser grpc.method=ProcessProposal grpc.peer_address=172.18.0.1:51702 grpc.code=OK grpc.call_duration=4.573006ms
2019-07-09 09:22:03.274 UTC [chaincode] HandleTransaction -> DEBU 1548b [a0a2570d] Completed PUT_STATE. Sending RESPONSE
2019-07-09 09:22:03.274 UTC [chaincode] handleMessage -> DEBU 1548c [a0a2570d] Fabric side handling ChaincodeMessage of type: PUT_STATE in state ready
2019-07-09 09:22:03.274 UTC [chaincode] HandleTransaction -> DEBU 1548d [a0a2570d] handling PUT_STATE from chaincode
2019-07-09 09:22:03.274 UTC [chaincode] HandleTransaction -> DEBU 1548e [a0a2570d] Completed PUT_STATE. Sending RESPONSE
2019-07-09 09:22:03.275 UTC [chaincode] handleMessage -> DEBU 1548f [a0a2570d] Fabric side handling ChaincodeMessage of type: COMPLETED in state ready
2019-07-09 09:22:03.275 UTC [chaincode] Notify -> DEBU 15490 [a0a2570d] notifying Txid:a0a2570dd9a4ce0c696ab08263320927382c6f3db046843dca70a96b63a97da9, channelID:mychannel
2019-07-09 09:22:03.275 UTC [chaincode] Execute -> DEBU 15491 Exit
2019-07-09 09:22:03.275 UTC [endorser] callChaincode -> INFO 15492 [mychannel][a0a2570d] Exit chaincode: name:"fabcar" (3ms)
2019-07-09 09:22:03.275 UTC [lockbasedtxmgr] GetTxSimulationResults -> DEBU 15493 Simulation completed, getting simulation results
2019-07-09 09:22:03.275 UTC [lockbasedtxmgr] Done -> DEBU 15494 Done with transaction simulation / query execution [a0a2570dd9a4ce0c696ab08263320927382c6f3db046843dca70a96b63a97da9]
2019-07-09 09:22:03.275 UTC [endorser] SimulateProposal -> DEBU 15495 [mychannel][a0a2570d] Exit
2019-07-09 09:22:03.275 UTC [endorser] endorseProposal -> DEBU 15496 [mychannel][a0a2570d] Entry chaincode: name:"fabcar"
2019-07-09 09:22:03.275 UTC [endorser] endorseProposal -> DEBU 15497 [mychannel][a0a2570d] escc for chaincode name:"fabcar" is escc
2019-07-09 09:22:03.275 UTC [endorser] EndorseWithPlugin -> DEBU 15498 Entering endorsement for {plugin: escc, channel: mychannel, tx: a0a2570dd9a4ce0c696ab08263320927382c6f3db046843dca70a96b63a97da9, chaincode: fabcar}
2019-07-09 09:22:03.275 UTC [msp.identity] Sign -> DEBU 15499 Sign: plaintext: 0A20828C242C3048295EE0453AD5EA85...455254494649434154452D2D2D2D2D0A
2019-07-09 09:22:03.275 UTC [msp.identity] Sign -> DEBU 1549a Sign: digest: F3BEDFED5C78408FD01F0A41C0714245508FD2F5AEF8A34F33E7F3C61DEFF987
2019-07-09 09:22:03.275 UTC [endorser] EndorseWithPlugin -> DEBU 1549b Exiting {plugin: escc, channel: mychannel, tx: a0a2570dd9a4ce0c696ab08263320927382c6f3db046843dca70a96b63a97da9, chaincode: fabcar}
2019-07-09 09:22:03.276 UTC [endorser] endorseProposal -> DEBU 1549c [mychannel][a0a2570d] Exit
2019-07-09 09:22:03.276 UTC [lockbasedtxmgr] Done -> DEBU 1549d Done with transaction simulation / query execution [a0a2570dd9a4ce0c696ab08263320927382c6f3db046843dca70a96b63a97da9]
2019-07-09 09:22:03.276 UTC [endorser] func1 -> DEBU 1549e Exit: request from 172.18.0.1:51702
2019-07-09 09:22:03.276 UTC [comm.grpc.server] 1 -> INFO 1549f unary call completed grpc.service=protos.Endorser grpc.method=ProcessProposal grpc.peer_address=172.18.0.1:51702 grpc.code=OK grpc.call_duration=6.750666ms
I tried some solutions found on SO such as:
*
*having anchor peers set for each org: was already done
*setting CORE_PEER_LISTENADDRESS=org1.example.com:7051 -> failed the peer containers. If I set the address to 0.0.0.0:7051 the containers starts again but the error stays the same
*restarting Docker / removing volumes / redownloading images: didn't change a thing
Further points:
The orderer doesn't seem to be notified, as we can see in its logs.
When I use node invoke.js I sometimes get this error, which disappears when I launch the command again. Peer logs don't show an error.
node invoke.js inconsistent error
2019-07-09T14:13:21.232Z - error: [AbstractStrategy]: constructor: No event hubs for strategy
Failed to submit transaction: Error: No event hubs for strategy
When I query using node, I'll sometimes get the following error:
node query.js inconsistent error
2019-07-09T13:23:13.602Z - error: [SingleQueryHandler]: evaluate: message=No peers available to query. Errors: [], stack=FabricError: No peers available to query. Errors: []
at SingleQueryHandler.evaluate (/home/path_to_dir/app/javascript/node_modules/fabric-network/lib/impl/query/singlequeryhandler.js:39:17)
at Transaction.evaluate (/home/path_to_dir/app/javascript/node_modules/fabric-network/lib/transaction.js:246:29)
at Contract.evaluateTransaction (/home/path_to_dir/app/javascript/node_modules/fabric-network/lib/contract.js:172:39)
at main (/home/path_to_dir/app/javascript/query.js:47:39)
at <anonymous>, name=FabricError
Failed to evaluate transaction: FabricError: No peers available to query. Errors: []
This error usually disappears when I start a query again but will pop off from time to time. When the query comes from the CLIorg1 it never happens.
Some probably useful files:
configtx.yaml
crypto-config.yaml
docker-compose-org1.yaml
docker-compose-org2.yaml
EDIT: added insert.js file and logs after trying to node insert.js (see comments)
Configuration information
HLF 1.4.1 ; Docker 18.09.7 ; docker-compose 1.23.2 ; node v8.16.0 ; npm 6.4.1 ; Ubuntu 18.04.2 LTS
Apologies for the multitude of errors which makes the question broad, but I assume they are somehow all connected to an endorsement issue. If not, do not hesitate to edit / ping me to narrow it down.
| |
doc_23532929
|
Kindly help on it
can we use MONTHD#2 | ....| MONTHD#15 to achieve it ?
| |
doc_23532930
|
*
*The report contains a group.
*The group header must print at the beginning of the group and also on a new page.
This is not a problem since I just have to tell it to "Reprint Header On Each Page". So far so good.
*The detail section is not allowed to split across a page.
*The group header must not print at the bottom of a page unless at least one detail section will fit. (Could be rephrased as: The group header must only print when at least one detail section will fit)
At this point I noticed that there is a property for the group called "Min Height To Start New Page". This would be useful for a detail
section of constant height, however...
*The detail section is dynamic height.
I have tried using "Keep together" on the group, but that can leave too much blank space on pages if the first group is small, but the second is large. It was rejected as a solution.
With these requirements in mind. All I am trying to do is not print the group header when the page cannot fit any detail entries.
I suspect that when it is filling in the report that it probably doesn't know the height of the detail section until it has filled it in, and by then it is too late. I'm hoping I am wrong.
I have tried recreating this report in two ways:
*
*One report with a group and detail sections.
*A main report with a subreport for the group, and within the subreport another subreport for the detail.
Both ways have led me to the same results.
Visually, if this was my data:
Province - Ontario
City - Ottawa
City - Toronto
Province - Nova Scotia
City - Halifax
City - New Glasgow
Province - Quebec
City - Montreal
City - Quebec City
I might get this result:
**Page 1**
Province - Ontario
City - Ottawa
City - Toronto
Province - Nova Scotia
City - Halifax
City - New Glasgow
Province - Quebec **<- This hanging header is unwanted**
**Page 2**
Province - Quebec
City - Montreal
City - Quebec City
I have tried many permutations of settings, placing the subreports in different bands, but I haven't found something that works. I am hoping someone knows of a combination of settings, placing subreports in different bands, etc. that will work.
Any idea how I might accomplish this?
A: You can't really prevent that becuase your detail band can be more than one page. However, you have a couple of options that you can try.
*
*Go to Group properties and set the "min height to start new page" to something like 200 or a value that meets your needs.
*Secondly, you can check the "print group header on each page" so that if your details section goes over a page then the header is repeated.
Hope this helps!
A: To answer #4, preventing having a group header at the end of the page with no detail, this solution may work. You say in #5 that the detail section is dynamic in height. If you are referring to the height of the detail band, than I do not have a good solution. If you are referring to the number of detail entries in the detail section for a group, then the following solution should work.
Similar to what Fatih stated, set the "min height to start new page" setting to the number of pixels in height of your group header band, plus the number of pixels in height of the detail band. This will force the group header to print only on the next page if there isn't space for the group header and a single detail band.
I hope this helps.
A: I had a similar situation with a report containing lots of subreports. Each subreport consist of a group header and detail band.
the problem I had sometimes the group header with appear in one page, then rest of the space will be a gap and the details of the subreport will appear in the next page. My subreport details was dynamic sizing in height.
The way I solved it is as follows:
Main report, I used to have splitType="Stretch" and I changed it to splitType="Prevent"
<detail>
<band height="20" splitType="Prevent">
<!-- this part contains all my subreports -->
</band>
</detail>
For my subreports, I used to have minHeightToStartNewPage="200" which I removed (also using the keepTogether="true" did not work for me)
<group name="titleGroup">
<groupHeader>
<band height="20" splitType="Stretch">
For detail band in my subreport, the splitType remained as "Stretch"
| |
doc_23532931
|
Possible Duplicate:
OutOfMemoryError: bitmap size exceeds VM budget :- Android
In my application I load some little Bitmap(between 2k and 300k) that I affect to ImageViews, during the first launch of my App it works fine but when I quit it and relaunch it, I always have the OutOfMemoryError during a Bitmap creation.
Could somebody tell me why?
A: You should use bitmap.recycle() manually when you leave your activity.
Please refer to http://developer.android.com/reference/android/graphics/Bitmap.html#recycle()
A: The problem is because your bitmap's size is too large than the VM can handle. For example from your code I can see that you are trying to paste an Image into imageView which you are capturing using Camera. So normally the camera images will be too large in size which will rise this error obviously. So as others have suggested, you have to compress your image either by sampling it or convert your image into smaller resolution. For example if your imageView is 100x100 in width and height, you can create a scaled bitmap so that your imageView gets filled exactly. You can do this for that,
Bitmap newImage = Bitmap.createScaledBitmap(bm, 350, 300,true);
And you have to recycle your bitmap and null your bitmap like this,
Bitmap bmap.recycle();
Bitmap bmap=null;
A: I really doubt you have to use bitmap.recycle() if you null your references, allowing GC (but please prove me wrong).
I'd say it's more likely your bitmaps are too large, possibly aggravated by long lived Context references or somesuch.
| |
doc_23532932
|
expected output = "Hello. My name is $xyz$. I am from $abc$.
# code
string = 'Hi. My name is #something1#. I am from #something2#. My company is #something3#.'
toReplace = {'something1':'xyz', 'something2': 'abc', 'something3': 'ttl'}
modified = list(string)
arr=[]
for i in range(len(string)):
if string[i]=='#':
arr.append(i)
#print(arr)
indices = []
for i in range(len(arr)):
if i%2 != 0:
continue
else:
indices.append(arr[i]+1)
#print(indices)
sources = []
l = 0
while l<len(arr):
sources.append(string[arr[l]+1:arr[l+1]])
#print(l, sources)
l+=2
#print(sources)
targets = toReplace.values()
#print(targets)
for index, source, target in zip(indices, sources, targets):
#print(index, source, target)
if not string[index:].startswith(source):
continue
else:
modified[index] = target
#print(modified)
for i in range(index+1,len(source)+index):
modified[i] = ''
print("".join(modified))
should get this without using replace() or re.replace() functions. it should not remove placeholders. only word inside dictionary to be replace but to be done without replace functions. Any ideas??
A: you're there. I'd suggest if instead of listing all characters in the sentence you can split() it with # delimiter, the solution becomes a lot simpler.
'$'.join([toReplace[k] if k in toReplace.keys() else k for k in string.split('#')])
# 'Hi. My name is $xyz$. I am from $abc$. My company is $ttl$.'
*
*string.split('#') will generate a list of strings, broken at every '#'
*The list comprehension will search for the list's strings in the dict's keys, and if found, it will pull the item from the dictionary
*The resulting list after the comprehension can then be joined using the '#' delimiter as it was split. You could also update the join string to be '$'.
A: Good day to you! I'm glad if the following code will help you in anyway. I have used regular expression to get the required output. Here you go,
import re
string = "Hello. My name is $something1$. I am from $something2$."
dict = {'something1':'xyz', 'something2':'abc'}
for k,v in zip(dict.keys(),dict.values()):
string=re.sub(k,v,string)
print(string)
And Output is :
Hello. My name is $xyz$. I am from $abc$.
I'm really glad for this opportunity to help you! Thank you!
| |
doc_23532933
|
So, My question is Can I use get method directly? means do i need to encode url or any other thing ??
I have checked it in modern browsers. It works just fine..
Thanks
Edit:
Urlencode is used when puting variables in url.
I am submitting my search form with method='get' Then I get variable and perform search query and make new page links with variable data.
- Length,Size is not a prob.
U people suggesting I should use urlencode func. while making new links only ???
A: You can and should use urlencode() on data that possibly contains spaces and other URL-unfriendly characters.
http://php.net/manual/en/function.urlencode.php
A: You need to URL Encode the parameters on the URL eg http://www.example.com/MyScript.php?MyVariable=%3FSome%20thing%3F.
Be aware that there's a limit to how much data can be sent via GET - more restrictive on older browsers. If I remember correctly, IE6 has a limit of 1024 characters in the URL so if you think you're going to go over that, consider using POST or you may exclude some users.
A: You should use urlencode($variable) (Link) before sending the variable (even though the browser usually takes care of this) and urldecode ($variable) (Link) after receiving it, this way you can be sure special chars will be treated correctly.
| |
doc_23532934
|
I'm wondering if I can setup the listbox once and use it on both pages, or if I need to setup a separate listbox on each page and manage both as the list box in one page changes?
A: You cannot pack/grid/place the listbox inside two different frames simultaneously.
However, you can re-pack/grid/place the listbox each time the notebook tab changes. To do so, I used the <<NotebookTabChanged>> event which is triggered each time the notebook tab changes:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
notebook = ttk.Notebook(root)
notebook.pack()
frame1 = tk.Frame(notebook, bg='red', width=400, height=400)
frame1.pack_propagate(False)
frame2 = tk.Frame(notebook, bg='blue', width=400, height=400)
frame2.pack_propagate(False)
notebook.add(frame1, text='frame 1')
notebook.add(frame2, text='frame 2')
var = tk.StringVar(root, 'a b c d e f g')
listbox = tk.Listbox(notebook, listvariable=var)
def display_listbox(event):
tab = notebook.tabs()[notebook.index('current')]
listbox.pack(in_=tab)
notebook.bind('<<NotebookTabChanged>>', display_listbox)
root.mainloop()
Explanations about display_listbox:
*
*notebook.tabs() returns (frame1, frame2) (i.e the tuple of the tabs)
*notebook.index('current') returns the index of the currently visible tab
*the in_ option can be used to specify the widget in which we want to pack the listbox (it also works with grid and place)
A: Sharing the same listvariable between the two list boxes is sufficient to keep them synchronized.
import tkinter as tk
from tkinter import ttk
rootWin = tk.Tk()
rootWin.title('Talk Like A Pirate')
listvar = tk.StringVar()
#create a notebook
pirateBook = ttk.Notebook(rootWin)
#create a tab
tab1 = tk.Frame(pirateBook)
#create a listbox in the tab
listbx1 = tk.Listbox(tab1,
listvariable=listvar,
height=21,
width=56,
selectmode='single'
)
listbx1.pack()
#create another tab
tab2 = tk.Frame(pirateBook)
#create a listbox in the second tab
listbx2 = tk.Listbox(tab2,
listvariable=listvar,
height=21,
width=56,
selectmode='single'
)
listbx2.pack()
#add the tabs to the notebook
pirateBook.add(tab1, text="Tab 1")
pirateBook.add(tab2, text="Tab 2")
#pack the notebook
pirateBook.pack()
#you can access the listbox through the listvariable, but that takes
# a list as the argument so you'll need to build a list first:
ls=list() #or you could just ls = []
#build a list for the list box
ls.append("Arr, matey!")
ls.append("Dead men tell no tales!")
ls.append("Heave ho, me hearties!")
ls.append("I'll cleave ye t'yer brisket a'fore sendin' ye to Davey Jones Locker!")
#then just set the list variable with the list
listvar.set(ls)
#or you can manipulate the data using Listbox()'s data manipulation
# methods, such as .insert()
listbx1.insert(1, "Shiver me timbers!")
listbx2.insert(3, "Yo ho ho!")
listbx1.insert(5, "Ye scurvy dog!")
listbx2.insert('end', "Ye'll be walking the plank, Sharkbait!")
#you'll see this if you run this program from the command line
print(listbx1.get(5))
rootWin.mainloop()
You would do this a little bit differently if you had your tabs in their own classes, making the common variable global, for instance, but the same idea still applies: sharing a common listvariable.
| |
doc_23532935
|
values of its items changes and I don't know how can I fix it.
my adapter code:
public class HeterogenousRecyclerviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private ArrayList<DataObject> mDataset;
Context context;
RecyclerView.ViewHolder viewHolder;
public HeterogenousRecyclerviewAdapter(ArrayList<DataObject> myDataset) {
this.mDataset = myDataset;
}
@Override
public int getItemCount() {
return mDataset.size();
}
@Override
public int getItemViewType(int position) {
int view_type=mDataset.get(position).getView_type();
return view_type;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context=parent.getContext();
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType){
case 0:
View v1 = inflater.inflate(R.layout.layout_viewholder1, parent, false);
viewHolder = new ViewHolder1(v1);
break;
case 1:
View v2 = inflater.inflate(R.layout.layout_viewholder2, parent, false);
viewHolder = new ViewHolder2(v2);
break;
}
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (viewHolder.getItemViewType()){
case 0:
ViewHolder1 vh1 = (ViewHolder1) viewHolder;
configureViewHolder1(vh1, position);
break;
case 1:
ViewHolder2 vh2 = (ViewHolder2) viewHolder;
configureViewHolder2(vh2, position);
break;
}
}
private void configureViewHolder1(ViewHolder1 vh1, int position) {
if (mDataset != null) {
vh1.getLabel1().setText(mDataset.get(position).getName());
//vh1.getLabel2().setText("Hometown: " + user.hometown);
}
}
private void configureViewHolder2(ViewHolder2 vh2, int position) {
//vh2.getImageView().setImageResource(R.mipmap.img1);
try {
Resources res = context.getResources();
int resourceId = res.getIdentifier(mDataset.get(position).getImg(), "mipmap",
context.getPackageName());
vh2.getImageView().setImageResource(resourceId);
} catch (Exception e) {
// TODO: handle exception
}
}
}
this is my ViewHolder1 class:
public class ViewHolder1 extends RecyclerView.ViewHolder {
private TextView label1;
public ViewHolder1(View v) {
super(v);
label1 = (TextView) v.findViewById(R.id.text1);
//label2 = (TextView) v.findViewById(R.id.text2);
}
public TextView getLabel1() {
return label1;
}
public void setLabel1(TextView label1) {
this.label1 = label1;
}
}
this is ViewHolder1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textStyle="bold" />
</LinearLayout>
this is ViewHolder2 class:
public class ViewHolder2 extends RecyclerView.ViewHolder {
private ImageView ivExample;
public ViewHolder2(View v) {
super(v);
ivExample = (ImageView) v.findViewById(R.id.ivExample);
}
public ImageView getImageView() {
return ivExample;
}
public void setImageView(ImageView ivExample) {
this.ivExample = ivExample;
}
}
this is ViewHolder2.xml:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ivExample"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:layout_width="200dp"
android:layout_height="200dp"/>
this is my main activity code:
ArrayList<DataObject> personList = new ArrayList<DataObject>();
DataObjectDBAdapter dataObjectDBAdapter = new DataObjectDBAdapter(getApplicationContext());
personList = dataObjectDBAdapter.getALL();
adapter = new HeterogenousRecyclerviewAdapter(personList);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(adapter);
can sb help me?
A: I hadn't saved names of images in the SQLite database so the first problem was because of that, and the second problem was in my adapter code. I had to write "viewHolder" instead of "holder" in onBindViewHolder(), so the correct method is:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
switch (viewHolder.getItemViewType()){
case 0:
ViewHolder1 vh1 = (ViewHolder1) viewHolder;
configureViewHolder1(vh1, position);
break;
case 1:
ViewHolder2 vh2 = (ViewHolder2) viewHolder;
configureViewHolder2(vh2, position);
break;
}
}
A:
First make sure the given statement must only return 0 or 1. because view type must start with 0
int view_type=mDataset.get(position).getView_type();
No need to create the below viewHolder as a member of class
RecyclerView.ViewHolder viewHolder;
Don't check viewType in onBindViewHolder . Instead check holder instanceOf
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceOf ViewHolder1){
(ViewHolder1) holder.getLabel1().setText(mDataset.get(position).getName());
}
else
{
try {
Resources res = context.getResources();
int resourceId = res.getIdentifier(mDataset.get(position).getImg(), "mipmap",
context.getPackageName());
(ViewHolder2) holder.getImageView().setImageResource(resourceId);
} catch (Exception e) {}
}
}
A:
i had the same problem values changes after the scroll, then i overide these methods
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemCount() {
return dataList.size();
},
This solved my problem and for the Image heck the image resourceId is null or not
i am not sure if your way is good to set the Resource.
A: While using multiple view types with dynamic data some users may face issues like duplicate data items, data being swapped between questions. To avoid that you have to set a unique view type id for every item.
@Override
public int getItemViewType(int position) {
// Here you can get decide from your model's ArrayList, which type of view you need to load. Like
if (list.get(position).type == Something) { // Put your condition, according to your requirements
return VIEW_TYPE_ONE;
}
return VIEW_TYPE_TWO;
}
The above code for getItemViewType can fail where 3 consecutive items will have the same type. For example, if the user enters ans1 in item 1
edit text,ans2 in item 2 edit text, ans3 in item 3 edit text and scroll the recycler view up and down then some users may face issues like duplicate data items, data being swapped between questions.
Formula to create unique view type id :
Formula : pos * Constants.Max + viewType;
set value Constants.Max = 100000;
class DataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_TYPE_EDIT_TEXT = 1;
private final int VIEW_TYPE_IMAGE_VIEW = 2;
private final ArrayList<DataModel> dataModelArrayList = new ArrayList<>();
@Override
public int getItemViewType(int position) {
String dataType = dataModelArrayList.get(position).getDataType();
int viewType = VIEW_TYPE_EDIT_TEXT;
switch (dataType) {
case "A":
case "E":
viewType = VIEW_TYPE_EDIT_TEXT;
break;
case "I":
viewType = VIEW_TYPE_IMAGE_VIEW;
break;
}
int pos = position + 1;
return pos * Constants.Max + viewType;
}
@Override
public long getItemId(int position) {
return position;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int type) {
int count = (int) Math.ceil(type / Constants.Max);
int viewType = type - count * Constants.Max;
if (viewType == VIEW_TYPE_EDIT_TEXT) {
return new ViewHolderTypeEditText(LayoutInflater.from(context).inflate(R.layout.adapter_status_prompts_et_item, parent, false));
} else if (viewType == VIEW_TYPE_IMAGE_VIEW) {
return new ViewHolderTypeImageView(LayoutInflater.from(context).inflate(R.layout.adapter_status_prompts_sp_item, parent, false));
}
return new ViewHolderTypeEditText(LayoutInflater.from(context).inflate(R.layout.adapter_status_prompts_et_item, parent, false));
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int pos) {
int type = holder.getItemViewType();
int count = (int) Math.ceil(type / Constants.Max);
int viewType = type - count * Constants.Max;
if (viewType == VIEW_TYPE_EDIT_TEXT) {
DataAdapter.ViewHolderTypeEditText viewHolderTypeEditText = (DataAdapter.ViewHolderTypeEditText) holder;
} else if (viewType == VIEW_TYPE_IMAGE_VIEW) {
DataAdapter.ViewHolderTypeImageView viewHolderTypeImageView = (DataAdapter.ViewHolderTypeImageView) holder;
}
}
@Override
public int getItemCount() {
return dataModelArrayList.size();
}
public class ViewHolderTypeEditText extends RecyclerView.ViewHolder {
EditText etText;
public ViewHolderTypeEditText(@NonNull View itemView) {
super(itemView);
etText = itemView.findViewById(R.id.et_text);
}
}
public class ViewHolderTypeImageView extends RecyclerView.ViewHolder {
ImageView imageView;
public ViewHolderTypeImageView(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_view);
}
}
}
| |
doc_23532936
|
E.g. the first time I load my app it works, and after making a code change the live reload displays a blank page, then it works, then a blank page and so on.
How do I find the cause of this? I've compared its routing setup to that of a project which works (a blank project) and they seem to work the same.
When it fails to live reload and shows a blank page, no errors are displaying in the Chrome DevTools console, or in my terminal.
This occurs when serving the app using any of the commands:
ionic serve
ionic cordova run android -l
ionic serve --devapp
My app.component.ts:
import { Component } from '@angular/core';
import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
public appPages = [
{
title: 'Home',
url: '/home',
icon: 'home'
},
{
title: 'List',
url: '/list',
icon: 'list'
}
];
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar
) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
}
A: Try to hit ctrl+f5 to bust cache
I have same issue specially when I switch v3 to v4 or vise-versa
A: it is your cashing issue and what data are you loading in your
app.component.ts
its due to loading heavy task in your component.ts
A: This was a routing issue. My empty path redirected to my dashboard, which had an AuthGuard associated with it. The AuthGuard would reject my navigation, leaving me with a blank page.
As for why every even reload, I think my logic for logging in was flipping some boolean isAuthenticated flag each time my auto sign-in code ran.
| |
doc_23532937
|
here a minimal example:
import numba as nb
import numpy as np
@nb.njit()
def test(N,P,B,D):
for i in range(N):
a = D[i,:]
b = B[i,a]
P[:,i] =b
P = np.zeros((5,5))
B = np.random.random((5,5))*100
D = (np.random.random((5,5))*5).astype(np.int32)
print(D)
N = 5
print(P)
test(N,P,B,D)
print(P)
I get an error of numba at the line b = B[i,a]
File "dj.py", line 10:
def test(N,P,B,D):
<source elided>
a = D[i,:]
b = B[i,a]
^
This is not usually a problem with Numba itself but instead often caused by
the use of unsupported features or an issue in resolving types.
I don't understand what AM I doing wrong here.
The code works without the @nb.njit() decorator
A: numba doesn't support all the same "fancy-indexing" that numpy does - in this case the issue is selecting array elements with the a array.
For your particular case, because you know the shape of b in advance, you could workaround like this:
import numba as nb
import numpy as np
@nb.njit
def test(N,P,B,D):
b = np.empty(D.shape[1], dtype=B.dtype)
for i in range(N):
a = D[i,:]
for j in range(a.shape[0]):
b[j] = B[i, j]
P[:, i] = b
A: Another solution is to apply swapaxes on B before calling test and to invert indices (B[i,a] -> B[a,i]). I don't know why this is working, but here is the implementation:
import numba as nb
import numpy as np
@nb.njit()
def test(N,P,B,D):
for i in range(N):
a = D[i,:]
b = B[a,i]
P[:, i] = b
P = np.zeros((5,5))
B = np.arange(25).reshape((5,5))
D = (np.random.random((5,5))*5).astype(np.int32)
N = 5
test(N,P,np.swapaxes(B, 0, 1), D)
By the way, in the answer given by @chrisb, it is not: b[j] = B[i, j] but b[j] = B[i, a[j]].
| |
doc_23532938
|
(print "test")
And when I pressed Shift+Ctrl+B I got this:
[Error 2]
[cmd: [u'lein', u'compile', u':all']]
[dir: D:\Document\ACM-ICPC\Code\PKU]
[path: C:\Windows\system32;C:\Windows;...]
[Finished]
so,how to run it?
A: I use SublimeREPL when developing Clojure on SublimeText. It works, it supports other languages (CoffeScript, F#, Haskell ..), highly configurable and you will get a colored REPL!
I recommend to give it a try.
A: Seems like command lein compile :all is not what you need to run single script.
You can install lein exec plugin by adding line {:user {:plugins [[lein-exec "0.3.1"]]}} to your %USERPROFILE%\.lein\profiles.clj file.
And then add new Sublime build system or change existing with something like ['cmd': [u'lein', u'exec', '$file']]
| |
doc_23532939
|
Why is Devise redirecting instead of adding the user to the database? On the local machine everything is fine:
App 18981 stdout: Started POST "/en/sign_up" for ... at 2015-07-28 05:08:34 -0400
App 18981 stdout: Processing by Devise::RegistrationsController#create as HTML
App 18981 stdout: Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ti/CgGvzauy/neVnvPtc+aBEc5NGKRD0SVPqYLL6+J8=", "user"=>{"email"=>"test678777@gmail.com", "show_password"=>"[FILTERED]", "password"=>"[FILTERED]", "newsletter"=>"0"}, "commit"=>"Sign me up", "locale"=>"en"}
App 18981 stdout: Redirected to ...homepage...
App 18981 stdout: Completed 302 Found in 139ms (ActiveRecord: 14.3ms)
App 18981 stdout: Started GET "/en" for ... at 2015-07-28 05:08:34 -0400
Create action in the production env. in a console works fine.
2.2.2 :056 > User.create(email: "1231222232212312@mail.ru", password: "password")
(0.3ms) BEGIN
User Exists (0.5ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = '1231222232212312@mail.ru' LIMIT 1
SQL (4.5ms) INSERT INTO "users" ("created_at", "email", "encrypted_password", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", "2015-07-29 03:09:25.623040"], ["email", "1231222232212312@mail.ru"], ["encrypted_password", "$2a$10$h60hw3at5glyZMtFRt6UiuPEhaUOWa8dNzqU.8fK91XTKNavHWZA2"], ["updated_at", "2015-07-29 03:09:25.623040"]]
SQL (0.6ms) INSERT INTO "user_notifications" ("created_at", "from_email", "from_name", "locale", "template_name", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["created_at", "2015-07-29 03:09:25.630950"], ["from_email", "test@gmail.com"], ["from_name", "Fundinar"], ["locale", "en"], ["template_name", "new_user_registration"], ["updated_at", "2015-07-29 03:09:25.630950"], ["user_id", 9]]
(0.6ms) COMMIT
A: Need to replace all values with catarse.me in settings table. It helped.
| |
doc_23532940
|
A: First set up your centered div with position relative
#centered-div{position: relative; width: 900px; margin: auto;}
Then set up your login button with position absolute
#login{position: absolute; left: 0; top: 50px;}
A: A simple answer would be to wrap both inside of an invisible container div with a width of 900px, and then to center that div with auto-margins.
so it would be
<div class="container">
<input type="submit" value="login">
<div class="innerDiv">
</div>
</div>
With the style
div.container{
width:900px;
margin:0 auto;
}
A: $.fn.makeAbsolute = function (rebase) {
return this.each(function () {
var el = $(this);
var pos = el.position();
el.css({
position: "absolute"
, marginLeft: 0
, marginTop: 0
, top: pos.top
, left: pos.left
, zIndex: 1
});
if (rebase)
el.remove().appendTo("body");
});
}
You can use jQuery("#myDiv").makeAbsolute();
Is this what you are looking for ?
| |
doc_23532941
|
void *tmp;
if( (tmp = realloc(myobject, sizeof(object) * newsize) != NULL)
myobject = tmp
I thought I'd make my code shorter by doing something like this (silly idea):
void GetSpace(void *ptr, size_t size_of_object, int newsize){
void *tmp = NULL;
if ((tmp = realloc(ptr, size_of_object * newsize) == NULL)
//print error msg and exit
else
ptr = tmp;
}
int main(){
//This is an example
double *mydata1 = (double *)malloc (sizeof double * 5);
//later request more space for mydata1
GetSpace( mydata1, sizeof(double), 50);
}
This is silly since it doesn't save that many lines or make the code more readable but I'd like to know why it doesn't work the way I expect. When I use the GetSpace() for a single object only it works fine. If I run the code without initializing any of the objects I call the function with, it runs fine but when I call GetSpace() for an object, then put data in it and then call GetSpace() for another object, I get a stack trace with a message like this
*** glibc detected *** ./a.out: realloc(): invalid old size: 0x00007fff05d96790 ***
0x00007fff05d96790 is the address of the second array/object before resizing. Why does this happen?
A: In your GetSpace function, you are allocating a new block of memory with the bigger size, and assigning the address to the local variable ptr. But when the function exits, this new address is lost. Your main program still has the old value of ptr, which is now pointing to invalid (freed) memory.
You need to return the new address to the caller. Try this instead. Note that the parameter ptr is now passed by reference, so the caller's variable is updated.
void GetSpace(void **ptr, size_t size_of_object, int newsize){
void *tmp = NULL;
if ((tmp = realloc(*ptr, size_of_object * newsize) == NULL)
//print error msg and exit
else
*ptr = tmp;
}
EDIT: as pointed out in the comments, this still isn't ideal, as you have to do messy casting to pass the address of your pointer as a void**. An improvement would be to return the new pointer separately, as follows:
void *GetSpace(void *ptr, size_t size_of_object, int newsize){
void *tmp = NULL;
if ((tmp = realloc(ptr, size_of_object * newsize) == NULL)
//print error msg and exit
else
return tmp;
}
int main(){
...
//later request more space for mydata1
mydata1 = GetSpace( mydata1, sizeof(double), 50);
}
| |
doc_23532942
|
For example, I get the load average like so:
cat /proc/loadavg
Outputs:
0.18 0.48 0.46 4/234 30719
A: Try this command:
cat /proc/stat
This will be something like this:
cpu 55366 271 17283 75381807 22953 13468 94542 0
cpu0 3374 0 2187 9462432 1393 2 665 0
cpu1 2074 12 1314 9459589 841 2 43 0
cpu2 1664 0 1109 9447191 666 1 571 0
cpu3 864 0 716 9429250 387 2 118 0
cpu4 27667 110 5553 9358851 13900 2598 21784 0
cpu5 16625 146 2861 9388654 4556 4026 24979 0
cpu6 1790 0 1836 9436782 480 3307 19623 0
cpu7 1306 0 1702 9399053 726 3529 26756 0
intr 4421041070 559 10 0 4 5 0 0 0 26 0 0 0 111 0 129692 0 0 0 0 0 95 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 369 91027 1580921706 1277926101 570026630 991666971 0 277768 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 8097121
btime 1251365089
processes 63692
procs_running 2
procs_blocked 0
More details:
http://www.mail-archive.com/linuxkernelnewbies@googlegroups.com/msg01690.html
http://www.linuxhowtos.org/System/procstat.htm
A: Maybe something like this
ps -eo pid,pcpu,comm
And if you like to parse and maybe only look at some processes.
#!/bin/sh
ps -eo pid,pcpu,comm | awk '{if ($2 > 4) print }' >> ~/ps_eo_test.txt
A: Linux does not have any system variables that give the current CPU utilization. Instead, you have to read /proc/stat several times: each column in the cpu(n) lines gives the total CPU time, and you have to take subsequent readings of it to get percentages. See this document to find out what the various columns mean.
A: You can use top or ps commands to check the CPU usage.
using top : This will show you the cpu stats
top -b -n 1 |grep ^Cpu
using ps: This will show you the % cpu usage for each process.
ps -eo pcpu,pid,user,args | sort -r -k1 | less
Also, you can write a small script in bash or perl to read /proc/stat and calculate the CPU usage.
A: The command uptime gives you load averages for the past 1, 5, and 15 minutes.
A: Try this command:
$ top
http://www.cyberciti.biz/tips/how-do-i-find-out-linux-cpu-utilization.html
A: You need to sample the load average for several seconds and calculate the CPU utilization from that. If unsure what to you, get the sources of "top" and read it.
| |
doc_23532943
|
A: You may create WebM video file with alpha channel using FFmpeg in command line.
I found an example here.
The following command (for example), generates synthetic video with 70% transparency:
ffmpeg -y -f lavfi -i testsrc=duration=5:size=320x240:rate=1 -vf format=rgba,colorchannelmixer=aa=0.3' -c:v libvpx-vp9 -crf 10 -b:v 0 vid.webm
The sample is "self contained" (not required an input video file), but simplistic.
Playing the video file vid.webm in a browser, shows that there is transparency.
| |
doc_23532944
|
import requests
import subprocess
import os
import urllib.request
from bs4 import BeautifulSoup
os.chdir("C:/Users/Excel/Downloads/")
request = requests.get("http://ottofrello.dk/malerierstor.htm")
content = request.content
soup = BeautifulSoup(content, "html.parser")
element = soup.find_all("img")
for img in element:
urllib.request.urlretrieve("http://ottofrello.dk/" + img.get('src') + "," + img.get('src') + ")"
I am using Python 3.6.
A: you may want to rewrite the last line as:
urllib.request.urlretrieve("http://ottofrello.dk/" + img.get('src'), img.get('src'))
still you'll get occasional errors when the image path is not just a file name, but an actual path, but you'll be going in the right direction, and can solve this later.
| |
doc_23532945
|
#include <string>
#include <iostream>
using namespace std;
int number_needed(string a, string b) {
for(int i=0;i<a.length();i++)
{
for(int j=0;j<b.length();j++)
{
if(a[i]==b[j]){
{
a[i]='\0';
b[j]='\0';
}
}
}
}
cout<<a<<" "<<b<<endl;
return a.length()+b.length();
}
int main(){
string x;
cin >> x;
string y;
cin >> y;
cout << number_needed(x, y) << endl;
return 0;
}
input:
weasaa
asjdsa
output:
wea jds
12 (returned value from the func number_needed)
expected:
return value of func number_needed to be :
wea jds
6
A: A std::string is a counted string, not a NUL-terminated one.
Thus, changing any arbitrary character won't ever change its length.
If you want to change its size, use .resize(newlength).
A: What you actually want to do inside the if is:
if (a[i] == b[j])
{
a.erase(i, 1);
b.erase(j--, 1); //decrement j so we can check the new char at b[j]
}
This removes 1 element (change the number depending on your needs) from each string starting (and including, of course) at index i. A string can contain any number of '\0', this will not affect the size. If it's a character, then it will count towards the total size of the string.
A: What you want to accomplish may be delete repeating letters in std::string A and B, but you only change it to \0,which does not change string length.Also, your results according to your code, should be:
we\0\0\0a \0\0\0jds\0
12
So in your console, it may look like:
we a jds
12
But if you want your expected result, check:
for (auto Itr_a = a.begin(); Itr_a != a.end(); ++Itr_a)
{
for (auto Itr_b = b.begin(); Itr_b != b.end();)
{
if (*Itr_a == *Itr_b)
{
Itr_a = a.erase(Itr_a);
Itr_b = b.erase(Itr_b);
}
else
++Itr_b;
}
}
Output:
wea jds
6
A: length (which is the same as the preferred size method) returns:
The number of CharT elements in the string, i.e. std::distance(begin(), end())
Since string::operator[] does not invalidate iterators this means that you could assign a null to every character in a string and it wouldn't change the length.
You can use count_if to find the number of non-'\0' characters in a string. You can use it like this: count_if(begin(a), end(a), [](const auto& i){ return i != '\0'; })
With this change your return-statement then would look like this:
return count_if(begin(a), end(a), [](const auto& i){ return i != '\0'; }) + count_if(begin(b), end(b), [](const auto& i){ return i != '\0'; })
EDIT:
A couple comments can be made here:
*
*With the exception of the cout-statement number_needed could be replaced by set_symetric_difference
*If the cout-statement is needed, 2 set_difference statements should be considered
*If neither of the above are desirable, the if-statement should end with a break and the 2 parameters should be passed by const-reference.
| |
doc_23532946
|
What does cin does? Is it character in? I have added comments to the lines I need help to understand. Basically the for loop and the printf command. Rest is all okay.Thanks in advance.
class Solution{
public static void main(String[] args){
Scanner cin=new Scanner(System.in);
System.out.println("================================");
for(;cin.hasNext();){ //what is this doing?
String s=cin.next();
int a=cin.nextInt();
System.out.printf("%-15s%03d\n",s,a); //What is this doing exactly?
}
System.out.println("================================");
}
A: % : Begin format specifier
s : Formats value as a String
- : A flag for left-justified
%3d means there will be a minimum space of width 3 and by default right justified.
%-3d adding a minus infront will make the text left justified.
%03d Fill output with zeroes infront. So instead of 7, 007 will be printed.
%05d Another example for the above. So instead of 7, 00007 will be printed.
According to what was given by you: ("%-15s%03d\n", s, a)
You can deduce the following:
*
*There are 2 format specifiers (indicated by two %) - Two types of format specified.
*The first format (%-15s) is meant for first variable s.
*The second format (%03d) is meant for second variable a.
*The first variable s will be left justified with 15 characters width (Indicated -15s)
*The second variable a will be right justified and filled with zeroes infront. (Indicated by %0)
*The second variable a will have a width of 3 characters and it is right justified (Indicated by %3d)
Example:
Running the following code:
System.out.printf("%-8s%05d\n","hello", 50);
Output:
hello 00050
^^^
|||
3 spaces because hello has width of 8 when we write %8s.
5 spaces already taken by "hello".
Running the following code:
System.out.printf("%8s%05d\n","hello", 50); //Removing the - sign (Right justified)
Output:
hello00050
^^^
|||
3 spaces comes to the front because we removed the -. Text becomes right justified.
A: System.out.printf("%-15s%03d\n",s,a);
%3d\n
% - Begin formatting expression
3d - formatting expression. Expected a value type int. Print right-aligned with the length 3.
a – int Parameter of %3d\n
%-15s
(minus) – Left aligned
5s - Expected a value type string.
s - string parameter of %-15s
A:
for(;cin.hasNext();){ //what is this doing?
The above is similar as writing:
while(cin.hasNext()){
}
hasNext() returns true if this scanner has another token in its input
System.out.printf("%-15s%03d\n",s,a); //What is this doing exactly?
printf() writes a formatted string to this output stream using the specified format string.
A: The java.util.Scanner.hasNext() method Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input:
in your case it will always return true because you are using :
Scanner cin=new Scanner(System.in);*//passing inputs from console*****
following program might help you understand better:
public class ScannerDemo {
public static void main(String[] args) {
String s = "Hello World! 3+3.0=6";
Scanner scanner = new Scanner(s);
System.out.println("" + scanner.hasNext());
System.out.println("" + scanner.nextLine());
System.out.println("" + scanner.hasNext());
scanner.close();
}
}
output:
true
Hello World! 3+3.0=6
false
| |
doc_23532947
|
Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/maven/com.squareup.retrofit2/retrofit/pom.properties
File1: C:\Users\LouDoms\Documents\PICZON\LoOck2\app\libs\retrofit-2.0.0-beta3.jar
File2: C:\Users\LouDoms\.gradle\caches\modules-2\files-2.1\com.squareup.retrofit2\retrofit\2.0.0-beta3\97675641051febfee098903cc0eff62f2826e34e\retrofit-2.0.0-beta3.jar
I tried to include the packaging options but they didn't work. Someone help me please as I don't know what to do or what to remove.
My gradle looks like this:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.0"
defaultConfig {
applicationId "com.example.loudoms.loock"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/ASL2.0'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v4:23.1.1'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:cardview-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
compile 'com.jakewharton:butterknife:7.0.1'
}
A: This question is because ModuleA and ModuleB has same jar(also this jar has META-INF direct),
method is:create a new Module(select Library),then take the jar join to this Module's "libs" direct,then let ModuleA and ModuleB dependent this Module Library.
In this way,no DuplicateFileException.
| |
doc_23532948
|
npm install -g @angular/cli npm ERR! code ELOOP npm ERR! syscall stat
npm ERR! path \UserFS\AppData\ npm ERR! errno -62 npm ERR! ELOOP: too
many symbolic links encountered, stat '\UserFS\AppData\'
npm ERR! A complete log of this run can be found in: npm ERR!
\UserFS\AppData\mjones\Application
Data\npm-cache_logs\2020-03-23T17_04_01_197Z-debug.log
Here is the Log
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli 'install',
1 verbose cli '-g',
1 verbose cli '@angular/cli'
1 verbose cli ]
2 info using npm@6.12.0
3 info using node@v12.13.0
4 verbose npm-session 2b78e4caf18e9e98
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 http fetch GET 304 https://registry.npmjs.org/@angular%2fcli 270ms (from cache)
8 silly pacote tag manifest for @angular/cli@latest fetched in 322ms
9 verbose stack Error: ELOOP: too many symbolic links encountered, stat '\\UserFS\AppData\'
9 verbose stack at eloop (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-tree\realpath.js:58:17)
| |
doc_23532949
|
function decrypt(filename){
$.ajax({
type: "POST",
url: "app.php",
data: { action:'decrypt', filename: filename }
}).done(function( msg ) {
alert( "Data returned: " + msg );
});
return false;
}
Till this everything is okay. When the PHP function is called, I need to call javascript functionality from app.js file in app.php file. But its getting failed. I am trying:
<?php
if($_POST['action'] == 'decrypt') {
my_decrypt($_POST['filename']);
}
function my_decrypt($filename) {
$filedata = file_get_contents($filename);
// Remove the base64 encoding from our key
$key = 'wejnjfff';
$encryption_key = base64_decode($key);
// To decrypt, split the encrypted data from our IV - our unique separator used was "::"
list($encrypted_data, $iv) = explode('::', base64_decode($filedata), 2);
$result = openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
echo "<script type='text/javascript' src='./app.js'>
showPDF();
alert('successful!')
</script>";
return $result;
}
?>
Here, not the showPDF(); function is called nor the alert('successful!') popup is shown. I am new to PHP. Where am I getting wrong? How to call javascript from PHP?
A: <?php
if($_POST['action'] == 'decrypt') {
$result = my_decrypt($_POST['filename']);
echo json_encode(['result' => $result,'success' => 'successful']);
}
function my_decrypt($filename) {
$filedata = file_get_contents($filename);
// Remove the base64 encoding from our key
$key = 'wejnjfff';
$encryption_key = base64_decode($key);
// To decrypt, split the encrypted data from our IV - our unique separator used was "::"
list($encrypted_data, $iv) = explode('::', base64_decode($filedata), 2);
$result = openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
return $result;
}
?>
and in your ajax script
function decrypt(filename){
$.ajax({
type: "POST",
url: "app.php",
data: { action:'decrypt', filename: filename },
dataType: 'json',
success: function (response) {
if(response.success === 'successful') {
alert( "Data returned: " + response.result);
showPDF();
}
}
})
return false;
}
| |
doc_23532950
|
However , I am facing troubles with it, since it's the first time I try to use the MVVM pattern.
I have a main window view, and 2 UserControls, that I want to switch using Buttons. Easy as it is, I am stuck with the the following code, which should work but nothing happen when I click on the button:
MainView.xaml
<Window x:Class="WindowsClient.View.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:WindowsClient.ViewModel"
xmlns:local="clr-namespace:WindowsClient.View"
Height="768" Width="1366" MinHeight="768" MinWidth="1366">
<Window.Resources>
<DataTemplate DataType="{x:Type vm:HomeViewModel}">
<local:HomeView/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:ProfilViewModel}">
<local:ProfilView/>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="240"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!-- LeftMenu -->
<Border Grid.Column="0" Background="Black">
<StackPanel>
<Button Content="Home" Command="{Binding HomeViewCommand}"></Button>
<Button Content="Profil" Command="{Binding ProfilViewCommand}"></Button>
</StackPanel>
</Border>
<!-- Body -->
<ContentControl x:Name="Pages" Content="{Binding ContentControlViewModel}" Grid.Column="1"/>
</Grid>
MainViewModel.cs
namespace WindowsClient.ViewModel
{
public class MainWindowViewModel : INotifyPropertyChanged
{
private object contentControlViewModel;
public object ContentControlViewModel
{
get => contentControlViewModel;
set
{
contentControlViewModel = value;
OnPropertyChanged("ContentControlViewModel");
}
}
public MainWindowViewModel()
{
HomeViewCommand = new BaseCommand(OpenHome);
ProfilViewCommand = new BaseCommand(OpenProfil);
}
public ICommand HomeViewCommand { get; set; }
public ICommand ProfilViewCommand { get; set; }
public void OpenHome(object obj)
{
ContentControlViewModel = new HomeViewModel();
}
public void OpenProfil(object obj)
{
ContentControlViewModel = new ProfilViewModel();
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
public class BaseCommand : ICommand
{
private Predicate<object> _canExecute;
private Action<object> _method;
public event EventHandler CanExecuteChanged;
public BaseCommand(Action<object> method)
: this(method, null)
{
}
public BaseCommand(Action<object> method, Predicate<object> canExecute)
{
_method = method;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_method.Invoke(parameter);
}
}
}
HomeView.xaml
<UserControl x:Class="WindowsClient.View.HomeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Height="768" Width="1126"
MinHeight="768" MinWidth="1126">
<Grid>
<ToggleButton x:Name="CommunityButton" Content="Community" Height="30" Width="200" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="-300,100,0,0" FontSize="18" />
<ToggleButton x:Name="NewsButton" Content="News" Height="30" Width="200" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="300,100,0,0" FontSize="18"/>
<ScrollViewer x:Name="HomeContentViewer" Margin="10,150,10,10"/>
</Grid>
</UserControl>
HomeViewModel.cs
namespace WindowsClient.ViewModel
{
internal class HomeViewModel
{
}
}
ProfilView and ProfilViewModel are pretty much the same as those two.
Anyway, when I click on a button, the view does not change and I can't understand why...
A: This bit is missing from your MainView.xaml:
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
You can add that just above your <Window.Resources> line.
That would be why nothing is being bound to your view from your viewmodel.
| |
doc_23532951
|
A: I'm not sure I understand how your data is organized, but if you just want to check for equality (within a row) of Col. A and Col. E, returning the value in F if the values match, then a simple =IF(Condition, Result if True, Result if False) should work:
=IF(A1 = E1, F1, "")
A: If you need to look it up, it would be a VLOOKUP like so:
=IF(COUNTIF(E:E,A2)>0,VLOOKUP(A2,E:F,2,FALSE),"")
A: One possible way would be to add a fourth column, let's say X, with formulas like =IF($A1=$E1;1;0)
And then in B2 you use a simple lookup to find the 1-value: =LOOKUP(1;X2:X8;F2:F8)
| |
doc_23532952
|
I have a database table with about 20 fields, one of which is a Yes/No field. I want to extract the Yes/No value using DLookup, however am receiving the following error:
Run-time error '3075':
Syntax error (missing operator) in query expression 'Enabled'.
The code I am using it:
MsgBox (DLookup("Enabled", "Numbers", "ID = " & Me.cbxNumber.Value & ""))
Enabled is a Yes/No field
ID is a String field.
The above DLookup works absolutely fine for returning String values for other fields, so the last parameter with the search query, and the table field, should be fine. It is simply complaining about the return field ('Enabled') thinking it is a query.
The MsgBox element is also irrelevant, as I have tried assigning the result to an Integer and to a Boolean, and it's not complaining of a type mismatch which I would expect if this were the problematic part.
Any thoughts?
A: Your code works fine for me:
Table:
Form:
Code:
Private Sub Command30_Click()
MsgBox (DLookup("Enabled", "Numbers", "ID = " & Me.cbxNumber.Value & ""))
End Sub
The messagebox displays 0 or -1 as required. Things to check:
Is your code in the forms module? Otherwise Me.cbxNumber.Value won't return anything.
What do you get if you run
debug.print Me.cbxNumber
from the OnClick of a button on the form?
A: You stated that ID is a string field. If that is the case, try changing the DLookup to...
DLookup("[Enabled]", "Numbers", "ID = " & Chr(34) & Me.cbxNumber.Value & Chr(34))
If ID is a Long, then use this string...
DLookup("[Enabled]", "Numbers", "ID = " & Me.cbxNumber.Value)
| |
doc_23532953
|
and to make it display in the console by [System.out.println].
How can I make it and see the bigger size "Hello" in the console of eclipse?
[java]
A: The console (and, in general, strings in Java and other languages) deals with "plain text". Plain text has no notion of text size or formatting. You cannot do that. You can only change (globally, from the outside) the settings of the console program - among those settings there should be the (global) text size.
| |
doc_23532954
|
Here i my view:
class MyCustomView < NSView
attr_accessor :menu
def initWithFrame(frame)
super(frame)
return self
end
def mouseDown(event)
puts "---"
puts menu.class.to_s
NSMenu.popUpContextMenu(menu, withEvent:event, forView:self)
puts "---"
end
end
And here is the output when I click:
---
NSMenu
---
Does anyone has an idea why the menu does not show?
Thanks,
Greg
A: I have been able to solve my problem by using NSPopupButton.
| |
doc_23532955
|
For example:
export class Controller {
protected static response(res: Response, statusCode: number = 200, data: any, user: string = '', dev: string = '', code: number = 200, result: string = 'success'){
res.status(statusCode).send({
data: data,
message: {
user: '',
dev: ''
},
code: 403,
result: 'Error'
})
}
ERROR: res.status ---> This expression is not callable. Type 'Number' has no call signatures
A: I was getting this error as well, and realized I'd just forgotten to import Response. Adding an import line solved the problem for me.
import express, {Request, Response} from 'express';
A: Im NextJS make sure you import the correct Response type.
import { NextApiResponse } from "next";
A: In case it helps anyone else, I have also seen the same error in cases like this:
const shift = progressWidth * percentage
(this.$refs.expected as Vue).$el.style.left = "100px"
Where percentage is a number. The error occurs because without semicolons the second line is being interpreted as part of the line, like this:
const shift = progressWidth * percentage(this.$refs.expected as Vue).$el.style.left = "100px"
This can be fixed by adding a leading semi-colon:
const shift = progressWidth * percentage
;(this.$refs.expected as Vue).$el.style.left = "100px"
Or even better, rearrange so it isn't needed at all:
const expected = (this.$refs.expected as Vue).$el
const shift = progressWidth * percentage
expected.$el.style.left = "100px"
A: res.status is a number according to that error message. It doesn't look like that Controller is being called with the correct arguments. console.log(res) in there before calling res.status and check your call site code.
A: In your contoller just import the response from express or the framework that you use and it will work.
import { Response } from 'express';
| |
doc_23532956
|
this.route('posts', function() {
this.route('index', { path: '/' })
this.route('show', { path: '/:post_path' }, function() {
this.route('people', { path: '/people' })
this.route('files', function() {
this.route('images', { path: '/images' })
this.route('videos', { path: '/videos' })
})
})
}),
I have a problem with the class "active".
Take, for example, this link:
http://localhost:4200/posts/1-best-post/files/images
In this case, the class "active" will hang on two links - on posts.show.files.images and on posts.show.
How to make the class "active" only for posts.show.files.images?
ADDITION
Apparently the problem is not only with the class "active". But with the templates. The children use the "show" template.
Could you please explain how to properly describe such nested routes?
A: The issue you're encountering is because ember has a hidden index route for each nested function in the router.
Your route file actually expands out to look like this.
this.route('posts', function() {
this.route('index', { path: '/' })
this.route('show', { path: '/:post_path' }, function() {
this.route('index', { path: '/' }) #New
this.route('people', { path: '/people' })
this.route('files', function() {
this.route('index', { path: '/' }) #New
this.route('images', { path: '/images' })
this.route('videos', { path: '/videos' })
})
})
}),
When you define the link-to path, I'm going to assume that you specify it exactly as it looked, rather than using the hidden index.
# Don't do this
{{#link-to 'posts.show' "1234"}}Posts Show{{/link-to}}
{{#link-to 'posts.show.files.images' "1234"}}Images Show{{/link-to}}
# Do this
{{#link-to 'posts.show.index' "1234"}}Posts Show{{/link-to}}
{{#link-to 'posts.show.files.images' "1234"}}Images Show{{/link-to}}
This ember-twiddle shows an example of the issue you're having. The top section shows the issue you're experiencing. The bottom section shows the corrected links.
Similarly, the show.hbs route you're using is going to be considered a wrapper for ALL routes under show.
If you don't want the content of show when you're looking at files or images, move the logic and display into posts/show/index.js and posts/show/index.hbs
| |
doc_23532957
|
addTimestamp(e);
}
function addTimestamp(e){
var row = e.range.getRow();
var col = e.range.getColumn();
if(col === 10 && row > 1 && e.source.getActiveSheet().getName() === "Phy-JEE-Eng- 208_206_53")
if(e.source.getActiveSheet().getRange(row,11).getValue()== ""){
e.source.getActiveSheet().getRange(row,11).setValue(new Date());
}
}**
the above script is used in getting timestamp in a column (B) adjacent to column (A), When ever someone adds any value / clicks the checkbox in column (A). but the problem arises when someone selects a bunch or rows and tries to tick the checkbox by hitting space button, and when someone wants to paste bulk values into multiple rows in column (A), the script is only working in the cell which is the primary point (highlighted cell) of selection in an array of selection. I need a function where whenever something is added in any cell I should get a timestamp, looking for some suggestions other than OnEdit!
A: function onEdit(e) {
const sh = e.range.getSheet();
if (e.range.columnStart == 10 && e.range.rowStart > 1 && sh.getName() == "Phy-JEE-Eng- 208_206_53") {
if (e.range.offset(0, 1).getValue() == "") {
e.range.offset(0, 1).setValue(new Date());
}
}
}
| |
doc_23532958
|
Any ideas?
<script>
> var counter = 1;
> var limit = 15;
> function addInput(divName){
> > if (counter == 15) {
> var el = document.getElementById('destroy');
> el.style.display = "none";
> > }
> > else {
> > var newdiv = document.createElement('div');
> > newdiv.innerHTML = "<span id=''>Serial Number " + (counter + 1) + " : <input type='text' name='myInputs[]'/></span>";
> > document.getElementById(divName).appendChild(newdiv);
> > counter++;
> > }
> >
> > } </script>
A: I'm guessing you are trying to do this:
var counter = 1;
var limit = 15;
function addInput(divName){
if (counter < limit) {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<span id=''>Serial Number " + (counter + 1) + " : <input type='text' name='myInputs[]'/></span>";
document.getElementById(divName).appendChild(newdiv);
counter++;
if(counter === limit){
var el = document.getElementById('destroy');
el.style.display = "none";
}
}
}
A: A simple rearrangement should do the trick:
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = "<span id=''>Serial Number " + (counter + 1) + " : <input type='text' name='myInputs[]'/></span>";
document.getElementById(divName).appendChild(newdiv);
counter++;
if (counter == 15) {
var el = document.getElementById('destroy');
el.style.display = "none";
}
}
| |
doc_23532959
|
There's a standart function to show modals, but i'm using a parameter to declare if this modal should show up in a specific size, and i'm calling this function with this parameter only in modals i want, but this style is remaining for the following modals.
This is the important parts of the function:
function mostrarModal(btt, e, titulo, url, boolFullSize) //the parameter is boolFullSize
if(boolFullSize !== undefined && boolFullSize) {
modal.dialog("open");
carregaForm(undefined, 'modal', link, undefined, undefined, fullsizeModal);
return;
}
function fullsizeModal() {
centralizaModal();
modal.dialog({
minHeight: window.innerHeight * 0.9
});
$(".ui-dialog, .ui-content").css({
"max-height":"90vh",
"max-width":"90vw"
})
}
| |
doc_23532960
|
s1 = {'val' : 0}
s2 = {'val': 10}
s3 = {'val': 5}
s4 = {'val' : 4}
s5 = {'val' : 6}
s6 = {'val' : 7}
s7 = {'val' : 3}
shapelets = [s1,s2,s3,s4,s5,s6,s7]
I want to get the max 5 numbers in the shapelets list, knowing that it contains a key of name "val" and to which a value is assigned.
The solution here resides in parsing through the list of dict elements and get the max n numbers of it ( in this case the max 5 values )
What can be a simple solution, does operator library in python supports such operation ?
A: Here's a working example:
s1 = {'val': 0}
s2 = {'val': 10}
s3 = {'val': 5}
s4 = {'val': 4}
s5 = {'val': 6}
s6 = {'val': 7}
s7 = {'val': 3}
shapelets = [s1, s2, s3, s4, s5, s6, s7]
print(sorted(shapelets, key=lambda x: x['val'])[-5:])
A: You could do it in linear time using numpy.argpartition:
from operator import itemgetter
import numpy as np
arr = np.array(list(map(itemgetter("val"), shapelets)))
print(arr[np.argpartition(arr, -5)][-5:])
The 5 max values will not necessarily be in order, if you want that then you would need to sort the k elements returned.
A: You can use heapq:
import heapq
s1 = {'val': 0}
s2 = {'val': 10}
s3 = {'val': 5}
s4 = {'val': 4}
s5 = {'val': 6}
s6 = {'val': 7}
s7 = {'val': 3}
shapelets = [s1, s2, s3, s4, s5, s6, s7]
heapq.nlargest(5,[dct['val'] for dct in shapelets])
# [10, 7, 6, 5, 4]
heapq is likely to be faster than sorted for large lists if you only want a few of the largest values. Some discussions of heapq vs. sorted are here.
| |
doc_23532961
|
Thanks!
A: It works perfectly to install it in VS community 2013
| |
doc_23532962
|
A: You have 2 options:
*
*Use <jsp:usebean>, let the bean fill itself in the constructor.
<jsp:useBean id="bean" class="com.example.Bean" />
...
<input name="foo" value="${fn:escapeXml(bean.foo)}">
<input name="bar" value="${fn:escapeXml(bean.bar)}">
The fn:escapeXml() is not mandatory for the functioning, but it's mandatory to prevent XSS attacks if you're redisplaying user-controlled input in a HTML page.
*Use the doGet() method of a Servlet.
Bean bean = new Bean();
request.setAttribute("bean", bean);
request.getRequestDispatcher("page.jsp").forward(request, response);
and use the URL to servlet in browser address bar instead of the JSP's one. You can use the same code in JSP page as above, expect of the jsp:useBean line.
Way 1 is more the oldschool and student's way. Way 2 is more MVC oriented and preferred in this particular case since you seem to be doing more than just populating a bean.
See also:
*
*JSP tag info page - contains useful tutorial links at bottom
A: Sure - just set initial values in the bean properties that you are exposing in your form. Then use expression language to populate the fields, such as
<input type="text" value="${bean.myProperty}"/>
| |
doc_23532963
|
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<Parameter key="filePath" Value="C:\FilesToWatch"></Parameter>
</appSettings>
</configuration>
Then I did some research how to use this value in my HomeController and many people say that the ConfigurationManager is the solution so i tried this:
string s = System.Configuration.ConfigurationManager.AppSettings[key];
The problem I now have is, that I am not able to use the ConfigurationManager so it is red underlined. Is there something, that I have to import or install?
A: You need to add a reference to the System.Configuration namespace.
In Solution Explorer, right-click on the References or Dependencies node and choose Add Reference. You can also right-click on the project node and select Add > Reference.
Select the System.Configuration namespace.
You can now use this namespace in your classes.
using System.Configuration;
| |
doc_23532964
|
How can I to close/dismiss the ProgressHUD dialog programmatically? Because at the documentation it was using onPress to dismiss the dialog. What I want is to programmatically dismiss or close the dialog without onPress.
Thank you.
The library/package of the ProgressHUD dialog link below:
https://pub.dartlang.org/packages/progress_hud#-readme-tab-
The code below is initiate the dialog:
bool _loading = true;
@override
void initState() {
super.initState();
_progressHUD = new ProgressHUD(
backgroundColor: Colors.black12,
color: Colors.white,
containerColor: Colors.blue,
borderRadius: 5.0,
text: 'Loading...',
);
//If I put in this line, there have an error,
//the state is null, the dismiss() function called on null.
_progressHUD.state.dismiss();
}
You can see if I put the _progressHUD.state.dismiss(); in function initState() There is an error which is the state is null, the dismiss() function called on null reference.
The code below is use to dismiss dialog:
_progressHUD.state.dismiss();
A: You are dismissing progress in init state when the widget is not fully build. So, state null error is showing. To use it inside init state or when state is not fully set, you can use postframe callback.
WidgetsBinding.instance.addPostFrameCallback((_) {
_progressHUD.state.dismiss();
});
| |
doc_23532965
|
If they aren't equivalents, then what are the differences and how do they relate?
A: Gradle is not equivalent to the compiler. Compilers primarily meant for translating the high-level language(i.e. java) into machine code or other intermediate code representation like bytecode. wheres Gradle is a build system that packages the code for you and makes it ready for compilation. If you take an example from android, under the hood, Gradle downloads the defined dependencies and packages everything for you without messing up and simplifies the development flow. It does all the dependencies management for the project. Gradle output is not the translated code, instead, you can say it's arranged code. finally Gradle is not equivalent of any compiler.
There is a similar question on StackOverflow Post. Rather putting post multiple times, you can accept satisfactorily answer, so moderators can remove the duplicate/unaccepted one.
| |
doc_23532966
|
I have a scrollable div (overflow), with divs inside of it. The scrolling use is intended for touchscreens.
I want the user to be able to scroll as he likes, but as soon as he stops scrolling, the first div that's entirely within the viewport of the parent div needs to stick to the top of the parent div.
Basically like a casino roulette I guess. You can't have a div partially visible, halfway out of the viewport, if you stopped scrolling. You can only have that when scrolling.
Another example is time selector like the iphone one
If you stop scrolling, the closest value gets selected. That's what I need, within a parent div.
This is my html structure, the inside div is only to get rid of the scrolling bar:
$(document).ready(function () {
var pos = $('.current').offset();
var left = (pos.left - $('#inside_left').offset().left);
var right = (pos.top - $('#inside_left').offset().top);
$("#inside_left").scroll(function () {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
alert('bottom');
}
});
$('#inside_left').click(function () {
$('#frame_current').css("height", $('.current').height());
$('#frame_current').css("width", $('.current').width());
if ($('.current').isOnScreen() == true) {
alert('icansee');
}
});
});
#left_column {
float: left;
width: 40%;
height: 100vh;
background-color: red;
overflow: hidden;
}
#inside_left {
width: 125%;
overflow-y: scroll;
height: 100vh;
}
.section {
position: relative;
width: 90%;
height: 20%;
background-color: green;
margin-bottom: 1px;
}
<div id="parent">
<div id="inside">
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
</div>
</div>
A: If you are going to use full page sections, which seems to me the only solution if you want to stick each section when the user stops scrolling, then you can do it using my fullPage.js library.
Just use the option normalScroll:true like in this example.
The option fitToSection to cause the "sticky effect" is activated by default.
| |
doc_23532967
|
Here is the code
<html>
<head>
<script type="text/javascript">
var checkflag = "false";
function check(field) {
if (checkflag == "false") {
for (i = 0; i < field.length; i++) {
field[i].checked = true;
}
checkflag = "true";
return "Uncheck All";
} else {
for (i = 0; i < field.length; i++) {
field[i].checked = false;
}
checkflag = "false";
return "Check All";
}
}
function ShowHideDiv(chkPassport) {
var dvPassport = document.getElementById("dvPassport");
dvPassport.style.display = chkPassport.checked ? "block" : "none";
}
</script>
</head>
<body>
<form name=myform action="" method=post>
<table>
<tr>
<td><strong>Make a selection</strong><br> <input
type=checkbox name=list id="chkPassport"
onclick="ShowHideDiv(this)" value="1">Java<br> <input
type=checkbox name=list value="2">JavaScript<br> <input
type=checkbox name=list value="3">ASP<br> <input
type=checkbox name=list value="4">HTML<br> <input
type=checkbox name=list value="5">SQL<br> <br> <input
type=button value="Check All"
onClick="this.value=check(this.form.list)"></td>
</tr>
</table>
<div id="dvPassport" style="display: none">
Passport Number: <input type="text" id="txtPassportNumber" />
</div>
</form>
</body>
</html>
A: You can do so by the following jQuery code:
$('.checkbox').click(function() {
if( $(this).is(':checked')) {
$("#yourdiv").show();
} else {
$("#yourdiv").hide();
}
});
Change the #yourdiv - and .checkbox to your CSS identifiers.
| |
doc_23532968
|
Uncaught DOMException: Failed to execute 'postMessage' on 'Worker': An OffscreenCanvas could not be cloned because it was detached.
at main (http://localhost:8000/responsivetemplate/:47:14)
[index.html]
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="cache-control" content="must-revalidate" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
<meta charset="UTF-8" />
<title>OffscreenCanvas</title>
</head>
<body>
<div id='wrapper'>
<div id='content'>
<canvas id="testcanvas" width="512" height="512"></canvas>
</div>
</div>
</body>
<script>
'use strict';
document.body.onload = function () {
var canvas = document.getElementById('testcanvas');
canvas.imageSmoothingEnabled = false;
const offscreenCanvas = canvas.transferControlToOffscreen();
const worker = new Worker('render.js');
var speed = 100;
var currentTime = 0; var timeDiff = 0; var lastTime = 0;
var timeProduct = 0; var dTime = 0; var timeScale = 1; var timeStep = 0.01;
var posX = 10; var posY = 10;
function main() {
currentTime = performance.now();
timeDiff = (Math.abs(currentTime - lastTime) * 0.001);
dTime += Math.min(timeDiff, 1);
timeProduct = timeStep * timeScale;
while (dTime > timeProduct) {
//draw();
worker.postMessage({canvas: offscreenCanvas, posX: posX, posY: posY}, [offscreenCanvas]);
dTime -= timeProduct;
}
lastTime = currentTime;
posX += speed * timeDiff;
posY += speed * timeDiff;
if (posX > 500) posX = 10;
if (posY > 500) posY = 10;
requestAnimationFrame(main);
}
requestAnimationFrame(main);
};
</script>
</html>
[worker.js]
'use strict';
var canvas;
var ctx;
function draw(posX, posY) {
//clear
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
//draw
ctx.beginPath();
ctx.moveTo(posX, posY);
ctx.ellipse(posX,
posY,
5,
5,
0.7854,
0,
2 * Math.PI,
false);
ctx.strokeStyle = "white";
ctx.stroke();
}
onmessage = function(ev) {
if(ev.data) {
if (!canvas) canvas = ev.data.canvas;
if (!ctx) ctx = canvas.getContext('2d');
var posX = ev.data.posX; var posY = ev.data.posY;
draw(posX, posY);
}
}
I don't know what causes this error - code works fine when run only in the main thread, also already checked some sites and I'm sure the controll was sent to offscreen :\
A: You should send OffscreenCanvas to worker only once:
worker.postMessage({canvas: offscreenCanvas}, [offscreenCanvas]);
while (dTime > timeProduct) {
worker.postMessage({ posX, posY });
dTime -= timeProduct;
}
| |
doc_23532969
|
<context-param>
<param-name>myparam</param-name>
<param-value>myvalue</param-value>
</context-param>
A: I believe @Endpoint annotated class is managed by spring container if so , then you can Autowire ServletContext as below
class MyWS{
@Autowired(required = false)
private ServletContext servletContext;
public String myParamTest() {
String ret = servletContext.getInitParameter("myparam");
LOG.debug(ret);
return ret;
}
}
| |
doc_23532970
|
We are not planning to approve all stages (some stages might take weeks to get approved or some will be never approved) because we don't want to promote every single build to production.
Is this an expected behavior? Are the agents released during the wait period?
See image below as en example. As you can see, we did not approve the 3rd stage but the timer keeps increasing.
A:
Is this an expected behavior?
The answer for this question is Yes. This is a expected behavior. The Approve will waiting until it be approved/rejected or expired by the the Timeout setting:
Are the agents released during the wait period?
In fact, after the previous stage job finished. The agent has been released. And during the period of waiting for approve, it will not possess this agent. As you can see the pic shown below:
I have 2 stages in release. After stage1 job finished and waiting for stage2's pre-approve, the agent has been released and does not be possessed by the stage2. The agent will be used again until you approve this stage and job begin running. So, for waiting approval, you don't need worry about the agent will be possessed.
| |
doc_23532971
|
(this is pandas data frame)
{]1
import pandas as pd
df = pd.read_csv(r'C:\Users\ASUS\Downloads\bridges.csv' , header=None)
df.columns = ["IDENTIF", "RIVER", "LOCATION", "ERECTED","PURPOSE", "LENGTH", "LANES", "CLEAR-G","T-OR-D", "MATERIAL", "SPAN", "REL-L","TYPE"]
print(df)
A: Try
df = df.replace('?', "Null")
Or, you probably actually want to use:
import numpy as np
df = df.replace('?', np.nan)
| |
doc_23532972
|
Below is my code :
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
o = win32com.client.Dispatch("Outlook.Application")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
for message in messages:
if message.Subject == "aaa":
print("Found message")
message.body="This is a reply"
message.Reply()
The reply is getting sent to the sender of "aaa" but the previous email on which I am trying to reply does not appear below the new email.The history of emails on which I am replying gets lost.
A: I do not have the means to test this, but from the code you shared, I think the problem is as follows:
you iterate over messages and each found MailItem is assigned the loop variable "message".
Next you set the body of message as "This is a reply" - in other words: You overwrite the original message with the new string and then send the reply.
.Reply() then simply creates a new MailItem object from message, just with Sender and Recipient Properties switched... and the new body you yourself assigned it.
https://learn.microsoft.com/en-gb/office/vba/api/outlook.mailitem.reply(method)
EDIT:
So I made this code:
import win32com.client as win32
outlook = win32.Dispatch("Outlook.Application").GetNamespace("MAPI")
acc = outlook.Folders("myemail@provider.com")
inbox = acc.folders("Inbox") #change to localized versions
drafts = acc.folders("Drafts") #if necessary
def createReply(email:object):
reply = email.Reply()
newBody = "Dear friend,\n\nThis should be added on top.\nI hope this
works\n\nkr\ntst\n"
reply.HTMLBody = newBody + reply.HTMLBody
reply.Move(drafts)
for mailItem in inbox.Items:
if mailItem.Subject == "Test4Reply":
print("Start")
createReply(mailItem)
First, I sent an email to myself with the Subject line "Test4Reply" so I can grab that. I added some gibberish into the Email body, just to check if it gets retained. Then, I created a new MailItem Object reply from the email in my inbox using the .Reply() Method, which I then moved (with .Move()) into my Drafts folder. There I can inspect it and see that, indeed, the original email is preserved in the history, as well as the Subject line automatically gaining the "AW: " prefix.
So:
To preserve the original email, you just need to make sure to not overwrite the original Body and only insert new text at the beginning of the MailItem.HTMLBody.
| |
doc_23532973
|
12345631
L1234512
P12345
234556
19090912
J123456
Using Linq and .Net 3.5, I want to create a csv string for accounts starting with L or P and is of 6 characters. Following code creates a csv string but how to add the filter?
string[] accounts = accountList.Select(c => c.acctnbr).ToArray();
string csv = string.Join(",", accounts);
The output should be L12345,P12345.
A: Try this:
string[] accounts = accountList
.Where
(
a=> (a.acctnbr.StartsWith("L") || a.acctnbr.StartsWith("P"))
&&
(a.acctnbr.Length == 6)
)
.Select(c => c.acctnbr)
.ToArray();
string csv = string.Join(",", accounts);
A: In case you't interested, here's a version using the query syntax instead as well
var accounts = from a in accountList
where (a.acctnbr.StartsWith("L") || a.acctnbr.StartsWith("P"))
&& (a.acctnbr.Length == 6)
select a.acctnbr;
var csv = String.Join("," accounts.ToArray());
Based on the comment you added regarding which solution is better, mine or Cybernate. The solutions are the same, C# let's you write queries in two ways. You can take a look at LINQ Query Syntax versus Method Syntax (C#) for more information.
Relevant bit from ducumentation (though I would strongly urge you to read up more on Linq)
In general, we recommend query syntax because it is usually simpler and more readable; however there is no semantic difference between method syntax and query syntax. In addition, some queries, such as those that retrieve the number of elements that match a specified condition, or that retrieve the element that has the maximum value in a source sequence, can only be expressed as method calls.
A: string[] accounts = accountList.Select(c => c.acctnbr).ToArray();
IEnumerable<string> namesWithFourCharacters = from name in accounts
where name.StartsWith("L")
select name;
Hope this helps.
| |
doc_23532974
|
public static Statistic[] combineStatistics(Statistic[] rptData, Statistic[] dbsData) {
HashSet<Statistic> set = new HashSet<Statistic>();
for (int i=0; i<rptData.length; i++) {
set.add(rptData[i]);
}
/*If there's no data in the database, we don't have anything to add to the new array*/
if (dbsData!=null) {
for (int j=0; j<dbsData.length;j++) {
set.add(dbsData[j]);
}
}
Statistic[] total=set.toArray(new Statistic[0]);
for (int workDummy=0; workDummy<total.length; workDummy++) {
System.out.println(total[workDummy].serialName);
}
return total;
}//end combineStatistics()
A: Properly implement equals(Object obj) and hashCode() on YourObject if you expect value equality instead of reference equality.
Set<YourObject> set = new HashSet<YourObject>(yourCollection);
or
Set<YourObject> set = new HashSet<YourObject>();
set.add(...);
then
YourObject[] array = set.toArray(new YourObject[0])
A: I think you should pay attention to:
1 - what to do if there is a duplicate in the original Collection? Use the first added to the array? Use the other(s)?
2 - You definitely need to implement equals and hashcode so that you can tell what are duplicate objects
3 - Are you going to create a fixed size array and then won't add anymore objects? Or are you going to keep adding stuff?
You can use any kind of Set actually, but if you use LinkedHashSet, then you will have a defined iteration order (which looks like an array). HashSet wont't garantee any order and TreeSet will try to order data ascending.
A: Depends on what you are referring to as a duplicate. If you mean an identical object, then you could use a List and simply see if the List contains the object prior to adding it to the list.
Object obj = new Object();
List<Object> list = new ArrayList<Object>();
if (!list.contains(obj)) {
list.add(obj);
}
| |
doc_23532975
|
Everything is working fine...content loads and fades In. I just don't know where and how to put the FadeOut part! So it Fades Out the current div, loads in the new content and then Fades that In!
Help?
$('.menu_home').click(function() {
var href = $(this).attr('href');
$('#pageContent').hide().load(href).fadeIn(2000);
return false;
});
A: Use the callback from fadeOut:
$('#pageContent').fadeOut(2000, function() {
$(this).load(href).fadeIn(2000);
})
| |
doc_23532976
|
I can get the box to appear using this code:
let errors = [];
let radiobutton = form.getAnswerText("sIsPersonLongTermNeeds");
if (radiobutton == "sIsPersonLongTermNeedsNo" ||
radiobutton == "sIsPersonLongTermNeedsUnknown"
) {
window.confirm("text");
}
But I don't know how to use the values (which I believe are true/false)?
| |
doc_23532977
|
f = pd.read_csv("test.csv",delimiter=",")
df = pd.DataFrame(f)
if df.str.startswith('pjp-'):
df = df.replace(["pjp-*|"],[""])
print(df)
head(df)
Quantity code boxes
34 pjp-custom|3cex 10
20 pjp-cusm|4cex 8
12 pjp-ctom|5cex 6
40 pjp-custom|6cex 14
desired output
Quantity code boxes
34 3cex 10
20 4cex 8
12 5cex 6
40 6cex 14
A: I think you should actually just do:
df[column] = df[column].str.replace("pjp-*|","")
Hope it helps, we need more information overhere
A: This does exactly what you want it to do in 1 line of code:
#Theres actually 4 things going on in this 1 line of code
df['Code_Boxes'] = (((df['Code_Boxes'].str.rsplit('pjp-')).str[1]).str.rsplit('|')).str[1]
This will only work if what you say is true 'pjp-' is always at the front and '|' is at the end of what you want to split. Just so you can learn what I did see the 4 steps below.
#these 4 things can actually be done in one line, but its easy to see what we're doing this way.
df['Code_Boxes'] = df['Code_Boxes'].str.rsplit('pjp-')
df['Code_Boxes'] = df['Code_Boxes'].str[1]
df['Code_Boxes'] = df['Code_Boxes'].str.rsplit('|')
df['Code_Boxes'] = df['Code_Boxes'].str[1]
| |
doc_23532978
|
A: The App Engine Standard Environment in which you have deployed the application following the tutorial is a sandboxed environment and you cannot really access the instances and the filesystem where the application is deployed. Read this document to better understand how instances are managed.
On the other hand, App Engine Flexible Environment runs on top of Compute Engine instances and therefore you can access these instances via SSH, for example.
Take a look here and here. The two articles will get you started on the differences of App Engine Standard and Flexible environments.
I also recommend that you take a look at the tutorials to deploy Java applications on App Engine Standard and Flexible environments.
| |
doc_23532979
|
I have a small bug which I can't seem to fix regarding the scrollview and setstate. I have a function that displays the search list under my search bar. It is an absolutely positioned element. The bug occurs when I try to scroll down on the scrollview and press on one of the items, instead of the scrollview remaining in place it scrolls directly to the top. Ideally I would like the scrollview to remain in place once the user has pressed on a item. I feel like it has something to do with how I'm calling setstate. The function is as follows:
const [userIngredients, setUserIngredients] = useState([]);
const OutputSearchList = () => {
const clickIngredient = (i) => {
if (!userIngredients.includes(i)) {
setUserIngredients((temp) => [...temp, i]);
} else {
const temp = userIngredients.filter((item) => item !== i);
setUserIngredients(temp);
}
};
return ingredients.map((item) => {
return (
<TouchableOpacity
style={styles.searchBarListItem}
onPress={() => clickIngredient(item)}
key={item}
>
<View style={styles.searchBarListContentChecked}>
<Text style={styles.searchBarListText}>{item}</Text>
<Ionicons
style={styles.searchBarListAdd}
name="checkmark-circle-outline"
size={28}
color="#000000"
/>
</View>
</TouchableOpacity>
);
});
};
and the function is called like so:
<ScrollView>
{ingredients?.length > 0 ? (
<View>
<OutputSearchList />
</View>
) : searchText?.length > 0 ? (
<View>
<Text>No ingredients found</Text>
</View>
) : (
<View>
<Text>Search for an ingredient (e.g. Eggs, Beef, Rice)</Text>
</View>
)}
</ScrollView>
| |
doc_23532980
|
Can someone please help me understand how i can use this?
A: I think you need to go up one level and look at tutorials first: http://docs.oracle.com/javase/tutorial/. Once you understand the basics of Java, then you can use the API reference to find the classes and methods you need.
| |
doc_23532981
|
?- position([[b,c,f],[a,d,g],[h,e]],c,P)
P=1
?- position([[b,c,f],[a,d,g],[h,e]],g,P)
P=2
?- position([[b,c,f],[a,d,g],[h,e]],b,P)
P=0
I've been looking at the nth0/3 predicate but I'm not sure if that is the right way to go about this. Any pointers would be highly appreciated.
I'm trying to find the position of each element within its nested list.
A: position(LL,E,N):-
nth1(N,LL,L),
member(E,L).
?- position([[b,c,f],[a,d,g],[h,e]],c,P).
P = 1 ;
false.
?- position([[b,c,f],[a,d,g],[h,e]],g,P).
P = 2 ;
false.
Assuming you are allowed to use member/2 and nth1/3, see their implementation below.
The predicate just goes through all members L of the inputlist LL through nth1/3 (and tracks the position N) and checks if your searched element E is a member of the list L.
This predicate works for simple nested lists where the searched element is direct member of the sublist. It will not work for further nested sublosts, example: position([[b,c,f],[[a],[d,g]],[h,e]],g,P)
In case you are not allowed to use inbuild predicates:
my_nth1(1,[X|_],X).
my_nth1(Idx,[_|List],X) :-
my_nth1(Idx1,List,X),
Idx is Idx1+1.
my_member(X, [X|_]).
my_member(X, [_|T]):-
my_member(X, T).
You could even not use the member predicate by just writing
position(LL,E,N):-
mynth1(N,LL,L),
mynth1(_,L,E).
In case you are not interested in the number of the sublist but the number of the element within the sublist:
position(LL,E,N):-
member(L,LL),
nth0(N,L,E).
?- position([[b,c,f],[a,d,g],[h,e]],c,P).
P = 1 ;
false.
?- position([[b,c,f],[a,d,g],[h,e]],g,P).
P = 2 ;
false.
A: Here's my approach:
1. The first position predicate is the base case (Stopping Condition if Element not found keep checking till list is empty).
2. The second predicate takes the list, Element to be checked, and give the final position in P. Using if-else technique. If Element is a member of H (meaning H=[b,c,f]) then give us the position of the Element using nth0. Else, check the remaining T (Tail: [[a,d,g],[h,e]]) in the same manner.
position([],_,_).
position([H|T],Element,P):-
( member(Element,H)->
nth0(P,H,Element);
position(T,Element,P)).
Example:
?-position([[b,c,f],[a,d,g],[h,e]],c,P).
P = 1
false
?-position([[b,c,f],[a,d,g],[h,e]],e,P).
P = 1
?-position([[b,c,f],[a,d,g],[h,e]],g,P).
P = 2
?-position([[b,c,f],[a,d,g],[h,e]],b,P).
P = 0
false
| |
doc_23532982
|
I have a list of vectors:
l <- list(c(1, 2), c(5, 10))
and I want to test whether a given vector --- for instance, c(1, 2) --- is in that list. I thought the "straightforward" approach would work:
c(1, 2) %in% l
but that returns
[1] FALSE FALSE
In the end I found the following solution:
any(sapply(l, function(x) { all(x == c(1, 2)) }))
but it is quite cumbersome, so I really wonder if that is the simplest option. Is there any simpler way to test for a vector in a list of vectors?
A: Since you are dealing with objects the == operator is not ideal. A slightly simpler approach is:
any(sapply(l, identical, y=c(1,2)))
The %in% operator doesn't work because it is a call to the function match. It reads l as a vector. In other words, what it's doing is:
for(i in 1:length(c(1,2)))
c(1,2)[i]==l[[i]]
| |
doc_23532983
|
let principal = document.getElementById("principal").value;
let rate = document.getElementById("rate").value;
let years = document.getElementById("years").value;
let interest = principal * years * rate / 100;
let year = new Date().getFullYear() + parseInt(years);
document.getElementById("result").innerHTML = "If you deposit " + principal + ",\<br\>at an interest rate of " + rate + "%\<br\>You will receive an amount of " + interest + ",\<br\>in the year " + year + "\<br\>"
}
Instead of the rate, principal, rate, interest, year, I need their values with a yellow background color, however, rate.style.background = "yellow" is not possible. How could I change the variables background color in the result?
A: You need to change the DOM style, and not it's value like you did there, you can query the DOMs (so you can manipulate the styles) and ask for value every time, like this:
function click() {
let principal = document.getElementById("principal");
let rate = document.getElementById("rate");
let years = document.getElementById("years");
let interest = principal.value * years.value * rate.value / 100;
let year = new Date().getFullYear() + parseInt(years);
document.getElementById("result").innerHTML = "If you deposit " + principal.value + ",\<br\>at an interest rate of " + rate.value + "%\<br\>You will receive an amount of " + interest.value + ",\<br\>in the year " + year.value + "\<br\>"
}
A: As mentioned in the comment, there are a few things that should be fixed:
*
*document.getElementById().value returns the value attribute of a DOM element and the attribute has no background property that can be modified. In order to do what you want to achieve, you have to wrap that value in a DOM element (e.g. a <span>) and give the background to that element
*document.getElementById().value returns the value as a string; if you want to do math with it, you have to convert the value to a number
When you fix that, you should end up with something similar to:
function clickFn() {
let principal = parseFloat(document.getElementById("principal").value);
let rate = parseFloat(document.getElementById("rate").value);
let years = parseInt(document.getElementById("years").value);
let interest = principal * years * rate / 100;
let year = new Date().getFullYear() + years;
document.getElementById("result").innerHTML = "If you deposit <span class='yellow'>" + principal + "</span>,<br\>at an interest rate of <span class='yellow'>" + rate + "%</span><br\>You will receive an amount of <span class='yellow'>" + interest + "</span>,<br\>in the year <span class='yellow'>" + year + "</span><br\>";
/*
You could use a templating string instead of string concatenation, to make your code a little bit more compact:
document.getElementById("result").innerHTML = `If you deposit <span class='yellow'>${principal}</span>,<br\>at an interest rate of <span class='yellow'>${rate}%</span><br\>You will receive an amount of <span class='yellow'>${interest}</span>,<br\>in the year <span class='yellow'>${year}</span><br\>`
*/
}
document.getElementById("calculate").addEventListener('click', clickFn);
.yellow {
background-color: yellow;
}
<input id="principal" name="principal" type="number" />
<input id="rate" name="rate" type="number" />
<input id="years" name="years" type="number" />
<button id="calculate">calculate</button>
<p id="result">
</p>
| |
doc_23532984
|
12/26/2016 9A Christmas Day
3/25/2016 9A Good Friday
3/28/2016 AS Easter Monday
12/26/2016 AS St. Stephen's Day
3/25/2016 AS Easter Monday
1/1/2016 AS New Year's Day
12/26/2016 BE Christmas
1/1/2016 BZ New Year's Day
2/9/2016 BZ Carnival
5/26/2016 BZ Corpus Christ
4/21/2016 BZ Tiradentes Day
12/27/2016 CA Boxing Day (obs)
10/10/2016 CA Thanksgiving
What I want is, to append new column with content of the 2nd column, where the dates are the same. For example:
12/26/2016 9A Christmas Day 9A AS BE
3/25/2016 9A Good Friday 9A
3/28/2016 AS Easter Monday AS
12/26/2016 AS St. Stephen's Day 9A AS BE
3/25/2016 AS Easter Monday AS
1/1/2016 AS New Year's Day AS BZ
12/26/2016 BE Christmas 9A AS BE
1/1/2016 BZ New Year's Day AS BZ
2/9/2016 BZ Carnival BZ
5/26/2016 BZ Corpus Christ BZ
4/21/2016 BZ Tiradentes Day BZ
12/27/2016 CA Boxing Day (obs) CA
10/10/2016 CA Thanksgiving CA
The rows that have same date, will have same values in the fourth column.Column names are (Date, CDR Code, Holiday). Data is the name of the sheet. The code I wrote:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim MyConnection As New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='d:\test.xlsx';Extended Properties='Excel 12.0;HDR=YES'")
Dim MyCommand As New System.Data.OleDb.OleDbDataAdapter("select * from [Data$]", MyConnection)
Dim DtSet As New System.Data.DataSet
MyCommand.Fill(DtSet)
DataGridView1.DataSource = DtSet.Tables(0)
MyConnection.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim MyConnection2 As New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='d:\test.xlsx';Extended Properties='Excel 12.0;HDR=YES'")
Dim MyCommand2 As New System.Data.OleDb.OleDbDataAdapter("select [CDR Code] from [Data$] WHERE [Date]=[Date] ", MyConnection2)
Dim DtSet2 As New System.Data.DataSet
MyCommand2.Fill(DtSet2)
DataGridView2.DataSource = DtSet2.Tables(0)
MyConnection2.Close()
End Sub
End Class
A: For intI As Integer = 0 To DataGridView1.Rows.Count - 1
For intJ As Integer = intI + 1 To DataGridView1.Rows.Count - 1
If DataGridView1.Rows(intI).Cells(0).Value = DataGridView1.Rows(intJ).Cells(0).Value Then
DataGridView1.Rows(intI).Cells(3).Value = DataGridView1.Rows(intI).Cells(1).Value + DataGridView1.Rows(intJ).Cells(1).Value
Exit Sub
End If
Next
Next
Now u just have to adapt the code. I added a 4th row in dgv1 by the way.
A: Solution :
Public Class Form1
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim fd As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String
fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "Excel Files|*.xlsx"
fd.FilterIndex = 2
fd.RestoreDirectory = True
If fd.ShowDialog() = DialogResult.OK Then
strFileName = fd.FileName
End If
Dim dbconnect As New DBConnection(strFileName)
Dim ds As New System.Data.DataSet
Dim tempTable As DataTable
Dim tempnames As String
Dim tempdate As String
Dim tempds As New System.Data.DataSet
ds = dbconnect.ExecuteSql("select * from [Data$]")
tempTable = ds.Tables(0)
tempTable.Columns.Add("OtherNames", Type.GetType("System.String"))
For Each Row As DataRow In tempTable.Rows
tempdate = Row.Item(0)
tempds = dbconnect.ExecuteSql("select [CDR Code] from [Data$] where [Date]=#" + tempdate + "#")
tempnames = ""
For Each Row1 As DataRow In tempds.Tables(0).Rows
tempnames += Row1.Item(0) + " "
Next
Row.Item("OtherNames") = tempnames
Next
DataGridView1.DataSource = tempTable
End Sub
End Class
And DBConnection Class:
Public Class DBConnection
Dim con As System.Data.OleDb.OleDbConnection
Public Sub New(ByVal FilePath As String)
con = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + "; Extended Properties='Excel 12.0 Xml;HDR=YES';")
End Sub
Protected Overrides Sub Finalize()
MsgBox("Connection Closed")
con.Close()
End Sub
Public Function ExecuteSql(ByVal sql As String) As System.Data.DataSet
Dim da As New System.Data.OleDb.OleDbDataAdapter(sql, con)
Dim ds As New System.Data.DataSet
da.Fill(ds)
Return ds
End Function
End Class
| |
doc_23532985
|
The TParallel.For loops are very simple:
TParallel.For(0, inImage.Height -1,
Procedure(ty : integer)
begin
SomeProcedure(ty);
end);
If I create a Delphi application with exactly the same code, everything works perfectly.
After doing a lot of research and debugging, it looks like there is a deadlock which is preventing the C++ application from exiting when FreeLibrary is called, but I can't find where the problem is in TParallel.
Just to summarise the situation:
*
*The TParallel.For loops all complete and produce the correct results.
*The exact same TParallel.For code in a Delphi .exe works correctly.
*The DLL is loaded and the functions are called and perform correctly from within the C++ application.
*The C++ application will exit correctly if there are no TParallel.For loops.
*The C++ application will hang if there are TParallel.For loops.
*I am guessing that there is a deadlock which occurs when FreeLibrary is called.
*If I use the OTL threading library, everything works as it should.
My questions are:
Has anyone else experienced this behaviour?
What is a good debugging strategy to find a deadlock in this situation?
Any advice is greatly appreciated.
UPDATE
OK, so if you want Minimal, Complete and Verifiable example, here you go (thank you Stephen Ball):
library ADelphiDLL;
uses
System.SysUtils, System.Classes, Threading, SyncObjs;
function IsPrime (N: Integer): Boolean;
var
Test: Integer;
begin
IsPrime := True;
for Test := 2 to N - 1 do
if (N mod Test) = 0 then
begin
IsPrime := False;
break; {jump out of the for loop}
end;
end;
function Prime(Max : integer) : boolean;
var
tot : integer;
begin
tot := 0;
TParallel.For(1, Max, procedure (I: Integer)
begin
if IsPrime (I) then
TInterlocked.Increment (Tot);
end);
return true;
end;
exports Prime;
begin
IsMultiThread := True;
end.
in C++:
#include "stdafx.h"
typedef bool(__stdcall *primesf)(int);
void main()
{
HINSTANCE hGetDLL = LoadLibrary(L"ADelphiDLL.dll");
primesf primes = (primesf)GetProcAddress(hGetProcIDDLL, "Primes");
bool result = primes(100);
FreeLibrary(hGetDLL);// <-- Hangs here forever
}
In response to the very "helpful" comments, "there is a defect in the code " and "debug it yourself", thank you, that is what I have been doing for a too long a time. So, if there is no help forthcoming here, I will try and get permission to switch to OTL, which does work in the DLL in question.
UPDATE 2
OTL works exactly as expected. So, yes, there is a "defect in the code". I give up. I will recommend abandoning Delphi altogether and then we can move everything over to C++ and C#. That has to be a much better short (and long term) solution.
A: I have seen an issue similar to this, although i was using Delphi 10.0 Seattle, and a Delphi EXE loading a Delphi DLL.
Anyway, the solution that I came up with is the following:
*
*In your Delphi DLL, first create your own thread pool.
*Use the overloaded version of TParallel.For that takes a thread pool object as its last parameter, and provide your own thread pool object.
*Before unloading your Delphi DLL, make sure to free your thread pool object.
This approach solved the problem for me.
TParallel.For documentation:
http://docwiki.embarcadero.com/Libraries/Berlin/en/System.Threading.TParallel.For
Example pseudo-code:
MyPool: TThreadPool;
MyPool := TThreadPool.Create;
TParallel.For(1, Max, procedure (I: Integer)
begin
if IsPrime (I) then
TInterlocked.Increment (Tot);
end,
MyPool
);
MyPool.Free;
| |
doc_23532986
|
However, on WAS ND, we don't see the properties wl.analytics.queues or wl.analytics.queue.size available for either our MobileFirst project WAR, or the MobileFirst administration WAR.
How can we set these JNDI properties?
A: As of MobileFirst Platform v7.0, this JNDI is no longer available.
The process of forwarding logs to the MFP Analytics server has been optimized in such a way that setting this property is unnecessary. Your logs should be visible in your MFP Operational Analytics console in close to real time.
| |
doc_23532987
|
I need to be able to accept connections from c# running on another computer, I really don't care what technology I use as long as I can trigger javascript events on the "server" browser.
A: You can't start "real" webserver in a browser (e.i there is no API and you are not allowed for security reasons to bind to and listen TCP port). However, if you connect to a HTTP server wich acts as a "bus" and forwards messages to you then you in essence have the same functionality. That's how browserver works.
| |
doc_23532988
|
[WebMethod]
public string TrelloCallback()
{
//connect to database
//do stuff
//return "OK"
}
However this fails immediately, even if my code only consists of "return OK". I have used Applications such as Postman (https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en) and have successfully sent both post and get request to TrelloCallback using the url excample.com/excample2.asmx/TrelloCallback, however requests from Trello simply fail.
If anyone has any idea about what could be causing this problem, or has solutions for a workaround I would be very grateful.
p.s.
The payload is of the form:
{
action: { ... }//Action (comment, move)
model: { ... }//Basic information
}
A: First, you have to make sure you have the line for ScriptService
namespace MyName
{
...
[ScriptService]
...
public class MyClass: MyWebService
{
...
Then you only need to read through the stream to get the Body
StreamReader reader = new StreamReader(Context.Request.InputStream);
Context.Request.InputStream.Position = 0;
String Body= reader.ReadToEnd().ToString();
Context.Request.XXX provides many useful messages for interoperating the request you received.
For example - Context.Request.Headers, Context.Request.RawUrl, and Context.Request.HttpMethod.
| |
doc_23532989
|
Before adding the attribute [ApiExplorerSettings(IgnoreApi = true)]on my api actions I was able to see the models / schema in the swagger UI.
This is how I have configured swagger
Startup.cs
ConfigureServices
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "My Working API",
Description = "All Information related to API",
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
Configure
app.UseSwagger();
app.UseSwaggerUI(c =>
{
string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v1/swagger.json", "API v1");
});
app.UseStaticFiles();
DBContext
/// <summary>
///
/// </summary>
public class MyDBContext: DbContext
{
/// <summary>
/// My Product DB
/// </summary>
public MyDBContext()
{
}
/// <summary>
/// My Product information DB
/// </summary>
/// <param name="options"></param>
public MyDBContext(DbContextOptions<MyDBContext> options)
: base(options)
{
}
/// <summary>
/// Product Model
/// </summary>
public virtual DbSet<Product> Product{ get; set; }
}
Am I missing anything here?
A: For Swagger to show the "Schemas" (Models) you need to use it in code.
Before: [Member object not used within API route]
After: [Member object used within API route]
| |
doc_23532990
|
for(i=0; num>0; i++)
{
a[i]=num%2;
num= num/2;
}
I am working on decimal to binary conversion. I can convert themi want answer in 8 bits. And it gives me as, for example x =5, so output will be 101, but i want 00000101. Is there any way to append zeros in the start of array, without using any library.
A: The health clinic manages patients and the patient manages their own data.
You can run/check this code in https://repl.it/@JomaCorpFX/StdGetLine#main.cpp
Code
#include <iostream>
#include <string>
#include <vector>
class Patient
{
private:
std::string phoneNumber;
std::string name;
std::string email;
float weight;
float height;
public:
void SetName(const std::string &name)
{
this->name = name;
}
void SetEmail(const std::string &email)
{
this->email = email;
}
void SetPhoneNumber(const std::string &phoneNumber)
{
this->phoneNumber = phoneNumber;
}
void SetWeight(const float &weight)
{
this->weight = weight;
}
void SetHeight(const float &height)
{
this->height = height;
}
std::string GetName()
{
return this->name;
}
std::string GetEmail()
{
return this->email;
}
std::string GetPhoneNumber()
{
return this->phoneNumber;
}
float GetWeight()
{
return this->weight;
}
float GetHeight()
{
return this->height;
}
public:
};
class HealtClinic
{
private:
std::vector<Patient> patients;
public:
void AddPatient()
{
Patient p;
std::cout << "\nEnter name : ";
std::string sdata;
std::getline(std::cin, sdata);
p.SetName(sdata);
std::cout << "\nEnter email : ";
std::getline(std::cin, sdata);
p.SetEmail(sdata);
std::cout << "Enter phone number : ";
std::getline(std::cin, sdata);
p.SetPhoneNumber(sdata);
int idata;
std::cout << "Enter weight in kg : ";
std::cin >> idata;
p.SetWeight(idata);
std::cout << "Enter height in meters: ";
std::cin >> idata;
p.SetHeight(idata);
patients.push_back(p);
}
void ShowPatients()
{
std::cout << "--- PATIENTS ---" << std::endl;
for (int i = 0; i < patients.size(); i++)
{
std::cout << "--- " << i << std::endl;
std::cout << "Name: " << patients[i].GetName() << std::endl;
std::cout << "Email: " << patients[i].GetEmail() << std::endl;
std::cout << "Phone number: " << patients[i].GetPhoneNumber() << std::endl;
std::cout << "Weight: " << patients[i].GetWeight() << std::endl;
std::cout << "Height: " << patients[i].GetHeight() << std::endl;
std::cout << std::endl;
}
}
};
int main()
{
HealtClinic clinic;
clinic.AddPatient();
clinic.ShowPatients();
return EXIT_SUCCESS;
}
Output
Enter name : Joma
Enter email : joma@email.com
Enter phone number : 123456789
Enter weight in kg : 88
Enter height in meters: 1.8
--- PATIENTS ---
--- 0
Name: Joma
Email: joma@email.com
Phone number: 123456789
Weight: 88
Height: 1
| |
doc_23532991
|
A: It took me a while to find a way to install PHP 5.6 by using https://github.com/JVerstry/openshift-php-framework-stack , but the sad thing is that when I tried to install Laravel 5.1 based on it, it automatically used OpenShift's own PHP (5.3.3). Even I tried export my own PHP into path, the installation would still fail.
I gave it up. A pity that Openshift doesn't offer Laravel 5.1 support. I switched to DigitalOcean and it saved my day. I am using Laravel 5.2.37 & PHP 7.0.7 on DigitalOcean now.
A: *
*Create HHVM Application
*Then Clone the current application repo in local machine
Create laravel app
*
*using laravel installer
laravel new test
*using composer
composer create-project --prefer-dist laravel/laravel test
Then move all file including hidden files from test to laravel52 (cloned folder) folder
*
*remove /vendor and .env line from .gitgnore file
Edit NGINX server config file
which is located at
config/nginx.d/default.conf.erb
Change:
root <%= ENV['OPENSHIFT_REPO_DIR'] %><%= ENV['NGINX_WWW_ROOT'] %>;
To:
root <%= ENV['OPENSHIFT_REPO_DIR'] %>public;
change:
location / {
try_files $uri $uri/ =404;
}
To:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
save default.conf.erb file and git commit
git add .
git commit -am "fix nginx server"
git push
After that visit site, you should see laravel welcome page.
Note: When you connect database, don't forget to put openshift database variable in .env file.
source ubutnu nepal blog
| |
doc_23532992
|
public static void main( String[] args ) throws Exception {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
App.file = fc.getSelectedFile();
//This is where a real application would open the file.
System.out.println("Opening: " + App.file.getName() + ".");
} else {
System.out.println("Open command cancelled by user.");
}
workbook = Workbook.getWorkbook(App.file);
Sheet sheet = workbook.getSheet(1);
Cell cell1 = sheet.getCell(4, 27);
System.out.println(cell1.getContents());
Cell cell2 = sheet.getCell(4, 28);
System.out.println(cell11.getContents());
App.eStop = false;
int i = 0 ;
while (App.eStop == false) {
try {
cell3 = sheet.getCell(9, i);
System.out.println(cell3.getContents());
} catch (Exception e) {
App.eStop = true;
};
i++;
}
System.out.println("done");
and i pasting this values to some other tool using the below command
psess.GetPS().SendKeys(cell1.getContents(), 8, 18);
All the values from the excel file are numbers.
Sometimes i get decimal numbers (like 2.02).
Because i can't change the excel file, its possible to tell to my app to ignore the .02 and keep only the 2 for example?
A: If the Excel file has proper formats set for the cells that you are trying to read, you can try to apply the format and thus get the values in the same format as Excel displays them.
See e.g. the following example from the documentation at http://poi.apache.org/spreadsheet/eval.html
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
// suppose your formula is in B3
CellReference cellReference = new CellReference("B3");
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
CellValue cellValue = evaluator.evaluate(cell);
switch (cellValue.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cellValue.getBooleanValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cellValue.getNumberValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cellValue.getStringValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
break;
// CELL_TYPE_FORMULA will never happen
case Cell.CELL_TYPE_FORMULA:
break;
}
A: Have-you try a Math.round() ? Or a new BigDecimal(cell3.getContents()).setScale(1) ?(if you want to keep the first digit)
A: Thank you for the help.
Finally i solve my problem using the bellow:
Cell cell4 = sheet.getCell(3, 7);
String number3 = cell4.getContents().split("\\.")[0].replaceAll("\\,","");
System.out.println(number3);
A: import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.math.BigDecimal;
Row currentRow = rowIterator.next();
currentRow.getCell(4).setCellType(XSSFCell.CELL_TYPE_NUMERIC);
Double doubleValue = currentRow.getCell(4).getNumericCellValue();
BigDecimal bd = new BigDecimal(doubleValue.toString());
long lonVal = bd.longValue();
String actualNumber = Long.toString(lonVal).trim();
| |
doc_23532993
|
I would have though of having instances of all the forms in a static class and have the application loop through the status of all the forms each time the user hides a form and if all are hidden then exit the application. Is this a good way to do it?
A: Usually in this situation you would create a ApplicationContext and you would pass that in to Application.Run( instead of a specific form.
If you look at the MSDN page for ApplicationContext it has a example of starting two forms then only closing the program when both forms get closed. You can make your own program use whatever logic you want, for example using hiding instead closing to trigger the ExitThread() call.
| |
doc_23532994
|
A
- static Map<String, A>
- String name
- String aInfo1
- String aInfo2
B
- static Map<String, B>
- String name
- String bInfo1
- String bInfo2
C
- A aObject
- B bObject
Now, in my XML, I define a list of tags for A objects and B objects and then I define tags for C objects which refer to A and B objects using there name field.
I have two requirements:
*
*populate static maps in A and B while reading the A and B objects from XMLs. The maps will contain a mapping of A.name to A, and B.name to B respectively.
*populate C objects by reading the A.name and B.name from XML tag and then using the maps defined in A and B objects.
I have read about some Java frameworks like JAXB but I am unable to come up with a way to create such type of objects from my XML. Is there a framework in Java which can do this out-of-the box or with minimum logic?
Edit:
There is another requirement:
I need to define D and E objects of the form
D
- Map<A, E>
I would define E objects similar to how servlets are defined in web.xml i.e. first define the name and class for the E class and then use the name for E at some other place. Additionally, pass parameters to instantiate E objects. The tag would look like:
<E>
<name>queryProcessor</name>
<class>com.mydomain.QueryProcessor</class>
</E>
Now this would be used while defining content of Map in D
<D>
<map>
<A>name_of_some_A_object</A>
<E name="queryProcessor">
<param1>name_of_some_B_object</param1>
<param2>name_of_some_B_object</param2>
</E>
<A>name_of_some_A_object</A>
<E name="queryProcessor">
<param1>name_of_some_B_object</param1>
<param2>name_of_some_B_object</param2>
</E>
</map>
</D>
Essentially the map in D will be populated by instantiating a class of base type E with the parameters passed to it and an object of A, referred by its name.
A: *
*Specify the correct XML format with an XSD
*Generate the JAXB classes
(You could do it also the other way around, if you are familiar with JAXB annotations and want to control the interface with Java rather than with an XSD).
Note: static Maps is most likely not what you want to use. If you explain more about what problem you want to solve we might be able to point you out some alternative ways
Edit:
Are you talking about the format of the XML? Or why I need XML at all? I need XML for the ability to make my applications configurable outside of Java.
It looks like you're re-inventing the wheel. Have a look at Spring and see if it fits your needs. If it doesn't, explain why.
A: From what you describe this could be done with a common framework such as Spring, either by you changing your XML or generate a XSTL which creates a Spring XML config file from your XML.
Spring Core documentation is probably enough to get you started. An example of the XML would be
<bean id="beanOneId" class="the.bean.Class">
<property name="someProperty" value="staticValue">
<property name="someOtherProperty" ref="beanTwoId">
</bean>
<bean id="beanTwoId" class="the.otherbean.Class">
<property name="someOtherProperty" ref="beanOneId">
<property name="someOtherProperty" ref="beanThreeId">
</bean>
But what you describe should not be too hard with reflection. Assuming that none of the other objects need a reference in the constructor (but rather as setX) I would start by scanning the xml, create and store all objects with their names and remember a list of "connections" so be made. After all objects are created do all connections in the connection list.
A: Maybe you want to have a look at XStream: http://x-stream.github.io/
It is a good library to marshal and unmarshal objects to and from XML, and does nothing more (unlike Spring). Like example in http://x-stream.github.io/tutorial.html, You can load objects from XML as easy as:
Person newJoe = (Person)xstream.fromXML(xml);
In order for XStream to understand your XML, you need to setup some alias like http://x-stream.github.io/alias-tutorial.html described.
XStream alone will not be able to solve your problem completely, mainly due to the two static maps. However you can let XStream to load a list of As and Bs from the XML, then build the two maps from the list.
For object C referencing A and B, you can read the following tutorial talking about object reference: http://x-stream.github.io/graphs.html. If it does not suit your need, you can always easily build another Class to read necessary information from XML using XStream, like
public class CInfo {
public String aName;
public String bName
}
And construct C instances using CInfo. Given you already have name to instance map of A and B, it will be trivial.
| |
doc_23532995
|
A: You have to call the gdk_flush function to actually send the command to the server. Note that this is only needed because of the sleep call which you shouldn't use anyway (application becomes unresponsive during the time); had you used g_timeout_add, gdk would flush the X command queue automatically.
About making widgets visible: this is an operation that requires bidirectional communication between the program and the server, basically, the server asks the client to paint the window and the client responds with commands to draw it. In Gtk, this means you have to let the main loop run. Either:
*
*setup a timeout for the sleep with gtk_timeout_add, and do the rest of the work in the callback
*run a nested main loop with gtk_main (return from it with gtk_main_quit, possibly from a callback of a timeout
*run the loop iterations with gtk_main_iteration. This is the least promising approach, because it will be hard to combine it with the sleep.
| |
doc_23532996
|
I had renamed some of the files when I copied them over, so that could have something to do with it. Searching online I see people solved similar issues by using the file > read class files in IB, but IB is not standalone in new versions of xcode and this option doesn't appear on the xcode file menu.
Any ideas?
A: I know this is old but just in case someone runs into this. I solved it by going to "Identity Inspector" and changing the "Class" drop down to the correct file. So after copying or recreating a project don't for get to re-associate the Identity Inspector Class.
| |
doc_23532997
|
static public void starttimer() {
t1 = date3 - date;
progressbarstatus ();
starttimercd ();
timer = new CountDownTimer ( totalSeconds, 1000 ) {
@Override
public void onTick(long millisUntilFinished) {
if (isclicked = true) {
secondc = totalSeconds - millisUntilFinished;
mEndtime = System.currentTimeMillis () + secondc;
countdowntext ();
}
if (isclicked = false) {
secondc = System.currentTimeMillis () - mEndtime;
countdowntext ();
timer.cancel ();
}
percentage = Math.round ( secondc / t1 * 100 );
tvp.setText ( percentage + "%" );
}
@Override
public void onFinish() {
timerrunning = false;
}
}.start ();
}
i have tried to put boolean on the on the listener.
btn_start.setOnClickListener ( new View.OnClickListener () {
@Override
public void onClick(View v) {
isclicked = true;
starttimer ();
}
});
the problem is when i run the app the timer is running by default. Does anyone have any solution on how to make the timer runs only when the button is clicked and how to put boolean on onclicklisterner? Appreciated if anyone could help.
A: You shouldn't put boolean in onclick function. Put if out of starttimer. When the boolean is true function will run regardless of boolean to be true or false after that.
| |
doc_23532998
|
how much time before the program lets say c# int and the database INT value no longer support each other, or how long before the INT value is used up, or how large is this auto generated id field for a database, lets say sqlite?
When you try to insert a new record, and the data base auto generated row id is used up, what happens; no more insert?
thanks
[EDIT]
Do you look at the ID values of your tables once in a while?
Most people don't know that if for some reason you app does alot of insert and delete, then a new ID value is generated each time you insert. is seems that databases does not reuse deleted ID, so in that case a database with just 1000 records can use up that value if the app does alot of insert and deleteing!!!
The reason i asked this question is this, normally in apps you frequently make use of the ID value, to keep track of records; i do always.
lest say i did somthing like this
int record_id= reader("id").value;
when will i get an overflow error?
is the database INT the same as int in all programing environment?
A: I don't know about sqlite but for the SQL Server the maximum values look like this:
max int (32 bit) = 2,147,483,647
max bigint (64 bit) = 9,223,372,036,854,775,807
If at some point you've used up the value range then an attempt to insert a new record will fail. It will say the following:
Arithmetic overflow error converting IDENTITY to data type int. Arithmetic overflow occurred.
Again, have no idea about sqlite but in SQL Server the failed transactions will also consume a value from the pool. If you attempt an insert and the containing transaction is rolled back then the generated IDENTITY value will not be returned to the pool. If you have transactions failing regularly then that will also waste a certain ( though very small) percentage of the values.
Most likely sqlite works in a similar way.
A: The maximum size for an INT in SQLite is 8-bytes, which is a very, very big number. I find it hard to imagine an application which used SQLite where you could actually "run out" of INTs. You would have to be running some very large data-warehousing system for this to happen, which you are not going to be doing with SQLite. So don't worry!
| |
doc_23532999
|
But mtools still give me this error:
Error converting to codepage 850 Invalid argument
Error setting code page
Cannot initialize 'A:'
why?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.