text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How to extract particular properties from generic list based on property name sent as string array? I have a Generic List of type List<InstanceDataLog> which has huge number of properties in it. I want to pass names of a few properties to a method and want to extract a refined List from within this list.
public void Export(string col) //a,b,c
{
string [] selectedcol = col.Split(',');
var grid = new GridView();
var data = TempData["InstanceDataList"];
List<InstanceDataLog> lst = new List<InstanceDataLog>();
List<EToolsViewer.APIModels.InstanceDataLog> lstrefined = new List<InstanceDataLog>();
lst= (List<EToolsViewer.APIModels.InstanceDataLog>)TempData["InstanceDataList"];
var r= lst.Select(e => new {e.a, e.b}).ToList();// I would like to replace these hardcoded properties with names of properties present in `selectedcol `
grid.DataSource =r;
grid.DataBind();
}
To clear things up further, suppose InstanceDataLog has 5 properties : a,b,c,d,e I would like pass a,b and be able to extract a new list with only properties a,b
EDIT:
$('#export').mousedown(function () {
window.location = '@Url.Action("Export", "TrendsData",new { col = "a,b,c" })';
});
A: To keep compiler type/name checking suggest to pass a Func<InstanceDataLog, TResult> instead of array of names
public void Export<TResult>(Func<InstanceDataLog, TResult> selectProperties)
{
var grid = new GridView();
var data = TempData["InstanceDataList"];
var originalList = (List<InstanceDataLog>)TempData["InstanceDataList"];
var filteredList = originalList.Select(selectProperties).ToList();
grid.DataSource = filteredList;
grid.DataBind();
}
Then use it:
Export(data => new { Id = data.Id, Name = data.Name });
A: You could use such method to get properties:
private object getProperty(EToolsViewer.APIModels.InstanceDataLog e, string propName)
{
var propInfo =typeof(EToolsViewer.APIModels.InstanceDataLog).GetProperty(propName);
return propInfo.GetValue(e);
}
and with another function you could get all properties you want:
private dynamic getProperties(string[] props, EToolsViewer.APIModels.InstanceDataLog e )
{
var ret = new ExpandoObject() as IDictionary<string, Object>;;
foreach (var p in props)
{
ret.Add(p, getProperty(e, p));
}
return ret;
}
The problem occurs if you try to assign DataSource with expando object. Solution is described hier:
Binding a GridView to a Dynamic or ExpandoObject object
We do need one more method:
public DataTable ToDataTable(IEnumerable<dynamic> items)
{
var data = items.ToArray();
if (data.Count() == 0) return null;
var dt = new DataTable();
foreach (var key in ((IDictionary<string, object>)data[0]).Keys)
{
dt.Columns.Add(key);
}
foreach (var d in data)
{
dt.Rows.Add(((IDictionary<string, object>)d).Values.ToArray());
}
return dt;
}
and use it:
var r = lst.Select(e => getProperties(selectedcol, e)).ToList();
grid.DataSource = ToDataTable(r);
The same thing, but ready to run for LinqPad:
void Main()
{
var samples = new[] { new Sample { A = "A", B = "B", C = "C" }, new Sample { A = "A1", B = "B2", C = "C1" } };
var r = samples.Select(e => getProperties(new[] {"A", "C", "B"}, e)).ToList();
r.Dump();
}
private object getProperty(Sample e, string propName)
{
var propInfo = typeof(Sample).GetProperty(propName);
return propInfo.GetValue(e);
}
private dynamic getProperties(string[] props, Sample e)
{
var ret = new ExpandoObject() as IDictionary<string, Object>; ;
foreach (var p in props)
{
ret.Add(p, getProperty(e, p));
}
return ret;
}
public class Sample
{
public string A { get; set;}
public string B { get; set;}
public string C { get; set;}
}
With output:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40863405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting started with JSON in .net and mono I would like to keep a custom configuration file for my app and JSON seems like an appropriate format*.
I know that there are JSON libraries for .NET, but I couldn't find a good comparative review of them. Also, my app needs to run on mono, so it's even harder to find out which library to use.
Here's what I've found:
*
*JSON.NET
*JSONSharp
I remember reading that there is a built-in way to (de)serialize JSON as well, but I don't recall what it is.
What library would be easiest to use in mono on linux? Speed isn't critical, as the data will be small.
*Since the app runs on a headless linux box, I need to use the command line and would like to keep typing down to a minimum, so I ruled out XML. Also, I couldn't find any library to work with INF files, I'm not familiar with standard linux config file formats, and JSON is powerful.
A: The DataContractJsonSerializer can handle JSON serialization but it's not as powerful as some of the libraries for example it has no Parse method.
This might be a way to do it without libraries as I beleive Mono has implemented this class.
To get more readable JSON markup your class with attributes:
[DataContract]
public class SomeJsonyThing
{
[DataMember(Name="my_element")]
public string MyElement { get; set; }
[DataMember(Name="my_nested_thing")]
public object MyNestedThing { get; set;}
}
A: Below is my implementation using the DataContractJsonSerializer. It works in mono 2.8 on windows and ubuntu 9.04 (with mono 2.8 built from source). (And, of course, it works in .NET!) I've implemented some suggestions from Best Practices: Data Contract Versioning
. The file is stored in the same folder as the exe (not sure if I did that in the best manner, but it works in win and linux).
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using NLog;
[DataContract]
public class UserSettings : IExtensibleDataObject
{
ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; }
[DataMember]
public int TestIntProp { get; set; }
private string _testStringField;
}
public static class SettingsManager
{
private static Logger _logger = LogManager.GetLogger("SettingsManager");
private static UserSettings _settings;
private static readonly string _path =
Path.Combine(
Path.GetDirectoryName(
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName),
"settings.json");
public static UserSettings Settings
{
get
{
return _settings;
}
}
public static void Load()
{
if (string.IsNullOrEmpty(_path))
{
_logger.Trace("empty or null path");
_settings = new UserSettings();
}
else
{
try
{
using (var stream = File.OpenRead(_path))
{
_logger.Trace("opened file");
_settings = SerializationExtensions.LoadJson<UserSettings>(stream);
_logger.Trace("deserialized file ok");
}
}
catch (Exception e)
{
_logger.TraceException("exception", e);
if (e is InvalidCastException
|| e is FileNotFoundException
|| e is SerializationException
)
{
_settings = new UserSettings();
}
else
{
throw;
}
}
}
}
public static void Save()
{
if (File.Exists(_path))
{
string destFileName = _path + ".bak";
if (File.Exists(destFileName))
{
File.Delete(destFileName);
}
File.Move(_path, destFileName);
}
using (var stream = File.Open(_path, FileMode.Create))
{
Settings.WriteJson(stream);
}
}
}
public static class SerializationExtensions
{
public static T LoadJson<T>(Stream stream) where T : class
{
var serializer = new DataContractJsonSerializer(typeof(T));
object readObject = serializer.ReadObject(stream);
return (T)readObject;
}
public static void WriteJson<T>(this T value, Stream stream) where T : class
{
var serializer = new DataContractJsonSerializer(typeof(T));
serializer.WriteObject(stream, value);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3926079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Need a way to add a button to this android xamarin sample I used this sample here : https://github.com/xamarin/xamarin-forms-samples/blob/master/CustomRenderers/View/Droid/CameraPreview.cs
to get a camera feed on my project. On the IOS part, I easily added a takepicture button over the camera feed. Im trying to do the exact same thing here on the android side but I cant find a way on how to do that... Everything I tried render a blank page or throw an error.
What is the simpliest way to add a button on this camera feed? Thanks in advance
A: You could use RelativeLayout in the MainPage. Then you add the Button and the CameraPreview into it. For example:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:CustomRenderer;assembly=CustomRenderer"
x:Class="CustomRenderer.MainPage"
Padding="0,20,0,0"
Title="Main Page">
<ContentPage.Content>
<RelativeLayout>
<local:CameraPreview
Camera="Rear" x:Name="Camera"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,Property=Width,Factor=1,Constant=0}"
RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent,Property=Height,Factor=1,Constant=0}"/>
<Button x:Name="button"
Text="Button" Clicked="button_Clicked"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView,ElementName=Camera,Property=Height,Factor=.85,Constant=0}"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToView,ElementName=Camera,Property=Width,Factor=.05,Constant=0}"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,Property=Width,Factor=.9,Constant=0}"
RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent,Property=Height,Factor=.125,Constant=0}" />
</RelativeLayout>
</ContentPage.Content>
</ContentPage>
And you could use the MessagingCenter to fired the click event of CameraPreview.
For example, in the renderer:
protected override void OnElementChanged(ElementChangedEventArgs<CustomRenderer.CameraPreview> e)
{
base.OnElementChanged(e);
if (Control == null)
{
cameraPreview = new CameraPreview(Context);
SetNativeControl(cameraPreview);
MessagingCenter.Subscribe<MainPage>(this, "ButtonClick", (sender) => {
if (cameraPreview.IsPreviewing)
{
cameraPreview.Preview.StopPreview();
cameraPreview.IsPreviewing = false;
}
else
{
cameraPreview.Preview.StartPreview();
cameraPreview.IsPreviewing = true;
}
});
}
if (e.OldElement != null)
{
// Unsubscribe
cameraPreview.Click -= OnCameraPreviewClicked;
}
if (e.NewElement != null)
{
Control.Preview = Camera.Open((int)e.NewElement.Camera);
// Subscribe
cameraPreview.Click += OnCameraPreviewClicked;
}
}
And in the Button click event:
private void button_Clicked(object sender, System.EventArgs e)
{
MessagingCenter.Send<MainPage>(this, "ButtonClick");
}
A: This worked for me.
In the CameraPreview class just add a new View member (cameraLayoutView) and a button:
public sealed class CameraPreview : ViewGroup, ISurfaceHolderCallback
{
View cameraLayoutView;
global::Android.Widget.Button takePhotoButton;
}
Then in the constructor instantiate this view and button:
public CameraPreview (Context context)
: base (context)
{
surfaceView = new SurfaceView (context);
AddView (surfaceView);
Activity activity = this.Context as Activity;
cameraLayoutView = activity.LayoutInflater.Inflate(Resource.Layout.CameraLayout, this, false);
AddView(cameraLayoutView);
takePhotoButton = this.FindViewById<global::Android.Widget.Button>(Resource.Id.takePhotoButton);
takePhotoButton.Click += TakePhotoButtonTapped;
windowManager = Context.GetSystemService (Context.WindowService).JavaCast<IWindowManager> ();
IsPreviewing = false;
holder = surfaceView.Holder;
holder.AddCallback (this);
}
async void TakePhotoButtonTapped(object sender, EventArgs e)
{
//handle the click here
}
protected override void OnLayout (bool changed, int l, int t, int r, int b)
{
var msw = MeasureSpec.MakeMeasureSpec (r - l, MeasureSpecMode.Exactly);
var msh = MeasureSpec.MakeMeasureSpec (b - t, MeasureSpecMode.Exactly);
surfaceView.Measure (msw, msh);
surfaceView.Layout (0, 0, r - l, b - t);
cameraLayoutView.Measure(msw, msh);
cameraLayoutView.Layout(0, 0, r - l, b - t);
}
Also add this layout in Resources/Layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextureView
android:id="@+id/textureView"
android:layout_marginTop="-95dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/toggleFlashButton"
android:layout_width="37dp"
android:layout_height="37dp"
android:layout_gravity="top|left"
android:layout_marginLeft="25dp"
android:layout_marginTop="25dp"
android:background="@drawable/NoFlashButton" />
<Button
android:id="@+id/switchCameraButton"
android:layout_width="35dp"
android:layout_height="26dp"
android:layout_gravity="top|right"
android:layout_marginRight="25dp"
android:layout_marginTop="25dp"
android:background="@drawable/ToggleCameraButton" />
<Button
android:id="@+id/takePhotoButton"
android:layout_width="65dp"
android:layout_height="65dp"
android:layout_marginBottom="15dp"
android:layout_gravity="center|bottom"
android:background="@drawable/TakePhotoButton" />
</FrameLayout>
And the button icons in Resources/drawable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50767653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Not able to load keycloak authentication page from application, calling protected resource with ajax request I have configured keycloak for IAM with gatekeeper as a proxy. When I call protected resource from my angular application through ajax request, it's not redirecting me to login page of keycloak, although in browser request call its showing me request going for login page. Any help would be much appreciated.
enter image description here
A: To me, it sounds like you have set up Gatekeeper to only protect your backend resources? Otherwise, the redirect would happen when you try to access your frontend.
If you are running your frontend as a separate application you need to obtain a Bearer token from Keycloak and pass it along in your ajax request. You can use the JS adapter to do that: https://www.keycloak.org/docs/latest/securing_apps/#_javascript_adapter
In that case, you should also configure Gatekeeper with the --no-redirect option, so that it denies any unauthorized request.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63751399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Required Field Missing. PHP Paypal REST API I'm currently trying to use the PHP PayPal REST API. However, it seems I am unable to pass a list of items through a transaction because "required field(s) are missing".
$item = new Item();
$item->setQuantity("1");
$item->setName("stuff");
$item->setPrice("305.00");
$item->setCurrency("USD");
$amount = new Amount();
$amount->setCurrency("USD");
$amount->setTotal("305.00");
$item_list = new ItemList();
$item_list->setItems(array($item));
$transaction = new Transaction();
$transaction->setAmount($amount);
$transaction->setDescription("This is incredibly awesome.");
$transaction->setItem_list($item_list);
I've filled all the fields that Paypal's documentation deems as "required" as per "Common Objects" in the documentation (https://developer.paypal.com/webapps/developer/docs/api/#common-objects). But I am being thrown this error when I try to redirect to Paypal to start the transaction:
Exception: Got Http response code 400 when accessing
https://api.sandbox.paypal.com/v1/payments/payment. string(269)
"{"name":"VALIDATION_ERROR","details":[{"field":"transactions[0].item_list.items[0].sku","issue":"Required
field missing"}],"message":"Invalid request - see
details","information_link":"https://developer.paypal.com/docs/api/#VALIDATION_ERROR","debug_id":"9e292fc3a312d"}"
When I comment out $transaction->setItem_list($item_list);, it works properly. So it's obvious that something is missing in the item list or the item. But I can't see what.
Any ideas?
A: the error point you to this:
transactions[0].item_list.items[0].sku
This filed seems to be required i think it just need to put sku in item array so let's do it:
try to add:
$item->setSKU("CODEHERE");
after
$item->setCurrency("USD");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16075411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Argument 1 passed to setArchived() must be an instance of bool, boolean given I have this property
/**
* @ORM\Column(columnDefinition="TINYINT DEFAULT 0 NOT NULL")
*/
private $archived;
on save Doctrine execute this:
/**
* @ORM\PrePersist
* @ORM\PreUpdate
*/
public function updatedDefaults()
{
if($this->getArchived() == null)
{
$this->setArchived(1);
}
}
but I got this error:
Argument 1 passed to setArchived() must be an instance of bool, boolean given
how can I set a boolean object in symfony?
thanks
A: The issue is with your setArchived method : type hints can not be used with scalar types.
You must remove the bool type :
public function setArchived($archived) {
$this->archived = $archived; return $this;
}
(perhaps you write 'bool' instead of 'boolean' when using doctrine:generate:entities ?)
A: Why not use a column type of "boolean"?
/**
* @ORM\Column(type="boolean")
*/
private $archived;
Then in your update function pass true/false instead of 1/0
/**
* @ORM\PrePersist
* @ORM\PreUpdate
*/
public function updatedDefaults()
{
if($this->getArchived() == null)
{
$this->setArchived(true);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24633508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Regex in online test tool works well, but misses many matches when applied in application As the title says, my regex in the online tester works, but it is less effective (i.e. missing some matches) when I use it in my application.
I am working on an application to get quotes from wikiquotes and present them to a user. The regex for determining which blocks of HTML are potential candidates for containing a quote seems fairly reliable. The regex I am using for obtaining the name of the author is problematic. The get_author function contains the regex pattern that seems to be missing matches when run in the browser, even though it successfully matches when used with the online tool. Here is my regex in the tester, with the regex pattern and the HTML string I am parsing..
Note: I am aware that my regex has some mistakes in what it matches/matching too many HTML blocks. That's not my issue here, I will work towards refining the regex once I understand where these discrepancies are coming from.
What is the cause of the issue here?
CODE
$(document).ready(function(){
//Make a call to the war page as soon as the page is loaded and get the page HTML
$.ajax({
url: "https://en.wikiquote.org/w/api.php?",
dataType: "json",
data: {
action: "parse",
page: "War",
origin: "*",
format: "json",
},
method: "GET",
success: function(return_data, status){
html_return = return_data.parse.text["*"];
quote_candidates = get_quote_candidates(html_return);
authors = get_author(quote_candidates);
}
});
});
function get_author(quote_candidates){
authors = [];
var re = /<ul>\n<li>[\w\W]*?<ul>\n<li>[\w\W]*?title="?(w:|wikipedia:)?([\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC .]*)(?=">)/g;
quote_candidates.map(function(quote_candidate){
quote_candidate_html = quote_candidate[0];
author = re.exec(quote_candidate_html);
if(!author){ //Debugging purposes: log all of the quote candidates that weren't matched by the regex
console.log(author);
console.log(quote_candidate_html);
} else {
authors.push(author);
}
});
}
//Get the blocks of HTML in the page that potentially have a quote within them.
function get_quote_candidates(html_string){
quote_candidates = [];
var re = /<ul>\n<li>[\s\S]*?(?=<\/ul>\n<\/li>\n<\/ul>)/g;
console.log(typeof(html_string));
var next_quote_candidate;
while(next_quote_candidate = re.exec(html_string)){
quote_candidates.push(next_quote_candidate);
}
return quote_candidates;
}
Examples of strings that aren't matched in the application, but are matched in the test tool
<ul>
<li>Not with dreams, but with blood and with iron<br />
Shall a nation be moulded to last.
<ul>
<li><a href="/wiki/Algernon_Charles_Swinburne" title="Algernon Charles
Swinburne">Algernon Charles Swinburne</a>, <i>A Word for the Country</i>.
</li>
</ul>
</li>
</ul>
<ul>
<li>Man is the only animal that deals in that atrocity of atrocities, War. He is the only one that gathers his brethren about him and goes forth in cold blood and calm pulse to exterminate his kind. He is the only animal that for sordid wages will march out…and help to slaughter strangers of his own species who have done him no harm and with whom he has no quarrel … and in the intervals between campaigns he washes the blood off his hands and works for "the universal brotherhood of man" — with his mouth.
<ul>
<li><a href="/wiki/Mark_Twain" title="Mark Twain">Mark Twain</a>, <i>The War Prayer</i>.</li>
</ul>
</li>
</ul>
A: I have slept on it and discovered the problem/solution.
TL;DR
*
*Remove the global flag from the regex pattern (I have no need for the global flag here, so I have opted to just remove it); or
*set the lastIndex property back to 0 before each search . i.e.
re.lastIndex = 0;
re.exec(your_string_to_search_goes_here);
Explanation
I had the global flag set but was applying the regex pattern iteratively to each element of an array. The regex object updates the lastIndex property when a match is found, provided the global flag is set. This is useful so that whatever pattern matching function you end up using knows where to start from after each time it matches something in your string.
For my use case, the global flag was totally unnecessary because I had already elementised the strings to search into an array, and I know that if there is to be a match, I expect there to be 1 and only 1, so remembering where the search pattern was last up to is irrelevant - if it doesn't match, move onto the next array element.
More useful threads here:
*
*RegExp.exec() returns NULL sporadically
*Regex.prototype.exec returns null on second iteration of the search
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48841623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to access physical file in OrchardProject? I have a blog that is using the OrchardProject CMS. One thing I noticed is that if I add a file to the root of my website, and access it via www.example.com/test.html, I get a 404 error.
Does OrchardProject have a restriction on this?
A: You need to put a handler entry in the web.config for static files to be served up. By default a 404 is returned for any requests that are not served via a managed handler.
If your file is in the root, then in the Orchard.Web web.config replace
<handlers accessPolicy="Script">
<!-- Clear all handlers, prevents executing code file extensions or returning any file contents. -->
<clear />
<!-- Return 404 for all requests via a managed handler. The URL routing handler will substitute the MVC request handler when routes match. -->
<add name="NotFound" path="*" verb="*" type="System.Web.HttpNotFoundHandler" preCondition="integratedMode" requireAccess="Script" />
<!-- WebApi -->
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
with
<handlers accessPolicy="Script, Read">
<!-- Clear all handlers, prevents executing code file extensions or returning any file contents. -->
<clear />
<add name="TestFile" path="test.html" verb="*" type="System.Web.StaticFileHandler" preCondition="integratedMode" requireAccess="Read" />
<!-- Return 404 for all requests via a managed handler. The URL routing handler will substitute the MVC request handler when routes match. -->
<add name="NotFound" path="*" verb="*" type="System.Web.HttpNotFoundHandler" preCondition="integratedMode" requireAccess="Script" />
<!-- WebApi -->
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
The path can use wildcards if you want to allow access to multiple files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29663994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does cv2 mask + imwrite reduce image detail? I have a 1.17 Gb tiff ('heatmap') which I want to crop to the outline of another 425.7 Mb tiff ('pavement'). The heatmap contains subtle color shading that I want to keep in the final image. I'm using a bitwise_and operation to apply the pavement image as a mask, and using cv2.imwrite to save. But the resulting tiff lacks the subtle shading and is only 10.5 Mb. That seems like a big reduction in size and is probably why the final image has less detail.
What can I do to retain the subtle shading of the input in the output image?
import sys
import cv2
import numpy as np
heatmapfile = "heatmap.tif"
pavementfile = "pavement.tif"
output = "masked_heatmap.tif"
heatmap = cv2.imread(heatmapfile,-1)
pavement = cv2.imread(pavementfile,0)
# apply thresholding to create mask
ret, binimg = cv2.threshold(pavement,1,255,cv2.THRESH_BINARY)
# make binary image same size as heatmap, needed for bitwise_and
bin_4ch = cv2.cvtColor(binimg,cv2.COLOR_GRAY2BGRA)
# mask the heatmap and save
hm_masked = cv2.bitwise_and(heatmap,bin4ch)
cv2.imwrite(output, hm_masked)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64163118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: conan install --build fails due to mismatching versions even after changing default I am using conan to handle dependencies and I have already been able to compile and run the project by running individual steps like source and build.
I however want to be able to install and build in a single step, and for that purpose I do:
conan install . -if build -s build_type=Debug --build
In which case for some packages I get:
Compiler version specified in your conan profile: 10.3
Compiler version detected in CMake: 9.3
Please check your conan profile settings (conan profile show
[default|your_profile_name])
P.S. You may set CONAN_DISABLE_CHECK_COMPILER CMake variable in order to
disable this check.
Now I can change the profile settings to match the requested compiler settings, but then other, different, packages start complaining about mismatching compiler versions. i.e. some packages want version 9.3, others version 10.3, others version 9...
Considering the packages dependencies already link with my executable if I just run the build steps individually, I am not sure why I am getting this catch 22 behaviour.
I tried a suggestion in the comments by adding this to my conanfile.py
def configure(self):
# gcc compiler version
defs = {}
if self.settings.compiler == "gcc":
defs["CMAKE_C_COMPILER"] = f"gcc-{self.settings.compiler.version}"
defs["CMAKE_CXX_COMPILER"] = f"g++-{self.settings.compiler.version}"
# configure cmake
cmake = CMake(self)
cmake.configure(defs = defs)
return super().configure()
I get an exception.
A: If you don't tell CMake about the compiler you want to use, it will try to discover it in the project(...) call. If they don't match, a check performed by a Conan macro will fail.
Typically, if you want to use a compiler version different from the default you need to inform CMake about it. One of the most common ways to do it using Conan profiles is to add the CC and CXX variables to the profile itself.
[settings]
...
compiler=gcc
compiler.version=10.3
...
[env]
CC=/usr/bin/gcc-10
CXX=/usr/bin/g++-10
Conan will add these variables to the environment before calling the build system and most of them (CMake, Autotools,...) will take them into account.
This way, you don't need to modify the conanfile.py file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68605531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to populate a table in SQL In table 1 of my database is a column called Product Title, some of the products have the same name. However, they have different prices.
There is also a column called Product Version. This could be filled with Sale Price, Master Retail Price, Black Friday Price.
For all of the the products that are not 'Master Retail Price', I need to populate the Master Retail Price product number in to the Main Product Number Column.
So for example: If there are three Items called Banana, I need the ones that are the sale versions to have the Main Product Number in the Main Product Number Column.
If the Product Version is 'Master Retail Price', then Main Product Number should be NULL for that row.
So far, the code I have inserts all the product numbers from table 1 into table 2. If anyone could help here I would greatly appreciate it.
Select [Table 1].[Product Title], [Table 1].[Product No]
FROM [Table 1]
INNER JOIN [Table 2] ON [Table1].[Product Title]=[Table 2].[Product Title]
UPDATE [Table 1]
SET [Table 1].[Main Product Number]=[Table1.[Product No]
WHERE [Table 1].[Product Verison]='Master Retail Price';
A: OK, Let's reproduce what you have said
For this example I've used an Oracle Database.
We have table t1 with let's say 4 columns (the ones that you mentioned)
create table t1(
main_product_number int,
product_number int,
product_title varchar2(20),
product_version varchar2(40) );
Populate the table with some imaginary values
insert into t1 values (NULL, 1,'Banana','Master Retail Price');
insert into t1 values (5, 2, 'Banana','Sale Price');
insert into t1 values (7, 3, 'Banana','Black Friday Price');
Do a simple select to see the data:
select * from t1;
MAIN_PRODUCT_NUMBER PRODUCT_NUMBER PRODUCT_TITLE PRODUCT_VERSION
- 1 Banana Master Retail Price
5 2 Banana Sale Price
7 3 Banana Black Friday Price
For all of the the products that are not 'Master Retail Price', I need
to populate the Master Retail Price product number in to the Main
Product Number Column.
Hmmm... Let's use a correlated subquery for this task in a beautiful self join:
update t1 a
set a.main_product_number=( select product_number
from t1 b
where a.product_title = b.product_title
and b.product_version='Master Retail Price'
and b.main_product_number is null
)
where a.product_version <> 'Master Retail Price';
Now all of the products that are not master retail price, their main product number will be populated with the master retail price product number, as you can see in the select bellow.
MAIN_PRODUCT_NUMBER PRODUCT_NUMBER PRODUCT_TITLE PRODUCT_VERSION
- 1 Banana Master Retail Price
1 2 Banana Sale Price
1 3 Banana Black Friday Price
Hope it helps you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44232365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Recursive xmlhttp Request Not Changing I'm not sure what's happening here. I've hit a wall while trying to debug this.
I have the below xmlhttp request and have set it up to do a recursive call every 3 seconds to a public API. The problem I'm having is every call returns the exact same object, but if I refresh the page each time the object changes.
In other words, my xmlhttp variable is basically holding the first object it gets and never updating. I've tried nulling it before the recursive call but that didn't work. Not really sure what to do now.
var pullEvents = function(url){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
var res = JSON.parse(xmlhttp.responseText);
console.log(res);
setTimeout(function(){
pullEvents(url);
}, 3000);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28416108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: javascript/jquery simple search engine - implement a simple search engine, data stored in an array Question is Edited! I have stored all products name in an Array in object format. I have a input[type=text], too. I need a simple code to search among this array.
SQL command is like : (SELECT name FROM tbl_product WHERE name LIKE %txt% ). But I am implementing this on frond-end and there is no connection to back-end!
<input type="text" id="mytxt" />
<script>
// [{ in_ordered_id : "product name"}, ...]
var products_name = [{ 8 : "product ninety two"}, {21 : "product two"}, {35 : "product nine"} , ....];
$("#mytxt").keyup(function(){
var txt = $("#mytxt").val();
var results = start_search(txt); // `results` must be array of ids e.g. [35, 98]
});
function start_search(text){
/// I don't know what to write here
}
</script>
A: string.includes might help
products_name = ["product one", "product two"];
$("#mytxt").keyup(function() {
var txt = $("#mytxt").val();
var results = start_search(txt);
console.log(results);
});
function start_search(text) {
return products_name.filter(pr => pr.includes(text))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="mytxt">
--Edit
const products_name = [{
8: "product ninety two"
}, {
21: "product two"
}, {
35: "product nine"
}]
$("#mytxt").keyup(function() {
var txt = $("#mytxt").val();
var results = start_search(txt);
console.log(results);
});
function start_search(text) {
return products_name.filter(pr => Object.values(pr)[0].includes(text)).map(pr => Number(Object.keys(pr)[0]))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="mytxt">
A: How about using the array.indexOf function?
products_name = ["product one", "product two"];
function start_search(text){
if(products_name.indexOf(text) > -1){
return true;
}else{
return false;
}
};
start_search('product'); // returns false
start_search('product one'); // returns true
start_search('product two'); // returns true
start_search('product three'); // returns false
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62262138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Outer Joins of dataframe
Need to join one main dataframe in such a way that for a given primary data is not present in all others data frames then row from main frame should not be returned .
Example is shown in excel. In example you will find org code 876 is removed
A: You could do an inner join of main_df with the full outer join of the two vendor dataframes. This way, lines from main_df are kept if and only if there appear at least once in one of the vendor dataframes. In pseudo code: main_df.inner_join(vendor1.full_join(vendor2)).
In spark:
# creating your data
vendor1_df = spark.createDataFrame([(123, 90, 45), (167, 45, 60)], ['Org_code', 'revenue', 'emp_code'])
vendor2_df = spark.createDataFrame([(456, 90, 45), (167, 450, 899)], ['Org_code', 'revenue', 'emp_code'])
main_df = spark.createDataFrame([(123, 'ABC'), (456, 'CDE'), (876, "egf"), (167, 'hnmm')], ['Org_code', 'Org_name'])
# renaming colunms
df1 = vendor1_df.select('Org_code', vendor1_df['revenue'].alias('v1_revenue'), vendor1_df['emp_code'].alias('v1_emp_code'))
df2 = vendor2_df.select('Org_code', vendor2_df['revenue'].alias('v2_revenue'), vendor2_df['emp_code'].alias('v2_emp_code'))
# and the result
all_vendors = df1.join(df2, ['Org_code'], 'full')
main_df.join(all_vendors, ['Org_code']).show()
+--------+--------+----------+-----------+----------+-----------+
|Org_code|Org_name|v1_revenue|v1_emp_code|v2_revenue|v2_emp_code|
+--------+--------+----------+-----------+----------+-----------+
| 123| ABC| 90| 45| null| null|
| 456| CDE| null| null| 90| 45|
| 167| hnmm| 45| 60| 450| 899|
+--------+--------+----------+-----------+----------+-----------+
A: I like ANSI SQL. I have been writing queries since the 1990s. Therefore, lets you spark SQL.
#
# Create dataframes
#
df1 = spark.createDataFrame( [(123, 90, 45), (167, 45, 60)], ['Org_code', 'vendor1_revenue', 'vendor1_emp_code'] )
df2 = spark.createDataFrame( [(456, 90, 45), (167, 450, 899)], ['Org_code', 'vendor2_revenue', 'vendor2_emp_code'] )
df3 = spark.createDataFrame( [(123, 'ABC'), (456, 'CDE'), (876, "egf"), (167, 'hnmm')], ['Org_code', 'Org_name'] )
Make dataframes above and create temporary views below.
#
# Create views
#
df1.createOrReplaceTempView("vendor1")
df2.createOrReplaceTempView("vendor2")
df2.createOrReplaceTempView("main")
Just use a left join since the main table is the driver.
%sql
select
m1.*,
v1.vendor1_revenue,
v1.vendor1_emp_code,
v2.vendor2_revenue,
v2.vendor2_emp_code
from main as m1
left join vendor1 as v1 on m1.org_code = v1.org_code
left join vendor2 as v2 on m1.org_code = v2.org_code
where v1.org_code is not null or v2.org_code is not null
We just need to add a where clause that tosses out rows in which the main table does not match any vendors.
I keep on trying to promote Spark SQL since many technologist know ANSI SQL.
The expected result is in the above image.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75597527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: where best to define enumerations java? Is there a "best practice" for the place at which an enum should be defined in java?
One option is to have a separate .java file for each enum, and any class that uses that enum can include it.
example:
Direction.java:
public enum Direction {
INPUT, OUTPUT, UNKNOWN
}
Type.java
public enum Type{
DATA, VALID, READY, UNKNOWN
}
Another option is to have one big file with all the enums in my application, and if a class uses any of the enums, it will have to include that big file.
example:
MyEnums.java
public class MyEnums{
public enum Direction {
INPUT, OUTPUT, UNKNOWN
}
public enum Type{
DATA, VALID, READY, UNKNOWN
}
}
Which of the two options is better, both in terms of performance and code portability/extensibility? or is it a matter of choice and there is no one better option? What is the best way to define enumerations in Java?
A: Basically if you're not planning to expose the usage of the enum, for e.g. Direction then you could do it right in the class which is using it. I mean that you could make it private, such as:
1 As inner type (direct usage)
public class Foo {
private Direction directionType = Direction.UNKNOWN;
// some code
private enum Direction {
INPUT, OUTPUT, UNKNOWN
}
}
2 As an external type
Write enums w/ logic (if there is some) in the separate *.java files. This is absolutely fine approach. Example below is the classical one from the Oracle Guide:
public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
private double mass() { return mass; }
private double radius() { return radius; }
// universal gravitational constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
double surfaceGravity() {
return G * mass / (radius * radius);
}
double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java Planet <earth_weight>");
System.exit(-1);
}
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight/EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
}
Summary
It really depends on the context and the architecture decision. Basically grouping enums in the one java file is not the best solution especially when your application begins 'to grow'. The code will be hard to read for other developers that will work on it. I suggest to use the approach #1 or #2
A: The general practice that I have seen is to have a package for all the enums and each enum is in its own java file with all the associated methods for that enum. If all you're going to have is just a bunch of enums with no methods operating on the contents of the enum, I guess it then just boils down to a matter of choice.
Imagine the common scenario where each enum has several methods associated with the constants it holds. You can see that having several enums in a single class can very easily make the code clunky. But on the other hand, if you are just going to have a collection of enums, it might even be desirable to put them all together in one place for the sake of brevity.
There would be no difference as far as performance and portability are concerned - you just need to think whether the code becomes clunky or not.
A: Same as for any other class or interface.
The fact that it's an enumeration doesn't change the basic nature of the question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27369145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Svelte component async loading in version 3 I would like to ask you a question about updating a simple example from version 2 to version 3.
This example of svelte v2 async component loading works (https://codesandbox.io/s/0ooo3z8nqp), but this one written for v3 doesn't (https://codesandbox.io/s/615zv3xp33).
Any clue?
Thanks!
Update:
My question was about converting the following piece of code from Svelte V2 to V3.
<script>
export default {
components: {},
data() {
return {
ChatBox: null
};
},
methods: {
async loadChatbox() {
const { default: ChatBox } = await import("./Chatbox.html");
this.set({ ChatBox });
}
}
};
</script>
A:
In version 3 of Svelte you can assign a new value to the variable directly without using set.
You can name the default to something other than ChatBox so that the outer variable isn't shadowed, and then assign directly to it.
let ChatBox;
async function loadChatBox() {
const { default: Component } = await import("./ChatBox.svelte");
ChatBox = Component;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56010077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Room dao cannot resolve table name and method I'm trying to implement a simple database using Room and Dao, this is what I did
My entity:
public class Note {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "title")
private String title;
}
I have also generated all getters and setters in the entity but I don't include here because it's very long.
My Dao interface:
@Dao
public interface NoteDAO {
List<Note> getAllNotes();
}
My database class:
@Database(entities = Note.class, version = 1, exportSchema = false)
public abstract class NoteDatabase extends RoomDatabase {
private static NoteDatabase noteDatabase;
public static synchronized NoteDatabase getDatabase(Context context){
if (noteDatabase == null){
noteDatabase = Room.databaseBuilder(
context,
NoteDatabase.class,
);
}
return noteDatabase;
}
}
When I use List<Note> notes and notes.toString(), it only shows me the date and time, the title is null, I also notice that in the Dao interface, it raises 2 errors which are Cannot resolve symbol notes and Cannot resolve symbol id. I don't understand why it doesn't insert to the database. Can someone help me with this problem? Thanks for your help !
A: The code you have included in your question is fine (after adding the getters and setters) and then using:-
public class MainActivity extends AppCompatActivity {
NoteDatabase db;
NoteDAO dao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = NoteDatabase.getDatabase(this);
dao = db.noteDAO();
Note note1 = new Note();
note1.setTitle("NOTE001");
note1.setDatetime("2022-01-01 10:30");
note1.setSubtitle("The First Note");
note1.setWebsite("www.mynotes.com");
note1.setNoteText("This is the note");
note1.setColor("Black");
note1.setImagePath("notes/note1.jpg");
dao.insertNote(note1);
for (Note n: dao.getAllNotes()) {
Log.d("NOTEINFO","Title is " + n.getTitle() + " Date is " + n.getDatetime() + " blah blah ToString = " + n);
}
}
}
*
*note the only amendment to the code copied from the question is the use of .allowMainThreadQueries in the databaseBuilder.
The result being:-
D/NOTEINFO: Title is NOTE001 Date is 2022-01-01 10:30 blah blah ToString = NOTE001 : 2022-01-01 10:30
However, adding :-
Note note2 = new Note();
//note1.setTitle("NOTE001"); //<<<<<<<<<<< OOOPS
note2.setDatetime("2022-01-01 10:30");
note2.setSubtitle("The Second Note");
note2.setWebsite("www.mynotes.com");
note2.setNoteText("This is the note");
note2.setColor("Black");
note2.setImagePath("notes/note2.jpg");
Results in what you appear to be describing as per:-
D/NOTEINFO: Title is null Date is 2022-01-01 10:30 blah blah ToString = null : 2022-01-01 10:30
I believe you saying
I also notice that in the Dao interface, it raises 2 errors which are Cannot resolve symbol notes and Cannot resolve symbol id
Is perhaps the clue to the cause, which could be that you have the incorrect dependencies you should have 2 for Room:-
*
*the runtime library e.g. implementation 'androidx.room:room-runtime:2.5.0-alpha02', and
*the compiler library e.g. annotationProcessor 'androidx.room:room-compiler:2.5.0-alpha02'
Another possibility is that in addition to the getters and setters you have a constructor that doesn't set correctly the title so it is left as null.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73508562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: need to read the json arrays inside the object using java I am trying to read the JSON using java but unable to do that. So need to write a java code read the JSON file where arrays are inside the object.
"exclusion":{
"serviceLevelList":[ "SIS98", "C4P","SNTP" ],
"pid":[ "ABC", "DEF" ]
}
A: Use JSONObject for simple JSON and JSONArray for array of JSON.
try {
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(
new FileReader("/config.json"));//path to the JSON file.
JSONObject jsonObject = data.getJSONObject("exclusion");
JSONArray array= jsonObject.getJSONArray("pid");
} catch (Exception e) {
e.printStackTrace();
}
Use google-simple library
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
A: Try this:
String jsonTxt = IOUtils.toString( is );
JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
JSONObject exclusion= json.getJSONObject("exclusion");
String serviceLevelList[]= pilot.getString("serviceLevelList");
String pid[]= pilot.getString("pid");
A: You Can Try methods Of Gson Object to convert JSON to Java Object and Vise Versa.
for That you Can Use Dependancy as follows
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
Gson object Provides several methods as follows :
Gson gson = new Gson();
// Convert Java object to JSON and assign to a String
String jsonInString = gson.toJson(obj);
//Convert JSON to Java object, read it from a JSON String.
String jsonInString = "{'name' : 'myname'}";
Staff staff = gson.fromJson(jsonInString, Student.class);
you can try this with your code :-)
A: We have been using XStream for years now. Although our main use has been for .XML files, it also supports reading and writing JSON as well, and we've used like that for a couple of times.
Include it in your maven project with this dependency snippet:
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11</version>
</dependency>
You have all info you need in their web site. They even have a "Two minute tutorial" and a "JSON Tutorial" that might be of use (which, by the way, has a "Read from JSON" mention that might be directly applicable to your case). There are also several posts across the internet, as they documented in their references section, and even a XStream course in StudyTrails.
A: By using JSONObject and JSONArray classes you can perform different operation on json data.
Refer this link for know about handling the json data of different format,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54664416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to tell if a param was passed assuming it was a constant? I am using this code (note: HELLO_WORLD was NEVER defined!):
function my_function($Foo) {
//...
}
my_function(HELLO_WORLD);
HELLO_WORLD might be defined, it might not. I want to know if it was passed and if HELLO_WORLD was passed assuming it was as constant. I don't care about the value of HELLO_WORLD.
Something like this:
function my_function($Foo) {
if (was_passed_as_constant($Foo)) {
//Do something...
}
}
How can I tell if a parameter was passed assuming it was a constant or just variable?
I know it's not great programming, but it's what I'd like to do.
A: if a constant isn't defined, PHP will treat it as String ("HELLO_WORLD" in this case) (and throw a Notice into your Log-files).
You could do a check as follows:
function my_function($foo) {
if ($foo != 'HELLO_WORLD') {
//Do something...
}
}
but sadly, this code has two big problems:
*
*you need to know the name of the constant that gets passed
*the constand musn't contain it's own name
A better solution would be to pass the constant-name instead of the constant itself:
function my_function($const) {
if (defined($const)) {
$foo = constant($const);
//Do something...
}
}
for this, the only thing you have to change is to pass the name of a constant instead of the constant itself. the good thing: this will also prevent the notice thrown in your original code.
A: You could do it like this:
function my_function($Foo) {
if (defined($Foo)) {
// Was passed as a constant
// Do this to get the value:
$value = constant($Foo);
}
else {
// Was passed as a variable
$value = $Foo;
}
}
However you would need to quote the string to call the function:
my_function("CONSTANT_NAME");
Also, this will only work if there is no variable whose value is the same as a defined constant name:
define("FRUIT", "watermelon");
$object = "FRUIT";
my_function($object); // will execute the passed as a constant part
A: Try this:
$my_function ('HELLO_WORLD');
function my_function ($foo)
{
$constant_list = get_defined_constants(true);
if (array_key_exists ($foo, $constant_list['user']))
{
print "{$foo} is a constant.";
}
else
{
print "{$foo} is not a constant.";
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18200992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Autopopulate a set of generic many to many fields in Django? I'm trying to combine this answer and this one, with a bit of for looping.
On creating a character, I want to add all possible skills with a value of 0 but I'm getting confused on how to follow the above answers.
I have this mixin:
class CrossCharacterMixin(models.Model):
cross_character_types = models.Q(app_label='mage', model='mage')
content_type = models.ForeignKey(ContentType, limit_choices_to=cross_character_types,
null=True, blank=True)
object_id = models.PositiveIntegerField(null=True)
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
abstract = True
(eventually, the cross_character_types will be expanded)
And this model:
class CharacterSkillLink(Trait, CrossCharacterMixin):
PRIORITY_CHOICES = (
(1, 'Primary'), (2, 'Secondary'), (3, 'Tertiary')
)
skill = models.ForeignKey('SkillAbility')
priority = models.PositiveSmallIntegerField(
choices=PRIORITY_CHOICES, default=None)
speciality = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
spec_string = " (" + self.speciality + ")" if self.speciality else ""
return self.skill.skill.label + spec_string
What I've started writing is this, on the NWODCharacter model:
def save(self, *args, **kwargs):
if not self.pk:
character_skills_through = CharacterSkillLink.content_object.model
CharacterSkillLink.objects.bulk_create([
[character_skills_through(skill=SkillAbility(
skill), content_object=self) for skill in SkillAbility.Skills]
])
super(NWODCharacter, self).save(*args, **kwargs)
This doesn't work as I don't think I'm passing in the right objects.
Based on this answer though:
from django.db import models
class Users(models.Model):
pass
class Sample(models.Model):
users = models.ManyToManyField(Users)
Users().save()
Users().save()
# Access the through model directly
ThroughModel = Sample.users.through
users = Users.objects.filter(pk__in=[1,2])
sample_object = Sample()
sample_object.save()
ThroughModel.objects.bulk_create([
ThroughModel(users_id=users[0].pk, sample_id=sample_object.pk),
ThroughModel(users_id=users[1].pk, sample_id=sample_object.pk)
])
In this situation, what is my ThroughModel? Is it CharacterSkillLink.content_object.model ?
How do I do this in my scenario? I'm sorry if this is trivial, but I'm struggling to get my head round it.
A: It looks to me like CharacterSkillLink itself is your through model in this case... it generically joins a content type to a SkillAbility
If you think about it, it also makes sense that if you're doing a bulk_create the objects that you pass in must be of the same model you're doing a bulk_create on.
So I think you want something like this:
def save(self, *args, **kwargs):
initialise_skill_links = not self.pk
super(NWODCharacter, self).save(*args, **kwargs)
if initialise_skill_links:
CharacterSkillLink.objects.bulk_create([
CharacterSkillLink(
skill=SkillAbility.objects.get_or_create(skill=skill)[0],
content_object=self
)
for skill in SkillAbility.Skills
])
Note you had too many pairs of [] inside your bulk_create.
Also I think you should use SkillAbility.objects.get_or_create()... for a foreign key you need the related object to exist. Just doing SkillAbility() won't fetch it from the db if it already exists and won't save it to the db if it doesn't.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28437208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Run Angular and ASP.NET Web API on the same port I am currently using angular to issue API call to an API server running ASP.NET. However, I have a cross-origin issue as for angular development, I am using localhost. While in the production version they will all run under the same domain using IIS.
Is there a way to run the angular app on the same port with ASP.NET?
P.S.: I am also open for other alternatives on solving this issue.
A: I was able to achieve that with IIS successfully! I know the post is old but hopefully, it will save time for solution seekers :)
First (just a reminder) ensure that you have .NET Core Hosting Bundle installed on IIS machine (link could be found here). Bear in mind that it will require at least WinSrvr2012R2 to run.
Now copy published .net core API solution folder to the server. The same for Angular - next reminder here: execute ng build --prod then copy dist folder to the server.
Then configure IIS - create a new web site that points to the Angular app folder. Your Angular app should run at this point (but obviously there is no API yet).
Go to application pools - you will see the pool created for your application. Open basic settings and change CLR version to 'No managed code'.
And finally, click on your Web Site and 'Add application' under it. Point to dotnet core API folder and name it using some short alias. Now you should have a website structure with the application included.
If your angular app URL is:
https://myiissrvr/
your API is under:
https://myiissrvr/[ALIAS]/
DONE
Final remarks:
Usually, web API using URL structure like
https://myiissrvr/api/[controller]/[action]
So after bundling it together, it will look like:
https://myiissrvr/[ALIAS]/api/[controller]/[action]
With that approach, you should be able to attach multiple web API services under statically served Angular website - each one under its own alias. Potentially it might be useful in many scenarios.
A: I've encountered the same problem, then I've found this post on medium, hope this works for you.
Edit:
Actually the solution that I've used is from that article.
The idea is that you can't "publish" the API and the Angular app on the same port, but you can use a proxy to connect from the Angular app to the API on the other port.
Update: sorry for not answering this long time ago.
To deal with the cors issue (in this case) you can use a proxy with the ng serve command.
For example, in my case I have used a proxy.conf.json file like this:
{
"/api/*": {
"target": "http://localhost:3000",
"secure": false,
"pathRewrite": {"^/api" : ""}
}
}
This code rewrite the url on every request to /api/* to the http://localhost:3000 where your api is listening.
So, to illustrate, if in angular you make a request like http://localhost:4200/api/users it will be redirected/rewrited to http://localhost:3000/api/users solving the cors issue.
Now, the way you have to run your angular application is different.
ng serve --proxy-config proxy.conf.json
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50753407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Creating an Indexvariable in R based on several Indexvariables I'm looking for a fast and easy alternative in R to create new Indexvariables out of several existing Indexvariables. Eg:
var1 var2 var3 newvar
0 1 1 1
0 0 0 0
1 0 0 1
1 1 1 1
1 0 9 1
1 9 9 1
0 9 9 1
How to create the newvar column with only one line in R?
I have also the value 9 for "not answered" in the dataframe. I Just want to count the values 1 (and nothing else).
I'm looking for an alternative for the SPSS-Code:
COMPUTE newvar= any(1,var1,var2,var3).
A: To count the values 1 for each row you can just use:
mydf$newvar <- rowSums(mydf==1)
If you want to see whether any of the values is 1 (as your intended outpur newvar implies):
mydf$newvar <- +(rowSums(mydf==1)>0)
A: Thank you Henrik!
You are right. It was answered in the thread you mentioned.
Here the answer again, because nothing is trivial for everyone :-)
newvar<-as.numeric(apply(cbind(var1,var2,var3), 1, function(r) any(r == 1)))
Elch von Oslo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33759188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get dataset from prepare_data() to setup() in PyTorch Lightning I made my own dataset using NumPy in the prepare_data() methods using the DataModules method of PyTorch Lightning. Now, I want to pass the data into the setup() method to split into training and validation.
import numpy as np
import pytorch_lightning as pl
from torch.utils.data import random_split, DataLoader, TensorDataset
import torch
from torch.autograd import Variable
from torchvision import transforms
np.random.seed(42)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
class DataModuleClass(pl.LightningDataModule):
def __init__(self):
super().__init__()
self.constant = 2
self.batch_size = 10
def prepare_data(self):
a = np.random.uniform(0, 500, 500)
b = np.random.normal(0, self.constant, len(a))
c = a + b
X = np.transpose(np.array([a, b]))
# Converting numpy array to Tensor
self.x_train_tensor = torch.from_numpy(X).float().to(device)
self.y_train_tensor = torch.from_numpy(c).float().to(device)
training_dataset = TensorDataset(self.x_train_tensor, self.y_train_tensor)
return training_dataset
def setup(self):
data = # What I have to write to get the data from prepare_data()
self.train_data, self.val_data = random_split(data, [400, 100])
def train_dataloader(self):
training_dataloader = setup() # Need to get the training data
return DataLoader(self.training_dataloader)
def val_dataloader(self):
validation_dataloader = prepare_data() # Need to get the validation data
return DataLoader(self.validation_dataloader)
obj = DataModuleClass()
print(obj.prepare_data())
A: The same answer as your previous question...
def prepare_data(self):
a = np.random.uniform(0, 500, 500)
b = np.random.normal(0, self.constant, len(a))
c = a + b
X = np.transpose(np.array([a, b]))
# Converting numpy array to Tensor
self.x_train_tensor = torch.from_numpy(X).float().to(device)
self.y_train_tensor = torch.from_numpy(c).float().to(device)
training_dataset = TensorDataset(self.x_train_tensor, self.y_train_tensor)
self.training_dataset = training_dataset
def setup(self):
data = self.training_dataset
self.train_data, self.val_data = random_split(data, [400, 100])
def train_dataloader(self):
return DataLoader(self.train_data)
def val_dataloader(self):
return DataLoader(self.val_data)
A: Simply call setup() on your DataModule object after calling prepare() on that object. So:
dm = DataModuleClass()
dm.prepare_data()
dm.setup()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67441163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Laravel 302 redirection when I do a POST I am having a problem with Laravel.
I try to do a POST with JQuery to my Controller, but when I do that, I recieve a HTTP 302 code (found), and after that It creates a GET to the same controller URL.
Here there is my code:
WizardController.php
class WizardController extends Controller
{
public function saveForm(Request $request) {
$data = $request->data;
error_log(print_r($data, true));
return response()->json(['message' => 'test']);
}
}
routes/web.php
Route::group(['prefix' => 'wizard', 'middleware' => 'auth'], function(){
Route::post('create', 'WizardController@saveForm');
})
Wizard.html
<script>
var token = $('meta[name=csrf-token]').attr('content');
$.ajax('wizard/create', function() {
method: 'POST',
data: {'data' : 'test'},
headers: { 'X-CSRF-TOKEN': token },
success: function(data) {
console.log(data);
}
});
</script>
I even cannot see the log in my controller. Any suggestion?
Thanks
A: You have middleware 'auth' for your route. You should investigate a bit on it and you'll understand why doesn't it work.
The point is that 'auth' middleware requires cookies to work correctly, while you have it empty when you're have Ajax request. Why does it give you 302 and not 401? You should look into your authentication handler for any custom logic on that.
What to do? Implement JWT auth or stateless authentication!
A: OK problem solved...
My problem was in routes/web.php, I declared that route inside a Route group, which has two other customized middlewares.
One of those middleware was making me that wrong redirection.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51132595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP Email Form Formatting I have, with the help of a few users here - created a form that sends data (name, checkbox awnsers) to my email.
However, when I recieve the email it is wrongly formatted and thus not very useful to me.
My code is below:
PHP (mailer.php)
<?php
if(isset($_POST['submit'])) {
$to = "[email protected]";
$subject = "This is the subject";
$name_field = $_POST['name'];
$match_name= $_POST['match_name'];
$check_msg ="";
foreach($_POST['check'] as $value) {
$check_msg .= "Selected: $value\n";
}
$body = "From: $name_field\n $check_msg";
$body = "Match: $match_name\n $check_msg";
mail($to, $subject, $body);
echo "Data has been submitted to $to!";
} else {
echo "blarg!";
}
?>
HTML
<html>
<head>
<title>World Cup Challenge</title>
<style>
BODY{color:#000000; font-size: 8pt; font-family: Verdana}
.button {background-color: rgb(128,128,128); color:#ffffff; font-size: 8pt;}
.inputc {font-size: 8pt;}
.style3 {font-size: xx-small}
</style>
</head>
<form method="POST" action="mailer.php">
Name: <input type="text" name="name" size=""><br>
<br>
Brazil VS Croatia
<input type="hidden" name="match_name" value="Brazil VS Croatia">
<br>
<input type="checkbox" name="check[]" value="Brazil">Brazil<br>
<input type="checkbox" name="check[]" value="Croatia">Croatia<br>
<br>
Mexico VS Cameroon
<input type="hidden" name="match_name" value="Mexico VS Cameroon">
<br>
<input type="checkbox" name="check[]" value="Mexico">Mexico<br>
<input type="checkbox" name="check[]" value="Cameroon">Cameroon<br>
<br>
<input type="submit" value="Submit" name="submit">
</form>
Some background, I am creating this form for myself and a few friends to select our picks for the upcoming World Cup. I will need there to be 50 matches posted, that they can select their choice for each.
When i recieve the email, I want it to be formatted as:
**NAME OF USER**
MATCH NAME
SELECTED TEAM
NAME NAME #2
SELECTED TEAM
and so forth, this script currently works - but just formats wrongfully. (forgive me if I formatted wrong, or for my newbie-ness)
any help is very much appreciated!
A: Try this:
HTML
<html>
<head>
<title>World Cup Challenge</title>
<style>
BODY{color:#000000; font-size: 8pt; font-family: Verdana}
.button {background-color: rgb(128,128,128); color:#ffffff; font-size: 8pt;}
.inputc {font-size: 8pt;}
.style3 {font-size: xx-small}
</style>
</head>
<body>
<form method="POST" action="mailer.php">
Name: <input type="text" name="name" size=""><br>
<br>
Brazil VS Croatia
<input type="hidden" name="match_name[]" value="Brazil VS Croatia">
<br>
<input type="radio" name="check0[]" value="Brazil">Brazil<br>
<input type="radio" name="check0[]" value="Croatia">Croatia<br>
<br>
Mexico VS Cameroon
<input type="hidden" name="match_name[]" value="Mexico VS Cameroon">
<br>
<input type="radio" name="check1[]" value="Mexico">Mexico<br>
<input type="radio" name="check1[]" value="Cameroon">Cameroon<br>
<br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
php:
<?php
if(isset($_POST['submit'])) {
$to = "[email protected]";
$subject = "This is the subject";
$name_field = $_POST['name'];
$i = 0;
$body = "From: " . $name_field. "\n";
foreach($_POST['match_name'] as $match_name) {
$body .= "Match: " . $match_name . "\n";
$check = "check".$i;
foreach($_POST[$check] as $val) {
$body .= "Selected Team: " . $val . "\n";
}
$i++;
}
if (mail($to, $subject, $body)) {
echo "Mail sent to: $to!";
} else {
echo "Sending mail failed";
}
} else {
echo "blarg!";
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23927239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I stop brute-force attack to keep documents secure inside folder? Example:
if we hit the link of any document then we can easily download it. for example backup.sql inside the backup folder of the website then we can download it by hitting URL www.example.com/backup/backup.sql
I don't know which type of document the client will store there but obviously, it can be confidential that is why it is not shareable to all.
working:
now I am creating a certain document management tool where we can upload a document and download the document and can assign to users who can download that document but while creating I got the idea that anyone can brute force that folder just hitting URL with random names. backup.sql, database.sql and so on. I am using URL myself to make the document downloadable should I go with get_file_content()?.
I want to know if there is a way to download the file in a secure way example only the user that is logged in into my website can only download the file.
something like via htaccess or something else I can block the files directory from outside access. only the logged-in user can download the file and it will be blocked by outside access so that nobody can brute force it. I know I can block it via htaccess but I want them to download too but only for the users of my website.
A: maybe you should use "x-accel-redirect" for Nginx, and "X-Sendfile" for Apache.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57058856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: SQLDependency Onchange event always firing without data change I'm using it on a console project.
.NET Framework: 4.5
In my test code, SQLDependency onChange always firing although there is no data changes in Database.
class Program
{
private static string _connStr;
static void Main(string[] args)
{
_connStr = "data source=xxx.xxx.xx.xx;User Id=xxx;Password=xxx; Initial Catalog=xxx";
SqlDependency.Start(_connStr);
UpdateGrid();
Console.Read();
}
private static void UpdateGrid()
{
using (SqlConnection connection = new SqlConnection(_connStr))
{
using (SqlCommand command = new SqlCommand("select msgdtl,msgid From NotifyMsg", connection))
{
command.CommandType = CommandType.Text;
connection.Open();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
SqlDataReader sdr = command.ExecuteReader();
Console.WriteLine();
while (sdr.Read())
{
Console.WriteLine("msgdtl:{0}\t (msgid:{1})", sdr["msgdtl"].ToString(), sdr["msgid"].ToString());
}
sdr.Close();
}
}
}
private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
UpdateGrid();
}
when I start running, onChange event fires and never stop. But there is no change in my databse.
A: Try to check the SqlNotificationEventArgs object in the dependency_OnChnage method. It looks like you have an error there. I had the same SqlDependency behavior one time and the problem was solved by changing select msgdtl,msgid From NotifyMsg to select msgdtl,msgid From dbo.NotifyMsg (The dbo statement has been added).
But I should warn you: be careful using SqlDependency class - it has the problems with memory leaks. Hovewer, you can use an open source realization of the SqlDependency class - SqlDependencyEx. It uses a database trigger and native Service Broker notification to receive events about the table changes. This is an usage example:
int changesReceived = 0;
using (SqlDependencyEx sqlDependency = new SqlDependencyEx(
TEST_CONNECTION_STRING, TEST_DATABASE_NAME, TEST_TABLE_NAME))
{
sqlDependency.TableChanged += (o, e) => changesReceived++;
sqlDependency.Start();
// Make table changes.
MakeTableInsertDeleteChanges(changesCount);
// Wait a little bit to receive all changes.
Thread.Sleep(1000);
}
Assert.AreEqual(changesCount, changesReceived);
With SqlDependecyEx you are able to monitor INSERT, DELETE, UPDATE separately and receive actual changed data (xml) in the event args object. Hope this help.
A: there is a custom implementation of SqlDependency that report you the changed table records:
var _con= "data source=.; initial catalog=MyDB; integrated security=True";
static void Main()
{
using (var dep = new SqlTableDependency<Customer>(_con, "Customer"))
{
dep.OnChanged += Changed;
dep.Start();
Console.WriteLine("Press a key to exit");
Console.ReadKey();
dep.Stop();
}
}
static void Changed(object sender, RecordChangedEventArgs<Customer> e)
{
if (e.ChangeType != ChangeType.None)
{
for (var index = 0; index < e.ChangedEntities.Count; index++)
{
var changedEntity = e.ChangedEntities[index];
Console.WriteLine("DML operation: " + e.ChangeType);
Console.WriteLine("ID: " + changedEntity.Id);
Console.WriteLine("Name: " + changedEntity.Name);
Console.WriteLine("Surame: " + changedEntity.Surname);
}
}
}
Here is the link: [https://tabledependency.codeplex.com]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29726738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Plot day events from date and value in Gnuplot I have data of this format:
2011-06-22 22:33:19 23 15
2011-06-23 09:46:13 12 79
2011-06-24 12:31:09 31 4
2011-06-24 17:34:10 7 2
2011-06-25 16:42:43 44 14
2011-06-25 20:26:52 54 9
2011-06-26 19:34:29 217 28
How can I create a histogram of daily activities with Gnuplot? By default, using these settings:
set xdata time
set timefmt "%Y-%m-%d %H:%M:%S"
set style data boxes
set grid
plot 'data' using 1:3 t "ins", \
'data' using 1:4 t 'dels'
the boxes will fit next to each other. But I would like to leave noneventful days at 0. Just like the Reputation graph here in StackOverflow behaves. If there's nothing on a given day, it should leave an empty place in the graph. If there's one event for one day, that box should be about the maximum width for one day. If there are more than one to given day, they all should be fit to that width.
Setting boxwidth is tricky because any value seem to give me 1-pixel wide "boxes".
Thanks kindly.
A: if I understand you correctly, then what you are trying to do is to my knowledge not possible with gnuplot. Or at least not in an easy way. And this is the reason why I think you'll have a hard time:
You cannot plot different box widths in a single plot. So trying to plot no box on an "non eventful" day and a single column on a day with one event will work just fine. Plotting multiple columns on one day where more than one event occurs in the same plot will fail because:
*
*You cannot set different box sizes in the same plot
*You need to offset the boxes on the same day according to the amount of events
There are ways to work around that problem for example plot two boxes of the same color next to each other to "simulate" a single box on one day and then make use of the smaller box width on days with two events. But this will very soon get pretty hairy and hard to maintain.
Maybe you want to think about using a different plot style? Take a look at histograms like here. Maybe one of the styles suites your data better. Or you could think about splitting your plot up into multiple plots?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6563251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Azure B2C Impersonated User access token to call web API? I am successfully using the Impersonation custom policy (https://github.com/azure-ad-b2c/samples/tree/master/policies/impersonation) to get an ID token for the user I am trying to impersonate.
However, when I call a web API (that is also secured by Azure B2C), the acquireTokenSilent() call is defaulting back to the logged in user access token to make the web API call. How do I obtain an access token for the impersonated user so that I am calling the web API as the impersonated user.
I have modified the react b2c-sample (https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-react-samples/b2c-sample) to execute the Impersonation policy and I am seeing the correct impersonation token being returned, but when I execute a call to my web api, it is using the logged in user access token.
Any ideas on what I am missing?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75550573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Merging two mostly similar adapters for recyclerview I have two adapters that adapt to a recycler view depending on different conditions. I want to merge them.
The issue is that I created first in the same file as the activity where it is being used and the other is in a new file.
Take it as follows:
DefaultAdapter is in the file where it is being used.
AutoCompleteAdapter is also used in the same file but is declared in other file.
I want to get rid of Default Adapter and get its funtions into AutoCompleteAdapter.
There are some issues to it: I can no more use the ParentFiles' variables.
Below is the adapter that I want to get rid of.
public class DefaultAdapter extends RecyclerView.Adapter<DefaultAdapter.ViewHolder> {
private Context context;
private AdapterView.OnItemClickListener onItemClickListener;
List<String> searchList;
@NonNull @Override
public DefaultAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = (View) LayoutInflater.from(parent.getContext())
.inflate(android.R.layout.simple_list_item_1, null);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.txt.setText(
Html.fromHtml(getItem(position)).toString());///need to get rid of this error
}
@Override public int getItemCount() {
return searchList.size();
}
@NonNull public String getItem(int position) {
return searchList.get(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txt;
public ViewHolder(@NonNull View itemView) {
super(itemView);
txt = itemView.findViewById(android.R.id.text1);
itemView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
String title = txt.getText().toString();
searchPresenter.saveSearch(title);
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override public boolean onLongClick(View v) {
String searched = txt.getText().toString();
deleteSpecificSearchDialog(searched);
return true;
}
});
}
}
}
Please take note of the SearchPresenter. This is a variable in the parent file, that is causing major issues. Autocomplete adapter doesn't have to use it, but default have to.
This is the adapter I want it to merge into
public class AutoCompleteAdapter extends RecyclerView.Adapter<AutoCompleteAdapter.ViewHolder>
implements Filterable {
@Inject JNIKiwix currentJNIReader;
@Inject SharedPreferenceUtil sharedPreferenceUtil;
@Inject ZimReaderContainer zimReaderContainer;
private List<String> data;
private KiwixFilter kiwifilter;
private Context context;
public AutoCompleteAdapter(Context context) {
this.context = context;
data = new ArrayList<>();
kiwifilter = new KiwixFilter();
setupDagger();
}
private void setupDagger() {
CoreApp.getCoreComponent().inject(this);
}
@NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = (View) LayoutInflater.from(parent.getContext())
.inflate(android.R.layout.simple_list_item_1, null);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.title.setText(Html.fromHtml(getItem(position)).toString());
}
@Override
public String getItem(int index) {
String a = data.get(index);
if (a.endsWith(".html")) {
String trim = a.substring(2);
trim = trim.substring(0, trim.length() - 5);
return trim.replace("_", " ");
} else {
return a;
}
}
@Override public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
public ViewHolder(@NonNull View itemView) {
super(itemView);
title = itemView.findViewById(android.R.id.text1);
}
}
}
...
Note the similarity between the two, they are almost similar, autocompleteadapter is like superset of defaultadapter.
I just want to get rid of the default adapter.
Note: I have chopped off some other things from autocompeleteadapter, I think they are not required for the problem.
Noob here...
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58716686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: statsd architecture for a distributed system I am studying to use the graphite - statsd - collectd stack to monitor a a distributed system.
I have tested the components (graphite-web, carbon, whisper, statsd, collectd and grafana) in a local instance.
However I'm confused about how I should distributed these components in a distributed system:
- A monitor node with graphite-web (and grafana), carbon and whisper.
- In every worker node: statsd and collectd sending data to the carbon backend in the remote monitor node.
Is it right this scheme? What I should configure statsd and collectd to get an acceptable network ussage (tcp/udp, packets per second...)?
A: Assuming you have a relatively light workload, having a node that manages graphite-web, grafana, and carbon (which itself manages the whisper database) should be fine.
Then you should have a separate node for your statsd. Each of your machines/applications should have statsd client code that sends your metrics to this statsd node. This statsd node should then forward these metrics onto your carbon node.
For larger workloads that stress a single node, you'll need to either scale vertically (get more powerful node to host your carbons/statsd instances), or start clustering those services.
Carbon clusters tend to use some kind of relay that you send to that manages forwarding those metrics to the cluster (usually using consistent hashing). You could use a similar setup to consistently hash metrics to a cluster of statsd servers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32719081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Creating a mailto link in codebehind for a dynamically generated gridview I am working on an internal directory service for my school and am having a problem creating "mailto:" links on a dynamically generated gridview from the codebehind.
After tinkering around for a while with this, I found out that Hyperlinkfields do not support the ":" character- making "mailto:" links not possible.
Because I am dynamically generating the Gridviews to allow for grouping by header, I am doing it all in the codebehind. The Gridviews are created reading from a datasource and added to a placeholder tag on the aspx page along with a corresponding label defining the group.
public void GenerateDynamicGVs()
{
//...
DataTable dt = new DataTable();
//...
using (SqlDataReader dr = DBUtility.ExecuteReader(cmd, "www_ConMasterDBString"))
{
dt.Load(dr);
var query = dt.AsEnumerable()
.GroupBy(r => r.Field<string>("GroupName"))
.Select(grp => new
{
GroupName = grp.Key,
})
.OrderBy(o => o.GroupName)
.ToList();
foreach (var item in query)
{
Label NewLabel = new Label();
NewLabel.Text = item.GroupName;
NewLabel.CssClass = "DirectoryHeaders";
GridView newGV = new GridView();
newGV.CssClass = "CONServices";
newGV.ShowHeader = false;
newGV.AutoGenerateColumns = false;
newGV.DataSource = dt.AsEnumerable().Where(p => p.Field<string>("GroupName") == item.GroupName)
.Select(p => new
{
id = p["id"].ToString(),
EntryName = p["EntryName"].ToString(),
EntryNumber = p["EntryNumber"].ToString(),
EntryContact = p["EntryContact"].ToString(),
Email = p["Email"].ToString(),
GroupName = p["GroupName"].ToString()
});
HyperLinkField hlName = new HyperLinkField();
BoundField bfNumber = new BoundField();
BoundField bfContact = new BoundField();
hlName.DataNavigateUrlFields = new string[] { dt.Columns[4].ToString() };
hlName.DataTextField = dt.Columns[1].ToString();
hlName.DataNavigateUrlFormatString = "mailto:{0}"; //This line executes, but is not a clickable link because of the colon.
bfNumber.DataField = dt.Columns[2].ToString();
bfContact.DataField = dt.Columns[3].ToString();
newGV.Columns.Add(hlName);
newGV.Columns.Add(bfNumber);
newGV.Columns.Add(bfContact);
divPlaceHolder.Controls.Add(NewLabel);
divPlaceHolder.Controls.Add(newGV);
newGV.DataBind();
}
dr.Close();
}
}
Is there a good way to create a mailto link in the codebehind? I can't convert it to the aspx file because of the need for dynamic creation. Am I missing something here? Any help or advice is greatly appreciated. Thanks.
EDIT: The link needs to have the name displayed rather than the email address, requiring calling two columns from the datatable: [1] and [4].
Got it working, code is all below.
Where my gridview stuff is:
tfName.ItemTemplate = new NameColumn();
The class that was required for the TemplateField. It is a bit messy with the literal tags, but I am just happy for a solution that worked:
class NameColumn : ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
Literal lit1 = new Literal();
Literal litName = new Literal();
Literal lit3 = new Literal();
Literal litEmail = new Literal();
Literal lit5 = new Literal();
lit1.Text = "<a href=\"mailto:";
lit3.Text = "\">";
lit5.Text = "</a>";
litEmail.DataBinding += new EventHandler(LabelEmailDatabinding);
litName.DataBinding += new EventHandler(LabelNameDatabinding);
container.Controls.Add(lit1);
container.Controls.Add(litEmail);
container.Controls.Add(lit3);
container.Controls.Add(litName);
container.Controls.Add(lit5);
}
private void LabelNameDatabinding(object sender, EventArgs e)
{
Literal lit = (Literal)sender;
GridViewRow row = (GridViewRow)lit.NamingContainer;
lit.Text = DataBinder.Eval(row.DataItem, "EntryName").ToString();
}
private void LabelEmailDatabinding(object sender, EventArgs e)
{
Literal lit = (Literal)sender;
GridViewRow row = (GridViewRow)lit.NamingContainer;
lit.Text = DataBinder.Eval(row.DataItem, "Email").ToString();
if (lit.Text == null)
{
lit.Text = "test";
}
}
}
A: Just curious, have you tried something like this:
hlName.DataNavigateUrlFormatString = "<a href=\"mailto:{0}\">{0}</a>";
or some variation of it?
A: okay sorry you need to switch to a bound field vs. a hyperlinkfield for the mailto. Apparently there is a problem with the ":" in the DataNavigateUrlFormatString.
Reference: http://forums.asp.net/t/1014242.aspx?How+to+create+mailto+in+gridview+
So all you really need to do is
BoundField hlName = new BoundField();
hlName.DataField= dt.Columns[1].ToString();
hlName.DataFormatString= "<a href=\"mailto:{0}\">{0}</a>";
hlName.HtmlEncodeFormatString = false;
That should resolve your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24249863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ChartJS v2: Scale value at click coordinates (time scale) I have a time-base line chart and I'm attempting to obtain the values for each scale at the click coordinates.
My onClick function specified in ChartJS options:
onClick: function(event, elementsAtEvent)
{
console.log(event, elementsAtEvent, this);
var valueX = null, valueY = null;
for (var scaleName in this.scales) {
var scale = this.scales[scaleName];
console.log(scale.id, scale.isHorizontal());
if (scale.isHorizontal()) {
valueX = scale.getValueForPixel(event.offsetX);
} else {
valueY = scale.getValueForPixel(event.offsetY);
}
}
console.log(event.offsetX, valueX, null, event.offsetY, valueY);
},
JSFiddle: https://jsfiddle.net/AllenJB/dmebo9g5/1/
The code above appears to work well for the Y axis, but not the X (time scale) - it always returns the last value regardless of where in the chart you click.
What might I be doing wrong?
A: This code actually works fine. The only problem was that I was looking at the _i value of the moment object to check it's value (this is the value used as the initial input when creating the object, not necessarily the current value).
Changing the console.log line to the following yields the expected / correct result:
console.log(event.offsetX, valueX.format('YYYY-MM-DD HH:mm:ss'), null, event.offsetY, valueY);
A: If you want to get the nearest x axis value you could do it this way:
onClick: function (event) {
const activeElements = this.getElementsAtXAxis(event);
const xval = this.scales['x-axis-0']._timestamps.data[activeElements[0]._index];
console.log(xval)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37141313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Why does a Rust macro re-exported from another crate work unless there's a dependency conflict I'm writing a Rust crate for internal company use that wraps the excellent Tokio tracing crate, with a bit of additional functionality. Not only do I re-export the macros in tracing, but I also add a few of my own that internally invoke the tracing macros. My goal is to enable all of our other internal crates to depend only on my wrapper crate, without having to pull in tracing dependencies explicitly in each crate.
This works really well, until I ran into an issue today that took me a few hours to isolate. I've made a minimal example to show the behavior here.
In this example, I have a workspace with two crates: my-logger-crate which wraps tracing and exposes a macro print_trace!, and a binary crate my-binary-crate which has a dependency on my-logger-crate, and invokes the macro inside the main function.
The Cargo.toml for my-logger-crate is very simple; the only thing I added to the auto-generated skeleton is a tracing dependency:
[package]
name = "my-logger-crate"
version = "0.1.0"
authors = ["Adam Nelson <[email protected]>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tracing = "0.1.12"
This is the my-logger-crate macro:
/// Re-export everything in the `tracing` crate
pub use ::tracing::*;
/// A version of the `trace!` macro that sets a special target
#[macro_export]
macro_rules! print_trace {
($($arg:tt)*) => (
// Invoke the `trace!` macro which is defined in the `tracing` crate but which has been
// re-exported from this crate, so that downstream callers don't have to take an explicit
// dependency on `tracing`
$crate::trace!(target: "console", $($arg)*)
)
}
This is used by my-binary-crate, whose Cargo.toml is also simple:
[package]
name = "my-binary-crate"
version = "0.1.0"
authors = ["Adam Nelson <[email protected]>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
my-logger-crate = { path = "../my-logger-crate" }
# If the following line is uncommented, then the call to `print_trace!` in `main()` fails to compile.
# tower = "0.3"
And here's the main() function in my-binary-crate:
fn main() {
println!("Hello, world!");
// Log a trace event with the logging system
my_logger_crate::print_trace!("this is a trace message from print_trace!");
}
If my-binary-crate doesn't have any conflicting dependencies, this compiles and runs fine.
But take a look at what happens if we have a dependency on tower in the my-binary-crate/Cargo.toml file:
[package]
name = "my-binary-crate"
version = "0.1.0"
authors = ["Adam Nelson <[email protected]>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
my-logger-crate = { path = "../my-logger-crate" }
# If the following line is uncommented, then the call to `print_trace!` in `main()` fails to compile.
tower = "0.3"
Here's what happens:
Compiling my-binary-crate v0.1.0 (/home/cornelius/scrap/e2780c4bd3dfa24758fcfd93e225b100/my-binary-crate)
error[E0433]: failed to resolve: use of undeclared type or module `tracing`
--> my-binary-crate/src/main.rs:5:5
|
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ use of undeclared type or module `tracing`
|
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
The print_trace! macro is expanding out to the tracing::trace! macro, which then expands to tracing::event!, and then expands to the code to log an event, which includes calls to tracing::.... All of this works fine before I add that tower dependency, so clearly the compiler is able to resolve tracing::... properly, even though my-binary-crate doesn't have a direct dependency on tracing itself.
I suspect this is related to a dependency conflict. tower pulls in a long dependency tree, including tower-buffer, which itself has a dependency on tracing = "0.1.2".
My understanding of how Cargo resolves this seeming conflict is that it would use tracing version 0.1.12, since my logging crate explicitly depends on version =0.1.12, and tower-buffer specifies 0.1.2, which is equivalent to ^0.1.2. But I don't understand why adding this additional dependency tree breaks the use of my macro.
For the moment I've worked around it by adding explicit dependencies on tracing in all of the downstream crates that use my logging crate, but that's far from ideal.
I ran with macro tracing enabled:
$ RUSTFLAGS="-Z macro-backtrace" cargo +nightly test
Compiling my-binary-crate v0.1.0 (/home/cornelius/scrap/e2780c4bd3dfa24758fcfd93e225b100/my-binary-crate)
error[E0433]: failed to resolve: use of undeclared type or module `tracing`
--> <::tracing::macros::__mk_format_args macros>:78:17
|
1 | / (@ { $ (,) * $ ($ out : expr), * $ (,) * }, $ fmt : expr, fields : $ (,) *) =>
2 | | { format_args ! ($ fmt, $ ($ out), *) } ;
3 | | (@ { $ (,) * $ ($ out : expr), * }, $ fmt : expr, fields : $ ($ k : ident) . +
4 | | = ? $ val : expr $ (,) *) =>
... |
78 | | (@ { }, tracing :: __mk_format_string ! ($ ($ kv) *), fields : $
| | ^^^^^^^ use of undeclared type or module `tracing`
79 | | ($ kv) *)
80 | | }
81 | | } ;
... [a lot of macro expansions snipped]
Not surprisingly, the error is an attempt to call tracing::__mk_format_string!, which fails because there is no such crate tracing referenced by my-binary-crate. The strange thing is that in order to get to this error, several other macros in tracing had to be evaluated. Perhaps this is a bug in tracing, and it should be $crate::__mk_format_string!. However I still don't understand why this works until I add a tower dependency on my-binary-crate.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60305272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Why does C++ has an additional class name declaration? why do we have to declarer a class name in C++ like:
class MDT_DECL Transfer{
// declaration goes here
};
? What's the reason for the <DIRNAME>_DECL? I see it's especially used when the code needs to be compiled in Windows
A: You don't have to. But in windows you have to explicitly state you want the class to export symbols with _declspec(dllexport) (which is probably what that macro expands to).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11693338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python Reading JSON as Binary I need to parse a file with JSONs in it. File format is txt and content is like below:
{"key_1":"value_1", ....., "key_n":"value_n"}
{"key_1":"value_1", ....., "key_n":"value_n"}
......
There is no association between JSONs they are just in the file consecutively. They also includes non-utf characters, so it is impossible to parse them with using json library. I tried to read them line by line in byte format. Then a line that read as like below:
b'{"key_1":"value_1", ....., "key_n":"value_n"}'
I'm stuck to that step. I read a line corresponds to a JSON but it includes non-utf characters and its format is byte. How can I convert it to a dictionary?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59248219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why ZipEntry fails to work in Jelly Bean I have a ZIP file of 140 MB containing about 40 thousand MP3 files. I use the following code to play a certain file inside the ZIP file without decompressing it:
String fullPath = Environment.getExternalStorageDirectory().getPath() + "_audio_.mp3";
String path = Environment.getExternalStorageDirectory().getPath() + "mySoundFolder";
try {
ZipFile zip = new ZipFile(path + "myFile.zip");
Enumeration zipEntries = zip.entries();
ZipEntry entry = zip.getEntry("myFile" + "/" + currentWord + ".mp3");
if (entry != null) {
Log.i(MAIN_TAG, "entry found: " + entry.getName());
InputStream in = zip.getInputStream(entry);
File f = new File(fullPath);
FileOutputStream out = new FileOutputStream(f);
IOUtils.copy(in, out);
byte buffer[] = new byte[4096];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
if (f.exists())
{
Log.i(MAIN_TAG,"Audio file found!");
final MediaPlayer mp = new MediaPlayer();
mp.setDataSource(fullPath);
mp.prepare();
mp.setOnBufferingUpdateListener(null);
mp.setLooping(false);
mp.setOnPreparedListener(new OnPreparedListener()
{ public void onPrepared(MediaPlayer arg0)
{
mp.start();
Log.i(MAIN_TAG,"Pronunciation finished!");
}});
}
else
{
Log.i(MAIN_TAG,"File doesn't exist!!");
}
}
else {
// no such entry in the zip
Log.i(MAIN_TAG, "no such entry in the zip");
}
}
catch (IOException e) {
e.printStackTrace();
Log.i(MAIN_TAG,"IOException reading zip file");
}
}
There are two strange things with this code:
*
*It works flawlessly in Android 2.2 but fails in Android 4.0.3. In 2.2, it finds and plays the MP3 file as I expect, but in 4.0.3, it keeps saying it cannot find the entry in the ZIP file ("no such entry in the zip").
*If I reduce the number of MP3 files down to about 100 files, then in Android 4.0.3, it finds and plays the selected MP3 files as it should do.
Can you guys please help me to figure out what the problem is?
Thanks a lot in advance.
A: In the end, I have a workaround for this problem. I split my zip file into two files, with each containing about 20k entries. Voila, it works like a charm again.
I've heard of Java's problem with reading entries in zip files of more than 64k entries. What I have no idea why is my file has only about 40k entries but it faces the problem as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19655841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make jQuery UI Draggable/Droppable work properly in this case I have a floating toolbar with tools buttons in it. The toolbar itself is draggable using its header with title "Basic tools". Below the toolbar there is a workspace filling the whole page. Buttons on the toolbar are draggable too and droppable to the workspace. When I drag/drop a button to the workspace, it turns into a rectangle widget with some content in it.
My issue is that I want an icon to be dropped only when it's over the gridded workspace, not over the toolbar. I have added console.log to track Draggable/Droppable events and it seems that the workspace emits drop event event if I drop the element on the toolbar. I suppose it's because the workspace is below the toolbar. So, when it's being dropped on the toolbar, it should revert back to its initial position in the toolbar.
A: You have to determine where the tool is dropped: How do I get the coordinate position after using jQuery drag and drop?
You also have to determine where your toolbox is placed: http://api.jquery.com/position/
Then you have to determine the width and height of your toolbox: http://api.jquery.com/width/
After that calculate the rectangle of your toolbox and check if the tool is placed there. If it is placed there then deny dropping, if not allow dropping.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11754221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why my csv file doesn't pass the internal CSVHelper test? i'm trying to use CSVHelper inside my project. I created that files:
*
*JobApplicationMap.cs
*JobApplicationModel.cs
*ICsvParserService.cs
*CsvParserService.cs
*JobApplicationCSV.cs
*Constants.cs
But after executing the JobApplicationCSV.WriteCSV method i'm getting a CSVHelper Exception:
System.Exception
HResult=0x80131500
Nachricht = Header with name 'Company' was not found. If you are expecting some headers to be missing and want to ignore this validation, set the configuration HeaderValidated to null. You can also change the functionality to do something else, like logging the issue.
Quelle = latex_curriculum_vitae
Stapelüberwachung:
at latex_curriculum_vitae.Services.CsvParserService.ReadCsvFileToJobApplicationModel(String path) in C:\Users\Sasch\source\repos\Visual Studio\latex_curriculum_vitae-dotnet\latex_curriculum_vitae\Services\CsvParserService.cs:line 51
at latex_curriculum_vitae.JobApplicationCSV.WriteCSV(String company, String jobtitle, String city, String joburl) in C:\Users\Sasch\source\repos\Visual Studio\latex_curriculum_vitae-dotnet\latex_curriculum_vitae\JobApplicationCSV.cs:line 17
at latex_curriculum_vitae.MainWindow.BtnGenerate_Click(Object sender, EventArgs e) in C:\Users\Sasch\source\repos\Visual Studio\latex_curriculum_vitae-dotnet\latex_curriculum_vitae\MainWindow.xaml.cs:line 106
I pre created a CSV file in path, with the header:
Company,Jobtitle,City,Status,EmailSent,JobOfferUrl
So i actually don't know why it don't passes the test. Maybe i have missed anything?
A: The version of CsvHelper you are using uses CurrentCulture to get the delimiter. It appears your are in Germany, so your delimiter would be ";" instead of ",". The current version of CsvHelper forces you to pass in a CultureInfo object to CsvReader and CsvWriter with the suggestion of CultureInfo.InvariantCulture to try and mediate this issue.
In your CsvParserService try adding the following to both the ReadCsvFileToJobApplicationModel() and WriteNewCsvFile() methods.
csv.Configuration.Delimiter = ",";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64211271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to ignore mv error? I'm making a Makefile that moves an output file (foo.o) to a different directory (baz).
The output file moves as desired to the directory. However since make won't recompile the output file if I type make again, mv gets an error when it tries to move the non-existent empty file to the directory baz.
So this is what I have defined in my rule make all after all compilation:
-test -e "foo.o" || mv -f foo.o ../baz
Unfortunately, I'm still getting errors.
A: I notice nobody has actually answered the original question itself yet, specifically how to ignore errors (all the answers are currently concerned with only calling the command if it won't cause an error).
To actually ignore errors, you can simply do:
mv -f foo.o ../baz 2>/dev/null; true
This will redirect stderr output to null, and follow the command with true (which always returns 0, causing make to believe the command succeeded regardless of what actually happened), allowing program flow to continue.
A: -test -e "foo.o" || if [ -f foo.o ]; then mv -f foo.o ../baz; fi;
That should work
A: Errors in Recipes (from TFM)
To ignore errors in a recipe line, write a - at the beginning of the
line's text (after the initial tab).
So the target would be something like:
moveit:
-mv foo.o ../baz
A: +@[ -d $(dir $@) ] || mkdir -p $(dir $@)
is what I use to silently create a folder if it does not exist. For your problem something like this should work
-@[ -e "foo.o" ] && mv -f foo.o ../baz
A: Something like
test -e "foo.o" && mv -f foo.o ../baz
should work: the operator should be && instead of ||.
You can experiment with this by trying these commands:
test -e testfile && echo "going to move the file"
test -e testfile || echo "going to move the file"
A: I faced the same problem and as I am generating files, they always have different time. Workaround is set the same time to the files: touch -d '1 June 2018 11:02' file. In that case, gzip generates the same output and same md5sum. In my scenario, I don't need the time for the files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3143635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
} |
Q: Add data two tables Sequelize Here its my problem.
I create a Api rest in nodejs where i manage my database. I have 3 tables: bets, users and users-bets (this one link bets with users).
Well my problem is when im using Sequelize to do this. In my webpage, its an Angular2 app, i want to create a new bet so when i fill the formulary i send all the data to the server by post method. The problem start here because i want to add in the bets table (thats not the problem) and add the reference in bets-users.
Example:
User A create a new bet, so when he click on create, he send a post method with the bet data that contains Title, cost and earnings. In the server side, the query runs fine but what i want it is that when i insert the bet in the bet table, i want to add the id_bet and the id_user in bet-users because i want to link the user that adds the bet with the bet that he create.
I dont know if im explaining good.
Here its my code:
This is the bets model.
module.exports = (sequelize, Sequelize) => {
const Bet = sequelize.define('apuestas', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
titulo: {
type: Sequelize.STRING
},
coste: Sequelize.INTEGER,
beneficio: Sequelize.INTEGER
}, {
updatedAt: false,
classMethods: {
associate: (models) => {
Bet.belongsTo(models['usuarios_apuestas'], {
foreignKey: 'id',
targetKey: 'id_apuesta'
});
}
},
freezeTableName: true
});
return Bet;
};
I have a controller:
createBet(req, res) {
return this.service.create(this.mapper.inputUpdate(req.body))
.then(this.mapper.outputGet.bind(this.mapper, req.body))
.then(res.json.bind(res)).catch(res.send.bind(res));
}
This is the mapper:
inputUpdate(inputBet) {
return {
titulo: inputBet.titulo,
coste: inputBet.coste,
beneficio: inputBet.beneficio
};
}
And the service:
create(model) {
return this.db.create(model);
}
All this methods are separate in different files.
In summary, what i want its that when i add a new bet i want to add in the bet-users the relation between users and bets saving his id.
The bets-user table have 3 columns: id, id_bet, id_user.
Now i can find all bets in that an user participate using his id_user.
I dont know if i need to explain more my problem or if you dont understand it.
titulo = title
coste = cost
beneficio = earnings
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44263515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I see if any values in one data frame exist in any other data frame? I have eight data frames, all of which contain an id field and I want to know if any of the id values are common among all eight data frames.
I'm not looking for an intersection (where the values are common across all data frames); I simply want to know those instances where they appear in any of the other data frames.
Let's say that one of the data frames looks like this:
id TestDay
1 66 m
2 90 t
3 71 w
4 59 th
5 38 f
6 84 sa
7 15 su
8 89 m
9 18 t
10 93 w
11 88 th
12 42 f
13 10 sa
14 33 su
15 49 m
16 51 t
17 80 w
18 32 th
19 1 f
20 91 sa
21 58 su
If you wish to create eight sample data frames, you can do so by using this code eight times (with different data frame names, naturally):
x <- data.frame(id = sample(1:100, 21, FALSE), TestDay = rep(c("m","t","w","th","f","sa","su"), 3))
I want to know if any of the id values listed here appear in any of the other seven data frames, and conversely, whether any of the id values listed in any of the other seven data frames exist in this one.
How can this be done?
A: Combine all the dataframes in one dataframe with a unique id value which will distinguish each dataframe.
I created two dataframes here with data column representing the dataframe number.
library(dplyr)
x1 <- data.frame(id = round(runif(21, 1, 21)), TestDay = rep(c("m","t","w","th","f","sa","su"), 3))
x2 <- data.frame(id = round(runif(21, 1, 21)), TestDay = rep(c("m","t","w","th","f","sa","su"), 3))
combine_data <- bind_rows(x1, x2, .id = 'data')
group by the id column and count how many dataframes that id is present in.
combine_data %>%
group_by(id) %>%
summarise(count_unique = n_distinct(data))
You can add filter(count_unique > 1) to the above chain to get id's which are present in more than 1 dataframe.
A: To add to @Ronak 's answer, you can also concatenate c() the dataframe number using summarise(). This tells you which dataframe the ID comes from.
df1 <- data.frame(id = letters[1:3])
df2 <- data.frame(id = letters[4:6])
df3 <- data.frame(id = letters[5:10])
library(tidyverse)
df <- list(df1, df2, df3)
df4 <- df %>%
bind_rows(.id = "df_num") %>%
mutate(df_num = as.integer(df_num)) %>%
group_by(id) %>%
summarise(
df_found = list(c(df_num)),
df_n = map_int(df_found, length)
)
df4
A: We can use data.table methods
*
*Get the datasets in a list and rbind them with rbindlist
*Grouped by 'id' get the count of unique 'data' with uniqueN
library(data.table)
rbindlist(list(x1, x2, idcol = 'data')[, .(count_unique = uniqueN(data)), by = id]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67987370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: storing user data in firebase with unique identifiers I have a publicly accessible app. No sign in is required but I need a way to store user data in the database as an object associated with a unique key.
From what I understand, tokens would be a way to get a unique identifier from firebase(??)
I tried creating an anonymous user and getting a token like this:
let user = firebase.auth().signInAnonymously();
user.getIdToken(true);
I expected getIdToken to return a string but I get an object.
So...
1) Are tokens what I want to do this?
2) If so how can I get a new token as a string?
A: Use the following code as a global listener on ur page to check if the sign-in is successful:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous;
var unique_id = user.uid;
} else {
// User is signed out.
// ...
}
});
This snippet has been taken from the Firebase Anonymous Auth link: Click Here to open link.
A: For some reason I was trying to set up a binding to sync my app with Firebase, which I just realized I don't need at all! (I just need to push the data at the end of the poll).
Of course as soon as removed that requirement it was as simple as:
firebase.database().ref().push().set(myData);
When using the push() method, Firebase automatically generates a unique key which is all I need...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50264732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Programmatically selecting radios in jQuery buttonset makes it break down I'm building an editor function on a website using a jQuery buttonset based on radio buttons. When I load the item into the editor I need to set the selected radio button and then, of course, the user can change the option and it get's saved into the database. When the item closes I want to reset the buttonset to default.
Problem is that when I set the buttonset it works the first time I select each item then it breaks down and stops working all together.
Demo of problem: http://jsfiddle.net/kallsbo/vSmjb/
HTML:
<div id="dumpSec">
<input type="radio" name="security" id="r_public" value="public" class="rSec">
<label for="r_public"><i class="icon-globe"></i> Public</label>
<input type="radio" name="security" id="r_private" value="private" class="rSec">
<label for="r_private"><i class="icon-lock"></i> Private</label>
<input type="radio" name="security" id="r_link" value="link" class="rSec">
<label for="r_link"><i class="icon-link"></i> Anyone with the link</label>
</div>
<div>
If you use the buttons below you can programmatically select each of the radios in the buttonset once before it all breaks down...
</div>
<div>
<button id="nbr1">Select Private</button><br/>
<button id="nbr2">Select Link</button><br/>
<button id="nbr3">Select Public</button><br/>
</div>
JavaScript:
// Basic function
$("#dumpSec").buttonset();
$("#r_public").attr("checked", true);
$("#dumpSec").buttonset('refresh');
// Put in functions on the demo buttons
$( "#nbr1" )
.button()
.click(function( event ) {
$("#r_private").attr("checked", true);
$("#dumpSec").buttonset('refresh');
});
$( "#nbr2" )
.button()
.click(function( event ) {
$("#r_link").attr("checked", true);
$("#dumpSec").buttonset('refresh');
});
$( "#nbr3" )
.button()
.click(function( event ) {
$("#r_public").attr("checked", true);
$("#dumpSec").buttonset('refresh');
});
I have tried a number of things like trying to trigger the click function of the label for each radio button and so on but I can't find anything that works. Any input is appreciated!
A: http://jsfiddle.net/vSmjb/2/
you can trigger click(), to make it work
$("#r_private").click()
A: You need to use .prop() instead of .attr() to set the checked status
$("#r_link").prop("checked", true);
Demo: Fiddle
Read: Attributes vs Properties
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18954824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Crash with iOS 8 SceneKit Assets when building over command line I am building a 3D game over command line with. My script works for all other applications without a problem. Unfortunately the built IPA of the game crashes when I start it on my iPhone. If I build it with the Xcode GUI, it works fine. This error only appears for Xcode projects with SceneKit Assets.
Any idea how I can prevent this error?
A: Seems like Xcode forgets to generate the scnassets when building on command line (xcodebuild). we fixed it with the following build rule:
Script:
${DEVELOPER_TOOLS_DIR}/../usr/bin/copySceneKitAssets "${INPUT_FILE_PATH}" -o "${DERIVED_FILE_DIR}/${INPUT_FILE_NAME}”
Output Files:
$(DERIVED_FILE_DIR)/${INPUT_FILE_NAME}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25913156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it possible to get the optional parameter values from a constructor using reflection? Given a class like this:
public abstract class SomeClass
{
private string _name;
private int _someInt;
private int _anotherInt;
public SomeClass(string name, int someInt = 10, int anotherInt = 20)
{
_name = name;
_someInt = someInt;
_anotherInt = anotherInt;
}
}
Is it possible using reflection to get the optional parameter's default values?
A: Lets take a basic program:
class Program
{
static void Main(string[] args)
{
Foo();
}
public static void Foo(int i = 5)
{
Console.WriteLine("hi" +i);
}
}
And look at some IL Code.
For Foo:
.method public hidebysig static void Foo([opt] int32 i) cil managed
{
.param [1] = int32(0x00000005)
// Code size 24 (0x18)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "hi"
IL_0006: ldarg.0
IL_0007: box [mscorlib]System.Int32
IL_000c: call string [mscorlib]System.String::Concat(object,
object)
IL_0011: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: nop
IL_0017: ret
} // end of method Program::Foo
For Main:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 9 (0x9)
.maxstack 8
IL_0000: nop
IL_0001: ldc.i4.5
IL_0002: call void ConsoleApplication3.Program::Foo(int32)
IL_0007: nop
IL_0008: ret
} // end of method Program::Main
Notice that main has 5 hardcoded as part of the call, and in Foo. The calling method is actually hardcoding the value that is optional! The value is at both the call-site and callee site.
You will be able to get at the optional value by using the form:
typeof(SomeClass).GetConstructor(new []{typeof(string),typeof(int),typeof(int)})
.GetParameters()[1].RawDefaultValue
On MSDN for DefaultValue (mentioned in the other answer):
This property is used only in the execution context. In the reflection-only context, use the RawDefaultValue property instead. MSDN
And finally a POC:
static void Main(string[] args)
{
var optionalParameterInformation = typeof(SomeClass).GetConstructor(new[] { typeof(string), typeof(int), typeof(int) })
.GetParameters().Select(p => new {p.Name, OptionalValue = p.RawDefaultValue});
foreach (var p in optionalParameterInformation)
Console.WriteLine(p.Name+":"+p.OptionalValue);
Console.ReadKey();
}
http://bartdesmet.net/blogs/bart/archive/2008/10/31/c-4-0-feature-focus-part-1-optional-parameters.aspx
A: DefaultValue of the ParameterInfo class is what you are looking for:
var defaultValues = typeof(SomeClass).GetConstructors()[0].GetParameters().Select(t => t.DefaultValue).ToList();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14009359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How do I find a .NET remoting memory leak on select machines? The memory leak is not happening on every machine, but reliably on a couple at my work, and it's looking like close to 10% in the field.
I have a product that uses a Windows service to monitor user input to launch alerts, paired with a visual application that serves only to sit in the system tray, and allow the user to make configuration changes.
I chose to use a remoted object to share the configuration information between the two processes. In the service it is called serviceConfig, and in the visual application it is called configData. The object is created on the server first, and then remoted as follows:
try
{
InitializeComponent();
setAppInitDLL(thisDirectory);
serviceConfig = new serviceConfigData();
Regex getVersion = new Regex("Version=(?<ver>[^,]*)");
if (getVersion.IsMatch(Assembly.GetExecutingAssembly().FullName))
{
serviceConfig.Version = new Version(getVersion.Match(Assembly.GetExecutingAssembly().FullName).Result("${ver}").ToString());
}
// Create the server channel for remoting serviceConfig.
serverChannel = new TcpServerChannel(9090);
ChannelServices.RegisterChannel(serverChannel, false);
RemotingServices.Marshal(this.serviceConfig, "ServiceConfigData");
baseLease = (ILease)RemotingServices.GetLifetimeService(serviceConfig);
lock (Logger) { Logger.Write(String.Format("The name of the channel is {0}", serverChannel.ChannelName)); }
lock (Logger) { Logger.Write("Exiting Constructor"); }
}
catch (Exception ex)
{
lock (Logger) { Logger.Write(String.Format("Error in Constructor:{0}", ex.Message)); }
}
Then in the visual application I have a private object that I connect using:
configData = (serviceConfigData)Activator.GetObject(typeof(serviceConfigData), "tcp://localhost:9090/ServiceConfigData");
When reading or writing to this object, I have catch statements for Socket Exceptions and Remoting Exceptions which then call this same statement.
On most machines this works without leaking memory, but on some it leaks very quickly. All machines at work have .NET 3.5, some are XP, a couple are Vista. The problem has only been seen on XP machines, and the machines in the field are all XP.
Any ideas where I should be looking, and as a secondary question, should I be using something completely different from this?
A: My first thought would be to profile the application on the machines you're seeing the leak with something like Red Gate's Memory Profiler.
It'll be a lot more reliable than attempting to guess what the leak might be.
As for chosing the right technology, if all your machines will have .NET 3.5 installed you might want to consider migrating to WCF (primarily Named Pipes) for your inter-process communication. Check this SO post for more detail...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1840090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery - Clear Textboxes I have a drop down list and two textboxes on an ASP.Net MVC 3 view. The drop down lists numbers from 1 to 10. The two textboxes are both wired up to use the JQuery Datepicker.
When the user selects an option from the drop down, I would like JQuery code to clear the values in the two textboxes.
I have written the JQuery code below which does just this, however, when I go to submit the form details to the post method within my controller, the dates I have selected for the two textboxes are cleared.
This is my code to date:
$(document).ready(function () {
$('#equipment_warrantyLength').change(ResetDates); //fires when drop down changed
function ResetDates() {
alert("hello");
$("#equipment_purchaseDate").val(''); // clear textbox
$('#equipment_warrentyExpires').val(''); //clear textbox
}
});
The textboxes should only be cleared when the drop down is selected, but currently, they also clear when the user attempts to submit the form.
Any feedback would be much appreciated.
A: When the form is submitted to the server the page is reloaded. Unless you set the submitted values in the textboxes upon loading the page again they are cleared. ASP.NET MVC doesn't use Viewstate like ASP.NET WebForms so unless you manually init the fields they will be empty when pages are reloaded after a form submission.
Update:
You can also submit the form data via jQuery. In order to do that you would do something like this:
*
*Add a click handler to the submit button. (If it is declared as you should also change it to a normal button so that the browser wont submit the form automatically.
*In the click handler add code to do the ajax submission. See this question for tips on that Submit form using AJAX and jQuery
But en the end it might be easier to just put the submitted data in the viewmodel and reinitialize the fields in the view after submission.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5079344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error while buliding pysha3 with pip? ERROR: Failed building wheel for pysha3 when I try to install with pip install pysha3, I get the error "ERROR: Failed building wheel for pysha3". I did already install the Windows build tools. I can't find much help on Google unfortunately. I am on Windows 11.
Here is the log
`
PS C:\Users\Alexis> pip3 install pysha3
Collecting pysha3
Using cached pysha3-1.0.2.tar.gz (829 kB)
Preparing metadata (setup.py) ... done
Building wheels for collected packages: pysha3
Building wheel for pysha3 (setup.py) ... error
error: subprocess-exited-with-error
× python setup.py bdist_wheel did not run successfully.
│ exit code: 1
╰─> [16 lines of output]
running bdist_wheel
running build
running build_py
creating build
creating build\lib.win-amd64-cpython-311
copying sha3.py -> build\lib.win-amd64-cpython-311
running build_ext
building '_pysha3' extension
creating build\temp.win-amd64-cpython-311
creating build\temp.win-amd64-cpython-311\Release
creating build\temp.win-amd64-cpython-311\Release\Modules
creating build\temp.win-amd64-cpython-311\Release\Modules\_sha3
"C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -DPY_WITH_KECCAK=1 -IC:\Python311\include -IC:\Python311\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\cppwinrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" /TcModules/_sha3/sha3module.c /Fobuild\temp.win-amd64-cpython-311\Release\Modules/_sha3/sha3module.obj
sha3module.c
C:\Users\Alexis\AppData\Local\Temp\pip-install-78ji94vk\pysha3_9e9c90f2f01445aeb1ab3ed6a6c14e42\Modules\_sha3\backport.inc(78): fatal error C1083: Cannot open include file: 'pystrhex.h': No such file or directory
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.34.31933\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for pysha3
Running setup.py clean for pysha3
Failed to build pysha3
Installing collected packages: pysha3
Running setup.py install for pysha3 ... error
error: subprocess-exited-with-error
× Running setup.py install for pysha3 did not run successfully.
│ exit code: 1
╰─> [18 lines of output]
running install
C:\Python311\Lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
running build
running build_py
creating build
creating build\lib.win-amd64-cpython-311
copying sha3.py -> build\lib.win-amd64-cpython-311
running build_ext
building '_pysha3' extension
creating build\temp.win-amd64-cpython-311
creating build\temp.win-amd64-cpython-311\Release
creating build\temp.win-amd64-cpython-311\Release\Modules
creating build\temp.win-amd64-cpython-311\Release\Modules\_sha3
"C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -DPY_WITH_KECCAK=1 -IC:\Python311\include -IC:\Python311\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\cppwinrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" /TcModules/_sha3/sha3module.c /Fobuild\temp.win-amd64-cpython-311\Release\Modules/_sha3/sha3module.obj
sha3module.c
C:\Users\Alexis\AppData\Local\Temp\pip-install-78ji94vk\pysha3_9e9c90f2f01445aeb1ab3ed6a6c14e42\Modules\_sha3\backport.inc(78): fatal error C1083: Cannot open include file: 'pystrhex.h': No such file or directory
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.34.31933\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure
× Encountered error while trying to install package.
╰─> pysha3
note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.
`
I did install the Windows Build tools for c++
A: Having this same issue, last time I resolved it by back-switching to Python 3.8.7 perhaps. But now I installed 3.11 and now again pysha3 is not installing. (Window 10)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74369660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Gekko: MINLP - Error options.json file not found I am trying to solve a MINLP problem using first the IPOPT solver to get an initial solution then the APOPT to get the mixed integer solution. However, I get the following error when calling the APOPT solver:
Error: Exception: Access Violation At line 359 of file ./f90/cqp.f90 Traceback: not available, compile with -ftrace=frame or -ftrace=full Error: 'results.json' not found. Check above for additional error details Traceback (most recent call last): File "optimisation_stack.py", line 244, in Optimise_G(t,ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous, G_max, G_min) File "optimisation_stack.py", line 134, in Optimise_G sol = MINLP(xinit, A, B, A_eq, B_eq, LB ,UB, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous) File "optimisation_stack.py", line 215, in MINLP m_APOPT.solve(disp = False) File "C:\Users\Zineb\AppData\Local\Programs\Python\Python37\lib\site-packages\gekko\gekko.py", line 2227, in solve self.load_JSON() File "C:\Users\Zineb\AppData\Local\Programs\Python\Python37\lib\site-packages\gekko\gk_post_solve.py", line 13, in load_JSON f = open(os.path.join(self._path,'options.json')) FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Zineb\AppData\Local\Temp\tmptdgafg1zgk_model1\options.json'
My code is the following, I tried to simplify it as much as possible :
import numpy as np
from gekko import GEKKO
# Define matrices A,A_eq, and vectors b, b_eq for the optimization
def Optimise_G(t,ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous, G_max, G_min):
Mbig_1 = T*C
Mbig_2 = C
nb_phases = len(G_next)
b_max = len(t)
no_lanegroups = len(q)
A_eq = np.zeros(((nb_phases+1)*b_max + 1, (3*nb_phases+3)*b_max+nb_phases))
for i in range(nb_phases):
A_eq[0][i] = 1
#B_eq = np.zeros(((nb_phases+1)*b_max + 1, 1))
B_eq = np.zeros((nb_phases+1)*b_max + 1)
B_eq[0] = C - sum(Y[0:nb_phases])
counter_eq = 0
# G(i)=Ga(i,b)+Gb(i,b)+Gc(i,b)
for b in range(b_max):
for i in range(nb_phases):
counter_eq = counter_eq + 1
A_eq[counter_eq][i] = 1
A_eq[counter_eq][nb_phases*(b+1)+ i] = -1
A_eq[counter_eq][nb_phases*b_max + nb_phases*(b+1) + i] = -1
A_eq[counter_eq][2*nb_phases*b_max + nb_phases*(b+1) + i] = -1
# ya(b)+y(b)+y(c)=1
for b in range(b_max):
counter_eq = counter_eq + 1
A_eq[counter_eq][3*nb_phases*b_max + nb_phases + b] = 1
A_eq[counter_eq][(3*nb_phases+1)*b_max + nb_phases + b] = 1
A_eq[counter_eq][(3*nb_phases+2)*b_max + nb_phases + b] = 1
B_eq[counter_eq] = 1
A = np.zeros((no_lanegroups + (2*3*nb_phases+4)*b_max, (3*nb_phases+3)*b_max+nb_phases))
B = np.zeros(no_lanegroups + (2*3*nb_phases+4)*b_max)
counter = -1
# Sum Gi (i in Ij)>=Gj,min
for j in range(no_lanegroups):
counter = counter + 1
for i in range(k[j], l[j]+1):
A[counter][i-1] = -1
B[counter] = -C*qc[j]/s[j]
# ya(b)G_lb(i)<=Ga(i,b), yb(b)G_lb(i)<=Gb(i,b), yc(b)G_lb(i)<=Gc(i,b)
for b in range(b_max):
for i in range(nb_phases):
counter = counter + 1
A[counter][nb_phases*(b+1)+i] = -1
A[counter][3*nb_phases*b_max + nb_phases + b] = G_min[i]
B[counter] = 0
counter = counter + 1
A[counter][nb_phases*b_max + nb_phases*(b+1) + i] = -1
A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = G_min[i]
B[counter] = 0
counter = counter + 1
A[counter][2*nb_phases*b_max + nb_phases*(b+1) +i] = -1
A[counter][(3*nb_phases+2)*b_max + nb_phases + b] = G_min[i]
B[counter] = 0
# ya(b)Gmax(i)>=Ga(i,b), yb(b)Gmax(i)>=Gb(i,b), yc(b)Gmax(i)>=Gc(i,b)
for b in range(b_max):
for i in range(nb_phases):
counter = counter + 1
A[counter][nb_phases*(b+1) +i] = 1
A[counter][3*nb_phases*b_max + nb_phases + b] = -G_max[i]
B[counter] = 0
counter = counter + 1
A[counter][nb_phases*b_max + nb_phases*(b+1) + i] = 1
A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = -G_max[i]
B[counter] = 0
counter = counter + 1
A[counter][2*nb_phases*b_max + nb_phases*(b+1) +i] = 1
A[counter][(3*nb_phases+2)*b_max + nb_phases + b] = -G_max[i]
B[counter] = 0
# (1-yc(b))t(b)<=(T-1)C+sum(Gi(1:l(jofbuses(b))))+sum(Y(1:l(jofbuses(b))-1))
for b in range(b_max):
counter = counter + 1
A[counter][0:l[jofbuses[b]-1]] = -np.ones((1,l[jofbuses[b]-1]))
A[counter][(3*nb_phases+2)*b_max+nb_phases+b] = -t[b]
B[counter] = -t[b] + (T-1)*C + sum(Y[0:l[jofbuses[b]-1]-1])
# (T-1)C+sum(Gi(1:l(jofbuses(b))))+sum(Y(1:l(jofbuses(b))-1))<=yc(b)t(b)+(1-yc(b))Mbig_1
for b in range(b_max):
counter = counter + 1
A[counter][0:l[jofbuses[b]-1]] = np.ones((1,l[jofbuses[b]-1]))
A[counter][(3*nb_phases+2)*b_max+nb_phases+b] = -t[b] + Mbig_1
B[counter] = Mbig_1 - (T-1)*C - sum(Y[0:l[jofbuses[b]-1]-1])
# -Mbig_2(1-yb(b))<=db(b)=right-hand side of Equation (6)
for b in range(b_max):
counter = counter + 1
constant = q[jofbuses[b]-1]/s[jofbuses[b]-1]*(t[b] - (T-1)*C + sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases]))+ (T-1)*C + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b]
A[counter][0:k[jofbuses[b]-1]-1] = -np.ones((1,k[jofbuses[b]-1]-1))
A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = Mbig_2
B[counter] = constant + Mbig_2
# db(b)<=Mbig_2 yb(b)
for b in range(b_max):
counter = counter + 1
constant = q[jofbuses[b]-1]/s[jofbuses[b]-1]*(t[b] - (T-1)*C +sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases]))+ (T-1)*C + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b]
A[counter][0:k[jofbuses[b]-1]-1] = np.ones((1,k[jofbuses[b]-1]-1))
A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = -Mbig_2
B[counter] = -constant
#Lower Bound LB
LB_zeros = np.zeros(3*b_max*(nb_phases+1))
G_min = np.array(G_min)
LB = np.append(G_min, LB_zeros)
#Upper Bound UB
UB = np.ones(3*b_max)
G_max = np.array(G_max)
for i in range(3*b_max+1):
UB = np.concatenate((G_max,UB))
xinit = np.array([(a+b)/2 for a, b in zip(UB, LB)])
sol = MINLP(xinit, A, B, A_eq, B_eq, LB ,UB, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous)
The objective function:
def objective_fun(x, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous):
nb_phases = len(G_next)
b_max = len(t)
no_lanegroups = len(q)
obj = 0
obj_a = 0
obj_b = 0
G = x[0:nb_phases]
for j in range(no_lanegroups):
delay_a = 0.5*q[j]/(1-q[j]/s[j]) * (pow((sum(G_previous[l[j]:nb_phases]) + sum(G[0:k[j]-1]) + sum(Y[l[j]-1:nb_phases]) + sum(Y[0:k[j]-1])),2) + pow(sum(G[l[j]:nb_phases]) + sum(G_next[0:k[j]-1]) + sum(Y[l[j]-1:nb_phases]) + sum(Y[0:k[j]-1]),2))
obj = obj + oa*delay_a
obj_a = obj_a + oa*delay_a
for b in range(b_max):
delay_b1 = x[(3*nb_phases+1)*b_max + nb_phases + b]*(q[jofbuses[b]-1]/s[jofbuses[b]-1] * (t[b] - (T-1)*C + sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases])) + (T-1)*C - t[b] + sum(Y[0:k[jofbuses[b]-1]-1]))
delay_b2 = x[(3*nb_phases+2)*b_max + nb_phases + b-1]*(q[jofbuses[b]-1]/s[jofbuses[b]-1] * (t[b] - (T-1)*C - sum(Y[0:l[jofbuses[b]-1]-1])) + T*C + sum(G_next[0:k[jofbuses[b]-1]-1]) + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b])
delay_b3 = sum(x[nb_phases*b_max + nb_phases*b:nb_phases*b_max + nb_phases*b+k[jofbuses[b]-1]-1]) - q[jofbuses[b]-1]/s[jofbuses[b]-1]*sum(x[2*nb_phases*b_max + nb_phases*b:2*nb_phases*b_max + nb_phases*b +l[jofbuses[b]-1]])
delay_b = delay_b1+delay_b2 +delay_b3
obj = obj + delay_b*ob[b]
obj_b = obj_b + delay_b*ob[b]
return obj
MINLP solver:
def MINLP(xinit, A, B, A_eq, B_eq, LB ,UB, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous):
nb_phases = len(G_next)
b_max = len(t)
## First Solver: IPOPT to get an initial guess
m_IPOPT = GEKKO(remote = False)
m_IPOPT.options.SOLVER = 3 #(IPOPT)
# Array Variable
rows = nb_phases + 3*b_max*(nb_phases+1)#48
x_initial = np.empty(rows,dtype=object)
for i in range(3*nb_phases*b_max+nb_phases+1):
x_initial[i] = m_IPOPT.Var(value = xinit[i], lb = LB[i], ub = UB[i])#, integer = False)
for i in range(3*nb_phases*b_max+nb_phases+1, (3*nb_phases+3)*b_max+nb_phases):
x_initial[i] = m_IPOPT.Var(value = xinit[i], lb = LB[i], ub = UB[i])#, integer = True)
# Constraints
m_IPOPT.axb(A,B,x_initial,etype = '<=',sparse=False)
m_IPOPT.axb(A_eq,B_eq,x_initial,etype = '=',sparse=False)
# Objective Function
f = objective_fun(x_initial, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous)
m_IPOPT.Obj(f)
#Solver
m_IPOPT.solve(disp = True)
####################################################################################################
## Second Solver: APOPT to solve MINLP
m_APOPT = GEKKO(remote = False)
m_APOPT.options.SOLVER = 1 #(APOPT)
x = np.empty(rows,dtype=object)
for i in range(3*nb_phases*b_max+nb_phases+1):
x[i] = m_APOPT.Var(value = x_initial[i], lb = LB[i], ub = UB[i], integer = False)
for i in range(3*nb_phases*b_max+nb_phases+1, (3*nb_phases+3)*b_max+nb_phases):
x[i] = m_APOPT.Var(value = x_initial[i], lb = LB[i], ub = UB[i], integer = True)
# Constraints
m_APOPT.axb(A,B,x,etype = '<=',sparse=False)
m_APOPT.axb(A_eq,B_eq,x,etype = '=',sparse=False)
# Objective Function
f = objective_fun(x, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous)
m_APOPT.Obj(f)
#Solver
m_APOPT.solve(disp = False)
return x
Define parameters and call Optimise_G:
#Define Parameters
C = 120
T = 31
b_max = 2
G_base = [12,31,12,11,1,41]
G_max = [106, 106, 106, 106, 106, 106]
G_min = [7,3,7,10,0,7]
G_previous = [7.3333333, 34.16763, 7.1333333, 10.0, 2.2008602e-16, 47.365703]
Y = [2, 2, 3, 2, 2, 3]
jofbuses = [9,3]
k = [3,1,6,4,1,2,5,4,2,3]
l = [3,2,6,5,1,3,6,4,3,4]
nb_phases = 6
oa = 1.25
ob = [39,42]
t = [3600.2, 3603.5]
q = [0.038053758888888886, 0.215206065, 0.11325116416666667, 0.06299876472222223,0.02800455611111111,0.18878488361111112,0.2970903402777778, 0.01876728472222222, 0.2192723663888889, 0.06132227222222222]
qc = [0.04083333333333333, 0.2388888888888889, 0.10555555555555556, 0.0525, 0.030555555555555555, 0.20444444444444446,0.31083333333333335, 0.018333333333333333, 0.12777777777777777, 0.07138888888888889]
s = [1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5]
nb_phases = len(G_base)
G_max = []
for i in range(nb_phases):
G_max.append(C - sum(Y[0:nb_phases]))
Optimise_G(t,ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous, G_max, G_min)
Is there a way to solve this issue?
Thanks a lot !
A: The Windows version of the APOPT solver crashed and wasn't able to find a solution. However, the online Linux version of APOPT is able to find a solution. Get the latest version of Gekko (v1.0.0 pre-release) available on GitHub. This will be available with pip install gekko --upgrade when the new version is published but for now you need to copy the source to Lib\site-packages\gekko\gekko.py. After updating gekko, switch to remote=True as shown below.
import numpy as np
from gekko import GEKKO
# Define matrices A,A_eq, and vectors b, b_eq for the optimization
def Optimise_G(t,ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous, G_max, G_min):
Mbig_1 = T*C
Mbig_2 = C
nb_phases = len(G_next)
b_max = len(t)
no_lanegroups = len(q)
A_eq = np.zeros(((nb_phases+1)*b_max + 1, (3*nb_phases+3)*b_max+nb_phases))
for i in range(nb_phases):
A_eq[0][i] = 1
#B_eq = np.zeros(((nb_phases+1)*b_max + 1, 1))
B_eq = np.zeros((nb_phases+1)*b_max + 1)
B_eq[0] = C - sum(Y[0:nb_phases])
counter_eq = 0
# G(i)=Ga(i,b)+Gb(i,b)+Gc(i,b)
for b in range(b_max):
for i in range(nb_phases):
counter_eq = counter_eq + 1
A_eq[counter_eq][i] = 1
A_eq[counter_eq][nb_phases*(b+1)+ i] = -1
A_eq[counter_eq][nb_phases*b_max + nb_phases*(b+1) + i] = -1
A_eq[counter_eq][2*nb_phases*b_max + nb_phases*(b+1) + i] = -1
# ya(b)+y(b)+y(c)=1
for b in range(b_max):
counter_eq = counter_eq + 1
A_eq[counter_eq][3*nb_phases*b_max + nb_phases + b] = 1
A_eq[counter_eq][(3*nb_phases+1)*b_max + nb_phases + b] = 1
A_eq[counter_eq][(3*nb_phases+2)*b_max + nb_phases + b] = 1
B_eq[counter_eq] = 1
A = np.zeros((no_lanegroups + (2*3*nb_phases+4)*b_max, (3*nb_phases+3)*b_max+nb_phases))
B = np.zeros(no_lanegroups + (2*3*nb_phases+4)*b_max)
counter = -1
# Sum Gi (i in Ij)>=Gj,min
for j in range(no_lanegroups):
counter = counter + 1
for i in range(k[j], l[j]+1):
A[counter][i-1] = -1
B[counter] = -C*qc[j]/s[j]
# ya(b)G_lb(i)<=Ga(i,b), yb(b)G_lb(i)<=Gb(i,b), yc(b)G_lb(i)<=Gc(i,b)
for b in range(b_max):
for i in range(nb_phases):
counter = counter + 1
A[counter][nb_phases*(b+1)+i] = -1
A[counter][3*nb_phases*b_max + nb_phases + b] = G_min[i]
B[counter] = 0
counter = counter + 1
A[counter][nb_phases*b_max + nb_phases*(b+1) + i] = -1
A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = G_min[i]
B[counter] = 0
counter = counter + 1
A[counter][2*nb_phases*b_max + nb_phases*(b+1) +i] = -1
A[counter][(3*nb_phases+2)*b_max + nb_phases + b] = G_min[i]
B[counter] = 0
# ya(b)Gmax(i)>=Ga(i,b), yb(b)Gmax(i)>=Gb(i,b), yc(b)Gmax(i)>=Gc(i,b)
for b in range(b_max):
for i in range(nb_phases):
counter = counter + 1
A[counter][nb_phases*(b+1) +i] = 1
A[counter][3*nb_phases*b_max + nb_phases + b] = -G_max[i]
B[counter] = 0
counter = counter + 1
A[counter][nb_phases*b_max + nb_phases*(b+1) + i] = 1
A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = -G_max[i]
B[counter] = 0
counter = counter + 1
A[counter][2*nb_phases*b_max + nb_phases*(b+1) +i] = 1
A[counter][(3*nb_phases+2)*b_max + nb_phases + b] = -G_max[i]
B[counter] = 0
# (1-yc(b))t(b)<=(T-1)C+sum(Gi(1:l(jofbuses(b))))+sum(Y(1:l(jofbuses(b))-1))
for b in range(b_max):
counter = counter + 1
A[counter][0:l[jofbuses[b]-1]] = -np.ones((1,l[jofbuses[b]-1]))
A[counter][(3*nb_phases+2)*b_max+nb_phases+b] = -t[b]
B[counter] = -t[b] + (T-1)*C + sum(Y[0:l[jofbuses[b]-1]-1])
# (T-1)C+sum(Gi(1:l(jofbuses(b))))+sum(Y(1:l(jofbuses(b))-1))<=yc(b)t(b)+(1-yc(b))Mbig_1
for b in range(b_max):
counter = counter + 1
A[counter][0:l[jofbuses[b]-1]] = np.ones((1,l[jofbuses[b]-1]))
A[counter][(3*nb_phases+2)*b_max+nb_phases+b] = -t[b] + Mbig_1
B[counter] = Mbig_1 - (T-1)*C - sum(Y[0:l[jofbuses[b]-1]-1])
# -Mbig_2(1-yb(b))<=db(b)=right-hand side of Equation (6)
for b in range(b_max):
counter = counter + 1
constant = q[jofbuses[b]-1]/s[jofbuses[b]-1]*(t[b] - (T-1)*C + sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases]))+ (T-1)*C + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b]
A[counter][0:k[jofbuses[b]-1]-1] = -np.ones((1,k[jofbuses[b]-1]-1))
A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = Mbig_2
B[counter] = constant + Mbig_2
# db(b)<=Mbig_2 yb(b)
for b in range(b_max):
counter = counter + 1
constant = q[jofbuses[b]-1]/s[jofbuses[b]-1]*(t[b] - (T-1)*C +sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases]))+ (T-1)*C + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b]
A[counter][0:k[jofbuses[b]-1]-1] = np.ones((1,k[jofbuses[b]-1]-1))
A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = -Mbig_2
B[counter] = -constant
#Lower Bound LB
LB_zeros = np.zeros(3*b_max*(nb_phases+1))
G_min = np.array(G_min)
LB = np.append(G_min, LB_zeros)
#Upper Bound UB
UB = np.ones(3*b_max)
G_max = np.array(G_max)
for i in range(3*b_max+1):
UB = np.concatenate((G_max,UB))
xinit = np.array([(a+b)/2 for a, b in zip(UB, LB)])
sol = MINLP(xinit, A, B, A_eq, B_eq, LB ,UB, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous)
def objective_fun(x, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous):
nb_phases = len(G_next)
b_max = len(t)
no_lanegroups = len(q)
obj = 0
obj_a = 0
obj_b = 0
G = x[0:nb_phases]
for j in range(no_lanegroups):
delay_a = 0.5*q[j]/(1-q[j]/s[j]) * (pow((sum(G_previous[l[j]:nb_phases]) + sum(G[0:k[j]-1]) + sum(Y[l[j]-1:nb_phases]) + sum(Y[0:k[j]-1])),2) + pow(sum(G[l[j]:nb_phases]) + sum(G_next[0:k[j]-1]) + sum(Y[l[j]-1:nb_phases]) + sum(Y[0:k[j]-1]),2))
obj = obj + oa*delay_a
obj_a = obj_a + oa*delay_a
for b in range(b_max):
delay_b1 = x[(3*nb_phases+1)*b_max + nb_phases + b]*(q[jofbuses[b]-1]/s[jofbuses[b]-1] * (t[b] - (T-1)*C + sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases])) + (T-1)*C - t[b] + sum(Y[0:k[jofbuses[b]-1]-1]))
delay_b2 = x[(3*nb_phases+2)*b_max + nb_phases + b-1]*(q[jofbuses[b]-1]/s[jofbuses[b]-1] * (t[b] - (T-1)*C - sum(Y[0:l[jofbuses[b]-1]-1])) + T*C + sum(G_next[0:k[jofbuses[b]-1]-1]) + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b])
delay_b3 = sum(x[nb_phases*b_max + nb_phases*b:nb_phases*b_max + nb_phases*b+k[jofbuses[b]-1]-1]) - q[jofbuses[b]-1]/s[jofbuses[b]-1]*sum(x[2*nb_phases*b_max + nb_phases*b:2*nb_phases*b_max + nb_phases*b +l[jofbuses[b]-1]])
delay_b = delay_b1+delay_b2 +delay_b3
obj = obj + delay_b*ob[b]
obj_b = obj_b + delay_b*ob[b]
return obj
def MINLP(xinit, A, B, A_eq, B_eq, LB ,UB, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous):
nb_phases = len(G_next)
b_max = len(t)
## First Solver: IPOPT to get an initial guess
m_IPOPT = GEKKO(remote = True)
m_IPOPT.options.SOLVER = 3 #(IPOPT)
# Array Variable
rows = nb_phases + 3*b_max*(nb_phases+1)#48
x_initial = np.empty(rows,dtype=object)
for i in range(3*nb_phases*b_max+nb_phases+1):
x_initial[i] = m_IPOPT.Var(value = xinit[i], lb = LB[i], ub = UB[i])#, integer = False)
for i in range(3*nb_phases*b_max+nb_phases+1, (3*nb_phases+3)*b_max+nb_phases):
x_initial[i] = m_IPOPT.Var(value = xinit[i], lb = LB[i], ub = UB[i])#, integer = True)
# Constraints
m_IPOPT.axb(A,B,x_initial,etype = '<=',sparse=False)
m_IPOPT.axb(A_eq,B_eq,x_initial,etype = '=',sparse=False)
# Objective Function
f = objective_fun(x_initial, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous)
m_IPOPT.Obj(f)
#Solver
m_IPOPT.solve(disp = True)
####################################################################################################
## Second Solver: APOPT to solve MINLP
m_APOPT = GEKKO(remote = True)
m_APOPT.options.SOLVER = 1 #(APOPT)
x = np.empty(rows,dtype=object)
for i in range(3*nb_phases*b_max+nb_phases+1):
x[i] = m_APOPT.Var(value = x_initial[i], lb = LB[i], ub = UB[i], integer = False)
for i in range(3*nb_phases*b_max+nb_phases+1, (3*nb_phases+3)*b_max+nb_phases):
x[i] = m_APOPT.Var(value = x_initial[i], lb = LB[i], ub = UB[i], integer = True)
# Constraints
m_APOPT.axb(A,B,x,etype = '<=',sparse=False)
m_APOPT.axb(A_eq,B_eq,x,etype = '=',sparse=False)
# Objective Function
f = objective_fun(x, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous)
m_APOPT.Obj(f)
#Solver
m_APOPT.solve(disp = True)
return x
#Define Parameters
C = 120
T = 31
b_max = 2
G_base = [12,31,12,11,1,41]
G_max = [106, 106, 106, 106, 106, 106]
G_min = [7,3,7,10,0,7]
G_previous = [7.3333333, 34.16763, 7.1333333, 10.0, 2.2008602e-16, 47.365703]
Y = [2, 2, 3, 2, 2, 3]
jofbuses = [9,3]
k = [3,1,6,4,1,2,5,4,2,3]
l = [3,2,6,5,1,3,6,4,3,4]
nb_phases = 6
oa = 1.25
ob = [39,42]
t = [3600.2, 3603.5]
q = [0.038053758888888886, 0.215206065, 0.11325116416666667, 0.06299876472222223,0.02800455611111111,0.18878488361111112,0.2970903402777778, 0.01876728472222222, 0.2192723663888889, 0.06132227222222222]
qc = [0.04083333333333333, 0.2388888888888889, 0.10555555555555556, 0.0525, 0.030555555555555555, 0.20444444444444446,0.31083333333333335, 0.018333333333333333, 0.12777777777777777, 0.07138888888888889]
s = [1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5]
nb_phases = len(G_base)
G_max = []
for i in range(nb_phases):
G_max.append(C - sum(Y[0:nb_phases]))
Optimise_G(t,ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous, G_max, G_min)
The APOPT solver is successful and returns an integer solution.
APMonitor, Version 1.0.0
APMonitor Optimization Suite
----------------------------------------------------------------
--------- APM Model Size ------------
Each time step contains
Objects : 2
Constants : 0
Variables : 48
Intermediates: 0
Connections : 96
Equations : 1
Residuals : 1
Number of state variables: 48
Number of total equations: - 105
Number of slack variables: - 0
---------------------------------------
Degrees of freedom : -57
* Warning: DOF <= 0
----------------------------------------------
Steady State Optimization with APOPT Solver
----------------------------------------------
Iter: 1 I: 0 Tm: 0.00 NLPi: 1 Dpth: 0 Lvs: 3 Obj: 1.64E+04 Gap: NaN
Iter: 2 I: -1 Tm: 0.00 NLPi: 2 Dpth: 1 Lvs: 2 Obj: 1.64E+04 Gap: NaN
Iter: 3 I: 0 Tm: 0.00 NLPi: 3 Dpth: 1 Lvs: 3 Obj: 1.81E+04 Gap: NaN
Iter: 4 I: -1 Tm: 0.01 NLPi: 6 Dpth: 1 Lvs: 2 Obj: 1.64E+04 Gap: NaN
--Integer Solution: 2.15E+04 Lowest Leaf: 1.81E+04 Gap: 1.68E-01
Iter: 5 I: 0 Tm: 0.00 NLPi: 4 Dpth: 2 Lvs: 1 Obj: 2.15E+04 Gap: 1.68E-01
Iter: 6 I: -1 Tm: 0.01 NLPi: 4 Dpth: 2 Lvs: 0 Obj: 1.81E+04 Gap: 1.68E-01
No additional trial points, returning the best integer solution
Successful solution
---------------------------------------------------
Solver : APOPT (v1.0)
Solution time : 4.670000000623986E-002 sec
Objective : 21455.9882666580
Successful solution
---------------------------------------------------
If you need to use remote=False (local solution) on Linux then the new executable will be available with the new release of Gekko. There are some compiler differences and it appears that the Windows FORTRAN compiler that creates the local apm.exe is not as good as the Linux FORTRAN compiler that creates the local apm executable. Those executables are in the bin folder: Lib\site-packages\gekko\bin of the Python folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67431986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to convert sample in AWS Lambda from javascript to Java? I currently am trying to convert this javascript sample:
javascript
'use strict';
exports.handler = (event, context, callback) => {
callback(null, {"speech": "hello lambda js"});
};
output from hitting test button in aws lambda
{
"speech": "hello lambda js"
}
Now I want to convert this in the simplest way into a Java program.
This is what I tried:
public class Sample implements RequestHandler<String, String> {
@Override public String handleRequest(String s, Context context) {
return "{\"speech\": \"hello lambda java\"}";
}
}
but hitting the test button in AWS lamda complains:
{
"errorMessage": "An error occurred during JSON parsing",
"errorType": "java.lang.RuntimeException",
"stackTrace": [],
"cause": {
"errorMessage": "com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token\n at [Source: lambdainternal.util.NativeMemoryAsInputStream@5f375618; line: 1, column: 1]",
"errorType": "java.io.UncheckedIOException",
"stackTrace": [],
"cause": {
"errorMessage": "Can not deserialize instance of java.lang.String out of START_OBJECT token\n at [Source: lambdainternal.util.NativeMemoryAsInputStream@5f375618; line: 1, column: 1]",
"errorType": "com.fasterxml.jackson.databind.JsonMappingException",
"stackTrace": [
"com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)",
"com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:857)",
"com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:62)",
"com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)",
"com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1511)",
"com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1102)"
]
}
}
}
A: Your javascript function is returning an object literal, not a JSON string. Probably you need to do the parallel in Java, which would be to return an instance of a class that contains a property named speech, which a getter and setter for speech, and with the value of speech set to "hello lambda java". AWS will probably take care of serializing that object to the JSON response you want.
More typing in Java than Javascript. Ha! I punned.
A: It doesn't really make sense but send the method something like "hello", not JSON. Lambda tries to be smarter than you and, if it sees something that looks like JSON it tries to parse it. But then you ask for a string so it gets confused. Personally I think this is a bug but since you can't pass a "Content-Type" it has to guess.
For reference, if I use this code:
public class HelloWorldLambdaHandler implements RequestHandler<String, String> {
public String handleRequest(String inputObject, Context context) {
context.getLogger().log("context logger - got \"" + inputObject + "\" from call");
return "{\"speech\": \"hello lambda java\"}";
}
}
and test with the string "hello" (yes, including the quotes) I get back what I expect in the Lambda test console. If I send:
{
"key3": "value3",
"key2": "value2",
"key1": "value1"
}
I get the same error as you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45361091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Kendo UI - custom grid filter: checkbox doesn't work on each click [UPDATE]
After I did as in:
http://dojo.telerik.com/aqIXa
when I click for example ProductName filter, and then select and deselect all items, go to other fields example Unit Price,click select and deselect all I turnback to Product Name field, and in filter is now:
You can see that Select All combobox is created once more and it will continue to create after I repeat the steps. Does anyone has the Idea why is it happend?
I'm currently working in Kendo and try to make custom grid filter for each column.
I used this example:
http://dojo.telerik.com/iwAWU
inside initCheckboxFilter function I added, which created checkbox for select all.
var selectAllCheckbox= $("<div><input type='checkbox' id='checkAll' checked/> Select All</div>").insertBefore(".k-filter-help-text");
and outside that function I implemeted:
function clickMe(){
$("#checkAll").click(function () {
if ($("#checkAll").is(':checked')) {
$(".book").prop("checked", true);
} else {
$(".book").prop("checked", false);
}
});
}
(.book is class for template inside:
var element = $("<div class='checkbox-container'></div>").insertAfter(helpTextElement).kendoListView({
dataSource: checkboxesDataSource,
template: "<div><input type='checkbox' class='colDefFilter' value='#:" + field + "#' checked />#:" + field + "#</div>",
});
)
I also added UnitPrice and UnitInStock fields:
function onFilterMenuInit(e) {
debugger;
if (e.field == "ProductName" || "UnitPrice" || "UnitInStock") {
initCheckboxFilter.call(this, e);
}
}
This looks like:
The first time I click Select All checkbox on some column filter, it check and uncheck all items and it works fine. When I try to do it on other column, the event is not trigger. Does anyone has idea what is wrong?
Thanks!
A: Your problem is that you are using id for check all checkbox that's why jquery always select check-box from first drop-down (Product)
you need to use checkAll as class not id then change your clickMe() function like this and it will work :
function clickMe(){
$(".checkAll").click(function () {
if ($(this).is(':checked')) {
$(this).closest('.k-filter-menu').find(".book").prop("checked", true);
} else {
$(this).closest('.k-filter-menu').find(".book").prop("checked", false);
}
});
}
Here is working example http://dojo.telerik.com/aqIXa
Edit :
the way you are using to add Select all checkbox should be like this
var selectAllCheckbox= $("<div><input type='checkbox' class='checkAll' checked/> Select All</div>").insertBefore(e.container.find(".k-filter-help-text"));
insted of this
var selectAllCheckbox= $("<div><input type='checkbox' id='checkAll' checked/> Select All</div>").insertBefore(".k-filter-help-text");
otherwise it will add multiple Select All check box for previously initialized filter-dropdowns.
Here is updated demo :http://dojo.telerik.com/aqIXa/4
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39510466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does superclass constructor exist (but not inherited) in subclass? We are able to invoke super() from subclass constructor. Since subclass IS-A superclass , and there is only 1 object created ( new Subclass()) does this imply superclass constructor exists, although it cannot be inherited, in subclass?
A: Constructors are not inherited. Superclass constructor 'exists' in a way that you could call it from a subclass unless it's marked as private.
And as I.K. has mentioned class could have a default constructor:
If a class contains no constructor declarations, then a default
constructor with no formal parameters and no throws clause is
implicitly declared.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29318092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to call a PHP function in an URL of ajax? I have written a PHP code having single function with an echo statement and I wish to call that function as a url in ajax code.
I tired doing this.
<html>
<head>
<title>Writing PHP Function</title>
<script>
$.ajax(
{
url : localhost/practice.php/f=myFirst();
type: "GET",
data: dataString,
success: function(result)
{
alert(result);
}
});
</script>
</head>
<body>
<?php
function myFirst()
{
echo 'The First ran successfully.';
}
?>
</body>
</html>
A: There are a lot of things wrong with what you have. Here is just a simple example that should work for you.
practice.php
<?php
if(isset($_GET['f']))
echo strip_tags($_GET['f']);
?>
index.php
<?php function myFirst() {
echo 'The First ran successfully.';
} ?><html>
<head>
<title>Writing PHP Function</title>
<!-- You need to add the jQuery library -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
// You should activate it on an event like click (unless you want it to autoload)
$("#content").click(function() {
$.ajax({
// Your url is funky, and cannot be terminated with a semicolon
// but rather a comma
url : 'localhost/practice.php?f=<?php myFirst(); ?>',
type: "GET",
// You can do an alert, but I just made it populate a div instead
success: function(result) {
$("#place-to-load").html(result);
}
});
});
</script>
</head>
<body>
<!-- Your php function will not work as you intend because one -->
<!-- is a server-side function and the other is a client-side script -->
<!-- The functions are not interchangeable. That being said, you can -->
<!-- populate a javascript with a php variable but it would need to be -->
<!-- echoed like <?php myFirst(); ?> -->
<div id="place-to-load"></div>
<div id="content">Load</div>
</body>
</html>
A: I would try to call the functions based on the params from the URL.
Ajax part,
$.ajax({url:'localhost/practice.php?f=myFirst',type:'GET'}).done(function(response){
alert(response); // or you can write to your document
});
and PHP file
<?php
if(isset($_GET) && $_GET['f'] == 'myFirst'){
myFirst();
}else{
die('No GET params received');
}
function myFirst(){
echo 'The First ran successfully.';
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27519266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-7"
} |
Q: How to redirect a page from '/' route to main '/dashboard' route automatically after first sign in angular js? I have auth.js page which decides which route to direct to after login.I am using ui-router for routing.Now the thing is after login user details are captured and the route accordingly changes.Here if I change the route from '/dashboard' to '/' and hit enter, then it first shows sign in page then redirects to dashboard which I don't want.If I go from '/dashboard' to '/' then it should automatically go to dashboard page without going to sign in page.How do I achieve this?
Thanks in advance
A: In your auth.js when user signIn (callback after user signIn success)
//In SignIn success callback.
$state.go('dashboard');//for state
$location.path("/dashboard");//for url dashboard
Hope it helps
A: You can use resolve to address this issue. When you are redirecting to "/" page. Just check in resolve section, whether the user is logged in or not. If the user is logged in, redirect to dashboard page.
A:
then it first shows sign in page then redirects to dashboard which I don't want.If I go from '/dashboard' to '/' then it should automatically go to dashboard page without going to sign in page.How do I achieve this
Really depends on your code. I recommend having the login route / logic maintained by the backend (check credentials there, and send a redirect to /login if not logged in.)
A: <!--HTML code-->
<div ng-init="CheckIfLoggedIn()">
<form id="login-form">
..............
</form>
</div>
//in angular JS
$scope.CheckIfLoggedIn = function(){
if (loggedinuser){
$location.path("/dashboard");
}
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36146875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get the data from log file using udp appender How to send log details by using udp appender in wowza Media Server . i have uncomment the udp appender in log4j.properties and added serverAccessUDP to root. but i Cant view the result.Where i Can Get the Result?
Anybody Help Me
Thanks in Advance?
A:
By using .Net framework,Udp Appender is easy to Access the Log File,Here the link
Udp Appender
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7777358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to save server state of CGI application? I have a cgi web program (in C) that prints out different error messages to a log file. If the program is run again and runs into he same error, I do not want the same error message to log again. I'm looking at different options and any advice is appreciated. Thanks.
-Cookie: unable to set cookie after the html <head> section has been printed out.
(After the head section is where any errors would occur.)
-Database: Do not have one. Too much overhead for this issue to install one.
-Parse log file: Many other processes are writing to this log file.
-Hidden form inputs on html file: Seems messy. Have 3 different forms on the same html page. How do am I sure the hidden fields are always submitted regardless of which form is submitted? But one of the errors is when the html can not be produced, so can not depend on this.
Thanks.
A: Storing the built page in a variable and outputting it at the end will allow you to emit a header any time before then.
A: The other option is to create some form of temporary file wherever you are able (not sure about permissions) and read that pre doing any work. Simply list the error types and optionally times in there, perhaps? This is assuming you want to persist this behaviour across runs of your program. This is the database solution without the database, really, so I'm not sure how helpful that is.
Whenever I mention database solutions without databases I always have to mention SQLite which is a file based serverless SQL "server".
A: I think you should refactor your program to create all its output previously to sending any HTML to the client, that way you'll be able to know beforehand all existing errors and set a cookie.
Now, if this is not viable for any reason you should have a temporary file identifying IP address and user agent and errors already shown. A simple text file should be quick enough to parse.
A: Using memcached might be a way to keep states throughout different sessions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2225579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ViewPager fragmentstatepageadapter getItem isn't passing correct position I have created a viewpager layout, a class that extends FragmentActivity and a fragment. What I want is that each fragment get's passed in what position it is within the viewpager. So first viewpager is created getting the argument 0, second getting 1 etc. Then if I scroll one way or another these numbers remain a true count.
The problem is the first time a fragment is created, it seems to be created twice so the position passed is 0 then 1. However I can't scroll back but I know for sure the class is being called twice. Now as I scroll forward the position increases incrementally by one. However if I scroll back it drops immediately to three on just one page back, then continues to drop past the 1 to 0 so now I can finally see my layout for 0.
I have this:
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
PracticeFragment fragment = new PracticeFragment();
getAll.putInt("position", position);
fragment.setArguments(getAll);
return fragment;
}
@Override
public int getCount() {
return numberofQ;
}
}
It first of all runs getItem twice before even going to my fragment class so that the position is 0 then 1. Then when it gets to my fragment class it makes a layout fine, I scroll through a few (3 or 4) new pages and it adds one to the position each time then when I scroll back it says it is zero or two then the numbers continue to be just as sporadic. Finally suddenly when I scroll back to the beginning the position is again 0 so my fragment for position 0 is suddenly displayed.
I don't understand what's happening, so I'm wondering what the mistake is?
public class PracticeFragment extends Fragment {
TextView question, explain;
private ScrollView sv;
private boolean starActionBar;
private final static int version = Consts.SDKversion;
ArrayList<RadioButton> rbArray;
ArrayList<LinearLayout> lArray;
ArrayList<ImageView> ivArray;
int iRow;
SQLite info;
private String correctAnswer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
info = new SQLite(getActivity());
starActionBar = PreferenceManager.getDefaultSharedPreferences(
getActivity()).getBoolean("star", true);
setHasOptionsMenu(true);
}
@Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
for (RadioButton r : rbArray) {
if (r.isChecked()) {
r.performClick();
}
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.activity_pm_fragment, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.activity_main, container, false);
lArray = new ArrayList<LinearLayout>();
rbArray = new ArrayList<RadioButton>();
ivArray = new ArrayList<ImageView>();
lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay0));
lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay1));
lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay2));
lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay3));
lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay4));
for (LinearLayout l : lArray) {
l.setOnTouchListener(PracticeFragment.this);
l.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (((ViewGroup) v).getChildAt(0).isEnabled()) {
((ViewGroup) v).getChildAt(0).performClick();
}
}
});
}
rbArray.add((RadioButton) rootView.findViewById(R.id.radio0));
rbArray.add((RadioButton) rootView.findViewById(R.id.radio1));
rbArray.add((RadioButton) rootView.findViewById(R.id.radio2));
rbArray.add((RadioButton) rootView.findViewById(R.id.radio3));
rbArray.add((RadioButton) rootView.findViewById(R.id.radio4));
ivArray.add((ImageView) rootView.findViewById(R.id.ivradio0));
ivArray.add((ImageView) rootView.findViewById(R.id.ivradio1));
ivArray.add((ImageView) rootView.findViewById(R.id.ivradio2));
ivArray.add((ImageView) rootView.findViewById(R.id.ivradio3));
ivArray.add((ImageView) rootView.findViewById(R.id.ivradio4));
rootView.findViewById(R.id.bNext).setVisibility(View.GONE);
rootView.findViewById(R.id.bPrevious).setVisibility(View.GONE);
sv = (ScrollView) rootView.findViewById(R.id.svMain);
info.open();
iRow = Integer.valueOf(info.getEverything(getArguments(), getArguments().getInt("position"), "next"));
Cursor c = info.getCursor(iRow);
((TextView) rootView.findViewById(R.id.tvQuestion))
.setText((getArguments().getInt("position") + 1) + ") " + c.getString(2));
explain = (TextView) rootView.findViewById(R.id.tvExplain);
explain.setText(c.getString(9));
explain.setVisibility(View.GONE);
correctAnswer = c.getString(8);
String[] aArray = { c.getString(3), c.getString(4), c.getString(5),
c.getString(6), c.getString(7) };
c.close();
info.close();
int o = 0;
int pos = 0;
for (String s : aArray) {
LinearLayout l = lArray.get(pos);
if (s.contentEquals("BLANK")) {
l.setVisibility(View.GONE);
} else {
l.setVisibility(View.VISIBLE);
rbArray.get(pos).setText(s);
rbArray.get(pos).setOnClickListener(null);
if (o % 2 == 0) {
l.setBackgroundColor(Consts.colorAlt);
}
o++;
}
pos++;
}
return rootView;
}
}
However if I comment out everything but the viewgroup and return rootview - still the same problem.
A: initialize the getAll every time as a new object in getItem()
make your fragment class static
and create one method in PracticeFragment
static PracticeFragment newInstance(int num) {
PracticeFragment f = new PracticeFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
and change in adapter
@Override
public Fragment getItem(int position) {
return PracticeFragment.newInstance(position);
}
A: Subclassing it fixed the problem!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14116977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Most viewed product I am trying to find most viewed product as per user ID. If two products have been viewed for the same number of times then the most recent viewed product is to be selected.
I have the following coding:
#tabulating most viewed product by an user in the last 15 days
df_most_viewed_product= new_df.groupby('UserID')['ProductID'].apply(lambda x: x.value_counts().index[0]).reset_index()
Its finding the most viewed product for all the USER IDs except for those, where the USER has viewed two products for the same number of time.In such a scenario I need to get the output as the most recently viewed product.
ProductID UserID Activity OS date time
392281 Pr102405 U100040 PAGELOAD Windows 2018-05-21 04:18:05.465000
764999 Pr102405 U100040 CLICK Windows 2018-05-23 15:52:02.061000
1501633 Pr105055 U100040 PAGELOAD Windows 2018-05-23 15:52:39.035000
1603959 Pr100283 U100040 PAGELOAD Windows 2018-05-25 15:27:37.062000
2212636 Pr100513 U100040 PAGELOAD Windows 2018-05-27 02:18:47.676000
3093767 Pr100513 U100040 PAGELOAD Windows 2018-05-26 20:47:49.788000
The answer should be Pr100513 as it has been been viewed recently.
A: Systematically build it up as you describe
*
*get hits and last hit per UserID and ProductID
*select rows from this aggregated data frame that match max hits and max last_hit
import io
import pandas as pd
df = pd.read_csv(io.StringIO(''' ProductID UserID Activity OS date time
392281 Pr102405 U100040 PAGELOAD Windows 2018-05-21 04:18:05.465000
764999 Pr102405 U100040 CLICK Windows 2018-05-23 15:52:02.061000
1501633 Pr105055 U100040 PAGELOAD Windows 2018-05-23 15:52:39.035000
1603959 Pr100283 U100040 PAGELOAD Windows 2018-05-25 15:27:37.062000
2212636 Pr100513 U100040 PAGELOAD Windows 2018-05-27 02:18:47.676000
3093767 Pr100513 U100040 PAGELOAD Windows 2018-05-26 20:47:49.788000 '''), sep="\s", engine="python")
df["date"] = pd.to_datetime(df["date"] + " " + df["time"])
# count hits per user and product after sorting so last_hit works
dfh = df.sort_values(["UserID","date"]).groupby(["UserID","ProductID"]).agg(hits=("OS","size"),last_hit=("date","last"))
# select the row with max hits and last hit
dfh.loc[dfh["hits"].eq(dfh["hits"].max()) & dfh["last_hit"].eq(dfh["last_hit"].max())]
output
hits last_hit
UserID ProductID
U100040 Pr100513 2 2018-05-27 02:18:47.676
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68237537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Take and save screenshot with html javascript I'm trying to take a screenshot and save it in a specific folder in my local computer with an onclick in a button, using HTML and JavaScript (or JQuery).
A: There's no way to save DOM elements as an image (unless you just use Firefox or something), but you can convert the DOM elements into canvas and save the image from there.
See http://html2canvas.hertzen.com/
Then use canvas.toDataURL() to save the image.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63308982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: gcloud app deploy fails with only [ERROR] I've been running python 2.7 apps on GCP for about 5 years and deploying using the App Engine Launcher.
Now that AEL is deprecated I'm trying to deploy via gcloud and get "ERROR: (gcloud.app.deploy)"
*
*I can use gcloud to run the project locally so I have confidence that the project is setup correctly and in the right directory locally.
*I ran gcloud auth login to give myself permission to upload to the project.
But when I try to redeploy my app I get an error:
DEBUG: Running gcloud.app.deploy with Namespace(__calliope_internal_deepest_parser=ArgumentParser(prog='gcloud.app.deploy', usage=None, description='Deploy the local code and/or configuration of your app to App Engine.', version=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=False), account=None, authority_selector=None, authorization_token_file=None, bucket=None, calliope_command=<googlecloudsdk.calliope.backend.Command object at 0x037D1F90>, command_path=['gcloud', 'app', 'deploy'], configuration=None, credential_file_override=None, deployables=[], docker_build=None, document=None, flatten=None, format=None, h=None, help=None, http_timeout=None, ignore_bad_certs=False, image_url=None, log_http=None, project='MY_PROJECT', promote=None, quiet=None, server=None, skip_image_url_validation=False, skip_staging=False, stop_previous_version=None, trace_email=None, trace_log=None, trace_token=None, user_output_enabled=None, verbosity='debug', version=None).
DEBUG: API endpoint: [https://appengine.googleapis.com/], API version: [v1beta5]
You are creating an app for project [MY_PROJECT].
WARNING: Creating an app for a project is irreversible.
DEBUG: (gcloud.app.deploy)
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\cli.py", line 740, in Execute
resources = args.calliope_command.Run(cli=self, args=args)
File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\backend.py", line 1684, in Run
resources = command_instance.Run(args)
File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\surface\app\deploy.py", line 53, in Run
return deploy_util.RunDeploy(args)
File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 374, in RunDeploy
app = _PossiblyCreateApp(api_client, project)
File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 507, in _PossiblyCreateApp
create_util.CreateAppInteractively(api_client, project)
File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\create_util.py", line 109, in CreateAppInteractively
all_regions = sorted(set(api_client.ListRegions()))
File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\appengine_api_client.py", line 415, in ListRegions
self.client.apps_locations.List, request)
File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\api\requests.py", line 67, in MakeRequest
raise err() if err else exc
NotFoundError
ERROR: (gcloud.app.deploy)
It doesn't give me much to go on. Wondering if it is a problem with app.yaml or some other basic issue.
gcloud info
Google Cloud SDK [138.0.0]
Platform: [Windows, x86_64]
Python Version: [2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]]
Python Location: [C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\bundledpython\python.exe]
Site Packages: [Disabled]
Installation Root: [C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk]
Installed Components:
bundled-python: [2.7.10]
app-engine-python: [1.9.49]
bq-win: [2.0.24]
core: [2016.12.09]
core-win: [2016.11.07]
gcloud: []
windows-ssh-tools: [2016.05.13]
app-engine-python-extras: [1.9.49]
gsutil: [4.22]
bq: [2.0.24]
powershell: [1.0.0.1]
gsutil-win: [4.20]
System PATH: [C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin\..\bin\sdk;C:\Users\Jay-swtchbk\Miniconda2\condabin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin;C:\WINDOWS\System32\OpenSSH\;C:\Users\Jay-swtchbk\AppData\Roaming\Dashlane\4.6.5.21982\bin\Firefox_Extension\{442718d9-475e-452a-b3e1-fb1ee16b8e9f}\components;C:\Users\Jay-swtchbk\AppData\Local\Microsoft\WindowsApps;C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin;C:\Program Files (x86)\Google\google_appengine\]
Cloud SDK on PATH: [True]
Kubectl on PATH: [False]
WARNING: There are old versions of the Google Cloud Platform tools on your system PATH.
C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gcloud.cmd
C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\dev_appserver.py
C:\Program Files (x86)\Google\google_appengine\dev_appserver.py
C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gsutil.cmd
C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\git-credential-gcloud.cmd
C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\bq.cmd
C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gcloud-ps.ps1
C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gsutil-ps.ps1
C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\bq-ps.ps1
C:\Program Files (x86)\Google\google_appengine\endpointscfg.py
C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\endpointscfg.py
Installation Properties: [C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\properties]
User Config Directory: [C:\Users\Jay-swtchbk\AppData\Roaming\gcloud]
Active Configuration Name: [tvpub1]
Active Configuration Path: [C:\Users\Jay-swtchbk\AppData\Roaming\gcloud\configurations\config_tvpub1]
Account: [*******@gmail.com]
Project: [MY_PROJECT]
Current Properties:
[core]
project: [MY_PROJECT]
account: [******@gmail.com]
disable_usage_reporting: [False]
app.yaml contents:
runtime: python27
api_version: 1
threadsafe: false
libraries:
- name: jinja2
version: latest
- name: webapp2
version: latest
- name: lxml
version: latest
- name: numpy
version: "1.6.1"
builtins:
- remote_api: on
inbound_services:
- mail
handlers:
- url: /assets
static_dir: assets
- url: /static
static_dir: static
- url: /admin/.*
script: MY_PROJECT.app
login: admin
- url: /favicon\.ico
static_files: assets/img/favicon.ico
upload: assets/img/favicon\.ico
- url: /.*
script: MY_PROJECT.app```
A: Solved, for those who having similar issues:
I Was using:
*
*gcloud app deploy --project=MY_PROJECT
But it works if you specify the version flag (which is optional according to Google's documentation)
*
*gcloud app deploy --project=MY_PROJECT --version=1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63837650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: My Flutter App is Not Working on Android 11 But Working fine in emulator as well as android 8 || (OS Error: Operation not permitted, errno = 1) Here is My Code
import 'package:flutter/material.dart';
import 'package:screenshot/screenshot.dart';
import 'package:sweld/globals.dart';
import 'package:geolocator/geolocator.dart';
class WeldSetup extends StatelessWidget {
WeldSetup({Key? key}) : super(key: key);
final pageNum = 211;
@override
Widget build(BuildContext context) {
final _ssc = ScreenshotController();
return Scaffold(
appBar: AppBar(
title: Text("Weld Setup"),
centerTitle: true,
actions: [
IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(Icons.railway_alert_rounded),
),
],
),
body: Screenshot(controller: _ssc, child: WsLocation()),
persistentFooterButtons: [
ElevatedButton(
onPressed: () async {
Globals.ss211 = await _ssc.captureAndSave(Globals.appDir,
fileName: "ss211.png",
pixelRatio: MediaQuery.of(context).devicePixelRatio,
delay: Duration(milliseconds: 100));
Navigator.pushNamed(context, "/212");
},
child: Text("Next"))
],
extendBody: true,
);
}
}
class WsLocation extends StatefulWidget {
const WsLocation({Key? key}) : super(key: key);
@override
_WsLocationState createState() => _WsLocationState();
}
class _WsLocationState extends State<WsLocation> {
late Position curPos;
var longitute = Globals.longitude;
var latitude = Globals.latitude;
TimeOfDay sTime = TimeOfDay(hour: 00, minute: 00);
TimeOfDay eTime = TimeOfDay(hour: 00, minute: 00);
Widget selectTime(time) {
if (time == TimeOfDay(hour: 00, minute: 00)) {
return Text("Select Time");
} else {
if (time == sTime) {
return Text("${Globals.stime}");
} else {
return Text("${Globals.etime}");
}
}
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Container(
margin: EdgeInsets.all(15),
color: Colors.white,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"LOCATION",
textScaleFactor: 2,
style: TextStyle(
fontWeight: FontWeight.bold,
),
)
],
),
Divider(
thickness: 2,
height: 50,
),
Container(
child: Form(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Flexible(
child: TextFormField(
initialValue: Globals.longitude,
decoration: InputDecoration(
labelText: "Longitude",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(
color: Colors.black,
style: BorderStyle.solid,
width: 1.5,
),
),
),
onChanged: (val) {
setState(() {
Globals.longitude = val;
});
},
),
),
Divider(
indent: 5,
),
Flexible(
child: TextFormField(
initialValue: Globals.latitude,
decoration: InputDecoration(
labelText: "Latitude",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(
color: Colors.black,
style: BorderStyle.solid,
width: 1.5,
),
),
),
onChanged: (val) {
setState(() {
Globals.latitude = val;
});
},
),
),
],
),
Divider(
thickness: 0,
height: 10,
),
TextFormField(
initialValue: Globals.section,
decoration: InputDecoration(
labelText: "Section",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(
color: Colors.black,
style: BorderStyle.solid,
width: 1.5,
),
),
),
onChanged: (val) {
setState(() {
Globals.section = val;
});
},
),
Divider(
thickness: 0,
height: 10,
),
TextFormField(
initialValue: Globals.division,
decoration: InputDecoration(
labelText: "Division",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(
color: Colors.black,
style: BorderStyle.solid,
width: 1.5,
),
),
),
onChanged: (val) {
Globals.division = val;
},
),
Divider(
thickness: 0,
height: 10,
),
TextFormField(
initialValue: Globals.distance,
decoration: InputDecoration(
labelText: "Distance",
hintText: "In kilometers(km)",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(
color: Colors.black,
style: BorderStyle.solid,
width: 1.5,
),
),
),
onChanged: (val) {
Globals.distance = val;
},
),
Divider(
thickness: 0,
height: 10,
),
DropdownButtonFormField<String>(
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(
color: Colors.black,
style: BorderStyle.solid,
width: 1.5,
),
),
),
hint: Text("Line"),
isExpanded: true,
items: <String>['Single', 'Up-Line', 'Down-Line']
.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (val) {
Globals.line = val;
},
),
Divider(
thickness: 0,
height: 10,
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: Row(
children: [
Divider(
indent: 15,
endIndent: 5,
),
Text("Start Time "),
TextButton(
onPressed: () {
showTimePicker(
context: context,
initialTime: sTime)
.then((value) {
if (value != null) {
setState(() {
sTime = value;
Globals.stime = value.format(context);
});
}
});
},
child: Globals.stime == null
? selectTime(sTime)
: Text(" ${Globals.stime} "),
),
],
),
),
// Divider(
// thickness: 0,
// indent: 5,
// ),
Flexible(
child: Row(
children: [
Divider(
indent: 10,
),
Text("End Time "),
TextButton(
onPressed: () {
showTimePicker(
context: context,
initialTime: eTime)
.then((value) {
if (value != null) {
setState(() {
eTime = value;
Globals.etime = value.format(context);
});
}
});
},
child: Globals.etime == null
? selectTime(eTime)
: Text(" ${Globals.etime} "),
),
],
),
),
],
),
),
],
),
),
),
Divider(
height: 50,
),
],
),
),
);
}
}
Here user is able to Input in Text fields, But when He presses Next He is not able to goto next Page. Moreover When I run it in emulator then it is working Totally Fine !.
And Yes its important to take screenshot of everypage therefore, I cannot Exclude it.
And sometime it returns Null, It Might be a problem But I dont know How to deal with it or What should I do Next.
Any Suggestions Please
Here is My Build Gradle File
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 30
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.sweld"
minSdkVersion 16
targetSdkVersion 30
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
UpDate
I just Recieved the error, It is
[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FileSystemException: Creation failed, path = 'storage/emulated/0/sweld' (OS Error: Operation not permitted, errno = 1)
E/flutter ( 7337): #0 _Directory.create.<anonymous closure> (dart:io/directory_impl.dart:117:11)
E/flutter ( 7337): #1 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter ( 7337): #2 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter ( 7337): <asynchronous suspension>
So Please Tell me what SHow I DO ??
A: try to change minSdkVersion 16 to minSdkVersion 21
A: I solved this issue My getting Some additional Permissions.
MANAGE_EXTERNAL_STORAGE and INTERNET Permission
in Android Manifest File
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69314305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: regex get text from next line I'm looking for a way to find text on the next line of a certain string using regex.
Say I have the following text:
Note:
Just some text on this line
Some more text here.
I just want to get the text 'Just some text on this line'.
I don't know exactly what the other text will be, so I can't search between 'Note:' and 'Some more text here'.
All I know is that the text I want is on the next line from 'Note:'.
How could I do this?
Cheers,
CJ
A: I'd go line by line down your string, and when a regex matches, then take the next line
string str;
// if you're not reading from a file, String.Split('\n'), can help you
using (StreamReader sr = new StreamReader("doc.txt"))
{
while ((str = sr.ReadLine()) != null)
{
if (str.Trim() == "Note:") // you may also use a regex here if applicable
{
str = sr.ReadLine();
break;
}
}
}
Console.WriteLine(str);
A: This can be done with a multiline regex, but are you sure you want to? It sounds more like a case for line-by-line processing.
The Regex would be something like:
new Regex(@"Note:$^(?<capture>.*)$", RegexOptions.MultiLine);
although you might need to make that first $ a \r?$ or a \s*$ because $ only matches \n not the \r in \r\n.
Your "Just some text on this line" would be in the group named capture. You might also need to strip a trailing \r from this because of the treatment of $.
A: You can do this
(?<=Note:(\r?\n)).*?(?=(\r?\n)|$)
---------------- --- ------------
| | |->lookahead for \r\n or end of string
| |->Gotcha
|->lookbehind for note followed by \r\n. \r is optional in some cases
So,it would be like this
string nextLine=Regex.Match(input,regex,RegexOptions.Singline | RegexOptions.IgnoreCase ).Value;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15528352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Max application memory Limit in iPad? I have created iPad application which downloads images using web service. But my application crashes somewhere during manipulating with high quality images. So my question is - what is max memory limit for application running on iPad? When does the application hit LowMemoryWarning on iPad?
A: There is no per-application limit so to say. The amount of memory available to an application depends on the amount of free memory, which again depends on the amount of memory used by applications running in the background. These apps include permanently running system apps like SpringBoard, sometimes running system apps like Safari, iPod, etc and (when iOS 4 will come for iPad) user-apps that still run in background.
Nevertheless, I'd say an app should never use more than 50% of all available ram. On iPad this currently means 128 MB and should be quite a lot. Did you do a leak check on your app?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3585094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Packages to verify the re-rendering in es5 components other than "WhyDidYouRender" Right now I'm using the WhyDidYourender package to verify the component re-rendering but there are few components in my repo that uses es2015. WhyDidYouRender is not working in es2015 components. Seeing below error:
TypeError: Class constructor MyComponent cannot be invoked without 'new'
So need a way to verify the re-rendering for es5 components. Also, tried Chrome highlights to verify the re-rendering, please don't recommend that.
Any help is appreciated, Thanks!
WhyDidYouRender repo link: https://github.com/welldone-software/why-did-you-render
A: Support the ES6 or not is rely on your Browser. It's more like you trying to use the class but there is no instance to access.
Transpiled to es5 class is available in PR#8656, the whole react class elements are supported to extend with this library. If you transpile your classes by ES5 or ES6, use below code:
// traspiled to es5
const whyDidYouRender = require('@welldone-software/why-did-you-render);
// traspiled to es6
const whyDidYouRender = require('@welldone-software/why-did-you-render/dist/no-classes-transpile/umd/whyDidYouRender.min.js');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60268732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Security - Method returns internal array - Sonar security warning - even when I am returning a clone The below return statement gives me a Sonar security warning even when I am not returning the original array but a clone of it.
What is the "correct" way to do this?
public String[] getList() {
return list!=null? list.clone():null;
}
A: Edited my previous answer for some obvious errors :)
List.clone() doesn't work because it returns a shallow copy of the list. So basically it just returns the reference to the original list. We don't want that here. What we want is a brand new array that doesn't have the same reference to be returned.
For that the best idea will always be to create a new array and run a for loop like this:
String[] newArr = new String[list.length];
int i = 0;
for (String s : list) {
newArr[i++] = s
}
If you wanna know why this is the issue, refer to this answer :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29895191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Elasticsearch aggregation using Java api Hi I am trying to do query on elastic search by following the sql query and I want to implement same logic using Java API
select dttime, avg(cpu) from table cpustats where server="X" and dttime="Y" group by dttime,cpu
Now I have the following Java code but it does not return expected output
SearchResponse response = client.prepareSearch("cpuindex")
.setTypes("cputype")
.setQuery(QueryBuilders.matchAllQuery())
.addAggregation(AggregationBuilders.terms("cpu_agg")
.field("cpu").size(100))
.execute().actionGet();
Please guide I am new to Elastic search. Thanks in advance.
A: since elastic search 2.3, FilterBuilders class has been removed from JavaAPI. you can use
QueryBuilder qb = QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery("_all", "JPMORGAN"))
.must(QueryBuilders.matchQuery(field, value)) ;
instead, and set it to
.setQuery(qb).
A: I think this will help.
SearchResponse response=
client.prepareSearch("your_index_name_here").setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
FilterBuilders.andFilter(
FilterBuilders.termFilter("server","x"),
FilterBuilders.termFilter("dt_time","x")
))).addAggregation(
AggregationBuilders.terms("dt_timeaggs").field("dt_time").size(100).subAggregation(
AggregationBuilders.terms("cpu_aggs").field("cpu").size(100)
)
).setSize(0).get();
please verify.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24964361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: QML rotating a Gauge needle - pivot correctly I am trying to rotate a Gauge needle, but instead of pivoting at the base of the needle which have a circle with cross.. needle is pivots around the tip of the needle.. please see the attached image.. tip of the image is fixed/pivots but base is rotating.. please suggest how to correct this ?
main.qml :--
import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 2.5
Window
{
visible: true
x :0
y :0
width: 800
height: 480
color: "grey"
Rectangle
{
id: cluster
Speed_Needle{
id: cluster_pointer_base
x : 214+16
y : 222
}
}
Slider
{
id : slide_1
width: parent.width
from: 0
to: 360
value: 0
enabled: true
onValueChanged:
{
cluster_pointer_base.value=slide_1.value
}
}
}
Speed_Needle.qml :--
import QtQuick 2.0
Item {
property int value: 0
width: 186
height: 36
Image
{
id: root
source: "files/pointer_needle2.png"
x : 0
y : 0
transform: Rotation {
id: needleRotation
angle : value
Behavior on angle {
SmoothedAnimation { velocity: 50 }
}
}
}
}
A: You have to set the origin of the Rotation:
Speed_Needle.qml :--
import QtQuick 2.0
Item {
property int value: 0
width: 186
height: 36
Image
{
id: root
source: "files/REE Demo images/pointer_needle2.png"
x : 0
y : 0
transform: Rotation {
id: needleRotation
angle : value
origin.x: root.width / 2 // here!
origin.y: root.height / 2
Behavior on angle {
SmoothedAnimation { velocity: 50 }
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58393454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Response from Postman shows 200, But Android returns 403 I was trying to develop an android app using Volley, The api I used to communicate is working fine when I checked with POSTMAN and retrieves 200 .
But when I use the same API in my App its returns me 403 "Forbidden"
<p〉You don't have permission to access /API/checkPassOtp on this server.〈/p〉
Please find the screenshot.
I have tried multiple solution for this issue, But nothing worked for me.
Can anyone please help me.
Attaching volley code and error response
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("otp", otp);
Log.e("jsonBody", jsonBody.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, URL, jsonBody, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// handle response data
VolleyHelper.progressDialog.dismiss();
Log.e("onResponse", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyHelper.progressDialog.dismiss();
Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_SHORT).show();
Log.e("onErrorResponse", error.toString());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Application.getInstance().addToRequestQueue(jsonObjReq, "app");
volleyHelper.showProgressDialogWithTitle(MainActivity.this);
A: Try to use
"Accept", "application/json"
in your params (use both).
I have to use x-api-key when connecting with my company's webserver, but I'm not sure if you'll need it.
A: --> Use https instead of http in android , Postman seems fine with the http, but OkHttp needed https.
I was stuck for a day for this error 403 forbidden in android , but giving 200 success in Postman .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54649618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cocoa: loading a bundle in which some classes inherit from a custom framework SHORT VERSION:
How can I load classes during runtime from a bundle, when those classes inherit from superclasses not defined in the bundle, but from another framework which was loaded prior? When loading my framework, classes contained therein work fine. When loading the plugin afterwards, any classes which inherit from NSObject work fine but classes inheriting from the framework are not being loaded.
LONG VERSION:
Cocoa allows you to control the Dock icon explicitly via the "Dock Tile Plugin" mechanism. In a nutshell, when your app is added to the Dock, the OS looks inside the app's bundle plugins directory for a bundle called "MyDockTilePlugin.docktileplugin". It then loads this plugin's principal class which must conform to the NSDockTilePlugIn protocol.
I have built such a bundle according to Apple's guide. Now I want to reuse this code by making the component classes superclasses in my custom framework. Subclasses specific to a given project can load the framework.
Surprisingly, this is not very straightforward.
Here is the process in psuedocode:
*
*The docktileplugin is loaded by the Dock.
*In its +initialize class method, the class loads the custom framework, which is set to "optional" in build settings.
*The class then loads its own plugin which contains classes inheriting from framework classes.
*Something like NSLog(@"%@", NSStringFromClass(NSClassFromString(classInheritingFromFramework))); will always display (null)
How does inheritance work across plugin bundles? THANKS...
If this isn't enough information, please ask for more. I'm trying to be concise and thorough.
MORE CODE:
+ (void)initialize {
[[NSNotificationCenter defaultCenter] addObserverForName:NSBundleDidLoadNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
NSLog(@"bundle loaded %@", note);
}];
//Plugin bundle
NSBundle *selfBundle = [NSBundle bundleForClass:[self class]];
//Load Custom Framework
NSString *frameworkName = @"Custom.framwork";
NSString *frameworkPath = [[selfBundle bundlePath] stringByAppendingPathComponent:[@"Contents/Frameworks" stringByAppendingPathComponent:frameworkName]];
NSLog(@"Framework %@ at %@", ([[NSFileManager defaultManager] fileExistsAtPath:frameworkPath]? @"EXISTS" : @"DOES NOT EXISTS"), frameworkPath);
if( [[NSBundle bundleWithPath:frameworkPath] load] ) {
NSLog(@"Framework loaded...");
NSLog(@"Framework provided classes such as DockTilePlugin (%@) and UndoManager (%@)", NSStringFromClass(NSClassFromString(@"DockTilePlugin")), NSStringFromClass(NSClassFromString(@"UndoManager")));
} else {
NSLog(@"Error, framework failed to load.");
exit(1);
}
//Load Dock Tile Plugin
NSString *pluginName = [[selfBundle infoDictionary] objectForKey:@"DockTilePluginCoreBundle"];
NSString *pluginPath = [[selfBundle builtInPlugInsPath] stringByAppendingPathComponent:[pluginName stringByAppendingPathExtension:@"bundle"]];
NSLog(@"Plugin %@ at %@", ([[NSFileManager defaultManager] fileExistsAtPath:pluginPath]? @"EXISTS" : @"DOES NOT EXISTS"), pluginPath);
if( [[NSBundle bundleWithPath:pluginPath] load] ) {
NSLog(@"Plugin loaded...");
NSLog(@"Plugin provided classes such as DockTilePlugin (%@) and DockTileView (%@)", NSStringFromClass(NSClassFromString(@"DockTilePlugin")), NSStringFromClass(NSClassFromString(@"DockTileView")));
} else {
NSLog(@"Error, Plugin failed to load.");
exit(1);
}
}
What output I see in the Console.app is that the first two "classes such as" show up (class names appear), but in the second two I get "Plugin Provided classes such as DockTilePlugin (null) and DockTileView (null)".
Also, the notifications are received for both bundles. In the framework, I see in the "NSLoadedClasses" key that all framework classes are loaded and available. In the Plugin bundle, this list is empty (although there should be several classes from the bundle, but they all inherit from the framework).
If I add a third class to the plugin, which inherits from Cocoa, that class appears fine. Something about bundle-loading a class which inherits from another bundle-loaded class is tricky. That is the heart of it I think.
A: Mike from http://mikeash.com - an amazing resource - provided me with the tip that solved this problem. The cause of the problem eludes me, but it was fixed by doing two things:
*
*In the Framework's project, setting its build location to @rpath as described in this article: http://mikeash.com/pyblog/friday-qa-2009-11-06-linking-and-install-names.html
*In the plugins loading the framework, weak reference during build, don't copy the framework during build, and then set the -rpath build setting to the location of the framework in the containing app. This ensures all items are using the same copy of the framework.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6824213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: VSCode pylint not displaying relative import failures I am running a Django application in VSCode, using pylint, and the relative imports errors are not displaying. They were before I installed a newer version of VSCode.
I have tried changing user settings and also workspace settings, but still can't get the errors to show.
User Settings
{
"window.zoomLevel": 1,
"explorer.confirmDelete": false,
"workbench.startupEditor": "newUntitledFile",
"window.menuBarVisibility": "default",
"explorer.confirmDragAndDrop": false,
"workbench.colorTheme": "Visual Studio Dark",
"update.enableWindowsBackgroundUpdates": false,
"update.channel": "none",
"php.validate.run": "onSave",
}
Workspace settings
{
"python.linting.enabled": true,
"python.linting.pep8Enabled": false,
"python.linting.pylintArgs": ["--load-plugins", "pylint_django"],
"python.linting.pylintEnabled": true,
"python.pythonPath": "/home/justin/anaconda3/bin/python",
"python.linting.pylintPath": "/home/justin/anaconda3/bin/pylint"
}
At the top of one of my functions, a couple of different relative imports. Which one is right or wrong, VSCode should show me. Both imports are in the same project directory in Django, therefore import should be a single '.' I believe.
from .performance import get_perf_dates, get_perf_data
from ..models import DistributionList, Legend
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56531077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ListViewItem ItemSelectionChangedEvent Fires 4 times [e.Selected fires twice] leads to Win32 Exception Unhandled I am using a button and a listview to display a list of options to the user. Selection is made with a mouse click, the listview removes its self from the .Controls array + un-registers eventlistener and loads a new listview else where on the screen.
My problem is both listviews trigger e.selected twice:
' private void _lvKids_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (e.IsSelected)//fires twice per click
{
HideKidsList();//--REMOVE CURRENT LISTVIEW
ValidateUser();//CREATE NEW LISTVIEW
}`
If the button is clicked a second time to restart the process, it causes a win32 Exception. After much research, this exception is the often the cause of a memory leak. So I'm thinking memory leak?
When I first started, listboxes were used which worked perfectly. I'd love to able to use them, but my form has a graphic for a background and listbox doesn't. Listview does.
I don't have anyone to turn to so any thing you can offer would be appreciated.
Thanks;
Sam
A: An update if anyone else has the same issue. Selecting the listview item called for it to be removed from Controls array. Removing the listview also cause the selected item to be deselected, thus 4 calls to the handler.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6605682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Start EC2 for specific time XX hours and then terminate A customer requested an EC2 instance for XX hours.
I created an on-demand EC2 instance and I sent the credentials to the user. He used it for a short lived calculation.
How can I terminate that EC2 instance exactly after XX hours?
Thank you in advance.
A: The simplest way to terminate an instance after a given time period is:
*
*Provide a User Data script when launching the Amazon EC2 instance
*The script should wait the given period then issue a shutdown command, such as:
sleep 3600; shutdown now -h
Also, when launching the instance, set Shutdown Behavior = Terminate. This means that when the instance is stopped from within the instance, it will actually be terminated.
Alternatively, you could code a Stopinator that would trigger at times and determine which instances to stop/terminate. For some examples see: Simple Lambda Stopinator: Start/Stop EC2 instances on schedule or duration
A: Thanks, John(@john-rotenstein).
I tested all your suggestions.
I used the following User Data script for
Windows instances:
<script>
shutdown -s -t 3600
</script>
<persist>true</persist>
Linux instances:
...
#cloud-config
cloud_final_modules:
- [scripts-user, always]
--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
sleep 3600
shutdown now -h
In addition, Stopinator Type 2 is working perfectly well for me, but only with Stop-After tag
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61963932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to avoid spurious 'unused parameter' warnings in TypeScript I've encountered this a bunch and have finally decided to figure out what the right way to do it is. If I have an abstract parent class that declares a method, and then some of the concrete sub-classes implement real logic in their implementation (and, obviously, use the method parameters), but some of the sub-classes don't need to do anything in that method (so don't use the method parameters) - the ones that don't have to do anything generate spurious (in my view) warnings in my code.
For instance, if I have some classes that look like:
abstract class Child {
constructor(protected name: string) {
connsole.log(name + " was just born.");
}
abstract tellThemToDoSomething(command: string);
}
class GoodChild extends Child {
constructor(name: string) { super(name); }
tellThemToDoSomething(command: string) {
console.log("I will do " + command);
}
}
class BadChild extends Child {
constructor(name: string) { super(name); }
tellThemToDoSomething(command: string) {
// bad children just ignore what their parents tell them
}
}
Then I get a (TSLint? JSLint? WebStorm?) warning in WebStorm for the unused parameter in the BadChild tellThemToDoSomethign() method.
I know of a few options, but none seem great.
1) Ignore it (but that seems suboptimal, since I'll grow blind to real warnings)
2) Remove the parameter from the BadChild's method implementation (but that unfortunately removes useful information, since I may later want to implement it, and not having the signature there makes it more difficult, and I also get errors from callers expecting there to be parameters - though given that I should be able to call a method with extraneous parameters in JavaScript, I be there's a way around that problem)
3) Tell WebStorm(TSLint) to stop warning on unused parameters (but that seems suboptimal since I won't get warnings in other real problem situations)
4) Do something meaningless with the parameter so it is not unused (obviously not great)
What is do experienced Java/TypeScript coders do in situations like this? Is there an easy way to tell WebStorm/TSLint to ignore the parameter in individual cases like this? Or, even better, a way to tell it to ignore unused parameters in sub-class implementations of abstract methods, as long as some implementations actually use the parameters?
I'm a little unsure on where the warning is coming from, though, since my brief googling shows a TSLint warning for unused-variables but not unused-parameters, and adding a // tslint:ignore-next-line:no-unused-parameter (or no-unused-variable) didn't make the warning go away. So I guess it's possible the warning is coming from WebStorm itself? Further, the warning is "Unused parameter Foo: Checks JavaScript parameter, local variable, function, classes and private member declarations to be used in given file scope". So it doesn't look like a TSLint warning. And if I look in my WebStorm Preferences -> Languages & Frameworks -> Javascript -> Code Quality Tools, none of the linters are enabled (JSLint, JSHint, ESLint, etc.). So any idea where the error is coming from?
I've not coded in TypeScript long enough to have a feel for what the ideal dial on this warning should be.
A: This warning is caused by JetBrains PhpStorm/WebStorm inspections.
A conventional way that is properly handled by TypeScript is to underscore unused parameters. Unfortunately, this convention isn't supported by JetBrains IDEs.
It's possible to suppress inspections in-place in some cases by triggering suggestion list with Alt+Enter/⌥+Enter and choosing Suppress for statement (this never worked for me for IDE inspections).
It's possible to suppress inspections in inspections results.
This results in adding a comment above the method and affects all unused parameters in this method signature:
// noinspection JSUnusedLocalSymbols
tellThemToDoSomething(_command: string) {}
This can be added to live templates, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50266006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How Can I Terminate a Thread Using a Throw Exception Method - Python I found some code online that will stop a thread via an exception after a wait period of some time.
def raise_exception(self):
thread_id = self.get_id()
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id,
ctypes.py_object(SystemExit))
if res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
print('Exception raise failure')
An exception is called after some time by:
t1 = thread_with_exception('Thread 1')
t1.start()
time.sleep(1/1000)
t1.raise_exception()
t1.join()
I would like to call an exception that would specify how many time a process occurs. Such as:
t1 = thread_with_exception('Thread 1')
t1.start()
if t1.count >= 3:
t1.raise_exception()
t1.join()
This however fails to call an exception when t1.count >= 3.
Can an exception not be called in this manner?
A: Rather than calling the raise_exception outside the class, calling it from within the run method for the thread will work. Ex.
def run(self):
if count>3:
self.raise_exception()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55639104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to POST data using TLS 1.2 I am trying to POST data to a server who is just using TLS1.2
When i am running the code i am getting the following response from server.
HttpResponseProxy{HTTP/1.1 415 Unsupported Media Type [Date: Wed, 07 Sep 2016 17:42:57 CST, Server: , Strict-Transport-Security: max-age=63072000; includeSubdomains; preload, Pragma: no-cache, Content-Length: 0, charset: ISO-8859-1, X-ORACLE-DMS-RID: 0, X-ORACLE-DMS-ECID: 343fa6c0-ed24-4003-ad58-342caf000404-00000383, Set-Cookie: JSESSIONID=1ZMIvt1NqrtWpHgHs4mMmYyTPUGTOQgrA9biCE3Dok5v0gDCPXu6!681252631; path=/; secure; HttpOnly;HttpOnly;Secure, Cache-Control: no-store, P3P: policyref="/w3c/p3p.xml", CP="WBP DSP NOR AMT ADM DOT URT POT NOT", Keep-Alive: timeout=5, max=250, Connection: Keep-Alive, Content-Type: text/xml, Content-Language: en] [Content-Type: text/xml,Content-Length: 0,Chunked: false]}
I am using the below code to post the data to server . I am using apache httpcomponents-client-4.5.2.
private static Registry<ConnectionSocketFactory> getRegistry() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext sslContext = SSLContexts.custom().build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionSocketFactory)
.register("https", sslConnectionSocketFactory)
.build();
}
public static void main(String[] args) throws Exception
{
PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(getRegistry());
clientConnectionManager.setMaxTotal(100);
clientConnectionManager.setDefaultMaxPerRoute(20);
HttpClient client = HttpClients.custom().setConnectionManager(clientConnectionManager).build();
HttpPost request = new HttpPost("https://someserver.com/dataupload");
File file = new File("C://Nible//code//_client//Request.xml");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setContentType(ContentType.TEXT_XML);
FileBody fileBody = new FileBody(file);
builder.addPart("my_file", fileBody);
HttpEntity reqEntity = builder.build();
request.setEntity(reqEntity);
HttpResponse response = client.execute(request);
System.out.println(response);
}
Can you please tell me what wrong am i doing?
I tried using below code instead of MultipartEntityBuilder. I am still getting the same error.
EntityBuilder builder = EntityBuilder.create();
builder.setFile(file);
builder.setContentType(ContentType.TEXT_XML);
If i am sending the BLANK REQUEST to server then also i am getting the same error. Blank error means i am not putting any thing in request just
HttpPost request = new HttpPost("https://someserver.com/dataupload");
HttpResponse response = client.execute(request);
A: I suspect of these lines in your code:
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setContentType(ContentType.TEXT_XML);
Multipart entities cannot be of content-type xml. They must be one of these types:
*
*multipart/mixed
*multipart/alternative
*multipart/digest
*multipart/parallel
(See RFC 1341 7.2)
I guess you should use one of these content-types for the multipart entity, and set text/xml as the content type of the single part:
FileBody fileBody = new FileBody(file, ContentType.TEXT_XML);
(Another issue is that I don't see necessary to send a multipart for just one file: You could leave out the MultipartEntityBuilder object and build directly a FileEntity.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39376712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Mapping attributes using @JsonProperty when binding play.data.Form from JsonNode I have the following class
public static class Thing {
@JsonProperty("_name_")
String name;
}
and I'm trying to bind it to the form and get instance of this class this way
ObjectNode node = Json.newObject();
node.put("_name_", "some name");
Form<Thing> thingForm = Form.form(Thing.class);
thingForm = thingForm.bind(node);
Thing thing = thingForm.get();
So, I expect that thing.name will be "some name" but it's not, it is null. I understant that @JsonProperty is for Json (de)serialization, just tried if it works. The question is how to achieve this with Play's Form?
I also tried to Register a custom DataBinder as described in docs, but its methods never gets called.
Any help is appreciated.
A: Have you tried thingForm.bindFromRequest() instead of thingForm.bind()? I am using exactly same thing where I make an ajax post with json data and it is working fine for me. It doesn't look like it has anything to do with @JsonProperty().
Are you sure if you want to have class Thing static ? I am assuming you have public getter/setters for your form properties.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27060882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PaypalPlus iFrame integration with Payment Logos How can I add the payment logo to the PaypalPlus iFrame integration? We have 2 extensions for PaypalPlus, the old one shows payment logos for Paypal, direct debit etc. but the new one not. (The Image has class class="paymentMethodIcon")
In all SDK & Integration guides I did not find any information about this.
Who can help? Is this something which depends on integration and is controlled by Paypal or is there any setting?
Thats how it should look
A: The payment wall iframe is configured by paypal with a whitelist of allowed domains (see Content Security Policy).
*
*The image URL must be https (specified in the docs)
*Your images must be on a server on the whitelist.
*This includes: The image URL can not have a custom port.
*PayPal automatically adds the domain containing the PPP script to the whitelist.
If you look into the browser console you might be able to see an error like this:
Refused to load the image 'https://my-domain.de:7443/images/payment_sofort_small.png' because it violates the following Content Security Policy directive: "img-src https://*.paypalobjects.com https://ak1s.abmr.net https://ak1.abmr.net https://ak1s.mathtag.com https://akamai.mathtag.com https://my-domain.de".
This is how it looked in my case:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42230832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: create distinct objects in a loop in js var subject = [] ;
var subjectTemplate = {GUID:"", Title:"", Description:""};
for (var x = 0; x < 5; x++) {
var clsSubject = subjectTemplate;
clsSubject.GUID = id.generateRandomNumber()
clsSubject.Title = "Intorduction to js";
clsSubject.Description = "Subject to learn js";
subject.push = clsSubject;
}
what is happening is that there are 5 references of the same object in the array. So after the last run; all the 5 objects in the array have the same values. The five objects in the array are identical.
I need to create 5 distinct objects with distinct values in an array.
A: After doing some research and have come with the following:
var subjects = [];
var subjectTemplate = {GUID:""};
for (var x = 0; x < 5; x++)
{
var subject = Object.Create(subjectTemplate);
subject.GUID = <generate GUID>;
subjects[x] = subject;
}
A: With javascript you do not need to declare or initialize the fields when you first initialize the object.
Replace
var clsSubject = subjectTemplate;
with
var clsSubject = {};
With your current implementation you set all clsSubject to the same object instance, namely subjectTemplate.
A: You can just change the delcaration of clsSubject to create a new object. You can actually just fill in the properties directly if you want. Also you didn't push to the array correctly.
var clsSubject = {
GUID: id.generateRandomNumber(),
Title: "Intorduction to js",
Description: "Subject to learn js"
};
subject.push(clsSubject);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57581806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Rails - Running tests with unexpected results - should be failing but instead its passing I am doing Hartl's tutorial.
https://www.railstutorial.org/book/static_pages
On section 3.3.3
I am running test but running into unexpected results.
In my static_pages_controller_test.rb I have the following:
test "should get about" do
get :about
assert_response :success
end
According to Listing 3.17, I should be getting:
AbstractController::ActionNotFound:
The action 'about' could not be found for StaticPagesController
However, the test still passes even though there is no about action defined in my static_pages_controller.rb
gemfile:
group :test do
gem 'minitest-reporters', '1.0.5'
gem 'mini_backtrace', '0.1.3'
gem 'guard-minitest', '2.3.1'
end
Guardfile (though I'm not actively running it to execute test)
# Defines the matching rules for Guard.
guard :minitest, spring: true, all_on_start: false do
watch(%r{^test/(.*)/?(.*)_test\.rb$})
watch('test/test_helper.rb') { 'test' }
watch('config/routes.rb') { integration_tests }
watch(%r{^app/models/(.*?)\.rb$}) do |matches|
"test/models/#{matches[1]}_test.rb"
end
watch(%r{^app/controllers/(.*?)_controller\.rb$}) do |matches|
resource_tests(matches[1])
end
watch(%r{^app/views/([^/]*?)/.*\.html\.erb$}) do |matches|
["test/controllers/#{matches[1]}_controller_test.rb"] +
integration_tests(matches[1])
end
watch(%r{^app/helpers/(.*?)_helper\.rb$}) do |matches|
integration_tests(matches[1])
end
watch('app/views/layouts/application.html.erb') do
'test/integration/site_layout_test.rb'
end
watch('app/helpers/sessions_helper.rb') do
integration_tests << 'test/helpers/sessions_helper_test.rb'
end
watch('app/controllers/sessions_controller.rb') do
['test/controllers/sessions_controller_test.rb',
'test/integration/users_login_test.rb']
end
watch('app/controllers/account_activations_controller.rb') do
'test/integration/users_signup_test.rb'
end
watch(%r{app/views/users/*}) do
resource_tests('users') +
['test/integration/microposts_interface_test.rb']
end
end
# Returns the integration tests corresponding to the given resource.
def integration_tests(resource = :all)
if resource == :all
Dir["test/integration/*"]
else
Dir["test/integration/#{resource}_*.rb"]
end
end
# Returns the controller tests corresponding to the given resource.
def controller_test(resource)
"test/controllers/#{resource}_controller_test.rb"
end
# Returns all tests for the given resource.
def resource_tests(resource)
integration_tests(resource) << controller_test(resource)
end
A: Do you have a view named about in static_pages_controller's corresponding view folder?
If so, rails assumes controller action just being empty and proceeds with render.
To have test fail - rename or delete the view
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34160948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to make two UIGestures respond simultaneously on two different views? I have View (A) has two subviews: view B and view C. View (B) that has a UILongPressGestureRecognizer and View (C) has a UIPanGestureRecognizer and is hidden by default. When I long press on a View B, view C is shown (isHidden = false).
Now, when I long press on view B, view C is shown but gesture defined in it is not responding, gesture defined in view B is still active.
I want to be able to respond to UIPanGestureRecognizer of View C when it is shown, and when I release touch I want to ended both gestures a UILongPressGestureRecognizer of View B, and UIPanGestureRecognizer of View C.
Is it possible?
A: I think there is no necessary to add UIPanGestureRecognizer to View(C), you can recognize finger position in UILongPressGestureRecognizer handle method. look at sample code
declare variables:
@IBOutlet var cView: UIView?
Here is UILongPressGestureRecognizer handle method:
@IBAction func handleLongPressGesture(_ gesture: UILongPressGestureRecognizer) {
switch gesture.state {
case .began:
cView?.isHidden = false
case .changed:
if let cView = cView, cView.isHidden == false {
let location = gesture.location(in: self.cView)
print("Finger Location - (\(location.x),\(location.y))")
}
case .ended, .cancelled:
cView?.isHidden = true
default: break
}
}
The code performs your requirements.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49415107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Outlook Manifest functional in web Outlook, won't properly install in desktop Outlook I'm working on an Outlook Add-In. I've been working so far in the web version, but my understanding is that a manifest that functions in Web should automatically also function in Desktop.
However, I'm encountering an issue where I install my add-in on the desktop, it succeeds, but then instantly disappears. If I go to the "Get Add-ins" page again and go to My Addins, my addin which I just installed does not show up.
This add-in is fully functional in web outlook, so I'm not at all sure what the issue may be. I've tried validating it using
npx office-addin-manifest validate MANIFEST_FILE
But it passes this. I've also tried enabling runtime logging, but I just get an empty log file if I install it while logging. I'm not sure where to go from here. I've confirmed that the same issue occurs on another machine.
My suspicion is that it may have something to do with the utilization of VersionOverrides 1.1 (we're using this to support pinning a task pane open), but I have no idea why this would cause an issue in Desktop. Minus the resources section, our buttons/tabs are defined with the VersionOverrides 1.1 section.
Appreciate any suggestions for further debugging!
<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp
xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0"
xmlns:mailappor="http://schemas.microsoft.com/office/mailappversionoverrides/1.0"
xsi:type="MailApp">
<!-- IMPORTANT! Id must be unique for your add-in, if you reuse this manifest ensure that you change this id to a new GUID. -->
<Id>d0aa58bd-1618-45ed-a773-9e8353a85215</Id>
<Version>1.0.0.0</Version>
<ProviderName>Test Name</ProviderName>
<DefaultLocale>en-US</DefaultLocale>
<DisplayName DefaultValue="Onvio Add-In" />
<Description DefaultValue="Onvio Outlook Add-In For Interaction With Document Management Service"/>
<IconUrl DefaultValue="https://img.icons8.com/clouds/2x/cloud-network.png" />
<HighResolutionIconUrl DefaultValue="https://d1nhio0ox7pgb.cloudfront.net/_img/g_collection_png/standard/256x256/earth.png" />
<SupportUrl DefaultValue="https://localhost:4200"/>
<!--End Basic Settings. -->
<Hosts>
<Host Name="Mailbox" />
</Hosts>
<Requirements>
<Sets>
<Set Name="Mailbox" MinVersion="1.1" />
</Sets>
</Requirements>
<FormSettings>
<Form xsi:type="ItemEdit">
<DesktopSettings>
<SourceLocation DefaultValue="https://localhost:4200"/>
</DesktopSettings>
</Form>
</FormSettings>
<Permissions>ReadWriteItem</Permissions>
<Rule xsi:type="RuleCollection" Mode="Or">
<Rule xsi:type="ItemIs" ItemType="Message" FormType="Read" />
</Rule>
<DisableEntityHighlighting>false</DisableEntityHighlighting>
<VersionOverrides xmlns="http://schemas.microsoft.com/office/mailappversionoverrides" xsi:type="VersionOverridesV1_0">
<Resources>
<bt:Images>
<bt:Image id="Onvio.PaneButton.Icon" DefaultValue="https://i.imgur.com/FkSShX9.png" />
</bt:Images>
<bt:Urls>
<bt:Url id="Onvio.FunctionFile.Url" DefaultValue="https://localhost:4200" />
<bt:Url id="Onvio.Taskpane.Url" DefaultValue="https://localhost:4200" />
</bt:Urls>
<bt:ShortStrings>
<bt:String id="Onvio.Pane.Title" DefaultValue="Onvio Side Panel" />
<bt:String id="Onvio.Pane.Label" DefaultValue="Show Taskpane" />
<bt:String id="Onvio.Tab.Label" DefaultValue="Onvio Tab Label" />
<bt:String id="Onvio.OpenedMessageTools.Label" DefaultValue="Onvio.OpenedMessageTools.Label" />
<bt:String id="Onvio.ComposeMessageTools.Label" DefaultValue="Onvio.ComposeMessageTools.Label" />
</bt:ShortStrings>
<bt:LongStrings>
<bt:String id="Onvio.Pane.Description" DefaultValue="Onvio Side Panel Description" />
</bt:LongStrings>
</Resources>
<VersionOverrides xmlns="http://schemas.microsoft.com/office/mailappversionoverrides/1.1" xsi:type="VersionOverridesV1_1">
<Description resid="residDescription" />
<Requirements>
<Sets xmlns="http://schemas.microsoft.com/office/officeappbasictypes/1.0">
<Set Name="Mailbox" MinVersion="1.1" />
</Sets>
</Requirements>
<Hosts>
<Host xsi:type="MailHost">
<DesktopFormFactor>
<ExtensionPoint xsi:type="MessageComposeCommandSurface">
<OfficeTab id="TabDefault">
<Group id="Message" xmlns="http://schemas.microsoft.com/office/mailappversionoverrides/1.1">
<Label resid="Onvio.ComposeMessageTools.Label" />
<Control xsi:type="Button" id="Onvio.ComposePane.Button">
<Label resid="Onvio.Pane.Label" />
<Supertip>
<Title resid="Onvio.Pane.Title" />
<Description resid="Onvio.Pane.Description" />
</Supertip>
<Icon>
<bt:Image size="16" resid="Onvio.PaneButton.Icon" />
<bt:Image size="32" resid="Onvio.PaneButton.Icon" />
<bt:Image size="80" resid="Onvio.PaneButton.Icon" />
</Icon>
<Action xsi:type="ShowTaskpane">
<SourceLocation resid="Onvio.Taskpane.Url" />
<SupportsPinning>true</SupportsPinning>
</Action>
</Control>
</Group>
</OfficeTab>
</ExtensionPoint>
<ExtensionPoint xsi:type="MessageReadCommandSurface">
<CustomTab id="Onvio.OpenedMessageTools.Tabs">
<Group id="Onvio.OpenedMessageTools.Group" xmlns="http://schemas.microsoft.com/office/mailappversionoverrides/1.1">
<Label resid="Onvio.OpenedMessageTools.Label" />
<Control xsi:type="Button" id="Onvio.Pane.Button">
<Label resid="Onvio.Pane.Label" />
<Supertip>
<Title resid="Onvio.Pane.Title" />
<Description resid="Onvio.Pane.Description" />
</Supertip>
<Icon>
<bt:Image size="16" resid="Onvio.PaneButton.Icon" />
<bt:Image size="32" resid="Onvio.PaneButton.Icon" />
<bt:Image size="80" resid="Onvio.PaneButton.Icon" />
</Icon>
<Action xsi:type="ShowTaskpane">
<SourceLocation resid="Onvio.Taskpane.Url" />
<SupportsPinning>true</SupportsPinning>
</Action>
</Control>
</Group>
<Label resid="Onvio.Tab.Label" />
</CustomTab>
</ExtensionPoint>
</DesktopFormFactor>
</Host>
</Hosts>
</VersionOverrides>
</VersionOverrides>
</OfficeApp>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59200376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Injecting application level dependency into node module I'm trying to create package from higher order components that are currently in application.
The issue is that in some of those components application routes are being used ( through helper that imports all the routes and returns url based on route name ).
I have no idea how to inject those routes to my module from app level.
For example in Symfony ( PHP ) this issue would be fairly simple, due to dependency injection. But with imports inside each file I'm really lost here.
I'm using NextJS and here is code sample ( I would love to inject those routes instead of directly importing them ):
import { routes } from "../../routes";
export default (routeName, params) =>
routes.find(route => route.name === routeName).toPath(params);
A: You could build your own dependency injection module.
Using NodeJs it's fairly simple to do.
This one for instance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58264884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I create an HTML list in a D3.js SVG container Here is the code I am working on. I want to plot events for a certain year as an unordered list.
Is it possible to do using d3.js?
Code-
var mevent = svg.append("text")
.attr("class", "year mevent")
.attr("text-anchor", "end")
.attr("y", height - 450)
.attr("x", width - 300)
.attr("width", 1000)
.attr("height", 200)
.text("");
// Updates the display to show the specified year.
function displayYear(year) {
dot.data(interpolateData(year), key).call(position).sort(order);
year = Math.round(year);
label.text(year);
price.text("$ " + iacprices[year]);
mevents_text = "";
for (var i = 0; i < (mevents[year]).length; i++) {
mevents_text = "*" + mevents_text
+ (mevents[year])[i];
}
mevent.text(mevents_text);
A: Yes, you can place HTML elements in a SVG with a foreignObject.
Example w/ d3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18890040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL Server SMO script generation throwing deadlock error I have a huge database with nearly 16k tables. Some of these tables are transnational tables and always receive some insert/select/update queries.I am using SMO to transfer the definition of all these 16K tables to some test database. But my code is failing while scripting tables and throwing deadlock issue (especially while copying those transaction heavy tables). I was just wondering "why deadlock" as SMO internally use some SYS tables to extract definition and shouldn't be messing up with any other transaction.
Stack trace:
<SqlException>
<Message>Transaction (Process ID 670) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.</Message>
<Server>p01db107</Server>
<Source>.Net SqlClient Data Provider</Source>
<StackTrace> at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
at System.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)
at System.Data.SqlClient.SqlDataReader.Read()
at Microsoft.SqlServer.Management.Smo.DataProvider.ReadInternal()
at Microsoft.SqlServer.Management.Smo.DataProvider.Read()
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.InitObjectsFromEnumResults(Urn levelFilter, IDataReader reader, Boolean forScripting, List`1 urnList, Int32 startLeafIdx, Boolean skipServer)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.InitQueryUrns(Urn levelFilter, String[] queryFields, OrderBy[] orderByFields, String[] infrastructureFields, ScriptingPreferences sp, Urn initializeCollectionsFilter)
at Microsoft.SqlServer.Management.Smo.DefaultDatabasePrefetch.PrefetchUsingIN(String idFilter, String initializeCollectionsFilter, String type, IEnumerable`1 prefetchingList)
at Microsoft.SqlServer.Management.Smo.DatabasePrefetchBase.<PrefetchObjects>d__1.MoveNext()
at Microsoft.SqlServer.Management.Smo.SmoDependencyDiscoverer.SfcChildrenDiscovery(HashSet`1 discoveredUrns)
at Microsoft.SqlServer.Management.Smo.SmoDependencyDiscoverer.Discover(IEnumerable`1 urns)
at Microsoft.SqlServer.Management.Smo.ScriptMaker.DiscoverOrderScript(IEnumerable`1 urns)
at Microsoft.SqlServer.Management.Smo.ScriptMaker.ScriptWorker(List`1 urns, ISmoScriptWriter writer)
at Microsoft.SqlServer.Management.Smo.Scripter.ScriptWithListWorker(DependencyCollection depList, SqlSmoObject[] objects, Boolean discoveryRequired)
at Microsoft.SqlServer.Management.Smo.Scripter.ScriptWithList(DependencyCollection depList, SqlSmoObject[] objects, Boolean discoveryRequired)</StackTrace>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39129216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to calculate number of post which have particular meta_key? I am using repeatable meta boxes what i want to achieve is display number of post which have particular meta key such as
Country Pakistan
City Islamabad
Age 12
Age 12
Meta key "Age" is used in 2 posts.
No i want structure like Age in Post 2 , Islamabad in Post 1 , Pakistan in Post 1.
/**
* Display callback for the submenu page.
*/
function iif_register_submenu_form_details_callback() {
$id = get_current_user_id();
$loop = new WP_Query( array(
'post_type' => 'iff-info-forms',
'post_status' => 'publish',
'author' => $id,
'meta_query' => array(
array(
'key' => 'repeatable_fields',
//'value' => $user_data_new,
'compare' => 'LIKE'
))
) );
//print_r($loop);
while ( $loop->have_posts() ) : $loop->the_post();
$info = get_post_meta(get_the_id(), 'repeatable_fields', true);
if ( $info ) {
// echo '<strong>Emergency Contacts:</strong><br />';
foreach ( $info as $emergency_contact_metas ) {
echo '<strong>' . esc_html( $emergency_contact_metas['iif_label'] ) .'</strong> ' . esc_html( $emergency_contact_metas['iif_details'] ) . '<br />';
}
}
endwhile;
}
OUTPUT SHOWING IS Below
Country Pakistan
City Islamabad
Age 12
Age 12
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54928149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using C++ to receive int inputs and displaying the larger and smaller number The instructions are to
*
*Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the program when a terminating 'I' is entered.
*Change the program to write out the smaller value is: followed by the smaller of the nwnbers and the larger value is: followed by the larger value.
I got the program to run but it terminates with a Range error: Can anybody correct my mistake in this code?
/*a drill in the Programming Principles
and Practice Using C++ by Bjarne Stroustrup*/
#include "std_lib_facilities.h" /*standard library from the author's website*/
int main()
{
vector<int>values;
int a, b; //ints declared
while(cin>>a>>b){ //ints read
values.push_back(a); //ints put into vector
values.push_back(b); //********************
}
for(int i = 0; i < values.size(); ++i){ //loop
if(values[i]>values[i+1]){
cout << "The larger value is: " << values[i] << endl; /*print larger value on screen*/
}
else
cout << "The smaller value is: " << values[i] << endl; /*prints smaller value on screen*/
}
return 0;
}
A: values[i+1] goes out of bounds for the last value, so you need to change your for loop condition
for(int i = 0; i < values.size() - 1; ++i){
// ^^^
A: 1.Write a program that consists of a while-loop that (each time around
the loop) reads in two ints and then prints them. Exit the program
when a terminating 'I' is entered.
int a, b = 0;
// anything that isn't a int terminate the input e.g. 2 3 |
while (cin >> a >> b)
cout << a << " " << b << "\n";
2.Change the program to write out the smaller value is: followed by the smaller of the nwnbers and the larger value is: followed by the larger value.
int a, b;
const string smaller = "smaller value is: ";
const string larger = "larger value is: ";
while (cin >> a >> b) {
if (a < b)
cout << smaller << a << larger << b << endl;
else
cout << smaller << b << larger << a << endl;
}
if (cin.fail()) {
cin.clear();
char ch;
if (!(cin >> ch && ch == '|'))
throw runtime_error(string {"Bad termination"});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34576602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Get C Code Stack Trace in Go Program I'm using the rana/ora oracle driver in my Go program to query some Oracle tables.
The program somehow always gets SIGSEGV from a C library after running for a while and exits on segfault. It also gets a lot of query timeouts (context deadline exceeded) before it hits segfault error.
I'm using the driver in a pretty standard way:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Seconds)
defer cancel()
rows, err := initialedDb.QueryContext(ctx, "sql_query")
The stack trace from the 1st Goroutine is:
fatal error: unexpected signal during runtime execution
[signal SIGSEGV: segmentation violation code=0x1 addr=0x70 pc=0x7fbb03e5d193]
runtime stack:
runtime.throw(0xa4a0a4, 0x2a)
/usr/local/go/src/runtime/panic.go:596 +0x95
runtime.sigpanic()
/usr/local/go/src/runtime/signal_unix.go:274 +0x2db
goroutine 5230 [syscall, locked to thread]:
runtime.cgocall(0x921850, 0xc421667348, 0xa495f1)
/usr/local/go/src/runtime/cgocall.go:131 +0xe2 fp=0xc421667308 sp=0xc4216672c8
gopkg.in/rana/ora%2ev4._Cfunc_OCIAttrGet(0x2c92f08, 0x35, 0xc421cb8be4, 0xc421cb8be8, 0x5, 0x2b81930, 0xc400000000)
gopkg.in/rana/ora.v4/_obj/_cgo_gotypes.go:347 +0x4d fp=0xc421667348 sp=0xc421667308
gopkg.in/rana/ora%2ev4.(*Rset).paramAttr.func1(0x2c92f08, 0xc400000035, 0xc421cb8be4, 0xc421cb8be8, 0x5, 0x2b81930, 0xf1ef01)
/go/src/gopkg.in/rana/ora.v4/rset.go:970 +0xfc fp=0xc421667390 sp=0xc421667348
gopkg.in/rana/ora%2ev4.(*Rset).paramAttr(0xc4211f22d0, 0x2c92f08, 0xc421cb8be4, 0xc421cb8be8, 0xc400000005, 0x0, 0x0)
/go/src/gopkg.in/rana/ora.v4/rset.go:976 +0x88 fp=0xc4216673e0 sp=0xc421667390
gopkg.in/rana/ora%2ev4.(*Rset).open(0xc4211f22d0, 0xc421358000, 0x7fbae405ed28, 0x0, 0x0)
/go/src/gopkg.in/rana/ora.v4/rset.go:554 +0xd43 fp=0xc421667b98 sp=0xc4216673e0
gopkg.in/rana/ora%2ev4.(*Stmt).qryC(0xc421358000, 0xf1e940, 0xc421ace900, 0xc421cb8ad0, 0x1, 0x1, 0xc4211f22d0, 0x0, 0x0)
/go/src/gopkg.in/rana/ora.v4/stmt.go:442 +0x3e0 fp=0xc421667f18 sp=0xc421667b98
gopkg.in/rana/ora%2ev4.(*DrvStmt).QueryContext.func1(0xc421b73260, 0xc420e789e8, 0xc420e789e0, 0xf1e940, 0xc421ace900, 0xc421cb8ad0, 0x1, 0x1)
/go/src/gopkg.in/rana/ora.v4/drvStmt_go1_8.go:76 +0xa6 fp=0xc421667fa0 sp=0xc421667f18
runtime.goexit()
/usr/local/go/src/runtime/asm_amd64.s:2197 +0x1 fp=0xc421667fa8 sp=0xc421667fa0
created by gopkg.in/rana/ora%2ev4.(*DrvStmt).QueryContext
/go/src/gopkg.in/rana/ora.v4/drvStmt_go1_8.go:82 +0x30c
I checked my program many times and I don't think I'm causing any memory leaks, double frees or anything like that.
I wonder how I can debug this since Go doesn't give me C's stack trace. Will Valgrind's Memcheck tool help?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43727349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Different effects of ORDER BY clause on two servers My query:
SELECT * FROM table GROUP BY id;
id field is a primary key, of course;
In 9.4.4 I get expected error:
column "table.name" must appear in the GROUP BY clause or be used in an aggregate function
BUT! In 9.4.5 it works, like in MySQL.
Can anybody tell me - why? :)
A: Postgres version does not matter here. The tables are not identical. Most likely in your 9.4.5 table the column id is a primary key, while in 9.4.4 is not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35031563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Apps Script - Use Column Name (not In row1) rather than column number I have an Apps Script linked to my Google Sheet which grabs a range from one sheet and copies it to another. The issue I face now (and one that cannot be reasoned with) is that users will add columns to the destination sheet. What I am trying to do instead is look for the column names; to add another slight spanner in the works the column names are on row 7 instead of 1.
function OPupdates() {
// I have tried looking at this but couldn't get it to work for me- https://stackoverflow.com/questions/45901162/refer-to-column-name-instead-of-number-in-google-app-script
//Copies Status From One Sheet To Another
var sheetfrom2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Helper Sheet'); //this contains source info
var sheetto2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Plan');//sheet into which the new source data is copied
sheetfrom2.getRange(2, 2, sheetfrom2.getLastRow(), 1).copyTo(sheetto2.getRange(8,8, sheetfrom2.getLastRow()-2, 1), {
contentsOnly: true
});
//row 8 column 8. This is what needs to be changes to reflect the column name regardless of where it sits in row 8
}
I have tried looking at a similar issue/solution (link in the code above) but try as I might I could not figure out how to get this to work for my particular issue.
A: Instead of copying the range you'll need to create a value array that matches the target structure.
In lieu of sample data I'll play with the following toy example:
Sheet "Source":
A
B
C
1
1
2
Sheet "Target":
_
A
B
C
D
1
2
3
4
5
6
7
8
B
E
C
A
function copyOver() {
const source = SpreadsheetApp
.getActiveSpreadsheet()
.getSheetByName("Source")
.getDataRange()
.getValues();
const target = SpreadsheetApp
.getActiveSpreadsheet()
.getSheetByName("Target");
const headerRow = 8;
const targetHeaders = target.getDataRange().getValues()[headerRow - 1];
const sourceHeaders = source[0];
const sourceValues = source.slice(1);
const columnLookup = targetHeaders.map(h => sourceHeaders.indexOf(h));
function buildRow(row) {
return columnLookup.map(c => c == -1 ? "" : row[c]);
}
const output = sourceValues.map(buildRow);
if (output.length > 0) {
target
.getRange(headerRow + 1, 1, output.length, output[0].length)
.setValues(output);
}
}
A: First of all try yelling at users and making them understand that they may not mess with sheets with active programming (This is successful 75% of the time). Otherwise, you'll want to check your columns before you copy.
function OPupdates() {
var sheetfrom2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Helper Sheet'); //this contains source info
var sheetto2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Plan');//sheet into which the new source data is copied
var statuscolumn = -1;
var headerWewant = "STATUS";//modify for the correct column name
var targetSheetHeader = sheetto2.getRange(1,1,1,sheetto2.getLastColumn().getValues();
for (var j=0; i<targetSheetHeader[0].length;i++)
{
if (data[0][j] == headerWeWant) statuscolumn = j+1;
}
if (statuscolumn == -1) {console.error("Couldn't find the status column"; return;}
sheetfrom2.getRange(2, 2, sheetfrom2.getLastRow(), 1).copyTo(sheetto2.getRange(8,statuscolumn, sheetfrom2.getLastRow()-2, 1), {
contentsOnly: true
});
}
But training the users to go in fear of your wroth is a better long term strategy ;).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69254915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Insert contents of a file in middle of another file with Python? There is already a question on SO that explains how to insert a line into the middle of a python file at a specific line number.
But what if I have 2 files. inputfile.txt and outputfile.txt (which already has some text) and I want to insert all of inputfile.txt (with formatting preserved) into the middle of outputfile.txt?
A: Why do you think it is any different from this probable SO question you are referring to?
Its just that instead of inserting a line, you need to read your inputfile.txt into a variable as shown here
and insert that into the file, instead of the value as clearly shown in the question. (links provided above)
A: insert contents of "/inputFile.txt" into "/outputFile.txt" at line 90
with open("/inputFile.txt", "r") as f1:
t1 = f1.readlines()
with open("/outputFile.txt", "r") as f2:
t2 = f2.readlines()
t2.insert(90, t1)
with open("/outputFile.txt", "w") as f2:
f2.writelines(t2)
That should do it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51353969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is SparseArray good for resource id keys? Is it advisable to use a SparseArray when the integer keys are resources id's? Or is it aimed at keys with lower numbers?
Yes, I know the definition of SparseArray, and the compiler always issues a warning when one uses ArrayList with integer keys, advising to use SparseArray.
But maybe when SparseArray was defined, they had in mind an array where you do have elements, but not all of them.
In my case, I want to use Resource IDs as keys, which are, for those of you who had a pick at the generated R.java file, very big numbers only. So I though that it may not fit, not only the intention, but also the implementation of SparseArray.
A: SparseArray is exactly for values which are of an unknown range. So it seems to fit your need.
A: in R.java the resrource ids are all integer so there is no problem using sparse array.
A: Do not use the SparseArray together with the Resourse IDs as keys. SparseArraysorts keys in ascending order for efficient access. Since resource ids are generated automatically, you cannot guarantee their order within SparseArray. This means that when you iterate over the SparseArray, you will not follow the same order as you would when filling in the FW.
I think you should use LinkedHashMap instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16756935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How Do I Ensure a Candidate Latin Square Is a Valid Damm Operation Table I am attempting to write a function in Scala that takes a valid Latin Square as input and then returns a Boolean value indicating whether the input Latin Square is a valid instance of an operation-table for the Damm Algorithm, or not. The Damm Algorithm appears to be of the "Check digit" class of error detection mechanisms.
The desired function is an implementation of the implication described in the Design section of the Wikipedia article for the Damm Algorithm. The implication is captured by the assertion of:
a weak totally anti-symmetric quasigroup with the property x ∗ x = 0
I'm insufficient in both the math skills to properly read and interpret Damm's paper, and then having enough German (the language within which the paper was written) reading skills to be able to confidently interpret how I would encode a correct validation function.
Given the following function definition:
def validate(latinSquare: List[List[Int]]): Boolean =
???
With what would I replace the ????
Within the paper, a single instance of a valid 10x10 Latin Square is provided. It is reproduced within the Wikipedia article and looks like this:
|0 1 2 3 4 5 6 7 8 9
-+-------------------
0|0 3 1 7 5 9 8 6 4 2
1|7 0 9 2 1 5 4 8 6 3
2|4 2 0 6 8 7 1 3 5 9
3|1 7 5 0 9 8 3 4 2 6
4|6 1 2 3 0 4 5 9 7 8
5|3 6 7 4 2 0 9 5 8 1
6|5 8 6 9 7 2 0 1 3 4
7|8 9 4 5 3 6 2 0 1 7
8|9 4 3 8 6 1 7 2 0 5
9|2 5 8 1 4 3 6 7 9 0
I can see there are others who have sought an answer to this. However, no one has yet provided a requested code-based valid Latin Square solution.
I have coded up a generic Latin Square generator, but need the above validation function which will serve as the filter to eliminate each candidate Latin Square that does not meet the necessary condition(s) of the above implication.
A: In functional programming terms, the checksum algorithm is foldLeft with a carefully chosen binary operation. The requirements for this binary operation, in English:
*
*In every two-digit input, if we change one of the digits, then the checksum changes (Latin square…);
*In every three-digit input, if the latter two digits are distinct and we swap them, then the checksum changes (…with weak total antisymmetry);
*The Latin square has zeros on the diagonal.
In Python 3:
def validate(latinSquare):
Q = range(len(latinSquare))
return all(
x == y
for c in Q
for x in Q
for y in Q
if latinSquare[latinSquare[c][x]][y] == latinSquare[latinSquare[c][y]][x]
) and all(latinSquare[x][x] == 0 for x in Q)
print(
validate(
[
[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
[5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
[8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
[9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0],
]
)
)
A: This is a conversion into Scala of the Python 3 Answer that was provided by David Eisenstat's answer.
View in Scastie:
def isValidDammOperationTable(validLatinSquare: List[List[Int]]): Boolean = {
val indices = validLatinSquare.indices.toList
(
indices.forall(index => validLatinSquare(index)(index) == 0)
&& indices.forall(
c =>
indices.forall(
x =>
indices.forall(
y =>
(validLatinSquare(validLatinSquare(c)(x))(y) != validLatinSquare(validLatinSquare(c)(y))(x))
|| (x == y)
)
)
)
)
}
val exampleLatinSquareX10: List[List[Int]] =
List(
List(0, 3, 1, 7, 5, 9, 8, 6, 4, 2)
, List(7, 0, 9, 2, 1, 5, 4, 8, 6, 3)
, List(4, 2, 0, 6, 8, 7, 1, 3, 5, 9)
, List(1, 7, 5, 0, 9, 8, 3, 4, 2, 6)
, List(6, 1, 2, 3, 0, 4, 5, 9, 7, 8)
, List(3, 6, 7, 4, 2, 0, 9, 5, 8, 1)
, List(5, 8, 6, 9, 7, 2, 0, 1, 3, 4)
, List(8, 9, 4, 5, 3, 6, 2, 0, 1, 7)
, List(9, 4, 3, 8, 6, 1, 7, 2, 0, 5)
, List(2, 5, 8, 1, 4, 3, 6, 7, 9, 0)
)
println(isValidDammOperationTable(exampleLatinSquareX10)) //prints "true"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72341050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to set full-text index to 'active' in table-designer In SQL Server 2008 R2 Management Studio, I have set my database to be full-text indexed and ran the command
EXEC sp_fulltext_database 'enable'
along with creating a catalog. When I open the table design mode, and right click the Primary Key, then click Full-Text Indexes in the context menu, I add my columns under the 'General' section, but when I go to set it to Active = Yes, it's grayed out.
How can I change this? Here is a screen-shot of what it's looking like.
http://snag.gy/2QSDN.jpg
A: For some reason you can't enable or disable the full text index from that screen. Instead you have to right-click the table in Object Explorer, then choose Full-Text index > Enable Full-Text index.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30243955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: It gives this error while running: undefined is not a function (evaluating '_reactNativr.default.createElement') This section of code is not running it always return en error saying undefined or not a function in the render function().
Heading
'use strict';
import React, {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
AlertIOS,
Dimensions,
BackHandler,
PropTypes,
Component,
} from 'react-native';
import NavigationExperimental from 'react-native-deprecated-custom-
components';
var _navigator;
//var Navipanel=require('./App/Navigation/Navipanel.js');
var Dashboard= require('./App/Dashboard/dashboard.js');
//var Sample= require('./App/Navigation/sample.js');
var Matches = require('./App/Components/Matches.js');
var Users = require('./App/Components/Users.js');
var SCREEN_WIDTH =require('Dimensions').get('window').width;
var BaseConfig=NavigationExperimental.Navigator.SceneConfigs.FloatFromRight;
var CustomLeftToRightGesture = Object.assign({}, BaseConfig.gestures.pop,
{
snapVelocity: 8,
edgeHitWidth: SCREEN_WIDTH,
});
BackHandler.addEventListener('hardwareBackPress', () => {
if (_navigator.getCurrentRoutes().length === 1) {
return false;
}
_navigator.pop();
return true;
});
var CustomSceneConfig = Object.assign({}, BaseConfig, {
// A very tighly wound spring will make this transition fast
springTension: 100,
springFriction: 1,
// Use our custom gesture defined above
gestures: {
pop: CustomLeftToRightGesture,
}
});
//var createReactElement = require('create-react-element');
var createReactClass = require('create-react-class');
var test = createReactClass({
_renderScene(route,navigator) {
_navigator = navigator;
if (route.id === 1) {
return <Dashboard navigator={navigator}/>;
}
else if(route.id === 2) {
return <Sample navigator={navigator} /> ;
}
else if(route.id === 3) {
return <Navipanel navigator={navigator} /> ;
}
else if(route.id === 4){
return <Matches navigator={navigator} /> ;
}
else if(route.id === 5) {
return <Users navigator={navigator} />
}
},
_configureScene(route) {
return CustomSceneConfig;
},
render:function() {
return (
<NavigationExperimental.Navigator [//error in this line]
initialRoute = {{id:1}}
renderScene = {this._renderScene}
configureScene = {this._configureScene} />
);
}
});
Undefined error _reactNative.default.createElement
A: You imported React from "react-native";
import React, {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
AlertIOS,
Dimensions,
BackHandler,
PropTypes,
Component,
} from 'react-native';
instead of this, you need to import React from "react";
import React from 'react';
When we use JSX in our render functions, in the background JSX runs React.createElement(...). And in your code, React is not defined. Because of this, it gives that error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54548608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Wordpress SQL query different results I added a custom Visual Composer element and want to output a result of a query. However when I output this query(1) it gives other results then when I output this query(2).
// declared vars
global $wpdb;
$nn = '{{ post_data:ID }}';
$nn1 = (string)$nn;
1) $results2 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = 526 AND guid like '%pdf'", OBJECT );
2) $results2 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = ".$nn1." AND guid like '%pdf'", OBJECT );
When I output the 526 string(query 1) it gives the right result however I want the output to be with the var because every post has its unique ID.
I've also tried to put the var in a string so it isn't being seen as a POST_ID
$nn = '{{ post_data:ID }}';
$nn1 = (string)$nn;
Any ideas to where this is failing?
What i've tried in the meantime:
$nn1 = (string)$nn;
$nn2 = strval($nn);
$nn3 = settype($nn, "string");
$results1 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = ".$nn1." AND guid like '%pdf'", OBJECT );
$results2 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = ".$nn2." AND guid like '%pdf'", OBJECT );
$results3 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = ".$nn3." AND guid like '%pdf'", OBJECT );
$results4 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = %d AND guid like '%pdf'", $nn3, OBJECT );
All of the above are returning an empty string which means there is still something wrong with the var
When I echo the whole string it returns the right mysql query:
echo ("SELECT guid FROM wp_posts WHERE post_parent = ".$nn."");
//output
SELECT guid FROM wp_posts WHERE post_parent = 526;
When I execute that query, it gives me the right solution:
$results6 = $GLOBALS['wpdb']->get_results( "SELECT guid FROM wp_posts WHERE post_parent = 526", OBJECT );
// output
[6]=>object(stdClass)#8030 (1) {
["guid"]=>
string(69) "http://blabla.pdf"}
Greetz
A: None of your tests seem to include the one query you've shown to be working:
$GLOBALS['wpdb']->get_results(
"SELECT guid FROM wp_posts WHERE post_parent = $nn",
OBJECT
);
There's no need to do any type conversions, especially not to string. $nn should contain int 526.
full disclosure: I'm not a WP dev and I have no idea how you got from '{{ post_data:ID }}' to 256, also string(18) "526" seems like a very weird output to me. (groetjes aan de daddykaters!)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41427896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Solve PHP7.2 use of undefined constant priority warning In trying the next PHP 7.2 release out on my site (previously we've been on 7.1 with no problems) I noticed that one of our older scripts suddenly began throwing up this warning.
Warning: Use of undefined constant priority - assumed 'priority' (this will throw an Error in a future version of PHP) in /../plugins.inc.php on line 146
Of course I could hide this as it's only a warning but I'd rather figure out the problem than store them up for PHP8.0. The code it relates to is this block and nothing else in the file appears to be related to it.
function SortByActionPriority($a, $b) {
return $a[priority] > $b[priority] ? 1 : -1;
}
Sadly this is not a system I'm familiar with (it's an older one) and it has thousands of PHP files, so I'm not entirely sure where else in the program this is being used for full context.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47605881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ERLANG - Pattern Matching specifc pattern in unknown size list Ok now I think Im getting warmer, I have to pattern match whatever comes in.
So if I had say
Message = = [[<<>>],
[<<"10">>,<<"171">>],
[<<"112">>,<<"Gen20267">>],
[<<"52">>,<<"20100812-06:32:30.687">>]]
And I was looking to pattern match the field <<"112">>
Such as the 112 is always going to say 112, but the Gen2067 can change whenever to whatever.. its the data, it will be stored in a variable.
Also the fields can be in any order, whatever function im trying to do has to be able to find the field and parse it.
This is the code I am using right now:
loop() ->
receive
[_,[<<"112">>, Data], _] when is_list(X) -> %% Just dosen't work in anyway..
?DEBUG("Got a list ~p~n", [X]),
loop();
_Other ->
?DEBUG("I don't understand ~p~n", [_Other]),
loop()
end.
I feel im close, but not 100%
-B
A: You can extract your data this way:
1> Message = [[<<>>],
1> [<<"10">>,<<"171">>],
1> [<<"112">>,<<"Gen20267">>],
1> [<<"52">>,<<"20100812-06:32:30.687">>]] .
[[<<>>],
[<<"10">>,<<"171">>],
[<<"112">>,<<"Gen20267">>],
[<<"52">>,<<"20100812-06:32:30.687">>]]
2> [Data] = [X || [<<"112">>, X] <- Message ].
[<<"Gen20267">>]
3> Data.
<<"Gen20267">>
Another way:
4> [_, Data] = hd(lists:dropwhile(fun([<<"112">>|_]) -> false; (_)->true end, Message)).
[<<"112">>,<<"Gen20267">>]
5> Data.
<<"Gen20267">>
And another one as function in module (probably fastest):
% take_data(Message) -> Data | not_found
take_data([]) -> not_found;
take_data([[<<"112">>, Data]|_]) -> Data;
take_data([_|T]) -> take_data(T).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3471684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting multiple ints from string I have a string:
"3, V, 11, H, 21, H"
and I am trying to get
int first = 3
int second = 11
int third = 21
I'm not exactly sure how to do this since the numbers could be one or two digits, there are non-digit characters between the numbers, and I have to capture multiple numbers. I tried regex but then I'm left with "31121" which does not indicate what the three numbers are.
A: Try this code. Should get you the job done.
public static void main(String[] args){
String s = "3, V, 11, H, 21, H";
String[] t = s.split(" [ ,]*|,[ ,]*");
int first = Integer.parseInt(t[0]);
int second = Integer.parseInt(t[2]);
int third = Integer.parseInt(t[4]);
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
A: You can split your String by "," and check if it's a number using NumberUtils.isNumber (String str) from org.apache.commons.lang.math.NumberUtils :
Checks whether the String a valid Java number.
Valid numbers include hexadecimal marked with the 0x qualifier,
scientific notation and numbers marked with a type qualifier (e.g.
123L).
Null and empty String will return false.
String s = "3, V, 11, H, 21, H";
for(String st : s.split(",")){
if(NumberUtils.isNumber(st.trim()))
System.out.println(st);
}
If you want to check that the String contains only digits, you can use NumberUtils.isDigits(String str)
A: public static void main(String[] args) {
String in = "3, V, 11, H, 21, H";
List<String> storage = Arrays.asList(in.split(","));
List<Integer> output = new ArrayList<Integer>();
int first = 0;
int second = 0;
int third = 0;
for(String str : storage){
if(str.trim().matches("[0-9]+") ){ // or if(NumberUtils.isNumber(str) )
output.add(Integer.parseInt(str.trim()));
}
}
if(output.size() == 3){
first = output.get(0);
second = output.get(1);
third = output.get(2);
}
System.out.print("first: "); System.out.println(first);
System.out.print("second: "); System.out.println(second);
System.out.print("third: "); System.out.println(third);
}
Output:
first: 3
second: 11
third: 21
A: You can split this string by , and then check if every part is a number like this :
import java.util.*;
public class HelloWorld{
public static void main(String []args){
String str = "3, V, 11, H, 21, H";
String[] parts = str.split(", ");
ArrayList<Integer> listNumbers = new ArrayList<Integer>();
for(String x : parts){
try{
listNumbers.add( Integer.parseInt(x) );
}
catch(Exception e){}
}
for(int i=0;i<listNumbers.size();i++) System.out.println("Number "+(i+1)+" : "+listNumbers.get(i));
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20598935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Facebook api shows only statuses of the last year i'm working with a facebook app that aims to show all user statuses, after a couple of questions here on stackoverflow , i got this (almost )working.
The problem is that graph api show only statuses of last year.
Is not a script problem because if i use the Graph Api explorer tool , the json output is the same (now - october 2013).
tested with several facebook account, same problem.
Any idea / help? thanks
UPDATE:
Basically i get data from : https://graph.facebook.com/v2.1/me?fields=statuses (this is from Explorer api tool), script code is
" $request = new FacebookRequest( $session, 'GET', '/me/statuses' ); "
In both ways i got same result. (using explorer tool or by script). few statuses and i cant go back untill very old statuses.
But the problem is not my code , i'm asking because maybe there are some limitation , not listed in docs. As Wizkid suggest i've filed a bug.
A: Is a Bug.
https://developers.facebook.com/bugs/298184123723116/
We have managed to reproduce this issue and it appears to be a valid
bug. We are assigning this to the appropriate team.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26263944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.