text
stringlengths
15
59.8k
meta
dict
Q: embed hyperlinks in a subliime text file One cool thing about Google Docs is that you can highlight a word, hit command-K (on a mac) and, hey presto, turn that word into a hyperlink. One cool thing about Sublime Text is that it is better than Google Docs in every other way. My humble opinion. Question: are there any plugins for ST that let you embed clickable hyperlinks into words? Specifically I want to do this for markdown files.
{ "language": "en", "url": "https://stackoverflow.com/questions/38958171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can pass this regular expression in C# ?about"[]" mean I have the following regular expression: ^[A-Z&&[^EIOSTUYZ]][X|0-9&&[^4-6]][A-F[NWX]].?.?$ I don't how can pass this regular expression. I trid AW0AW,AXFX,3D0E, but all can't pass it.
{ "language": "en", "url": "https://stackoverflow.com/questions/49621066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Auto-start my program in administrative mode when system starts up without the UAC prompt My problem : I made a program and i have this program for example now under this directory : "C:\Program Files (x86)\AppName", now in the program i'm saving some images in my program directory, but since this is in the C drive, it's giving me a access denied error, now i made the program to always run in administrative mode and that worked just fine, but also there is in my program a feature to auto-start my program when the system starts up using a registry key, but when the "always run in administrative mode" is ON, the program will not start even though there is a start-up key in the registry, and when the "always run in administrative mode" is OFF, it will start. What I have tried so far : I tried making an another executable file that will start when the system starts up and then it will run my main program and close it self and i knew that will work but now every time i start my computer, the User Access Control prompt ask me if i trust this program even and that is not very user-friendly. So i searched and i found that i can create scheduled task but i didn't find a lot of examples and but i tried creating one manually and it did work as wanted! But here is a code which didn't work : Imports Microsoft.Win32.TaskScheduler Using ts As New TaskService("\\RemoteServer") 'Create a new task definition and assign properties Dim td As TaskDefinition = ts.NewTask() td.RegistrationInfo.Description = "Does something" 'Create a trigger that will fire the task at this time every other day td.Triggers.Add(New DailyTrigger() With { Key.DaysInterval = 2 }) 'Create an action that will launch Notepad whenever the trigger fires td.Actions.Add(New ExecAction("notepad.exe", "c:\test.log", Nothing)) 'Register the task in the root folder ts.RootFolder.RegisterTaskDefinition("Test", td) End Using And the problem with the code is : It couldn't find the TaskService and it has no use of the TaskScheduler library! Hope someone have some previous experience with that who can help me! A: To answer your question: To use that code you've got to download the Managed Task Scheduler Wrapper first. Then to make it run with administrative privileges you've got to set the RunLevel to TaskRunLevel.Highest on your TaskDefinition: td.Principal.RunLevel = TaskRunLevel.Highest However like Plutonix says you shouldn't be writing files to the directory of your program (as that's usually located in the restricted %ProgramFiles% folder). Instead, use the %ProgramData% directory. You can get the path to it from your code via Environment.GetFolderPath(): Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) 'Example: Dim ConfigPath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "AppName") Dim ImagePath As String = Path.Combine(ConfigPath, "MyImage.png") If Directory.Exists(ConfigPath) = False Then Directory.CreateDirectory(ConfigPath)
{ "language": "en", "url": "https://stackoverflow.com/questions/47462457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change state without overriding other values in react I am trying to change the state of my app without overriding the values that haven't changed. I am doing so using the spread operator, but something is going wrong. Here is my base state : useState({data : [{name : undefined , project : []}] }); With setState i want to just add names but keep the project array empty since it didn't change. setManager(prevState => ({...prevState , data : res.data})) After performing setState the new state looks like this : [ {name: "John doe"}, {name: "Jane Doe"} ] as you can see the default state is completely overridden. res.data looks like this by the way : [ {name: "john doe"}, {name: "jane doe"} ] A: By setManager(prevState => ({...prevState , data : res.data})) you're simply overriding your earier 'main' data property. data is an array, new values are in array ... simply concat them setManager(prevState => ({...prevState , data : prevState.data.concat( res.data ) })) After that you should have [ {name: undefined , project : []}, {name: "john doe"}, {name: "jane doe"} ] ... but probably you wanted to manage names and project separately: const [manager, setManager] = useState({ data: { name: undefined, project: [] } }); ... or even const [manager, setManager] = useState({ name: undefined, project: [] }); This way you don't need to 'address' this data with 'intermediatory' .data <Component names={manager.name} /> ... not by {manager.data.name}. Of course updating only name needs different code setManager(prevState => ({ ...prevState, name : prevState.name.concat( res.data ) })) * *...prevState prevents deleting project property *name should be initialized with [], not undefined *conditional rendering can be done with `{!manager.name.lenght && ... } If you have separate states 'slices' then no need to use one common state, use many useState declarations. A: Probably what you need is: const [manager, setManager] = useState({ data: [{ name: undefined, project: [] }] }); setManager(prevState => ({ data: prevState.data.map((item, index) => ({ ...item, ...res.data[index] })) })); However, if you're just storing an array of "items", then your state should look more like: const [manager, setManager] = useState([{ name: undefined, project: [] }]); setManager(prevState => prevState.data.map((item, index) => ({ ...item, ...res.data[index] })) ); Also, the way how you're gonna merge prev and incoming data depends on many things and maybe you need some more sophisticated way of storing state. A: You inited your state with an Array, not an Object, that's the reason for the behavior. Change this from useState({data : [{name : undefined , project : []}] }); to useState({data : {name : undefined , project : []} });
{ "language": "en", "url": "https://stackoverflow.com/questions/60930779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: *ngIf is adding elements instead of replaceing them My Code <i *ngIf="!isFollowing" class="far fa-bell"></i> <i *ngIf="isFollowing" class="fas fa-bell"></i> Type of isFollowing is Boolean Whenever I'm changing it to true or false it's showing the new element according to the expression but it is not removing the previous element but adding a new element to the DOM. As a result, multiple icons are visible like in the image. Multiple Icons being Added I believe change detection is detecting the change and adding a new DOM element but it's not updating the previous DOM Element. A: Try this <i [ngClass]="{'far': !isFollowing, 'fas': isFollowing}" class="fa-bell"> <i> A: Try with <i *ngIf="!isFollowing; else follow" class="far fa-bell"></i> <ng-template #follow><i class="fas fa-bell"></i></ng-template> A: Why not you doing this with ngClass? <i [ngClass]="{'fas fa-bell': isFollowing == true, 'far fa-bell': isFollowing == false}"></i> A: I ran into this exact same issue, each of the suggested answers did not work. I haven't figured out why this was happening, but I solved it by wrapping the i tags in span tags and moving the *ngIf to the span tags like so: <span *ngIf="!isFollowing"><i class="far fa-bell"></i></span> <span *ngIf="isFollowing"><i class="fas fa-bell"></i></span>
{ "language": "en", "url": "https://stackoverflow.com/questions/52966771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to nest the all function? I have a list of objects named items. Each object has a property state and a property children, which is another list of objects. And each child object has also a property named state. What I want to know is if every item and their children are in the states happy or cheerful. I did this with all (only analysing the states of the items): if all(item.state in ['happy', 'cheerful'] for item in items): pass I would like to know which is the best way to do the same with not only items but children too. A: You are seeking for some recursion here: def is_happy(items): return all(item.state in ['happy', 'cheerful'] for item in items) and all(is_happy(item.childs) for item in items) As @tobias_k pointed out this should be quicker since it iterates only once on items: def is_happy(items): return all(item.state in ['happy', 'cheerful'] and is_happy(item.childs) for item in items) It is at least more readable. In the case you only have two layers of objects a simple for might do the trick too. def is_happy(items): happy_children = True for item in items: if any(child.state not in ['happy', 'cheerful'] for child in item): happy_children = False break return all(item.state in ['happy', 'cheerful'] for item in items) and happy_children A: I guess this would be the right way: if all(item.state in ['happy', 'cheerful'] and all(c.state in ['happy', 'cheerful'] for c in item.childs) for item in items): pass A: First step: flatten the list of items: def flatten(items): for item in items: yield item for child in getattr(item, 'children', ()): yield child Or using Python 3.4+: def flatten(items): for item in items: yield item yield from getattr(item, 'children', ()) And now you can iterate through flattened items using all(..) or some other way: is_happy = lambda item: getattr(item, 'state') in ('happy', 'cheerful') are_happy = lambda items: all(map(is_happy, flatten(items))) A: Recursion is your friend here def happy(x): return (x.state in ('happy', 'cheerful') and all(happy(xc) for xc in x.children)) A: This is probably best done manually. def valid(item): return item.state in ['happy', 'cheerful'] for item in items: if not (valid(item) and all(valid(child) for child in item)): break else: # success Changing the generator expression to work with this is possible but makes it a bit hacky. if all(child.state in ['happy', 'cheerful'] for item in items for child in item+[item]): pass So to answer your question, yes its possible to nest the all function and thats how you could do it if you really wanted.
{ "language": "en", "url": "https://stackoverflow.com/questions/27484771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Why is the white box appearing? The first box the loop outputs is a white box with a black outline. I don't understand where it's coming from... https://editor.p5js.org/matranson/present/6fNelJM8_ function setup() { colorMode(HSB,360,100,100); createCanvas(400, 400); var boxh = height / 10; var boxw = width; for(var i = 0; i < 10; i++) { var h = lerp(64, 22, i / 9); var s = lerp(86, 90, i / 9); var l = lerp(96, 56, i / 9); rect(0, i * boxh, boxw, boxh); fill(h,s,l); stroke(0,0,100); } } function draw() { } <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script> A: stroke() sets the color used to draw lines and borders. fill() sets the color used to fill shapes. rect() draws a rectangle. The stroke and the fill color has to be set before the rectangle is drawn: fill(h,s,l); stroke(0,0,100); rect(0, i * boxh, boxw, boxh); function setup() { colorMode(HSB,360,100,100); createCanvas(400, 400); var boxh = height / 10; var boxw = width; for(var i = 0; i < 10; i++) { var h = lerp(64, 22, i / 9); var s = lerp(86, 90, i / 9); var l = lerp(96, 56, i / 9); fill(h,s,l); stroke(0,0,100); rect(0, i * boxh, boxw, boxh); } } <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/56417688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: give labels as a numpy array with shape(m,1) or shape(m,) to a model simply i trying to test a simple Dense neural network without hidden layer.first 50th columns of my data is features and last one is label. X = data[:, :50] y = data[:, -1] input = keras.Input(shape=(50,)) output = keras.layers.Dense(1)(input) model = keras.Model(inputs=input, outputs=output) model.compile(loss='mse') model.fit(X, y, epochs=20) is there difference between giving data[:, -1] or data[:, 50:] as labels to model? why? (seems the results is equal) >>> data[:, 50:].shape result: (1000, 1) >>> data[:, -1].shape result: (1000,) >>> data[:, :50].shape result: (1000, 50) A: data[:, -1] returns the value of the last column for every row but data[:, 50:] will return the values of the all columns starting from column no 50. Since in your case there are only 50 columns it is same as data[:, -1] but with 1 in the second dimension indicating that only 1 column was picked Assume that the data is of size (1000, 60), then data[:, -1] would still return a array of shape (1000,) but data[:, 50:] would return an array of shape (1000, 10)
{ "language": "en", "url": "https://stackoverflow.com/questions/67434832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not able to access imported class using * wildcard but able to use same class when imported with full qualified name * *I am new to java please help me *I am having trouble using the * wild card in my import statements *I compiled the javatesting1 class using javac -d . javatesting1.java and also got the .class file in test1 package *here is my folder structure click on this image *When i compile javatesting2 while using import statement with * I am getting the following error javac javatesting2.java javatesting2.java:2: error: cannot access javatesting1 class testingclass extends javatesting1 ^ bad source file: .\javatesting1.java file does not contain class javatesting1 Please remove or make sure it appears in the correct subdirectory of the sourcepath. javatesting2.java:6: error: cannot find symbol System.out.println(a); ^ symbol: variable a location: class testingclass 2 errors Here is my code package test1; public class javatesting1 { protected int a=45; int b=78; } //I am not able to use the javatesting1 class when i use test1.* instead of test1.javatesting1 // the below code is on another file in the same directory import test1.javatesting1; class testingclass extends javatesting1 { public void meth1() { System.out.println(a); // System.out.println(b); } } public class javatesting2 { public static void main(String [] args) { testingclass obj=new testingclass(); obj.meth1(); } } A: Hello and welcome to Stack Overflow! Since you are declaring class javatesting1 to be in a package test1, Java expects to find that class in a folder named like the package in order to scan it (using the wildcard). I have tested your code, importing using wildcard *, with a folder structure like this folder * *javatesting2.java *test1 * *javatesting1.java Try editing your folder structure. Also please try do adhere to coding conventions: class names should be named using CamelCase, e.g. JavaTesting1
{ "language": "en", "url": "https://stackoverflow.com/questions/67103718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Highchart x-axis show label after specific days no matter what is in the x-axis categories This is my code for highchart: Highcharts.setOptions({ time: { useUTC: false } }); $('#container-chart').highcharts({ chart: { type: 'line', alignTicks: false, }, title: { text: "Title 1", }, tooltip: { formatter: function() { return Highcharts.dateFormat('%b %e, %Y',new Date(this.x))+ '<br/>' + this.y; } }, xAxis: { categories: [1391122800000,1393542000000,1396216800000,1398808800000,1401487200000,1404079200000,1406757600000,1409436000000,1412028000000,1414710000000,1417302000000,1419980400000,1422658800000,1425078000000,1427752800000,1430344800000,1433023200000,1435615200000,1438293600000,1440972000000,1443564000000,1446246000000,1448838000000,1451516400000,1454194800000,1456700400000,1459375200000,1461967200000,1464645600000,1467237600000,1469916000000,1472594400000,1475186400000,1477868400000,1480460400000,1483138800000,1485817200000,1488236400000,1490911200000,1493503200000,1496181600000,1498773600000,1501452000000,1504130400000,1506722400000,1509404400000,1511996400000,1514674800000,1517353200000,1519772400000,1522447200000,1525039200000,1527717600000,1530309600000,1532988000000,1535666400000,1538258400000,1540940400000], // tickInterval: (24 * 3600 * 1000 * 173), labels: { formatter: function () { return Highcharts.dateFormat("%b %y", this.value); }, } }, yAxis: { title: { text: '' }, }, legend: { enable: true, }, plotOptions: { series: { marker: { enabled: false }, dataLabels: { enabled: false, allowOverlap: true, }, lineWidth: 2, states: { hover: { lineWidth: 3 } }, threshold: null } }, series: [{ data: [0.57,0.41,0.51,0.35,0.16,0.16,0.05,0.19,0.27,0.57,0.45,0.59,0.49,0.77,0.56,0.25,0.3,0.28,0.27,0.33,0.45,0.62,0.62,0.46,0.46,0.45,0.68,0.18,0.22,0.28,0.29,0.41,0.34,0.59,0.67,0.69,0.65,0.57,0.73,-0.01,0.32,0.27,0.47,0.47,0.57,0.75,0.7,0.6,0.71,0.88,0.79,-0.11,0.22,0.15,0.07,0.09,0.09,0.09], }], exporting: { sourceWidth: 1500 }, }); I have 58 days data for highchart's xAxis categories properties. The date difference from 1st day data to 58th date data is 1734 i.e. total number of days are 1734 days. Now, Say, i only want to show 10 labels on x-axis, of equal distance including first and last data, that means, label interval will be 173 days. How can i achieve this label interval no matter what date gap present in x-axis categories ? Any help ? A: You can use tickPositioner function, but you should use timestamps as x values not as categories: xAxis: { tickPositioner: function() { var positions = [], interval = 24 * 3600 * 1000 * 173; for (var i = this.dataMin; i <= this.dataMax; i += interval) { positions.push(i); } return positions; }, labels: { formatter: function() { return Highcharts.dateFormat("%b %y", this.value); }, } } Live demo: http://jsfiddle.net/BlackLabel/npq3x2bc/ API Reference: https://api.highcharts.com/highcharts/xAxis.tickPositioner A: Highcharts.setOptions({ time: { useUTC: false } }); $('#container-chart').highcharts({ chart: { type: 'line', alignTicks: false, }, title: { text: "Title 1", }, tooltip: { formatter: function() { return Highcharts.dateFormat('%b %e, %Y',new Date(this.x))+ '<br/>' + this.y; } }, xAxis: { categories: [1391122800000,1393542000000,1396216800000,1398808800000,1401487200000,1404079200000,1406757600000,1409436000000,1412028000000,1414710000000,1417302000000,1419980400000,1422658800000,1425078000000,1427752800000,1430344800000,1433023200000,1435615200000,1438293600000,1440972000000,1443564000000,1446246000000,1448838000000,1451516400000,1454194800000,1456700400000,1459375200000,1461967200000,1464645600000,1467237600000,1469916000000,1472594400000,1475186400000,1477868400000,1480460400000,1483138800000,1485817200000,1488236400000,1490911200000,1493503200000,1496181600000,1498773600000,1501452000000,1504130400000,1506722400000,1509404400000,1511996400000,1514674800000,1517353200000,1519772400000,1522447200000,1525039200000,1527717600000,1530309600000,1532988000000,1535666400000,1538258400000,1540940400000], // tickInterval: (24 * 3600 * 1000 * 173), labels: { formatter: function () { return Highcharts.dateFormat("%b %y", this.value); }, } }, yAxis: { title: { text: '' }, tickInterval:(maxValue/10), min: 0, max: maxValue, }, legend: { enable: true, }, plotOptions: { series: { marker: { enabled: false }, dataLabels: { enabled: false, allowOverlap: true, }, lineWidth: 2, states: { hover: { lineWidth: 3 } }, threshold: null } }, series: [{ data: [0.57,0.41,0.51,0.35,0.16,0.16,0.05,0.19,0.27,0.57,0.45,0.59,0.49,0.77,0.56,0.25,0.3,0.28,0.27,0.33,0.45,0.62,0.62,0.46,0.46,0.45,0.68,0.18,0.22,0.28,0.29,0.41,0.34,0.59,0.67,0.69,0.65,0.57,0.73,-0.01,0.32,0.27,0.47,0.47,0.57,0.75,0.7,0.6,0.71,0.88,0.79,-0.11,0.22,0.15,0.07,0.09,0.09,0.09], }], exporting: { sourceWidth: 1500 }, }); here I have added : tickInterval:(maxValue/10), min: 0, max: maxValue, it means you need to fist get max value and take the nearest value divisible by 10 and use , I hope it will help you
{ "language": "en", "url": "https://stackoverflow.com/questions/54086263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to reuse React component that has different markup? I have the following component today, which represents a container box that has a heading and different rows. This is how it looks: var Box = React.createClass({ render: function() { return ( <BoxHeading title={this.props.headingTitle}/> <BoxBody rows={this.props.rows} /> ) } }); var BoxBody = React.createClass({ render: function() { return ( {this.rows()} ) } rows: function() { return _.map(this.props.rows, function(row) { return ( <HouseRow /> ); }, this); } }); Now my question is: If I want to reuse the Box & BoxBody but instead of using I want to use another kind of Row, how would I do it? Would I pass the kind of component that I want as row to the Box? So, I would do <Box rowType={<HouseRow} /> or something similar? A: The approach you chose looks really good — you can basically combine Box with every type of row you want, provided it has a correct interface. It is called Object Composition and is a legit and well respected pattern in software engineering. The only thing is, in React you should do it not by passing a already rendered component, but the component class, like this: <Box rowComponent={ HouseRow } /> As you see, you don't need to use parenthesis. And inside component, you do something like this: var RowComponent = this.props.rowComponent; return ( <RowComponent /> ); A: <Box rowType={HouseRow} /> This is exactly how you would do it. Pass dynamic content that varies from components as props from a parent. Then in your rows function, return <{@props.rowType} /> should work
{ "language": "en", "url": "https://stackoverflow.com/questions/30929751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the usage of OAuth 2.0 client id from Google Fit on Android Im really confused from Google Api platform. Recently guide leads you to generate oAuth Client ID JSON. On the other hand there is no clear reason or need to generate or have at all. Im doing these steps to enable Google Fit on Android: * *Get a project on Google APIs *Enable Google Fit API *Create OAuth Client ID on Android *Provide fingerprint and package name (ApplicationID) that's it .. but what is the usage of that Json file of OAuth Client ID ? or that client Id? 111111111111-aaaaaaaaaaaaaaa.apps.googleusercontent.com (sample) A: The OAuth Client ID is obtained so that your app can access the Google Fit API. As the SHA-1 of your certificate is already known by Google Fit, you do not need to enter the actual Client ID into your code. Your certificate is part of your app, and identifies the app to Google Fit. https://developers.google.com/fit/android/get-api-key
{ "language": "en", "url": "https://stackoverflow.com/questions/46920653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: t-sql dynamic cursors May I use variable to declaring cursors?? I want to creating dynamic cursor, how can i do this?? Regards I have table: CREATE TABLE [UsersUniTask] ( [id] uniqueidentifier CONSTRAINT [DF_UsersUniTask_id] DEFAULT newid() NOT NULL, [userUniID] uniqueidentifier NOT NULL, [taskID] int NOT NULL, [time] datetime NOT NULL, [doTask] int NOT NULL, [priority] int NOT NULL, CONSTRAINT [PK_UsersUniTask] PRIMARY KEY CLUSTERED ([id]), CONSTRAINT [FK_UsersUniTask_UsersUni] FOREIGN KEY ([userUniID]) REFERENCES [UsersUni] ([id]) ON UPDATE NO ACTION ON DELETE CASCADE ) ON [PRIMARY] GO A: Can you explain more about what you mean? If you are talking about declaring the cursor in a dynamic context as in the following example, then yes you can: DECLARE @i int -- variable input DECLARE @valuableData int SET @i = 1 -- value for that input, this could be set by a query DECLARE cursorFoo CURSOR FOR SELECT valuableData FROM myTable WHERE someParameter = @i OPEN cursorFoo WHILE (1=1) BEGIN FETCH NEXT FROM cursorFoo INTO @valuableData IF (@@FETCH_STATUS <> 0) BREAK SELECT @valuableData -- Do something with your data END CLOSE cursorFoo EDIT due to discussion in comments You should have two separate program loops here Loop 1: * *Webservice adds tasks to permanent table with information on priority. Loop 2: * *Server script queries permanent table for most important task *Server script removes task from table and processes task (or hands that information off to a script that does the work *Server script goes back to permanent table and looks for most important task SQL is meant to store data, not loop around and process it. The processing should be done with a server script. That script should get the data from the database. You start to have the concurrency issues you have having right now when SQL is writing and reading and looping through the same temporary table concurrently. You can do processing in SQL, but you should only use temp tables for data that is relevant only to that particular process.
{ "language": "en", "url": "https://stackoverflow.com/questions/3563929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: validating bitbucket commit if it has a jira id Hi i need to validate bitbucket commit if it has a jira id. May be apply a pre receive webhook in bitbucket to check if there's a jira id. Can some guide me. I think we can make a pre webhook - testing the bitbucket commit against a regular expression.
{ "language": "en", "url": "https://stackoverflow.com/questions/46399267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Avoiding join in MS Access delete query I am trying to create a delete query to remove records from one table, based on whether or not one of the field exists in another master table. The situation is that I am importing new records into a database, but I want to remove the records that have already been imported, i.e. that already have an account in the master table. The field I need to join on, however is not equal: it is prefixed with a constant three letter code XYZ. tbl_to_import.Account master_table.Account 123456 XYZ.123456 345678 XYZ.345678 To avoid using a join in the delete query I tried the following: Delete tbl_to_import.* From tbl_to_import Where Exists( Select master_table.Account From master_table Where master_table.Account = ("XYZ."& tbl_to_import.Account) ) = True; However, the query gets hung up in Access. I'm not sure what I'm doing incorrectly. I don't get an error message, but the query runs without producing anything and I eventually stop it. In this situation, tbl_to_import has 2,700 records and master_table has 50,000 records. Additionally, I am connecting to the master_table via ODBC. Originally, I constructed two queries using a join to perform the delete. tbl_to_import.Account has a primary key called ID. One query, qry_find_existing_accounts, located the ID numbers in tbl_to_import for which there exists a corresponding account in master_table.Account: SELECT DISTINCTROW tbl_to_import.ID AS DELETEID FROM tbl_to_import LEFT JOIN master_table ON ("XYZ."& tbl_to_import.Account) = master_table.Account WHERE ((("XYZ." & [Account])=[master_table].[Account])); Then I used this query to construct the delete query: DELETE DISTINCTROW tbl_to_import.*, tbl_to_import.ID FROM tbl_to_import RIGHT JOIN qry_find_existing_accounts ON tbl_to_import.ID =qry_find_existing_accounts.DELETEID WHERE (((tbl_to_import.ID)=[qry_find_existing_accounts].[DELETEID])); The query qry_find_existing_accounts worked fine; however, when I tried to run the second query to delete, I got the error: Could not delete from specified tables. Typically, when I get this error, it is because I have not selected unique records only, however, I used DISTINCTROW in both queries. Any ideas what I am doing wrong and how I can accomplish what I need to do? A: I'd go with a simpler nested SQL statement: Delete tbl_to_import.* From tbl_to_import Where "XYZ." & tbl_to_import.Account In (Select master_table.Account From master_table); This should be fairly fast, especially if your Account fields are indexed. A: I think you can simplify the query; delete based on the ID, where the IDs are in the query: DELETE * FROM tbl_to_import WHERE tbl_to_import.ID IN ( SELECT DISTINCT [DELETED] FROM qry_find_existing_accounts )
{ "language": "en", "url": "https://stackoverflow.com/questions/12335973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inserting data into database using AdoDB This is how you insert using AdoDB Databse Abstraction Layer. <?php include 'adodb5/adodb.inc.php'; $host = 'localhost'; $user = 'user2000'; $pass = 'password2000'; $dbname = 'w3cyberlearning'; $conn1 = &ADONewConnection('mysql'); $conn1->PConnect($host, $user, $pass, $dbname); // the MySQL insert statement. $sql = "INSERT INTO user_infor(id,first_name,last_name, email) values(?,?,?,?) "; $my_data = array( array(1, 'Paul', 'Mark', '[email protected]'), array(2, 'Jam', 'Gill', '[email protected]'), array(3, 'Mix', 'Alex', '[email protected]'), array(4, 'King', 'Mix', '[email protected]') ); // loop through the array for ($i = 0; $i < count($my_data); $i++) { $d = $conn1->Execute($sql, $my_data[$i]); if (!$d) { print 'error' . $conn1->ErrorMsg() . '<br>'; } echo 'Success!'; echo "<br/>"; } The data is in array format. What if I use a form. if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST['name']; $age = $_POST['age']; } <form enctype="multipart/form-data" method="post" action="<?php $_SERVER['PHP_SELF']; ?>"> <input type="text" id="name" name="name" /> <input type="number" id="age" name="age" /> <input type="submit" value="Submit"/> </form> Now, the data comes from two variables $name and $age. What I am unable to do is replace the above $my_data with the two variables which collects the data. How do I replace them A: As I see from $d = $conn1->Execute($sql, $my_data[$i]); arguments passed to Execute method are query string and array with some values. So, in your case you can do the same: $d = $conn1->Execute($sql, array($name, $age)); where $name, $age your variables and $sql is your query string.
{ "language": "en", "url": "https://stackoverflow.com/questions/34120697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Compilation issue on new kernel I have installed Fedora 22 , which has default kernel 4.0.4. But I have a requirement of Kernel 4.1.4, so I installed kernel 4.1.4 on Fedora 22. and make an entry in grub for new kernel. Kernel 4.1.4 is installed successfully and I am able to login with new kernel. output of "uname -a"- uname -a Linux localhost.localdomain 4.1.4 #1 SMP Fri Aug 7 10:52:36 EDT 2015 x86_64 x86_64 x86_64 GNU/Linux Path of new kernel - /usr/src/linux-4.1.4 Path of include folder - /usr/src/linux-4.1.4/include Now I wrote a C program, which uses the macro AF_MPLS, which is defined in new kernel headers. Compilation of c program is failed because AF_MPLS is not in /usr/include/sys/socket.h. Error found - RouteMPLS.c: In function âroute_addâ: RouteMPLS.c:212:24: error: âAF_MPLSâ undeclared (first use in this function) req.r.rtm_family = AF_MPLS; Headers file used in RouteMPLS.c #include <stdio.h> #include <asm/types.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <errno.h> So, I changed the location of header file a/c to new kernel- #include "/usr/src/linux-4.1.4/include/linux/socket.h" still it throws an compilation error, then I tried with gcc RouteMPLS.c -I /usr/src/linux-4.1.4/include/ In file included from /usr/src/linux-4.1.4/include/linux/kernel.h:6:0, from /usr/src/linux-4.1.4/include/linux/skbuff.h:17, from /usr/src/linux-4.1.4/include/linux/netlink.h:6, from RouteMPLS.c:3: /usr/src/linux-4.1.4/include/linux/linkage.h:7:25: fatal error: asm/linkage.h: No such file or directory compilation terminated. Please guide how can I install our c program with new kernel headers - Default kernel header location - /usr/include New Kernel header location - /usr/src/linux-4.1.4/include Thanks in advance. A: The problem is that you have the linux kernel 4.1.4 header files in the directory for kernel compilation. To compile user programs, the compiler normally looks for them in /usr/include (well, in the new architectures, it is some more complicated) and there's normally a copy of the kernel headers for the running kernel installed inside /usr/include But now, you have a kernel headers version mismatch. You don't say where have you downloaded that sources from, but in the Documentation subdirectory of the kernel source tree, you have some document explaining how to install the kernel headers in the proper place, so the compiler for system applications finds them right. Read the doc at /usr/src/linux-4.1.4/Documentation for a file which explainst how to install the kernel headers in the proper place. Mainly, it refers to all files installed under /usr/include/linux, /usr/include/asm and (as is your case) /usr/include/asm-amd64. Note: After some search in the kernel source tree, I have found a target headers_install in the Makefile (by trying make help) I suppose serves to install the header files from the kernel tree to the proper place. So, the most probable way to install the kernel header files is to do: make headers_install or (in case you must install them in other place) INSTALL_HDR_PATH=<new_path> make headers_install (it says by default installation goes to ./usr)
{ "language": "en", "url": "https://stackoverflow.com/questions/31913435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't run background service at a regular period of 3 minutes on Chinese custom ROM to send latitude and longitude I have tried job scheduler and work manager but it does not work in doze mode and not at regular period. I have used normal service which is not working on some Chinese custom rom phone specially oppo and vivo. I have used the Alarm Manager to start service but it also not working any type of solution not working on this phone. A: If you really want to have it working on all devices, I suggest you this approach: * *Set up Firebase messaging *Subscribe all devices to specific topic e.g. "UPDATE_LOCATION" *Extend FirebaseMessagingService and implement onMessageReceive() *If your data message contains instruction to update location, call the method to update location from onMessageReceive() *Trigger recurring messages to "UPDATE_LOCATION" topic from Firebase (CRON job or scheduled tasks) It's a little more work that methods you have already tried, but it works on all phones and also after device restart and system update. Additional plus is that you have control over the location updater from your backend (not per device which relies on app update).
{ "language": "en", "url": "https://stackoverflow.com/questions/58624262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How can I customize the output from pygments? If I run a python source file through pygments, it outputs html code whose elements class belong to some CSS file pygments is using. Could the style attributes be included in the outputted html so that I don't have to provide a CSS file? A: By setting the noclasses attribute to True, only inline styles will be generated. Here's a snippet that does the job just fine: formatter = HtmlFormatter(style=MyStyle) formatter.noclasses = True print highlight(content,PythonLexer(),formatter) A: @Ignacio: quite the opposite: from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter code = 'print "Hello World"' print highlight(code, PythonLexer(), HtmlFormatter(noclasses=True)) [ ref.: http://pygments.org/docs/formatters/, see HtmlFormatter ] ( Basically it is the same as Tempus's answer, I just thought that a full code snippet may save a few seconds ) ) PS. The ones who think that the original question is ill-posed, may imagine e.g. the task of pasting highlighted code into a blog entry hosted by a third-party service. A: Pass full=True to the HtmlFormatter constructor. A: Usually, your code is only one of many things on a web page. You often want code to look different from the other content. You, generally, want to control the style of the code as part of the overall page style. CSS is your first, best choice for this. However, you can embed the styles in the HTML if that seems better. Here's an example that shows the <style> tag in the <head> tag. http://www.w3schools.com/TAGS/tag_style.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/624345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Select multiple film category I am having trouble with my small film database tag/category query. My table is: ID(index),Name(film name),category One movie can have multiple categories. SELECT Name FROM categorytable WHERE category ='Action'; Works fine but if I want other tags I get empty cursor: SELECT Name FROM categorytable WHERE category ='Action' AND category ='Sci-Fi'; Example select: 1 Film001 Action 2 Film001 Sci-Fi 3 Film002 Action EDIT: My home databese: ID|NAMEFILM|DESCRIPTION And complete query is: SELECT DATABASEFILM.NAMEFILM , DATABASEFILM.DESCRIPTION , NAME from DATABASEFILM , CATEGORY where DATABASEFILM.NAMEFILM=NAME AND category=(SELECT NAME FROM CATEGORY WHERE category ='Action'); A: The reason your query doesn't work is because each row has only one category. Instead, you need to do aggregation. I prefer doing the conditions in the having clause, because it is a general approach. SELECT Name FROM categorytable group by Name having sum(case when category ='Action' then 1 else 0 end) > 0 and sum(case when category ='Sci-Fi' then 1 else 0 end) > 0; Each clause in the having is testing for the presence of one category. If, for instance, you changed the question to be "Action films that are not Sci-Fi", then you would change the having clause by making the second condition equal to 0: having sum(case when category ='Action' then 1 else 0 end) > 0 and sum(case when category ='Sci-Fi' then 1 else 0 end) = 0; A: You can use the OR clause, or if you have multiple categories it will probably be easier to use IN So either SELECT Name FROM categorytable WHERE category ='Action' OR category ='Sci-Fi' Or using IN SELECT Name FROM categorytable WHERE category IN ('Action', 'Sci-Fi', 'SomeOtherCategory ') Using IN should compile to the same thing, but it's easier to read if you start adding more then just two categories. A: with mustAppear(category) as ( select 'Action' union all select 'Sci-Fi' ) select Name -- select those film names for which from categorytable as C1 where not exists ( -- there is no category that must appear with that name select M.category from mustAppear as M where not exists ( -- that does not. select * from categorytable as C2 where C2.Name = C1.Name and C2.category = M.category ) ) You can also be more direct this way: select Name from categorytable where category = 'Sci-Fi' intersect select Name from categorytable where category = 'Action'; The advantage of the former query is that you can use it without modification if you create a permanent table (mustAppear, or you can use a table variable @mustAppear) to hold the category list that must match. The latter query is simpler, but it must be rewritten when the categories change.
{ "language": "en", "url": "https://stackoverflow.com/questions/18006656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't Load Image from JSON I want to display a list that contain text and image. The text and image stored on my online database, i using JSON for taking them down to my android app. The JSON doesn't display any error, the text are displayed but the image are not appear. I check the logcat and there's no error for this process. I using viewAdapter for displaying the image on the list. Please help me, can you gimme some simple explanation how to solve this?? Thanks... NB. This is my code for CustomListAdaper2: public class CustomListAdaper2 extends ArrayAdapter<contenus> { ArrayList<contenus> contenus; Context context; int resource; public CustomListAdaper2(@NonNull Context context, @LayoutRes int resource, @NonNull ArrayList<contenus> contenus) { super(context, resource, contenus); this.contenus = contenus; this.context = context; this.resource = resource; }@NonNull @Override public View getView(int position2, @Nullable View convertView, @NonNull ViewGroup parent) { if(convertView==null){ LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.custom_list_layout_layout, null, true); } contenus contenus = getItem(position2); ImageView imageView = (ImageView) convertView.findViewById(imageView5); Picasso.with(context).load(contenus.getImage()).into(imageView); TextView textViewtitle = (TextView) convertView.findViewById(R.id.textViewtitle); textViewtitle.setText((replacehtml(contenus.getNom()))); TextView textViewcity = (TextView) convertView.findViewById(R.id.textViewcity); textViewcity.setText((replacehtml(contenus.getVille()))); TextView textViewtime = (TextView) convertView.findViewById(R.id.textViewtime); textViewtime.setText((replacehtml(contenus.getTime()))); TextView textViewprice = (TextView) convertView.findViewById(R.id.textViewprice); textViewprice.setText((replacehtml(contenus.getPrix()))); return convertView; } } this is my code for the json: public class Multimedia extends AppCompatActivity { ArrayList<contenus> arrayList2; ListView lv2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_multimedia); arrayList2 = new ArrayList<>(); lv2 = (ListView) findViewById(R.id.ListView2); runOnUiThread(new Runnable() { @Override public void run() { new ReadJSON().execute("http://wach.ma/mobile/category.php?id=Pour_La_Maison_Et_Jardin"); } }); } class ReadJSON extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... params) { return readURL(params[0]); } @Override protected void onPostExecute(String content) { JSONObject jsonObject = null; try { jsonObject = new JSONObject(content); } catch (JSONException e) { e.printStackTrace(); } JSONArray jsonArray = null; try { jsonArray = jsonObject.getJSONArray("articles"); } catch (JSONException e) { e.printStackTrace(); } for (int i = 0; i < jsonArray.length(); i++) { JSONObject contenusobject = null; try { contenusobject = jsonArray.getJSONObject(i); } catch (JSONException e) { e.printStackTrace(); } try { arrayList2.add(new contenus( contenusobject.getString("picture"), contenusobject.getString("name"), contenusobject.getString("city"), contenusobject.getString("add_time"), contenusobject.getString("price") )); } catch (JSONException e) { e.printStackTrace(); } CustomListAdaper2 adaper2 = new CustomListAdaper2( getApplicationContext(), R.layout.custom_list_layout_layout, arrayList2 ); lv2.setAdapter(adaper2); } } @NonNull private String readURL(String theURL) { StringBuilder content = new StringBuilder(); try { URL url = new URL(theURL); URLConnection urlConnection = url.openConnection(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { content.append(line + "\n"); } bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); } return content.toString(); } } } A: Just Edit This Code... ImageView imageView = (ImageView) convertView.findViewById(R.id.your_image_view_id); Otherwise everything is fine... I test it. Update Before using url of the image be sure that When you set the value you are assigning write position on the model contractor. arrayList2.add(new contenus( //is this "picture" is first argument contenusobject.getString("picture"), contenusobject.getString("name"), contenusobject.getString("city"), contenusobject.getString("add_time"), contenusobject.getString("price") )); //Or Check hare String url = contenus.getImage(); Log.d("image url", url); Picasso.with(context).load(url).into(imageView); and what about imageView5 is this right id for imageView?
{ "language": "en", "url": "https://stackoverflow.com/questions/46909581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Running from terminal, changes the character encoding! I think. ( UBUNTU ) I asked that question, Ubuntu Zend Framework cli securityCheck Error and i found the problem. Actually it is not about zendframework. Because it happens doctrine too. And it doesnt happen if i run my web site from browser. The problem is as i wrote before. My operating system using utf8 character encoding for file names. utf8-encoded file names with the php is run by the terminal gives the error. 'I' is the upper one 'ı' in my language. But php expects to be 'i'. If i change the file names to ASCII in php using iconv , error happens again because it cant find the location of the file at this time. How can i run php from cli same like through apache. PLEASE HELP ! ( thank you in advance ) A: May be this package (or similar) required to run php scripts as cli? A: Solution is: Everytime solve your own things. Anyway, My linux locale is UTF-8 so i've changed it to 8859-9 locale setting. There are many place to change locale settings in ubuntu. But the easiest way to change it in /etc/default/locale. And i am happy, it's working now. Thank you.
{ "language": "en", "url": "https://stackoverflow.com/questions/4932990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best practice for disabling a cache request from the Full Page Cache (FPC) in magento (enterprise) I wish to remove the following setting: <cms>enterprise_pagecache/processor_default</cms> ... from the config.xml of the core / Enterprise / PageCache / config.xml file so that the home page will not be cached, (because we have a complicated custom store switch in place). Since this value is not stored in core_config_data I am unsure of the best way to override the out of the box value. The comments above the line in the core file do hint that it is not actually bad practice to edit this file, however, can I open this to the community to see what they think? PS = This is a multi website setup with a custom store switcher. A: Hole punching is what it sounds like you may need. Add a etc/cache.xml file with a <config> root to your module. (see Enterprise/PageCache/etc/cache.xml). Choose a unique [placeholder] name. The placeholders/[placeholder]/block node value must match the class-id of your custom dynamic block, e.g. mymodule/custom The placeholders/[placeholder]/container node value is the class to generate the content dynamically and handle block level caching The placeholders/[placeholder]/placeholder node value is a unique string to mark the dynamic parts in the cached page placeholders/[placeholder]/cache_lifetime is ignored, specify a block cache lifetime in the container’s _saveCache() method if needed Implement the container class and extends Enterprise_PageCache_Model_Container_Abstract. Use _renderBlock() to return the dynamic content. Implement the _getCacheId() method in the container to enable the block level caching. Use cookie values instead of model ids (lower cost). One last note: You DON’T have the full Magento App at your disposal when _renderBlock() is called. Be as conservative as possible. SOURCE: http://tweetorials.tumblr.com/post/10160075026/ee-full-page-cache-hole-punching
{ "language": "en", "url": "https://stackoverflow.com/questions/7651061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I get to store a downloaded file with Java and Jersey? I use Jersey for building RESTful services and currently I'm stuck on something that, I thought, shouldn't be too hard. I manage to GET the file I want to download, but I do not know how to save it. I searched for answers on the web, but I didn't find anything useful enough to fill in the gaps in my knowledge. Can you, please, give me a hit how to go on in order to save the file in a location on hdd? Any code samples are going to be highly appreciated! Client client = Client.create(); WebResource imageRetrievalResource = client .resource("http://server/"); WebResource wr=imageRetrievalResource.path("instances/attachment"); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add("item", "1"); Builder wb=wr.accept("application/json,text/html,application/xhtml+xml,application/xml"); client.addFilter(new HTTPBasicAuthFilter("user","pass")); ClientResponse response= wr.queryParams(queryParams).get(ClientResponse.class); String s= response.getEntity(String.class); System.out.println(response.getStatus()); Thank you! A: I got the answer to my question: File s= response.getEntity(File.class); File ff = new File("C:\\somewhere\\some.txt"); s.renameTo(ff); FileWriter fr = new FileWriter(s); fr.flush(); A: Using Rest easy Client this is what I did. String fileServiceUrl = "http://localhost:8081/RESTfulDemoApplication/files"; RestEasyFileServiceRestfulClient fileServiceClient = ProxyFactory.create(RestEasyFileServiceRestfulClient.class,fileServiceUrl); BaseClientResponse response = (BaseClientResponse)fileServiceClient.getFile("SpringAnnontationsCheatSheet.pdf"); File s = (File)response.getEntity(File.class); File ff = new File("C:\\RestFileUploadTest\\SpringAnnontationsCheatSheet_Downloaded.pdf"); s.renameTo(ff); FileWriter fr = new FileWriter(s); fr.flush(); System.out.println("FileDownload Response = "+ response.getStatus());
{ "language": "en", "url": "https://stackoverflow.com/questions/8928037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: react-client-session Login loop I'm trying to implement Login Functionality to my app but whenever I do a FRESH Reload and try to redirect to my home page it enters an infinite loop, How could I go about resolving this?. ** Note ** I have refactored this in so many ways with and Without react state in place and many ways of redirecting but zero to no luck, It just loops infinitely in different ways. My current method doesn't generate an error in the console its just the logs of 'mounting' and 'redi' you will read in my code infinitely looping till my CPU dies. Code for reference // Other Imports. lke axios, useEffect and components from bootstrap. import { ReactSession } from 'react-client-session'; import { Redirect } from "react-router-dom"; const Login = () => { const { handleSubmit, register } = useForm(); const BASE_URL = process.env.REACT_APP_BASE_URL let [error, setError] = useState(false) let [errorMessage, setErrorMessage] = useState('') let [loginToken, setToken] = useState('') const login = async (data, e ) => { try { let loginData = { email: data.email, password: data.password, } let res = await axios.post(BASE_URL + '/users/admin/login', loginData) if (res.status === 200) { ReactSession.set('token', res.data.token) // return <Redirect to="/admin/index" /> setToken(res.data.token) }} catch (error) { setError(error) setErrorMessage("There's been a problem while you were loggin in") } } useEffect(() => { const token = ReactSession.get("token"); setToken(token) console.log('mounting') }, [loginToken]) if (loginToken){ console.log('redi') return <Redirect to="/admin/meals" /> } return ( // Login Form components. A copy of my router for reference // More Imports import AdminLayout from "layouts/Admin.js"; import AuthLayout from "layouts/Auth.js"; ReactSession.setStoreType("localStorage"); const token = ReactSession.get("token"); ReactDOM.render( <BrowserRouter> <Switch> <Route path="/auth" render={(props) => <AuthLayout {...props} />} /> <Route path="/admin" render={(props) => token ? <AdminLayout {...props} /> : <Redirect from="*" to="/auth/login" /> } /> {(token) ? <Redirect from="/" to="/admin/index" /> : <Redirect from="*" to="/auth/login" /> } </Switch> </BrowserRouter>, document.getElementById("root") );
{ "language": "en", "url": "https://stackoverflow.com/questions/72118176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linq clarification on projection This question is to seek technical help in projecting enumerables to meet specified condition. Say, A ball contains two Red balls and three Blue balls.Based on the following conditions i have to select the balls. (i) Each pair should contain one blue ball and one red ball (ii) if the ball is "Blue1" ignore it and the expected result is {"Blue2","Red1" } {"Blue2","Red2" } {"Blue3","Red1" } {"Blue3","Red2" } Just i want to complete the following code to project the result. var bag = new[] { "Red1", "Red2", "Blue1", "Blue2", "Blue3" }; var BallsProjection = from blueball in bag from redball in bag **(What is the condition required here to select the balls)** select new { ball1 = blueball, ball2 = redball }; A: You can use the following code to get the result what you wanted. var BallsProjection = from blueball in bag from redball in bag where blueball.Contains("Blue") && redball.Contains("Red") && blueball.CompareTo("Blue1") !=0 select new { ball1 = blueball, ball2 = redball }; You can enhance this code to meet your requirement.I have not tested this code.
{ "language": "en", "url": "https://stackoverflow.com/questions/17273419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Displaying Japanese Characters using DOMpdf Problem: I want to generate a pdf using DomPDF that includes Japanese text. In order to do so I know that I need a font that supports Japanese characters and to load the font into DomPDF. I have read the UnicodeHowTo of DomPDF and several similar questions on SO but I can not seem to get it to work. I get ? at the place where the Japanese characters should be. In my dompdf config I have set def("DOMPDF_UNICODE_ENABLED", true); and it shows true in the admin interface as well. The font I use (I have tried several) should support japanese characters and is loaded in DomPDF using the load_font.php script. I do have to note for the sake of completeness that generating the font files gives me 2 identical warnings Warning: strftime(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in .. Minimal (not) working example: Relevant html stored in PHP variabe $template: <HTML> <HEAD> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <META http-equiv="X-UA-Compatible" content="IE=8"> <TITLE>Test voucher</TITLE> <STYLE type="text/css"> @font-face { font-family: \'mgenplus\'; font-style: normal; font-weight: 400; src: url(dompdf/fonts/rounded-mgenplus-1c-regular.ttf) format(\'truetype\'); } .ft0{font: 14px;line-height: 16px;} *{ font-family: mgenplus !important;} </STYLE> </HEAD> <BODY> <P>ねん だい かい にほんごのうりょくしけん</P> <!-- .... --> Relevant PHP: require_once("dompdf/dompdf_config.inc.php"); $template = mb_convert_encoding($template, 'HTML-ENTITIES', 'UTF-8'); $dompdf = new DOMPDF(); $dompdf->load_html($template, 'UTF-8'); $dompdf->render(); $dompdf->stream("test.pdf",array('Attachment'=>0)); If anybody has a suggestion or see if I missed something, it would be appreciated! A: Never mind, I found out why it did not work and I will post it here for anybody facing the same problem. The problem was in this piece: @font-face { font-family: \'mgenplus\'; font-style: normal; font-weight: 400; src: url(dompdf/fonts/rounded-mgenplus-1c-regular.ttf) format(\'truetype\'); } .ft0{font: 14px;line-height: 16px;} *{ font-family: mgenplus !important;} I had to remove the @font-face block, it is not needed since you load the font from DomPDF and not from the file. The line that caused all the trouble was .ft0{font: 14px;line-height: 16px;} it sets the font-family to the browser default apparently and the overwrite afterwards is not taken into account by DomPDF (no support for !important?). Changing the line to .ft0{font-size: 14px;line-height: 16px;} fixed my problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/33902718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mapstructure tags not used by Viper when writing to YAML I have structs defined as follows type config struct { Contexts map[string]Context `mapstructure:"contexts"` CurrentContext string `mapstructure:"current-context"` Tokens []Token `mapstructure:"tokens"` } type Context struct { Endpoint string `mapstructure:"endpoint,omitempty"` Token string `mapstructure:"token,omitempty"` Platform string `mapstructure:"platform"` Components []string `mapstructure:"components,omitempty"` Channel string `mapstructure:"channel,omitempty"` Version string `mapstructure:"version,omitempty"` EnforcedProvider string `mapstructure:"enforced-provider,omitempty"` } I'm writing to a YAML config file as follows configObj.Contexts[contextName] = context viper.Set("contexts", configObj.Contexts) viper.Set("current-context", configObj.CurrentContext) viper.Set("tokens", configObj.Tokens) err = viper.WriteConfig() if err != nil { return err } The mapstructure tags I have defined are not written to the YAML file, instead the field names are written in lower case. This is especially a problem with the EnforcedProvider field which is written as enforcedprovider instead of enforced-provider. How do I make it so that the mapstructure tag is used ? A: The documentation mentions mapstructure tags in its Unmarshaling section, but not in its WriteConfig section. It looks like WriteConfig will go through one of the default encoders : * *location where such encoders are declared: https://github.com/spf13/viper/blob/b89e554a96abde447ad13a26dcc59fd00375e555/viper.go#L341 *code for the yaml codec (it just calls the default yaml Marshal/Unmarshal functions): https://github.com/spf13/viper/blob/b89e554a96abde447ad13a26dcc59fd00375e555/internal/encoding/yaml/codec.go If you know you will read/write from yaml files only, the simplest way is to set yaml tags on your struct (following the documentation of the gopkg.in/yaml.v2 package) : type config { Contexts map[string]Context `yaml:"contexts"` CurrentContext string `yaml:"current-context"` Tokens []Token `yaml:"tokens"` } type Context struct { Endpoint string `yaml:"endpoint,omitempty"` Token string `yaml:"token,omitempty"` Platform string `yaml:"platform"` Components []string `yaml:"components,omitempty"` Channel string `yaml:"channel,omitempty"` Version string `yaml:"version,omitempty"` EnforcedProvider string `yaml:"enforced-provider,omitempty"` }
{ "language": "en", "url": "https://stackoverflow.com/questions/74692580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .loc only returning first value in a list instead of the full list I have a data frame and I'm trying to return all the matching values in one column based on another column using loc. The dataframe looks like this. Col1 Col2 Alpha Bravo Alpha Charlie Delta Charlie Delta Echo Delta Echo Mike Rodeo I'm wanting to return an additional column that has all the values in Col2 for each item in Col1. I tried posting the second table, but StackOverflow thought it was a code command and won't let me post. When I run this code, Col3 is value from Col2 and not the full list, but when I run only the right side of the code for a specific value, it returns the correct list for value in col1_values: df.loc[df['Col1'].eq(value),'Col3'] = list(df['Col2'].loc[df['Col1'].eq(value)])
{ "language": "en", "url": "https://stackoverflow.com/questions/75176043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "Request cookies" vs cookies In my project, I use XMLHttpRequest.withCredentials for authentication. Now, on a regular desktop browser this understandably sets a cookie to be passed on every request to the appropriate domain. Good. Now, since my project is a cordova app, and cordova web views supposedly don't have cookies, I'm trying to wrap my head around how this works. When I run my app and inspect the app's WebView through Chrome, I see that there are no Local File cookies, as expected, with a message on the inspector saying "By default cookies are disabled for local files. You could override this by starting the browser with --enable-file-cookies command like flag.". Except when I do a a request to my domain, the browser does in fact send the right cookie through a "request cookie". It looks like this in Chrome Inspector: So I'm trying to figure out. * *How does this even work if cordova is supposed to not have cookies? *What is the difference between regular cookies and these Request Cookies?
{ "language": "en", "url": "https://stackoverflow.com/questions/31725103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to add HTML to a template based on an if condition? I have an HTML template that's stored in sql as follows <script id="Accounttmpl" type="text/x-jsrender"> <div class="authenticated" id="authenticated" > <span class="loginWelcome">Hi </span> <span class="loginWelcome">{{>FirstName}}</span> <span id="Test" style="display:none">{{>(Verified)}} </span> </div> </script> So, in my code in Javascript the template above gets called. However I want to add an if statement where if verified == 'false' it must display a message saying not verified. This is my Javascript: Success: function (result, context) { if (result) { $(context).html($('#Accounttmpl').render(result)); } else { $(context).html($('#Accounttmpl').render({})); } } So, in my result I get back the "verified" details, so what I tried is the following: Success: function (result, context) { if (result) { if(result.Verified === 'false'){ document.getElementById("Test").html("not verified")} //however it doesn't find the "Test" id and throws an error that it cant read property of null $(context).html($('#Accounttmpl').render(result)); } else { $(context).html($('#Accounttmpl').render({})); } } } So, my question is how do I check the #Accounttmpl for the "Test" id so that I can add the if statement to it? A: The reason why you get null is because you are trying to get the id of Test before you add it to the DOM. Where you have: if(result.Verified === 'false'){ document.getElementById("Test").html("not verified") } $(context).html($('#Accounttmpl').render(result)); Change the order round: $(context).html($('#Accounttmpl').render(result)); if(result.Verified === 'false'){ document.getElementById("Test").html("not verified") } Also, you are mixing JavaScript with jQuery here: document.getElementById("Test").html("not verified") Either do: document.getElementById("Test").textContent = "not verified"; Or $("#Test").html("not verified")
{ "language": "en", "url": "https://stackoverflow.com/questions/60450056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: If i have a column, activity_year_and_month, that has data like 201901-201907 If I have a column, activity_year_and_month, that has data like 201901-201907, how can I filter my data in the where clause to only care about data now - 3 months prior? Looking for the SQL code to do that. Right now I get ERROR [HY000] ERROR: Bad timestamp external representation '201812' I tried (ACTIVITY_YEAR_AND_MONTH) >= (DATE_TRUNC('MONTH', NOW()) - INTERVAL '3 MONTH')
{ "language": "en", "url": "https://stackoverflow.com/questions/56938614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can an Admin User save a file as a Standard User So I have a program that saves a text file to the C:\ProgramData\MED folder std::filesystem::path fileName("C:\\ProgramData\\MED\\Data.txt"); int ret(0); FILE *fp; ret = _tfopen_s(&fp, fileName.c_str(), _T("w")); if (ERROR_SUCCESS == ret) { _ftprintf_s(fp, _T("1 = Type\n")); _ftprintf_s(fp, _T("MED = Name\n")); fclose(fp); } Now if a Standard User runs the program and creates the Data.txt file, then an Admin User can run the same program and delete that file. If however an Admin User runs the program and creates the Data.txt file, then a Standard User cannot run the same program and delete that file. They don't have the correct permissions. Here is my code for deleting: for (const auto &entry2 : std::filesystem::directory_iterator("C:\\ProgramData\\MED")) std::filesystem::remove_all(entry2.path()); So how do I save/create a file that any User can delete or update? A: Remy you are my hero. It was very easy to modify the SECURITY_DESCRIPTOR. I added just one line of code: std::filesystem::path fileName("C:\\ProgramData\\MED\\Data.txt"); int ret(0); FILE *fp; ret = _tfopen_s(&fp, fileName.c_str(), _T("w")); if (ERROR_SUCCESS == ret) { _ftprintf_s(fp, _T("1 = Type\n")); _ftprintf_s(fp, _T("MED = Name\n")); fclose(fp); // Now give Standard Users permissions to modify/delete the file SetNamedSecurityInfoA("C:\\ProgramData\\MED\\Data.txt", SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, NULL, NULL); }
{ "language": "en", "url": "https://stackoverflow.com/questions/63058494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript set cookie expire time on button click onClick="javascript:document.cookie='n=1'" Im new in javascript I have a btn click will set cookie, how can I set expire time 1 hour on this cookie? A: When you write the cookie to the browser, you need to specify an expiration date or a max age. However, note that max-age is ignored by Interent Explorer 8 and below. So if you're expecting to get usage from that browser, you can just rely on expires. Example: <script type="text/javascript"> function setMyCookie() { var now = new Date(); var expires = new Date(now.setTime(now.getTime() + 60 * 60 * 1000)); //Expire in one hour document.cookie = 'n=1;path=/;expires='+expires.toGMTString()+';'; } </script> And your button can call this function like so: <input type="button" onclick="setMyCookie();">Set Cookie</input> Note that I've also included the path to indicate that this cookie is site-wide. You can read more about expiring cookies with the date or max-age here: http://mrcoles.com/blog/cookies-max-age-vs-expires/ A: You can do: onClick="setupCookie();" function setupCookie() { document.cookie = "n=1"; setTimeout(function() { document.cookie = "n=0"; }, 3600000); // 1 hour } A: On click you can call some javascript function and while creating cookie itself you can set expire time please refer this javascript set cookie with expire time
{ "language": "en", "url": "https://stackoverflow.com/questions/18638265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to make a field label in forms datasheet mode to be multi-line? I need a reasonably long label name but don't want to make the datasheet column unnecessarily large since the corresponding data is not large. Is there a way to get Access to break the label into multiple lines? Thanks A: Based off of the question here: How to alter title bar height for access form? and here: http://www.pcreview.co.uk/threads/how-can-you-change-an-access-datasheet-column-header-height-or-wra.3309187/, No, Access doesn't have this capability.
{ "language": "en", "url": "https://stackoverflow.com/questions/30712810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to delete items from object array where some keys have duplicate value? I want to delete rows from an object array that have the same id, but other keys are different. For example, I have the following Array: testArray = [ {id: 1, type: 1} {id: 2, type: undefined} {id: 3, type: 0} {id: 3, type: undefined} {id: 4, type: 0} ]; testArray[2] and testArray[3] have the same id value, but I want to delete the one that has the type undefined. Final array should look like: testArray = [ {id: 1, type: 1} {id: 2, type: undefined} {id: 3, type: 0} {id: 4, type: 0} ]; A: You could seach for same id in the result set and replace if the former type is undefined. var array = [{ id: 1, type: 1 }, { id: 2, type: undefined }, { id: 3, type: undefined }, { id: 3, type: 0 }, { id: 4, type: 0 }], result = array.reduce((r, o) => { var index = r.findIndex(q => q.id === o.id) if (index === -1) r.push(o); else if (r[index].type === undefined) r[index] = o; return r; }, []); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; } A: Try this const testArray = [ {id: 1, type: 1}, {id: 2, type: undefined}, {id: 3, type: undefined}, {id: 3, type: 0}, {id: 4, type: 0} ]; let newArray = []; testArray.forEach(item => { const newArrayIndex = newArray.findIndex(newItemArray => newItemArray.id === item.id); if (newArrayIndex < 0) return newArray.push(item); if (item.type === undefined) return newArray[newArrayIndex].type = item.type; }); console.log(newArray)
{ "language": "en", "url": "https://stackoverflow.com/questions/61230431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Remove horizontal slice of an image and fill its void by the surrounding areas from above and below Original Images & Desired Outcome I have a batch of PNG images which need the same automated image processing: * *Middle part (red) shall get eliminated entirely and its void filled from above/below *Top (blue) and middle part (red) always have the same height *The bottom part (green) may vary in height How do I achieve this with a free script-able image processing suite? * *Such as ImageMagic or sips A: ImageMagick -chop does just that Man page on -chop: The -chop option removes entire rows and columns, and moves the remaining corner blocks leftward and upward to close the gaps. Also handy is the counterpart function -splice: This will add rows and columns of the current -background color into the given image Chop out the undesired red row → convert in.png -chop x92+0+50 out-chopped.png * *in.png is the original image *out-chopped.png is the desired outcome *-chop x92+0+50: From the default reference point top left (could be changed with -gravity) at x +0px and y +50px (after the top blue part we want to keep) chop out the red segment at full width (because no number is specified before the x and hence it assumes full canvas width) and at a height of 92px (had some seam, hence I added 2px to cut clean) Chop out the undesired red part + insert a thin separator row → → If you want to insert some separator where you chopped out, you can achieve that with -splice. convert in.png -chop x92+0+50 -background black -splice x2+0+50 out-chopped-spliced-separator.png * *-chop already explained above *as the next processing step we change -background to black which applies to all later command in the queue. *-splice x2+0+50 From the default reference point top-left at X 0px and Y 50px splice in a row of full width (nothin specified in front of the x) and of 2px height. Because we have set the background color black in the previous step that 2px row is filled black. Batch processing mogrify -path ../batch-done -chop x92+0+50 -background black -splice x2+0+50 * * *mogrify keeps the same filename of each input file for the corresponding output file. Normally it overwrites in place. But we use: *-path to write the out files to target directory ../batch-done ** to consider all files of your current directory via shell globbing as the input files of your batch. Sources * *v7 man page on -chop *v6 legacy manpage with sample images on Chop, removing rows, columns and edges
{ "language": "en", "url": "https://stackoverflow.com/questions/71470152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing Database stored in Internal Storage of Android Q I would like to access the database that is stored in the Internal storage. I'm using the following code to do so. db_connection_string = "URI=file:" + GetAndroidInternalFilesDir() + "/employee.db"; Debug.Log("db_connection_string" + db_connection_string); db_connection = new SqliteConnection(db_connection_string); Following is my GetAndroidInternalFilesDir function. public static string GetAndroidInternalFilesDir() { string[] potentialDirectories = new string[] { "/storage/Company", "/sdcard/Company", "/storage/emulated/0/Company", "/mnt/sdcard/Company", "/storage/sdcard0/Company", "/storage/sdcard1/Company" }; if(Application.platform == RuntimePlatform.Android) { for(int i = 0; i < potentialDirectories.Length; i++) { if(Directory.Exists(potentialDirectories[i])) { return potentialDirectories[i]; } } } return ""; } The above code works fine in every device that is <Android10 but it fails with Android 11 and above. The SDK Version is set to 30 in my Unity3D. I have also tried changing it to 29 with no success. How can I fix this? UPDATE: I have used the following code to trigger the permission for scoped storage but still, it shows zero success. void initiate() { AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject packageManager = jc.Call<AndroidJavaObject>("getPackageManager"); AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("android.provider.Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION"); AndroidJavaObject launchIntent = packageManager.Call<AndroidJavaObject>("getLaunchIntentForPackage", packageManager); launchIntent = jo.Call<AndroidJavaObject>("setData", packageManager); jc.Call("startActivity", launchIntent); } A: if you want to search in listed directories (not in scope of your app) then you need a MANAGE_EXTERNAL_STORAGE permission. some doc in HERE
{ "language": "en", "url": "https://stackoverflow.com/questions/68062763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Instagram style comments, calculating width of indent based on UIButton I'm working on implementing some instagram style comments. I seem to have everything appearing correctly, except during the first load. I'm using a UIButton for the username, with a label underneath of that with the comment. The UILabel is then indented by the width of the UIButton. It seems the problem is that the UIButton and UILabel are generated and rendered at the same time, so that they don't line up properly - on a second pass things seem to get sorted out. When the tableview cell is first loaded it looks like this: Once the tableview has scrolled away, if you scroll back it renders properly: The cellForRowAtIndexPath looks like this: cell.usernameButton.setTitle(comment.user.userName, forState: UIControlState.Normal) var style = NSMutableParagraphStyle() style.firstLineHeadIndent = cell.usernameButton.frame.width + 2 let s = [NSParagraphStyleAttributeName : style] cell.commentLabel.attributedText = NSAttributedString(string: comment.text, attributes: s) The UITableViewCell just has the two components, a UIButton and UILabel with the UIButton being on top. My question is this: Is there a way to tell the UILabel to render AFTER the UIButton has its autolayout computed?
{ "language": "en", "url": "https://stackoverflow.com/questions/27745638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Line up Pictures in footer I recently added some icons to my site's footer: http://ininkk.com/ They ended up sitting below one another instead of being flush in one line. Specifically the payment options icon (all-in-one image) and the shipping icons (all-in-one). Does anyone know how I can made them sit side by side but with a little space in between? Thanks in advance! A: Try using .visamastercard, .shipna { display: inline-block; } There will be a space between the icon as long as the img tags aren't immediately adjacent to each other (i.e., there's a newline or space between the img tags).
{ "language": "en", "url": "https://stackoverflow.com/questions/38340175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't get a Javascript to call a wcf webservice on localhost or on a crm 2013 server Good afternoon. I don't mean to bump the thread, but it's over a month later and I can't seem to get a post OR get request to work. I have looked at (and tried to incorporate) so many pre-written solutions but each and every time some issue seems to come up that I can't resolve. Any help would be seriously appreciated. Thank you tremendously. an Edit to my problem: I've been trying to create a default WCF service with a simple "Hello message" that accepts POST data per Filburt's suggestion, and I can't get ANYTHING to work at all. Any help would be appreciated. I'm trying to write a test web service for CRM 2013 that will fire from an iframe on a form and call an AJAX enabled WCF webservice sitting on the same crm server. The message will need to send a POST (not get) message to the service. The service seems to be returning a "400" error: "XMLHttpRequest cannot load http://localhost/PasswordResetter/Resetter.svc. Invalid HTTP status code 400". I've tried browsing through 30 or so "Tutorials" and explanations from here, the web, the msdn, and I have no idea what I seem to be doing wrong or why it's not working. I couldn't get it to work from the iframe, nor from a custom html page where the service and html page I created were both on localhost. Lastly, if this question is somehow "improperly formed" for this site, please point out to me how/why so I may modify it appropriately. Thank you in advance for all of your help. Below is my Interface: namespace PasswordResetter { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IResetter" in both code and config file together. [ServiceContract] public interface IResetter { [OperationContract()] string test(string a, string b); } } Below is the method: public class Resetter : IResetter { [WebInvoke(Method = "POST", //was POST BodyStyle = WebMessageBodyStyle.Bare, //This means that our JSOn will map directly to our parameters with no additional processing?? RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Test")] public string test(string a, string b) { //return "Success!: " + a + " " + b; string myJsonString = (new JavaScriptSerializer()).Serialize("Hello World! A: " + a + " b: " + b); return myJsonString; } } Here's the Javascript I'm trying to get working: $(document).ready(function () { $('#iframesubmit').click(function () { //var obj = { username: $("#txtuser").val(), name: $("#txtname").val() }; var obj = '[{ username: $("#password_old").val(), name: $("#password_new").val() }]'; $.ajax({ type: "POST", //was POST contentType: "application/json; charset=utf-8", url: "http://localhost/PasswordResetter/Resetter.svc", //data: "", data: JSON.stringify(obj), //data: "{ 'a': '" + $("#password_old").val() + "', 'b': '" + $("#password_new").val() + "'}",//JSON.stringify(obj), dataType: "json", success: function (data) { alert("Successfully register"); document.getElementById("results").value = "Response: " + data; //service.responseText; $("#iframesubmit").click(); },error: function (xhr) { window.alert('error: ' + xhr.statusText); } }); }); }); And finally my web.config: <?xml version="1.0"?> <configuration> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5"/> </system.web> <system.serviceModel> <bindings> <webHttpBinding> <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true"> <security mode="Transport"> <transport clientCredentialType="None"></transport> </security> </binding> </webHttpBinding> <customBinding> <binding name="CRMPoint.CRM.Services.PasswordResetter.customBinding0"> <!-- <binaryMessageEncoding /> --> <httpTransport /> </binding> </customBinding> </bindings> <services> <service name="PasswordResetter"> <endpoint address="http://localhost/PasswordResetter/Resetter.svc" behaviorConfiguration="PasswordResetter.Service1AspNetAjaxBehavior" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="PasswordResetter.IResetter" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> <service name="Test"> <endpoint address="http://localhost/PasswordResetter/Resetter.svc" binding="customBinding" bindingConfiguration="CRMPoint.CRM.Services.PasswordResetter.customBinding0" contract="PasswordResetter" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> <service name="PasswordResetter.Service1"> <endpoint address="http://localhost/PasswordResetter/Resetter.svc" behaviorConfiguration="PasswordResetter.Service1AspNetAjaxBehavior" binding="webHttpBinding" contract="PasswordResetter.Service1" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <endpointBehaviors> <behavior name="webHttpBehavior"> <webHttp helpEnabled="true" /> </behavior> <behavior name="PasswordResetter.Service1AspNetAjaxBehavior"> <enableWebScript /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> <protocolMapping> <add binding="basicHttpsBinding" scheme="https" /> </protocolMapping> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <standardEndpoints> <webScriptEndpoint> <standardEndpoint name="test" crossDomainScriptAccessEnabled="true" /> </webScriptEndpoint> </standardEndpoints> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> </customHeaders> </httpProtocol> <directoryBrowse enabled="true"/> </system.webServer> </configuration> A: there are some issues in the code... * *Firstly the method decoration with WebInvoke is usually done in the interface not in main class *Second is the method name (test) and the UriTemplate="/Test" should be same. It should be like as follows *UriTemplate="/Test" public string Test(string a, string b) { string myJsonString = (new JavaScriptSerializer()).Serialize("Hello World! A: " + a + " b: " + b); return myJsonString; } *There is an issue where you do an ajax call to this method Replace the following line url: "http://localhost/PasswordResetter/Resetter.svc" with url: "http://localhost/PasswordResetter/Resetter.svc/Test" Hope this will help....
{ "language": "en", "url": "https://stackoverflow.com/questions/28328563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extracting the info from Outlook to Excel I have the code below which gives me the Sender line, Subject line and date information, however is there a way to also get the information from the To line (Name and Email Address). Sub GetFromOutlook() Dim OutlookApp As Outlook.Application Dim OutlookNamespace As Namespace Dim Folder As MAPIFolder Dim OutlookMail As Variant Dim I As Integer Set OutlookApp = New Outlook.Application Set OutlookNamespace = OutlookApp.GetNamespace("MAPI") Set Folder = OutlookNamespace.GetDefaultFolder(olFolderInbox).Folders("Mail").Folders("Test") I = 1 For Each OutlookMail In Folder.Items If OutlookMail.ReceivedTime >= Range("From_date").Value Then Range("eMail_subject").Offset(I, 0).Value = OutlookMail.Subject Range("eMail_date").Offset(I, 0).Value = OutlookMail.ReceivedTime Range("eMail_sender").Offset(I, 0).Value = OutlookMail.SenderName Range("eMail_text").Offset(I, 0).Value = OutlookMail.Body I = I + 1 End If Next OutlookMail Set Folder = Nothing Set OutlookNamespace = Nothing Set OutlookApp = Nothing End Sub A: Loop through all recipients in the MailItem.Recipients collection. If you only need To recipients, check the Recipient.Type property - it ca be olTo, olCC, olBCC for each recip in OutlookMail .Recipients if recip.Type = olTo Then MsgBox recip.Name & ": " & recip.Address End If next As a sidenote, the condition If OutlookMail.ReceivedTime >= Range("From_date").Value will never be satisfied - you cannot use equality comparison for the datetime values, you only only use a range: (value < const1) and (value > const2)
{ "language": "en", "url": "https://stackoverflow.com/questions/58561079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Escaped regular characters Are strings such as "\$" illegal? Why or why not? (Gcc and clang give a warning but treat it as if it was "$") How is \ followed by a character that, with the backslash prepended, doesn't form a reserved escape sequence supposed to behave? A: From this escape sequence reference: ISO C requires a diagnostic if the backslash is followed by any character not listed here. So a compiler is required to print a message about it. After a quick reading of the C11 specification (INCITS+ISO+IEC+9899-2011[2012], following the references in the above linked reference) I find no mention about behavior. While it could be specified somewhere else I doubt it, so the behavior for unspecified escape sequences is, well, unspecified. A: It is explicit in a (non normative) note of the draft n1570 for C11. The 6.4.4.4 Character constants paragraph defines escape sequences as: escape-sequence: * *simple-escape-sequence *octal-escape-sequence *hexadecimal-escape-sequence *universal-character-name simple-escape-sequence: one of * *\' \" \? \ *\a \b \f \n \r \t \v octal-escape-sequence: * *\ octal-digit *\ octal-digit octal-digit *\ octal-digit octal-digit octal-digit hexadecimal-escape-sequence: * *\x hexadecimal-digit *hexadecimal-escape-sequence hexadecimal-digit All other sequences of another character following a \ are not defined here, so the behaviour is unspecified (not undefined) by current standard A note says: 77) ... If any other character follows a backslash, the result is not a token and a diagnostic is required. See ‘‘future language directions’’ (6.11.4). And 6.11.4 says: 6.11.4 Character escape sequences Lowercase letters as escape sequences are reserved for future standardization. Other characters may be used in extensions. Commonly, compilers issue the required warning but just ignore the superfluous \. It is fully conformant for non lowercase letters as it can be a local extension, but it could break in a future version of the C language for lower case letters because it is explicitely a reserved feature
{ "language": "en", "url": "https://stackoverflow.com/questions/40863676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drawing Hexagon like piechart in iOS I am drawing a hexagon with 3 different colors. I gave a color for each line. Here is my code; - (void)drawRect:(CGRect)rect { self.colors = [[NSMutableArray alloc] initWithObjects:[UIColor yellowColor],[UIColor yellowColor],[UIColor blueColor],[UIColor blueColor],[UIColor greenColor],[UIColor greenColor], nil]; [self addPointsToArray]; CGPoint startPoint = [[self.points objectAtIndex:self.pointCounter] CGPointValue]; CGPoint endPoint = [[self.points objectAtIndex:self.pointCounter+1] CGPointValue]; UIColor *color = [self.colors objectAtIndex:self.pointCounter]; [self drawingEachLineWithDifferentBezier:startPoint endPoint:endPoint color:color]; self.pointCounter++; } - (void)addPointsToArray { self.points = [[NSMutableArray alloc] init]; float polySize = self.frame.size.height/2; CGFloat hexWidth = self.frame.size.width; CGFloat hexHeight = self.frame.size.height; CGPoint center = CGPointMake(hexWidth/2, hexHeight/2); CGPoint startPoint = CGPointMake(center.x, 0); for(int i = 3; i >= 1 ; i--) { CGFloat x = polySize * sinf(i * 2.0 * M_PI / 6); CGFloat y = polySize * cosf(i * 2.0 * M_PI / 6); NSLog(@"x = %f, y= %f",x,y); CGPoint point = CGPointMake(center.x + x, center.y + y); [self.points addObject:[NSValue valueWithCGPoint:point]]; } for(int i = 6; i > 3 ; i--) { CGFloat x = polySize * sinf(i * 2.0 * M_PI / 6); CGFloat y = polySize * cosf(i * 2.0 * M_PI / 6); CGPoint point = CGPointMake(center.x + x, center.y + y); [self.points addObject:[NSValue valueWithCGPoint:point]]; } [self.points addObject:[NSValue valueWithCGPoint:startPoint]]; } - (void)drawingEachLineWithDifferentBezier:(CGPoint)startPoint endPoint:(CGPoint)endPoint color:(UIColor *)color { UIBezierPath *path = [UIBezierPath bezierPath]; [path moveToPoint:startPoint]; [path addLineToPoint:endPoint]; CAShapeLayer *pathLayer = [CAShapeLayer layer]; pathLayer.frame = self.bounds; pathLayer.path = path.CGPath; pathLayer.lineCap = kCALineCapRound; //pathLayer.lineCap = kCALineCapSquare; pathLayer.strokeColor = [color CGColor]; pathLayer.fillColor = nil; pathLayer.lineWidth = 15.0f; pathLayer.cornerRadius = 2.0f; pathLayer.lineJoin = kCALineJoinBevel; //pathLayer.lineDashPattern = @[@15]; [self.layer addSublayer:pathLayer]; CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; pathAnimation.duration = 0.3f; pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f]; pathAnimation.toValue = [NSNumber numberWithFloat:1.0f]; pathAnimation.delegate = self; [pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"]; } - (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag{ if (self.pointCounter < self.points.count - 1) { CGPoint startPoint = [[self.points objectAtIndex:self.pointCounter] CGPointValue]; CGPoint endPoint = [[self.points objectAtIndex:self.pointCounter+1] CGPointValue]; UIColor *color = [self.colors objectAtIndex:self.pointCounter]; [self drawingEachLineWithDifferentBezier:startPoint endPoint:endPoint color:color]; self.pointCounter++; } } and I got this view. My purpose is, i want to be yellow color until red point on 3. line. So i thought if i can find red point coodinate, i can add new point in my points array. Than i can draw yellow line from end of 2. line to red point and blue line from red point to end of 3. line. Am i on wrong way? If i am not, how can i find red point coordinate or what is your advice? Thanks for your answer and interest :).
{ "language": "en", "url": "https://stackoverflow.com/questions/33813779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django - language switching with query data Hi I have a search results page which returns queries form the database using this view: def search(request): show_results = False # check if POST if 'q' in request.POST: query = request.POST['q'].strip() # check if GET (paginated) if 'q' in request.GET: query = request.GET['q'].strip() # check if query length is more than 2 characters and proceed if query and len(query) > 2: # if there is a query string show results (as opposed to arriving without any POST/GET show_results = True keywords = query.split() q = Q() for keyword in keywords: q = q & (Q(title__icontains=keyword) | (Q(keywords__icontains=keyword))) query_set = Article.objects.filter(q) # create a new paginator instance with items-per-page paginator = Paginator(query_set, 10) # get the page number from a get param if param is blank then set page to 1 page = int(request.GET.get('page', '1')) # grab the current page from the paginator... items = paginator.page(page) # update search counter with term try: term = Search.objects.get(term=query) except Search.DoesNotExist: # if not already in db, then add query term = Search(term=query) term.counter += 1 term.last_search = datetime.now() term.save() elif len(query) <= 2: short_string = True else: pass #render the template and pass the contacts page into the template return render_to_response('search_results.html', locals(), context_instance=RequestContext(request)) and the template: {% load i18n %} <form action="/i18n/setlang/" name=postlink method="post"> <ul class="lang"> <li class="lang" style="color:gray"> {% for lang in LANGUAGES %} {% if lang.0 != LANGUAGE_CODE %} <input type="hidden" name="language" value="{{ lang.0 }}"> <a href=# onclick="submitPostLink()">{{ lang.1 }}</a> {% else %} {{ lang.1 }} {% endif %} {% endfor %} </li></ul> </form> The language switching works fine on all pages except one case. When I submit the language change data on the search results page where no results have been returned (i.e. empty queryset), I get the following error: UnboundLocalError at /search/ local variable 'query' referenced before assignment I think I need to tweak the view slightly, but I'm not sure where. Any suggestions much appreciated. Traceback: traceback: `Environment: Request Method: GET Request URL: http://localhost:8000/search/ Django Version: 1.3 Python Version: 2.7.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'journal', 'django.contrib.admin'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.csrf.CsrfResponseMiddleware') Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/home/sam/public_html/django- projects/galapagos_research/../galapagos_research/journal/views.py" in search 40. if query and len(query) > 2: Exception Type: UnboundLocalError at /search/ Exception Value: local variable 'query' referenced before assignment A: You haven't defined query if q isn't in POST or GET. Since that's the only place where this error would appear, you must not be passing in q. An empty QuerySet wouldn't cause this error. To be sure, it would help to have the line that triggered the error (the traceback - please). def search(request): show_results = False query = None # set default value for query # check if POST if 'q' in request.POST: query = request.POST['q'].strip() # check if GET (paginated) if 'q' in request.GET: query = request.GET['q'].strip() ########################### # was `query` defined here if 'q' isn't in POST or GET? ########################### # check if query length is more than 2 characters and proceed if query and len(query) > 2: # error probably on this line? A: At the start, query is never set to a default. if 'q' in request.POST: query = request.POST['q'].strip() # check if GET (paginated) if 'q' in request.GET: query = request.GET['q'].strip() Then in your elif, you try to determine the len() of query which isn't defined anywhere yet if 'q' is not in GET or POST. elif len(query) <= 2: short_string = True
{ "language": "en", "url": "https://stackoverflow.com/questions/7246870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running a windows executable within R using wine in ubuntu I am trying to execute a windows only executable called (groundfilter.exe from FUSION) within Rstudio on Ubuntu. I am able to run groundfilter.exe from a terminal using wine as follows: wine C:/FUSION/groundfilter.exe /gparam:0 /wparam:1 /tolerance:1 /iterations:10 test_Grnd.las 1 test.las The executes fine and produces file test_Grnd.las OK. But when i try to do this from within Rstudio using system() it doesn't quite work, and no output file is produced (unlike from terminal). I do this: command<-paste("wine C:/FUSION/groundfilter.exe", "/gparam:0 /wparam:1 /tolerance:1 /iterations:10", "/home/martin/Documents/AUAV_Projects/test_FUSION/test_FUSION/test_GroundPts.las", "1", "/home/martin/Documents/AUAV_Projects/test_FUSION/test_FUSION/test.las",sep=" ") system(command) The executable appears to be called OK in Rstudio console, but run as if no file names were supplied. The output( truncated ) is: system(command) GroundFilter v1.75 (FUSION v3.60) (Built on Oct 6 2016 08:45:14) DEBUG --Robert J. McGaughey--USDA Forest Service--Pacific Northwest Research Station Filters a point cloud to identify bare-earth points Syntax: GroundFilter [switches] outputfile cellsize datafile1 datafile2 ... outputfile Name for the output point data file (stored in LDA format) This is the same output from the terminal if the file names are left off, so somehow my system call in R is not correct? A: I think wine will not find paths like /home/martin/.... One possibility would be to put groundfilter.exe (and possibly dlls it needs) into the directory you want to work with, and set the R working directory to that directory using setwd(). The other possibility I see would be to give a path that wine understands, like Z:/home/martin/.... This is not an authoritative answer, just my thoughts, so please refer to the documentation for the real story.
{ "language": "en", "url": "https://stackoverflow.com/questions/41754006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Check if a UTF-8 character or string can be converted into Windows-1252 in Javascript? I need to store form data sent from the browser into a database that stores text in Windows-1252. Since modern browsers will send the form data to my backend as UTF-8, I plan to validate the input both on the browser as well as in the backend to make sure I am not storing garbage into the database. Is there a function in Javascript that checks if a UTF-8 character or string can be converted into Windows-1252 so that I can warn the user that an illegal character was detected before form submission? For example let's say I have a function is_w1252(unicodeChar) that has the following inputs/outputs: utf8 Input | Output ---------------------------------------------------------- 'a' | true 'è' | true (has windows-1252 equivalent: 0xE8) 'fèèbar' | true '' | false (no windows-1252 equivalent) Is there such a thing? My PHP backend is much more simple; I plan to use iconv() to convert the form data into Windows-1252 before storing it into the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/72580692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Removing the first instance of an element (Haskell) I am new to working with haskell but I tried to follow the answer to this question to create my own function that takes a list and an element as input and removes the first instance of said element from list. My code looks like this: rem1 :: Eq a => [a] -> a -> [a] rem1 [] _ = [] rem1 ys _ = ys rem1 (y:ys) x | x == y = ys | otherwise = y : rem1 ys x The code compiles when I load it in ghci, but when I test it the list is unchanged. Like so: Ok, one module loaded. ghci> rem1 "abab" 'b' "abab" When it should be like this: Ok, one module loaded. ghci> rem1 "abab" 'b' "aab" How do I fix this? A: For any argument except an empty list, the second case always fires: rem1 ys _ = ys It says "whatever the arguments are, always return the first argument". So it does. You were probably thinking about the second case "in comparison" with the third case: the third case matches on (:), and the second case matches "when there is no (:)". But that's not how pattern matching works. A pattern like ys matches anything, anything at all, regardless of whether it's the (:) constructor or not. So your second case matches any parameter. To fix, just remove the second case. You don't need it.
{ "language": "en", "url": "https://stackoverflow.com/questions/69125973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL query to retrieve records that fall outside of a time range defined between two datetime fields I am trying to find anomolies in our work order system, and one of my where statements needs to retrieve records where work occurs out of a certian time frame in the last 30 days. I am trying to determine if any work occured before 6am or after 4pm. My database has a datetime field storing this information. So far i have this query: Select WORKORDERID, DESCRIPTION, actualstartdate, actualfinishdate FROM [CityWorks].[AZTECA].[WORKORDER] WHERE actualstartdate BETWEEN '2014-05-05 01:00:00.000' AND '2014-06-05 23:00:00.000' order by actualstartdate desc How would i add a where statement to see if work in the actualstartdate column occured before 'yyyy-mm-dd 06:00:00.000' or after 'yyyy-mm-dd 16:00:00.000' in the actualfinishdate while still pulling from the last 30 days? A: Quick-and-dirty solution: select all rows and subtract the non-suspect rows Demo: http://sqlfiddle.com/#!3/f0651/1 Select WORKORDERID, DESCRIPTION, actualstartdate, actualfinishdate FROM [CityWorks].[AZTECA].[WORKORDER] WHERE actualstartdate BETWEEN '2014-05-05 01:00:00.000' AND '2014-06-05 23:00:00.000' EXCEPT Select WORKORDERID, DESCRIPTION, actualstartdate, actualfinishdate FROM [CityWorks].[AZTECA].[WORKORDER] WHERE actualstartdate BETWEEN '2014-05-05 01:00:00.000' AND '2014-06-05 23:00:00.000' AND actualstartdate >= DATEADD(hour, 6,CAST(CAST(actualstartdate AS date) AS datetime)) AND actualfinishdate <= DATEADD(hour,16,CAST(CAST(actualfinishdate AS date) AS datetime)) AND CAST(actualstartdate AS date) = CAST(actualfinishdate AS date) A: SQL Fiddle MS SQL Server 2008 Schema Setup: CREATE TABLE WORKORDER ([WORKORDERID] int, [DESCRIPTION] varchar(3), [actualstartdate] datetime, [actualfinishdate] datetime) ; INSERT INTO WORKORDER ([WORKORDERID], [DESCRIPTION], [actualstartdate], [actualfinishdate]) VALUES (1, 'w1', '2014-05-07 01:00:00', '2014-05-07 05:00:00'), (2, 'w2', '2014-05-07 04:00:00', '2014-05-07 12:00:00'), (3, 'w3', '2014-05-07 05:59:00', '2014-05-07 12:00:00'), (4, 'w4', '2014-05-07 06:00:00', '2014-05-07 12:00:00'), (5, 'w5', '2014-05-07 06:01:00', '2014-05-07 16:00:00'), (6, 'w6', '2014-05-07 06:01:00', '2014-05-07 16:01:00'), (7, 'w7', '2014-05-07 06:01:00', '2014-05-08 12:01:00') ; Query 1: Select WORKORDERID, DESCRIPTION, actualstartdate, actualfinishdate FROM [WORKORDER] WHERE actualstartdate BETWEEN '2014-05-05 01:00:00.000' AND '2014-06-05 23:00:00.000' and (CAST(actualstartdate AS date) = CAST(actualfinishdate AS date) and (((DATEPART(hh, actualstartdate)*3600)+ (DATEPART(mi, actualstartdate)*60)+ DATEPART(ss, actualstartdate)) < 21600 or ((DATEPART(hh, actualfinishdate)*3600)+ (DATEPART(mi, actualfinishdate)*60)+ DATEPART(ss, actualfinishdate)) > 57600) or CAST(actualstartdate AS date) <> CAST(actualfinishdate AS date)) order by actualstartdate desc Results: | WORKORDERID | DESCRIPTION | ACTUALSTARTDATE | ACTUALFINISHDATE | |-------------|-------------|----------------------------|----------------------------| | 6 | w6 | May, 07 2014 06:01:00+0000 | May, 07 2014 16:01:00+0000 | | 7 | w7 | May, 07 2014 06:01:00+0000 | May, 08 2014 12:01:00+0000 | | 3 | w3 | May, 07 2014 05:59:00+0000 | May, 07 2014 12:00:00+0000 | | 2 | w2 | May, 07 2014 04:00:00+0000 | May, 07 2014 12:00:00+0000 | | 1 | w1 | May, 07 2014 01:00:00+0000 | May, 07 2014 05:00:00+0000 | A: You can use the datepart function to look at the hour: SELECT WORKORDERID , DESCRIPTION , actualstartdate , actualfinishdate FROM [CityWorks].[AZTECA].[WORKORDER] WHERE actualstartdate BETWEEN '2014-05-05 01:00:00.000' AND '2014-06-05 23:00:00.000' AND (DATEPART(HOUR, actualstartdate) <= 6 OR DATEPART(HOUR, actualstartdate) => 16) ORDER BY actualstartdate DESC A: Select WORKORDERID, DESCRIPTION, actualstartdate, actualfinishdate FROM [CityWorks].[AZTECA].[WORKORDER] WHERE actualstartdate BETWEEN '2014-05-05 01:00:00.000' AND '2014-06-05 23:00:00.000' and (CONVERT(time,actualstartdate )<'06:00' or CONVERT(time,actualfinishdate )> '16:00') order by actualstartdate desc A: You can easily get the hour portion of the date as follows: DATEPART(hh, actualstartdate); Use it as follows: Select WORKORDERID, DESCRIPTION, actualstartdate, actualfinishdate FROM [CityWorks].[AZTECA].[WORKORDER] WHERE actualstartdate BETWEEN '2014-05-05 01:00:00.000' AND '2014-06-05 23:00:00.000' AND (DATEPART(hh, actualstartdate) < 6 or (DATEPART(hh, actualfinishdate) >= 16) order by actualstartdate desc This will get all rows between your given dates that occurred before six in the morning or after four at night. Edit: If you want to allow an actualfinishdate of exactly 16 hundred you can change the second clause to: or actualfinishdate > DATEADD(hh, 16, cast(actualfinishdate as date)) This would check if the actual finish date is after 4.
{ "language": "en", "url": "https://stackoverflow.com/questions/24085363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Multiple elements with inline "this.select" Javascript; only 1st one gets selected I've got a page that has multiple instances of a form. Each form has, among its other fields, this field: <input class="span1" type="text" name="abc" id="abc" value="25" placeholder="25" onfocus="if (this.value==this.defaultValue) this.value=''; else this.select()" onblur="if (!this.value) this.value=this.defaultValue"> The problem is that when I click in any instance of the above field, the focus gets put to the first occurrence of the field. this.select isn't being restricted to that specific element. How can I ensure that the JS of each field targets that field for its operations? I'm pretty sure this is an elementary JS newb issue, but since I'm a JS newb... ;) A: After reading the Quirksmode article on the subject, I realized that the problem was exactly what was being described there - the function was being referred instead of copied. From what I gathered, it's impossible to have inline JS work like I wanted for multiple instances on a single page. My solution was to extract the JS from the HTML tags and make it into functions. I used some jQuery to do so (because jQuery!). :p Here's the HTML: <input class="span1 hasDefaultValue" type="text" name="abc" value="25" placeholder="25"> And the JS: <script type="text/javascript"> function fieldFocus() { if (this.value==this.defaultValue) { this.value=''; } else { this.select(); } } function fieldBlur() { if (!this.value) { this.value=this.defaultValue; } } $(document).ready(function() { $("input.hasDefaultValue").click(fieldFocus); $("input.hasDefaultValue").blur(fieldBlur); }); </script> I'm sure that can be made more streamlined, but I wanted to post the answer ASAP. I might update with a streamlined solution later.
{ "language": "en", "url": "https://stackoverflow.com/questions/17570648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to create count object array using date array javascript My javascript array like that. var datearray = [ "2016-01-13", "2016-01-18", "2016-01-30", "2016-02-13", "2016-02-18", "2016-02-28", "2016-03-13", "2016-03-23", "2016-03-30", "2016-04-13", "2016-04-18", "2016-04-30", "2016-05-13", "2016-05-18", "2016-05-28", "2016-06-13", "2016-06-23", "2016-06-30", "2016-08-22" ] but my searching dates are startDate = 2015-12-01; and endDate = 2016-09-30; I want to get new date array between above startDate and endDate. This new array will display like this, var newOjArray = [ {"2015-12":"0"}, {"2016-01":"3"}, {"2016-02":"3"}, {"2016-03":"3"}, {"2016-04":"3"}, {"2016-05":"3"}, {"2016-06":"3"}, {"2016-07":"0"}, {"2016-08":"1"}, {"2016-09":"0"} ]; values meaning total count of considering date range. How I created It. A: A complete proposal. With an array with the wanted grouped result. function getGroupedData(dates, from, to) { function pad(s, n) { return s.toString().length < n ? pad('0' + s, n) : s; } var temp = Object.create(null), result = [], fromYear = +from.slice(0, 4), fromMonth = +from.slice(5, 7), toYear = +to.slice(0, 4), toMonth = +to.slice(5, 7), o, k; datearray.forEach(function (d) { var k = d.slice(0, 7); temp[k] = (temp[k] || 0) + 1; }); while (true) { k = pad(fromYear, 4) + '-' + pad(fromMonth, 2); o = {}; o[k] = (temp[k] || 0).toString(); result.push(o); if (fromYear === toYear && fromMonth === toMonth) { break; } fromMonth++; if (fromMonth > 12) { fromMonth = 1; fromYear++; } } return result; } var datearray = ["2016-01-13", "2016-01-18", "2016-01-30", "2016-02-13", "2016-02-18", "2016-02-28", "2016-03-13", "2016-03-23", "2016-03-30", "2016-04-13", "2016-04-18", "2016-04-30", "2016-05-13", "2016-05-18", "2016-05-28", "2016-06-13", "2016-06-23", "2016-06-30", "2016-08-22"]; console.log(getGroupedData(datearray, '2015-12-01', '2016-09-30')); A: You can use Array.filter to filter through this array. Taking advantage of your particular date format, we do not need to do any date arithmetic, we can simply compare dates as strings and use localeCompare() to compare them: var datearray = [ "2016-01-13", "2016-01-18", "2016-01-30", "2016-02-13", "2016-02-18", "2016-02-28", "2016-03-13", "2016-03-23", "2016-03-30", "2016-04-13", "2016-04-18", "2016-04-30", "2016-05-13", "2016-05-18", "2016-05-28", "2016-06-13", "2016-06-23", "2016-06-30", "2016-08-22" ]; var startDate = "2015-12-01"; var endDate = "2016-01-30"; var filteredArray = datearray.filter(function(item){ return item.localeCompare( startDate ) > -1 && endDate.localeCompare( item ) > -1; }); console.log( filteredArray ); Now, you have the filteredArray and you can simply iterate through it to count the number of dates falling in a month. A: You may try this: Underscore.js has been used to manipulate data. var datearray=["2016-01-13","2016-01-18","2016-01-30","2016-02-13","2016-02-18","2016-02-28","2016-03-13","2016-03-23","2016-03-30","2016-04-13","2016-04-18","2016-04-30","2016-05-13","2016-05-18","2016-05-28","2016-06-13","2016-06-23","2016-06-30","2016-08-22"]; var boxingDay = new Date("12/01/2015"); var nextWeek = new Date("09/30/2016"); function getDates( d1, d2 ){ var oneDay = 24*3600*1000; for (var d=[],ms=d1*1,last=d2*1;ms<last;ms+=oneDay){ var new_Date=new Date(ms); d.push( new_Date.getFullYear()+"-"+("0" + (new_Date.getMonth() + 1)).slice(-2) ); } return d; } var x=[]; _.each(datearray, function(e){x.push(e.substring(0, 7));}); var z= _.uniq(getDates( boxingDay, nextWeek )); var f=x.concat(_.uniq(getDates( boxingDay, nextWeek ))); document.getElementById("xx").innerHTML=JSON.stringify(_.countBy(f)); <script src="http://underscorejs.org/underscore-min.js"></script> <div id="xx"></div> A: If you looking for a more ES6 way then check it out: var dateArray = ["2016-01-13", "2016-01-18", "2016-01-30", "2016-02-13", "2016-02-18", "2016-02-28", "2016-03-13", "2016-03-23", "2016-03-30", "2016-04-13", "2016-04-18", "2016-04-30", "2016-05-13", "2016-05-18", "2016-05-28", "2016-06-13", "2016-06-23", "2016-06-30", "2016-08-22"]; var group = {}; dateArray.forEach(date => group[(date = date.substr(0, 7))] = (group[date] || []).concat(date) ); var result = Object.keys(group) .map(date => ({ [date]: group[date].length })); console.log(result) If your date format is as the date array then the easiest way would be to use substr if the length is not constant then you can split it by spacer and then get the two first values. And if it's totally a date string you can create a date from this and convert it to your desired string as key of your object.
{ "language": "en", "url": "https://stackoverflow.com/questions/37988786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Vue.set insert an item at a specific index this is my items object: items: { houses:{ name: 'Houses', url: '/houses', icon: 'icon-home', }, users:{ name: 'Users', url: '/users', icon: 'icon-people', }, } I use vue.set to add item in my items object: Vue.set(nav.items, 'agency_home', {name: 'Agency', url: '/pages/404', icon: 'icon-home'} ) This code works, it adds it after the users key. However, I want to add it after the the houses key. A: Instead of set, you would use the splice array method, which will invoke the update.
{ "language": "en", "url": "https://stackoverflow.com/questions/53018618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Sendgrid Design template, how to use handlebar iteration for table? I'm using SendGrid online "Design" template, with a module "code". In their documentation (https://sendgrid.com/docs/ui/sending-email/editor/#code-modules), they say that de code editor does not modify or validate any HTML. If I write this piece of code inside the code module: <ul> {{#each items}} <li>test</li> {{/each}} </ul> <table> <tbody> {{#each items}} <tr> <td>Col 1</td> <td>Col 2</td> </tr> {{/each}} </tbody> </table> it results in: <ul> {{#each items}} <li>test</li> {{/each}} </ul> {{#each items}}{{/each}} <table> <tbody><tr> <td>Col 1</td> <td>Col 2</td> </tr></tbody> </table> We can see that the {{each}} function stays in the right place for the ul, but is remove from inside of the table. Is this a temporary bug? How can I do this simple operation? Thanks for your help A: I get the same issue. Definitely a bug in the Design Editor. My work around was to: * *Style the email with the Design Editor. *Export HTML. *Go back and create a new version of the transaction email using the 'Code Editor' and not the 'Design Editor'. *Paste in the previously exported HTML. *Find the table that needs the {{each}} loop and place the functions exactly as you did. A: I found a undocumented way to make this works. You will need to comment out the each helper like this: <table> <tbody> <!-- {{#each items}} --> <tr> <td>Col 1</td> <td>Col 2</td> </tr> <!-- {{/each}} --> </tbody> </table>
{ "language": "en", "url": "https://stackoverflow.com/questions/53614202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Distinguish design and implementation detail when doing TDD I have been doing Unit tests for a while. I am a little confused about the boundary between design and implementation details when doing TDD. For example, I have two interfaces, service and adapter, that process employee information (add, get, delete ...) public interface IEmployeeService { Employee GetEmployeeById(int id) } public interface IEmployeeAdapter { private IEmployeeService _service Employee GetEmployeeById(int id) } By design, service reads data from storage such as database, file system or web service, adapter uses service to get certain information. This design looks fine until I start writing unit test for the adapters. The problem is I need to know whether adapter.GetEmployeeById(id) will call service.GetEmployeeById(id) (or other methods) to determine whether I need to mock services in the test method. That makes feel like I am kind of considering the implementation detail when writing unit test. Is there anything wrong? A: Unit tests are white-box tests, so you are fully aware of what goes on inside the system under test. There's nothing wrong with using that information to help determine what to mock. Yes, it's an implementation detail, and it can make your test "fragile" in the sense of needing to change it when your underlying implementation changes. But in a case like this, I would want to know that when I call adapter.foo(), it calls underlyingService.foo(), and mocks are perfect for this. A: The best rule of thumb I can advice is: try to use behavior setup/verification only in cases it is a part of your contract. In case you test behavior but what you are actually interested in is state, tests tends to break lot more often as the behavior is in fact an implementation detail. In your example, if no one cares for the exact boundary between service and an adapter, feel free to use state verification on adapter class. But if your adapter is supposed to translate specific message calls patterns to another well-defined set of messages, you might want to use behavior verification instead. In other words, if adapter.GetEmployeeById(id) needs to translate to service.GetEmployeeById(id) then it is not an implementation detail.
{ "language": "en", "url": "https://stackoverflow.com/questions/30946217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to change a Vimeo's video privacy via API (PHP)? I'm trying to set a Vimeo's video privacy via API (v3.4) request. Sending an HTTP PATCH to https://api.vimeo.com/videos/{videoId} with Headers: "Authorization" => $api_key, "Accept" => "application/vnd.vimeo.*+json;version=3.4" Body: "form_params" => array( "privacy" => array( "embed" => "public" ), "name" => $video_name, "description" => $video_description ) ...properly changes the video's name and description (the API token has edit permission), but the privacy setting remains untouched. I've followed every step specified by the Vimeo's API Documentation but I can't get it to work. What am I doing wrong? A: The privacy field is actually privacy.{key}. So, the correct code is "form_params" => array( "privacy.embed": "public" "name" => $video_name, "description" => $video_description )
{ "language": "en", "url": "https://stackoverflow.com/questions/52080930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sFlow data generator tool I am developing an application to parse the sFlow data. For this I need a sFlow data generator, which can be used as an input to my application. Is there any open source/tools/linux network commands which I can use to generate sFlow data? Platform is Ubuntu A: The Host sFlow agent runs on Ubuntu and can generate sFlow using iptables and ulog/nflog. Alternatively, you could use Mininet to simulate a network and enable sFlow in the virtual switches. sflowtool is a command line sFlow decoder that you can use to check your parser.
{ "language": "en", "url": "https://stackoverflow.com/questions/35284007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: change background resource of an image in the gridview in android here am trying to change the background resource for the image, am success in that, but the problem is, when i clicking on all the items in the gridview every item has changes in the background resource, my question is if i click on item which is 0 position it has to change the background resource image, and again if i click on the item which is in 1 position it has to change the background resource and as well as a image on 0 position has to set normal image like without background resource comes to normal state. public void onItemClick(AdapterView<?> arg0, View vv, int arg2, long arg3) { // TODO Auto-generated method stub vv.setBackgroundResource(android.R.drawable.btn_default); } Provide me to set only one selected item has to change the image. Thanks in advance. A: You need modify your adapter to set background for checked items. For Example: @Override public View getView(int position, View convertView, ViewGroup parent) { // creating view if(item.isChecked()){ veiw.setBackgroundResource(android.R.drawable.btn_default); } return view; } A: You actually need to modify the Adapter and for that i will refer you to this question here How to set an image as background image on a click? Check the accepted answer and do it as described and you are good to go
{ "language": "en", "url": "https://stackoverflow.com/questions/21981523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selenium Webdriver C# How to test an element is not present? This element can be found when a required field has been filled out: IWebElement e1SK = Driver.Instance.FindElement(By.XPath(baseXPathSendKeys + "div[2]/textarea")); When the required field is not filled in, the above element should not be present. The test throws an exception: OpenQA.Selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with Is this something I need to create a method for or is it even more simple than that? If you could show an example, it would be helpful, I'm still fairly new to C# and Selenium Webdriver. I have read that I might be able to user something called findwebelements then checking to make sure the result has a length of zero, but am not sure how to implement that either. A: you can use the below code snippet. If you are writing logic within the step definition method then the below code would be handy as method nesting is not advisable. Boolean elementnotpresent; Try { IWebElement element = Driver.FindElement(By.XPath("Element XPath")); } catch (NoSuchElementException) { elementnotpresent=true; } if (elementnotpresent == true) { Console.WriteLine("Element not present"); } else { throw new Exception("Element is present"); } A: Here's a straightforward approach to the problem: if (Driver.Instance.FindElements(By.XPath(baseXPathSendKeys + "div[2]/textarea")).Count != 0) { // exists } else { // doesn't exist } You could create a method Exists(By) to test elements: public bool Exists(By by) { if (Driver.Instance.FindElements(by).Count != 0) { return true; } else { return false; } } Then call it when you want to test something: By by = By.XPath(baseXPathSendKeys + "div[2]/textarea") if (Exists(by)) { // success } A: I had a strange case, when selenium was not throwing a NoSuchElementException exception, but MakeHttpRequest timed out. So i had come up with idea, that i got the attribute innerHTML of parent HTML element, and assert that it doesnot contain not wanted element. Assert.IsTrue(!parent.GetAttribute("innerHTML").Contains("notWantedElement")); A: I know this was asked a while ago but you can try something like this var wait = new WebDriverWait(driver, Timespan.FromSeconds(10)); wait.Until(driver => driver.FindElements(By.WhateverYourLocatorIs("")).Count == 0);
{ "language": "en", "url": "https://stackoverflow.com/questions/26963392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Remove a laravel passport user token In my unit test, I have a user for whom I generate a token: $tokenString = $this->user->createToken('PHPunit', ['example'])->accessToken; How can I afterward delete this user's token? A: This is what I do when a user logged out. public function logout() { Auth::user()->tokens->each(function($token, $key) { $token->delete(); }); return response()->json('Successfully logged out'); } This code will remove each token the user generated. A: I think something like this can revoke the token: $this->user->token()->revoke() Based on this link. A: Laravel Sanctum documentation stated 3 different ways to revoke tokens. you can find it here. but for most cases we just revoke all user's tokens via: // Revoke all tokens... auth()->user()->tokens()->delete(); note: for some reason intelephense gives an error saying tokens() method not defined but the code works fine. Hirotaka Miyata found a workaround here. so the over all logout method can be something like this: public function logout() { //the comment below just to ignore intelephense(1013) annoying error. /** @var \App\Models\User $user **/ $user = Auth::user(); $user->tokens()->delete(); return [ 'message' => 'logged out' ]; } A: the best working solution is this public function logout(LogoutRequest $request): \Illuminate\Http\JsonResponse { if(!$user = User::where('uuid',$request->uuid)->first()) return $this->failResponse("User not found!", 401); try { $this->revokeTokens($user->tokens); return $this->successResponse([ ], HTTP_OK, 'Successfully Logout'); }catch (\Exception $exception) { ExceptionLog::exception($exception); return $this->failResponse($exception->getMessage()); } } public function revokeTokens($userTokens) { foreach($userTokens as $token) { $token->revoke(); } } A: public function __invoke(Request $request) { $request->user() ->tokens ->each(function ($token, $key) { $this->revokeAccessAndRefreshTokens($token->id); }); return response()->json('Logged out successfully', 200); } protected function revokeAccessAndRefreshTokens($tokenId) { $tokenRepository = app('Laravel\Passport\TokenRepository'); $refreshTokenRepository = app('Laravel\Passport\RefreshTokenRepository'); $tokenRepository->revokeAccessToken($tokenId); $refreshTokenRepository->revokeRefreshTokensByAccessTokenId($tokenId); }
{ "language": "en", "url": "https://stackoverflow.com/questions/58280790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Change factor to numeric in dataframe and drop missing values I have downloaded the data and would like to change columns named USD and EUR to numeric and also treat the column date as a date. I would also like to get rid of the missing values in the dataframe named result3. library(dplyr) library(ggplot2) library(reshape2) getNBPRates <- function(year) { url1 <- sprintf( paste0("https://www.nbp.pl/kursy/Archiwum/archiwum_tab_a_", year, ".csv"), year) url1 <- read.csv2(url1, header=TRUE, sep=";", dec=",") %>% select(data, X1USD, X1EUR) %>% rename(usd=X1USD, eur=X1EUR, date=data) %>% slice(-1) transform(url1, date = as.Date(as.character(date), "%Y%m%d")) } a <- getNBPRates(year=2015) head(as.data.frame(a)) years<- c(2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020) result <- lapply(years, getNBPRates) result3 <- Reduce(rbind, result) A: getNBPRates <- function(year) { url1 <- sprintf(paste0("https://www.nbp.pl/kursy/Archiwum/archiwum_tab_a_", year, ".csv")) url1 <- read.csv2(url1, header=TRUE, sep=";", dec=",", fileEncoding = "Windows-1250") url1 <- url1 |> select(data, X1USD, X1EUR) |> slice(-1) |> filter(row_number()<= n()-3) |> mutate(data = as.Date(data, format = "%Y%m%d"), usd = as.numeric(gsub(",", ".", X1USD)), eur = as.numeric(gsub(",", ".", X1EUR))) |> select(-c(X1USD, X1EUR)) } years<- c(2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020) result <- lapply(years, getNBPRates) result3 <- Reduce(rbind, result) And what you understand with "to get rid of the missing values in dataframe named result3."? If that's the missing dates, then you have to substitute it with some logic. If I'm not mistaken - if there is no NBP for particular day, a last one has to be taken. A: To change a column to numeric you can use as.numeric(column_name) Based on the date format in the archiwum_tab_a_2015.csv file, you can change the date column with as.Date(column_name, format = "%Y%m%d") To remove all missing values you can use complete.cases(data): mydata[complete.cases(mydata),]
{ "language": "en", "url": "https://stackoverflow.com/questions/70838926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convenient C++ struct initialisation I'm trying to find a convenient way to initialise 'pod' C++ structs. Now, consider the following struct: struct FooBar { int foo; float bar; }; // just to make all examples work in C and C++: typedef struct FooBar FooBar; If I want to conveniently initialise this in C (!), I could simply write: /* A */ FooBar fb = { .foo = 12, .bar = 3.4 }; // illegal C++, legal C Note that I want to explicitly avoid the following notation, because it strikes me as being made to break my neck if I change anything in the struct in the future: /* B */ FooBar fb = { 12, 3.4 }; // legal C++, legal C, bad style? To achieve the same (or at least similar) in C++ as in the /* A */ example, I would have to implement an annoying constructor: FooBar::FooBar(int foo, float bar) : foo(foo), bar(bar) {} // -> /* C */ FooBar fb(12, 3.4); Which feels redundant and unnecessary. Also, it is pretty much as bad as the /* B */ example, as it does not explicitly state which value goes to which member. So, my question is basically how I can achieve something similar to /* A */ or better in C++? Alternatively, I would be okay with an explanation why I should not want to do this (i.e. why my mental paradigm is bad). EDIT By convenient, I mean also maintainable and non-redundant. A: Extract the contants into functions that describe them (basic refactoring): FooBar fb = { foo(), bar() }; I know that style is very close to the one you didn't want to use, but it enables easier replacement of the constant values and also explain them (thus not needing to edit comments), if they ever change that is. Another thing you could do (since you are lazy) is to make the constructor inline, so you don't have to type as much (removing "Foobar::" and time spent switching between h and cpp file): struct FooBar { FooBar(int f, float b) : foo(f), bar(b) {} int foo; float bar; }; A: Your question is somewhat difficult because even the function: static FooBar MakeFooBar(int foo, float bar); may be called as: FooBar fb = MakeFooBar(3.4, 5); because of the promotion and conversions rules for built-in numeric types. (C has never been really strongly typed) In C++, what you want is achievable, though with the help of templates and static assertions: template <typename Integer, typename Real> FooBar MakeFooBar(Integer foo, Real bar) { static_assert(std::is_same<Integer, int>::value, "foo should be of type int"); static_assert(std::is_same<Real, float>::value, "bar should be of type float"); return { foo, bar }; } In C, you may name the parameters, but you'll never get further. On the other hand, if all you want is named parameters, then you write a lot of cumbersome code: struct FooBarMaker { FooBarMaker(int f): _f(f) {} FooBar Bar(float b) const { return FooBar(_f, b); } int _f; }; static FooBarMaker Foo(int f) { return FooBarMaker(f); } // Usage FooBar fb = Foo(5).Bar(3.4); And you can pepper in type promotion protection if you like. A: Many compilers' C++ frontends (including GCC and clang) understand C initializer syntax. If you can, simply use that method. A: Since style A is not allowed in C++ and you don't want style B then how about using style BX: FooBar fb = { /*.foo=*/ 12, /*.bar=*/ 3.4 }; // :) At least help at some extent. A: Designated initializes will be supported in c++2a, but you don't have to wait, because they are officialy supported by GCC, Clang and MSVC. #include <iostream> #include <filesystem> struct hello_world { const char* hello; const char* world; }; int main () { hello_world hw = { .hello = "hello, ", .world = "world!" }; std::cout << hw.hello << hw.world << std::endl; return 0; } GCC Demo MSVC Demo Update 2021 As @Code Doggo noted, anyone who is using Visual Studio 2019 will need to set /std:c++latest  for the "C++ Language Standard" field contained under Configuration Properties -> C/C++ -> Language. A: Yet another way in C++ is struct Point { private: int x; int y; public: Point& setX(int xIn) { x = Xin; return *this;} Point& setY(int yIn) { y = Yin; return *this;} } Point pt; pt.setX(20).setY(20); A: Option D: FooBar FooBarMake(int foo, float bar) Legal C, legal C++. Easily optimizable for PODs. Of course there are no named arguments, but this is like all C++. If you want named arguments, Objective C should be better choice. Option E: FooBar fb; memset(&fb, 0, sizeof(FooBar)); fb.foo = 4; fb.bar = 15.5f; Legal C, legal C++. Named arguments. A: I know this question is old, but there is a way to solve this until C++20 finally brings this feature from C to C++. What you can do to solve this is use preprocessor macros with static_asserts to check your initialization is valid. (I know macros are generally bad, but here I don't see another way.) See example code below: #define INVALID_STRUCT_ERROR "Instantiation of struct failed: Type, order or number of attributes is wrong." #define CREATE_STRUCT_1(type, identifier, m_1, p_1) \ { p_1 };\ static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\ #define CREATE_STRUCT_2(type, identifier, m_1, p_1, m_2, p_2) \ { p_1, p_2 };\ static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\ static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\ #define CREATE_STRUCT_3(type, identifier, m_1, p_1, m_2, p_2, m_3, p_3) \ { p_1, p_2, p_3 };\ static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\ static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\ static_assert(offsetof(type, m_3) >= (offsetof(type, m_2) + sizeof(identifier.m_2)), INVALID_STRUCT_ERROR);\ #define CREATE_STRUCT_4(type, identifier, m_1, p_1, m_2, p_2, m_3, p_3, m_4, p_4) \ { p_1, p_2, p_3, p_4 };\ static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\ static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\ static_assert(offsetof(type, m_3) >= (offsetof(type, m_2) + sizeof(identifier.m_2)), INVALID_STRUCT_ERROR);\ static_assert(offsetof(type, m_4) >= (offsetof(type, m_3) + sizeof(identifier.m_3)), INVALID_STRUCT_ERROR);\ // Create more macros for structs with more attributes... Then when you have a struct with const attributes, you can do this: struct MyStruct { const int attr1; const float attr2; const double attr3; }; const MyStruct test = CREATE_STRUCT_3(MyStruct, test, attr1, 1, attr2, 2.f, attr3, 3.); It's a bit inconvenient, because you need macros for every possible number of attributes and you need to repeat the type and name of your instance in the macro call. Also you cannot use the macro in a return statement, because the asserts come after the initialization. But it does solve your problem: When you change the struct, the call will fail at compile-time. If you use C++17, you can even make these macros more strict by forcing the same types, e.g.: #define CREATE_STRUCT_3(type, identifier, m_1, p_1, m_2, p_2, m_3, p_3) \ { p_1, p_2, p_3 };\ static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\ static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\ static_assert(offsetof(type, m_3) >= (offsetof(type, m_2) + sizeof(identifier.m_2)), INVALID_STRUCT_ERROR);\ static_assert(typeid(p_1) == typeid(identifier.m_1), INVALID_STRUCT_ERROR);\ static_assert(typeid(p_2) == typeid(identifier.m_2), INVALID_STRUCT_ERROR);\ static_assert(typeid(p_3) == typeid(identifier.m_3), INVALID_STRUCT_ERROR);\ A: The way /* B */ is fine in C++ also the C++0x is going to extend the syntax so it is useful for C++ containers too. I do not understand why you call it bad style? If you want to indicate parameters with names then you can use boost parameter library, but it may confuse someone unfamiliar with it. Reordering struct members is like reordering function parameters, such refactoring may cause problems if you don't do it very carefully. A: You could use a lambda: const FooBar fb = [&] { FooBar fb; fb.foo = 12; fb.bar = 3.4; return fb; }(); More information on this idiom can be found on Herb Sutter's blog. A: What about this syntax? typedef struct { int a; short b; } ABCD; ABCD abc = { abc.a = 5, abc.b = 7 }; Just tested on a Microsoft Visual C++ 2015 and on g++ 6.0.2. Working OK. You can make a specific macro also if you want to avoid duplicating variable name. A: For me the laziest way to allow inline inizialization is use this macro. #define METHOD_MEMBER(TYPE, NAME, CLASS) \ CLASS &set_ ## NAME(const TYPE &_val) { NAME = _val; return *this; } \ TYPE NAME; struct foo { METHOD_MEMBER(string, attr1, foo) METHOD_MEMBER(int, attr2, foo) METHOD_MEMBER(double, attr3, foo) }; // inline usage foo test = foo().set_attr1("hi").set_attr2(22).set_attr3(3.14); That macro create attribute and self reference method. A: For versions of C++ prior to C++20 (which introduces the named initialization, making your option A valid in C++), consider the following: int main() { struct TFoo { int val; }; struct TBar { float val; }; struct FooBar { TFoo foo; TBar bar; }; FooBar mystruct = { TFoo{12}, TBar{3.4} }; std::cout << "foo = " << mystruct.foo.val << " bar = " << mystruct.bar.val << std::endl; } Note that if you try to initialize the struct with FooBar mystruct = { TFoo{12}, TFoo{3.4} }; you will get a compilation error. The downside is that you have to create one additional struct for each variable inside your main struct, and also you have to use the inner value with mystruct.foo.val. But on the other hand, it`s clean, simple, pure and standard. A: I personally have found that using constructor with struct is the most pragmatic way to ensure struct members are initialized in code to sensible values. As you say above, small downside is that one does not immediatelly see what param is which member, but most IDEs help here, if one hovers over the code. What I consider more likely is that new member is added and in this case i want all constructions of the struct to fail to compile, so developer is forced to review. In our fairly large code base, this has proven itself, because it guides developer in what needs attention and therefore creates self-maintained code.
{ "language": "en", "url": "https://stackoverflow.com/questions/6181715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "167" }
Q: QMap Insert only produces (error) 0 for Value and Key I am having a problem inserting values into a QMap & I cannot figure out why. I have stripped my code right down to just make what I was trying to do work. The code is below: #include <QtCore/QCoreApplication> #include <QString> #include <QMap> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QString string1 = "a"; QString string2 = "b"; QMap<QString,QString> myMap; myMap.insert(string1,string2); return a.exec(); } This produces the following map: Why is this happening? What am I doing wrong? A: This looks like a problem with the VS variable watch, that it is having trouble parsing the contents of the variable. If you check the values in myMap using QDebug(), you'll probably find that the pairs have inserted correctly but VS is not interpreting the contents correctly. Try uninstalling and re-installing your VS plugin and, if the problem persists, log a bug with Qt that their QMap parsing script in the VS plugin might be faulty.
{ "language": "en", "url": "https://stackoverflow.com/questions/24367028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android - deletion of resources in Java I am planning to write an Android chat application - in this application, one of the main features is user anonymity and security. The application will allow the user to upload pictures, and will also allow the user to write texts, which will be saved as Strings. How can I ensure that these resources are completely destroyed by the Java system upon the destroy method being called? Obviously in C, since I have direct access to memory, I can write NULL values over all of the memory before calling free() in order to ensure complete deletion - but my understanding in Java is that this is impossible, and that I am supposed to just wait for the garbage collector to decide to delete resources.
{ "language": "en", "url": "https://stackoverflow.com/questions/33248354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why am i always getting Group C Question: Display the message Group A if a string contains at least one letter A, either in uppercase or lowercase in the last 3 positions of the string. Display Group B if a string contains the letter B, either in uppercase or lowercase in all last three positions. Display the message Group C otherwise. Do not use loop/repetition structure. Use the slice operator. My code: s = input('Enter string: ') if 'Aa' in s[-3:]: print('Group A') elif 'Bb' in s[-3] and 'Bb' in s[-2] and 'Bb' in s[-1]: print('Group B') else: print('Group C') A: 'Aa' in 'ABC' will return False. The in operator in this context well check if the exact full substring (not any individual characters) is present. In your case, you need to check each character individually, or convert the case to use a single character. You can use: s = input('Enter string: ') if 'A' in s[-3:].upper(): print('Group A') elif 'BBB' == s[-3:].upper(): print('Group B') else: print('Group C') Or better, slice and convert the case only once: s = input('Enter string: ')[-3:].upper() if 'A' in s: print('Group A') elif 'BBB' == s: print('Group B') else: print('Group C') `` A: It looks like you may think you're using Regex, to actually use it: import re s = input('Enter string: ') if re.match('[Aa]', s): print('Group A') ...
{ "language": "en", "url": "https://stackoverflow.com/questions/72298394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Intermitent Naming Conflict I call for collective wisdom on this one. I am having the following extremely weird bug. I have a model named File.php. I have used it in several places in my app. But now it doesn't seem to work. In this case, it works in my Template.php: $this->Behaviors->load('Containable'); $this->contain( array( 'User', 'TemplatesUserType' => array( 'UserType', 'FilesTemplatesUserType'=>array('File') ) ) ); $template=$this->find('first',array('conditions'=>array('Template.id'=>$template_id,"Template.user_id"=>$user['User']['id']))); This also works in FilesTemplatesUserTypesController: $this->FilesTemplatesUserType->File->recursive=-1; $file=$this->FilesTemplatesUserType->File->findByName($name); if(gettype($file)=="array" && count($file)>0){ $file_id=$file["File"]["id"]; } else{ $this->FilesTemplatesUserType->File->create(); $this->FilesTemplatesUserType->File->save(array("File"=>array("name"=>$name))); $file_id=$this->FilesTemplatesUserType->File->getInsertID(); } $this->request->data["FilesTemplatesUserType"]["file_id"]=$file_id; } $this->FilesTemplatesUserType->create(); $this->FilesTemplatesUserType->save($this->request->data); Both cases work, perfectly fine. But now, from model Document.php, it fails throwing a 500 internal server error: $this->Behaviors->load("Containable"); $this->contain(array( "UsersVersion"=>array( "conditions"=>array("UsersVersion.user_id !="=>$user["User"]["id"]), "User" ), "Draft"=>array( "fields"=>array("Draft.id,Draft.template_id,Draft.name"), "Template"=>array( "fields"=>array("Template.id, Template.name, Template.user_id"), "TemplatesUserType"=>array( "DraftsUser"=>array( "User" ), "FilesTemplatesUserType"=>array("FilesUsersVersion","File") ) ) ) ) ); $draft=$this->findById($document_id); But it is until I remove the "File" that works. To debug, I tried this in the same file: $model=$this->Draft->Template->TemplatesUserType->FilesTemplatesUserType->File; $model->recursive=-1; $file=$model->findByName("Ident"); It throws an error at line 88 in CORE/Utility/File.php indicating that $path has: array("class"=>"File","alias"=>"File") instead of a string and the following error message: Fatal error: Call to undefined method File::findByName() in C:\Inetpub\vhosts\*******.com\httpsdocs\eolas\app\Controller\DocumentsController.php on line 245 To make matters more confusing, this works from my Template.php model: $model=$this->TemplatesUserType->FilesTemplatesUserType->File; $model->recursive=-1; $file=$model->findByName("Ident"); It appears that somehow the error occurs depending on the recursive level that the model File is being called and that is when it might get in conflict with File.php Utility class. My question is: Why is it working perfectly in some places and until now is failing? Is there something to CakePHP inner workings that I am hitting correctly by chance and now I am losing it? I hope you can steer me in the right direction (and not to have to change my model name, =P). Thank you very much in advance! A: As stated in my answer to your previous question you cannot have a model named File as there is already a class named File in CakePHP's core code. You need to use an alternative name for your model. Think of File as a reserved word. The reason why your code is sometimes working comes down to whether your model or Cake's File utility is touched first. In the case where your code is failing File is being used as the utility class rather than your model so isn't compatible. Think about it: if Cake tries to initiate an instance of the class File (i.e. new File(/* some params */)) which File class will it use in your code? The fact that this is unclear should give you the clue that you shouldn't be using a model with the same name as the utility class. I suspect your error logs contain more errors/warnings about your code as a result of this. Unfortunately you have no choice but to change the name of your model. However, you may be able to change some of the renamed model class' attributes so that it still behaves as the File model (this is untested as I've never needed to do this, but might be worth a try). For example, rename the class (and filename) to AppFile and then set the $name, $alias and $table properties so that the model behaves as File:- <?php class AppFile extends AppModel { public $name = 'File'; public $alias = 'File'; public $table = 'files'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/34214074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sys.WebForms.PageRequestManagerParserErrorException with IE I am working on a relatively complex asp.net web forms application, which loads user controls dynamically within update panels. I've run into a very peculiar problem with Internet Explorer where after leaving the page idle for exactly one minute you receive a Sys.WebForms.PageRequestManagerParserErrorException javascript exception when the next request is made. This doesn't happen in Firefox and Chrome. When the server receives the bad request, the body is actually empty but the headers are still there. The response that is sent back is a fresh response you would get from a GET request, which is not what the update panel script is expecting. Any requests done within a minute are okay. Also any requests made following the bad request are okay as well. I do not have any response writes or redirects being executed. I've also tried setting ValidateRequest and EnableEventValidation in the page directive. I've looked into various timeout properties. A: The problem resided with how IE handles NTLM authentication protocol. An optimization in IE that is not present in Chrome and Firefox strips the request body, which therefore creates an unexpected response for my update panels. To solve this issue you must either allow anonymous requests in IIS when using NTLM or ensure Kerberos is used instead. The KB article explains the issue and how to deal with it.KB251404
{ "language": "en", "url": "https://stackoverflow.com/questions/18282400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Export Records in batches in sql server 2005? As already said in the title, how do i export a table into Excel file but into batches? I have total 300 thousands records in one table. I exported it into Excel but when it hit the 65536 records in Excel, operation failed. (may be coz of limit of rows in excel). So how to get around with this situation? All i need is a table exported from one server and imported it into another server. I can't use Linked Server coz of limitation of VPNs (both servers are on different VPN network). A: Export to a CSV file instead of an XLS - there's no size limit in CSVs. I get 10 GB+ CSV files from my clients on a regular basis. A: Yes that is a limitation of Excel in any version eralier than 2007. If you are going from one server to another server, it is silly to use Excel anyway as it has all kinds of bad issues with data conversion. Use a pipe delimted text file and life will be much better. Frankly SSIS is so bad at handling Excel, we try very hard to get clients to accept a text file even if the file is going to a person who wants to play with it in Excel (Excel can easily open a text file.)
{ "language": "en", "url": "https://stackoverflow.com/questions/4072588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Understanding the content in value attribute? $userId = $_POST["userId"] print <input type="hidden" name="userId" value='".$userId."'/>; I can't understand what is inserted into the attribute value here and why here dot$userIddot actually does? I know that single dot operator is used for concatenation then why is here author used two? A: Firstly, your example has syntax errors. Should be: $userId = $_POST["userId"]; print '<input type="hidden" name="userId" value="'.$userId.'" />'; ------------------------------------------------------------------------------------ Basic Explanation: If $userId = 123 (ie. $_POST['userId'] = 123), all that it's saying is add all the parts together using the .: /* Piece 1->*/ '<input type="hidden" name="userId" value="' PLUS ( . ): /*Piece 2->*/ 123 PLUS ( . ): /* Piece 3->*/ '" />' Would print to the browser: <input type="hidden" name="userId" value="123" /> See the manual: http://php.net/manual/en/language.operators.string.php
{ "language": "en", "url": "https://stackoverflow.com/questions/32030592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Access User's Friends with only App Access_token in facebook As mentioned in Link an app can access user's friend's id with an app access_token. But when I try to access friends of a user by www.graph.facebook.com/USER_ID?fields=friendlists&access_token=ACCESS_TOKEN I get an error: { "error": { "message": "An access token is required to request this resource.", "type": "OAuthException", "code": 104 } } How can I access a user's friendlist with only app access token? A: Did you try the field "friends"? https://graph.facebook.com/USER_ID?fields=friends&access_token=ACCESS_TOKEN If you requirement is just to fetch user's friends and their facebook ids, you can get them here.
{ "language": "en", "url": "https://stackoverflow.com/questions/19096129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I replace some element and remove some element in one loop in java? I wanna do some thing like this : List<Integer> list = [1,2,1,3]; for (each : list) { if (each == 1) { remove (each); } else { each = 4; } } after the loop the list is supposed to be [4,4]. I have tried the following codes : List<String> list = new ArrayList<>(Arrays.asList("1", "2", "1", "3")); for (String i : list) { if (i.equals("1")) { i = "4"; } } But it doesn't change the value, the list is [2,3]. List<Integer> list = [1,2,1,3]; for (int i = 0; i< list.size(); i++) { //do something to replace the element } This can replace the element but can not remove the element. The only way I can come up with is to remove the elements in one loop, and replace the element in another loop, how can I do both in just one loop? A: Your following code doesn't work: for (String i : list) { if (i.equals("1")) { i = "4"; } } because you're replacing the value of String i instead of the selected item of list. You need to use set method: for (int i = 0; i < list.size(); i++) { String item = list.get(i); if (item.equals("1")) { list.set(i, "4"); } } UPDATE If you want to remove and change the item in one loop, you need to use listIterator and change for loop with while loop: ListIterator<String> iterator = list.listIterator(); while(iterator.hasNext()){ String item = iterator.next(); // Change item value if(item.equals("1") iterator.set("4"); // remove item if(item.equals("2") iterator.remove(); } Please be noted, I haven't test the code yet. A: You need to be careful to avoid a ConcurrentModificationException when attempting to remove an element from a list while iterating over it. You can use this: list = list.stream() .filter(element -> element != 1) .map(element -> 4) .collect(Collectors.toList());
{ "language": "en", "url": "https://stackoverflow.com/questions/66594899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Business Use Case and just Use Case What's the difference between a Business Use-Case Model and a Use-Case model? I'm supposed to make both for a website, but I cannot understand what's the difference... Help? A: Perhaps an alternative description would help. 'Business' and 'System' Use Cases differ in scope. The former encompasses everything the customer and supplier have to do in order to complete the goal. Some of that may involve a system interaction - but some may not. As an example, take buying a book online. Certain aspects will involve be completed online (e.g. browsing available books, placing order). But some are not: picking the stock, packaging, shipping, signing for receipt of package. A Business Use Case is a "black box" description of the entire interaction ("Buy Book"). Completing the task means following a business process. Some of the steps in the process will involve a user-system interaction, some will not. Where a step does involve a user and a system ("Browse available books") that step is a System Use Case. Typically there will be a number of System Use Cases for a given Business Use Case. So do you need both? It depends on circumstances. If you're (a) responsible for the complete business scope, and (b) want to document the business capabilities as Use Cases, then a Business UCD and supporting UC definitions is useful. The steps in the UC description would represent the business process. If someone else is responsible for the business-level definitions then you probably don't need to. One final thing: sometimes the two are coincident. For example: buying an eBook. The Business Need is for the customer to be able to get their book. The entire thing could be delivered in a single system interaction (select book, pay, receive download) - and so could be covered by a single System Use Case. So the Business- and System Use Cases are equivalent. hth. A: Think of it this way: A business UC (use case) contains absolutely no technical detail. And you need to step back a way to see the business need. So business UCs may be something like: * *Manage Photos Online *Create Personal Log Entries *Interact With Other Users Online *Share Photos With Other Users Notice none of this says anything about how it will be done. At this point it's pretty much a listing of needed functionality put into action-subject-qualifier format. You can put them into a use case model with the actors and you have a very useful set of high-level business UCs. Finish spec'ing out UCs with their pre- and post-conditions and such for low-level business UCs. But at this poing the detail of the paths aren't known. A system UC contains the system-level perspective on those business UCs. So, while Manage Photos Online may describe the need to upload photos and group them into albums, the system UCs may actually turn into: * *Upload Image (with paths for uploading, naming, cropping and deleting) *Manage Album (with paths for creating, adding images and removing images) Here we've gotten into technical detail. The business may be thinking in terms of storing and swapping photos, but you know that there's little difference in how the system will perceive and handle photos and bitmap images. You've started thinking about just what's involved in uploading images and what the user may need to do with the images. I hope this helped.
{ "language": "en", "url": "https://stackoverflow.com/questions/4761915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the formula used by .NET chart controls when using a logarithmic scale? I'm making a bar chart using .NETs Chart controls with a pretty wide range of values. The top of the chart (AxisY.Maximum) is 4930 and some of the Y values are: 573, 392, 151, 182, 4675, 103, 3100, 432, 326, 53, 3415, 1125, 115... A pretty wide range of values, so I'm setting the chart to use a logarithmic scale with chart.ChartAreas[0].AxisY.IsLogarithmic = true; and chart.ChartAreas[0].AxisY.Interval = .1; //Gives a nice number of lines. That's fine, it works quite well. What isn't working is I'm trying to figure out the scale of each tick mark on the graph. Side of the graph looks like this: Looking at the .NET object, it says the log base scale is 10, but that doesn't seem to fit at all. Looks like each tick mark is going up by 25. Here's why I'm trying to do, each of the bars in the chart have text on them, I'm looking at each one individually and trimming the text if it gets too long. So something with a Y value of around 125 should only have a few characters of text, but something with a value of 1000 should be allowed about 50 characters (Total length of the screen in characters is about 110). The formula I've tried using with a log base of 10, works OK, but has a tendency to put in too many characters on low scores. This is what it looks like: My ultimate question is, if I'm looking an individual Y value of a bar (Say 150) how can I tell where on the chart this will fall (e.g. it's 150, so it's above the 126 tick mark and below the 158 tick mark.). A: So, if I understand your question correctly you want to know how far along the chart a number is. The answer could be pixels or inches or whatever...we'll call that multiplier m. * *10 should appear at 1*m (log (10) == 1) *100 should appear at 2*m (log (100) == 2) To find where any arbitrary value will appear (I'm using 150 from your example): Math.Log10(150) * m Which equals 2.18 * m. All that's left is for you to figure out what your m is. I don't have enough info to help you with that. It may help to use values from the chart to understand why they are there: * *Math.Log10(126) = 2.1 *Math.Log10(158) = 2.2 *Math.Log10(200) = 2.3 *Math.Log10(251) = 2.4 You'll note that they increment along the chart by 1/10 each time.
{ "language": "en", "url": "https://stackoverflow.com/questions/33269691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PDO inserting zero into my data base instead of the variable content I'm trying to insert data into my database using PDO prepare statement but its inserting zero into my table instead of the variable content
{ "language": "en", "url": "https://stackoverflow.com/questions/55305020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Huge picturebox (16000x16000) Sometimes, my users will use a 16000x16000 picturebox (which is located in a Panel, for autoscroll). The picturebox is used like a tiles map. On it, I draw tiles for making maps (yes, it is a map editor)... But the mere idea of being able to create a picturebox that huge, is terrible for performance. I am told to "only load the visible area", but, what do they mean by "load" on a picturebox? Can I control that? A: You don't want to let the picturebox display complete images. Instead, you use the Paint event to draw the visible image portion yourself
{ "language": "en", "url": "https://stackoverflow.com/questions/4845861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: communication of two remote shell scripts through file I really need help to understand the strange behavior of my shell scripts. In fact, I have two scripts running on different nodes. the first script ssh a remote node and launch the second script. the second script computes a cost and send it to the first script. for that the second script ssh the node of the first script (asker node) and write the cost in a file that will be read by the first script (as shown bellow). the problem is that when the value of cost is 0 the first script continues its execution normally, but if its value is different then 0 the first script remains suspended and doesn't execute the instructions after the ssh. Does anyone have an explanation for that? I can give more details about my code if needed. Thank you in advance. First script: .... ssh $remore_node "sh cost_computation.sh <parameters>" cost=`cat $response_file` if [ $cost -eq 0 ] then .... else .... fi Second script (cost_computation): .... computation of the cost ssh $asker_node "echo $cost > $response_file" A: Can you just do this? First script: .... cost=$(ssh $remore_node "sh cost_computation.sh <parameters>") if [ $cost -eq 0 ] then .... else .... fi Second script (cost_computation): .... computation of the cost echo $cost
{ "language": "en", "url": "https://stackoverflow.com/questions/14138657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Require operator double() to be explicitly called via static_cast(x) I'd like to enable conversion of my class to a double value. This can be achieved by overloading operator double() but this then allows for implicit conversion, which ideally I'd like to be able to avoid. Is there any way to add this functionality but with the requirement that conversions are made using double y = static_cast<double>(x) rather the implicitly being made; double y = x? I'm using C++17. Thanks A: Yes, you can mark conversion operators explicit since C++11. explicit operator double() { /* ... */ } This will prevent copy-initialization, e.g., double y = x; return x; // function has double return type f(x); // function expects double argument while allowing explicit conversions such as double y(x); double y = static_cast<double>(x); A: Use explicit: struct X { explicit operator double() const { return 3.14; } }; double y = static_cast<double>(X{}); // ok; double z = X{}; // error
{ "language": "en", "url": "https://stackoverflow.com/questions/47085095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using a NSMutableArray to store data Can you store an Array ( that contains another two subarrays one being a string and another another array) into a single MutableArray object? A: Please read the documentation on NSArray. It can contain any number of arbitrary objects. That said, without knowing more about what you're doing, I'd suggest you look at NSDictionary and its mutable subclass. A: Yes, you can store any type of object into one of the NSArray classes. The only difficulty is in conceptually dealing with how to access this data structure; complex nesting of arrays within arrays can be hard to manage and lead to bugs. Make sure your needs aren't better solved by another data structure, or a custom class. A: Yes. You can use the following (enormous) line of code: NSMutableArray * completeArray = [NSMutableArray arrayWithArray: [[myArray objectAtIndex:0] arrayByAddingObjectsFromArray: [myArray objectAtIndex:1]]]; edit: Assuming that myArray is defined as follows: NSArray * stringArray = [NSArray arrayWithObjects: @"one", @"two", @"three", nil]; NSArray * otherArray = [NSArray arrayWithObjects: someObj, otherObj, thirdObj, nil]; NSArray * myArray = [NSArray arrayWithObjects: stringArray, otherArray, nil]; The line of code I posted above will give you one big NSMutableArray which contains: @"one, @"two", @"three", someObj, otherObj, thirdObj
{ "language": "en", "url": "https://stackoverflow.com/questions/351661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Writing to Android device with Cordova file system plugin, different AndroidPersistentFileLocation values I'm writing a Javascript function to write to a text file on an Android device using the Cordova file system plugin. If in my config.xml file I use the recommended setting: <preference name="AndroidPersistentFileLocation" value="Internal" /> the code fails when calling fs.root.getFile() with INVALID_MODIFICATION_ERR. But if I use: <preference name="AndroidPersistentFileLocation" value="Compatibility" /> the code creates and writes to the file as expected. What can be the reason for this and will using Compatibility instead of Internal have any negative impact on my app? Code that writes to file: window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) { var filePath = cordova.file.externalDataDirectory.replace(cordova.file.externalRootDirectory,""); var fileName = filePath + "acuDevice.txt"; console.log("acuDevice fileName:"+fileName); fs.root.getFile(fileName, { create:true, exclusive:false }, function(fileEntry) { console.log("acuDevice fileEntry:"+JSON.stringify(fileEntry)); fileEntry.createWriter( function (fileWriter) { fileWriter.onerror = function (err) { console.log("acuDevice write failed:"+JSON.stringify(err)); }; fileWriter.onwriteend = writeComplete; fileWriter.write("hello acuDevice world"); } ); // createWriter }, fileErrorHandler ); // getFile }, fileErrorHandler ); // requestFileSystem
{ "language": "en", "url": "https://stackoverflow.com/questions/39935812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Draggable - Droppable positioning bug? I'm making an activity that requires certain letters to be put in certain places to complete words. Here's a screenshot: The Activity I'm Working On (linking it because it's too big) The two small wooden boards at the bottom contain the letters that should be dragged to the blank boxes on the bigger wooden boards. The problem is that every time I try to drag the letters into the blank spaces, it does this: And if I don't drag it to that certain spot (for example, I want to place it exactly at the center of the red box), it reverts to its original position as if I never dropped it in a droppable. Is this a bug? Is there a workaround? Here's the script: $(".drag").draggable({ revert: 'invalid' }); /*======================================================*/ $( "#dropArea1A" ).droppable({ accept: '.drag', drop: function( event, ui) { console.log(ui.draggable.attr('class')); console.log(answers); console.log(correct); if(ui.draggable.hasClass('letterH')){ choice1 = 'correct'; $('#dropArea1A').addClass('correct') } $(".drag").css('cursor', 'default'); $(".drag").append(ui.draggable.css('margin','0')); $(".draggable").draggable({ disabled: false }); $(this).append(ui.draggable.css('position','static')); $(this).droppable( 'disable' ); }, }); And some additional info that might be useful: I used position: absolute a lot in the stylesheet to get the droppable divs into the correct position. The wooden boards (and the static letter boxes) are background images. Would this be the culprit? A: After some chat room traversing and playing around with jsfiddle, I found that droppable areas have problems with the css margin property, not position: absolute. What happens is, if you set a margin-top or a margin-left or any other value for the margin property, only the element will move -- the drop area will not. I hope this helps someone! A: This issue was reported four years ago here: http://bugs.jqueryui.com/ticket/6876 It was recently fixed in jquery-ui 1.11.2
{ "language": "en", "url": "https://stackoverflow.com/questions/23054868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Duplicate keys OK when nested in JSON Consider a JSON representation for delivering a package from one address to another. Simplified, { "parcelId": 123, "source": { "street": "123 Main Street", "city": "Anytown", "state": "New York" }, "destination": { "street": "456 Avenue B", "city": "Elsewhere", "state": "New Jersey" } } I'm fairly sure that keys "street", "city", and "state" can be legally nested in both "source" and "destination" objects. Are there technical reasons that the key names should not be repeated? A: Are there technical reasons that the key names should not be repeated? No. Seems perfectly reasonable to me. e.g. if I was serialising a Scala/Java object, that object could look like: class Delivery { val parcelId : String val source : Address val destination : Address } and the field names of the Address object would be the same here. A: There is nothing wrong with having duplicate property keys which are part of different objects in JSON. Your JSON example is perfectly valid. This is only an issue when they are at the same level. For example two source objects: { "parcelId": 123, "source": { "street": "123 Main Street", "city": "Anytown", "state": "New York" }, "source": { "street": "456 Avenue B", "city": "Elsewhere", "state": "New Jersey" } } Or two street properties inside one object: "source": { "street": "456 Avenue B", "street": "Elsewhere", "state": "New Jersey" } A: No. This would be confusing if you had delivery.street and then a different delivery.street. But you don't. You have delivery.source.street and delivery.destination.street. Basically the key street is addressing a completely different object now.
{ "language": "en", "url": "https://stackoverflow.com/questions/41245381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change SVG icon color using inline css I am fairly new to SVG but how can I display a SVG icon and change its color using inline CSS? For example, if I wanted to change the color of example.svg to #FFF000 how would I do that? I tried searching online but I couldn't find anything. A: collinksmith did answer your question but didn't explain that you cannot change the colour of a .svg file with CSS. You need to add the SVG inline then you can apply CSS to it. A: You need to use the fill property of the svg's path. Assuming an svg html element, with a class set on the svg element itself: .class-name path { fill: red; } EDIT Here's an example: https://jsfiddle.net/4447zb7o/ EDIT 2 To set the css inline, change the style attribute of the path element inside the svg: <svg class="my-svg" height="210" width="400"> <path style="fill: green" d="M150 0 L75 200 L225 200 Z" /> </svg>
{ "language": "en", "url": "https://stackoverflow.com/questions/34442914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Dismissing the keyboard while simulating a wait This function is designed to simulate a wait if the user is successful logging in. As you can see I dismiss the keyboard first but that doesn't stop NSThread from sleeping before the keyboard is dismissed. I think I need to harness the power of the dispatch queue but not quite sure. Any way I can dismiss the keyboard before sleep occurs? -(IBAction)userLoginButtonPressed:(id)sender { /* resign first responders so that the user can see the label of the server trying to log in */ [self.usernameField resignFirstResponder]; [self.passwordField resignFirstResponder]; self.statusLabel.text = @"Logging In..."; // create the server object and pass in the username and password values IONServer *server = [[IONServer alloc] init]; NSString *user = self.usernameField.text; NSString *pw = self.passwordField.text; [server loggingInWithUserName:user password:pw]; // redirect based on result if (server.result.success) { [self serverSuccess]; [NSThread sleepForTimeInterval:2.0f]; } else { [self serverFailure]; } // store the server object as this class' server var self.server = server; NSLog(@"Result From Server: %@", server.result); } A: dismissing the keyboard is animated and this is enough for us to know that it happens async-ly, on main thread. In other words - you code block starts, dismissing the keyboard being added to main thread runloop, the thread sleeps for 2 seconds because you said so (Terrible thing to do if you ask me), and only than it's the keyboard's turn to get animated down and be dismissed. A nice trick can be [UIView animateWithDuration:0 animations: ^{ [self.usernameField resignFirstResponder]; [self.passwordField resignFirstResponder]; } completion: ^(BOOL finished) { // Do whatever needed... [NSThread sleepForTimeInterval:2.0f]; }]; BUT - I highly recommend finding a better solution than freezing the main thread. Also - no what you asked for, but, assuming all your text fields are subviews of self.view you can just call [self.view endEditing:YES]; and you don't need to care about which text field is corrently the responder.
{ "language": "en", "url": "https://stackoverflow.com/questions/23320079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery loaded data not firing modal like it should Okay, I have a map of the country, the user clicks on their state, and a bunch of suppliers is loaded through jQuery via a page like this: $('#sa').click(function () { $('#mapimg').hide(); $('<div id="info">&nbsp;</div>').load('dealers.php?state=sa', function () { $(this).hide() .appendTo('#dealers') .slideDown(3000); }); }); Then when it displays the deals, I want the user to be able to click the 'contact us' next to each dealer and have a modal jump up with a contact form in it. But it doesn't seem to be firing. on clicking just does nothing. Here is the jQuery code to trigger the modal box: $(document).ready(function () { //select all the a tag with name equal to modal $('a').click(function (e) { //I have tried everything here, div, a[name=something], li, etc //Cancel the link behavior e.preventDefault(); //Get the A tag var id = $(this).attr('href'); //Get the screen height and width var maskHeight = $(document).height(); var maskWidth = $(window).width(); //Set heigth and width to mask to fill up the whole screen $('#mask').css({ 'width': maskWidth, 'height': maskHeight }); //transition effect $('#mask').fadeIn(1000); $('#mask').fadeTo("slow", 0.8); //Get the window height and width var winH = $(window).height(); var winW = $(window).width(); //Set the popup window to center $(id).css('top', winH / 2 - $(id).height() / 2); $(id).css('left', winW / 2 - $(id).width() / 2); //transition effect $(id).fadeIn(2000); }); //if close button is clicked $('.window .close').click(function (e) { //Cancel the link behavior e.preventDefault(); $('#mask').hide(); $('.window').hide(); }); //if mask is clicked $('#mask').click(function () { $(this).hide(); $('.window').hide(); }); }); The following code works outside the loaded content, but not inside. Did anyone get any ideas? <a href='#dialog2' class='openmodal'>Open Modal Box</a> A: with the dynamically loaded content you just need to juse live bindings. Please use jQuery live events. Suppose contact link has class "clsContact" then you can put dialog opening login in function "OpenModal" and bind links like this: $("a.clsContact").live('click', OpenModal);
{ "language": "en", "url": "https://stackoverflow.com/questions/1237579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Download a Single file in Remote Zip file I want to download a single file in a remote Zip file that is in the cloud. The zip file is too large for me to download as a whole therefore I have decided to look for a way to download only a single file(XML) that I need within the archive. I have tried and Tested a webclient and web request but it downloads the whole zip file(also too large file for these technuques usually fails). I'm eyeing the SharpZipLib but I dont know how to use it. Is it the right library I should use or there are other available ones I can get and test. Thank you so much.
{ "language": "en", "url": "https://stackoverflow.com/questions/49483459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I set up a facet search with a many to many relationship using Sunspot? I haven't implemented a search feature before and feel a bit stuck. I have a Sunspot search feature which finds results based on keywords - this works great - but I now want to implement the multi select facet feature, but I can't even seem to figure out how to set-up a basic facet search. I have a many to many relationship (in rails not in real life): Class People has_many :skills, :through => experience (and vice versa etc) Class People < ActiveRecord::Base has_many :skills, :through => experience searchable do text :first_name, :surname end end In the controller @search = Sunspot.search(People) facet :skill_ids end This is the basic example I can't get working. It generates this error: Sunspot::UnrecognizedFieldError: No field configured for People with name 'skill_ids' How do I create the link to :skill_ids I think I must be missing some reference in the model - but no examples I can find do reference the Ids of a relationship. Most of the examples I found use columns that are already in that model when using the facet functionality. * *How can I get the basic implementation working? *How would I use this in the view - do I have to call hits.facet and iterate over the skills? What would the code look like to display this? *How would I select multiple facets to search by? *Should I put this in the community wiki? Thank you for your time! A: Anything you want to filter, facet, or order on, Sunspot needs to know about. So in your model: searchable do text :first_name, :surname integer :skill_ids, :multiple => true, :references => Skill end Your #search call in your controller looks right. In your view, you'd do something along these lines: - @search.facet(:skill_ids).rows.each do |row| = row.instance.name row.instance will return the instance of Skill that the row's value refers to (that's what the :references option is doing in the searchable definition). I'm not sure what you mean by "select multiple facets to search by" -- one can generate multiple facets (which give users choices for further search refinement) by calling the facet method multiple times in a search; and you can then use their facet choices with scope restrictions using the with method, which you can also call as many times as you'd like. Speaking of wikis, most of this information is available (with more explanation) in the Sunspot wiki: * *http://wiki.github.com/outoftime/sunspot/
{ "language": "en", "url": "https://stackoverflow.com/questions/2522231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Android: 3G to WIFI switch while in the middle on the app = loss of network connectivity I am running into a annoying problem with HTC Legend (Android 2.2). Not seeing this issue on Xperia, Galaxy, Nexus, etc. When I launch my app on a 3G connection, fetch some data, then go into phone Settings and enable WIFI, the phone automatically obtains a WIFI connection which is favoured over 3G. The trouble is, once i switch back to the app, it appears to have lost all network connectivty and unable to connect to anything. However, other apps, like Web Browser for example, have no problem using the new Wifi connection. Ping works fine from the phone's shell. If I wait long enough, (e.g. 15 minutes), the network stack seems to repair itself automatically and my app is able to make network connections once again. Of course, this delay is unacceptable. Is there a way to re-init the network stack programmatically? I create a new java.net.HttpURLConnection each time, yet it still times out once the WIFI has been acquired. Thanks Code: byte[] response = null; HttpURLConnection connection = null; int responseCode = -1; // check the cache first String readyResponse = ResponseCache.getInstance().get(getUrl()); if (readyResponse != null) { Log.d(LOG_TAG, "Returning CACHED server response for " + getUrl()); return readyResponse.getBytes(); } try { URL url = new URL(getUrl()); Log.i(LOG_TAG, "Sending Request: " + url.toExternalForm()); connection = (HttpURLConnection) url.openConnection(); connection.setUseCaches(false); connection.setDoOutput(true); connection.setDoInput(true); connection.setConnectTimeout(ApplicationConfiguration.HTTP_CONNECT_TIMEOUT); connection.setReadTimeout(ApplicationConfiguration.HTTP_READ_TIMEOUT); if (BuildType.getHTTPMethod() == BuildType.METHOD_GET) { connection.setRequestMethod("GET"); } else { connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String body = getParameters(); connection.setRequestProperty("Content-Length", Integer.toString(body.length())); OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(getParameters()); wr.flush(); } connection.connect(); responseCode = connection.getResponseCode(); And stacktrace E/xxx.yyy.zzz( 927): java.net.SocketTimeoutException: Read timed out E/xxx.yyy.zzz( 927): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.nativeread(Native Method) E/xxx.yyy.zzz( 927): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.access$200(OpenSSLSocketImpl.java:55) E/xxx.yyy.zzz( 927): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl$SSLInputStream.read(OpenSSLSocketImpl.java:532) E/xxx.yyy.zzz( 927): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.readln(HttpURLConnectionImpl.java:1279) E/xxx.yyy.zzz( 927): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.readServerResponse(HttpURLConnectionImpl.java:1351) E/xxx.yyy.zzz( 927): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.sendRequest(HttpURLConnectionImpl.java:1339) E/xxx.yyy.zzz( 927): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequestInternal(HttpURLConnectionImpl.java:1656) E/xxx.yyy.zzz( 927): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequest(HttpURLConnectionImpl.java:1649) E/xxx.yyy.zzz( 927): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:1374) E/xxx.yyy.zzz( 927): at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:117) E/xxx.yyy.zzz( 927): at xxx.yyy.zzz.executeRequest(zzz.java:95) A: I see you have a SocketTimeoutException, perhaps you can catch this exception and connect using a new socket? A: There is a bug that causes the system to reuse old http connections. Setting the system property http.keepAlive to false should resolve the problem: System.setProperty("http.keepAlive", "false");
{ "language": "en", "url": "https://stackoverflow.com/questions/4347507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to increase pointer's pointer value in C++ I've been reading how the pointer works in C++ and I tried to mess with it a little but the program stopped working. #include <iostream> using namespace std; int main () { char a[] = "Hello"; char * b = a; char ** c = &b; cout << *(b+1) << endl; //cout << **(c+2) << endl; return 0; } If the commented line is not commented, the program stops working with error code: 0xC0000005. Am I doing something wrong or is this some sort of bug? A: Here: char a[] = "Hello"; char * b = a; You are taking advantage of array to pointer decay. So now b points to a[0]. That is, b holds the address of a[0] and then char ** c = &b; c now points to the address of b, which is itself a pointer. c holds the address of b, which holds the address of a (see why people hate pointers now?) If you want to access a[0] from c, you first need to de-reference it: *c which gives b, and then we need to dereference that to get back to a[0]: *(*c) If you want to use pointer arithmetic to access a[1], you want to increment b, so: *c+1 and now we have the address of a[1], and if we want to print that, we need to dereference again: *(*c+1) You made the mistake of incrementing the address of b instead of the address of a[0] when you said: **(c+2) c held the address of b, not a, so incrementing on that will cause undefined behavior. A: c points to the address of b on the current stack frame. c + 2 points to some location on the stack frame, thanks to pointer arithmetic. *(c + 2) You then access this location, taking unspecified bytes there as an address. **(c + 2) Now you attempt to access said unspecified address, and luckily for you, it crashes. A: Okay let's try again. a is a pointer to the first element in the array, in this case "H". c is a pointer to the address of b which is also a pointer to the first element. When you increment c by 2, you are moving that pointer forward by two. So the memory address goes forward by two, but c is just a pointer to a and not a itself, so you're in unknown territory. Instead, what would likely work (untested): cout<<*(*c+1)<<endl; This dereferences c, so you get b (or a, same thing), you increment this pointer by 1, which stays in the array, and then you dereference again to access the value.! A: &b + 2 is not a valid pointer. For simplicity, let's assume that a pointer is just one char wide (our memory is very, very small). Assume that a is stored at the address 10, b at 20, and c at 21. char* b = a; is the same as char* b = &a[0]; – it stores the location of the array's first element (10) in b. char**c = &b stores the location of b (20) in c. It looks like this: a b c 10 11 12 13 14 15 16 17 18 19 20 21 22... | H | e | l | l | o | 0 | | | | | 10 | 20 | It should be clear from this image that c + 2 is 22, which is not a valid address. Dereferencing it is undefined and anything can happen – your crashing was just good luck. If you were expecting the first l in "Hello", it's located at a[2], which is b[2] (or *(b + 2)), which is (*c)[2] (or *(*c + 2)). A: char a[] = "Hello"; char * b = a; char ** c = &b; a and b point to the beginning of char array having "Hello" as its characters. So, lets starting at memory location 0x100 Hello is stored. a is pointer so it stores an address. a and b both store this values 0x100. But their addresses are something else. Lets say address of a is 0x200 and address of b is 0x300. c is also pointer. So it stores address of b. So, c stores address 0x300 as its values. c+1 = 0x304 c+2 = 0x308 *c : You want to access value stored at 0x300, which is the address of b. *(c+1) : You want to access address 0x304 *(c+2) : You then access 0x308, taking unspecified bytes there as an address. **(c+2) : Dereference the address 0x308. It may or may not be address of pointer variable. So, dereferencing may be undefined operation.
{ "language": "en", "url": "https://stackoverflow.com/questions/34515367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I prevent this crash when updating the Touch Bar's escape key? I added Touch Bar support to my app when the latest MacBook Pro launched. Later I made various minor improvements, including custom escape keys where it made sense. After releasing that update, I started getting crash reports when the app tries to update the escape key. Here's one example: Exception Type: SIGBUS Exception Codes: BUS_ADRERR at 0x7fff54a05ff8 Crashed Thread: 0 Application Specific Information: Selector name found in current argument registers: objectForKey: Thread 0 Crashed: 0 Foundation 0x00007fffacbaea98 -[NSConcreteMapTable objectForKey:] + 21 1 Foundation 0x00007fffacbfc019 -[NSISEngine outgoingRowHeadForRemovingConstraintWithMarker:] + 214 2 Foundation 0x00007fffacbfbb4c -[NSISEngine removeConstraintWithMarker:] + 479 3 Foundation 0x00007fffacbf76a6 -[NSISEngine _flushPendingRemovals] + 615 4 Foundation 0x00007fffacbf4b06 -[NSISEngine withBehaviors:performModifications:] + 197 5 AppKit 0x00007fffa8c83760 -[NSView(NSConstraintBasedLayout) _withAutomaticEngineOptimizationDisabled:] + 69 6 AppKit 0x00007fffa8d129dd -[NSView(NSConstraintBasedLayout) removeConstraints:] + 276 7 AppKit 0x00007fffa8c88f9e -[NSView(NSConstraintBasedLayout) _constraints_snipDangliesWithForce:] + 595 8 AppKit 0x00007fffa8c82d9e -[NSView _setSuperview:] + 1076 9 AppKit 0x00007fffa8c88945 -[NSView removeFromSuperview] + 446 10 AppKit 0x00007fffa9593eef -[NSTouchBarEscapeKeyViewController setTouchBarItem:] + 145 11 AppKit 0x00007fffa9176bf5 -[NSApplicationFunctionRowController _updateEscapeKeyItem] + 438 12 AppKit 0x00007fffa9176bf5 -[NSApplicationFunctionRowController _updateEscapeKeyItem] + 438 13 AppKit 0x00007fffa9176bf5 -[NSApplicationFunctionRowController _updateEscapeKeyItem] + 438 … 509 AppKit 0x00007fffa9176bf5 -[NSApplicationFunctionRowController _updateEscapeKeyItem] + 438 510 AppKit 0x00007fffa9176bf5 -[NSApplicationFunctionRowController _updateEscapeKeyItem] + 438 511 AppKit 0x00007fffa9176bf5 -[NSApplicationFunctionRowController _updateEscapeKeyItem] + 438 I've removed about 500 lines for brevity—all of them are calls to [NSApplicationFunctionRowController _updateEscapeKeyItem] + 438 Here's another abbreviated report. This one is my most common crash. It actually calls my own code, though I suspect the code it's calling is not the actual problem: Exception Type: SIGBUS Exception Codes: BUS_ADRERR at 0x7fff5b8c2f74 Crashed Thread: 0 Thread 0 Crashed: 0 CoreText 0x00007fffc87d2e8d _ZNK3OTL7GCommon9NthLookupEj + 41 1 CoreText 0x00007fffc87d658b _ZNK3OTL4GPOS12ApplyLookupsER8TRunGlueiRNS_12GlyphLookupsE + 155 2 CoreText 0x00007fffc87d5f53 _ZN26TOpenTypePositioningEngine12PositionRunsER9SyncStateR13KerningStatus + 839 3 CoreText 0x00007fffc8823920 _ZN14TKerningEngine14PositionGlyphsER8TRunGlue11ShapingTypePK10__CFString + 168 4 CoreText 0x00007fffc87ddcf7 CTFontTransformGlyphs + 463 5 UIFoundation 0x00007fffd9d2a795 __NSStringDrawingEngine + 7348 6 UIFoundation 0x00007fffd9d315ea -[NSAttributedString(NSExtendedStringDrawing) boundingRectWithSize:options:context:] + 605 7 UIFoundation 0x00007fffd9d31efd -[NSAttributedString(NSExtendedStringDrawing) boundingRectWithSize:options:] + 32 8 AppKit 0x00007fffc4e711cb -[NSAttributedString(NSStringDrawingExtension) _sizeWithSize:] + 55 9 AppKit 0x00007fffc4e710ff -[NSButtonCell(NSButtonCellPrivate) _titleSizeWithSize:] + 97 10 AppKit 0x00007fffc4e70eab -[NSButtonCell(NSButtonCellPrivate) _alignedTitleRectWithRect:] + 235 11 AppKit 0x00007fffc4e25162 -[NSButtonCell cellSizeForBounds:] + 918 12 AppKit 0x00007fffc4da2a21 -[NSCell cellSize] + 68 13 AppKit 0x00007fffc4da295a -[NSControl sizeToFit] + 53 14 AppKit 0x00007fffc520392c +[NSButton(NSButtonConvenience) _buttonWithTitle:image:target:action:] + 421 15 AppKit 0x00007fffc5203a05 +[NSButton(NSButtonConvenience) buttonWithTitle:target:action:] + 199 16 Deliveries 0x0000000103b4c655 +[JUNTouchBar cancelButtonItemWithIdentifier:] (JUNTouchBar.m:75) 17 Deliveries 0x0000000103b67e9b -[JUNEditWindowController touchBar:makeItemForIdentifier:] (JUNEditWindowController.m:183) 18 AppKit 0x00007fffc57d7d2a __32-[NSTouchBar itemForIdentifier:]_block_invoke + 34 19 AppKit 0x00007fffc4e71bd0 +[NSAppearance _performWithCurrentAppearance:usingBlock:] + 79 20 AppKit 0x00007fffc57d7b9b -[NSTouchBar itemForIdentifier:] + 1158 21 AppKit 0x00007fffc57d868e -[NSTouchBar(NSEscapeKeyReplacementOld) escapeKeyReplacementItem] + 51 22 AppKit 0x00007fffc5250e80 -[NSApplicationFunctionRowController _updateEscapeKeyItem] + 238 23 AppKit 0x00007fffc5250f49 -[NSApplicationFunctionRowController _updateEscapeKeyItem] + 439 24 AppKit 0x00007fffc5250f49 -[NSApplicationFunctionRowController _updateEscapeKeyItem] + 439 25 AppKit 0x00007fffc5250f49 -[NSApplicationFunctionRowController _updateEscapeKeyItem] + 439 … 509 AppKit 0x00007fffc5250f49 -[NSApplicationFunctionRowController _updateEscapeKeyItem] + 439 510 AppKit 0x00007fffc5250f49 -[NSApplicationFunctionRowController _updateEscapeKeyItem] + 439 511 AppKit 0x00007fffc5250f49 -[NSApplicationFunctionRowController _updateEscapeKeyItem] + 439 My touchBar:makeItemForIdentifier: method is just this: - (nullable NSTouchBarItem *)touchBar:(NSTouchBar *)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier { if ([identifier isEqualToString:JUNTouchBarItemIdentifierCancel]) { NSCustomTouchBarItem *item = [JUNTouchBar cancelButtonItemWithIdentifier:identifier]; return item; } return nil; } And here's cancelButtonItemWithIdentifier:, also pretty simple: + (NSCustomTouchBarItem *)cancelButtonItemWithIdentifier:(NSString *)identifier { NSString *title = NSLocalizedString(@"Cancel", nil); NSButton *button = [NSButton buttonWithTitle:title target:nil action:@selector(cancelOperation:)]; NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:80.0]; constraint.priority = 950; constraint.active = YES; NSCustomTouchBarItem *item = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier]; item.view = button; return item; } Of course I can't reproduce this crash myself. It happens in macOS 10.12.2 through beta versions of 10.12.5. Many of the reports are from the same 13" model I'm testing on myself. The few people that include a comment with their crash report mostly say it's happening immediately after an action that would open a new window (thus changing the escape key)—one said it happened after an action that would close a window. One person mentioned in hanging for 10 seconds before crashing—which makes sense given the 500 calls to the same method. A couple of people have mentioned it happening more than once, but of course they didn't leave any contact information so I have no way to follow up with them. I know I could work around the crash by removing my custom escape keys, but I'd prefer not to. Any other ideas on how I can deal with this? Update: Since originally posting this, I've updated the app to remove the constraint, so my code for creating the button is about as simple as it can get now: + (NSCustomTouchBarItem *)cancelButtonItemWithIdentifier:(NSString *)identifier { NSString *title = JUNLocalizedString(@"Cancel", nil); NSButton *button = [NSButton buttonWithTitle:title target:nil action:@selector(cancelOperation:)]; NSCustomTouchBarItem *item = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier]; item.view = button; return item; } Unfortunately I'm still getting crash reports from the new version, with identical stack traces. So I don't think the issue is with the button I'm supplying. A: Sorry not an answer, but too long for a comment. I built a debug version for our users that experienced crashes, that swizzles the _updateEscapeKeyItem method, in an attempt to pinpoint the crash origin, which isn't visible due to the bottom of the stack being blown away by the infinite recursion. My guess is they changed the 10.13 implementation radically (they mentioned something about "KVO running amok"), and might not look into 10.12 crashes unless they have a solid clue. This is the quick and dirty code in you can drop in (mostly borrowed from How to swizzle a method of a private class), that stops the infinite recursion. The resulting crash reports might be more useful. @interface NSObject (swizzle_touchbar_stuff) @end static NSInteger updateEscapeKeyItem = 0; @implementation NSObject (swizzle_touchbar_stuff) + (void)load { static dispatch_once_t onceToken = 0; dispatch_once(&onceToken, ^{ Method original, swizzled; original = class_getInstanceMethod(objc_getClass("NSApplicationFunctionRowController"), NSSelectorFromString(@"_updateEscapeKeyItem")); swizzled = class_getInstanceMethod(self, @selector(sparkle_updateEscapeKeyItem)); method_exchangeImplementations(original, swizzled); }); } - (void)sparkle_updateEscapeKeyItem { updateEscapeKeyItem++; NSLog(@"sparkle_updateEscapeKeyItem %ld", updateEscapeKeyItem); assert(updateEscapeKeyItem < 10); [(NSObject *)self sparkle_updateEscapeKeyItem]; updateEscapeKeyItem--; } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/43503974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculate Date difference between multiple rows SQL I need to calculate the date difference between multiple rows. The scenario is I have a vehicle that can do inspections throughout the month as well as when the vehicle is assigned to a different project. I want to calculate that how many days that a vehicle is assigned to the project per month or previous month. I have tried multiple ways and I can't get even closer. I am relatively new to stack overflow. Apologies if anything is missing. Please let me know if this can be done. Thank you. All the columns are in one single table if that helps. Please let me know the query on how to achieve this I am using SQL server 2017. Original Data Expected Output A: I think you are looking for this: select vehicleId , Project , month(inspectiondate) month , year(inspectiondate) year , datediff(day , min(inspectiondate), case when max(inspectiondate) = min(inspectiondate) then eomonth(min(inspectiondate)) else max(inspectiondate) end) days from Vehicles group by vehicleId, Project , month(inspectiondate), year(inspectiondate) This query in for each month/year for each specific vehicle in a project in that month/year , you get the max and min inspection date and calculate the difference. db<>fiddle here A: I am not proud of this solution, but I think it works for you. My approach was to create a table of days and then look at which project the vehicle was assigned to each day. Finally, aggregate by month and year to get the results. I had to do this as a script since you can use aggregate functions in the definitions of recursive CTEs, but you may find a way to do this without needing a recursive CTE. I created a table variable to import your data so I could write this. Note, I added an extra assignment to test assignments that spanned months. DECLARE @Vehicles AS TABLE ( [VehicleID] INT NOT NULL, [Project] CHAR(2) NOT NULL, [InspectionDate] DATE NOT NULL ); INSERT INTO @Vehicles ( [VehicleID], [Project], [InspectionDate] ) VALUES (1, 'P1', '2021-08-20'), (1, 'P1', '2021-09-05'), (1, 'P2', '2021-09-15'), (1, 'P3', '2021-09-20'), (1, 'P2', '2021-10-10'), (1, 'P1', '2021-10-20'), (1, 'P3', '2021-10-21'), (1, 'P2', '2021-10-22'), (1, 'P4', '2021-11-15'), (1, 'P4', '2021-11-25'), (1, 'P4', '2021-11-30'), (1, 'P1', '2022-02-05'); DECLARE @StartDate AS DATE, @EndDate AS DATE; SELECT @StartDate = MIN([InspectionDate]), @EndDate = MAX([InspectionDate]) FROM @Vehicles; ;WITH [seq]([n]) AS (SELECT 0 AS [n] UNION ALL SELECT [n] + 1 FROM [seq] WHERE [n] < DATEDIFF(DAY, @StartDate, @EndDate)), [days] AS (SELECT DATEADD(DAY, [n], @StartDate) AS [d] FROM [seq]), [inspections] AS (SELECT [VehicleID], [Project], [InspectionDate], LEAD([InspectionDate], 1) OVER (PARTITION BY [VehicleID] ORDER BY [InspectionDate] ) AS [NextInspectionDate] FROM @Vehicles), [assignmentsByDay] AS (SELECT [d].[d], [i].[VehicleID], [i].[Project] FROM [days] AS [d] INNER JOIN [inspections] AS [i] ON [d].[d] >= [i].[InspectionDate] AND [d] < [i].[NextInspectionDate]) SELECT [assignmentsByDay].[VehicleID], [assignmentsByDay].[Project], MONTH([assignmentsByDay].[d]) AS [month], YEAR([assignmentsByDay].[d]) AS [year], COUNT(*) AS [daysAssigned] FROM [assignmentsByDay] GROUP BY [assignmentsByDay].[VehicleID], [assignmentsByDay].[Project], MONTH([assignmentsByDay].[d]), YEAR([assignmentsByDay].[d]) ORDER BY [year], [month], [assignmentsByDay].[VehicleID], [assignmentsByDay].[Project] OPTION(MAXRECURSION 0); And the output is: VehicleID Project month year daysAssigned 1 P1 8 2021 12 1 P1 9 2021 14 1 P2 9 2021 5 1 P3 9 2021 11 1 P1 10 2021 1 1 P2 10 2021 20 1 P3 10 2021 10 1 P2 11 2021 14 1 P4 11 2021 16 1 P4 12 2021 31 1 P4 1 2022 31 1 P4 2 2022 4
{ "language": "en", "url": "https://stackoverflow.com/questions/69755023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Using CSS class causes problems I set up my .nav class for my nav menu but when I use it it seems to cause problems and when I remove .nav and leave just ul li it fixes it but that also has a margin problem. the problem is on the bottom I commented /Problem/ http://jsbin.com/fupewijame/1/ You must remove .nav .nav ul li{ width: 100%; } and change it to ul li{ width: 100%; } that kinda fixes it but you can see a margin error. I also must use .nav class as I don't want it global. Please help I can't see the bug A: instead of : .nav ul li{ width: 100%; } use: .nav li{ width: 100%; margin-bottom: 0; } if you don't want to have a margin .nav{ margin: 0; padding: 0; } A: I'm not entirely sure what you'd like it to look like with 100% width. If you give a little more information I can help further. However, I noticed a few things that might be confusing your CSS. 1) The height is showing as "0" due to a float being applied to the list items. When you apply float to your items they are removed from the normal flow of the document. To solve, try first removing this: .nav li { float: left; } 2) Most browsers add default padding and/or margin to ol and ul I recommend you reset, and then try to style. RESET: ul { margin: 0; padding: 0; } TARGET RE-STYLE: .nav { margin: /* your style here */; padding: /* your style here */; } A: This .nav ul li{ width: 100%; } is saying : * *an element with class .nav *with a descendant of type ul *with a descendant of type li Since .nav is a class of your ul, and not of an ancestor of your ul, you should use ul.nav li { width: 100%; } that instead means : * *an element of type ul with class .nav *with a descendant of type li EDIT: for the margin problem, you should probably use position: relative; instead of position: absolute;, that should not be used if not completely aware of how it works
{ "language": "en", "url": "https://stackoverflow.com/questions/28688618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove item from a list on second select I would like to remove an item from drop down list not on first time, but after selecting a second item, in the bellow example if I select option1 will remove option1, but I need to select option1 (nothing will be removed), while selecting option4 (now option1 will be removed): <select name="selectBox" class="sel" id="selectBox"> <option value="0">Select</option> <option value="option1">option1</option> <option value="option2">option2</option> <option value="option3">option3</option> <option value="option4">option4</option> </select> And this is the code: $(".sel").change(function () { var getVal = $(this).val(); $("#selectBox option[value="+getVal+"]").remove(); }); Fiddle A: If you want to remove previously selected option then do something like this var getVal; $(".sel").change(function() { // checking previous value is defined or not if (getVal) // if defined removing the element $("#selectBox option[value=" + getVal + "]").remove(); // updating selected option value to variable getVal = $(this).val(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select name="selectBox" class="sel" id="selectBox"> <option value="0">Select</option> <option value="option1">option1</option> <option value="option2">option2</option> <option value="option3">option3</option> <option value="option4">option4</option> </select> Or something more simple using :selected selector var getVal; $(".sel").change(function() { // removing previous selected option $(getVal).remove(); // updating selected option object to variable getVal = $(':selected', this); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select name="selectBox" class="sel" id="selectBox"> <option value="0">Select</option> <option value="option1">option1</option> <option value="option2">option2</option> <option value="option3">option3</option> <option value="option4">option4</option> </select> Update: Initially trigger change event using change() to get default value if you needed. $(".sel").change(function() { //............. }).change(); //--^-- A: try this way var theValue; $('.sel').focus(function () { theValue = $(this).attr('value'); }); $(".sel").change(function () { $('.sel option[value=' + theValue + ']').remove(); theValue = $(this).attr('value'); }); DEMO
{ "language": "en", "url": "https://stackoverflow.com/questions/33664649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Select the top 2 applicants based on cognitive score by programming language I have this table: CREATE TABLE applicants ( id INT PRIMARY KEY IDENTITY, [name] varchar(255), [age] int, [address] varchar(255), [programming language] varchar(255), [cognitive score] int ) And I would need the top 2 applicants based on cognitive score from each programming language. I should do it by subqueries or joins or something similar, but not with ROW_NUMBER(). I need only 3 columns in the result: name, cognitive score, programming language I am aware of ORDER BY vs only 3 columns issue. It seems so easy but I have been struggling a lot. I would really appreciate some help A: Not sure why you don't want to / can't use row_number() but here's some code that works using CROSS APPLY. First I created a table with your specification and my dummy data: DROP TABLE IF EXISTS #applicants; CREATE TABLE #applicants ( id INT PRIMARY KEY IDENTITY, [name] VARCHAR(255), [age] INT, [address] VARCHAR(255), [programming language] VARCHAR(255), [cognitive score] INT ); INSERT INTO #applicants (name, age, address, [programming language], [cognitive score]) VALUES ('a', 20, 'address1', 'SQL', 70), ('b', 31, 'address2', 'SQL', 80), ('c', 32, 'address3', 'SQL', 90), ('d', 33, 'address4', 'C', 71), ('e', 34, 'address5', 'C', 81), ('f', 35, 'address6', 'C', 91), ('g', 36, 'address7', 'C#', 72), ('h', 37, 'address8', 'C#', 82), ('i', 38, 'address9', 'C#', 92); Then this code gets your actual output. SELECT A.id, A.name, A.age, A.id, A.[programming language], A.[cognitive score] FROM #applicants AS A CROSS APPLY ( SELECT TOP 2 t.id, t.[cognitive score] FROM #applicants AS t WHERE A.[programming language] = t.[programming language] ORDER BY t.[cognitive score] DESC ) AS A2 WHERE A.id = A2.id; The initial SELECT * FROM Applicants would return absolutely everything. The CROSS APPLY works by looking for the TOP 2 based on Cognitive Score whilst matching on Programming Language. Finally they join back using ID which forces the CROSS APPLY to act more like an inner join and only return the rows where the IDs match. Without it you'd end up with 18 rows because of the 9 rows each repeating twice. If this explanation is unclear take a look at this version of the query to see the duplication: SELECT A.id, A.name, A.age, A.id, A.[programming language], A.[cognitive score], A2.ID, A2.[cognitive score] FROM #applicants AS A CROSS APPLY ( SELECT TOP 2 t.id, t.[cognitive score] FROM #applicants AS t WHERE A.[programming language] = t.[programming language] ORDER BY t.[cognitive score] DESC ) AS A2
{ "language": "en", "url": "https://stackoverflow.com/questions/74548229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Padding is invalid and cannot be removed in C# licensing method in my project I'm Doing a licensing method where after the user enters the license key his product will be activated. Im using the following code but I'm getting an exception thrown saying "Padding is invalid and cannot be removed". The following is my code public void ValidateProductKey() { RSACryptoServiceProvider _cryptoService = new RSACryptoServiceProvider(); string productKey = "G7MA4Z5VR5R3LG001AS1N5HA3YHX05"; byte[] keyBytes = Base32Converter.FromBase32String(productKey); //Base32Converter is my customized method which returns byte of values; byte[] signBytes = new byte[2]; byte[] hiddenBytes = new byte[16]; using (MemoryStream stream = new MemoryStream(keyBytes)) { stream.Read(hiddenBytes, 0, 8); stream.Read(signBytes, 0, 2); stream.Read(hiddenBytes, 8, hiddenBytes.Length - 8); keyBytes = stream.ToArray(); } byte[] sign = _cryptoService.SignData(signBytes, new SHA1CryptoServiceProvider()); byte[] rkey = new byte[32]; byte[] rjiv = new byte[16]; Array.Copy(sign, rkey, 32); Array.Copy(sign, 32, rjiv, 0, 16); SymmetricAlgorithm algorithm = new RijndaelManaged(); try { hiddenData = algorithm.CreateDecryptor(rkey, rjiv).TransformFinalBlock(hiddenBytes,0,hiddenBytes.Length); } catch (Exception ex) { MessageBox.Show(ex.Message); } } When reaching the "hiddenData" variable I get an exception thrown as "Padding is invalid and cannot be removed". Any help would be really appreciated. A: You look to be generating the key and IV for the Rijndael decryption by signing your signBytes array using SHA1/RSA, however from the code you've given, you don't initialize the RSACryptoServiceProvider used in the signing process with a key pair, as such it will have a randomly generated key, and so the result of the signing process will be different every time. Consequently the key/IV being used in the Rijndael decryption are not going to be the same as that used to encrypt the hiddenData when you created the license key. There are a number of other issues with the method you're using in itself, but that falls outside the scope of your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/19156127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error in R Krig function in package fields I am using package fields to do spatial analysis. My data set is as follow: x y Kopenhagen 12,57 55,68 Rotterdam 4,48 51,92 Belgrade 20,46 44,82 Budapest 19,04 47,5 Dublin -6,27 53,34 Rome 12,48 41,89 Lisbon -9,14 38,71 Bucharest 26,1 44,45 Madrid -3,7 40,42 Lausanne 6,63 46,52 London -0,13 51,5 Kiel 10,13 54,33 Augsburg 10,89 48,36 Innsbruck 11,398 47,25 Helsinki 24,94 60,17 Lyon 4,83 45,77 Ngreece 22,5 41,5 Ancona 13,11 43,37 Forde 5,9 61,44 Warsawa 21,01 52,23 Uppsala 17,64 59,86 Barcelona 2,17 41,38 Prague 14,42 50,09 This is the output of dput(map) structure(list(x = structure(c(6L, 18L, 11L, 10L, 21L, 5L, 23L, 16L, 17L, 22L, 1L, 2L, 3L, 4L, 15L, 19L, 14L, 7L, 20L, 12L, 9L, 13L, 8L), .Label = c("-0,13", "10,13", "10,89", "11,398", "12,48", "12,57", "13,11", "14,42", "17,64", "19,04", "20,46", "21,01", "2,17", "22,5", "24,94", "26,1", "-3,7", "4,48", "4,83", "5,9", "-6,27", "6,63", "-9,14"), class = "factor"), y = structure(c(20L, 16L, 8L, 12L, 18L, 5L, 1L, 7L, 2L, 10L, 15L, 19L, 13L, 11L, 22L, 9L, 4L, 6L, 23L, 17L, 21L, 3L, 14L), .Label = c("38,71", "40,42", "41,38", "41,5", "41,89", "43,37", "44,45", "44,82", "45,77", "46,52", "47,25", "47,5", "48,36", "50,09", "51,5", "51,92", "52,23", "53,34", "54,33", "55,68", "59,86", "60,17", "61,44" ), class = "factor")), .Names = c("x", "y"), class = "data.frame", row.names= c("Kopenhagen","Rotterdam", "Belgrade", "Budapest", "Dublin", "Rome", "Lisbon", "Bucharest", "Madrid", "Lausanne", "London", "Kiel", "Augsburg", "Innsbruck", "Helsinki", "Lyon", "Ngreece", "Ancona", "Forde", "Warsawa", "Uppsala", "Barcelona", "Prague")) and [1] 97.11559 59.86429 25.85145 54.56235 86.00903 17.45889 81.48449 [8] 87.57361 68.49520 44.40894 106.80953 67.36760 77.33586 47.96955 [15] 35.00993 75.26571 43.15965 17.55405 65.85301 46.19634 126.52848 [22] 42.26424 53.29187 The first data set called map and second called sigma. I write this code: fit<-Krig(map, sigma, theta=100) but it gives me the following error: Error in signif(mat, digits) : Non-numeric argument to mathematical function I do not understand where I am wrong as the organization of my data sets look the same as in the fields package manual. Any help is highly appreciated. A: The error because your columns x and y are factor. You must transform a factor to approximately its original numeric values. map$x <- as.numeric(gsub(",",".", map$x)) map$y <- as.numeric(gsub(",",".", map$y)) Krig(map, sigma, theta=100) Call: Krig(x = dat2, Y = sigma, theta = 100) Number of Observations: 23 Number of parameters in the null space 3 Parameters for fixed spatial drift 3 Model degrees of freedom: 19.2 Residual degrees of freedom: 3.8 GCV estimate for sigma: 9.943 MLE for sigma: 8.931 MLE for rho: 8808 lambda 0.0091 User rho NA User sigma^2 NA I don't konw how you had read map structure , but you can easily avoid teh conversion if you read it as a numeric. for example : map <- read.table(files,sep=',')
{ "language": "en", "url": "https://stackoverflow.com/questions/14141282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: multiple gradient to sass variable I want to add multi-browser based single gradient value to one sass variable. Help me with syntax. I tried below syntax but not getting result. Compiler aborts. $bg-gradient : -moz-linear-gradient( 90deg, rgb(32,40,0) 0%, rgb(56,72,0) 49%, rgb(84,111,0) 100%), -webkit-linear-gradient(left, rgb(32,40,0) 0%, rgb(56,72,0) 49%, rgb(84,111,0) 100%), -o-linear-gradient(left, rgb(32,40,0) 0%, rgb(56,72,0) 49%, rgb(84,111,0) 100%), linear-gradient(to right, rgb(32,40,0) 0%, rgb(56,72,0) 49%, rgb(84,111,0) 100%), A: I don't think you can accomplish this as a sass variable; however, it is possible to use a mixin to get the same result: @mixin bggradient() { -moz-linear-gradient( 90deg, rgb(32,40,0) 0%, rgb(56,72,0) 49%, rgb(84,111,0) 100%), -webkit-linear-gradient(left, rgb(32,40,0) 0%, rgb(56,72,0) 49%, rgb(84,111,0) 100%), -o-linear-gradient(left, rgb(32,40,0) 0%, rgb(56,72,0) 49%, rgb(84,111,0) 100%), linear-gradient(to right, rgb(32,40,0) 0%, rgb(56,72,0) 49%, rgb(84,111,0) 100%), } Then to call this mixin in your sass code: @include bggradient(); Here is more information about mixins: http://sass-lang.com/guide
{ "language": "en", "url": "https://stackoverflow.com/questions/37084747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set CLLocationManager's attribute from other class I am working on a sport project at the moment. What i want to do is, when users select the AutoPause switch on, the CLLocationManager will pause updating location when speed is below a certain level. Basically, i have figure out how to implement the locationManager by changes its attribute, but my question is, how can I set CLLocationManager's attribute from the settingViewController, whereas the CLLocationManager instance is in another ViewController. Thanks in advance. A: You can use NSNotificationCenter to send notification to enable/ disable the CLLocationManager's autopause attribute in another View Controller. Other approaches can be: * *Use class method, it is explained very well in this SO Answer *Use Delegates A: idk what' your problem with CLLocationManager, do you mean the way to pass object to another view controller? there are several way to do this.See this question:Passing Data between View Controllers I'm pretty sure that you can pass the CLLocationManager object to settingViewController by setting a property of that CLLocationManager,because passing the object means pass the reference the object,you can change the object in settingViewController life cycle,and it affects the CLLocationManager object which created by ViewController.
{ "language": "en", "url": "https://stackoverflow.com/questions/40840057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create binary tree from tree (n-ary) I want to solve the problem given in the image below. A: A New Algorithm to Represent a Given k-ary Tree into Its Equivalent Binary Tree. Refer This Paper In Simple words: 1. Create L to R sibling pointers at each level 2. Remove all but the leftmost child pointer of each node 3. Make the sibling pointer the right pointer.
{ "language": "en", "url": "https://stackoverflow.com/questions/25962615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Django redirect to page only if it exists I have a Python Django application I'm working on. There is a submission page that takes some input from the user and I spend time working on it with a thread. This processing can take variable time, as low as one minute to maybe 30 minutes. While the thread is running, I redirect to a waiting page, but I want to redirect from that waiting page to some output page when the processing thread completes. I can have the thread create all necessary changes i.e. creating the page template, appending some code to the views.py file, and adding the path to the urls.py file, but I'm not sure how to have that redirect trigger. I believe the overall question here is how can I redirect to a page in Django only if it exists? A: One possibility is to poll the results page. When it doesn't return a 404, you load the page. This answer by KyleMit to another question should work in your situation. To adapt his code: const poll = async function (fn, fnCondition, ms) { let result = await fn(); while (fnCondition(result)) { await wait(ms); result = await fn(); } return result; }; const wait = function (ms = 1000) { return new Promise(resolve => { setTimeout(resolve, ms); }); }; (async() => { const url = "/result.html"; let fetchResult = () => fetch(url); let validate = result => !result.ok; let response = await poll(fetchResult, validate, 3000); if (response.ok) location.replace(url); })(); Disadvantages of this approach are: * *Polling increases network traffic *You load the page twice. The advantage is that you can make the results page a parameter, then the user can close the page then come back later and continue waiting.
{ "language": "en", "url": "https://stackoverflow.com/questions/71356462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set the browser name parameter in the protractor script I have started using protractor and now able to execute same test script on multiple browsers by doing below changes in protractor.conf.js file. multiCapabilities: [{ 'browserName': 'chrome' }, { 'browserName': 'firefox' }], Now, I would like to parameterized my tests to provide browser name on which it should run. For e.g.: I have 2 test cases, 1 should run on chrome and other should run on firefox. This should be handled by providing browser name parameter in the test itself. Below is my first test case. Can you please help me to pass the browser name parameter in it. 'use strict'; /* https://github.com/angular/protractor/blob/master/docs/toc.md */ describe('Login and Logout Test Case', function () { //before Each unittests case load the login page beforeEach(function () { browser.get('#/login'); }); it('unittests the scenario when the user clicks on Dutch', function () { //The link for Dutch language from the login page is clicked element(by.id('username')).sendKeys('kaustubhsaxena'); element(by.id('password')).sendKeys('saxena'); element(by.id('login')).click(); browser.quit(); }); }); Thanks in advance for your help A: To get the browser name, you can use browser.getCapabilities(): browser.getCapabilities().then(function(capabilities) { // Outputs 'chrome' when on Chrome console.log(capabilities.caps_.browserName); }); If waiting until a promise is resolved isn't good for your use case, then a hackier way that works on my system is to access the resolved/fulfilled session object directly: // Outputs 'chrome' when on Chrome console.log(browser.driver.session_.value_.caps_.caps_.browserName);
{ "language": "en", "url": "https://stackoverflow.com/questions/30044698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Decodable JSONDecoder handle different coding keys for the same value I'm using Swift decodable protocol to parse my JSON response: { "ScanCode":"4122001131", "Name":"PINK", "attributes":{ "type":"Product", "url":"" }, "ScanId":"0000000kfbdMA" } I'm running into an issue where sometimes I get the ScanId value with a key "Id" instead of "ScanId". Is there a way to work around that? Thanks A: You have to write a custom initializer to handle the cases, for example struct Thing : Decodable { let scanCode, name, scanId : String private enum CodingKeys: String, CodingKey { case scanCode = "ScanCode", name = "Name", ScanID, Id } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) scanCode = try container.decode(String.self, forKey: .scanCode) name = try container.decode(String.self, forKey: .name) if let id = try container.decodeIfPresent(String.self, forKey: .Id) { scanId = id } else { scanId = try container.decode(String.self, forKey: .ScanID) } } } First try to decode one key, if it fails decode the other. For convenience I skipped the attributes key
{ "language": "en", "url": "https://stackoverflow.com/questions/51160450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }