text
stringlengths
15
59.8k
meta
dict
Q: code/website to generate stacked bar graph in jsp hi all can any one provide me the code/website name from where i can get jsp source code to generate stacked bar graph and other graphs.it will be good if code is in jsp . Thanks Yugal A: Here's one on RoseIndia's site that shows how to create area chart in JSP http://www.roseindia.net/chartgraphs/areachart-jsppage.shtml Now, just replace the charting code with the one for making bar charts and you are done: http://www.geodaq.com/jfreechart-sample/bar_chart_code.jsp
{ "language": "en", "url": "https://stackoverflow.com/questions/4407237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to cast GETDATE() to be only time ignore day,month and year I have a table for store takt-time. It's compound with "day_shift(1)" and "night_shift(0)" like below. If I put current time(by using GETDATE() function ). I need to know this current time is "day(1)" or "night(0)". my query like this. SELECT [day_shift_flag] FROM [company_working_time] WHERE GETDATE() BETWEEN [start_time] AND[end_time] But it can't found because a date received from GETDATE() isn't '1900-01-01' How to compare a only time and ignore day,month,year. What should I do? A: You can cast a DateTime as a Time data type. For example: SELECT [day_shift_flag] FROM [company_working_time] WHERE CAST(GETDATE() AS TIME) BETWEEN CAST([start_time] AS TIME) AND CAST([end_time] AS TIME) A: By Following Way You can Ignore the day,month,year SELECT [day_shift_flag] FROM [company_working_time] WHERE DatePart(HH,GETDATE()) BETWEEN DatePart(HH,[start_time]) AND DatePart(HH,[end_time])
{ "language": "en", "url": "https://stackoverflow.com/questions/27286451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC3 - How to insert a ValidationMessageFor with a line break at the end? I'm validating about 10 input fileds in a form. The ValidationMessageFor-tags should be at the top of the page, so I'm writing every one like: @Html.ValidationMessageFor(model => model.Customer.ADDRESS.NAME) @Html.ValidationMessageFor(model => model.Customer.ADDRESS.CITY) and so on. My Models look like this: [Required(ErrorMessage = Constants.ErrorMsgNameMissing)] public string NAME { get; set; } [Required(ErrorMessage = Constants.ErrorMsgCityMissing)] public string CITY { get; set; } The constants are Strings. Now, if more than one ValidationMessageFor is shown, they are all in one line. How can I insert a line break like <br /> at the end of every message? This is NOT the right way: @Html.ValidationMessageFor(model => model.Customer.ADDRESS.NAME)<br /> @Html.ValidationMessageFor(model => model.Customer.ADDRESS.CITY)<br /> since the <br /> is shown even if there is no error...;) Thanks in advance. PS: Displaying them as a list would also be great. A: I think what you're actually looking for is: @Html.ValidationSummary() A: I would go with @Html.ValidationSummary() if possible A: Check out Custom ValidationSummary template Asp.net MVC 3. I think it would be best for your situation if you had complete control over how the validation is rendered. You could easily write an extension method for ValidationMessageFor. A: Actually, at the top should be: @Html.ValidationSummary(/*...*/) The field validations should be with their respective fields. However, if you absolutely insist on putting @Html.ValidationMessageFor(/*...*/) at the top then adjust their layout behavior in your CSS and forget about the <br />'s A: I'm not sure if there's a built in way, but you could easily make another Extension method: public static MvcHtmlString ValidationMessageLineFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) { return helper.ValidationMessageFor(expression) + "<br />"; } Something like that?
{ "language": "en", "url": "https://stackoverflow.com/questions/8619499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: return extra columns based on group and count results Source data: +-----+-------------+--------+---------+ | ID | CandidateID | Rating | Name | +-----+-------------+--------+---------+ | 777 | 119 | 5 | Fred | | 777 | 120 | 5 | Tony | | 777 | 121 | 3 | Ben | | 888 | 131 | 4 | Joe | | 888 | 132 | 4 | Matt | | 888 | 133 | 1 | Russell | +-----+-------------+--------+---------+ I need to find duplicates (where ID and Rating are the same), but also somehow keep a reference to them (CandidateID) to present their names in the resulting table. Desired output (only shows rows where ID AND Rating are the same): +-----+-------------+--------+------+ | ID | CandidateID | Rating | Name | +-----+-------------+--------+------+ | 777 | 119 | 5 | Fred | | 777 | 120 | 5 | Tony | | 888 | 131 | 4 | Joe | | 888 | 132 | 4 | Matt | +-----+-------------+--------+------+ My initial approach was to GROUP by ID and Rating, producing COUNT, then do HAVING COUNT(*) >= 2, and then listing all rows where ID from that result is present. Sadly, that also returns non-duplicate rows. Is there a better solution? A: One simple way uses exists: select t.* from t where exists (select 1 from t t2 where t2.id = t.id and t2.rating = t.rating and t2.candidateid <> t.candidateid ); A: You can use analytics function for this as well SELECT ID,CANDIDATEID,RATING,NAME FROM T QUALIFY COUNT(*)OVER(PARTITION BY ID,RATING)>=2 based on your database, you can change syntax for count(*) over. This syntax works in teradata.
{ "language": "en", "url": "https://stackoverflow.com/questions/40466258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Howto merge two arrays with values from array2 that are in 1? I have an array with allowed values and an array with given values. Howto merge two arrays with values from array2 that are in 1? allowed_values => ["one", "two", "three"] given_values => ["", "one", "five", "three", "seven"] ... expected_values => ["one", "three"] A: You want the array intersection, and you can obtain it via the & operator: Set Intersection—Returns a new array containing elements common to the two arrays, with no duplicates. [ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]
{ "language": "en", "url": "https://stackoverflow.com/questions/10027608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ERROR: could not get unknown property 'plugin' for root project I am trying to build LineageOS' trebuchet launcher. After updating protobuf plugin I managed to get rid of some errors. But after several tries I can not handle this error: Could not get unknown property 'plugin' for root project 'android_packages_apps_Trebuchet-lineage-16.0' of type org.gradle.api.Project. This is my first time editing code from Github. Please help. buildscript { repositories { mavenCentral() google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.6.2' classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.13' } } apply plugin 'com.android.application' apply plugin 'com.google.protobuf' version '0.8.13' final String SUPPORT_LIBS_VERSION = '28.0.0' android { defaultConfig { compileSdkVersion 28 minSdkVersion 21 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true } buildTypes { debug { minifyEnabled false } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } There is a lot more code after this, didn't seem important so didn't add. Let me know if it's needed A: It should be: apply plugin: 'com.android.application' with a colon.
{ "language": "en", "url": "https://stackoverflow.com/questions/64497141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Crash Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE), Xamarin Forms I'm using Xamarin Forms framework for android and iOS mobile platform, on iOS devices it work's well but in Android when going on a specific page app shut down. I got this error : Explicit concurrent copying GC freed 7041(512KB) AllocSpace objects Using breakpoint I noticed crash arrived executing this var content = JsonConvert.SerializeObject( newStorageUsers, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); I show you entire demo code Page in which I got error private readonly IStorageUserService _storageService public MyPage(User user) { InitializeComponent(); ... _storageService = new StorageUserServiceImpl(); _storageService.StoreUser(user); ... } Service Interface public interface IStorageUserService { void StoreUser(User user); } Service Implementation public class StorageUserServiceImpl : IStorageUserService { private string _usersPathFile = Path.Combine(App.GetPackagePath(), "users.txt"); public StorageUserServiceImpl() { if (!File.Exists(_usersPathFile)) { _createUsersFile(); } } private void _createUsersFile() { var file = File.Create(_usersPathFile); file.Close(); } public void StoreUser(User user) { var currentStorage = GetStorageUsers(); List<StorageUser> newStorageUsers = new List<StorageUser>() { }; if (currentStorage != "" && currentStorage != "[]") { newStorageUsers = JsonConvert.DeserializeObject<List<StorageUser>>(currentStorage); } var storageUser = new StorageUser() { Infos = user, CreationDate = Helper.DateFormatter.NowDateTime() ... }; newStorageUsers.Add(storageUser); var content = JsonConvert.SerializeObject( newStorageUsers, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); _store(newStorageUsers, content); } private void _store(List<StorageUser> newStorageUser, string content) { // breakpoint can't be triggered there because app shut down with logs File.WriteAllText(_usersPathFile, content); } } This service is used on several pages but I got this bug in only one page After this message on logs : Explicit concurrent copying GC freed 7041(512KB) AllocSpace objects, 2(264KB) LOS objects, 49% free, 4343KB/8687KB, paused 187us total 28.412ms I got Pending exception java.lang.StackOverflowError: stack size 8192KB ... JNI DETECTED ERROR IN APPLICATION: JNI IsInstanceOf called with pending exception java.lang.StackOverflowError: stack size 8192KB ... Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 8815 (om.myapp.app), pid 8815 I've no more details of what happened, how can I fix this please?
{ "language": "en", "url": "https://stackoverflow.com/questions/71008984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: csv file extension hidden while downloading I have written a nodeJS + express server backend which creates reports and then uses fs.createWriteStream to write data separated by "," like below: let writeStream = fs.createWriteStream(someFilename); writeStream.write("header1, header2, header3"); writeStream.write("\n1, 2, 3"); writeStream.write("\n1, 2, 3"); writeStream.end(); Then I send the name of the file on server as a response to this request - so that user can do a post to request this file from server - like an "export to excel" functionality. All this is working fine - but when the user downloads the csv file - in windows - it always hides the extension of the csv file. It downloads as a generic common file - when I open it in an explorer window - it doesn't have an extension - so I have to manually rename it and then open it. In mac it works perfectly. I have unchecked the "hide extension for known file types" checkbox in Folder options. How do I fix this - make the browser respect the extension of the file or download it with the extension - ONLY on Windows.
{ "language": "en", "url": "https://stackoverflow.com/questions/47159521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: do a sum when clicking on the datagridview checkbox private void grid_games_CellContentClick(object sender, DataGridViewCellEventArgs e) { int total = 0; for (int i = 0; i <= grid_games.RowCount - 1; i++) { Boolean chek = Convert.ToBoolean(grid_games.Rows[i].Cells[0].Value); if (chek) { total += 1; } } total *= 50; txt_total.Text = total.ToString(); } I need to do a sum for each row selected from the datagridview selection box. each line is worth 50. it is working, but it has a delay, so when I click on 2 check, it only shows me 50... and the same delay occurs when I uncheck a box. how can i instantly get the total by clicking on that checkbox? A: The CheckBox column of the DataGridView control is implemented by the DataGridViewCheckBoxCell class, and this class has a delay function, that is, when the user selects a CheckBox in the DataGridView, it will delay updating it to the data source for a period of time. You just need to add an event about CurrentCellDirtyStateChanged to get the state immediately private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e) { if (this.dataGridView1.IsCurrentCellDirty) { this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit); } } Best used with CellValueChanged: private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { int total = 0; for (int i = 0; i <= dataGridView1.RowCount - 1; i++) { Boolean chek = Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value); if (chek) { total += 1; } } total *= 50; textBox1.Text = total.ToString(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/75134094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIWebView stuck at the second time I am working on an iOS app that user can pick an email from inbox list, and view it on the next page (there's a UIWebView to serve the content). Here's what I am observing: The first time I pick the email and it shows up on the second page pretty fast. However, if I navigate back and choose to view the email again, it takes a very long time to get webViewDidFinishLoad: called on the second page. I saw the following message in console: void SendDelegateMessage(NSInvocation *): delegate (webView:didFinishLoadForFrame:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode As soon as this message is printed, the content is rendered on WebView. What I don't understand is, this always happen at the second time of using webview to show HTML content. There's no local cache for files/resources, and there's no network issues. Please point me where I should look at for this issue. Thanks! ---- Update ---- During my random attempts, I found removing this line: self.webView.delegate = self; will make the issue gone. This makes me feel even more confusing. Why making self to be the delegate could cause such issue? ---- Update 2 ---- I found the culprit is a flatten html method I called after webview loaded the html. If I remove the NSHTMLTextDocumentType it's all good, but I don't understand why: + (NSString *) stripHtmlSchema: (NSString *)htmlString { NSString *flatString = [[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil] string]; return flatString; } ---- Final Update ---- Figured out the issue. [NSAttributedString alloc] initWithData was taking too long to execute, so blocked everything. A: Figured out the issue. [NSAttributedString alloc] initWithData was taking too long to execute, so blocked everything.
{ "language": "en", "url": "https://stackoverflow.com/questions/29810161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Swing layout issue on migration to java 8 My swing application in java 5 which had a display like After migrating to java 8, zoomed up and displays only a part of it like I saw this and tried setting J2D_D3D as environment variable and also tried passing it as a vm parameter. But didn't solved the issue. Any idea what this could be? A: For reference, here's an example the doesn't have the problem. It uses a GridLayout(0, 1) with congruent gaps and border. Resize the enclosing frame to see the effect. Experiment with Box(BoxLayout.Y_AXIS) as an alternative. I suspect the original code (mis-)uses some combination of setXxxSize() or setBounds(), which will display the effect shown if the chosen Look & Feel has different geometry specified by the buttons' UI delegate. import java.awt.EventQueue; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /** @see https://stackoverflow.com/a/31078625/230513 */ public class Buttons { private void display() { JFrame f = new JFrame("Buttons"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel p = new JPanel(new GridLayout(0, 1, 10, 10)); p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); for (int i = 0; i < 3; i++) { p.add(new JButton("Button " + (i + 1))); } f.add(p); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Buttons()::display); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/31072766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: VBA - Check if recordset has been deleted before updating DB I'm experimenting with VBA and i made the following thingy. Dim rs1 As Recordset Set rs1 = CurrentDb.OpenRecordset("TBL_Registratie") With rs1 .AddNew !leerling_Id = Me.leerling_Id datum = DateValue(!datum_tijd) tijd = TimeValue(!datum_tijd) weekDag = Weekday(datum, vbMonday) Select Case weekDag Case 1, 2, 4 Select Case tijd Case "07:00:00" To "08:00:00" !score = !score + 1 Case "16:00" To "16:30" !score = !score + 1 Case "16:31" To "17:00" !score = !score + 2 Case "17:01" To "22:00" !score = !score + 3 Case Else Me.txt_resultaat.Caption = "Het is geen opvang" Me.txt_resultaat.Visible = True ( rs1.close ? ) End Select other cases .Update .Close QUESTION: How can i check if my last record in there recordset has a score added or not? if not, i want to delete it and close Else Update & Close A: A much easier way: Calculate the score before adding the record, save all needed data in variables instead of recordset fields. Then only if score > 0 do the rs1.AddNew etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/34651388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change back.color of WindowsForm using a picture box on a mouseClick event? I have a simple windows form and I have added a picturebox that I want to act as a dark mode on/off switch for my application. I have created an event for mouse click, but it only works one way: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WeatherApp2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // The below two lines are used to move my WindowsForm window private bool mouseDown; private Point lastlocation; public void picDarkMode_MouseClick(object sender, MouseEventArgs e) { //var frmForm1 = new Form1(); //frmForm1.BackColor = Color.Black; //var darkTheme = this.BackColor = System.Drawing.Color.DarkGray; this.BackColor = System.Drawing.Color.DarkGray; if (System.Drawing.Color.DarkGray == System.Drawing.Color.DarkGray) { this.BackColor = System.Drawing.Color.LightYellow; } else { this.BackColor = System.Drawing.Color.DarkGray; } //this.BackColor = System.Drawing.Color.LightYellow; } I tried to play with if statements, but cannot understand why it is not working... A: You are making two mistakes. You are setting the backcolor to DarkGray before the if statement, so it will always give the same result, and you are comparing DarkGray to DarkGray instead of the forms backcolor to DarkGray. So... Get rid of this line: this.BackColor = System.Drawing.Color.DarkGray; And change this: if (System.Drawing.Color.DarkGray == System.Drawing.Color.DarkGray) To this: if (this.BackColor == System.Drawing.Color.DarkGray) This is the whole click event: public void picDarkMode_MouseClick(object sender, MouseEventArgs e) { if (this.BackColor == System.Drawing.Color.DarkGray) { this.BackColor = System.Drawing.Color.LightYellow; } else { this.BackColor = System.Drawing.Color.DarkGray; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/65011392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simple approach to check and store which states that has changed from initial value This component checks if the fields have been changed from the initial value and display the number of changed fields. There's a useEffect for each field. It would be better with something more DRY, but haven't figured out how. Is there a way to do this faster and better? States const [unsavedChanges, setUnsavedChanges] = useState<Array<string>>([]); const [customField1, setCustomField1] = useState<string | null | undefined>( Data.field1 ); const [customField2, setCustomField2] = useState<string | null | undefined>( Data.field2 ); Set unsavedChanges state //Field 1 useEffect(() => { if ( (customField1 === Data.field1 || customField1 === null) && unsavedChanges?.includes('customfield1') ) { let filtered = unsavedChanges.filter( (item) => item !== 'customfield1' ); setUnsavedChanges(filtered); } else if ( customField1 === Data.field1 || unsavedChanges?.includes('customfield1') ) { return; } else { setUnsavedChanges([...unsavedChanges, 'customfield1']); } }, [customField1]); //Field 2 useEffect(() => { if ( (customField2 === Data.field2 || customField2 === null) && unsavedChanges?.includes('customfield2') ) { let filtered = unsavedChanges.filter( (item) => item !== 'customfield2' ); setUnsavedChanges(filtered); } else if ( customField2 === Data.field2 || unsavedChanges?.includes('customfield2') ) { return; } else { setUnsavedChanges([...unsavedChanges, 'customfield2']); } }, [customField2]); Return <> <Input value={customField1} onChange={setCustomField1(e.target.value}/> <Input value={customField2} onChange={setCustomField2(e.target.value}/> <h1>{unsavedChanges.length} # of unsaved changes.</h1> <Button disabled={unsavedChanges.length > 0 ? false : true} label='Submit'/> </> A: i created an example of how to make it simple (in my opinion). I merged the three states into one. this way i can get each one in more dynamic way. then i created on change handler that handles the changes and doing the all if statements (with less code). each input is firing the change handler on change. and it sets the state according to the if statements. this way we can create as many inputs as we want, we just need to pass the right arguments to the change handler and it will take care of the rest for us (and to make sure to include one more key value pair to the state) this is the dummy data for Data: const Data = { field1: "abc", field2: "efg" }; the state: const [generalState, setGeneralState] = useState({ unsavedChanges: [], customField1: "", customField2: "" }); the handler: const changeTheState = (type, value, field, customField) => { //setting the values to the state. so we can fetch the values for the inputs and for later use setGeneralState((prev) => ({ ...prev, [type]: value })); // i narrowed down the if statements. now its only two. if ( value === Data[field] && generalState.unsavedChanges?.includes(customField) ) { return setGeneralState((prev) => { let filtered = prev.unsavedChanges.filter( (item) => item !== customField ); return { ...prev, unsavedChanges: filtered }; }); } if (!generalState.unsavedChanges?.includes(customField)) { setGeneralState((prev) => ({ ...prev, unsavedChanges: [...prev.unsavedChanges, customField] })); } }; and the jsx: <div className="App"> <input value={generalState.customField1} onChange={(e) => { changeTheState( "customField1", e.target.value, "field1", "customField1" ); }} /> <input value={generalState.customField2} onChange={(e) => { changeTheState( "customField2", e.target.value, "field2", "customField2" ); }} /> <h1>{generalState.unsavedChanges.length} # of unsaved changes.</h1> <button disabled={generalState.unsavedChanges.length > 0 ? false : true}> Submit </button> </div> here is the example : codesandbox example One more thing you can do , is to create a reusable component for the input. create array of objects to represent each input. loop through the array and generate as many inputs you want. if you need extra explaination let me know.
{ "language": "en", "url": "https://stackoverflow.com/questions/72384519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delphi XE2 Rounding with DecimalRounding_JH1 Because of a documented rounding issue in Delphi XE2, we are using a special rounding unit available on the Embarcadero site named DecimalRounding_JH1 to achieve true bankers rounding. A link to the unit can be found here: DecimalRounding_JH1 Using this unit's DecimalRound function with numbers containing a large number of decimal place we This is the rounding routine from the DecimalRounding_JH1 unit. In our example we call this DecimalRound function with the following parameters (166426800, 12, MaxRelErrDbl, drHalfEven) where maxRelErrDbl = 2.2204460493e-16 * 1.234375 * 2 Function DecimalRound(Value: extended; NDFD: integer; MaxRelErr: double; Ctrl: tDecimalRoundingCtrl = drHalfEven): extended; { The DecimalRounding function is for doing the best possible job of rounding floating binary point numbers to the specified (NDFD) number of decimal fraction digits. MaxRelErr is the maximum relative error that will allowed when determining when to apply the rounding rule. } var i64, j64: Int64; k: integer; m, ScaledVal, ScaledErr: extended; begin If IsNaN(Value) or (Ctrl = drNone) then begin Result := Value; EXIT end; Assert(MaxRelErr > 0, 'MaxRelErr param in call to DecimalRound() must be greater than zero.'); { Compute 10^NDFD and scale the Value and MaxError: } m := 1; For k := 1 to abs(NDFD) do m := m*10; If NDFD >= 0 then begin ScaledVal := Value * m; ScaledErr := abs(MaxRelErr*Value) * m; end else begin ScaledVal := Value / m; ScaledErr := abs(MaxRelErr*Value) / m; end; { Do the diferent basic types separately: } Case Ctrl of drHalfEven: begin **i64 := round((ScaledVal - ScaledErr));** The last line is where we get a floating point error. Any thoughts on why this error is occurring? A: If you get an exception, that means you cannot represent your value as an double within specified error range. In other words, the maxRelErrDbl is too small. Try with maxRelErrDbl = 0,0000000001 or something to test if I am right.
{ "language": "en", "url": "https://stackoverflow.com/questions/17490266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add timestamp to sdterr? I've a application launched by bash script. I redirected stderr and stdout to different files: ./app >> /home/user/logs/debug.log 2>>/home/user/logs/debug.err & And I need to add a timestamp for stderr lines. How I can do it? A: check this out ./app >> /home/user/logs/debug.log 2> >( while read line; do echo "$(date): ${line}"; done > /home/user/logs/debug.err )
{ "language": "en", "url": "https://stackoverflow.com/questions/63950849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AJAX: download new content every X seconds using jQuery I have page with posts. Initially posts was added by server-side code. I need every 60 seconds download and show new posts from server. Server can return 0 to N posts. Page returned by server have this format for two posts (most recent on top): <div class='post' data-id='456'>...</div> <div class='post' data-id='123'>...</div> There is my code: <html> <head> <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script> var lastPostID; $(document).ready(function(){ var j = jQuery.noConflict(); j(document).ready(function() { setInterval(function(i) { lastPostID = j(".post div:last").data("id"); console.log(lastPostID, "lastPostID"); j.ajax({ url: "/post/"+lastPostID, cache: false, success: function(html){ j("#temp").html(html); j('#temp').prependTo("#posts"); j("#temp").empty(); } }) }, 10000) }); }); </script> </head> <body> <div id="temp" style="display: none;"></div> <div id="posts"> <div class='post' data-id='100'>...</div> <div class='post' data-id='20'>...</div> <div class='post' data-id='1'>...</div> </div> </body> </html> Can you please recommend me any good jQuery timer plugin? I see at JS console every 10s: null "lastPostID" Where I have an error? Update: If I use: <script> var divs = document.getElementsByClassName('post'); console.log(divs.length, "divs with class *post*"); for(var i=0; i<divs.length; i++) { var id = divs[i].getAttribute('data-id'); console.log(id, "lastPostID"); } </script> Output is OK: 3 "divs with class *post*" jQuery_div_update.html:37 100 lastPostID jQuery_div_update.html:40 20 lastPostID jQuery_div_update.html:40 1 lastPostID But with jQuery: <script> $(document).ready(function(){ var lastPostID = $(".post div:last").data("id"); console.log(lastPostID, "lastPostID"); }); </script> Output is bad: null "lastPostID" Why? A: If you want to poll some external resource (with an AJAX call, for example) you can follow the "Recursive setTimeout pattern" (from https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval). Example: (function loop(){ setTimeout(function(){ // logic here // recurse loop(); }, 1000); })(); A: use setInterval() instead of setTimeout() something like: setInterval(function(){ $.ajax({ url: "test.html", context: document.body }).done(function() { //do something }); },1000*60); http://www.w3schools.com/jsref/met_win_setinterval.asp https://api.jquery.com/jQuery.ajax/
{ "language": "en", "url": "https://stackoverflow.com/questions/21740635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: perf get time elasped with field separator option I have a program which parses the output of the linux command perf. It requires the use of option -x, (the field separator option. I want to extract elapsed time (not task-time or cpu-clock) using perf. However when I use the -x option, the elapsed time is not present in the output and I cannot find a corresponding perf event. Here are the sample outputs perf stat ls ============ Performance counter stats for 'ls': 0.934889 task-clock (msec) # 0.740 CPUs utilized 6 context-switches # 0.006 M/sec 0 cpu-migrations # 0.000 K/sec 261 page-faults # 0.279 M/sec 1,937,910 cycles # 2.073 GHz <not supported> stalled-cycles-frontend <not supported> stalled-cycles-backend 1,616,944 instructions # 0.83 insns per cycle 317,016 branches # 339.095 M/sec 12,439 branch-misses # 3.92% of all branches 0.001262625 seconds time elapsed //here we have it Now with field separator option perf stat -x, ls ================ 2.359807,task-clock 6,context-switches 0,cpu-migrations 261,page-faults 1863028,cycles <not supported>,stalled-cycles-frontend <not supported>,stalled-cycles-backend 1670644,instructions 325047,branches 12251,branch-misses Any help is appreciated A: # perf stat ls 2>&1 >/dev/null | tail -n 2 | sed 's/ \+//' | sed 's/ /,/' 0.002272536,seconds time elapsed A: Starting with kernel 5.2-rc1, a new event called duration_time is exposed by perf statto solve exactly this problem. The value of this event is exactly equal to the time elapsed value, but the unit is nanoseconds instead of seconds.
{ "language": "en", "url": "https://stackoverflow.com/questions/27257974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: passing bash a value with leading hyphen I have a bash command that requires a string value after "-v". When this string value has a leading "-", bash tries to interpret it as a new option of the bash command rather than the value I'm trying to give for -v. Is there a way I can escape this leading hyphen? I tried -v -- -myValue but then it tells me "option '-v' needs a parameter." The command is calling a ruby file. I think this is the meaningful part of the ruby code for the purposes of this question: opts = Trollop::options do opt :method, "Encrypt or Decrypt", :short => "m", :type => :string, :default => "decrypt" opt :value, "Value to Decrypt or Encrypt", :short => "v", :type => :string, :default => "" end A: There's two conventional ways to specify arguments, but these are not enforced at the shell level, they're just tradition: -v xxxx --value=xxxx Now it's sometimes possible to do: -vxxxx If you have a value with a dash and it's not being interpreted correctly, do this: --value=-value A: cmd -v '-string value with leading dash' edit $ cat ~/tmp/test.sh #!/bin/bash str= while getopts "v:" opt; do case "$opt" in v) str=$OPTARG;; esac done shift $(( OPTIND -1 )) echo "option was '$str'" simple test file, my bash is GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu) results: chris@druidstudio:~⟫ ~/tmp/test.sh -v string option was 'string' chris@druidstudio:~⟫ ~/tmp/test.sh -v -string option was '-string' chris@druidstudio:~⟫ ~/tmp/test.sh -v '-string' option was '-string' so, maybe, the bash script handling your options is not written correctly, or you have an early version of bash. As I answered in another of these silly questions earlier, clairvoyance is not one of my skills. So, be a good chap and possibly give us, the people you are asking for help from, the pertinent information (as you state, your script is failing at the bash level, not at the ruby level, so why bother to post a ruby script?)
{ "language": "en", "url": "https://stackoverflow.com/questions/37752454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to find if specific changeset within the parents in mercurial I am a git background and just moved to a project where is uses mercurial, the projects is branched with heads model. Before pushing things to our testing server, I want to make sure that production head is one of my parents list. is there is a command for that? A: actually I found a way to do so using "revsets" of mercurial. in order to list all ancestors for specific changeset, we can use the command hg log -r "ancestors(84e5bc6fd673)" now in order to find specific changeset in these parents, we can use the matching function like below hg log -r "ancestors(84e5bc6fd673) and id(hh6cjb9c48se)" so if hh6cjb9c48se is part of 84e5bc6fd673 parents it will be printed to the terminal.
{ "language": "en", "url": "https://stackoverflow.com/questions/39891337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cannot build OpenCL program on Windows I have written a simple "do-nothing" OpenCL application (in C++ but using the C API) on Linux to get some data about OpenCL speed. It compiles fine and runs without error. I don't have a graphics card that supports OpenCL, but I need to test it on a GPU. I'm trying to build the application on my friend's Windows 7 64bit computer using the OpenCL implementation provided with NVIDIA'S CUDA Toolkit. When I try to link to the OpenCL.lib file in CUDA\x64 I get undefined references for each OpenCL call within the program (using the standard C API). The same thing happens when I link to the OpenCL.dll in the system32 directory. If I link to the win32 library that came with the CUDA Toolkit, I don't get errors, but OpenCL cannot acquire a platform. All the undefined references I get when linking have an @20 or @46 or some random number on the end of the symbol name. I'm not familiar enough with Windows development to know how to fix this problem. What could be my problem? I apoligize for any newbie-ness. Thanks for any answers! A: I believe you'll want to use the library that doesn't give link errors. The other errors you're getting are because you're linking mismatched code together. Then focus on trying to determine what your platform identifier should be. I think you were close but gave up too soon
{ "language": "en", "url": "https://stackoverflow.com/questions/5018730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular 2 error: Playing around with Angular 2 and trying to get this simple code working. yet I keep getting an error of: EXCEPTION: Cannot resolve all parameters for Tab(undefined). Make sure they all have valid type or annotations. As far ng2 is not injecting in constructor(tabs:Tabs) {… into the constructor Here is the entire code: ///<reference path="../../typings/zone.js/zone.js.d.ts"/> import {Component, Input} from 'angular2/core'; @Component({ selector: 'tab', template: ` <ul> <li *ngFor="#tab of tabs" (click)="selectTab(tab)"> {{tab.tabTitle}} </li> </ul> <ng-content></ng-content> `, }) export class Tab { @Input() tabTitle: string; public active:boolean; constructor(tabs:Tabs) { this.active = false; tabs.addTab(this); } } @Component({ selector: 'tabs', directives: [Tab], template: ` <tab tabTitle="Tab 1"> Here's some content. </tab> `, }) export class Tabs { tabs: Tab[] = []; selectTab(tab: Tab) { this.tabs.forEach((myTab) => { myTab.active = false; }); tab.active = true; } addTab(tab: Tab) { if (this.tabs.length === 0) { tab.active = true; } this.tabs.push(tab); } } tx Sean A: That's because your Tabs class is defined after your Tab class and classes in javascript aren't hoisted. So you have to use forwardRef to reference a not yet defined class. export class Tab { @Input() tabTitle: string; public active:boolean; constructor(@Inject(forwardRef(() => Tabs)) tabs:Tabs) { this.active = false; tabs.addTab(this); } } A: You have two solutions: Inject your Tabs class globally at bootstrap: bootstrap(MainCmp, [ROUTER_PROVIDERS, Tabs]); On inject Tabs locally with a binding property, @Component({ selector: 'tab', bindings: [Tabs], // injected here template: ` <ul> <li *ngFor="#tab of tabs" (click)="selectTab(tab)"> [...]
{ "language": "en", "url": "https://stackoverflow.com/questions/34306041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hide formulas in excel without protecting the sheet I need to hid the formulas in my sheet without protecting the sheet,say i have sheet 1 in that i need to hide the formulas from range(A1:G10) i can hide the formula but iam not able to provide input for the whole sheet My requirement is to hide the selected cells formulas and able to give inputs for other cells in the same sheet how can i achieve this. A: Select the whole sheet, right click and then select Format Cells.... In the popup window, select Protection tab. Unselect both options and press OK button. This will unlock all cells on the sheet as by default all cells are locked. Next, select your range, repeat the above process again but this time ensure that both options (Locked and Hidden) are selected this time and press OK. Now protect your sheet (in Excel 2013, select the REVIEW tab and select Protect Sheet option and follow the steps). This will hide your formulas and stop anyone changing the values in the protected cells
{ "language": "en", "url": "https://stackoverflow.com/questions/45435672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Have border-bottom after grid-row css3 I have a grid container whose css is .optionsInnerContainer { display: grid; // grid-template-columns: 1fr 1fr 1fr; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); /* see notes below */ // grid-auto-rows: minmax(100px, auto); -webkit-column-gap: 10px; column-gap: 10px; row-gap: 2em; padding: 10px; } I want to add a border-bottom below every row of grid. I dont know how to do that. Please help.
{ "language": "en", "url": "https://stackoverflow.com/questions/51231838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are there some methods in golang manipulate function like std::bind in C++? Here is my design: type Handler func(c *gin.Context) func PreExecute(c *gin.Context, handle_func Handler) Handler { if c.User.IsAuthorized { return handle_func } else { return some_error_handle_func } } and I want to decorate every handler by PreExecute just like the decoration in Python. So I am looking for some std::bind functions in golang to get PreExecute a exactly same signature as Handler What I expect: handler = std::bind(PreExecute, _1, handler) // where _1 hold the position for parameter `c *gin.Context` some function like std::bind How can I do that in Golang? Are there some more elegant methods to get this work? A: Closure, here is my solution: handler_new = func(c *gin.Context){ return PreExecute(c, handler_old)(c) } // since there is no return value of handler, so just do not use `return` statements, I will not correct this error and then handler_new can be used as: handler_new(some_context) It's the same as handler_new = std::bind(PreExecute, _1, handler_old) in C++
{ "language": "en", "url": "https://stackoverflow.com/questions/43729511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why to use new to initialize something in JAVA? Why do we use this syntax in JAVA FreshJuice juice = new FreshJuice(); instead of just FreshJuice juice; A: For many reasons, including: * *There is no guarantee that FreshJuice will be a concrete class; it can be an interface or an abstract class instead. *You might not have a default constructor available. *You might not have any constructor available at all. A: Because you need to create an object before initializing it. When you call new FreshJuice(); it firsts allocates memory for the object on heap, and then initializes it.(with default values in this case as provided in corresponding default constructor)
{ "language": "en", "url": "https://stackoverflow.com/questions/49107635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-6" }
Q: How to make `format` function in python 2 to work with `unicode` type objects with UTF-8 encoding? I have huge code base with lots of format functions. I want to pass unicode type objects as arguments like: # -*- coding: UTF-8 -*- x = u"ñö" print isinstance(x,unicode)#prints "True" y = "Hello {0}".format(x)# "UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)" print y A: This did the trick for me without changing every line where format is used: from __future__ import unicode_literals Basically I had problems whenever "string {}" in "string {}".format("hello") was str object. Writing a simple u"string {}" would have helped, but huge code base remember? "hello" doesn't really matter. A: # -*- coding: UTF-8 -*- x = r"ñö" print isinstance(x,unicode)#prints "True" y = "Hello {0}".format(x)# "UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)" print y
{ "language": "en", "url": "https://stackoverflow.com/questions/57320865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Avoiding array assignment in autograd I understand from the autograd tutorial that array assignment is not supported when the array is contained in the objective to be differentiated. However, I currently have the following objective function in my code which I would like to differentiate with respect to theta: def obj(theta): """ Computes the objective function to be differentiated. Args: theta: np.array of shape (n, d) Return: res: np.array of shape (n,) """ theta = np.atleast_2d(theta) n = theta.shape[0] res = np.zeros(n) # Scores for i in xrange(n): res[i] = ... # Do some computations with theta[i, :] return res Typically I can avoid the for loop by vectorizing the computation over theta; however, in this case the computation already involves various linear algebra operations (inverses, etc.) given a specific row of theta (as hyperparameters), and I found it quite difficult to vectorize the operation over all rows of theta. In this case, I don't know of a better way than filling the res array row by row with a for-loop. I have tried a naive way to avoid array assignments by creating a list and at each iteration append the results to that list, then finally convert the list to the array upon returning res, but I get all-zero gradients in the end... I wonder what is the general recommend solution in this setup? A: You can use numpy.apply_along_axis to apply a function for certain axis in your data. def func(row): # return the computation result for "row" def obj(theta): """ Computes the objective function to be differentiated. Args: theta: np.array of shape (n, d) Return: res: np.array of shape (n,) """ theta = np.atleast_2d(theta) n = theta.shape[0] res = np.apply_along_axis(func1d=func, axis=1, arr=a) return res
{ "language": "en", "url": "https://stackoverflow.com/questions/50067267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: comparison of randomized algorithms Sometimes randomized algorithms return quite good results and they are often much faster than a deterministic alternatives. But how can I compare two randomized algorithms (or at least their implementations) ? The results will differ after each call and the output will highly depend on a (pseudo)-coincidence. I have to compare some clustering algorithms and the majority of solutions is randomized. * *is it smart to compare the distribution of the output? (This will highly depend on input and the coincidence.) *it is also quit hard to estimate the duration because some algorithms work until a threshold is reached (= depends highly on input).
{ "language": "en", "url": "https://stackoverflow.com/questions/20770810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Joining python threads, sum totals My issue is I'm trying to loop over an array with a number of threads, each thread then adds the value into the global array. But for some reason the array is coming out as planned, I have noticed you need to use the join() thread function but am a little confused on how to implement it here totalPoints = [] def workThread(i): global totalPoints totalPoints += i threads = [] for i in range(NUMBER_OF_THREADS): t = threading.Thread(target=workThread, args=(i,)) t.start() threads.append(t) Any help would be appreciated. Thanks! A: You just write a second loop to join the threads totalPoints = [] def workThread(i): global totalPoints totalPoints += i threads = [] for i in range(NUMBER_OF_THREADS): t = threading.Thread(target=workThread, args=(i,)) t.start() threads.append(t) for t in threads: t.join() Your code will fail at totalPoints += i because totalPoints is a list. You don't handle exceptions in your threads so you may fail silently and not know what happened. Also, you need to be careful how you access a shared resource such as totalPoints to be thread safe. A: does this help: ? #!/usr/bin/env python # -*- coding: utf-8 -*- import threading import time import random NUMBER_OF_THREADS=20 totalPoints = [] def workThread(i): global totalPoints time.sleep(random.randint(0, 5)) totalPoints.append((i, random.randint(0, 255))) threads = [] for i in range(NUMBER_OF_THREADS): t = threading.Thread(target=workThread, args=(i,)) t.start() threads.append(t) for t in threads: t.join() print totalPoints It always prints something like this: [(1, 126), (10, 169), (11, 154), (0, 214), (9, 243), (12, 13), (15, 152), (6, 24), (17, 238), (13, 28), (19, 78), (16, 130), (2, 110), (3, 186), (8, 55), (14, 70), (5, 35), (4, 39), (7, 11), (18, 14)] or this [(2, 132), (3, 53), (4, 15), (6, 84), (8, 223), (12, 39), (14, 220), (0, 128), (9, 244), (13, 80), (19, 99), (7, 184), (11, 232), (17, 191), (18, 207), (1, 177), (5, 186), (16, 63), (15, 179), (10, 143)]
{ "language": "en", "url": "https://stackoverflow.com/questions/35781185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to read pcapng (wireshark) files in Python? I have a capture of some TCP packets in pcapng format and I'd like to open it in python to inspect the TCP payloads with address 192.168.1.198. I've only found this library: https://python-pcapng.readthedocs.io/en/latest/api/blocks.html but it does not support inspecting TCP payloads. Is there an easy way? A: You can use python-pcapng package. First install python-pcapng package by following command. pip install python-pcapng Then use following sample code. from pcapng import FileScanner with open(r'C:\Users\zahangir\Downloads\MDS19 Wireshark Log 08072021.pcapng', 'rb') as fp: scanner = FileScanner(fp) for block in scanner: print(block) print(block._raw) #byte type raw data Above code worked for me. Reference: https://pypi.org/project/python-pcapng/
{ "language": "en", "url": "https://stackoverflow.com/questions/63441797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Azure Logic Apps ACI Connector - BackOff state I am using the ACI connector in logic apps, and using a customized version of nginx docker image that keeps failing with "CrashLoopBackOff" error. The customization I've made is just these two: apt update apt install ssh and built a new image out of that. While using the base nginx image (from docker hub - library/nginx) works like a charm, the custom version with SSH installed, always gets into the loop with CrashLoopBackOff error. I'm not a Linux/Ubuntu guy, any idea what could be the issue? I have in fact tried this many times and also used the Ubuntu base image to do the same customisation (install SSH), but the result is the same Background: I am using ACI to run a simple shell script on creation. This probably doesn't have anything to do with the error since it works ok with the base nginx image. A: To install the SSH in the image, you need to more than you have done. Here is the example: FROM ubuntu:16.04 RUN apt-get update && apt-get install -y openssh-server RUN mkdir /var/run/sshd RUN echo 'root:THEPASSWORDYOUCREATED' | chpasswd RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config # SSH login fix. Otherwise user is kicked off after login RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd ENV NOTVISIBLE "in users profile" RUN echo "export VISIBLE=now" >> /etc/profile EXPOSE 22 CMD ["/usr/sbin/sshd", "-D"] When you have built the image, I suggest you push it into the ACR. Then you can use it in the Logic App and it will work fine. For more details, see Dockerize an SSH service.
{ "language": "en", "url": "https://stackoverflow.com/questions/58609375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OleDbCommand, two sequential "using" With two sequential "using", will both connections be disposed when exiting from {}? using(OleDbConnection con = new OleDbConnection(conString)) using(OleDbCommand command = con.CreateCommand()) { } A: There's only one connection there - and a command using the same connection. Both will be disposed. This is effectively: using(OleDbConnection con = new OleDbConnection(conString)) { using(OleDbCommand command = con.CreateCommand()) { } // command will be disposed here } // con will be disposed here
{ "language": "en", "url": "https://stackoverflow.com/questions/27459823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP remove duplicate values from a multidimensional array How to remove duplicate values from a multidimensional array. For example, I have an array: Array ( [0] => Array ( [fruit_id] => cea2fc4b4058 [title] => Apple title one [name] => Apple [weight] => 22 ) [1] => Array ( [fruit_id] => sdfsdec4b4058 [title] => Grapefruit title one [name] => Grapefruit [weight] => 19 ) [2] => Array ( [fruit_id] => hjkvcbc4b4058 [title] => Grapefruit title two [name] => Grapefruit [weight] => 17 ) [3] => Array ( [fruit_id] => tyuutcgbfg058 [title] => Lemon title one [name] => Lemon [weight] => 15 ) [4] => Array ( [fruit_id] => lkjyurtws4058 [title] => Mango title [name] => Mango [weight] => 13 ) [5] => Array ( [fruit_id] => bner3223df058 [title] => Lemon title two [name] => Lemon [weight] => 11 ) ) In this array, I need to leave only one fruit with the maximum weight. I want to save all the data, but at the same time remove duplicate fruits. Thank. A: You can sort by weight ascending and then create a result using the name as the key so the ones with larger weight will overwrite the smaller weight ones: array_multisort(array_column($array, 'weight'), SORT_ASC, $array); foreach($array as $v) { $result[$v['name']] = $v; } Then if you want to re-index (not required): $result = array_values($result); A: Try to use array_unique($array); code
{ "language": "en", "url": "https://stackoverflow.com/questions/54448472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Frame 1:26 - What does q unify with? We have: (run* q (fresh (x) (== `(,x) q))) In this case `(,x) is a list where the refrence to the variable x isn't quoted. Does q unifies with a single element list? Is the result (_0) because q unifies with the fresh variable x (even if it's in a list) or because it doesn't unify with anything at all? Or would in that case the result have been ()? A: Does q unify with a single element list? Yes. (== (list x) q) is the same as (== q (list x)). Both q and x are fresh before the execution of this unification goal (and q does not occur in (list x)). Afterwards, it is recorded in the substitution that the value of q is (list x). No value for x is recorded. Is the result (_0) because q unifies with the fresh variable x (even if it's in a list) or because it doesn't unify with anything at all? Or would in that case the result have been ()? No, q does not unify with x, but rather with a list containing x. When the final value of the whole run* expression is returned, the variables are "reified", replaced with their values. x has no value to be replaced with, so it is printed as _0, inside a list as it happens, which list is the value associated with q. The value of (run* q ...) is a list of all valid assignments to q, as usual. There is only one such association, for the variable q and the value (list x). So ( (_0) ) should be printed as the value of the (run* q ...) expression -- a list of one value for q, which is a list containing an uninstantiated x, represented as a value _0.
{ "language": "en", "url": "https://stackoverflow.com/questions/73652268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery slider not adding active slide class I'm having an issue with a slider I've put together (with navigation to each slide). The issue being that the .active-slide class is not being added correctly to the next slide. I've had this working in CodePen - http://codepen.io/davelivesey/pen/mEBkAa - but as soon as I transplant that into my project it breaks, the main issue being the .active-slide class is no longer added to the next slide. I've added a $(document).ready( ... around it, but this doesn't fix it. There are no conflicts with any other code I've written and both the CodePen and the project use the same version of jQuery (2.2.4). Here's the code that's not working in the project. I've removed some of the CSS for the sake of brevity! HTML <div id="slider"> <div class="slide">I'm slide one.</div> <div class="slide">I'm slide two.</div> <div class="slide">I'm slide three.</div> </div> CSS(SASS) #slider { width: 100%; height: 600px; position: relative; background-color: rgb(240,240,240); .slide { width: 100%; height: 600px; position: absolute; top: 0; display: none; } } .slide.active-slide { display: block; } #slider-nav ul { list-style: none; text-align: center; li { display: inline-block; margin-right: 5px; a span { display: inline-block; width: 10px; height: 10px; border-radius: 10px; border: 1px solid rgb(130,130,130); } } li.active a span { background-color: rgb(180,180,180); } } jQuery: $(document).ready( function() { var $slides = $('#slider .slide'), $navWrap = $('#slider-nav ul'); function nextSlide() { var $next = $('#slider-nav ul li.active').next(); if ($next.length === 0){ $next = $('#slider-nav ul li:first-of-type'); } $next.click(); } function slideTransition(index) { $('#slider .slide.active-slide').delay(6000).fadeOut(500, function() { $(this).removeClass('active-slide'); }); $('#slider .slide:eq(' + index + ')').fadeIn(500, function() { $(this).addClass('active-slide'); }); } $slides.each( function(index) { $navWrap.append('<li><a href="#link'+index+'"><span></span></a></li>'); }); var timer = setInterval(nextSlide, 6000); $('#slider .slide:first').addClass('active-slide').fadeIn(200); $('#slider-nav ul li').click(function() { clearInterval(timer); $(this).siblings('.active').removeClass('active'); $(this).addClass('active'); var index = $(this).index('li'); slideTransition(index); timer = setInterval(nextSlide, 6000); return false; }); $('#slider-nav ul li:first-of-type').click(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/38346562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Conditionally add class to image by jquery This JS replace image file name default.jpg to hqdefault.jpg from all images below. But now I'm trying to add class to Image, if Image src has img.youtube.com link on images by extending this JS. JS: $('#selector img').attr('src',function(i,e){ return $(this).attr('src').replace("default.jpg","hqdefault.jpg"); }); HTML: <div id="selector"> <img src="http://img.youtube.com/vi/qDc_5zpBj7s/default.jpg"> <img src="http://img.youtube.com/vi/ss7EJ-PW2Uk/default.jpg"> <img src="http://img.youtube.com/vi/ktd4_rCHTNI/default.jpg"> <img src="http://img.youtube.com/vi/0GTXMEPDpps/default.jpg"> </div> Means, If image src has Youtube image then add a class .video to parent image. A: Try: $('#selector img').each(function(i) { var self = $(this); var src = self.attr('src'); if (src.match(/img.youtube.com/)) { self.attr('src', src.replace("/default.jpg","/hqdefault.jpg")); self.addClass('video'); } }); A: You can add a condition before replacing and add video class. $('#selector img').attr('src',function(i,e){ if($(this).attr('src').search('img.youtube.com') > 0){ $(this).addClass('video'); } return $(this).attr('src').replace("default.jpg","hqdefault.jpg"); });
{ "language": "en", "url": "https://stackoverflow.com/questions/33972068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: BIML: Issues about Datatype-Handling on ODBC-Source Columns with varchar > 255 I'm just getting into BIML and have written some Scripts to creat a few DTSX-Packages. In general the most things are working. But one thing makes me crazy. I have an ODBC-Source (PostgreSQL). From there I'm getting data out of a table using an ODBC-Source. The table has a text-Column (Name of the column is "description"). I cast this column to varchar(4000) in the query in the ODBC-Source (I know that there will be truncation, but it's ok). If I do this manually in Visual Studio the Advanced Editor of the ODBC-Source is showing "Unicode string [DT_WSTR]" with a Length of 4000 both for the External and the Output-Column. So there everything is fine. But if I do the same things with BIML and generate the SSIS-Package the External-Column will still say "Unicode string [DT_WSTR]" with a Length of 4000, but the Output-Column is telling "Unicode text stream [DT_NTEXT]". So the mapping done by BIML differs from the Mapping done by SSIS (manually). This is causing two things (warnings): * *A Warning that metadata has changed and should be synced *And a Warning that the Source uses LOB-Columns and is set to Row by Row-Fetch.. Both warnings are not cool. But the second one also causes a drasticaly degredation in Performance! If I set the cast to varchar(255) the Mapping is fine (External- and Output-Column is then "Unicode string [DT_WSTR]" with a Length of 255). But as soon as I go higher, like varchar(256) it's again treated as [DT_NTEXT] in the Output. Is there anything I can do about this? I invested days in the Evaluation of BIML and find many things an increase in Quality of Life, but this issue is killing it. It defeats the purpose of BIML if I have to correct the Errors of BIML manually after every Build. Does anyone know how I can solve this Issue? A correct automatic Mapping between External- and Output-Columns would be great, but at least the option to define the Mapping myself would be ok. Any Help is appreciated! Greetings Marco Edit As requested a Minimal Example for better understanding: * *The column in the ODBC Source (Postegres) has the type "text" (Columnname: description) *I select it in a ODBC-Source with this Query (DirectInput): SELECT description::varchar(4000) from mySourceTable *The ODBC-Source in Biml looks like this: <OdbcSource Name="mySource" Connection="mySourceConnection"> <DirectInput>SELECT description::varchar(4000) from mySourceTable</DirectInput></OdbcSource> *If I now generate the dtsx-Package the ODBC-Source throws the above mentioned warnings with the above mentioned Datatypes for External and Output-Column A: As mentioned in the comment before I got an answer from another direction: You have to use DataflowOverrides in the ODBC-Source in BIML. For my example you have to do something like this: `<OdbcSource Name="mySource" Connection="mySourceConnection"> <DirectInput>SELECT description::varchar(4000) from mySourceTable</DirectInput> <DataflowOverrides> <OutputPath OutputPathName="Output"> <Columns> <Column ColumnName="description" SsisDataTypeOverride="DT_WSTR" DataType="String" Length="4000" /> </Columns> </OutputPath> <OutputPath OutputPathName="Error"> <Columns> <Column ColumnName="description" SsisDataTypeOverride="DT_WSTR" DataType="String" Length="4000" /> </Columns> </OutputPath> </DataflowOverrides> </OdbcSource>` You won't have to do the Overrides for all columns, only for the ones you have mapping-Issues with. Hope this solution can help anyone who passes by. Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/71162537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can we create a link with dynamic ID in SPA model I am developing a single page application using ReactJS. My whole application is running in Single Page. Now, I need one page that accept the used ID from the URL and show the result based on the user ID. Is this possible in SPA model or I have to move the my website to MPA model? I tried some answers and am not clear about it for ex: https://stackoverflow.com/questions/id/101 I have to get the ID 101 and show the result based on the id in the page. A: yes sure this is possible. Let me give you some background over this. If you are building SPA with multiple pages, you would like to use a client-side routing in otder to display differen page based on the browser url. As I know defacto solution for routing in react is react-router but there are many other to chose from. See this link. Unfortunately, I won't be able to completely explain how to use react-router solution, but here is a brief example. Inside your main component (like App.jsx) add routing: // 1. do proper imports import { BrowserRouter } from "react-router-dom"; // 2. wrap your application inside of BrowserRouter component class App extends React.Component { // your code render() { return ( <BrowserRouter> {/* your app code */} {/* Add routing */} <Route path="/" exact component={Dashboard} /> <Route path="/questions/id/:id" component={Question} /> {/* your app code */} <BrowserRouter> ) } } You should see now that when your browser url matches /questions/id/:id component Question should be mounted to the page. Inside this component, you can fetch id that was passed in. It will be inside this.props.match.param.id property class Question extends React.Component { // your code render() { const id = this.props.match.param.id; return ( <div> Page with { id } was opened <div> ) } } Sure you would like to familiarise yourself with react-router docs. A: ReactJs don't include a router. But the most popular package to do this is React-router. The official documentation references other good packages
{ "language": "en", "url": "https://stackoverflow.com/questions/54309087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to retrieve current server FQDN in a java class I need to compose a dynamic URL based on current host running the web application. I have a backgrund process launched on startup via ServletContextListener. This thread has to send emails to customers with a registration ticket. In the email text I need to print the complete URL to my webapp and the servlet. Lets say those emails like "click here to confirm your subscription or copy&paste blabla...." How my I obtain the FQDN of my running webapp? It's not a servlet so I cannot relay on a HttpServletRequest instance and the server has many virtual hosts. Here is where I launch the thread: public class Initializer implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent arg0) { Log.addItem("SYSTEM START"); PasswordRecoveryListener pwlisten = new PasswordRecoveryListener(1000 * 60 * 1); pwlisten.start(); } } In arg0.getServletContext().getContextPath() I found nothing but the path. I looked for the hostname in the Context (where I have other constants) but without success.
{ "language": "en", "url": "https://stackoverflow.com/questions/21465180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: prototype function error : is not a function I tried to encapsulate a javascript object and declared some prototype function. But there were some errors. Here is my code: const editor_theme = require('./editor-theme.js') let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}') defaultTheme.setTitlebarColor('888888') console.log(defaultTheme.getTitlebarColor()) //main.js module.exports = { Editor_Theme: function (data) { var _themeData = JSON.parse(data) var _titlebar_color = _themeData.titlebar_color var _background_color = _themeData.background_color const Func = function() { } Func.prototype = { getTitlebarColor : function () { return _titlebar_color }, getBackgroundColor : function () { return _background_color }, setTitlebarColor : function (titlebarColor) { _titlebar_color = titlebarColor || _titlebar_color } } Object.freeze(Func) Object.freeze(Func.prototype) return Func } } //editor-theme.js The error log is it: Uncaught TypeError: defaultTheme.setTitlebarColor is not a function A: Your constructor now returns another constructor function, not an object. Return an instance of that constructor instead: // module.exports = { let moduleExports = { Editor_Theme: function(data) { var _themeData = JSON.parse(data) var _titlebar_color = _themeData.titlebar_color var _background_color = _themeData.background_color const Func = function() {} Func.prototype = { getTitlebarColor: function() { return _titlebar_color }, getBackgroundColor: function() { return _background_color }, setTitlebarColor: function(titlebarColor) { _titlebar_color = titlebarColor || _titlebar_color } } Object.freeze(Func) Object.freeze(Func.prototype) return new Func() //Instantiate constructor } } // const editor_theme = require('./editor-theme.js') const editor_theme = moduleExports let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}') defaultTheme.setTitlebarColor('888888') console.log(defaultTheme.getTitlebarColor()) Or even better, just Object.create an object with a custom prototype: // module.exports = { let moduleExports = { Editor_Theme: function(data) { var _themeData = JSON.parse(data) var _titlebar_color = _themeData.titlebar_color var _background_color = _themeData.background_color const prototype = { getTitlebarColor: function() { return _titlebar_color }, getBackgroundColor: function() { return _background_color }, setTitlebarColor: function(titlebarColor) { _titlebar_color = titlebarColor || _titlebar_color } } Object.freeze(prototype) return Object.create(prototype) //Object with custom prototype } } // const editor_theme = require('./editor-theme.js') const editor_theme = moduleExports let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}') defaultTheme.setTitlebarColor('888888') console.log(defaultTheme.getTitlebarColor())
{ "language": "en", "url": "https://stackoverflow.com/questions/58256499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Emacs does not react when I press C-. (dot/period) I am learning Agda and when I type C-cC-. there is no reaction in my Emacs. I can type either C-c. or C-cM-. and then I will be told that these bindings are not defined. But when I try to type C-cC-. the mini-buffer only shows C-c and it seems that Emacs is waiting for the next key binding. So how should I fix this problem? I am using a MacOS. Any help will be appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/56521532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ZOOM-IN & ZOOM-OUT 2D graphics C# i have to ZOOM-IN & ZOOM-OUT specific portion of 2D-graphics like (line, Rectangle, circle) which i have drawn on winform. I am not used any picture box, panel. I crated simple program to draw circle & on button click try to zoom but it showing error "parameter is not valid" in method Drawing() @ Line- DeviceContexct.Transform = mainViewTransform; public Graphics DeviceContexct; public Matrix mainViewTransform = new Matrix(); private void ScalingCircle_Paint( object sender, PaintEventArgs e ) { Pen myPen = new Pen(Color.Blue, 1); e.Graphics.DrawRectangle(myPen, 50, 50, 100, 100); mainViewTransform.Scale(3, 2); DeviceContexct = e.Graphics; } private void Drawing(Graphics gr) { Pen myPen2 = new Pen(Color.Red, 1); DeviceContexct.Transform = mainViewTransform; DeviceContexct.DrawRectangle(myPen2, 50, 50, 100, 100); } private void button1_Click( object sender, EventArgs e ) { Drawing(DeviceContexct); } A: I prefer to draw into Bitmaps with System.Drawing.Graphics object. Then you can use your graphics object with "go.DrawImage(...)" to draw the bitmap directly into your winforms and actually give it a scale. https://msdn.microsoft.com/en-us//library/ms142040(v=vs.110).aspx A: I got the solution, thanks for your help. I only need to call refresh/invalidate etc on button click. public partial class ScalingCircle : Form { public Graphics DeviceContexct; // current transformation matrix of main view (offset & scaling) public Matrix mainViewTransform = new Matrix(); public int scale = 1; public ScalingCircle() { InitializeComponent(); DeviceContexct = Graphics.FromHwnd(this.Handle); DeviceContexct = this.CreateGraphics(); } public void ScalingCircle_Paint(object sender, PaintEventArgs e) { DeviceContexct = e.Graphics; DeviceContexct.PageUnit = GraphicsUnit.Pixel; DeviceContexct.Transform = mainViewTransform; ScalingCircle1(scale); } private void ScalingCircle1(int x ) { Pen myPen2 = new Pen(Color.Black, 1); DeviceContexct.Transform = mainViewTransform; Rectangle myRectangle = new Rectangle(50, 50, 100 * x, 100 * x); DeviceContexct.FillRectangle(new SolidBrush(Color.BurlyWood), myRectangle); } private void ScalingCircle_Load( object sender, EventArgs e ) { this.ResizeRedraw = true; } private void button1_Click( object sender, EventArgs e ) { scale += 5; this.Refresh(); } private void button2_Click( object sender, EventArgs e ) { if (scale > 1) { scale -= 5; this.Refresh(); } } } A: You can use transformations for that. The graphics object you use for painting things has a Transformation property of type System.Drawing.Drawing2D.Matrix. Graphics also has the ScaleTransform method. I haven't used it myself, but that is how microsofts Chart does it. https://msdn.microsoft.com/de-de/library/system.drawing.drawing2d.matrix(v=vs.110).aspx https://msdn.microsoft.com/de-de/library/system.drawing.graphics.scaletransform(v=vs.110).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/48185865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: End processing a stream using event-stream I am reading a large JSON file using JSONStream and I want to call a method when the whole stream is processed. var JSONStream = require('JSONStream'), es = require('event-stream'); es.pipeline( fs.createReadStream('file.json'), JSONStream.parse(['features', true]), es.map(function (data) { console.log("Added data"); }) ); How can I do that? A: I used 'event-stream' for processing of ~200kB files contain JSONs inside and got the issue when 'end' Event was never called when using 'event-stream', if I put .on('end') after event-stream pipes. But when I put it Before pipes - everything works just ok! stream.on('end',function () { console.log("This is the End, my friend"); }).on('error',function (err) { console.error(err); }).pipe(es.split()) .pipe(es.map(function (line, cb) { //Do anything you want here with JSON of line return cb(); })); nodejs, event-stream A: Sorted. Save the read stream in a variable and pipe an on('end', function) on that read stream.
{ "language": "en", "url": "https://stackoverflow.com/questions/13419130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: python getting many to many from model mixin returning None I have a model: class Employee(models.Model, MyMixin): full_name = models.CharField(max_length=255) items = models.ManyToManyField(Item, blank=True) and a mixin class: class MyMixin(object): def my_m2m(self, field): field_value = getattr(self, field) print(field_value) // do something with many to many field emp = Employee() emp.my_m2m("items") It gives me the result like employee.Item.None while printing emp.my_m2m("items") on console. If I do emp.items.all() it gives me the result but I cant get it by name. Why is it not giving the list of item associated with it ? Am I missing anything ? A: As you say, adding .all() gives the result, so you need to add that to your dynamic lookup: field_value = getattr(self, field).all()
{ "language": "en", "url": "https://stackoverflow.com/questions/49010871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where does Identity Server 4 stores client's code verifier I have setup Identity Server 4 with EF & Angular client (OIDC JS library) with Authorization Code with PKCE grant. I see the code challenge & method being passed in the /authorize url. As per specification, auth server stores code challenged passed by client on auth server to be verified later when client sends code verifier. Where does identity server 4 stores the code challenge in database? A: It depends on how it is implemented, one common way is to store them in a database table called PersistedGrants. The Authorization Codes are also stored in this table, however they are deleted as as soon as they are used. The image shows what it can look like in this table. The Code_challenge is stored together with the access-code in the database and you can see the code where they pack it all together and then store it as an encrypted blob in the database. * *AuthorizeResponseGenerator.cs (look at the end of the file) The authorization code is stored in the database as the image below shows: The actual payload is encrypted and protected, at it looks like this: { "PersistentGrantDataContainerVersion": 1, "DataProtected": true, "Payload": "CfDJ8OFLAj3iVVVHvhgvjcKB19Z7-Hms4IIQobGgGl7VnJQCtKiB-Inr3h-mcWCxxD8dJ4QNTbuVeywbT6ROsaf13EpaIQDWtLgbnSPvCDTLQeWTO_vP0UtDwJ7TTCc5aTvKEp_9hX9S1b3l685bmBMlTIcZFqGGM2VfK0qasWCqKSQcTxeN6cgJygZEQNMgAG4ipqr..." }
{ "language": "en", "url": "https://stackoverflow.com/questions/70066791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++ syntax using inheritance I'm having trouble with the syntax of an inherited classes and constructors and methodes in them. I want to implement a class date and a child class date_ISO that would set a given day, month, year in a specific order and through a method write it into string. I thing my base class date works fine, but I'm having problems with the derived date_ISO How do I use correct syntax to inherite a constructor like Date, and how do I implement and execute it? code for class Date: #ifndef DATE_HPP #define DATE_HPP #include <sstream> #include <string> #include <iostream> class Date { private: short day; short month; short year; public: std::string getDD(short day); std::string getMM(short month); std::string getYear(short year); Date(short day, short month, short year); virtual std::string format() =0; virtual ~Date() =0; }; std::string Date::getDD(short day) { std::stringstream s_day; if(day < 10) { s_day << '0' << day; } return s_day.str(); } std::string Date::getMM(short month) { std::stringstream s_month; if(month < 10) { s_month << '0' << month; } return s_month.str(); } std::string Date::getYear(short year) { std::stringstream s_year; s_year << year; return s_year.str(); } Date::Date(short day, short month, short year) : day(day), month(month), year(year){} #endif code for class Date_iso: #ifndef DATEISO_HPP #define DATEISO_HPP #include "Date.hpp" #include <sstream> #include <string> #include <iostream> class DateISO : public Date { public: std::string format(); DateISO(short day, short month, short year); }; std::string DateISO::format() { std::stringstream ss; ss << this->getYear() << this->getMM() << this->getDD(); return ss.str(); } DateISO::DateISO(short day, short month, short year){} Date::~DateISO() { } #endif Followup question: I have written a small code with the tips i got here and I don't use it properly. I'm trying to have a polymorphic pointer that would help create a few objects of the derived class but firstly I wanted to check what happends when I create a simple objekt of the derived class. It doesnt compile and I get a "undefined referance" error to all my get methods. I add the new code (old code no longer relevant but is still there for comparison). code for class Date: #ifndef DATE_HPP #define DATE_HPP #include <sstream> #include <string> #include <iostream> class Date { private: short day; short month; short year; public: std::string getTT(short day); std::string getMM(short month); std::string getYear(short year); Date(short day, short month, short year); virtual std::string format() =0; virtual ~Date() =0; }; std::string Date::getTT(short day) { std::stringstream s_day; this->day = day; if(day < 10) { s_day << '0' << day; } else { s_day << day; } return s_day.str(); } std::string Date::getMM(short month) { std::stringstream s_month; this->month = month; if(month < 10) { s_month << '0' << month; } else { s_month << month; } return s_month.str(); } std::string Date::getYear(short year) { this->year = year; std::stringstream s_year; s_year << year; return s_year.str(); } Date::Date(short day, short month, short year) : day(day), month(month), year(year)//prueft die Attribute { //some code } #endif code for class dateISO: #ifndef DateISO_HPP #define DATEISO_HPP #include "Date.hpp" #include <sstream> #include <string> #include <iostream> class DateISO : public Date { public: std::string getTT(); std::string getMM(); std::string getYear(); std::string format(); DateISO(short day, short month, short year); ~DateISO(); }; std::string DateISO::format() { std::stringstream ss; ss << DateISO::getYear() << DateISO::getMM() << DateISO::getTT(); return ss.str(); } DateISO::DateISO(short day, short month, short year) : Date(day, month, year){} DateISO::~DateISO() { //some code } #endif and code for the test main: #include "DateISO.hpp" //#include "DateDE.hpp" #include "Date.hpp" #include <sstream> #include <string> #include <iostream> int main() { DateISO date_iso(5,9,2017); std::cout << date_iso.format(); return 0; } How do I use a polymorphic pointer to create and manage objekts? what is wrong with the object that I created (that gives me an error)? I am sorry for the long question and am thankful for any help. A: You already know how to use a constructor initializer list as you do it in the Date constructor. You "call" a parent class constructor just the same way. In your case DateISO::DateISO(short day, short month, short year) : Date(day, month, year) // "Call" the parent constructor {} A: In addition to Some Programmer Dude's answer, it is also possible to inherit a constructor with 'using' like so: class DateISO : public Date { using Date::Date; }; This will redeclare all the base classes constructors in the child class, and all arguments will be forwarded to the base constructor, so this probably wouldn't be suitable if your base class had multiple constructors and you only wanted to inherit one of them, nor if your child class has additional members which must be initialised, but for your case where all members are in the base class and the child class only adds methods this should be okay. See the section on 'Inheriting Constructors' for more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/48204133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Method for converting float to integer after checking I am trying to perform multiple operations on two numbers (say A and B). These two numbers are getting inputted via a single string. So I am converting them into Double values and performing an operation on them. The poblem is that the output is always double. I would like to have the answer to be an integer answer if the result is an integer, say, 2 instead of 2.0. Cases: * *A= 2 and B= 2 (input in string )=> extracted into float variables => varA= 2.0, varB=2.0 current result => 4.0 (simple * operation ) optimum result => 4 *A= 2.0 and B= 2.0 (input in string )=> extracted into float variables => varA= 2.0, varB=2.0 current result => 4.0 (simple * operation ) optimum result => 4.0 I looked it up and it wasn't much help. As such questions either deal with conversion or precision. Links to any similar/helping questions that I might have missed will work too. I know how to convert from float to int, but looking for optimum way to check if a number can be represented in int or not. And get result accordingly. Thank you A: You can try and use % operator to decide if the two doubles produce a perfect division and use integer casting like below. double num1 = 20.0; double num2 = 5.0; if (num1%num2 == 0) { System.out.println((long) (num1/num2)); } else { System.out.println(num1/num2); }
{ "language": "en", "url": "https://stackoverflow.com/questions/64100729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change div value based on option Using this great plugin http://exodecreations.com/jQuery/jqDropDown.html My Jquery code: jQuery(function() { jQuery('#list4').jqDropDown({ optionChanged: function(){ jQuery("#firmos").html('My New Text'); }, direction: 'up', defaultStyle: false, containerName: 'theContainer', toggleBtnName: 'awesomeToggleClass', optionListName: 'thisListIsRocking', effect: 'fade', effectSpeed: 300 }); }); My php code: <form action="#"> <select id="list4" name="invoices"> <option>Aspen</option> <option>Tokyo</option> <option>Cannes</option> <option>Capetown</option> <option>Paris</option> <option>Nice</option> <option>Geneva</option> </select> </form> Based on the option selected i would like the div with id #firmos to change its value. My current example changes the div text to a single value but i will need a different value for each option.. Any efficient ideas? The list of cities will be around 50.. maybe define an attribute within each <option> ? A: I believe this may work. jQuery("#firmos").html($(this).val()); In your document ready function it would look like this. jQuery(function() { jQuery('#list4').jqDropDown({ optionChanged: function(){ jQuery("#firmos").html($(this).val()); }, direction: 'up', defaultStyle: false, containerName: 'theContainer', toggleBtnName: 'awesomeToggleClass', optionListName: 'thisListIsRocking', effect: 'fade', effectSpeed: 300 }); }); Edited Actually if you want to redisplay the option in another element this control has a parameter called place holder you could do this. jQuery(function() { jQuery('#list4').jqDropDown({ placeholder: '#firmos', direction: 'up', defaultStyle: false, containerName: 'theContainer', toggleBtnName: 'awesomeToggleClass', optionListName: 'thisListIsRocking', effect: 'fade', effectSpeed: 300 }); }); Edited Again If you want a custom value you can do something like this jQuery(function() { jQuery('#list4').jqDropDown({ optionChanged: function(){ jQuery("#firmos").html((function (currentElement) { switch (currentElement.val()) { case "someval": return "somethingSpecial1"; break; case "someval2": return "somethingSpecial2"; break; /// more case statements. } })($(this))); }, direction: 'up', defaultStyle: false, containerName: 'theContainer', toggleBtnName: 'awesomeToggleClass', optionListName: 'thisListIsRocking', effect: 'fade', effectSpeed: 300 }); }); A: Well, I looked that this plugin just replicates a select element in a list <li> and seems not possible to get the exact changed value from the select because it doesn't change if you see the DOM (that makes me assume that the onchange event from that plugin is used just to trigger something when your list changes). So, it seems you need to do some tricky thing to get the selected value implementing an onchange event recreation. Like this: Live Demo: http://jsfiddle.net/oscarj24/nuRKE/ $(function () { var firmos = $('#firmos'); $('#list4').jqDropDown({ direction: 'up', defaultStyle: false, containerName: 'theContainer', toggleBtnName: 'awesomeToggleClass', optionListName: 'thisListIsRocking', effect: 'fade', effectSpeed: 300 }); //This will be your new 'onchange' event when using 'jqDropDown' plugin. $('ul .ddOption').on('click', function(e){ var selected = $.trim($(e.target).text()); switch (selected) { case 'Aspen': firmos.html('You selected Aspen.'); break; case 'Tokyo': firmos.html('You selected Tokyo.'); break; //Do the same for other options. } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/17243544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with SSD MobileNet V2 FPNLite 320x320 conversion for Coral AI TPU I'm trying to run Tensorflow model lite on Rasperry PI with Coral TPU. Model is SSD Mobile Net 2. It works fine on PC after conversion either fully quantized or with float I/O. However when I run it on Coral TPU I got a lot of wrong result. Usually it is false positive class 0 (mapped to person). Could somebody help me, I run out ideas how to fix it? Tensorflow version: 2.5.0 Tensorflow Lite version: 2.5.0 Steps I did: * *Download the model: http://download.tensorflow.org/models/object_detection/tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz *I changed input resize layer to 320x320, but the result is the same as original 300x300. *I converted saved model to tf lite friendly format: python3 object_detection/export_tflite_graph_tf2.py --pipeline_config_path /home/pawel/proj/net_models/ssd_mobilenet_v2_320x320_coco17_tpu-8-init/pipeline.config --trained_checkpoint_dir /home/pawel/proj/net_models/ssd_mobilenet_v2_320x320_coco17_tpu-8-init/checkpoint --output_directory /home/pawel/proj/net_models/ssd_mobilenet_v2_320x320_coco17_tpu-8-fixed-input *Model convertion to TF Lite format, model_path points to the previous step output, I tried quantize True/False and the commented part of the code below: converter = tf.lite.TFLiteConverter.from_saved_model(model_path) if quantize: # converter.optimizations = [tf.lite.Optimize.DEFAULT] # converter.representative_dataset = representative_data_gen # converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8] # converter.inference_input_type = tf.uint8 # converter.inference_output_type = tf.uint8 converter.representative_dataset = representative_data_gen converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8, tf.lite.OpsSet.SELECT_TF_OPS] converter.inference_input_type = tf.uint8 converter.inference_output_type = tf.uint8 converter.allow_custom_ops = True print(converter.experimental_new_quantizer) # outputs True print(converter.experimental_new_converter) # outputs True else: converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS] converter.optimizations = [] tflite_model = converter.convert() with open(lite_model_path, 'wb') as f: f.write(tflite_model) Data provider, used code from step 5: def representative_data_gen(): from cocodataset import CocoDataSet coco = CocoDataSet(input_size, input_size) images = coco.get_calibration_dataset(500) for img in images: yield [img] *Repressentative data set - Coco 2017 valuation data - 500 samples. class CocoDataSet: ... def get_calibration_dataset(self, limit: int): with open(self.annotation_file, 'r') as f: annotations = json.load(f) image_info = annotations['images'] random.shuffle(image_info) image_info = image_info[:limit] image_paths = [] for img in image_info: image_path = self.image_dir + img['file_name'] image_paths.append(image_path) print(f"{limit} images will be returned") images = [] fl = True for i, path in enumerate(image_paths): print(f"Loading {i}/{len(image_paths)}:" + path) image = cv.imread(path) image = cv.cvtColor(image, cv.COLOR_BGR2RGB) tensor = np.zeros((self.input_height, self.input_width, 3), dtype=np.uint8) _, _, channel = tensor.shape h, w, _ = image.shape scale = min(self.input_width / w, self.input_height / h) w, h = int(w * scale), int(h * scale) image = cv.resize(image.copy(), (w, h), interpolation=cv.INTER_LINEAR) reshaped = image margin_x = (self.input_width - w) // 2 margin_y = (self.input_height - h) // 2 tensor[margin_y:h + margin_y, margin_x:w + margin_x] = reshaped tensor = np.expand_dims(tensor, axis=0) tensor = tensor.astype(np.float32) - 127.5 tensor = tensor * 0.007843 images.append(tensor) return images *Coral AI compilation: edgetpu_compiler ssd_mobilenet_v2_coral.tflite *Inference with Coral AI (Rpi). It works fine with SSD2 Mobile Net provided in Coral AI SDK. x, y, scale = self.set_image_input(self.interpreter, region) self.interpreter.invoke() detection_boxes = self.get_output_tensor(self.interpreter, 0) detection_classes = self.get_output_tensor(self.interpreter, 1, np.int) detection_scores = self.get_output_tensor(self.interpreter, 2) count = self.get_output_tensor(self.interpreter, 3, np.int) 8.Input image, scaled and centered: def set_image_input(self, interpreter: tflite.Interpreter, image: np.ndarray) -> (int, int, float): self.did = self.did + 1 width, height = (self.input_height, self.input_width) stretch = False if stretch: h, w, _ = (self.input_height, self.input_width, 1) else: h, w, _ = image.shape cv.imwrite(f"{self.logs_dir}/image{self.did}.png", image) scale = min(width / w, height / h) w, h = int(w * scale), int(h * scale) tensor = self.input_tensor(interpreter) tensor.fill(0) _, _, channel = tensor.shape image = cv.resize(image.copy(), (w, h), interpolation=cv.INTER_LINEAR) reshaped = image if tensor.dtype == np.float32: reshaped = reshaped * (1.0/255) - 1 margin_x = (self.input_width - w) // 2 margin_y = (self.input_height - h) // 2 tensor[margin_y:h + margin_y, margin_x:w + margin_x] = reshaped return margin_x, margin_y, scale *Getting output tensor: def get_output_tensor(self, interpreter: tflite.Interpreter, index: int, result_type=np.float): output_details = interpreter.get_output_details()[index] quantization = output_details['quantization'] dtype = output_details['dtype'] tf_index = output_details['index'] tensor = np.squeeze(interpreter.get_tensor(tf_index)) if quantization != (0, 0): input_scale, input_zero_point = quantization tensor = (tensor.astype(np.float32) - input_zero_point) * input_scale if tensor.dtype != result_type: tensor = tensor.astype(result_type) return tensor What I noticed that the results differs a little when I run the conversion a couple of times - the representative data is randomly obtained from the set. The differences are much more visible on Coral AI compiled model, that that I run on PC. A: The accuracy quantized SSD model is slightly lowered than the float model, you can probably try the efficient-det model: https://www.tensorflow.org/lite/api_docs/python/tflite_model_maker/object_detector A: It looks that the newest update of Coral compiler and RaspberryPI runtime solved the issue. RPI runtime after update: 2.5.0.post1 Edge CPU compiler after update: 16.0.384591198 Some example detections (class, score): Coral: [(0, 0), (1, 0.7210485935211182), (0, 0), (1, 0.6919153332710266), (1, 0.7428985834121704), (1, 0.8485066890716553), (24, 0.6919153332710266)] TF Lite - CPU: [(0, 0), (1, 0.7210485935211182), (0, 0), (1, 0.6919153332710266), (1, 0.7356152534484863), (1, 0.8412233591079712), (24, 0.7028403282165527)] TF CPU: [(0, 0), (1, 0.75359964), (0, 0), (1, 0.7409908), (1, 0.7797077), (1, 0.8114069), (24, 0.750371)]
{ "language": "en", "url": "https://stackoverflow.com/questions/68055368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Upgrading Ghost Broke My Website My ghost blog was running fine and i've just tried to upgrade it using the guide posted here. I am using Digital Ocean as the web host by the way. After upgrade it's showing some problems, I've looked at the error log and it's showing a bunch of errors like this: 2015/09/07 13:22:50 [error] 3987#0: *23 connect() failed (111: Connection refused) while connecting to upstream, client: (IP HIDDEN), server: my-ghost-blog.com, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:2368/favicon.ico", host: "HOST HIDDEN", referrer: "http://URL HIDDEN/" I've removed IPs and what not A: Since nobody has answered it I might as well post what worked for me. I was able to start the blog manually with npm start it was just the service ghost start that reported [OK] but didn't actually start it. First I was able to find the error in /var/log/nginx/errors.log 2016/02/08 21:18:27 [error] 601#0: *2086 connect() failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: my-ghost-blog.com, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:xxxx/favicon.ico", host: "mydomain.com", referrer: "http://example.com/path-to-post/" I had to recursively change the owner of /ghost directory like this: chown -R ghost:ghost ghost/* I executed it from /var/www thanks to @BrettDeWoody for his post
{ "language": "en", "url": "https://stackoverflow.com/questions/32443719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: redirect to a action that expects value in other controller I have a controller StepOfIdea,and this controller has a action like this : StepOfIdeaRepository objStepOfIdearepository=new StepOfIdeaRepository(); public ActionResult Index(int ideaId) { return View(objStepOfIdearepository.FindBy(i=>i.IdeaId==ideaId)); } So i have another controller named idea and this controller has a view named index @model IEnumerable<DomainClass.Idea> @{ ViewBag.Title = "Index"; } <h2>لیست</h2> @if (User.IsInRole("User")) { <p> @Html.ActionLink("ایده جدید", "Create", new {step = 1}) </p> } <table> <tr> @if (User.IsInRole("Admin")) { <th> @Html.DisplayNameFor(model => model.User.Name) </th> } <th> @Html.DisplayNameFor(model => model.IdeaPersion) </th> <th> @Html.DisplayNameFor(model => model.IdeaEnglish) </th> <th> @Html.DisplayNameFor(model => model.IdeaResult) </th> <th> @Html.DisplayNameFor(model => model.Date) </th> <th></th> <th></th> </tr> @foreach (var item in Model) { <tr> @if (User.IsInRole("Admin")) { <td> @Html.DisplayFor(modelItem => item.User.Name) @Html.DisplayFor(modelItem => item.User.Name) </td> } <td> @Html.DisplayFor(modelItem => item.IdeaPersion) </td> <td> @Html.DisplayFor(modelItem => item.IdeaEnglish) </td> <td> @Html.DisplayFor(modelItem => item.IdeaResult) </td> <td> @Html.DisplayFor(modelItem => item.Date) </td> <td> @Html.RenderAction("ویرایش","index", stepofidea, new { id=item.Id }) | </td> <td> @Html.ActionLink("ویرایش", "Edit", new { id=item.Id }) | @Html.ActionLink("نمایش", "Edit", new { id=item.Id }) | @Html.ActionLink("حذف", "Delete", new { id=item.Id }) </td> </tr> } </table> In this line @Html.RenderAction("ویرایش","index", ????, new { id=item.Id }) | I want to redirect to index action of stepOfIdea controller and pass a value .But the above line doesn't work . A: I think you confused some terms in translation to English, and what you are actually looking for is to create an <a href="">Link</a> that also passes a variable. You can do this very simply, by: @Html.ActionLink("ویرایش", "Index", "StepOfIdea", new { id = item.Id }, null) This will create the HTML: <a href="http://example.com/StepOfIdea/Index/5">ویرایش</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/24143414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does content size of UITableView Change I have a UITableView that I am loading my data in 3 blocks. I load the latest 10 records and when user pulls up using the UIRefreshControl, I load the preceding 10 and show the last row from the previous block. I store the previous content size right before I load the new set from database previousContentSizeHeight = tableView.contentSize.height and then when data comes and update my array, I use previous to calculate the new content size of table let difference = tableView.contentSize.height - previousContentSizeHeight - MinimumCellHeight self.messageTableView.setContentOffset(CGPoint(x: 0, y: difference), animated: false) This works for the most part. It behaves correctly after the viewDidAppear when loading the first set and when loading the 2nd set, but in the third set it starts changing in content size. It gets decreased! My understanding is if I am adding data to it (not deleting anything), the content size should only grow. I have in multiple places in my code readings of the table content size like this event: func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { print("tableView.contentSize.height is: \(tableView.contentSize.height)") } as I am scrolling up and down, I see the number decrease and sometimes increase and decrease Why does content size changes in size!? NOTE: I want to stick to using the content offset. I have more luck with it than IndexPath. UPDATE #1 @Sohil R. Memon: I tried your suggestion. Per screenshot, I added a print statement and as you can see the viewDidLayoutSubviews is still not executing. i tried inside the endDisplaying with self.messageTableView and just tableView A: Once the cell are displayed and didEndDisplaying is called, there are more things to process and when you scroll cellForItem calls again and that gives you different sizes. In order to get the exact contentSize of UITableView once all the cells are displayed, you can get it from below method. Just write the below method in your UIViewController class. override func viewDidLayoutSubviews() { print(tableView.contentSize.height) //Exact Content Size of UITableView } func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { tableView.layoutIfNeeded() } Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/43084207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Connect to sftp server with host key fingerprint using python 3.0 on Windows I am trying to connect to an sftp server using python on Windows. I cannot connect to the server without a hostkey. A lot of options, especially with pysftp ask for hostkey files which apparently aren't generated on Windows. From what I can see is that I have 3 options: 1) [Most preferred] use a string to generate the required key through python code. But that's always producing errors - some of the code using StringIO doesn't work on Python 3 and the possible workarounds don't seem to work for me. Apparently I am not able to decode the key properly and I have no idea how to check for that. I have tried to generate PKey but I am not sure what I am doing wrong. 2) get the right format of known_hosts file (I have no idea what it should look like and couldn't find any samples online) - and put or add the hostkey there. That way I'd (hopefully) be able to use cnopts to connect to the server. 3) This is a fallback option, if the above two don't work: use python to call powershell script that does the work - I have been successful at this but would like to pass arguments from python script to powershell and then get results/status from powershell back to python. The most relevant options that I have tried out: Python - pysftp / paramiko - Verify host key using its fingerprint Embedding public key as string in Paramiko Application Using python pysftp package, getting a "SSHException: Bad host key from server" error What I'd like is a sample string (that would look like the actual thing) and the steps around creating a key from it. Or a sample file that I can use to just plugin the details and run the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/57697111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Not able to update reducer state in redux On change of select I want to save the value in reducer. But How can I pass the value into state. below is the code I am using. container/header/index.js const changeCloud = () => { return ('hello'); } const mapStateToProps = () => ({ cloud: changeCloud(), menuItems: menuItems, }) const mapDispatchToProps = (dispatch) => ({ setCloud: () => { dispatch(setCloud('sf')); }, }) const Header = connect( mapStateToProps, mapDispatchToProps )(HeaderPresentational); component/header/index.js setCloudClick(evt) { this.setState({ value: evt.target.value, }, function () { this.props.setCloud('this.state.value'); }); } render(){ return( <select onChange={this.setCloudClick} value={this.state.value}> <option value="zscaler.net">zscaler.net</option> <option value="zscalerOne.net">zscalerOne.net</option> <option value="zscaler.net">ZscalerTwo.net</option> <option value="Zscaler Private Access">Zscaler Private Access</option> </select> ); } reducer.js function reducer(state, action) { switch (action.type) { case 'SET_CLOUD' : alert(action.text); return state; default : return state; } } export default reducer; A: From the callback, you need to pass the value and not the string setCloudClick(evt) { this.setState({ value: evt.target.value, }, function () { this.props.setCloud(this.state.value); // pass this.state.value here }); } However, when you are storing value in store, you need not store it locally. You can dispatch the value like index.js setCloudClick(evt) { this.setState({ value: evt.target.value, }, function () { this.props.setCloud(this.state.value); }); } render(){ return( <select onChange={this.setCloudClick} value={this.state.value}> <option value="zscaler.net">zscaler.net</option> <option value="zscalerOne.net">zscalerOne.net</option> <option value="zscaler.net">ZscalerTwo.net</option> <option value="Zscaler Private Access">Zscaler Private Access</option> </select> ); } container/header/index.js const changeCloud = () => { return ('hello'); } const mapStateToProps = () => ({ cloud: changeCloud(), menuItems: menuItems, }) const mapDispatchToProps = (dispatch) => ({ setCloud: (value) => { dispatch(setCloud(value)); }, }) const Header = connect( mapStateToProps, mapDispatchToProps )(HeaderPresentational);
{ "language": "en", "url": "https://stackoverflow.com/questions/48982867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show html form using shortcode in wordpress? I want to show html form using shortcode. Here is my code: add_shortcode('sms_order_form', 'sms_order_form_html'); function sms_order_form_html(){?> '<form> <div class="tooltip"> 0<input type="range" id="range" value="0" min="0" max="100"/>100 <span class="tooltiptext">0</span> </div> </form> <?php } ?> But this doesn't print the form. but if I replace the HTML form by echo 'hello'; it prints hello. Is there any way to show any HTML using shortcode. N.B.: shortcode is placed using elementor. A: Shortcode should return a string: <?php add_shortcode( 'sms_order_form', 'sms_order_form_html' ); function sms_order_form_html() { ob_start(); ?> <form> <div class="tooltip"> 0<input type="range" id="range" value="0" min="0" max="100"/>100 <span class="tooltiptext">0</span> </div> </form> <?php return ob_get_clean(); } A: Shortcode functions need to return the output in form of a string as opposed to outputting HTML right away. You can use output buffering to return your code like so: add_shortcode('sms_order_form', 'sms_order_form_html'); function sms_order_form_html() { ob_start(); ?> <form> <div class="tooltip"> 0<input type="range" id="range" value="0" min="0" max="100"/>100 <span class="tooltiptext">0</span> </div> </form> <?php return ob_get_clean(); // clear the output buffer, and return as string }
{ "language": "en", "url": "https://stackoverflow.com/questions/62680274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does google chrome launch desktop apps? i don't really know the terminology so im going to start with an example. If I click a magnet link, Google chrome asks if i want to launch a torrent client. I click ok and chrome launches that app and the app does some stuff based on the link. now is there anyway to see how the app gets the info from chrome? and how chrome starts the app? A: It depends exactly on the OS, but in general, another desktop program can register a specific protocol, or URI scheme, to open up a program. Then, when Chrome doesn't know how to deal with a protocol, it'll just hand it over to the OS to deal with. In Windows for example, they're configured by putting something into the system registry under a specific key (https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx). Most applications will setup themselves as a default for the particular protocol when installed. A: Chrome is a "desktop" program. It can open any program exposed from the operating system. A link can contain a specific protocol instead of http://, the OS can have a map that ties protocols directly to installed programs. Chrome is not communicating with the app at any point. It only tells the os to open a resource at a given url with a given program.
{ "language": "en", "url": "https://stackoverflow.com/questions/44597071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Podio: "Item has been deleted" on PUT, but can retrieve item via GET For some items I have the following problem: I can retrieve them via GET https://api.podio.com/item/$itemId (meaning the item is not deleted). But when I want to update the item via PUT https://api.podio.com/item/$itemId, it results in a HTTP 410 with the following body: { "error_parameters": {}, "error_detail": null, "error_propagate": false, "request": { "url": "http://api.podio.com/item/$itemId", "query_string": "", "method": "PUT" }, "error_description": "Item has been deleted", "error": "gone" } Is there any wrong assumption on my side, or why do I get this error?
{ "language": "en", "url": "https://stackoverflow.com/questions/47257989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: insert table with onclick JS function I want a onclick button that when you press it, it shows up a pre-compilated table. I've tried to use the table as a text or a paragraph in teh script and obviusly it did'nt work. I can't figure out how to do it. can you help me? A: The easy way is to add the table with a 'hide' class, like: <button id='toggleTable'> show/hide table </button> <table class='hide' id='tableTarget'> ... </table> The js: document.addEventListener('DOMContentLoaded', () => { document .querySelector('#toggleTable') .addEventListener( 'click', () => { document .querySelector('#tableTarget') .classList .toggle('hide') }, false ) }, false ) the css: .hide { display: none !important; } if you use any frontend framework should be easier. But this is with plain html/js/css. And IE9 is not supported with this solution. If you need it, you have to change a little bit the js code. Good Luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/64110245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: My django objects get affected when I commit changes in heroku with git My django admin panel objects get affected when I commit changes in git for my heroku website. I commit changes to my heroku website from following command in terminal - git add . git commit -am "make it better" git push heroku master enter code here before committing when I add new model: after committing changes it disappeared: Is there any solution for that committing changes does not affect these objects in django admin panel ?
{ "language": "en", "url": "https://stackoverflow.com/questions/66118535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: reverse geocoding to find exact organization/building/landmark name that location When I search about an organization in google maps,along with map location, there is side pop up where other details like adress,ph no etc show up. I know the python coding to find cordinates for an address. but I am notable to find the a way to extract name of the organization from the address. Is there a way to program( python preferred) to find the organization/building/landmark name for which I only have the address ? Note : Through web scraping I can find the address of the organization from its web-site but how do I find the name of organization if I have only its address or cordinates Eg : search 'Ajanta Chemical Industries' on google map and you get below address Office & Factory 812/ E-9, 10 11 & 12, Samtel Zone, Phase- III, RIICO Industrial Area, Bhiwadi, Rajasthan 301019 Question - If I have above address , is there a programmable way to find that its for 'Ajanta Chemical Industries' ?
{ "language": "en", "url": "https://stackoverflow.com/questions/57205294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to convert unsigned char array to QByteArray in Qt? unsigned char x[] = {0x7E,0x00,0x00,0x0F }; I want to push it to QByteArray but the QByteArray when finds '\0' stops copying. A: Which Qt version are you using? 4.7 has QByteArray(const char*, size) which should work and QByteArray::fromRawData(const char*, int size) which also should work. A: QByteArray test("\xa4\x00\x00", 3);
{ "language": "en", "url": "https://stackoverflow.com/questions/5911832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Case insensitive matching python I want to match items from one list in another without worrying about case sensitivity. mylist1 = ['fbH_q1ba8', 'fHh_Q1ba9', 'fbh_q1bA10','hoot'] mylist2 = ['FBH_q1ba8', 'trick','FBH_q1ba9', 'FBH_q1ba10','maj','joe','civic'] I was doing this before: for item in mylist2: if item in mylist1: print "true" else: print "false" But this fails because it is not case sensitive. I am aware of re.match("TeSt", "Test", re.IGNORECASE) but how can I apply that to my example? A: Normalize the case with str.lower(): for item in mylist2: print item.lower() in mylist1 The in containment operator already returns True or False, easiest just to print that: >>> mylist1 = ['fbh_q1ba8', 'fhh_q1ba9', 'fbh_q1ba10','hoot'] >>> mylist2 = ['FBH_q1ba8', 'trick','FBH_q1ba9', 'FBH_q1ba10','maj','joe','civic'] >>> for item in mylist2: ... print item.lower() in mylist1 ... True False False True False False False If mylist1 contains mixed case values, you'll need to make the loop explicit; use a generator expression to produce lowercased values; testing against this ensures only as many elements are lowercased as needed to find a match: for item in mylist2: print item.lower() in (element.lower() for element in mylist1) Demo >>> mylist1 = ['fbH_q1ba8', 'fHh_Q1ba9', 'fbh_q1bA10','hoot'] >>> for item in mylist2: ... print item.lower() in (element.lower() for element in mylist1) ... True False False True False False False Another approach is to use any(): for item in mylist2: print any(item.lower() == element.lower() for element in mylist1) any() also short-circuits; as soon as a True value has been found (a matching element is found), the generator expression iteration is stopped early. This does have to lowercase item each iteration, so is slightly less efficient. Another demo: >>> for item in mylist2: ... print any(item.lower() == element.lower() for element in mylist1) ... True False False True False False False A: Why not just do: for item in mylist2: if item.lower() in [j.lower() for j in mylist1]: print "true" else: print "false" This uses .lower() to make the comparison which gives the desired result. A: The other answers are correct. But they dont account for mixed cases in both lists. Just in case you need that: mylist1 = ['fbh_q1ba8', 'fbh_q1ba9', 'fbh_q1ba10','hoot'] mylist2 = ['FBH_q1ba8', 'trick','FBH_q1ba9', 'FBH_q1ba10','maj','joe','civic'] for item in mylist2: found = "false" for item2 in mylist1: if item.lower() == item2.lower(): found = "true" print found
{ "language": "en", "url": "https://stackoverflow.com/questions/23063109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reading and using data from user files in Javascript (web application), without uploading them I'd like to have a way for a webpage -which is generated dynamically by my server- to read all the files in a specific user folder, manipulate them using javascript, within the web browser, and using them to show to the user some results (specific correlations between the data, dependent on the context and sometimes some graphs, drawn using these correlations). Communication with the server about these data is neither required nor desired. Actually, since all the manipulations needed can be done via javascript and the files can be huge, for now I absolutely don't want that their content is uploaded to the server. Therefore there are no security risks (at least none that I can see). Server side, I'm only interested to save the name of the folder, so that the user (who is registered) doesn't need to select the files one by one or to select them again every time a new page is dynamically created. For now, the only hopes to find a solution that I have been able to gather are about using the Chrome FileSystem API (but I'd prefer a general solution, not dependent on a specific browser) or creating an extension that the user should install to use this feature when visiting the website (which, for me, is maybe even worse than relying on a specific browser). So I wonder if there is a way to implement this feature using only pure javascript and HTML5 and using neither extensions nor browser dependent solutions. A: Due to security reasons, JavaScript running in the browser should not be used to access the filesystem directly. But definitely you can access it using Node's fs module (but that's on the server side). Another way is, if you let the user pick files using the <input type="file"> tag then you can use the File API to fetch the contents. But I think that is not what you are looking for. Recommended reading: https://en.wikipedia.org/wiki/JavaScript#Security
{ "language": "en", "url": "https://stackoverflow.com/questions/50544973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set the Priority for feature file inside include tag How to set the priority for feature file(s) to run in the TestNG.xml file with include tag. I have added the "priority" attribute inside the include tag as follows: <test name="DESKTOP Chrome" enabled="true"> <parameter name="platform" value="desktop" /> <parameter name="driver.name" value="chromeDriver" /> <parameter name="webdriver.chrome.driver" value="driver/chromedriver.exe" /> <parameter name="chrome.additional.capabilities" value="{'chromeOptions':{'useAutomationExtension':false}}"/> <groups> <run> <include name="@aLoginMenuDesktop" priority="1"/> <include name="@ViewPrimaryNavigationMenuDesktop" priority="2"/> <include name="@PortfolioOverview" priority="3"/> <include name="@FooterDesktop" priority="4"/> <include name="@zSignOutMenuDesktop" priority="5"/> </run> </groups> <classes> <class name="com.qmetry.qaf.automation.step.client.gherkin.GherkinScenarioFactory" /> </classes> </test> But during the execution it throws the below error. Caused by: org.xml.sax.SAXParseException; lineNumber: 17; columnNumber: 54; Attribute "priority" must be declared for element type "include". at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) A: I removed the priority inside the tag and make it run by default instead, I just found out that the priority by default (alphabetical) is not based on the tag name of the feature file (@faturefile) that is being called But, it is based from the filename of the feature file (teststep.feature)
{ "language": "en", "url": "https://stackoverflow.com/questions/57899300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set a breakpoint on clicking a 3rd party button? I'm trying to debug a 3rd party widget (+1 button to be exact). Specifically, I'd like to set a breakpoint in Chrome that stops when a button in the widget is clicked. I would like to break on the 3rd party code that handles to click event. Is there a Chrome extension (or something else I haven't thought of) to help me find the right place in the code to break on? A: You can make use of Chrome's Developer Tools; no extension is required. I made a +1 button example here: http://jsfiddle.net/rPnAe/. If you go to that fiddle and then open Developer Tools (F12), then go to Scripts and expand Event Listener Breakpoints and lastly expand 'Mouse' and tick the 'click' checkbox, then whenever you click somewhere (which includes an event listener), the debugger will now break at the line of code which contains the listener function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7703765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: JS Script not loading on Firefox and Safari My web page does not seem to load a JS file into it on Firefox, Safari and most mobile browsers, but it works on Chrome (and other chromium based browsers). https://paxco.in/wallet.html Is the page I have the script tage <script type="text/javascript" scr="./js/web3.min.js"></script> But it does not show in the sources when I use dev tools, and I get errors when I reference functions from the file as according to the browser it is non-existent. EDIT: Fixed Linking script, Now I can't reference the /js/web3.min.js file in my other scripts A: You have an unclosed tag somewhere on your page. This results in the browser not being able to parse the DOM properly, resulting in your script tag not being "rendered". Chrome has some better error handling for cases like that, which makes it work in that browser. Also, there's a typo: scr="./js/web3.min.js" Should be src="./js/web3.min.js"
{ "language": "en", "url": "https://stackoverflow.com/questions/55260124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hide buttons when printing I have a page which contains at the bottom 3 buttons with the following coding: function printpage() { //Get the print button and put it into a variable var printButton = document.getElementById("printpagebutton"); //Set the print button visibility to 'hidden' printButton.style.visibility = 'hidden'; //Print the page content window.print() printButton.style.visibility = 'visible'; } #options { align-content:center; align-items:center; text-align: center; } <div id="options"> <input type="submit" value="post news" > <input id="printpagebutton" type="button" value="print news" onclick="printpage()"/> <input type="button" value="re-enter the news"> </div> I managed to hide the print button while printing but i couldn't with the others. I've searched the internet for the solution, and most questions were answered by adding the display:none; in css, but i end up with 3 hidden buttons on the screen. I only want the buttons hidden while printing Answer might be simple, my knowledge in web developing is acient. Thank you in advance. A: You can use a css media query to target print: @media print { .hide-print { display: none; } } A: You can use CSS @media queries. For instance: @media print { #printPageButton { display: none; } } <button id="printPageButton" onClick="window.print();">Print</button> The styles defined within the @media print block will only be applied when printing the page. You can test it by clicking the print button in the snippet; you'll get a blank page. A: Assign an id to the other 2 buttons. For the POST NEWS button you can set id to postnews and RE-ENTER THE NEWS to reenterthenews; Then do this function printpage() { //Get the print button and put it into a variable var printButton = document.getElementById("printpagebutton"); var postButton = document.getElementById("postnews"); var reenterButton = document.getElementById("reenterthenews"); //Set the button visibility to 'hidden' printButton.style.visibility = 'hidden'; postButton.style.visibility = 'hidden'; reenterButton.style.visibility = 'hidden'; //Print the page content window.print() //Restore button visibility printButton.style.visibility = 'visible'; postButton.style.visibility = 'visible'; reenterButton.style.visibility = 'visible'; } HTML <div id="options"> <input type="submit" id="postnews" value="post news" > <input id="printpagebutton" type="button" value="print news" onclick="printpage()"/> <input type="button" id="reenterthenews" value="re-enter the news"> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/31425557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Using Teradata macros from Entity Framework? Is it possible to use Teradata Macros directly from Entity Framework? I tried the model designer and guessed they would show up under stored procedures which they don't. Does the Teradata .Net provider support macros at all? Or, do I have to manually write the SQL sentences to execute the macros?
{ "language": "en", "url": "https://stackoverflow.com/questions/9909317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL query to update all subpages of a specific uid in TYPO3 I'm looking to find an SQL query to update my TYPO3 table (pages) to add a specific fe_group for all pages under a specific uid in the page tree. Example: UPDATE pages SET fe_group = 16 WHERE pid = 84; This will add my fe_group to all pages under my specific uid in the page tree but only for the first level under. I need to reach the infinite levels. TYPO3 v6.2 and above Thanks! A: If you want to apply usergroup access rights to all subpages of a page, there is a built in function the page properties already: Extend to Subpages. This works in all TYPO3 versions you mentioned: If you really want to do it with an SQL query, you need to create a small PHP script to recursively change the access rights.
{ "language": "en", "url": "https://stackoverflow.com/questions/54223371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert websites into mobile website format I would like to display other we pages in my mobile webapp, but some web pages will be too cumbersome for use on a tiny mobile device screen. So implement some kind of google mobilizer feature. Is there any API available in PHP so that i can use that to convert these pages into mobile compatible A: No. You'll have to do it manually. You should look into responsive CSS layouts. These will adjust the content of the page as the width of the browser changes. So same page will work in a full browser window and mobile. Look at * *http://www.columnal.com/ *http://lessframework.com/ *http://speckyboy.com/2011/11/17/15-responsive-css-frameworks-worth-considering/ A: I got it, we can use skweezer API for this. If you want to see your website in mobile compatible format try this http://www.skweezer.com/s.aspx?q=www.example.com Replace www.example.com with your website URL. For more details, visit http://company.skweezer.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/11114757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Estimation time to read an article In ASP MVC How can I estimate time to read an article like docs.asp.net website docs.asp.net At the top of all articles, it says you need xxx minutes to read. I think they are using an algorithm to estimate time How can I do that! Thanks in advance A: The words read per minute average is about 250-300, once you know this you just need to: * *Get the article word count. *Divide this number by 275 (more or less). *Round the result to get a integer number of minutes. A: According to a study conducted in 2012, the average reading speed of an adult for text in English is: 228±30 words, 313±38 syllables, and 987±118 characters per minute. You can therefore calculate an average time to read a particular article by counting one of these factors and dividing by that average speed. Syllables per minute is probably the most accurate, but for computers, words and characters are easier to count. Study Citation: Standardized Assessment of Reading Performance: The New International Reading Speed Texts IReST by Susanne Trauzettel-Klosinski; Klaus Dietz; the IReST Study Group, published in Investigative Ophthalmology & Visual Science August 2012, Vol.53, 5452-5461 A: A nice solution here, on how to get an estimated read time of any article or blog post https://stackoverflow.com/a/63820743/12490386 here's an easy one * *Divide your total word count by 200. *You’ll get a decimal number, in this case, 4.69. The first part of your decimal number is your minute. In this case, it’s 4. *Take the second part — the decimal points — and multiply that by 0.60. Those are your seconds. Round up or down as necessary to get a whole second. In this case, 0.69 x 0.60 = 0.414. We’ll round that to 41 seconds. *The result? 938 words = a 4 minute, 41 second read.
{ "language": "en", "url": "https://stackoverflow.com/questions/49692008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make vs2010 auto generate method stubs at the end of file I try to auto generate method stub using visual studio's View.ShowSmartTag functionality When I choose this option, Method8 will be placed right after Method2 but I want to place it after all methods, Method7 in this case. Is there any settings for this? A: After researching I found that I couldn't do that
{ "language": "en", "url": "https://stackoverflow.com/questions/10497302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to extract the hidden value in imacros I want to extract the verification code in attribute value, what the code? i dont understand in this problem Look this A: I hope it helps, And not too late. TAG POS=1 TYPE=INPUT:HIDDEN ATTR=NAME:_RequestVerificationToken* EXTRACT=TXT
{ "language": "en", "url": "https://stackoverflow.com/questions/47899052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error JAVAC0000: error: package com.google.android.gms... does not exist So I just got a new MAC, and I have so many errors when running my project. I haven't worked on the project for about a year now, and this happens: Image here I have tried cleaning, rebuilding etc.. nothing seems to work. Tips? I am using Visual Studio Community 2019 for Mac Version 8.3.3 (build 8)
{ "language": "en", "url": "https://stackoverflow.com/questions/58367009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to create a value in enum with '&' I need to create a enum value something like this' DESIGN & BUILD'. I am writing an importer service and that imports the types like above. I need to compare it with ones in the Db. Is it possible to create enum values like above? Moreover, I think we could also do it by taking a regex expression that yields only text but not any sort of symbols, I mean we only get 'DESIGNBUILD'. A: You can't. Enum value names have to be valid C# identifiers, and that excludes &. I suggest you use DescriptionAttribute or something similar to provide more flexible metadata for the enum values. While you could use a regular expression to perform the mapping, I believe you'll end up with a more flexible result if you use metadata. You can then easily build a Dictionary<string, YourAttributeType> and vice versa.
{ "language": "en", "url": "https://stackoverflow.com/questions/5313550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ajax unpload image and showing img thumb I am trying to work on an application form that fill information and submit to server, but in the images part i am having a problem. i want to show the user a thumb of the selected img. and that can just happen with uploading the img to the server and give it the path and refresh the control when getting back the url of the img. I am not using the ajaxupload toolkit or anything, all whtat i am using is a input type file, and c# for the code behind and ajax functions. i am calling the ajax function with javascript but what should i pass as parameter so i can catch it from the server side, save it and how to return back the url of the saved img . i red lots of articles, most of them uses PHP, or ajaxupload packages, nd i think i can be done without that..surely i dont need a post back at all regards A: I don't think you can send file on server using AJAX, 'cause you don't have access to file system via JavaScript. I don't believe what you're trying to do is possible without Flash or Silverlight. Try SWFUpload, for instance. I was using it on my previous project, and it worked fine for me. EDIT: And about returning the URL. SWFUpload lets you to send some parameters along with file. So you could generate GUID (on the server side, then just insert it in JavaScript for SWFUpload as an additonal post parameter) and once SWFUpload finished with uploading image, save it on the server using posted GUID as a name of file. After that you can make AJAX request from JavaScript using the same GUID and ask for uploaded image. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7872195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java.lang.ClassNotFoundException: com.liferay.portal.jsonwebservice.JSONWebServiceServlet in Liferay? hai iam new to json web services in liferay i got the following error! i have added JSONWebServiceServlet in web.xml. do i have to add any jar file to classpath? 05:51:36,250 ERROR [PortalClassLoaderServlet:76] java.lang.ClassNotFoundException: com.liferay.portal.jsonwebservice.JSONWebServiceServlet java.lang.ClassNotFoundException: com.liferay.portal.jsonwebservice.JSONWebServiceServlet at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491) at com.liferay.portal.kernel.servlet.PortalClassLoaderServlet.portalInit(PortalClassLoaderServlet.java:70) at com.liferay.portal.kernel.util.PortalLifecycleUtil.register(PortalLifecycleUtil.java:52) at com.liferay.portal.kernel.servlet.PortalClassLoaderServlet.init(PortalClassLoaderServlet.java:44) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1173) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4350) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4659) at org.apache.catalina.startup.HostConfig.checkResources(HostConfig.java:1244) at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1342) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:303) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119) at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1337) at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1601) at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1610) at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1590) at java.lang.Thread.run(Unknown Source) in web.xml i have written like this: <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>pdfportlet-portlet</display-name> <jsp-config> <taglib> <taglib-uri>http://java.sun.com/portlet_2_0</taglib-uri> <taglib-location>/WEB-INF/tld/liferay-portlet.tld</taglib-location> </taglib> </jsp-config> <servlet> <servlet-name>JSON Web Service Servlet</servlet-name> <servlet-class>com.liferay.portal.kernel.servlet.PortalClassLoaderServlet</servlet-class> <init-param> <param-name>servlet-class</param-name> <param-value>com.liferay.portal.jsonwebservice.JSONWebServiceServlet</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>JSON Web Service Servlet</servlet-name> <url-pattern>/api/jsonws/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>JSON Web Service Servlet</servlet-name> <url-pattern>/api/secure/jsonws/*</url-pattern> </servlet-mapping> </web-app> A: configure the servlet like this: some sysntax error i think. its working fine now. <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>student-portlet</display-name> <servlet> <servlet-name>JSON Web Service Servlet</servlet-name> <servlet-class> com.liferay.portal.kernel.servlet.PortalClassLoaderServlet </servlet-class> <init-param> <param-name>servlet-class</param-name> <param-value>com.liferay.portal.servlet.JSONServlet</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>JSON Web Service Servlet</servlet-name> <url-pattern>/api/jsonws/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>JSON Web Service Servlet</servlet-name> <url-pattern>/api/secure/jsonws/*</url-pattern> </servlet-mapping> <jsp-config> <taglib> <taglib-uri>http://java.sun.com/portlet_2_0</taglib-uri> <taglib-location>/WEB-INF/tld/liferay-portlet.tld</taglib-location> </taglib> </jsp-config> </web-app>
{ "language": "en", "url": "https://stackoverflow.com/questions/18997374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How get get the entered values from input box and not the content of Value attribute I have some input fields with pre-populated values. After editing the values of this field if the save button is pressed in my script tag I want to take the edited value in the field and send it to my controller using ajax. The problem I faced is when I am picking the value of my input field using var name = document.getElementById('iusername').value; I am getting the value in value attribute and not the one resulted after edit.
{ "language": "en", "url": "https://stackoverflow.com/questions/46715119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Truncated If Statement C++ (Turning letters to numbers) I am trying to change a series of letters into numbers with C++ and have started by making this code. However, it appears that the math that calculates the digit1 variable is never getting executed. Any thoughts? #include <iostream> #include <string> using namespace std; int main() { int qtyofnumbers, num, digit1, counter; char letters, upperlower; cout << "Enter a letter: "; cin >> letters; for (counter = 0; counter < 8; counter++) { if (counter == 3) cout << "-"; num = static_cast<int>(letters) - static_cast<int>('A'); if (0 <= num && num < 26) digit1 = (num / 3) + 2; if (((num / 3 == 6 ) || (num / 3 == 7)) && (num % 3 == 0)) digit1 = digit1-1; if (digit1 > 9) digit1 = 9; cin >> letters; } cout << digit1; return 0; } A: My guess is that the problem is in your input. Are you entering capital letters or lowercase letters? Their ASCII codes are different. So, you probably want to change the code from num= static_cast<int>(letters)-static_cast<int>('A'); to something like if (num >= 'a') num = letters - 'a'; else num = letters - 'A'; Also, as mentioned by @jtbandes, use the curly braces { and }. Whitespace does not determine scope in C++. Even if it's for only one line of code after your if-statement, it'll save you headaches in the future. A: Is the static cast necessary? I recommend using a string stream or just traversing the string character by character using .at() and relying on the ascii values for conversion. http://web.cs.mun.ca/~michael/c/ascii-table.html.
{ "language": "en", "url": "https://stackoverflow.com/questions/38383634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Where can I set path to make.exe on Windows? When I try run make from cmd-console on Windows, it runs Turbo Delphi's make.exe but I need MSYS's make.exe. There is no mention about Turbo Delphi in %path% variable, maybe I can change it to MSYS in registry? A: The path is in the registry but usually you edit through this interface: * *Go to Control Panel -> System -> System settings -> Environment Variables. *Scroll down in system variables until you find PATH. *Click edit and change accordingly. *BE SURE to include a semicolon at the end of the previous as that is the delimiter, i.e. c:\path;c:\path2 *Launch a new console for the settings to take effect. A: Or you can just run this PowerShell command to append extra folder to the existing path: $env:Path += ";C:\temp\terraform" A: To add a PERSISTENT path (eg one that's permanent), you can do this one-liner in PowerShell (adjust the last c:\apps\terraform part) Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value (((Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).path) + ";c:\apps\terraform" ) Alternatively, you can jump directly to the Environment Variables dialog by RUNning/CMD/PowerShell this: rundll32.exe sysdm.cpl,EditEnvironmentVariables A: Here I'm providing solution to setup Terraform environment variable in windows for beginners. * *Download the terraform ZIP file from Terraform site. *Extract the .exe from the ZIP file to a folder eg C:\Apps\Terraform copy this path location like C:\Apps\terraform\ *Add the folder location to your PATH variable, eg: Control Panel -> System -> System settings -> Environment Variables In System Variables, select Path > edit > new > Enter the location of the Terraform .exe, eg C:\Apps\Terraform then click OK *Open a new CMD/PowerShell and the Terraform command should work A: I had issues for a whilst not getting Terraform commands to run unless I was in the directory of the exe, even though I set the path correctly. For anyone else finding this issue, I fixed it by moving the environment variable higher than others! A: Why don't you create a bat file makedos.bat containing the following line? c:\DOS\make.exe %1 %2 %5 and put it in C:\DOS (or C:\Windowsè or make sure that it is in your %path%) You can run from cmd, SET and it displays all environment variables, including PATH. In registry you can find environment variables under: * *HKEY_CURRENT_USER\Environment *HKEY_CURRENT_USER\Volatile Environment *HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment A: just copy it to system32 call make1 or whatever if the name conflicts.
{ "language": "en", "url": "https://stackoverflow.com/questions/1618280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "59" }
Q: How to catch ajax error response? when i have an ajax error response with jquery i have the following log: jquery.js:8630 OPTIONS http://10.0.1.108:8000/api/v1.0/auth/ net::ERR_CONNECTION_REFUSED Object {readyState: 0, status: 0, statusText: "error"} In my object i have a property statusText: 'error', but no properties with 'net::ERR_CONNECTION_REFUSED'. I tried to log the responseText as see here Get server response with AJAX error? but my object didn't have this property; Do you know how i can get it in javascript please? Thank. A: You can't. Many errors, including most (if not all) status: 0 errors, are not exposed to JavaScript. They indicate network or same origin policy errors and exposing the details to JavaScript could leak information. For example, if it was possible to distinguish between "Connection Refused", "Post doesn't speak HTTP" and "No Access-Control-Allow-Origin header", then it would be trivial to write a page that would quietly map out all the webservers on the visitor's corporate network. That information could then be used for phishing attacks.
{ "language": "en", "url": "https://stackoverflow.com/questions/38057355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: sum of specific key for multiple similar keys in array of object - JavaScript I have an array of objects like the following: [ { 'Product': 'P1', 'Price': 150, 'Location': 1, }, { 'Product': 'P1', 'Price': 100, 'Location': 1, }, { 'Product': 'P1', 'Price': 200, 'Location': 2, }, { 'Product': 'P2', 'Price': 10, 'Location': 1, }, { 'Product': 'P2', 'Price': 130, 'Location': 1, }, { 'Product': 'P3', 'Price': 40, 'Location': 1, } ] I need to add up all the prices for objects with the same product and same location. For the example above the result would be: [ { 'Product': 'P1', 'Price': 250, // price is the sum of both similar in location and product 'Location': 1, }, { 'Product': 'P1', 'Price': 200, 'Location': 2, // same product but different location }, { 'Product': 'P2', 'Price': 140, //sum of same 'Location': 1, }, { 'Product': 'P3', 'Price': 40, 'Location': 1, }, ] I have searched several similar issues, but those were dealing with only one key to check for, I have different keys (product and location - may be more than 2 in the future) to identify as different. A: const input = [ { 'Product': 'P1', 'Price': 150, 'Location': 1, }, { 'Product': 'P1', 'Price': 100, 'Location': 1, }, { 'Product': 'P1', 'Price': 200, 'Location': 2, }, { 'Product': 'P2', 'Price': 10, 'Location': 1, }, { 'Product': 'P2', 'Price': 130, 'Location': 1, }, { 'Product': 'P3', 'Price': 40, 'Location': 1, } ] const output = [] input.forEach(item => { const index = output.findIndex(o => o.Product === item.Product && o.Location === item.Location); if (index === -1) { output.push(item); } else { output[index].Price += item.Price; } }); console.log(output); Without arrow function input.forEach(function(item) { const index = output.findIndex(function(o) { return o.Product === item.Product && o.Location === item.Location}); if (index === -1) { output.push(item); } else { output[index].Price += item.Price; } }); A: You can use reduce() to do that, obj = [ { 'Product': 'P1', 'Price': 250, // price is the sum of both similar in location and product 'Location': 1, }, { 'Product': 'P1', 'Price': 200, 'Location': 2, // same product but different location }, { 'Product': 'P2', 'Price': 140, //sum of same 'Location': 1, }, { 'Product': 'P3', 'Price': 40, 'Location': 1, }, ] res = obj.reduce((prev, curr) => { index = prev.findIndex(item => item.Product=== curr.Product && item.Location === curr.Location); if(index > -1) { prev[index].Price += curr.Price; } else { prev.push(curr); } return prev; }, []); console.log(res); A: Modifying @William's answer (Accepted) for my use case as it was to be run on the platform which was not supporting ES6 features (findIndex and arrow function), this can be done without findIndex as below; var input = [{ 'Product': 'P1', 'Price': 150, 'Location': 1, }, { 'Product': 'P1', 'Price': 100, 'Location': 1, }, { 'Product': 'P1', 'Price': 200, 'Location': 2, }, { 'Product': 'P2', 'Price': 10, 'Location': 1, }, { 'Product': 'P2', 'Price': 130, 'Location': 1, }, { 'Product': 'P3', 'Price': 40, 'Location': 1, } ] var output = [] input.forEach(function(item) { var index = output.indexOf(output.filter(function(o) { return o.Product === item.Product && o.Location === item.Location })[0]); // note the [0] index here if (index === -1) { output.push(item); } else { output[index].Price += item.Price; } }); console.log(output);
{ "language": "en", "url": "https://stackoverflow.com/questions/65624969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is gmailr not working in docker build process? I'm using the gmailr package for sending emails from a r script. Locally it's all working fine, but when I try to run this during a docker build step in google cloud I'm getting an error. I implemented it in the following way described here. So basically, locally the part of my code for sending emails looks like this: gm_auth_configure(path = "credentials.json") gm_auth(email = TRUE, cache = "secret") gm_send_message(buy_email) Please note, that I renamed the .secret folder to secret, because I want to deploy my script with docker in gcloud and didn't want to get any unexpected errors due to the dot in the folder name. This is the code, which I'm now trying to run in the cloud: setwd("/home/rstudio/") gm_auth_configure(path = "credentials.json") options( gargle_oauth_cache = "secret", gargle_oauth_email = "[email protected]" ) gm_auth(email = "[email protected]") When running this code in a docker build process, I'm receiving the following error: Error in gmailr_POST(c("messages", "send"), user_id, class = "gmail_message", : Gmail API error: 403 Request had insufficient authentication scopes. Calls: gm_send_message -> gmailr_POST -> gmailr_query I can reproduce the error locally, when I do not check the following box. Therefore my first assumption is, that the secret folder is not beeing pushed correctly in the docker build process and that the authentication tries to authenticate again, but in a non interactive-session the box can't be checked and the error is thrown. This is the part of the Dockerfile.txt, where I'm pushing the files and running the script: #2 ADD FILES TO LOCAL COPY . /home/rstudio/ WORKDIR /home/rstudio #3 RUN R SCRIPT CMD Rscript /home/rstudio/run_script.R and this is the folder, which contains all files / folders beeing pushed to the cloud. My second assumption is, that I have to somehow specify the scope to use google platform for my docker image, but unfortunately I'm no sure where to do that. I'd really appreciate any help! Thanks in advance! A: For anyone experiencing the same problem, I was finally able to find a solution. The problem is that GCE auth is set by the "gargle" package, instead of using the "normal user OAuth flow". To temporarily disable GCE auth, I'm using the following piece of code now: library(gargle) cred_funs_clear() cred_funs_add(credentials_user_oauth2 = credentials_user_oauth2) gm_auth_configure(path = "credentials.json") options( gargle_oauth_cache = "secret", gargle_oauth_email = "[email protected]" ) gm_auth(email = "email.which.was.used.for.credentials.com") cred_funs_set_default() For further references see also here.
{ "language": "en", "url": "https://stackoverflow.com/questions/74816801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asking for name again if the first name input doesn't match the second name input I would like to make a program that asks the user his name two times. If the two names are the same regardless of the case, it will print success. If the two names are not the same, it will ask the user again to input another set of names (2 names) and if it is now the same it will also print success. public static void main(String args[]) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter name: "); String one = input.readLine(); System.out.println("Enter name: "); String two = input.readLine(); if (one.equalsIgnoreCase(two)) { System.out.print("Success"); } else { System.out.println("Enter name: "); input.readLine(); System.out.println("Eneter name: "); input.readLine(); } } The part that checks if the two names are the same is fine. The part that I am confused is the code where it will ask for another set of 2 names else { System.out.println("Enter name: "); input.readLine(); System.out.println("Eneter name: "); input.readLine(); } Example output: Enter name: Mark Andrew Enter name: Mark Andrew Success Enter name: Mark Andrew Enter name: John Paul Enter name: Mark Andrew Enter name: Mark Andrew //this is the part that I am confused. It doesn't print success// I am open to opinions and suggestions. Thanks A: In the else part, you are not checking again if the names are the same or not. That's why it's not showing Success the next time when you gave the same names. Using a loop would be better if we want to take inputs until the same names are entered. public static void main(String args[]) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); boolean areNamesEqual = false; while(!areNamesEqual) { System.out.println("Enter name: "); String one = input.readLine(); System.out.println("Re-enter name: "); String two = input.readLine(); if (one.equalsIgnoreCase(two)) { areNamesEqual = true; } } System.out.print("Success"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/67443733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP foreach() loop $string = "The complete archive of The New York Times can now be searched from NYTimes.com " //the actual input is unknown, it would be read from textarea $size = the longest word length from the string I assigned and initialized array in for loop, for example array1, array2 ....arrayN, here is how i did for ($i = 1; $i <= $size; $i++) { ${"array" . $i} = array(); } so the $string would be divided in the length of the word $array1 = [""]; $array2 = ["of", "be", ...] $array3 = ["the", "can", "now", ...] and so on So, my question is how to assign in simple for loop or foreach loop $string value to $array1, $array2, $array3 ....., since the input text or the size of the longest word is unknown A: I'd probably start with $words = explode(' ', $string) then sort the string by word length usort($words, function($word1, $word2) { if (strlen($word1) == strlen($word2)) { return 0; } return (strlen($word1) < strlen($word2)) ? -1 : 1; }); $longestWordSize = strlen(last($words)); Loop over the words and place in their respective buckets. Rather than separate variables for each length array, you should consider something like $sortedWords = array( 1 => array('a', 'I'), 2 => array('to', 'be', 'or', 'is'), 3 => array('not', 'the'), ); by looping over the words you don't need to know the maximum word length. The final solution is as simple as foreach ($words as $word) { $wordLength = strlen($word); $sortedWords[ $wordLength ][] = $word; } A: You could use something like this: $words = explode(" ", $string); foreach ($words as $w) { array_push(${"array" . strlen($w)}, $w); } This splits up $string into an array of $words and then evaluates each word for length and pushes that word to the appropriate array. A: you can use explode(). $string = "The complete archive of The New York Times can now be searched from NYTimes.com " ; $arr=explode(" ",$string); $count=count($arr); $big=0; for ($i = 0; $i < $count; $i++) { $p=strlen($arr[$i]); if($big<$p){ $big_val=$arr[$i]; $big=$p;} } echo $big_val; A: Just use the word length as the index and append [] each word: foreach(explode(' ', $string) as $word) { $array[strlen($word)][] = $word; } To remove duplicates $array = array_map('array_unique', $array);. Yields: Array ( [3] => Array ( [0] => The [2] => New [3] => can [4] => now ) [8] => Array ( [0] => complete [1] => searched ) [7] => Array ( [0] => archive ) [2] => Array ( [0] => of [1] => be ) [4] => Array ( [0] => York ) [5] => Array ( [0] => Times ) ) If you want to re-index the main array use array_values() and to re-index the subarrays use array_map() with array_values().
{ "language": "en", "url": "https://stackoverflow.com/questions/35483795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting the size of single document in Mongodb? I am new to MongoDB and am trying to retrieve the size of a single document from a database. The database is named "enron" The collection is named "email" I tried: Object.bsonsize(db.email.findOne()) I also tried: Object.bsonsize(db.enron.findOne()) But it only returns 0. How can I get the size of a document? Thank you! A: Here is the related question How to get the size of a single document in MongoDB?
{ "language": "en", "url": "https://stackoverflow.com/questions/64589184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I run an MVC app and WCF Web Api on the same AppHarbor site? We have a solution with this structure. * *OurApp.Web (mvc 3 project with controllers, views) *OurApp.Api (mvc 3 project with wcf web api service classes) *OurApp.Domain (entities, repositories, unit of work, etc) *OurApp.Tests (tests) We want to use a dns structured like this: http://www.ourapp.com points to OurApp.Web http://api.ourapp.com points to OurApp.Api We want to host on AppHarbor. How can we do this? A: AppHarbor currently only supports deploying one application from any given repository. One option might be to fold the API into the web project. I did this for a non-web API WCF service here. Another option is to maintain two AppHarbor applications, and use solution files named according to what application you want deployed for that application. That is, OurApp.Web.sln contains the Web project and any supporting projects and, OurApp.Api.sln references the API project and any supporting projects. Read more about AppHarbor solution file convention. (disclaimer, I'm co-founder of AppHarbor)
{ "language": "en", "url": "https://stackoverflow.com/questions/7882660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Python variable not defined error I thought it would be cool to make a text-based adventure game. I am having a problem with a naming error in this block of code: elif room1_choice1=='Search the room': print('You have chosen to search the room') print("As you walk around the room you find a chest that you couldn't see from the doorway") print('You see only two choices, to attempt to open it or to search the rest of the room') print("Type 'Attempt to open' to try to open the chest or type 'Keep searching' to continue your search") room1_chestChoice=input(':') if room1_chestChoice=='Attempt to open': print('You heave at the lid with all your strength but fail to open it.') print('It looks like it is locked and you need a key') print("Type 'Keep searching' to try and find the key") room1_chestChoice=input(':') I get an error at the if in the middle: Traceback (most recent call last): File "C:/Users/maxim/PycharmProjects/APCSP project/Prototype 1.py", line 41, in <module> if room1_chestChoice=='Attempt to open': NameError: name 'room1_chestChoice' is not defined Can anyone help? A: room1_chestChoice is defined only if the previous choice, room1_choice1, was "search the room". Checking room1_chestChoice makes sense only in that case. Change your indentation to reflect your decision tree: elif room1_choice1=='Search the room': print('You have chosen to search the room') ... room1_chestChoice=input(':') if room1_chestChoice=='Attempt to open': print('You heave at the lid ... room1_chestChoice=input(':') That second if has to be entirely within the code dependent on the elif.
{ "language": "en", "url": "https://stackoverflow.com/questions/49519353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OneSignal Push Notifications Landing Page for manual subscribe and unsubscribe i would like to know if its possible to have a manual subscribe/unsubscribe page for the onesignal web push service next to a existing wordpress setup. Currently i have created one app id working for the blog on https://example.com and https://www.example.com Now is there a way to build a landing page for e.g at https://www.example.com/push-landing where users subscribe/unscribe for the same App ID ? So all notifications sent through the blog keeps getting recieved by users manual subscribed on the landing page? The code below seems to work only for Safari yet, any idea why its not working on chrome/firefox? <!DOCTYPE html> <html> <head> <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script> <script> var useragentid = null; var OneSignal = window.OneSignal || []; OneSignal.push(["init", { appId: "e98e261d-b951-4335-accd-04887176b432", autoRegister: false, notifyButton: { enable: false }, persistNotification: false }]); //Firstly this will check user id OneSignal.push(function() { OneSignal.getUserId().then(function(userId) { if(userId == null){ document.getElementById('unsubscribe').style.display = 'none'; } else{ useragentid = userId; document.getElementById('unsubscribe').style.display = ''; OneSignal.push(["getNotificationPermission", function(permission){ }]); OneSignal.isPushNotificationsEnabled(function(isEnabled) { if (isEnabled){ document.getElementById('unsubscribe').style.display = ''; document.getElementById('subscribe').style.display = 'none'; } else{ document.getElementById('unsubscribe').style.display = 'none'; document.getElementById('subscribe').style.display = ''; } }); } }); }); //Secondly this will check when subscription changed OneSignal.push(function() { OneSignal.on('subscriptionChange', function (isSubscribed) { if(isSubscribed==true){ OneSignal.getUserId().then(function(userId) { useragentid = userId; }).then(function(){ // this is custom function // here you can send post request to php file as well. OneSignalUserSubscription(useragentid); }); document.getElementById('unsubscribe').style.display = ''; document.getElementById('subscribe').style.display = 'none'; } else if(isSubscribed==false){ OneSignal.getUserId().then(function(userId) { useragentid = userId; }); document.getElementById('unsubscribe').style.display = 'none'; document.getElementById('subscribe').style.display = ''; } else{ console.log('Unable to process the request'); } }); }); function subscribeOneSignal(){ if(useragentid !=null){ OneSignal.setSubscription(true); } else{ OneSignal.registerForPushNotifications({ modalPrompt: true }); } } function unSubscribeOneSignal(){ OneSignal.setSubscription(false); } </script> </head> <div id="home-top" class="clearfix"> <p>Push Notifications</p> <br> <button id="subscribe" class="button" onclick="subscribeOneSignal()">Subscribe </button> <button id="unsubscribe" class="button" onclick="unSubscribeOneSignal()">Unsubscribe </button> </div> <style> .button { background-color: #008CBA;border: none;color: white;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;cursor: pointer; } </style> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/45391524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Concatenate strings for variable identifier in PHP I know this is not the proper way to do this, however I am trying to put a quick fix on a form that was done by another developer. Basically I want to add an incremental number to a variable inside a while statement: $count = 1; while ($r = mysql_fetch_array($query)) { $variable . $count = $r['somefield']; $count++ } So that makes the variables: $variable1 $variable2 $variable3 ....etc A: $varname = 'variable' . $count; $$varname = $r['somefield']; http://www.php.net/manual/en/language.variables.variable.php A: You'd be better off with an array... $variable[] = $r['somefield']; You can use variable variables, however it is probably not a good idea, especially for a trivial case like this one.
{ "language": "en", "url": "https://stackoverflow.com/questions/10987614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Replace conditional with polymorphism refactoring or similar? I have tried to ask a variant of this question before. I got some helpful answers, but still nothing that felt quite right to me. It seems to me this shouldn't really be that hard a nut to crack, but I'm not able to find an elegant simple solution. (Here's my previous post, but please try to look at the problem stated here as procedural code first so as not to be influenced by the earlier explanation which seemed to lead to very complicated solutions: Design pattern for cost calculator app? ) Basically, the problem is to create a calculator for hours needed for projects that can contain a number of services. In this case "writing" and "analysis". The hours are calculated differently for the different services: writing is calculated by multiplying a "per product" hour rate with the number of products, and the more products are included in the project, the lower the hour rate is, but the total number of hours is accumulated progressively (i.e. for a medium-sized project you take both the small range pricing and then add the medium range pricing up to the number of actual products). Whereas for analysis it's much simpler, it is just a bulk rate for each size range. How would you be able to refactor this into an elegant and preferably simple object-oriented version (please note that I would never write it like this in a purely procedural manner, this is just to show the problem in another way succinctly). I have been thinking in terms of factory, strategy and decorator patterns, but can't get any to work well. (I read Head First Design Patterns a while back, and both the decorator and factory patterns described have some similarities to this problem, but I have trouble seeing them as good solutions as stated there. The decorator example seemed very complicated there for just adding condiments, but maybe it could work better here, I don't know. At least the fact that the calculation of hours accumulates progressively made me think of the decorator pattern... And the factory pattern example from the book with the pizza factory...well it just seems to create such a ridiculous explosion of classes, at least in their example. I have found good use for factory patterns before, but I can't see how I could use it here without getting a really complicated set of classes) The main goal would be to only have to change in one place (loose coupling etc) if I were to add a new parameter (say another size, like XSMALL, and/or another service, like "Administration"). Here's the procedural code example: public class Conditional { private int _numberOfManuals; private string _serviceType; private const int SMALL = 2; private const int MEDIUM = 8; public int GetHours() { if (_numberOfManuals <= SMALL) { if (_serviceType == "writing") return 30 * _numberOfManuals; if (_serviceType == "analysis") return 10; } else if (_numberOfManuals <= MEDIUM) { if (_serviceType == "writing") return (SMALL * 30) + (20 * _numberOfManuals - SMALL); if (_serviceType == "analysis") return 20; } else //i.e. LARGE { if (_serviceType == "writing") return (SMALL * 30) + (20 * (MEDIUM - SMALL)) + (10 * _numberOfManuals - MEDIUM); if (_serviceType == "analysis") return 30; } return 0; //Just a default fallback for this contrived example } } All replies are appreciated! (But as I stated in my previous posts I would appreciate actual code examples rather than just "Try this pattern", because as I mentioned, that is what I'm having trouble with...) I hope someone has a really elegant solution to this problem that I actually thought from the beginning would be really simple... ======================================================== NEW ADDITION: I appreciate all the answers so far, but I'm still not seeing a really simple and flexible solution to the problem (one I thought wouldn't be very complex at first, but apparently is). It may also be that I haven't quite understood each answer correctly yet. But I thought I'd post my current attempt at working it out (with some help from reading all the different angles in answers here). Please tell me if I'm on the right track or not. But at least now it feels like it's starting to get more flexible... I can quite easily add new parameters without having to change in lots of places (I think!), and the conditional logic is all in one place. I have some of it in xml to get the basic data, which simplifies part of the problem, and part of it is an attempt at a strategy type solution. Here's the code: public class Service { protected HourCalculatingStrategy _calculatingStrategy; public int NumberOfProducts { get; set; } public const int SMALL = 3; public const int MEDIUM = 9; public const int LARGE = 20; protected string _serviceType; protected Dictionary<string, decimal> _reuseLevels; protected Service(int numberOfProducts) { NumberOfProducts = numberOfProducts; } public virtual decimal GetHours() { decimal hours = _calculatingStrategy.GetHours(NumberOfProducts, _serviceType); return hours; } } public class WritingService : Service { public WritingService(int numberOfProducts) : base(numberOfProducts) { _calculatingStrategy = new VariableCalculatingStrategy(); _serviceType = "writing"; } } class AnalysisService : Service { public AnalysisService(int numberOfProducts) : base(numberOfProducts) { _calculatingStrategy = new FixedCalculatingStrategy(); _serviceType = "analysis"; } } public abstract class HourCalculatingStrategy { public abstract int GetHours(int numberOfProducts, string serviceType); protected int GetHourRate(string serviceType, Size size) { XmlDocument doc = new XmlDocument(); doc.Load("calculatorData.xml"); string result = doc.SelectSingleNode(string.Format("//*[@type='{0}']/{1}", serviceType, size)).InnerText; return int.Parse(result); } protected Size GetSize(int index) { if (index < Service.SMALL) return Size.small; if (index < Service.MEDIUM) return Size.medium; if (index < Service.LARGE) return Size.large; return Size.xlarge; } } public class VariableCalculatingStrategy : HourCalculatingStrategy { public override int GetHours(int numberOfProducts, string serviceType) { int hours = 0; for (int i = 0; i < numberOfProducts; i++) { hours += GetHourRate(serviceType, GetSize(i + 1)); } return hours; } } public class FixedCalculatingStrategy : HourCalculatingStrategy { public override int GetHours(int numberOfProducts, string serviceType) { return GetHourRate(serviceType, GetSize(numberOfProducts)); } } And a simple example form that calls it (I guess I could also have a wrapper Project class with a Dictionary containing the Service objects, but I haven't gotten to that): public partial class Form1 : Form { public Form1() { InitializeComponent(); List<int> quantities = new List<int>(); for (int i = 0; i < 100; i++) { quantities.Add(i); } comboBoxNumberOfProducts.DataSource = quantities; } private void CreateProject() { int numberOfProducts = (int)comboBoxNumberOfProducts.SelectedItem; Service writing = new WritingService(numberOfProducts); Service analysis = new AnalysisService(numberOfProducts); labelWriterHours.Text = writing.GetHours().ToString(); labelAnalysisHours.Text = analysis.GetHours().ToString(); } private void comboBoxNumberOfProducts_SelectedIndexChanged(object sender, EventArgs e) { CreateProject(); } } (I wasn't able to include the xml because it got automatically formatted on this page, but it's basically just a bunch of elements with each service type, and each service type containing the sizes with the hour rates as values.) I'm not sure if I'm just pushing the problem over to the xml file (I'd still have to add new elements for each new servicetype, and add elements for any new size in each servicetype if that changed.) But maybe it's impossible to achieve what I am trying to do and not having to do at least that type of change. Using a database rather than xml the change would be as simple as adding a field and a row: ServiceType Small Medium Large Writing 125 100 60 Analysis 56 104 200 (Simply formatted as a "table" here, although the columns aren't quite aligned... I'm not the best at database design though, and maybe it should be done differently, but you get the idea...) Please tell me what you think! A: I would tend to start with an enumeration ProjectSize {Small, Medium, Large} and a simple function to return the appropriate enum given a numberOfManuals. From there, I would write different ServiceHourCalculators, the WritingServiceHourCalculator and the AnalysisServiceHourCalculator (because their logic is sufficiently different). Each would take a numberOfManuals, a ProjectSize, and return the number of hours. I'd probably create a map from string to ServiceHourCalculator, so I could say: ProjectSize projectSize = getProjectSize(_numberOfManuals); int hours = serviceMap.getService(_serviceType).getHours(projectSize, _numberOfManuals); This way, when I added a new project size, the compiler would balk at some unhandled cases for each service. It's not all handled in one place, but it is all handled before it will compile again, and that's all I need. Update I know Java, not C# (very well), so this may not be 100% right, but creating the map would be something like this: Map<String, ServiceHourCalculator> serviceMap = new HashMap<String, ServiceHourCalculator>(); serviceMap.put("writing", new WritingServiceHourCalculator()); serviceMap.put("analysis", new AnalysisServiceHourCalculator()); A: A good start would be to extract the conditional statement into a method(although only a small method) and give it a really explicit name. Then extract the logic within the if statement into their own methods - again with really explicit names. (Don't worry if the method names are long - as long as they do what they're called) I would write this out in code but it would be better for you to pick names. I would then move onto more complicated refactoring methods and patterns. Its only when your looking at a series of method calls will it seem appropriate to start applying patterns etc.. Make your first goal to write clean, easy to read and comprehend code. It is easy to get excited about patterns (speaking from experience) but they are very hard to apply if you can't describe your existing code in abstractions. EDIT: So to clarify - you should aim to get your if statement looking like this if( isBox() ) { doBoxAction(); } else if( isSquirrel() ) { doSquirrelAction(); } Once you do this, in my opinion, then it is easier to apply some of the patterns mentioned here. But once you still have calculatios etc... in your if statement, then it is harder to see the wood from the trees as you are at too low of an abstraction. A: You don't need the Factory if your subclasses filter themselves on what they want to charge for. That requires a Project class to hold the data, if nothing else: class Project { TaskType Type { get; set; } int? NumberOfHours { get; set; } } Since you want to add new calculations easily, you need an interface: IProjectHours { public void SetHours(IEnumerable<Project> projects); } And, some classes to implement the interface: class AnalysisProjectHours : IProjectHours { public void SetHours(IEnumerable<Project> projects) { projects.Where(p => p.Type == TaskType.Analysis) .Each(p => p.NumberOfHours += 30); } } // Non-LINQ equivalent class AnalysisProjectHours : IProjectHours { public void SetHours(IEnumerable<Project> projects) { foreach (Project p in projects) { if (p.Type == TaskType.Analysis) { p.NumberOfHours += 30; } } } } class WritingProjectHours : IProjectHours { public void SetHours(IEnumerable<Project> projects) { projects.Where(p => p.Type == TaskType.Writing) .Skip(0).Take(2).Each(p => p.NumberOfHours += 30); projects.Where(p => p.Type == TaskType.Writing) .Skip(2).Take(6).Each(p => p.NumberOfHours += 20); projects.Where(p => p.Type == TaskType.Writing) .Skip(8).Each(p => p.NumberOfHours += 10); } } // Non-LINQ equivalent class WritingProjectHours : IProjectHours { public void SetHours(IEnumerable<Project> projects) { int writingProjectsCount = 0; foreach (Project p in projects) { if (p.Type != TaskType.Writing) { continue; } writingProjectsCount++; switch (writingProjectsCount) { case 1: case 2: p.NumberOfHours += 30; break; case 3: case 4: case 5: case 6: case 7: case 8: p.NumberOfHours += 20; break; default: p.NumberOfHours += 10; break; } } } } class NewProjectHours : IProjectHours { public void SetHours(IEnumerable<Project> projects) { projects.Where(p => p.Id == null).Each(p => p.NumberOfHours += 5); } } // Non-LINQ equivalent class NewProjectHours : IProjectHours { public void SetHours(IEnumerable<Project> projects) { foreach (Project p in projects) { if (p.Id == null) { // Add 5 additional hours to each new project p.NumberOfHours += 5; } } } } The calling code can either dynamically load IProjectHours implementors (or static them) and then just walk the list of Projects through them: foreach (var h in AssemblyHelper.GetImplementors<IProjectHours>()) { h.SetHours(projects); } Console.WriteLine(projects.Sum(p => p.NumberOfHours)); // Non-LINQ equivalent int totalNumberHours = 0; foreach (Project p in projects) { totalNumberOfHours += p.NumberOfHours; } Console.WriteLine(totalNumberOfHours); A: this is a common problem, there are a few options that i can think of. There are two design pattern that come to mind, firstly the Strategy Pattern and secondly the Factory Pattern. With the strategy pattern it is possible to encapsulate the calculation into an object, for example you could encapsulate your GetHours method into individual classes, each one would represent a calculation based on size. Once we have defined the different calculation strategies we wrap then in a factory. The factory would be responsible for selecting the strategy to perform the calculation just like your if statement in the GetHours method. Any way have a look at the code below and see what you think At any point you could create a new strategy to perform a different calculation. The strategy can be shared between different objects allowing the same calculation to be used in multiple places. Also the factory could dynamically work out which strategy to use based on configuration, for example class Program { static void Main(string[] args) { var factory = new HourCalculationStrategyFactory(); var strategy = factory.CreateStrategy(1, "writing"); Console.WriteLine(strategy.Calculate()); } } public class HourCalculationStrategy { public const int Small = 2; public const int Medium = 8; private readonly string _serviceType; private readonly int _numberOfManuals; public HourCalculationStrategy(int numberOfManuals, string serviceType) { _serviceType = serviceType; _numberOfManuals = numberOfManuals; } public int Calculate() { return this.CalculateImplementation(_numberOfManuals, _serviceType); } protected virtual int CalculateImplementation(int numberOfManuals, string serviceType) { if (serviceType == "writing") return (Small * 30) + (20 * (Medium - Small)) + (10 * numberOfManuals - Medium); if (serviceType == "analysis") return 30; return 0; } } public class SmallHourCalculationStrategy : HourCalculationStrategy { public SmallHourCalculationStrategy(int numberOfManuals, string serviceType) : base(numberOfManuals, serviceType) { } protected override int CalculateImplementation(int numberOfManuals, string serviceType) { if (serviceType == "writing") return 30 * numberOfManuals; if (serviceType == "analysis") return 10; return 0; } } public class MediumHourCalculationStrategy : HourCalculationStrategy { public MediumHourCalculationStrategy(int numberOfManuals, string serviceType) : base(numberOfManuals, serviceType) { } protected override int CalculateImplementation(int numberOfManuals, string serviceType) { if (serviceType == "writing") return (Small * 30) + (20 * numberOfManuals - Small); if (serviceType == "analysis") return 20; return 0; } } public class HourCalculationStrategyFactory { public HourCalculationStrategy CreateStrategy(int numberOfManuals, string serviceType) { if (numberOfManuals <= HourCalculationStrategy.Small) { return new SmallHourCalculationStrategy(numberOfManuals, serviceType); } if (numberOfManuals <= HourCalculationStrategy.Medium) { return new MediumHourCalculationStrategy(numberOfManuals, serviceType); } return new HourCalculationStrategy(numberOfManuals, serviceType); } } A: I would go with a strategy pattern derivative. This adds additional classes, but is more maintainable over the long haul. Also, keep in mind that there are still opporunities for refactoring here: public class Conditional { private int _numberOfManuals; private string _serviceType; public const int SMALL = 2; public const int MEDIUM = 8; public int NumberOfManuals { get { return _numberOfManuals; } } public string ServiceType { get { return _serviceType; } } private Dictionary<int, IResult> resultStrategy; public Conditional(int numberOfManuals, string serviceType) { _numberOfManuals = numberOfManuals; _serviceType = serviceType; resultStrategy = new Dictionary<int, IResult> { { SMALL, new SmallResult() }, { MEDIUM, new MediumResult() }, { MEDIUM + 1, new LargeResult() } }; } public int GetHours() { return resultStrategy.Where(k => _numberOfManuals <= k.Key).First().Value.GetResult(this); } } public interface IResult { int GetResult(Conditional conditional); } public class SmallResult : IResult { public int GetResult(Conditional conditional) { return conditional.ServiceType.IsWriting() ? WritingResult(conditional) : AnalysisResult(conditional); ; } private int WritingResult(Conditional conditional) { return 30 * conditional.NumberOfManuals; } private int AnalysisResult(Conditional conditional) { return 10; } } public class MediumResult : IResult { public int GetResult(Conditional conditional) { return conditional.ServiceType.IsWriting() ? WritingResult(conditional) : AnalysisResult(conditional); ; } private int WritingResult(Conditional conditional) { return (Conditional.SMALL * 30) + (20 * conditional.NumberOfManuals - Conditional.SMALL); } private int AnalysisResult(Conditional conditional) { return 20; } } public class LargeResult : IResult { public int GetResult(Conditional conditional) { return conditional.ServiceType.IsWriting() ? WritingResult(conditional) : AnalysisResult(conditional); ; } private int WritingResult(Conditional conditional) { return (Conditional.SMALL * 30) + (20 * (Conditional.MEDIUM - Conditional.SMALL)) + (10 * conditional.NumberOfManuals - Conditional.MEDIUM); } private int AnalysisResult(Conditional conditional) { return 30; } } public static class ExtensionMethods { public static bool IsWriting(this string value) { return value == "writing"; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/2792136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How do I encode URI parameter values? I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input: http://google.com/resource?key=value1 & value2 I expect the output: http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value2 Neither java.net.URLEncoder nor java.net.URI will generate the right output. URLEncoder is meant for HTML form encoding which is not the same as RFC 2396. URI has no mechanism for encoding a single value at a time so it has no way of knowing that value1 and value2 are part of the same key. A: I don't have enough reputation to comment on answers, but I just wanted to note that downloading the JSR-311 api by itself will not work. You need to download the reference implementation (jersey). Only downloading the api from the JSR page will give you a ClassNotFoundException when the api tries to look for an implementation at runtime. A: Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded. A: I wrote my own, it's short, super simple, and you can copy it if you like: http://www.dmurph.com/2011/01/java-uri-encoder/ A: You could also use Spring's UriUtils A: It seems that CharEscapers from Google GData-java-client has what you want. It has uriPathEscaper method, uriQueryStringEscaper, and generic uriEscaper. (All return Escaper object which does actual escaping). Apache License. A: I think that the URI class is the one that you are looking for. A: Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try. You said: For example, given an input: http://google.com/resource?key=value I expect the output: http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue So: C:\oreyes\samples\java\URL>type URLEncodeSample.java import java.net.*; public class URLEncodeSample { public static void main( String [] args ) throws Throwable { System.out.println( URLEncoder.encode( args[0], "UTF-8" )); } } C:\oreyes\samples\java\URL>javac URLEncodeSample.java C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value" http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue As expected. What would be the problem with this?
{ "language": "en", "url": "https://stackoverflow.com/questions/444112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "57" }
Q: Comparing Long values using Collections.sort(object) I'm trying to sort a simple list of objects by a long - the below isn't working because one of the long strings is pushed to the top simply because it starts with a lower number. So I'm looking for a way to sort these by the actual long values directly The current obj implementation looks something like the below. In the class I'm using this I call Collections.sort(trees); public class Tree implements Comparable<Tree> { public String dist; //value is actually Long public int compareTo(Tree o) { return this.dist.compareTo(o.dist); } } A: Just an example I made for sorting Files by date using a Long comparator: public File[] getAllFoldersByDescendingDate(File folder) { if (!folder.isDirectory()) { return null; } allFiles = folder.listFiles(); Arrays.sort(allFiles, new Comparator<File>() { public int compare(final File o1, final File o2) { return Long.compare(o2.lastModified(), o1.lastModified()); } }); return allFiles; } A: Long.compare( x , y ) If you have an object that you want to sort on a long value, and it implements Comparable, in Java 7+ you can use Long.compare(long x, long y) (which returns an int) E.g. public class MyObject implements Comparable<MyObject> { public long id; @Override public int compareTo(MyObject obj) { return Long.compare(this.id, obj.id); } } Call Collections.sort(my_objects) where my_objects is something like List<MyObject> my_objects = new ArrayList<MyObject>(); // + some code to populate your list A: It depends on how you want to do things? Do you want to keep the current implementation of Comparable? If yes, use the sort method which takes a Comparator and implement a custom comparator which uses the actual "long" values of the string (Long.parseLong(dist)). If no, then just modify the current compareTo and use the Long values of the "dist". BTW, I'd revisit the logic and ask myself why "dist" is of type String when it is actually a Long? A: why not actually store a long in there: public class Tree implements Comparable<Tree> { public long dist; //value is actually Long public int compareTo(Tree o) { return this.dist<o.dist?-1: this.dist>o.dist?1:0; } } that or first compare the length of the strings and then compare them public String dist; //value is actually Long public int compareTo(Tree o) { if(this.dist.length()!=o.dist.length()) return this.dist.length()<o.dist.length()?-1:1;//assume the shorter string is a smaller value else return this.dist.compareTo(o.dist); } A: well if the dist variable is actually long then you might try using public int compareTo(Tree o) { return Long.valueOf(this.dist).compareTo(Long.valueOf(o.dist)); } A: Why not public class Tree implements Comparable<Tree> { public Long dist; public int compareTo(Tree o) { return this.dist.compareTo(o.dist); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/6176019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Register php to sql server Postman when executing my register.php method and verifying it by POSTMAN I do not get any results, and when verifying in my preuse table of my SQL database I do not see any saved record. This is my code register.php try { $dbh = new PDO("sqlsrv:Server=$host,1433; Database=$dbname", $user, $password); if( $dbh === false ) { die( print_r( sqlsrv_errors(), true)); } $json=file_get_contents('php://input'); $data=json_decode($json); $stm = $dbh->query("INSERT INTO AUT_APP_PREUSO (IDPERSONAL,IDVEHICULO,IDPREGUNTAS,RESPSI,RESPNO,RESPNA,RESPIVSS,RESPDSS,RESPFM,RESPFS,OBSERVACION,FIRMA,FECHAREGISTRO,IDDISPOSITIVO,NOMBREDISPOSITIVO) VALUES ('".$data->{'idper'}."', '".$data->{'idveh'}."', '".$data->{'idpre'}."', '".$data->{'respsi'}."', '".$data->{'respno'}."', '".$data->{'respna'}."', '".$data->{'respivss'}."', '".$data->{'respdss'}."', '".$data->{'respfm'}."', '".$data->{'respfs'}."', '".$data->{'obs'}."', '".$data->{'freg'}."', '".$data->{'iddisp'}."', '".$data->{'nombdis'}."') "); if( $stm === false) { die( print_r( sqlsrv_errors(), true) ); } $stmt->execute(); $res=$stm-> fetch(PDO::FETCH_ASSOC); if(!$res) $mensaje="ERROR"; else $mensaje="GRABADO"; sqlsrv_free_result($res); sqlsrv_close($dbh); header('Content-type: application/json'); $response = array("resultado" => $mensaje); echo json_encode($response); } catch(PDOException $e) { die("Database connection failed: " . $e->getMessage()); exit; }
{ "language": "en", "url": "https://stackoverflow.com/questions/73665376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why would it be impossible to mannually test AES algorithm? I have this teacher who asked to study AES encryption algorithm, a C code implementation and do a bench testing of it. So, I've not even tried to do a calculation of the number of steps it would take, but rather I'd like to have these rational reasons why a human can´t or might not go for it. A: There is enough scope for misunderstanding and ambiguity in a cryptographic algorithm that it is standard practice to release example inputs and outputs (test vectors) with the specification of the algorithm, so you don't have to work through the algorithm by hand. There appear to be test vectors in the specfication at http://csrc.nist.gov/groups/STM/cavp/. In fact, appendix B of fips-197.pdf appears to show how the state table evolves during a single encryption. Of course, for a system like AES, where it is not practical to test every possible input and key, you can always argue that while testing can find errors it can never prove the absence of errors. A: Anything a computer can do - you can do as well.... they don't use magic for calculation. To test your algorithm, you should encrypt a small text and than decrypt and see that you get the same results (it will prove the algorithm works, it won't prove it's AES....)
{ "language": "en", "url": "https://stackoverflow.com/questions/17584770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: msvc++ doesn't see overloaded operator<< I'm porting a piece of code which was written for Linux and compiled with gcc v4.8.2 (using -std=c++11) to Windows. Part of it is an overloaded operator<< which MSVC++ 2013 doesn't agree with. A condensed example is below. We've defined a custom stream class which supports the standard stream manipulator functions. For this reason we've overloaded operator<< which accepts a function pointer as second argument. If I define a templated overload of operator<< for . MSVC++ complains: error C2676: binary '<<' : 'foobar' does not define this operator or a conversion to a type acceptable to the predefined operator But if I specify the type of the second argument as std::ostream instead of the templated std::basis_ostream<..,..> the code works as expected. At first I thought I had messed up the template arguments. However, if I define an arbitrary template function instead of an overload of operator<< the code compiles fine. What's going on here? Example #include "stdafx.h" #include <iostream> #include <sstream> #include <string> struct foobar { std::stringstream s_; }; /* Causes compiler error C2676 template <typename CharT = char, typename Traits = std::char_traits<CharT> > foobar& operator<<(foobar& foo, std::basic_ostream<CharT, Traits>& (*manip)(std::basic_ostream<CharT, Traits>&)) { foo.s_ << manip; return foo; } */ /* works as intendend */ foobar& operator<<(foobar& foo, std::ostream& (*manip)(std::ostream&)) { foo.s_ << manip; return foo; } /* works too */ template <typename CharT = char, typename Traits = std::char_traits<CharT> > foobar& qux(foobar& foo, std::basic_ostream<CharT, Traits>& (*manip)(std::basic_ostream<CharT, Traits>&)) { foo.s_ << manip; return foo; } int _tmain(int argc, _TCHAR* argv[]) { foobar foo; foo << std::endl; qux(foo, std::endl); return 0; } A: There appears to be some kind of bug with default arguments, overloaded operators, and template function parameter overload resolution. These are all complex, so sort of understandable. The good news is that you shouldn't be taking just any iomanip there -- you should be taking a specific one. You can either hard code it, or deduce it like so: // Get the nth type from a template instance: template<class...>struct types{using type=types;}; template<class T, size_t N> struct nth{}; template<class T, size_t N> using nth_t=typename nth<T,N>::type; template<template<class...>class Z, class T0, class...Ts, size_t N> struct nth<Z<T0,Ts...>,N>:nth<types<Ts...>,N-1>{}; template<template<class...>class Z, class T0, class...Ts> struct nth<Z<T0,Ts...>,0>{using type=T0;}; // From a String type, produce a compatible basic_stream type: template<class String> using compat_stream = std::basic_ostream<nth_t<String,0>, nth_t<String,1>>; // From a type T, produce a signature of a function pointer that // pass-through manipulates it: template<class T> using manip_f = T&(*)(T&); // From a String type, produce a compatible io-manipulator: template<class String> using io_manip_f = manip_f< compat_stream<String> >; // The return of foobar: struct foobar { std::stringstream s_; // the type of manipulators that is compatible with s_: using manip_f = io_manip_f<std::stringstream> manip; // a Koenig operator<<: friend foobar& operator<<( foobar& self, manip_f manip ) { self.s_ << manip; return self; } };
{ "language": "en", "url": "https://stackoverflow.com/questions/30531565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What are pipe and tap methods in Angular tutorial? I'm following the tutorial at https://angular.io, and I'm having trouble finding documentation; specifically for the methods pipe and tap. I can't find anything on https://angular.io or http://reactivex.io/rxjs/. My understanding is that pipe and tap are both methods of Observable, which is being imported from RxJS, correct? What are they supposed to do? Are these methods part of Angular? What do these two methods do? A: You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators: /** * Used to stitch together functional operators into a chain. * @method pipe * @return {Observable} the Observable result of all of the operators having * been called in the order they were passed in. * * @example * * import { map, filter, scan } from 'rxjs/operators'; * * Rx.Observable.interval(1000) * .pipe( * filter(x => x % 2 === 0), * map(x => x + x), * scan((acc, x) => acc + x) * ) * .subscribe(x => console.log(x)) */ In brief: Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above). Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().
{ "language": "en", "url": "https://stackoverflow.com/questions/47275385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "178" }
Q: How to store continuous user input in an array? For example: user input: 12345 then each integer will be placed inside an array. int[] arr = { 1, 2, 3, 4, 5 }; A: You can try some variation on the following //get user input as a string and convert to integer array int[] num = "12345".Select(a => Int32.Parse(a.ToString())).ToArray(); A: Try this way string str1 = "123456"; int[] arr = new int[str1.Length]; for (int ctr = 0; ctr <= str1.Length - 1; ctr++) { arr[ctr] = Convert.ToInt16(str1[ctr].ToString()); } Demo result: Take a look at Page load event code only.... :p Cheers A: String input="123456"; int [] intArray=new int[input.Length]; int count=0; foreach(var ch in input) { intArray[count]=Convert.ToInt32(ch.ToString()); count++; }
{ "language": "en", "url": "https://stackoverflow.com/questions/21950466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: SQL Server: Find words in string that don't exist in dictionary Consider the following tables: DROP TABLE IF EXISTS ##tableA; CREATE TABLE ##tableA (id int,keywords VARCHAR(MAX)); INSERT INTO ##tableA (id,keywords) VALUES (1,'apple,orange,potato'), (2,'I typed a sentence here because I can''t follow directions.'), (3,'potato and apple'); DROP TABLE IF EXISTS ##dictionary; CREATE TABLE ##dictionary (id int,keyword VARCHAR(255)); INSERT INTO ##dictionary (id,keyword) VALUES (1,'apple'), (2,'orange'), (3,'lemon'), (4,'potato'); We have users entering keywords into the keyword column in tableA. I want return the id of any record that contains a word not in ##dictionary. In the case above: - id 1 would not be returned because each comma separated keyword is found in the dictionary - id 2 would be returned because it contains words that are not in the dictionary - id 3 would be returned because it contains the word "and", which is not in the dictionary The ideal situation I think would somehow break up the keywords column from ##tableA into individual keywords, then check each of them against the keyword column in ##dictionary. A: Here is an inline approach Example Select Distinct A.* From ##tableA A Cross Apply ( Select RetSeq = Row_Number() over (Order By (Select null)) ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)'))) From (Select x = Cast('<x>' + replace((Select replace(replace(A.KeyWords,',',' '),' ','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A Cross Apply x.nodes('x') AS B(i) ) B Left Join ##dictionary C on B.RetVal=C.keyword Where C.keyWord is null Returns id keywords 2 I typed a sentence here because I can't follow directions. 3 potato and apple Just another BRUTE FORCE OPTION - Just for fun Declare @S varchar(max) = (Select * From ##tableA For XML Raw ) Select @S = replace(@S,keyword,'') From ##dictionary Select id = B.i.value('@id', 'int') From (Select x = Cast(@S as xml).query('.')) as A Cross Apply x.nodes('row') AS B(i) Where B.i.value('@keywords', 'varchar(max)') like '%[a-z]%' A: Under SQL Server 2017, you can use STRING_SPLIT: SELECT id FROM ##tableA CROSS APPLY STRING_SPLIT(keywords, ' ') splitBySpace CROSS APPLY STRING_SPLIT(splitBySpace.value, ',') splitBySpaceOrComma WHERE splitBySpaceOrComma.value NOT IN (SELECT keyword FROM ##dictionary) GROUP BY id; A: Using: Splitter you can split lines by delimiter then use the result to match against the dictionary. like this: SELECT t.keywords FROM ##tablea t CROSS APPLY (SELECT REPLACE(t.keywords, ' and ', ',')) new(kwds) CROSS APPLY dbo.DelimitedSplit8K(new.kwds, ',') s WHERE s.item NOT IN (SELECT keyword FROM ##dictionary) A: Try this: select t.* from ##tableA t cross join ( select max(case when id = 1 then keyword end) firstKeyword, max(case when id = 2 then keyword end) secondKeyword, max(case when id = 3 then keyword end) thirdKeyword, max(case when id = 4 then keyword end) fourthKeyword from ##dictionary ) d where len(replace(replace(replace(replace(replace(replace(keywords, firstKeyword, ''), secondKeyword, ''), thirdKeyword, ''), fourthKeyword, ''), ' ', ''), ',', '')) > 0 First, you need to pivot your data from ##dictionary, then you can replace your keywords with '' as well as spaces and commas, and see in the end if the are any characters left.
{ "language": "en", "url": "https://stackoverflow.com/questions/51899917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }