text
stringlengths
15
59.8k
meta
dict
Q: Integrated Windows Authentication with IIS, Firefox and SQL Server I have a web site running on IIS on my localhost. This web site has directory security set to only allow Integrated Windows Authentication. It is part of an intranet and needs to authenticate by our domain accounts. I then connect to SQL Server with Integrated Security = SSPI in the connection string. This works fine with Microsoft Internet Explorer, it automatically authenticates me as I am logged into the domain, and I can see that the logon_user is my domain account, and the SQL Server connection string works just fine. However, when I log-in using Firefox, things are different. Firstly, I am prompted to authenticate, which is fine and correct as Firefox is not configured to trust the localhost enough to automatically send credentials (and indeed I am aware of how to introduce this trust already, this is not the problem). I then login, which again is fine, provided I enter the domain account details everything is fine. Indeed, a debug statement or two show that logon_user is still my domain account and everything is fine. However, when I come to connect to SQL Server (which is running on a remote server box, to which my domain account has full sysadmin privileges), I get the following error: Microsoft OLE DB Provider for SQL Server (0x80040E4D) Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'. This indicates to me that something is wrong in the authentication stack, for some reason, IIS is not running as the authenticated account when I authenticate using windows authentication from firefox. This also works fine when using Google Chrome. Any suggestions? A: * *Open Firefox *In the address bar type: about:config *Firefox3.x and later requires you to agree that you will proceed with caution. *After the config page loads, in the filter box type: network.automatic *Modify network.automatic-ntlm-auth.trusted-uris by double clicking the row and enter http://www.replacewithyoursite.com *Multiple sites can be added by comma delimiting them such as http://www.replacewithyoursite.com, http://www.replacewithyourintranetsite.com I also use IEtab add-on for the intranet sites A: IIS needs to pass a Kerberos ticket to SQL Server for this scenario to work. MSIE is picking up the workstation session ticket, whereas Firefox is negotiating its own authentication (and not Kerberos). Check out e.g. this dense blog post as a starting point for understanding what is needed. I'm not sure if FF support MS-Kerberos. Be aware that even getting MSIE->IIS->SQL Server authentication can be tricky if you have the wrong versions or trust configuration... A: AS noted by Pontus Gagge, IIS needs to pass a Kerberos ticket to SQL Server. That was enough to tip my Google-fu in the right direction. Firefox supports Kerberos, but, you have to tell it which domains it trusts to send the Kerberos tokens too. * *Open Firefox *In the address bar type: about:config *Firefox3.x and later requires you to agree that you will proceed with caution. *After the config page loads, in the filter box type: network.negotiate-auth *Modify network.negotiate-auth.trusted-uris by double clicking the row and enter yourdomain.com *Multiple domains can be added by comma delimiting them such as yourdomain.com, yourotherdomain.com Note: This is not the same as gbn's solution which just configures firefox to not prompt you to enter domain account details on login. Also, if you have already tried to authenticate through the stack in your current Firefox session, you will need to restart Firefox for this to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/733237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Is it possible to use the Twitter API to get replies older than 7 days? I've seen this question, but the answers are a bit of a mess: outdated, focused on various libraries' capabilities, and/or not clear about whether they apply to old tweets. I'm trying to look up replies to historical tweets (months or years old). I want to know if it's theoretically possible to use the Twitter API to directly or indirectly find those replies. At first glance, the conversation_id introduced in v2 seems intended for things like this, but the only way I've found to use it is in the recent search endpoint, which only goes back 7 days. This is nearly useless for me. The closest I've got is to look up tweets from the original author's timeline and look for ones in the same conversation. But that's limited to their most recent 3,200 tweets, and won't find replies from other people. FYI, I'm only interested in the endpoints available to the general public for free, not the Academic or Enterprise ones. I think this is called the Standard product track (Basic access level).
{ "language": "en", "url": "https://stackoverflow.com/questions/68339789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Best way to write onClick multiline function? I have this onClick function that shows the details of the user and then sets another state back to true. Would it be better to declare this function outside of the return as it is multiline? and if so how should I write it? <Button onClick ={() => {setSelectedUser(user); setShowUser(true);}}>{user.name}</Button> Here the rest of my code as reference: const UserList = () => { const [users, setUsers] = useState([]) const [selectedUser, setSelectedUser] = useState() const [showUser, setShowUser] = useState(true) const onHandleClick = () => setShowUser(false) useEffect(() => { fetch(URL) .then(res => res.json()) .then(json => setUsers(json)); }, []) return ( <> <Header> <h1>Contact list</h1> </Header> <Container> <div> {users.map(user => ( <div key={user.id}> <Button onClick ={() => {setSelectedUser(user); setShowUser(true);}}>{user.name}</Button> </div> ))} </div> {selectedUser && ( <> {showUser ? <UserDetail name={selectedUser.name} username={selectedUser.username} email={selectedUser.email} address={selectedUser.address.street} phone={selectedUser.phone} company={selectedUser.company.name} onClick={onHandleClick} /> : false} </> )} </Container> </> ) } A: If you want to declare function outside of the JSX then you can do as: <Button onClick={() => changeUser(user)}>{user.name}</Button> Declaration of function function changeUser(user) { setSelectedUser(user); setShowUser(true); }
{ "language": "en", "url": "https://stackoverflow.com/questions/69776517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with retrieving some values out of my Database <?php include 'session.php'; ?> <html> <head> <link href="css/adminOpmaak.css" rel="stylesheet" type="text/css"/> <?php mysql_connect("localhost", "admin", "") or die(mysql_error()); mysql_select_db("test") or die(mysql_error()); ?> </head> <body> <div class = "header"> <a href="index.php"><img src="home-icon.png" width="25" height ="25"></a> </div> <!--header--> <div class = "menu"> </div> <!--menu--> <div class ="content"> <form action="Login.php" method="POST"> <input type="text" align="center" name="Account" value="<?php echo isset ($_POST['Account'])?$_POST['Account']:"";?>"/> <br /> <input type="text" align="center" name="Password" value="<?php echo isset ($_POST['Password'])?$_POST['Password']:"";?>" /><br /> <input type="submit" name="Login" value="Login"/><br /> <?php if(isset ($_POST ['Login'])) { $querystring ="SELECT Account FROM Admins WHERE Account ='".$_POST['Account']."';"; $result = mysql_query($querystring); mysql_query($querystring)or die (mysql_error()); if (empty($_POST['Account']) || empty($_POST['Password'])) { echo "niet alles is ingevoerd"; } elseif (mysql_num_rows($result) == 1) { $user = mysql_fetch_assoc($result); } else { echo "dit account bestaat niet"; } if(md5($_POST['Password']) != $user['Password']) { echo "wachtwoord is niet correct";?><br/> <?php echo "Het account is:".$user['Account'];?><br/> <?php echo "het wachtwoord is: ".$user['Password'];?><br/> <?php echo mysql_fetch_assoc($result); } } ?> </form> </div> </body> </html> It's kinda strange since he does recognize the $user['Account']; and he doesnt recognize the password version. My database has the right values. This is what he echo's: wachtwoord is niet correct Het account is:Probeersel het wachtwoord is: So I dont know why he DOES recognize the account but he doesn't recognize wachtwoord. Why is that? A: There are a few problems. First, your mysql statement is wrong. Change this: $querystring ="SELECT Account FROM Admins WHERE Account ='".$_POST['Account']."';"; To this: $querystring ="SELECT * FROM Admins WHERE Account ='" .$_POST['Account']. "'"; Next, for one test, echo out the account name and password that you get from the db query, just so you can make sure you are getting what you expect (perhaps the capitalization is wrong for the field name or something like that). $user = mysql_fetch_assoc($result); echo 'Got this username: ' .$user['Account']. '<br />'; echo 'Got this password: ' .$user['Password']. '<br />'; Once you have confidence that you are getting the correct data, then you can finish your script. This: if(md5($_POST['Password']) != $user['Password']) { echo "wachtwoord is niet correct";?><br/> <?php echo "Het account is:".$user['Account'];?><br/> <?php echo "het wachtwoord is: ".$user['Password'];?><br/> <?php echo mysql_fetch_assoc($result); } Can be re-written as: if(md5($_POST['Password']) != $user['Password']) { echo "wachtwoord is niet correct<br />"; echo "Het account is: " .$user['Account']. "<br />"; echo "het wachtwoord is: " .$user['Password']. "<br />"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/18405940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delete the entire row of selected item in listbox, VBA Excel I'm trying to delete the entire row of the item(s) selected in my listbox, but the problem is the code deletes the very first row. Here is the code. Private Sub Mature_Click() Dim I As Long With ListBox1 For I = .ListCount - 1 To 0 Step -1 If .Selected(I) Then .RemoveItem I Sheets("Sheet1").Rows(I + 2).EntireRow.Delete End If Next I End With End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/31917780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is TryParse in C#7 syntax (empty out parameter) emitting a warning if you compile it? In C#7, you are allowed to do if (int.TryParse("123", out int result)) Console.WriteLine($"Parsed: {result}"); or - if you don't use the result and just want to check if the parsing succeeds, discard the out value: if (int.TryParse("123", out _)) Console.WriteLine("Syntax OK"); That works fine usually, but in Visual Studio 2017 the second example, where the out parameter is empty, generates the warning Warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CSharp.Diagnostics.SimplifyTypeNames.CSharpSimplifyTypeNamesDiagnosticAnalyzer' threw an exception of type 'System.NullReferenceException' with message 'Object reference not set to an instance of an object.'. The Visual Studio Versions where I could verify that it occurs is Visual Studio Enterprise 2017 Version 15.1 (26403.7) Release Visual Studio Enterprise 2017 Version 15.2 (26430.4) Release Is this a bug, or is the usage of int.TryParse("123", out _) not officially supported? I could not find any hint so far. For completeness, here's the code of the console application showing the issue: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { if (int.TryParse("123", out _)) Console.WriteLine("Syntax OK"); } } } A: I submitted a bug request (request #19180) to the development team, and they confirmed it is a bug. You can see the entire status here at GitHub dotnet/roslyn. Pilchie commented 16 hours ago I can repro that in 15.2, but not 15.3. Moving to compiler based on the stack, >Abut I'm pretty sure this is a dupe. @jcouv? jcouv commented 16 hours ago Yes, this is a duplicate (of #17229 and possibly another one too). It was fixed in dev15.3 (#17544) and we were unfortunately unable to pull the >fix into dev15.2. Thanks @Matt11 for filing the issue and sorry for the bug. It seems to be already fixed and will be - as far as I understood - available in the next update. But there is no announced date when it will be included by Microsoft, so I submitted an issue through "Send Feedback/Report a Problem" in Visual Studio 2017. Notes: * *The issue is not limited to TryParse. I verified that it also occurs if you write your own function, i.e. the following sample shows the warning AD0001 as well: static void Main(string[] args) { bool myOutDemo(string str, out int result) { result = (str??"").Length; return result > 0; } // discard out parameter if (myOutDemo("123", out _)) Console.WriteLine("String not empty"); } *I noticed that there is now a VS Version 15.3 preview available, which should contain the fix mentioned in the GitHub comments. Check out the following link: Visual Studio 2017 Version 15.3 Preview. After installing it, I verified the issue again and can confirm it is fixed there. Thanks to all who participated in the discussion above! (question comments)
{ "language": "en", "url": "https://stackoverflow.com/questions/43736660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: How to create dynamic table in sqlite-3 using python when user give your email address Sql = "CREATE TABLE IF NOT EXISTS ℅s (℅s text, ℅s text)" ℅ (Username, "first", " Second ") con. execute(sql) #Error- sqlite3.OperationError:near "@gmail": syntax error #help me sir A: Though I must admit that it seems strange to me to create tables with data-depending names, but technically the solution is to put the table name in square parentheses. This is the way to escape special characters like '@'. Something like this: Sql = "CREATE TABLE IF NOT EXISTS [℅s] (℅s text, ℅s text)" ℅ (Username, "first", " Second ")
{ "language": "en", "url": "https://stackoverflow.com/questions/64465078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Javascript: Not picking up my "src" <input class="textBox" id="userWebsite" type="text" /> <input type="button" id="button" value="Store" onclick="submit();"/> <!-- Storage START --> <select id="webLinks"> <option id="webPageOne">Web Page One</option> <option id="webPageTwo">http://www.example.com</option> <option id="webPageThree">http://www.example.com</option> <option id="webPageFour">http://www.example.com</option> </select> <input type="button" id="button" value="Goto" onclick="goto();"/> <!-- Storage END --> <iframe src="http://www.freedom.tm/dashboard" id="iframe"></iframe> <!-- Default Promotor END --> <script> var userWebsite = document.getElementById('userWebsite'); function submit() { document.getElementById("webPageOne").innerHTML = userWebsite.value; } var webPageOne = document.getElementById('webPageOne'); function goto() { document.getElementById("iframe").src = document.getElementsByTagName("option"); } </script> Ok, currently the problem is the end part function goto() { document.getElementById("iframe").src = document.getElementsByTagName("option"); } I was wondering why it isn't picking up the option that's selected. For example, if webpage two is selected, Why it doesn't select the website selected and change the source to what ever website two is set as? A: try: function goto() { document.getElementById("iframe").src = document.getElementById('webLinks').options[document.getElementById('webLinks').selectedIndex].text; } A: you have a js error, edit following function function goto() { document.getElementById("iframe").src = document.getElementsByTagName("option")[1].value; } or common approach function goto() { document.getElementById("iframe").src = document.getElementById('webLinks').options[document.getElementById('webLinks').selectedIndex].text; }
{ "language": "en", "url": "https://stackoverflow.com/questions/24001988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add observable to existing Subject I have an observable (Angular Subject) called event$. When screens are loaded I want to add DOM controls as emitters to this observable. The observable will already have subscribers. I'm achieving this by subscribing to an observable based on the control with the existing event$ as below. (Subscription management details omitted for clarity.) shared service: private _event$: Subject<Event> = new Subject(); public addEventEmitter(event: Observable<Event>) { event.subscribe(this._event$); } component code: @ViewChild('leftSide', { read: ElementRef }) leftSide: ElementRef; const leftClick$: Observable<Event> = fromEvent(this.leftSide.nativeElement, 'click'); this.comms.addEventEmitter(leftClick$.pipe(mapTo(anEvent))); I'm having, possibly unrelated, issues with an ion-toggle control intermittently showing the incorrect state. Is this a reasonable method of merging an observable with one that already has subscribers? Would I be better off having an onChange or click event call event$.next()? To my mind combining the observables is more reactive whereas calling the next method on the event$ for each control interaction is very imperative. A: Disregarding the simplicity and the elegance of being able to write event.subscribe(this._event$);, this is not a good idea. From what I noticed by doing this, is that whenever your _event$ completes, the event will also complete, which I don't think is the behavior you want. You're better off emitting the value manually like this: event.subscribe(e => this._event$.next(e)); And even though you said you omitted the subscription management details, I feel it's important to mention again that you need to manage this subscription in order to avoid memory leaks.
{ "language": "en", "url": "https://stackoverflow.com/questions/72939807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use MySql with ruby I have learned MySql in my school, but on CMD Prompt. Since i want to use that knowledge and want to create a GUI program in ruby (NOT A RUBY-ON-RAILS PROJECT) which use MySql commands like: SHOW DATABASES; USE DATABASE ruby; SELECT * FROM TABLE staff; CREATE TABLE STUDENT(Rollno integer, Class integer); INSERT INTO STUDENT VALUES(32, 12); SHOW TABLES; DROP TABLE STUDENT; etc. and etc... but i am unable to find about that, i have found mysql2 gemfile but it doesn't supports the command in my code, in require 'mysql2' client = Mysql2::Client.new(hostname: 'localhost', username: 'root', password: '1234', database: 'ruby') list = client.query("SHOW TABLES") list.each do |item| puts item end No output and I'm just frustrated Please give Suggestions WITH THE CONTIBUTION OF @URSUS, WE HAVE SOLVED THIS, WE RECHECKED THE MySql GEMFILE AND RECHECK THE Table in Database AND USE irb look over at this link: https://drive.google.com/open?id=19YUhmcLeMJn9aNEjM0bQNjpHIWrPZ0RX A: You need to adjust the query. This query works for me. client.query("SHOW TABLES FROM DB") DB being your database. In your connection string you are specifying a database to connect to, so I don't believe you will be able to run SHOW DATABASES. Try removing the DB from the connection string.
{ "language": "en", "url": "https://stackoverflow.com/questions/47890589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bootstrap multi-select: Adding images instead of text firstly here's the link: http://liveweave.com/We9Qg8 I want to add images to a dropdown with multi-select, I am using bootstrap multi-select plugin, I've figured out how to add text to the dropdown after the main text of each dropdown. I can't seem to find how to add images after the checkboxes. HTML code: <div class="example"> <select id="example-multiple-selected" multiple="multiple" style="display: none;"> <option value="option-1">Option 1</option> <option value="option-2">Option 2</option> <option value="option-3">Option 3</option> <option value="option-4">Option 4</option> <option value="option-5">Option 5</option> <option value="option-6">Option 6</option> </select> </div><!--/.example --> JS Code: $(document).ready(function() { $('#example-multiple-selected').multiselect({ includeSelectAllOption: true, allSelectedText: 'No option left ...', selectAllText: 'All Libraries', buttonText: function(options, select) { return 'Libraries'; }, buttonTitle: function(options, select) { var labels = []; options.each(function () { labels.push($(this).text()); }); return labels.join(' - '); }, optionLabel: function(element) { return $(element).html() + '(' + $(element).val() + ')'; } }); }); Any help on how to add images would be appreciated. A: I found solution to this after a bit of research: Here's the fiddle The JS code to be used is as follows: $(document).ready(function() { $('.multiselect').multiselect({ buttonWidth: 'auto', numberDisplayed:15, enableHTML: true, optionLabel: function(element) { return '<img src="http://placehold.it/'+$(element).attr('data-img')+'"> '+$(element).text(); }, onChange: function(element, checked) { //console.log(element.attr('value') + checked); $("ul.multiselect-container").find("input[type=checkbox]").each(function(){ //console.log(element.attr('value')); var valueAttr = $(this).attr('value'); if (element.attr('value') == valueAttr) { var checkParent = $(this).parent().parent().parent().hasClass('active'); //console.log(checkParent); if (checkParent == false) { $(this).removeAttr('disabled') }else{ $(this).attr('disabled','disabled') } } }); } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/30305504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom provider within angular .config I saw a couple of examples how to insert custom providers into angular's .config, but I fail to do it properly. I have a provider: (function() { var app = angular.module('application.providers', ['application.services']) app.provider('accessProvider', function() { this.$get = ['userServices', function(userServices) { var auth = {} auth.action = function(action, roles) { auth[action] = angular.copy(roles) } auth.action('sell', [...]) auth.can = function(action) { var userRole = userServices.getRole() return auth[action].reduce(function(prev, now) { return prev || (now === userRole) }, false) } return auth } ] }) })() And when I am defining my routes here: (function() { var app = angular.module('application.configRoutes', ['ngRoute', 'application.providers']) app.config(['$routeProvider', '$locationProvider', 'accessProvider', function($routeProvider, $locationProvider, accessProvider) { ... I get the following error: Uncaught Error: [$injector:modulerr] Failed to instantiate module landingPage due to: Error: [$injector:modulerr] Failed to instantiate module application.configRoutes due to: Error: [$injector:unpr] Unknown provider: accessProvider This is how I instantiate my app: var app = angular.module('landingPage', [ 'application.configRoutes', 'application.directives', 'application.controllers', 'application.translate', 'application.flash', 'application.customInterceptors' ]) and I load the file storing the services.js before the providers.js and only then I load the configRoutes.js. A: Found my problem. I did not append Provider to the provider name. In this case it would look like accessProviderProvider.
{ "language": "en", "url": "https://stackoverflow.com/questions/25594487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I obtain the rows that contain a specific minimum value? I have a table with 3 rows and 3 columns. For all the rows with the same name, I want to retrieve the one that has the minimum value in the position column. in this example here. The result should be (apple, red, 3) and (melon, big, null). null value in the 'position' column means that fruit is not in the list. name category position apple fruit 5 apple red 3 melon big null A: The null makes this tricky. I'm not sure if it should be considered "high" or "low". Let me assume "low": select t.* from t where coalesce(t.position, -1) = (select min(coalesce(t2.position, -1)) from t t2 where t2.name = t.name ); A: SELECT f.* FROM ( SELECT name, MIN(IFNULL(position,0)) as min_position FROM fruits GROUP BY name ) tmp LEFT JOIN fruits f ON f.name = tmp.name AND IFNULL(f.position,0) = min_position -- GROUP BY name -- optional if multiple (name, position) are possible for example -- [apple,fruit,5], [apple,red,5]
{ "language": "en", "url": "https://stackoverflow.com/questions/45415733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I get my webpage to load quickly when I need lots of sound files? I'm pretty new to web design and I'm building a webpage for learning the Cherokee syllabary. The main page is a table of 85 characters that plays the sound for the character when you click on one. Currently I have all of the sound files stored in both .mp3 and .oog formats in a /sounds folder, and I put 85 different <audio> tags at the end of my html document, and play them using jQuery as shown below. The page load time is okay on my laptop but on my phone it's really slow, and I assume this is because of all of the sound files. How can I implement this in a way that loads the page more quickly? $('td').click(function(){ var name = $(this).find('.tbl-en').html(); var tag = 'audio-' + name; var sound = document.getElementById(tag); sound.play(); }); <audio id="audio-a"> <source src="sounds/a.mp3" type="audio/mp3"> <source src="sounds/a.oog" type="audio/oog"> </audio> A: Don't set the src attribute until the user has clicked on that element. Here is an example: http://codepen.io/tevko/pen/raQMjP
{ "language": "en", "url": "https://stackoverflow.com/questions/38296622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facing flash of images when my page loads When two stylesheets have classes with same names, how does the style apply on the elements? Does it apply both the styles linearly and then render the final output or it applies the first style and the one with higher specificity replaces the first one (showing both outputs maybe too fast)?
{ "language": "en", "url": "https://stackoverflow.com/questions/30435751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fadeout on hover effect in iPad I tried to use the fadeIn and fadeOut effect as you can see in this page: http://www.lifetime-watches.com/gal-w.html var titleString = $(this).find('a').attr("title"); $("#title").html(titleString).fadeIn(100); ; So when they run the script the title of the image would fade in in a div. But the problem is when this page is opened in iPads, the hover function doesn't work (because obviously they don't have hover) and the div wouldn't fade out. What are the alternatives to this? Any help is appreciated. Thank you. A: The jQuery Hoverable Plugin: unifies touch and mouse events over different platforms like desktops and mobile devices with touchscreens That might be a good alternative for your app. A: You want to create a second implementation that works with the click event. May be something like this: $(selector syntax).click(function () { AnimationEffect(this); }); $(selector syntax).mouseenter(function () { AnimationEffect(this); }); function AnimationEffect(TheDiv) { //your animation goes here, TheDiv is the jquery object //you can access it like this: $(TheDiv). } A: Have the user click on the watch, then click again to get rid of the info. This can be accomplished using the .toggle() method: http://api.jquery.com/toggle-event/
{ "language": "en", "url": "https://stackoverflow.com/questions/7543306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python - Connect AS400 Collection using ibm_db I am able to connect to our database given the following connection string (OLEDB). "Provider=IBMDA400;Data Source=10.33.xx.x;User Id=user;Password=pass;Default Collection=mm370lib;"; Then tried (Python ibm_db) import ibm_db, ibm_db_dbi ibm_db_conn = ibm_db.connect("DRIVER={IBM DB2 CLI DRIVER};DATABASE=mm370lib;HOSTNAME=10.33.xx.x;PORT=446;PROTOCOL=TCPIP;UID=user;PWD=pass;", '', '') But this error occured. Exception: [IBM][CLI Driver] SQL30061N The database alias or database name "MM370LIB " was not found at the remote node. SQLSTATE=08004 SQLCODE=-30061 What did I missed? Are the database Name and Default Collection different? A: Yes, the DB name is usually the system name; though it doesn't have to be. Originally, the AS/400 support only a single DB. With the introduction of independent storage pools (iASP), today's IBM i machines can have multiple DBs. From a 5250 session, try: WRKRDBDIRE Look for the *LOCAL entry, may be the only one. You can also see the DB names using IBM i Navigator for Windows or the web based IBM Navigator. The DB names are shown under the "Databases" , there are three DBs on the system: Rchasma1, Iasp320, Ima1db1.
{ "language": "en", "url": "https://stackoverflow.com/questions/28980698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: char* have internal linkage so it can't not be a none-type template argument Some code that I don't understand: template<const char *T> class A { }; const char *arr="hello world"; int main() { A<arr> obj; } This snippet won't compile. Error message from visual studio compiler is : Invalid template argument for 'A', expected compile-time constant expression Error messega from g++ is: 'arr' is not a valid template argument because 'arr' is a variable , not the address of a variable For visual studio compiler, even after I change the const to constexpr, that code still doesn't compile. Why is that? Is that relevant to those internal linkage and external linkage thing?(I read this from the book C++ template, but don't understand why and how) Additionally, change the const char *arr = "Hello world"; to const char arr[] = "Hello world"; or external const char *arr="Hello world"; won't work. But this would work:external const char arr[]="Hello world"; A: The issue is simpler than you're making it. The Visual Studio compiler's error message is actually quite clear. arr is not a valid template argument because it is not a compile-time constant. In order to use a string as a template non-type parameter, it must be a variable with external linkage (although C++11 does, I believe, remove this requirement—see Columbo's answer). So you could change your code to the following, and it would work: template <const char* T> class A { // ... }; extern const char arr[] = "hello world"; int main() { A<arr> obj; } Note how the declaration of arr has changed. The variable is now a named object with external linkage, and so it can be used as a template non-type parameter. Basically, what happens is its address is passed to the template. This means that it is not the content of the string that determines its uniqueness, but the object itself. In other words, if you had two different variables that held exactly the same string, they would nevertheless have different types and create two different instantiations of the template class. A: Template parameters of pointer type are not allowed to refer to string literals ([temp.arg.nontype]/(1.3)). Instead, declare a global array: constexpr char arr[] = "hello world"; // Or use const only, but won't be able to // use it inside the template This can be used as a template argument, since it can appear in constant expressions and has static storage duration, making it a permitted result of a constant expression ([expr.const]/5).
{ "language": "en", "url": "https://stackoverflow.com/questions/34788138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: LINQ to SQL - Database Design issue I'm quite new to working on Databases in general, and hope to get your guidance as to what went wrong. I have 4 tables at hand, currently set-up in this way: Company - Just an ordinary Company table with certain data in it Company_GoodsPackaging - A reference table for Company, where the information on WHAT kind of goods the company 'does' and what packaging type, for that good, is being done. GoodsType - Basically an enum, values right now are: 1 Commodity 2 Food / feed 3 Live Animals 4 Plants 5 Special cargo 6 Exceptional PackagingType - Also an enum, values: 1 Parcel 2 Pallet 3 Container 4 Bulk 5 Oversized CODE In my code-behind of my ASP.NET website I'm doing the following: I iterate through all GoodsType values, and try to see whether CompanyX (a LINQ Company object) has this value in its table, and if so, what's the Packaging_Type.Description of the value. The problem I'm having now, is that when I have my Company object, I don't seem to be able to extract its members. var theSource = (from g in Data.GoodsTypes select new { gvGoodsType = g.Description, gvParcels = true, gvContainers = curCompany.Company_GoodsPackagings.GoodsType == g.Goods_Type && curCompany.Company_GoodsPackagings.PackagingType1.Description == "Container" } The relationships are done, everything seems to be correct, but I can't just seem to be able to extract the GoodsType and PackagingType of a Company_GoodsPackaging entry. I know it's a EntitySet. Where is my DataBase design flawed/Code logic flawed? I have to say, I'm very new to working in DataBases alltogether. Any help/input would be much welcome. Error I'm getting in VS is Error 26 'System.Data.Linq.EntitySet' does not contain a definition for 'GoodsType' and no extension method 'GoodsType' accepting a first argument of type 'System.Data.Linq.EntitySet' could be found (are you missing a using directive or an assembly reference?) *****\Account\MyAccountTransport.aspx.cs 33 8 A: If I'm not mistaken, Company -> Company_GoodsPackagings is a one to many relationship? Therefore the property Copmany_GoodsPackagings will be a collection and so you will need to use the Any() function as follows: var theSource = (from g in Data.GoodsTypes select new { gvGoodsType = g.Description, gvParcels = true, gvContainers = curCompany.Company_GoodsPackagings.Any(gp => qp.GoodsType == g.Goods_Type && gp.PackagingType1.Description == "Container") } EDIT: It seems that my suggestion to use Any() is not supported by Linq to SQL. Therefore I would suggest that you bring back the whole goods packaging object and then check to see if it has a value or not in order to determine boolean gvContainers: You can then convert your anonymous type into a concrete class and add the property at the end of the example: var theSource = (from g in Data.GoodsTypes select new GoodsResult { gvGoodsType = g.Description, gvParcels = true, gvGoodsPackaging_Container = curCompany.Company_GoodsPackagings.FirstOrDefault(gp => qp.GoodsType == g.Goods_Type && gp.PackagingType1.Description == "Container") } public bool gvContainers { get { return this.gvGoodsPackaging != null } } A: The problem is that curCompany.Company_GoodsPackagings is a collection of GoodsPackagings (hence the plural and the mention of System.Data.Linq.EntitySet). You can't therefore refer directly to a single GoodsType for the Company in this way. I think you're looking for a way to test each one of the Company's GoodsPackagings against your conditions. To do this you can use the Any() Linq extension method: using System.Linq; ... gvContainers = curCompany.Company_GoodsPackagings.Any(gp => gp.GoodsType == g.Goods_Type && gp.PackagingType1.Description == "Container")
{ "language": "en", "url": "https://stackoverflow.com/questions/13658449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Split strings by commas only if substrings are elements of another vector I have a set of survey responses where respondents could select zero or more options to answer the question "What types of fruit do you like?". There was also a space for a write-in answer. In the results spreadsheet, each person's response is in one cell with the different types of fruit separated by commas, like so: (df <- data.frame(id = c("A", "B", "C", "D", "E"), data = c("oranges, apples, peaches, cherries, pineapples, strawberries", "oranges, peaches, pears", "pears, nectarines, cherries (bing, rainier)", "apples, peaches, nectarines", ""), stringsAsFactors = FALSE)) # id data # 1 A oranges, apples, peaches, cherries, pineapples, strawberries # 2 B oranges, peaches, pears # 3 C pears, nectarines, cherries (bing, rainier) # 4 D apples, peaches, nectarines # 5 E What I want to do is split up the responses into a long-format table, which I've nearly accomplished using the code at the bottom. However, some respondents included commas in their write-in responses, and I don't want to split their answers on the commas. I know what all the original multiple choice options were; how can I split up only these answers, leaving the write-ins (with commas) intact? I want to end up with a data frame like this: id data 1 A oranges 2 A apples 3 A peaches 4 A cherries, pineapples, strawberries 5 B oranges 6 B peaches 7 B pears 8 C pears 9 C nectarines 10 C cherries (bing, rainier) 11 D apples 12 D peaches 13 D nectarines The multiple choice options are: mc_answers <- c("oranges", "plums", "apples", "peaches", "pears", "nectarines") What I've accomplished so far is: # use strsplit to create a list of the types of fruit each person likes datalist <- strsplit(df$data, ", ") names(datalist) <- df$id # remove zero-length list elements (person E doesn't like any fruit) datalist <- Filter(length, datalist) # convert list elements to data frames datalist_dfs <- lapply(datalist, data.frame, stringsAsFactors = FALSE) datalist_dfs <- lapply(datalist_dfs, setNames, "data") # name each column 'data' # add id column to each data frame data_long <- mapply(function(x, y) "[<-"(x, "id", value = y), datalist_dfs, names(datalist_dfs), SIMPLIFY = FALSE) # combine into one big data frame (data_per_person <- do.call('rbind', data_long)) # data id # A.1 oranges A # A.2 apples A # A.3 peaches A # A.4 cherries A # should # A.5 pineapples A # be one # A.6 strawberries A # entry # B.1 oranges B # B.2 peaches B # B.3 pears B # C.1 pears C # C.2 nectarines C # C.3 cherries (bing C # should be # C.4 rainier) C # one entry # D.1 apples D # D.2 peaches D # D.3 nectarines D There are no rules for how many fruits a person could have selected, but if there is a write-in answer it is always last. A: After this line: datalist <- Filter(length, datalist) Do: datalist <- lapply(datalist, function(x) { if(any(!x %in% mc_answers)) c(x[x %in% mc_answers], paste(x[!x %in% mc_answers], collapse = ", ")) else x[x %in% mc_answers] }) Then run the rest of your code as-is so you end up with: > (data_per_person <- do.call('rbind', data_long)) data id A.1 oranges A A.2 apples A A.3 peaches A A.4 cherries, pineapples, strawberries A B.1 oranges B B.2 peaches B B.3 pears B C.1 pears C C.2 nectarines C C.3 cherries (bing, rainier) C D.1 apples D D.2 peaches D D.3 nectarines D A: You could also try: library(data.table) library(devtools) source_gist(11380733) ## df1 <- cSplit(df, "data", sep=", ", "long") indx <- df1$data %in% mc_answers res <- rbindlist(list(df1[indx,], df1[!indx,][, list(data=paste(data, collapse=", ")), by=id]))[order(id)] res # id data #1: A oranges #2: A apples #3: A peaches #4: A cherries, pineapples, strawberries #5: B oranges #6: B peaches #7: B pears #8: C pears #9: C nectarines #10: C cherries (bing, rainier) #11: D apples #12: D peaches #13: D nectarines A: How about something like this do.call(rbind, lapply(split(df, df$id), function(x) { v<-unlist(strsplit(x$data, ",\\s?")) v<-c(v[v %in% mc_answers], paste(v[!v %in% mc_answers], collapse=", ")) v<-v[nchar(v)>0] if (length(v)>0) { data.frame(id=x$id[1], data=v) } else { NULL } })) Here we split to process each group separately and then do the string splitting. Then we collapse all those entries that aren't in the mc_answers vector. It returns id data A.1 A oranges A.2 A apples A.3 A peaches A.4 A cherries, pineapples, strawberries B.1 B oranges B.2 B peaches B.3 B pears C.1 C pears C.2 C nectarines C.3 C cherries (bing, rainier) D.1 D apples D.2 D peaches D.3 D nectarines
{ "language": "en", "url": "https://stackoverflow.com/questions/25098280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Git commit of cordova package.json project with sensitive data I'm working on a Ionic/Cordova project which some plugins that need sensitive data: * *cordova-background-geolocation require a license; *cordova-plugin-googlemaps require api keys. When adding those plugins to the project, they get saved in my config.xml and package.json. My problem is that I need to commit to Github those files but how can I do it without committing those sensitive data? Anyone have a solution or suggestion? Thanks A: I keep these local changes in a branch that never gets pushed. My workflow looks like this (assuming master tracks a public branch origin/master): git checkout -b private // make local changes, such as plugging in license keys, passwords, etc. git commit -am "DO NOT PUSH: local changes" // tag here because later my cherry-pick starts here git tag -f LOCAL // now work on what you need to work on... and whenever I am ready, commit away git commit -am "feature 1" // keep hacking... git commit -am "feature 2" // When I get to a point where I want to push the series of commits I've got to the remote repo: git checkout master git cherry-pick LOCAL..private git push origin master git rebase master private git tag -f LOCAL // resume working...
{ "language": "en", "url": "https://stackoverflow.com/questions/50656942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: RxJS Observables: Creating with values I don't yet have the service to call for the values, so I am doing some boiler plate code with aysnc ngFors. I am trying to create an obserable that can be consumed by an ngFor. I try: statuses$ = Observable.create((o) => { o.next(new NameValue('Open', 'OPEN')); o.next(new NameValue('Closed', 'CLOSED')); o.complete(); }); then <mat-option *ngFor="let status of statuses$ | async" [value]="status.value"> {{ status.name }} </mat-option> but I get an Async error Cannot find a differ supporting object '[object Object]' of type 'Open'. NgFor only supports binding to Iterables such as Arrays A: Simulate your observable like this: import { of } from 'rxjs'; statuses$ = of([new NameValue('Open', 'OPEN'), new NameValue('Closed', 'CLOSED')]); which gives an array that *ngFor can interpret, rather than the object you are returning currently.
{ "language": "en", "url": "https://stackoverflow.com/questions/63620920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Leaflet+Vue+Vuetify / Leaflet map hide vuetify popup dialog On my Vuetify + Lealflet project the map hides all popup dialogs and I don't know why. I use Vue2Leaflet library. I am a beginner with web development. Here is a pic of the problem: <l-map :center="center" :zoom="zoom" @click.right="mapRclicked" ref="map" style="height: 50vh; width: 50vh" > A: Edit: This is an outdated answer. see @Javier answer below as pointed out by @ondrejsv on comment. It does not work anymore at least in Vuetify 2.1.9 and Vue 2.6.x. The solution by Javier seems to work. Increase the z-index style property of your dialog. <v-dialog style="z-index:9999;" ... rest of your code ... A: I find it quite practical to wrap the map in an image, like this <v-img height="100%" width="100%"> <l-map> ... </l-map> </v-img> This way there is no need to do anything with the z-index. A: The problem is a clash of z-index ranges. Vuetify uses z-index ranges 0-10 while leaflet uses the range 100-1100. Fortunately, the z-index of a child element is relative to the z-index of their parent. I advice you to give l-map a z-index of 0 like this. <l-map :center="center" :zoom="zoom" @click.right="mapRclicked" ref="map" style="z-index: 0; height: 50vh; width: 50vh" > This will automatically bring your component in line with all of Vuetify z-indexes. In contrast, @bgsuello workaround requires that you modify the z-index of every Vuetify component that may conflict with the map, including other dialogs, menus, animations, tabs, toolbars, snackbars... A: I am on Vue2.x + Vuetify + Vue2leaflet. I tried many things and finally what worked for me was to cover the with a . My code reads as : <v-lazy> <v-img> <l-map> .... rest of the code </l-map> </v-img> </v-lazy> This takes inputs on v-lazy from https://medium.com/@elralimi.lamia/leaflet-vuejs-vuetify-map-not-showing-well-in-a-modal-with-grey-parts-9a5d551ea472. v-img was suggested by geomuc in the above response. Other options that I tried but failed were: this.map.invalidateSize(); , this.map.remove();, this.$nextTick(() => {...}, z-index.
{ "language": "en", "url": "https://stackoverflow.com/questions/53929421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: C++ cin.ignore causing a seg fault? int client::add_user(item & item_in) { char temp[ASIZE]; cout << "\n\nEnter the name of your item: "; cin.get(temp, 100, '\n'); cin.ignore(100, '\n'); get_upper(temp); item_in.name = temp; cout << "\n\nEnter in effect one: "; cin.get(temp, 100, '\n'); cin.ignore(100, '\n'); get_upper(temp); item_in.effect1 = temp; cout << "\n\nEnter in effect two: "; cin.get(temp, 100, '\n'); cin.ignore(100, '\n'); get_upper(temp); item_in.effect2 = temp; cout << "\n\nEnter in effect three: "; cin.get(temp, 100, '\n'); cin.ignore(100, '\n'); get_upper(temp); item_in.effect3 = temp; cout << "\n\nEnter in effect four: "; cin.get(temp, 100, '\n'); cout << "this"; cin.ignore(100, '\n'); cout << "that"; get_upper(temp); item_in.effect4 = temp; ... Understanding that I am sure there is plenty wrong with this code, the problem I am having is that the first four blocks run just fine, but when I compile this code using g++ and run it, "this" displays, followed by a segmentation fault and no "that". Any ideas? A: Based on another of your questions, it looks like the parameter item_in is a struct with several char * fields. There is a serious problem because the array temp only exists for the duration of this function. You are assigning the address of a temporary array to pointers in item_in. When the function returns, the array goes out of scope and its memory is no longer yours. You could fix this by allocating memory to the pointers and copying the data but the best solution is to use std::string from the C++ standard library. It handles resource management and operations like assignment work as you would expect.
{ "language": "en", "url": "https://stackoverflow.com/questions/10749836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to change the value of a global varibale in javascript? I have been working on some code for a game which I have tried to add states to. I set a global variable "gameState", and I want to change the value of that global variable once a certain thing is selected by the player. For some reason, my global variable will not change when the player makes their selection. :/ Below is a shortened version of my code only containing Algeria as an example. When the character goes over the Algerian flag on the canvas and hits enter, I want to switch to state 2. Instead, nothing happens. The code continues to run state 1. // The Almighty Game State var gameState = 1; // Creates The Canvas var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); canvas.width = 1200; canvas.height = 500; document.body.appendChild(canvas); //-------------------------(GAME STATE 1)-------------------------// if (gameState === 1) { //---------------(IMAGE RESOURCES)---------------// // Loads Character Image var characterReady = false; var characterImage = new Image(); characterImage.onload = function () { characterReady = true; }; characterImage.src = "images/character.png"; // Loads Background Image 1 var background1Ready = false; var background1Image = new Image(); background1Image.onload = function () { background1Ready = true; }; background1Image.src = "images/background1.png"; // Loads Algeria Flag Image var falgeriaReady = false; var falgeriaImage = new Image(); falgeriaImage.onload = function () { falgeriaReady = true; }; falgeriaImage.src = "images/falgeria.png"; //---------------(GAME OBJECTS/VARIABLES)---------------// var action = 0; var character = { speed: 250 }; var falgeriaText = 0; var falgeria = {}; falgeria.x = 570; falgeria.y = 180; //---------------(GAME FUNCTIONS)---------------// // Resets Character To Center var reset = function () { character.x = canvas.width / 2; character.y = canvas.height / 2; }; // Checks For Key Inputs var keysDown = {}; addEventListener("keydown", function (e) { keysDown[e.keyCode] = true; }, false); addEventListener("keyup", function (e) { delete keysDown[e.keyCode]; }, false); //---------------(UPDATE GAME OBJECTS)---------------// var update = function (modifier) { // Establishes Keyboard Controls if (38 in keysDown) { // Player Holding Up Key character.y -= character.speed * modifier; } if (40 in keysDown) { // Player Holding Down Key character.y += character.speed * modifier; } if (37 in keysDown) { // Player Holding Left Key character.x -= character.speed * modifier; } if (39 in keysDown) { // Player Holding Right Key character.x += character.speed * modifier; } if (87 in keysDown) { // Player Holding W Key character.y -= character.speed * modifier; } if (83 in keysDown) { // Player Holding S Key character.y += character.speed * modifier; } if (65 in keysDown) { // Player Holding A Key character.x -= character.speed * modifier; } if (68 in keysDown) { // Player Holding D Key character.x += character.speed * modifier; } if (13 in keysDown) { // Player Holding Enter Key action = 1; } else { action = 0; } // Creates Borders Around Canvas if (character.x >= canvas.width - characterImage.width) { character.x = canvas.width - characterImage.width; } else if (character.x <= 0) { character.x = 0; } if (character.y >= canvas.height - characterImage.height) { character.y = canvas.height - characterImage.height; } else if (character.y <= 0) { character.y = 0; } //Checks If Character Is Over Algeria if ( character.x <= (falgeria.x + 30) && falgeria.x <= (character.x + 30) && character.y <= (falgeria.y + 30) && falgeria.y <= (character.y + 30) ) { falgeriaText = 1 } else { falgeriaText = 0 } if ( character.x <= (falgeria.x + 30) && falgeria.x <= (character.x + 30) && character.y <= (falgeria.y + 30) && falgeria.y <= (character.y + 30) && action === 1 ) { gameState = 2; } }; //---------------(DRAW TO CANVAS)---------------// var render = function () { if (background1Ready) { ctx.drawImage(background1Image, 0, 0); } if (falgeriaText === 0) { ctx.font = "24px Helvetica"; ctx.fillStyle = "rgb(0, 0, 0)"; ctx.textAlign = "center"; ctx.fillText("Select A Country To Grow Your Potato In", 600, 450); } if (falgeriaReady) { ctx.drawImage(falgeriaImage, 570, 180); } if (falgeriaText === 1) { ctx.fillText("Algeria | Press [ENTER] To Select", 600, 450); } if (characterReady) { ctx.drawImage(characterImage, character.x, character.y); } }; //---------------(Loop)---------------// var main = function () { var now = Date.now(); var delta = now - then; update(delta / 1000); render(); then = now; requestAnimationFrame(main); }; var w = window; requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame; var then = Date.now(); reset(); main(); } if (gameState === 2) { alert("gameState Changed") } A: You basically have this: var gameState = 0; if(gameState === 1) { // never called since gameState = 0 } if(gameState ===2) { // never called since gameState = 0 } Which is probably not want you want. If you aren't familiar with the Javascript debugger, you might want to look up a tutorial on how to use it. You would see that none of your code is being called at the moment. Even if you modify it to this: var gameState = 1; if(gameState === 1) { requestAnimationFrame(main); // main is called after the remaining sync code has executed } if(gameState ===2) { // never called since gameState = 1 } It still will never execute since the gameState===2 if statement will be executed immediately (since it is synchronous) before anything is executed with the requestAnimationFrame callback (since that is done asyncronously).
{ "language": "en", "url": "https://stackoverflow.com/questions/27372182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Keeping controls in the visible area I've got a grid with several TextBoxes in it. I want to keep this grid fixed at the bottom of my main window. So if the user scrolls down the grid should basically stay in it's place. One way I thought of doing this was to get some sort of value from the ScrollViewer and add it to the grids Canvas.TopProperty. However I am not sure which value changes when the user scrolls up or down. A: Then don't put the scroll on the main window. Put ScrollViewer only on the content (rows) that you want to scroll. Careful not to use an auto for the height of the rows with the ScrollViewer or the container will grow to support all the content and the Scroll does not come into play. A: One way: <Window x:Class="Sample.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <ListBox> <!--Hardcoded listbox items just to force the scrollbar for demonstration purposes --> <ListBoxItem>Item1</ListBoxItem> <ListBoxItem>Item2</ListBoxItem> <ListBoxItem>Item3</ListBoxItem> <ListBoxItem>Item4</ListBoxItem> <ListBoxItem>Item5</ListBoxItem> <ListBoxItem>Item6</ListBoxItem> <ListBoxItem>Item7</ListBoxItem> <ListBoxItem>Item8</ListBoxItem> <ListBoxItem>Item9</ListBoxItem> <ListBoxItem>Item10</ListBoxItem> <ListBoxItem>Item11</ListBoxItem> <ListBoxItem>Item12</ListBoxItem> <ListBoxItem>Item14</ListBoxItem> <ListBoxItem>Item15</ListBoxItem> <ListBoxItem>Item16</ListBoxItem> <ListBoxItem>Item17</ListBoxItem> <ListBoxItem>Item18</ListBoxItem> <ListBoxItem>Item19</ListBoxItem> <ListBoxItem>Item20</ListBoxItem> <ListBoxItem>Item21</ListBoxItem> <ListBoxItem>Item22</ListBoxItem> </ListBox> <Grid Panel.ZIndex="5" VerticalAlignment="Bottom" Background="DarkGray"> <StackPanel> <TextBox HorizontalAlignment="Left" VerticalAlignment="Center">Text box 1</TextBox> <TextBox HorizontalAlignment="Left" VerticalAlignment="Center">Text box 2</TextBox> <TextBox HorizontalAlignment="Left" VerticalAlignment="Center">Text box 3</TextBox> </StackPanel> </Grid> </Grid>
{ "language": "en", "url": "https://stackoverflow.com/questions/8388640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How I check that an api call to an appengine instance came from a Google Compute Engine instance? We are using a Google Compute Engine instance to generate convert datastore tables into large downloadable csv files. We want this instance to log errors to an app engine front end instance by calling: /api/log But we want to be sure that this call came from the Google Compute Engine instance which has the authority to write to the log. How can we check that an api call came from a Google Compute Engine instance? A: It all depends on how secure you want it to be. The simplest solution is to include a parameter in your POST request that only your backend and front-end instances would recognize - any random sequence of characters will do the trick. The next level is to use a secret key to encrypt the contents of the request - there are many implementations depending on the language that you use. This approach is more flexible too, if you decide, for example, to move your backend from App Engine to Compute Engine.
{ "language": "en", "url": "https://stackoverflow.com/questions/22229434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fabric8 unable to start on windows 10 I'm trying to run gofabric8 start on windows 10 i've the minikube and kubectl running perfectly but when I tried to run gofabric8 start it is giving me an error like Cannot connect to API server i tried setting no_proxy and everything but it is still giving me this error. please help me !!!
{ "language": "en", "url": "https://stackoverflow.com/questions/48762098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find min/max x,y in each vector> I found contours in the image and I store their coordinates in vector < vector < Point >> like below: vector of vector(Point) I want to find xmax,xmin,ymax and ymin in each vector. Min/Max coordinates I have to write it down somewhere, so I could use these values in further part of my script. vector<vector<Point> > contours1; vector<Vec4i> hierarchy1; findContours(testowy, contours1, hierarchy1, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); int xmax = 0; int xymax = 0; int ymax = 0; int yxmax = 0; for( int i = 0; i < contours1.size(); i++ ){ for(int j=0; j < contours1[i].size();j++){ if(contours1[i][j].x > xmax){ xmax = contours1[i][j].x; xymax = contours1[i][j].y; } if(contours1[i][j].y > ymax){ ymax = contours1[i][j].y; yxmax = contours1[i][j].x; } } } Unfortunately my code can only find the biggest coordinate of all vectors. A: struct myclass { bool operator() (cv::Point pt1, cv::Point pt2) { return (pt1.y < pt2.y); } } myobject; sort(pnt.begin(), pnt.end(), myobject); use this simple code and replace pnt to your vector name and you can find max/min value in vector vecotr[0] have mix value and vector[last] have max value
{ "language": "en", "url": "https://stackoverflow.com/questions/45622203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: socket.io multiplayer game player's view I'm very new to nodejs and socket.io. I'm trying to create a simple multiplayer card game in real time. my problem right now is I can't get the player's view to display on the correct div from player's perspective. example is.. I want my playing area to display at the bottom box and my opponent to display on top box and same goes with my opponent's viewer. he will see himself on the bottom div and sees me on the top div. How do u get that effect to work? client <div class='top'></div> <div class='bottom></div> <script> var socket = io(); socket.on('playerinfo', function(data){ $('.top').html(data[0]); $('.bottom')html(data[1]); }); </script> server var players = []; io.on('connection', function(socket){ //player is given 'P' with random number when connection is made to represent username socket.name = "P" + Math.floor(Math.random() * (20000)); players.push(socket.name); io.emit('playerinfo', players); } Also it would be great if you can point me to a tutorial or blog related to this. thank you. A: You are differentiating the self and other user by some uniqueness right, say for example uniqueness is user email or user id. Solution 1: On making socket connection, send the user id/email also and you can store that as part of socket object itself. So that when ever player1 did some move, on emit send the id also along with whatever data you are sending. Solution 2: When player1 did some move, you will send data to server, while sending the data, send the user id/email also. And in server again emit along with user id. In client you can check - if id is self, then update at bottom. If id is not self then update the top. Note: If you have multiple opponent player, still you can handle with this. EXAMPLE: In client: <script> var socket = io(); var selfId; socket.on('playerinfo', function(data){ selfId = data.name; playerInfo = data.players; $('.top').html(playerInfo); $('.bottom')html(selfId); }); socket.on('move', function(data){ if(data.uid == selfId) { $('.top').html(data.card); } else { $('.bottom')html(data.card); } }); socket.emit('move', {card:A, uid:56836480193347838764}); </script> In server: var players = []; io.on('connection', function(socket){ //player is given 'P' with random number when connection is made to represent username socket.name = "P" + Math.floor(Math.random() * (20000)); // Here may be you can assign the position also where the user is sitting along with the user name. //players will be an array of object which holds username and their position //So that in client you can decide where the user will sit. players.push(socket.name); io.emit('playerinfo', {'players':players, 'name':socket.name); socket.on('move', function (data) { socket.emit('move', data); }); } A: Take a look into this 7 part tutorial. I think it gives you a good picture about what needs to be done in a typical multiplayer game by Socketio: http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-1/ http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-2/ http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-3/ http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-4/ http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-5/ http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-6/ http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-7 A: You need to give each client some kind of id, and tell each client when they connect, what their id is. When a client connects, generate a random unique id for them, and then send this back to them so they know their id. When you send back the data of other players, the client can figure out which data is theirs based on the id and display it in the right area.
{ "language": "en", "url": "https://stackoverflow.com/questions/38493574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Typescript CRA Jest import TypeErrors - undefined imports? I'm experiencing a set of errors in my React project: TypeError: (0 , date_1.formatDate) is not a function 13 | 14 | const DATE = new Date(); > 15 | const DATE_VIEW = formatDate( | ^ ... at Object.<anonymous> (src/common/constants/date.ts:5:45) at Object.<anonymous> (src/common/utils/date.ts:3:1) at Object.<anonymous> (src/store/tables/actions.ts:1:1) at Object.<anonymous> (src/store/tables/index.ts:1:1) at Object.<anonymous> (src/common/utils/orders.ts:2:1) at Object.<anonymous> (src/pages/MainPage/convertValue.ts:2:1) at Object.<anonymous> (src/pages/MainPage/convertValue.test.ts:2:1) Test suite failed to run TypeError: Cannot read properties of undefined (reading 'default') at Object.TEXTS (src/common/texts/index.ts:35:32) at Object.<anonymous> (src/api/ordersService.ts:140:5) at Object.<anonymous> (src/api/api.ts:4:1) at Object.<anonymous> (src/store/allTables/thunkActions.ts:8:1) at Object.<anonymous> (src/store/allTables/index.ts:5:1) at Object.<anonymous> (src/store/utils.ts:43:1) at Object.<anonymous> (src/store/tables/actions.ts:1:1) at Object.<anonymous> (src/store/tables/index.ts:1:1) at Object.<anonymous> (src/common/utils/orders.ts:2:1) at Object.<anonymous> (src/common/utils/date.ts:21:1) at Object.<anonymous> (src/common/texts/index.ts:12:1) at Object.<anonymous> (src/pages/MainPage/getWidgetText.ts:1:1) at Object.<anonymous> (src/pages/MainPage/getWidgetText.test.ts:3:1) FAIL src/store/utils.test.ts ● Test suite failed to run TypeError: _ordersService.default is not a constructor 33 | public client = new ClientService(); 34 | public widget = new Widget(); > 35 | public orders = new OrdersService(); | ^ ... at new ApiService (src/api/api.ts:15:19) at Object.<anonymous> (src/api/api.ts:25:16) at Object.<anonymous> (src/store/tables/thunkActions.ts:3:1) at Object.<anonymous> (src/store/tables/index.ts:2:1) at Object.<anonymous> (src/common/utils/orders.ts:2:1) at Object.<anonymous> (src/api/ordersService.ts:5:1) at Object.<anonymous> (src/store/utils.ts:5:1) at Object.<anonymous> (src/store/utils.test.ts:1:1) that seem to have the same reason. The errors occure occasionally not depending on the tests modifications. The imports (named/default) are implemented properly - the app works well. The aliases are handled in jest.config.ts moduleDirectories: ['node_modules', 'src'],, relative importing doesn't help. After many modifications and runs of CRA (5.0.1) react-scripts test, installed Jest 29.1.2 with ts-jest upon with the whole setup - running directly is the same story. Failing tests don't even run, others run and succeed. At some points of the history they all succeed. I've seen some similar issues on Stackoverflow where updating Jest to newer versions helps, but neither different Jest versions, nor synchronising it's version with additional packages (like @types/jest) versions helps me. What are possible reasons? Thanks. A: I've also run into this issue in one of my CDK projects. The problem I discovered was that I had compiled .js files alongside my .ts files in my working directory. The relative imports selected the stale .js files instead of compiling the .ts files as another es module. These .js files were generated after running cdk deploy locally. Solution: delete any .js files alongside your .ts files. I hope this helps someone else in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/74011131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to play a animation on scrolling down and rewind on scrolling up I am trying to play an MP4 video while scrolling down and then rewind it while scrolling up. I currently have the video (of an animation) working with HTML CSS and JS. Any help would be appreciated thank you. A: I have made a small example to display with an image. like when you scroll down some animation will be shown and once you scroll back to up animation will be revert. CSS STYLE: .classname { -webkit-animation-name: cssAnimation; -webkit-animation-duration: 3s; -webkit-animation-iteration-count: 1; -webkit-animation-timing-function: ease; -webkit-animation-fill-mode: backwards; } .classname1 { -webkit-animation-name: cssAnimation1; -webkit-animation-duration: 3s; -webkit-animation-iteration-count: 1; -webkit-animation-timing-function: ease; -webkit-animation-fill-mode: forwards; } @-webkit-keyframes cssAnimation1 { from { -webkit-transform: rotate(1deg) scale(1) skew(0deg) translate(20px); } to { -webkit-transform: rotate(1deg) scale(1) skew(0deg) translate(20px); } } @-webkit-keyframes cssAnimation { from { -webkit-transform: rotate(0deg) scale(2) skew(0deg) translate(100px); } to { -webkit-transform: rotate(0deg) scale(2) skew(0deg) translate(100px); } } **JAVASCRIPT PART** var lastScrollTop = 0; document.addEventListener("scroll", function(){ var value = window.pageYOffset || document.documentElement.scrollTop; if (value > lastScrollTop){ scrollDownAnnimation(); } else { scrollUpAnnimation(); } lastScrollTop = value <= 0 ? 0 : st; }); function scrollDownAnnimation() { document.getElementById('img').className = 'classname'; } function scrollUpAnnimation() { document.getElementById('img').className = 'classname1'; } **HTML PART: Please make sure you have added page content so that scroll can come on page** <div> <img id="img" src="https://i.stack.imgur.com/vghKS.png" width="328" height="328" /> </div> For Demo: DEMO Hope this help, Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/73007720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: PHPStan inheritance & property types I have trouble passing PHPStan tests because of parent/child classes (besides, code runs well). These two kind of errors always show up: * *Parameter #1 $a of method xxx expects ConcreteChildClass, AbstractParentClass given *Property ClassName::$a (ConcreteChildClass) does not accept AbstractParentClass Here is the code (must be compatible with PHP 5.6): <?php abstract class AbstractClassA { /** * @return static */ abstract public function postProcess(); } class ConcreteClassA extends AbstractClassA { /** * @return ConcreteClassA */ public function postProcess() { return $this; } } abstract class AbstractClassB { /** * @return AbstractClassA */ abstract public function deserialize(); /** * @return AbstractClassA */ public function someMethodA($params) { return $this->someMethodB(); } /** * @return AbstractClassA */ public function someMethodB() { $object = $this->deserialize(); return $object->postProcess(); } } class ConcreteClassB extends AbstractClassB { /** * @return ConcreteClassA */ public function deserialize() { $object = new ConcreteClassA(); // some assignements return $object; } } And how this code is used: class SomeClass { /** @var ConcreteClassA $propertyA */ public $propertyA; /** @var ConcreteClassB $propertyB */ public $propertyB; public function someMethod() { $this->propertyA = $this->propertyB->someMethodA($params); $this->someProperty->someOtherMethod($this->propertyA); // again, someOtherMethod expects ConcreteClassA but AbstractClassA given... } I tried to "play" with @template without success... Please also note that I have limited control over abstract classes. Thanks,
{ "language": "en", "url": "https://stackoverflow.com/questions/72971016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IOS Segue- detecting table cell and opening a viewController i am new to ios programming. i have a static tableViewController in which i have 3 cells. i have another view controller where there is a label and description. what i am trying to do is detect the cell which user clicks and then change the label which is in my second view controller according to that but the problem is whenever i click the cell the program crashes and added the breakpoint here is my code - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { NSString *name; NSString *description; if([[segue identifier] isEqualToString:@"PushAppDetailsFromCell1"] ) { name = @"Label 1 "; description = @"Long description of Label 1..."; } else if([[segue identifier] isEqualToString:@"PushAppDetailsFromCell2"] ) { name = @"Label 2"; description = @"Long description of Label 2..."; } else if([[segue identifier] isEqualToString:@"PushAppDetailsFromCell3"] ) { name = @"Label 3"; description = @"Long description of Label 3..."; } else { return; } AppDetailsViewController *apDetailsViewController = segue.destinationViewController; //here i am getting the breakpoint apDetailsViewController.appDetails = [[AppDetails alloc] initWithName:name description:description]; } AppDetails.m -(id)initWithName:(NSString *)name description:(NSString *)descr{ self = [super init]; if(self){ self.name = name; self.description = descr; } return self; } AppDetailsViewController.m - (void)viewDidLoad { [super viewDidLoad]; self.nameLabel.text = self.appDetails.name; self.descriptionLabel.text = self.appDetails.description; } A: Steps to figure out the problem 1) Put a break point in prepareForSegue 2) Try to see it displays correct segue id as it should be(there might be making spelling mistake). 3) see where it's crashing in - In prepareForSegue? - Is this calling initname()? - has it started it viewDidLoad(). If you do this mostly you will figure out what the problem is. If you can not then let me know. A: Bind segue from UIViewController to UIViewController rather then cell to UIViewController. Implement following code for navigation. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { NSLog(@"%ld",aIntSelected); NSLog(@"%@",segue.destinationViewController); } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { aIntSelected=indexPath.row; NSLog(@"didSelectRowAtIndexPath called"); [self performSegueWithIdentifier:@"pushSecond" sender:self]; } A: NSArray *names = @[@"Label 1", @"Label2", @"Label 3"]; NSArray *descs = @[@"Description 1", @"Description", @"Description 3"]; - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"PushAppDetailsSegue"]) { NSIndexPath *indexPath = [self.yourTableView indexPathForSelectedRow]; AppDetailsViewController *controller = segue.destinationViewController; controller.appDetails = [[AppDetails alloc] initWithName:names[indexPath.row] description:descs[indexPath.row]]; } } Drag a segue from your ViewController to SecondViewController and name it "PushAppDetailsSegue".
{ "language": "en", "url": "https://stackoverflow.com/questions/20881479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to know which view has current focus I am putting focus on a view but when I change orientation the focus is lost from that view . does onConfigurationChanged() handles focus? or i need to explicitly set it and if yes then how can I set focus ? I need to keep track of current focusing view .how to do that? A: Override the onSaveInstanceState and onRestoreInstanceState methods in your Activity. You can then keep track of whatever view has focus by grabbing the ID of the view and saving it to the Bundle in the onSaveInstanceState method. Then in the onRestoreInstanceState method, you just grab the ID and find the view with that ID. You don't even need to cast it or anything. You then just request focus for that view. It will look like this: @Override protected void onSaveInstanceState(Bundle outState) { int viewId = this.getCurrentFocus().getId(); outState.putInt("hasFocus", viewId); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); int viewId = savedInstanceState.getInt("hasFocus"); View view = findViewById(viewId); view.requestFocus(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7858760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get a fixed size SIFT feature vector? I am trying to obtain feature vectors for N =~ 1300 images in my data set, one of the features I have to implement is shape. So I plan to use SIFT descriptors. However, each image returns different number of keypoints, so I run [F,D] = vl_sift(image); F is of size 4 x N and D is of size 128 x N where N is the number of keypoints detected. However, I want to obtain a single vector of size 128 x 1 that can represent an image as good as possible. I have seen things like clustering and k-means, but I don't have any idea how to do them. The most basic idea is to get the average of these N vectors of size 128x1, then I have a feature vector. But is taking the average meaningful? Should I do some kind of histogram? Any help will be appreciated. Thanks ! A: This is actually a big research problem. You are correct, averaging all the descriptors will not be meaningful. There are several approaches out there for creating a single vector out of a set of local descriptors. One big class of methods is called "bag of features" or "bag of visual words". The general idea is to cluster local descriptors (e. g. sift) from many images (e. g. using k-means). Then you take a particular image, figure out which cluster each descriptor from that image belongs to, and create a histogram. There are different ways of doing the clustering and different ways of creating and normalizing the histogram. A somewhat different approach is called "Pyramid Match Kernel", which is a way of training an SVM classifier on sets of local descriptors. So for starters google "bag of features" or "bag of visual words".
{ "language": "en", "url": "https://stackoverflow.com/questions/23159828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How bad is *RECURSION*? I want to create an App object which contains objects for my database, sanitizer, and user. This way, I can simply use a single App object rather than seperately called all of these different objects, as most of my other objects will require most if not all of these objects for the methods within them. The User object will have CRUD methods in the future so that its properties can be changed, therefore, I do not want a separate object from the one which contains the CRUD methods and the one which handles user authentication, signout, etc. The reason being is that I don't want to have the exact same object properties in two separate classes for what is technically the exact same object. That said, how bad is this recursive occurrence (see how the App object is utilized in the User class)? Should I bother taking measures to code this differently? Is this a big deal? Keep in mind that this User class will be called for CRUD methods, so the user which is signed in will be able to change any other user via this object by simply using a different variable name and instantiating a new instance of it. class App { public $db; public $sanitizer; public $user; public $settings; function __construct () { // create $app->db object $db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $this->db = $db; // create $app->sanitizer object $this->sanitizer = new Sanitizer(); // set $app->settings $this->setSettings(); // create $app->user object $this->user = new User($this); // NOTE THE RECURSION HERE $this->user->setIsSignedIn(); if ($this->user->is_signed_in) { $this->user->populateById(); } } function setSettings () { $sql = 'select * from `settings`'; $stm = $this->db->prepare($sql); $stm->execute(); $res = $stm->fetchAll(); if ($res) { $res = $this->sanitizer->action('sanitize', $res); foreach ($res as $r) { $this->settings[$r['key']] = $r['value']; } } } } class User { public $app; public $id; public $username; public $password; public $token; public $is_signed_in = false; function __construct ($app) { $this->app = $app; // AGAIN, *RECURSION* } function populateByPost () { foreach ($_POST as $k => $v) { if (property_exists($this, $k)) { $this->$k = $v; } } } function populateById () { $sql = 'select * from `users` where `id`=:id'; $stm = $this->app->db->prepare($sql); $stm->bindParam(':id', $this->id); $stm->execute(); $res = $stm->fetch(); if ($res) { $res = $this->app->sanitizer->action('sanitize', $res); foreach ($res as $k => $v) { $this->$k = $v; } } } function credentialsValid () { $sql = 'select * from `users` where `username`=:username'; $stm = $this->app->db->prepare($sql); $stm->bindParam(':username', $this->username); $stm->execute(); $res = $stm->fetch(); if ($res) { if (password_verify($this->password, $res['password'])) { $this->id = $res['id']; return true; } } return false; } function createToken () { $this->token = password_hash($this->id.'|'.$this->username.'|'.$this->password, PASSWORD_DEFAULT); $sql = 'insert into `user_tokens` (`id_user`, `token`) values (:id_user, :token)'; $stm = $this->app->db->prepare($sql); $stm->bindParam(':id_user', $this->id); $stm->bindParam(':token', $this->token); $stm->execute(); } function setSessionVars () { $_SESSION['id_user'] = $this->id; $_SESSION['token'] = $this->token; if (isset($_POST['remember_me'])) { setcookie('id_user', $this->id, time() + 31556926, '/'); setcookie('token', $this->token, time() + 31556926, '/'); } } function setIsSignedIn () { if (isset($_COOKIE['id_user'])) { $id_user = $_COOKIE['id_user']; $token = $_COOKIE['token']; } else if (isset($_SESSION['id_user'])) { $id_user = $_SESSION['id_user']; $token = $_SESSION['token']; } if (isset($id_user)) { $sql = 'select * from `user_tokens` where `id_user`=:id_user and `token`=:token'; $stm = $this->app->db->prepare($sql); $stm->bindParam(':id_user', $id_user); $stm->bindParam(':token', $token); $stm->execute(); $res = $stm->fetch(); if ($res) { $this->id = $res['id_user']; $this->is_signed_in = true; } } } function signOut () { $_SESSION['id_user'] = ''; $_SESSION['token'] = ''; session_destroy(); if (isset($_COOKIE['id_user'])) { setcookie('id_user', '', time() - 1, '/'); setcookie('token', '', time() - 1, '/'); } } // CRUD METHODS TO BE ADDED HERE LATER } Obviously when I print_r the App object it tells me there is a recursion within the App->user object due to the code in the App construct. Again, I am only curious if this is a really bad thing that I should absolutely recode. Any insight would be greatly appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/34149444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Capturing URL params in Django Rest I need to capture the url params in the following url "/portal/{pk}/portalProject/{pk}" the following url is not leading to the view function below . What is wrong here? urls.py router = routers.DefaultRouter() router.register(r'movies', MoviesViewSet) router.register(r'project', ClientViewSet) router.register(r'portal', PortalViewSet) router.register(r'portal/(?P<portal_pk>\d+)/portalProject/(?P<portalProject_pk>\d+)/$', PortalViewSet, 'portalProject') router.register(r'portalProject', PortalProjectViewSet) views.py class PortalViewSet(viewsets.ModelViewSet): ... @detail_route(methods=['post','get']) def portalProject(self, request, pk=None): print "in here" if request.method == 'post': #some code serializer = PortalProjectSerializer(data=request.data) if serializer.is_valid(): print "valid" serializer.save() return Response(status=status.HTTP_200_OK) else: print serializer.errors return Response(status=status.HTTP_400_BAD_REQUEST) else: #some code return Response(status=status.HTTP_200_OK) ... A: You don't actually declare a specific route in DefaultRouter. The router takes care of creating all sub urls for you. Just doing router.register(r'portal', PortalViewSet) will give you: * *[.format] *{prefix}/[.format] *{prefix}/{methodname}/[.format] - @list_route decorated method *{prefix}/{lookup}/[.format] *{prefix}/{lookup}/{methodname}/[.format] - @detail_route decorated method So unless you want to create a custom router, you're gonna have to change your url pattern to something like /portal/{pk}/portalProject/?id={pk} Also, if you're requesting the portalProject by pk anyway, then there is no need for nesting the url under /portal/{pk}. The pk of portalProject is already specific enough. You already have a route for portalProject, so you would effectively be getting two ways of accessing the same data, one of them being more complicated for no good reason. However, I believe this is what you're looking for: https://github.com/alanjds/drf-nested-routers or https://chibisov.github.io/drf-extensions/docs/#nested-routes
{ "language": "en", "url": "https://stackoverflow.com/questions/34985407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails Modify Request Route As luck would have it, I am creating a Rails application (2.3.8) in which I need to change where a request is dispatched based on some criteria. Basically, I need a custom dispatcher. I have looked at using Rack to modify the request, and in certain instances, re-route the request to a different controller that knows that to do with the request. I'm not looking to redirect - I need to have some requests handled by a different controller than the one the routing table gives me. Is this even possible? A: I think Rack is the answer to this. You should be able to intercept the request and alter the incoming parameters before the request hits your Rails stack. Why not change the route to use the correct controller in the first place?
{ "language": "en", "url": "https://stackoverflow.com/questions/3597700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaFX: Blank rows in FXML TableView I've been trying to add a row of information from my Product class to this tableView: When I hit the add button and run: productTableView.getItems().add(new Product(...) It adds a blank row to my table: Controller.java import javafx.scene.control.TableView; public class Controller { // Initialized all elements of GUI public TableView<Product> productTableView; public TableColumn<Product, Integer> productID; public TableColumn<Product, String> name; public TableColumn<Product, Double> price; public TableColumn<Product, Integer> quantity; public TableColumn<Product, Double> cost; public TableColumn<Product, Date> bought; public TableColumn<Product, Date> sold; public TableColumn<Product, Integer> threshold; public void addProduct() { productTableView.getItems().add(new Product( 1, "Toilet Paper", 9.99, 1.25, 300, 300, new Date(), new Date()) ); } Inventory_Management.fxml <?xml version="1.0" encoding="UTF-8"?> <?import javafx.geometry.Insets?> <?import javafx.scene.control.Button?> <?import javafx.scene.control.TableColumn?> <?import javafx.scene.control.TableView?> <?import javafx.scene.layout.HBox?> <?import javafx.scene.layout.VBox?> <?import javafx.scene.control.cell.PropertyValueFactory?> <VBox alignment="TOP_RIGHT" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" spacing="10.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Inventory_Management.Controller"> <children> <TableView fx:id="productTableView" VBox.vgrow="ALWAYS"> <columns> <TableColumn fx:id="productID" prefWidth="75.0" text="Product ID"> <cellValueFactory> <PropertyValueFactory property="productID" /> </cellValueFactory> </TableColumn> <TableColumn fx:id="name" prefWidth="75.0" text="Name"> <cellValueFactory> <PropertyValueFactory property="name" /> </cellValueFactory> </TableColumn> <TableColumn fx:id="price" prefWidth="75.0" text="Price"> <cellValueFactory> <PropertyValueFactory property="price" /> </cellValueFactory> </TableColumn> <TableColumn fx:id="quantity" prefWidth="75.0" text="Quantity"> <cellValueFactory> <PropertyValueFactory property="quantity" /> </cellValueFactory> </TableColumn> <TableColumn fx:id="cost" prefWidth="75.0" text="Cost"> <cellValueFactory> <PropertyValueFactory property="cost" /> </cellValueFactory> </TableColumn> <TableColumn fx:id="bought" prefWidth="75.0" text="Bought"> <cellValueFactory> <PropertyValueFactory property="bought" /> </cellValueFactory> </TableColumn> <TableColumn fx:id="sold" prefWidth="75.0" text="Sold"> <cellValueFactory> <PropertyValueFactory property="sold" /> </cellValueFactory> </TableColumn> <TableColumn fx:id="threshold" prefWidth="75.0" text="Threshold"> <cellValueFactory> <PropertyValueFactory property="threshold" /> </cellValueFactory> </TableColumn> </columns> <columnResizePolicy> <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" /> </columnResizePolicy> </TableView> </children> <padding> <Insets bottom="30.0" left="30.0" right="30.0" top="30.0" /> </padding> </VBox> I built the FXML using Scene Builder. I'm not sure how to implement the rows without creating the table programmatically. The data I input should be appearing in the table, but I'm not sure if its because of the way I'm implementing the row, or if there is something off with my PropertyValues. A: The issue was that in my Product class, I did not have the appropriate getters and setters. My getters in this case were case sensitive. Example of "bad code": public class Product { private int productID; public int getID() { return productID; } } Example of working code: public int getProductID() { return productID; } A small difference, but important.
{ "language": "en", "url": "https://stackoverflow.com/questions/55269899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: how to find available functions/properties of a dll I want to use functions/properties from 2-3 dlls. I could not find relevant details on the software because of which they get installed. Could you please let me know how can i find these details? I am using Excel VBA to use these dlls. A: If you're adding a reference to a DLL into your VBA project, you can use 'Object Browser' (F2), select the DLL you added and the methods / classes / properties will be shown. With luck, your DLLs will be well documented - and easy to use. Rgds A: I assume those are COM DLLs. In that case what you need is OLE-COM Object Viewer, available as part of whatever is the latest Windows SDK.
{ "language": "en", "url": "https://stackoverflow.com/questions/4933484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: trying to centre a div within in a div I am trying to centre a div but having difficulty. Beneath the chart in my fiddle I have a table which I want to centre under the chart. I have tried the class below, I also set the width but it doesn't seem to work. It looks to me like the right hand side of the table is centred to the middle of the chart rather than the middle of the chart. I am not fully understanding the behaviour. html <div id="IndexArea" class="content"> <div id="redraw" style="float:left"> <button class="ui-button ui-widget ui-corner-all">Paint</button> </div> <div id="range-butts-index" style="float:right"> <button class="ui-button ui-widget ui-corner-all" data-range="5">5d</button> <button class="ui-button ui-widget ui-corner-all" data-range="20">MTD</button> <button class="ui-button ui-widget ui-corner-all" data-range="999">Max</button> </div> <div id="chartIndexPerf" class="indexChart"></div> <div id="tableIndexPerf" class="centerDiv"></div> css .indexChart{ clear: both; height: 500px; } .centerDiv{ margin: auto; } .content { height: 1000px; background-color: #F5CF8E; overflow: hidden; }
{ "language": "en", "url": "https://stackoverflow.com/questions/51501857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android studio error: java version not found In Android Studio I got the following error Gradle snyc failed Error: no java version found. I tried removing / renaming gradle but all in vain. I am using linux mint cinnamon. Can anyone help? A: Go to CMD and check whether Java is installed, just type java in cmd and press enter. If java is installed it will display options etc. If you have installed java and its not displaying even when you type this command it means java path needs to be added to the Environment variables. to do this Select Start -> Computer -> System Properties -> Advanced system settings -> Environment Variables -> System variables -> PATH. Prepend C:\Program Files\Java\jdk.x.x.x\bin; to the beginning of the PATH variable. x.x.x is the version example jdk.6.0.27 Press OK to everything.
{ "language": "en", "url": "https://stackoverflow.com/questions/32541696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails - How to avoid repeating same i18n attributes translations I am building a Rails application using I18n translations. I have two models (Blog and Event), sharing same attributes (title, content). In my I18n yml files, how can I avoid repeating same keys for each attributes models and share them ? Extract of my actual code: fr: activerecord: attributes: blog: title: Titre content: Contenu event: title: Titre content: Contenu I also tried to set attributes as default, removing wrapped model key without any luck. fr: activerecord: attributes: title: Titre content: Contenu Thanks for your help ! My project: * *Rails 4.2.7.1 *Ruby 2.3.0 A: Similar kind of question is answered here You can achieve it using yaml aliases fr: activerecord: attributes: blog: &title_content title: Titre content: Contenu event: *title_content Refer yaml aliases for more info.
{ "language": "en", "url": "https://stackoverflow.com/questions/40088600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passing in results of a query to a CLR SqlFunction I have a stored procedure that needs to pass a result set from another stored procedure into a UDF, that in turn calls a CLR SqlFunction. What I can't figure out how to do is how to pass the result set into my CLR SqlFunction. I don't see a table SqlType nor can I find any examples online, maybe I am searching incorrectly? Also if you look at the last parameters passed in, that is where I am having problems. Don't know how to pass in the result set. Thanks! <SqlFunction(DataAccess:=DataAccessKind.Read, SystemDataAccess:=SystemDataAccessKind.Read)> _ Public Function GetMatchedConstituents(ByVal ID As SqlGuid, ByVal CustomID As SqlString, ByVal KeyName As SqlString, ByVal FirstName As SqlString, ByVal MiddleName As SqlString, ByVal AddressBlock_Home As SqlString, ByVal AddressBlock_Business As SqlString, ByVal PostCode_Home As SqlString, ByVal PostCode_Business As SqlString, ByVal Phone_Home As SqlString, ByVal Phone_Business As SqlString, ByVal ResultSet As [WhatType? There isnt a SqlTable like I assumed]) As IEnumerable 'do duplicate comparing logic here End Function A: See this question Pass table as parameter to SQLCLR TV-UDF which has links to other related information. In short, TVP is not currently supported in SQL CLR. If the result set is small enough you could convert it to an XML type and pass that as a parameter to your SQL CLR function (SqlXml). You could also have the stored procedures set up temporary tables to share. It's sloppy, but may end up being your only option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7040715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NgIf and click on same button on dialog I want make a form with error message if the name already exist or group not exist. I have the error message from the server when I click on submit . Now I close the dialog box with the on Close Confirm function. <button mat-raised-button class="createUserBtn" color="primary" type="submit" [disabled]="form.invalid" (click)="onCloseConfirm()">Save</button> But now I have to click on save button , wait for the error message or not If message , display it and let the dialog open. If no error message , execute the function on Close Confirm. the problem I think I have , is async wait , I wait for server answer to check error or not and after close or not the dialog. this is my function Submit error = false; errorMessage = ''; onSubmit() { if (this.form.valid) { this.fixtureService.create(this.form.value) .catch(error => { console.log(error); if (error.error.error ==='FIXTURE_NAME_TAKEN') { console.warn("Fixture name already exist"); this.error = true; this.errorMessage = 'Fixture name already exist' } else if (error.error.error ==='GROUP_NOT_FOUND') { console.warn("Group selected doesn't exist"); this.error = true; this.errorMessage = 'Group selected doesn\'t exist' } else onCloseConfirm(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/58210894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Render a Wordpress page as a variable Is it possible to get Wordpress to render a page and return it as HTML ? I'm thinking about a function that'd look like this : $html = render_page($id); echo $html; // prints the page My goal is to have all my sections' HTML and my corresponding logic in different files and, in my home page file, merge all the different sections in the order I wish. Thus making a one-page kind of website. Because you define a template for a page, I don't see why it's doesn't seem to be possible to do this. A: I have finally found a workaround for doing exactly what I wanted : * *I have all my different "pages" (they are Wordpress pages, but I use them as different sections on a one-page site) in different files. *Each file has it's own HTML and corresponding logic. *In my index.php file, I call my files this way : require_once(locate_template('tpl-name.php')); I'm pretty sure it's not exactly the best way of doing it, but it works for me. Wish Wordpress would allow API access to it's rendering though.
{ "language": "en", "url": "https://stackoverflow.com/questions/28032289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Are there easy ways to sort mongodb collection by reference document in mongoose I'm struggling with handling mongodb in nodejs. Are there any easy ways to sort mongodb collection by reference document in mongoose? When I need to sort mongodb documents by reference document, it is not easy. Querying all documents and sort or using mongodb aggregation is complex. When it is changing sorting field, I should rewrite all query. Let me know easy ways to do that. A: Refer to Mongoose documentation for providing options to populate field. In the options, you can pass a sort by fieldname.
{ "language": "en", "url": "https://stackoverflow.com/questions/50621270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: I am stuck with regexp only returning the match while I want to get the followup followed by the match TCL/TK: Problem: I want to be able to get the post-match string data, but even though I provide regexp with more than a variable for the match itself the secutive variables either turn out empty, or I got the same value from the first two. E.g: set args "!do dance" regsub -all {(!do)} $args prefix command puts $prefis "!do" puts $command "!do" What to do? Ty EDIT I found the solution thanks to inspiration by your answer, here's a snippet if { [ regsub {(!do\s+)} $args "" match ] >= 1 } { if { $match == "{help}" } A: Assuming you want to remove the "!do" then you can do the following: set args "!do dance" regsub -all {(!do)} $args "" output puts $output A: I'm not sure why you're using regexp here, and it seems like you're using eggdrop or something. You can easily use: set prefix [lindex $args 0] set command [lindex $args 1] Though you should be careful with $args. It's usually used in procs to mean all the other arguments passed on to the proc aside from the already defined arguments. % puts $prefix !do % puts $command dance
{ "language": "en", "url": "https://stackoverflow.com/questions/19258670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: i updated my project from dotnet 2.1 to 6 and some base repository function return 500 error in debugger im trying to do sothing like this but need help with how upgrate my project from dotnet 2.1 to 6 my base function now return 500 using vscode i need to check if IsActive property is exist in that model from base repo that im using generic model public virtual async Task<IEnumerable<TPickerDto>> GetForPickerAsync([Optional] List<string> fieldsForInclude, [Optional] Dictionary<string, ItemsPermissions> permissions) { IQueryable<TModel> listFromDb = this._context.Set<TModel>() .Where(r => (r.GetType().GetProperty("IsActive") != null && r.GetType().GetProperty("IsActive").GetValue(r) != null && (bool)r.GetType().GetProperty("IsActive").GetValue(r) == true) || (r.GetType().GetProperty("IsActive") == null) || (r.GetType().GetProperty("IsActive").GetValue(r) == null)); if (permissions != null) { if (permissions.ContainsKey("allowedUnits") && permissions.ContainsKey("allowedSites")) { if (permissions.GetValueOrDefault("allowedUnits").All && !permissions.GetValueOrDefault("allowedSites").All) { listFromDb = listFromDb.Where(r => r.GetType().GetProperty("SiteId").GetValue(r) == null || permissions.GetValueOrDefault("allowedSites").Indexes.Contains((int)r.GetType().GetProperty("SiteId").GetValue(r))); } else { if (!permissions.GetValueOrDefault("allowedUnits").All && permissions.GetValueOrDefault("allowedSites").All) { listFromDb = listFromDb.Where(r => r.GetType().GetProperty("UnitId").GetValue(r) == null || permissions.GetValueOrDefault("allowedUnits").Indexes.Contains((int)r.GetType().GetProperty("UnitId").GetValue(r))); } else { if (!permissions.GetValueOrDefault("allowedUnits").All && !permissions.GetValueOrDefault("allowedSites").All) { listFromDb = listFromDb.Where(r => (r.GetType().GetProperty("UnitId").GetValue(r) == null || permissions.GetValueOrDefault("allowedUnits").Indexes.Contains((int)r.GetType().GetProperty("UnitId").GetValue(r))) && (r.GetType().GetProperty("SiteId").GetValue(r) == null || permissions.GetValueOrDefault("allowedSites").Indexes.Contains((int)r.GetType().GetProperty("SiteId").GetValue(r)))); } } } } else { if (permissions.ContainsKey("allowedUnits")) { listFromDb = listFromDb .Where(r => permissions.GetValueOrDefault("allowedUnits").All || r.GetType().GetProperty("UnitId").GetValue(r) == null || permissions.GetValueOrDefault("allowedUnits").Indexes.Contains((int)r.GetType().GetProperty("UnitId").GetValue(r))); } if (permissions.ContainsKey("allowedSites")) { listFromDb = listFromDb .Where(r => permissions.GetValueOrDefault("allowedSites").All || r.GetType().GetProperty("SiteId").GetValue(r) == null || permissions.GetValueOrDefault("allowedSites").Indexes.Contains((int)r.GetType().GetProperty("SiteId").GetValue(r))); } } } // Import all the navigation properties if (fieldsForInclude != null) { listFromDb = _JoinNavigationProperties(listFromDb, fieldsForInclude); } IEnumerable<TPickerDto> mappingList = _mapper.Map<IEnumerable<TPickerDto>>(listFromDb); return mappingList; } A: Starting from dotnet core 3, Ef will throw an exception if a Linq query couldn't be translated to SQL and results in Client-side evaluation. In earlier versions you would just receive a warning. You will need to improve your Linq query so that it can be evaluated on client side. Refer to this link for details, https://learn.microsoft.com/en-us/ef/core/querying/client-eval You are using reflection to do the query, why not use the property directly? If your boolean can be be NULL then declare the type as bool? IsActive. That way you can check for null in the where, this._context.Set<TModel>().Where(r => (r.IsActive==true)) In case you are trying to create a repository then try declaring an interface that has IsActive as a field. interface ISoftDeleteTarget { public IsActive{get;} }
{ "language": "en", "url": "https://stackoverflow.com/questions/75082403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to start, stop and reset the chronometer in android? How to set start , stop , reset in chronometer ? I'm implementing chronometer in my app. I created three buttons start, stop , reset.. start : starts timer from the 00:00. stop: completely stops timer showing the time runned. reset: resets the timer to 00:00. i'm trying to do this but my code behaves weird. public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void startButton(View view) { ((Chronometer) findViewById(R.id.chronometer)).start(); } public void stopButton(View view) { ((Chronometer) findViewById(R.id.chronometer)).stop(); } public void resetButton(View view) { ((Chronometer) findViewById(R.id.chronometer)).setBase(SystemClock.elapsedRealtime()); }} how can i solve this problem? i just want to implement a start button(starts form 00:00) , stop button(stops the timer and shows runned time) and a reset button(which completely resets the timer to 00:00). A: try this import android.os.Bundle; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Chronometer; public class MainActivity extends AppCompatActivity { Chronometer simpleChronometer; Button start, stop, restart, setFormat, clearFormat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initiate views simpleChronometer = (Chronometer) findViewById(R.id.simpleChronometer); start = (Button) findViewById(R.id.startButton); stop = (Button) findViewById(R.id.stopButton); restart = (Button) findViewById(R.id.restartButton); setFormat = (Button) findViewById(R.id.setFormat); clearFormat = (Button) findViewById(R.id.clearFormat); // perform click event on start button to start a chronometer start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub simpleChronometer.start(); } }); // perform click event on stop button to stop the chronometer stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub simpleChronometer.stop(); } }); // perform click event on restart button to set the base time on chronometer restart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub simpleChronometer.setBase(SystemClock.elapsedRealtime()); } }); // perform click event on set Format button to set the format of chronometer setFormat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub simpleChronometer.setFormat("Time (%s)"); } }); // perform click event on clear button to clear the current format of chronmeter as you set through set format clearFormat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub simpleChronometer.setFormat(null); } }); } } A: I know it may be the little late, this can help someone later on stop = (Button) findViewById(R.id.stopButton); chronometer = findViewById(R.id.chronometerID); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { chronometer.stop(); chronometer.setBase(SystemClock.elapsedRealtime()); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/54677595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C/C++, NTFS. Multiple reparse points MSDN says "There is a limit of 31 reparse points on any given path." (http://msdn.microsoft.com/en-us/library/windows/desktop/aa365503%28v=vs.85%29.aspx) So, a single file can have max. 31 reparse points (?) To check if a file has "a" reparse point, GetFileAttributes can be used (mentioned here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365507%28v=vs.85%29.aspx) and to get the content of "the" reparse point DeviceIoControl with FSCTL_GET_REPARSE_POINT is needed (cant post a third link because of low reputation) But i see no possibility to specify what reparse data i want if there are multiple? GetFileAttributes will say only Yes/No instead of a count or something like that, and DeviceIoControl will fill one single REPARSE_GUID_DATA_BUFFER structure (according to MSDN), without any possibilty to give a GUID or index or somtehing like that. edit: My question if i´ve understood this with 31 reparse points right and how i can access them. A: I understood the MSDN docs wrong: A file/directory itself can have only one reparse point itself (and a directory can have more than 31 files/directories with reparse points in it, of course) The limit 31 is only valid for nested symlinks (etc.), ie. Case 1: Link1->Link2, Link2->Link3, ... Link32->RealDir Here it would not be possible to open Link1 if i want RealDir Case 2: If i want to open C:\L1\L2\L3\L4...\L32\file.txt and L1 is a symlink to another directory, the target´s subdirectory L2 is another symlink, and so on, this too wouldn´t be possible with >31 nested links.
{ "language": "en", "url": "https://stackoverflow.com/questions/20776663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is There a Bookmarklet That Can Change Tab Favacon Is there a bookmarklet that can change a tab favicon? I have tried google, and github. I know this may be really complicated, but is there a bookmarklet that can do that? A: Her is the final result of my research based on this question:Changing website favicon dynamically. The final result is as follows: javascript:(function()%7Bvar link %3D document.querySelector("link%5Brel~%3D'icon'%5D")%3Bif (!link) %7Blink %3D document.createElement('link')%3Blink.rel %3D 'icon'%3Bdocument.getElementsByTagName('head')%5B0%5D.appendChild(link)%3B%7Dlink.href %3D prompt('favicon url%3F'%2C 'https%3A%2F%2Fstackoverflow.com%2Ffavicon.ico')%7D)()
{ "language": "en", "url": "https://stackoverflow.com/questions/66446635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Tinyfilemanager upload from URL permissions I have a problem after upload image from URL: * *Preview thumbnail doesn't work *Direct Link doesn't work, I get Forbidden error But image file exists in my storage... Upload from URL was set to permission 0600 and upload image from file is set 0644, it's a problem about permissions, I can resolve this with default 0644 permissions after upload? Thank you everyone! Upload from file wotks well with default permissions 0644
{ "language": "en", "url": "https://stackoverflow.com/questions/71689443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: htaccess 301 redirect GET-Parameter and remove it I am in a need of a 301-Redirect with the following example: The pages * *https://www.example.com/index.php?id= *https://www.example.com/?id= Should be redirected to * *https://www.example.com but i really do not understand how to solve that. What i have tried: RewriteCond %{query_STRING} ^id=(.*)$ RewriteRule https://www.example.com/ [R=301,L] A: You need to use ? at the end of target URI to strip off any existing query string. Also you can use a relative target URI also if target is on same domain. Use this rule: RewriteEngine On RewriteCond %{QUERY_STRING} ^id= [NC] RewriteRule ^(?:index\.php)?$ /? [R=301,L,NC]
{ "language": "en", "url": "https://stackoverflow.com/questions/28363349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I stop getting the 'Can't resolve async_hooks' error when using npm start? I've been following a tutorial on how to connect to a mongoDB collection. The tutorial works fine but I'm trying the same code in a project I'm working on and have been getting the following error constantly: ./node_modules/raw-body/index.js Module not found: Can't resolve 'async_hooks' in '*:\*\*\Desktop\Projects\testing-area\node_modules\raw-body' I've tried: -deleting node_modules and then running npm install -running npm update to bring all dependencies to the latest version -updating npm itself I've read that async_hooks is used for backend work and if you try to use it in the frontend, it can cause this issue. Problem is, I don't really know a way around it. Here's the code I'm trying to use to connect to the mongodb collection: //give functions of mongo db to MongoClient const { MongoClient } = require('mongodb') let dbConnection const bark = (input) => { console.log(input) } module.exports = { connectToDb: (cb) => { MongoClient.connect("mongodb://localhost:27017/Treasures") .then((client) => { dbConnection = client.db() return cb() }) .catch(err => { bark("----------") bark("Pants shat when trying to connect to DB:\n") bark(err) return cb(err) bark("----------") }) }, getDb: () => dbConnection } And then in a component I have this, to try and get the data from the collection: // Imports/Requires for mongoDb connection const { ObjectID } = require("bson"); const express = require("express"); const { connectToDb, getDb } = require("../../db") // COMPONENT STARTS HERE: export const TreasureGen = () => { //init app and middleware const app = express(); //db connection let db connectToDb((err) => { if(!err) { app.listen(3000, () => { bark("App listening on port 3000") }) db = getDb() } })
{ "language": "en", "url": "https://stackoverflow.com/questions/73975963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Build process template not visible when creating build definition in TFS 2010 I am trying to add a new build process template (XAML) to TFS 2010, using VS 2017. I have committed it under the BuildProcessTemplates folder for the team project and it is shown in the Source Control Explorer, but it doesn't show up in the drop down list on the Process tab of the Build definition dialog. The drop down list only shows the other 3 templates (DefaultTemplate.xaml, UpgradeTemplate.xaml...) in the folder. I found this description of how the dropdown list works: This list is populated with the following build process templates: * *The ones that come out of the box (DefaultTemplate.xaml, UpgradetTemplate.xaml and LabDefaultTemplate.xaml). These are created for every new team project (this can be changed by modifying the process template) *Any build process templates that have previously been added for any other build definitions in the same team project. The last bullet is a bit unintuitive, but it means that if a developer creates a new build definition in team project A, and adds a new build process template (for example by by selecting New and then browse to an existing .xaml file), this build process template will be available in the process dropdown list for all other build definitions in team project A. It will not be available in team project B, but has to be added in the same way. https://blog.ehn.nu/2010/11/managing-build-process-templates-in-tfs-2010-build/ I tried clicking on "New..." next to the drop down list. It only shows the option to "Select a team project that contains your build process template", there's no option to create a new one. If I enter the path to the .xaml file under "Path in repository" and click on OK I get an error: "Object reference not set to an instance of an object" Screenshot of error How do I make the new build process template available for build definitions? A: Normally, you just need to check in the template xaml files under the BuildProcessTemplate folder, then in Build Definition Process tab, Click New… button to add these xaml files from that fold. The path of xaml should have a \ sample in front of it. In your case, also try to clear TFS and VS cache, then try it again. If delete cache folder still doesn't work, please try it with older Visual Studio Version such as Visual Studio 2015 and create a new build definition, select the template. Also take a look at this blog shows the customize process template experience in TFS 2013, which may be helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/51097697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Read Json files from Azure Data lake storage Gen2 using Active AD User account in Python I am trying to access the json files stored in Data lake storage account. I only have reader access and want to use Active AD User account (Organization Email ID & password for Azure resources) for creating a connection and authentication. Any help would be highly appreciated. I am unable to form a successful connection string. def list_directory_contents(): try: file_system_client = service_client.get_file_system_client(file_system=<storage account>) mydirectory = <path to file> paths = file_system_client.get_paths(path=mydirectory) for path in paths: print(path.name + '\n') except Exception as e: print(e) list_directory_contents() service_client = DataLakeServiceClient.from_connection_string("DefaultEndpointsProtocol=https;AccountName=<email ID>;AccountKey=<Password>;EndpointSuffix=dfs.core.windows.net")
{ "language": "en", "url": "https://stackoverflow.com/questions/73020846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirecting an ip in Java For the past few weeks, I have been scouring the internet, the minds of computer programmers, and just a few random people over the situation I am looking to overcome. Basically, what I am trying to do it write a AntiJoinBot "plugin" (if you will) for the popular game Minecraft. This would be like all others in respect that it blocks IPs based on if they are using a proxy or not, but this AntiJoinBot is running on a different VPS than the actual server. This is the best graph I can make of the situation (it's not that good): (non-minecraft server) Connection -> Proxy check -> Redirect to the server -> Minecraft The only problem is, I need to be able to redirect the IP and close the connection so that the player's real IP is the one that would connect to the server. If the connection is not able to be closed, it would cause real problems due to some of the plugins we are running. If you have a solution or a better way to do this, please help me. A: Redirection of connections along the lines that you want requires support from the (application) protocol. TCP/IP does not support it. AFAIK, SOCKS does not support it either. Unless the Minecraft application protocol (and by implication, Minecraft clients and servers) include support for redirection, you are out of luck. (FWIW - that's how HTTP redirection works. HTTP has a "protocol element" that allows the server to tell the client to redirect, and where to redirect to. The client then resends the original request to a new address.) But that doesn't mean that you can't deal with the pests. It just means that the redirection approach is not viable. Try a custom proxy or an IP filter / redirector instead. A: You are trying to save the server's resources on the cost of increase Traffic. I am not sure with the answer but may be by looking into the concept of LBS(Load Balancing Server) you may find the answer. LBS is purely defined and controlled by us so you can manage the resources of two servers using one load balancing server.
{ "language": "en", "url": "https://stackoverflow.com/questions/15775781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: I'm trying to implement a popup calender when click on edittext that in a Tab Activity I'm trying to implement a popup calender when click on edittext that in a Tab Activity.My Tab activity as below. I need the code to post before the return V. Here the tab activity package com.artificers.subin.inspection; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; import java.util.HashMap; /** * Created by Subin on 13-10-2015. */ public class Tab2Fragment extends Fragment { EditText fromdate; EditText todate; // List view private ListView lv; // Listview Adapter ArrayAdapter<String> adapter; // Search EditText EditText inputSearch; // ArrayList for Listview ArrayList<HashMap<String, String>> productList; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View V = inflater.inflate(R.layout.tab2_view, container, false); EditText fromdate=(EditText)V.findViewById(R.id.fromdate); EditText todate=(EditText)V.findViewById(R.id.todate); fromdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); // Listview Data String products[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE", "iPhone 4S", "Samsung Galaxy Note 800", "Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"}; lv = (ListView) V.findViewById(R.id.list_view); // Adding items to listview adapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item, R.id.product_name, products); lv.setAdapter(adapter); return V; } } I'm trying to implement a popup calender when click on edittext that in a Tab Activity.My Tab activity as below. I need the code to post before the return V. Here the tab activity A: use this: final DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() { // when dialog box is closed, below method will be called. public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) { if (isOkayClicked) { year = selectedYear; month = selectedMonth; day = selectedDay; } isOkayClicked = false; } }; final DatePickerDialog datePickerDialog = new DatePickerDialog( HomePageActivity.this, R.style.DialogTheme, datePickerListener, year, month, day); //use your activity name here instead of HomePageActivity datePickerDialog.getDatePicker().setMaxDate(new Date().getTime()); // setting the max date datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_NEGATIVE) { dialog.cancel(); isOkayClicked = false; } } }); datePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Change", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { isOkayClicked = true; DatePicker datePicker = datePickerDialog .getDatePicker(); datePickerListener.onDateSet(datePicker, datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth()); } } }); datePickerDialog.setCancelable(false); datePickerDialog.show(); if needed, remove final keyword.. add this to values/styles.xml <style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog"> <item name="colorAccent">#e9671c</item> // you can change the color here </style> A: hope this will help you place this in your on click event DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getSupportFragmentManager(), "datePicker"); also add below Fragment in your Project class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); return new DatePickerDialog(getActivity(), this, year, month, day); } public void onDateSet(DatePicker view, int year, int month, int day) { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/33519302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Downloading file with node express js I'm trying to download a file with express js, but I'm having some trouble. Below is the function: var download = function(uri, filename, callback) { request .get(uri) .on('response', function (response) { var ext = response.headers['content-type'].split('/'); filename += '.' + ext[1]; }) .pipe(fs.createWriteStream(filename)); }; The problem is that I don't know the extension of the file, so I need to get it in response headers but the ext[1] value doesn't increment my filename with the file extension. I can't even set a variable by reference to do it outside the function. A: * *I think your pipe is fired before the 'filename' get any data. *You should not split with '/' Try this instead: var mime = require('mime-types'); // After npm install mime-types request .get(uri) .on('response', function (response) { var responseType = (response.headers['content-type'] || '').split(';')[0].trim(); var ext = mime.extension(responseType); filename += '.' + ext; var fileStream = fs.createWriteStream(filename) .on('finish', function() { //Download complete }) this.pipe(fileStream); }) P.S. You are downloading with 'request' module, not with express.
{ "language": "en", "url": "https://stackoverflow.com/questions/39321358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pandas rolling apply to update the Series for next iteration? I have following Series s, I want to rolling apply a self-defined function "test", and immediately update the results to s so that the next iteration of "test" is based on the updated s. Let me walk you through my example: s = pd.Series(range(5), index=pd.date_range('1/1/2000', periods=5)) s 2000-01-01 0 2000-01-02 1 2000-01-03 2 2000-01-04 3 2000-01-05 4 Freq: D, dtype: int32 My self-defined function as below. This is just a simplified example of my real case. We can see during the first iteration, the returned variable 'update' is set to 100, and I want the s to be updated as [0, 1, 100, 3, 4,....]. For the next iteration, the arr.sum() will calculated based on (1+100+3) instead of (1+2+3). def test(arr): print(arr) print(arr.sum()) if arr.sum()%3==0: print('True') update=100 else: update=arr[-1] return update s=s.rolling(window=3).apply(test) [ 0. 1. 2.] 3.0 True [ 1. 2. 3.] 6.0 True [ 2. 3. 4.] 9.0 True Ideal output: [ 0. 1. 2.] 3.0 True 'Update s with 100' [ 1. 100. 3.] 104 [ 100. 3. 4.] 107 A: I think dataframe.rolling is operating on the original dataframe only, it actually provides a rolling transformation. If any data is modified in a rolling window of the dataframe, it will NOT be updated in the consequential rolling windows. Actually I am facing the same issue here. So far the alternative I am using is to manually loop through each rolling window, and put the logic inside the loop. I know it is slow, but I have no idea if there is a better way to do this. BTW, the same question is asked by other people: Sliding window iterator using rolling in pandas Why doesn't my pandas rolling().apply() work when the series contains collections?
{ "language": "en", "url": "https://stackoverflow.com/questions/38732878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EAV Model - how to handle internationalization I have an existing spring mvc application with hibernate and mysql. I have requirement to create dynamic form in this application and i am planning to use EAV model. How can i handle internationalization? currently i have the messages_en.properties file inside WebContent/resources folder and the configuration is <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/resources/messages" /> <property name="defaultEncoding" value="UTF-8" /> </bean> For dynamic form when i create a text field how should i add the label to the properties file? I hope this question is written well enough to SO standards. if you need any additional information, please do not hesitate to ask and I will try to help you help me. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/35508758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replacing all instances of certain character in JS? I am trying to create a simple function that replaces all instances of a certain character in a string in JS. In this instance, I want to replace all a's with o's. I am pretty sure the code is right, but the output is still the original string. function replaceLetter(string){ for(var i = 0; i < string.length; i++){ if(string[i] == 'a'){ console.log(string[i]); string[i] = 'o' } } return string; } replaceLetter('hahaha') // returns 'hahaha' Why isn't it replacing a's with o's? A: You can use a regular expression like this: function replaceLetter(str) { return str.replace(/a/g, 'o'); } var st = replaceLetter('hahaha'); console.log(st); Or use another string to accumulate the result like this: function replaceLetter(str) { var res = ''; // the accumulator (because string litterals are immutable). It should be initialized to empty string for(var i = 0; i < str.length; i++) { var c = str.charAt(i); // get the current character c at index i if(c == 'a') res += 'o'; // if the character is 'a' then replace it in res with 'o' else res += c; // otherwise (if it is not 'a') leave c as it is } return res; } var st = replaceLetter('hahaha'); console.log(st); A: I always like using split() and join() var string = "assassination"; var newString = string.split("a").join("o"); A: Strings in Javascript are immutable, and thus any changes to them aren't going to be reflected as you might expect. Consider just using the string.replace() function instead: function replaceLetter(string){ // This uses a regular expression to replace all 'a' characters with 'o' // characters (the /g flag indicates that all should be matched) return string.replace(/a/g,'o'); } A: Assuming you want to use a for loop: function replaceLetter(string){ var result = ''; for (var i = 0; i < string.length; i++) { result += string[i] === 'a' ? 'o' : string[i]; } return result; } You have to build a new string like this, because as mentioned in a comment, strings are immutable. You can write string[4] = 'b' and it won't cause an error, but it won't do anything either. It's probably overkill, but you could use reduce, which does the looping internally and maintains the result variable: const replaceLetter = string => [...string].reduce((result, chr) => result += (chr === 'a' ? 'o' : chr), ''); However, for this particular case, the regexp solution shown in other answers is probably preferable.
{ "language": "en", "url": "https://stackoverflow.com/questions/42162640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Providing an abstract class which extends a Guice AbstractModule and has provides methods I want to provide a Guice AbstractModule which has a few providers annotated with protected annotations so that those values can only be used by the extending class. public abstract class AssetModule extends AbstractModule { /** Protected annotation to inject the underlying {@link Asset} payload. */ @Qualifier @Retention(RetentionPolicy.RUNTIME) protected @interface ProtectedAssetPayload {} @Qualifier @Retention(RetentionPolicy.RUNTIME) public @interface ParentPublicAnnotation {} @Override protected void configure() { install(new Framework()); } private final class Framework extends AbstractModule { @Override protected void configure() {} @Provides @ParentPublicAnnotation String getPublicValue() { return "public value"; } @Provides @ProtectedAssetPayload protected String getAssetPayload() { return "payload"; } } } Which would allow me to extend the asset so: public final class SomeAssetModule extends AssetModule { @Qualifier @Retention(RetentionPolicy.RUNTIME) public @interface ChildPublicAnnotation {} @Provides @ChildPublicAnnotation String concactToPayload(@ProtectedAssetPayload String payload) { return String.format("concact_%s", payload); } } And use both of the publicly annotated bindings in a third class: public final class Foo { private final String a; private final String b; @Inject public Foo(@ParentPublicAnnotation String a, @ChildPublicAnnotation String b) { this.a = a; this.b = b; } } When I try to run this I get an errors which look like: No implementation for java.lang.String annotated with @ParentPublicAnnotation() was bound No implementation for java.lang.String annotated with @ProtectedAssetPayload() was bound It seems that Guice only binds the provider methods in the implementing SomeAssetModule class, and ignores the bindings in the super class. Any thoughts on how to force Guice to actually bind the provides methods in the super class? Cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/38252349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you use a type outside of its own namespace in clojure? I have a project set up with leiningen called techne. I created a module called scrub with a type in it called Scrub and a function called foo. techne/scrub.clj: (ns techne.scrub) (deftype Scrub [state] Object (toString [this] (str "SCRUB: " state))) (defn foo [item] (Scrub. "foo") "bar") techne/scrub_test.clj: (ns techne.scrub-test (:use [techne.scrub] :reload-all) (:use [clojure.test])) (deftest test-foo (is (= "bar" (foo "foo")))) (deftest test-scrub (is (= (Scrub. :a) (Scrub. :a)))) When I run the test, I get the error: Exception in thread "main" java.lang.IllegalArgumentException: Unable to resolve classname: Scrub (scrub_test.clj:11) at clojure.lang.Compiler.analyzeSeq(Compiler.java:5376) at clojure.lang.Compiler.analyze(Compiler.java:5190) at clojure.lang.Compiler.analyzeSeq(Compiler.java:5357) If I remove test-scrub everything works fine. Why does :use techne.scrub 'import' the function definitions but not the type definitions? How do I reference the type definitions? A: I add the import, but get the same problem. I'm testing with the Expectations package 2.0.9, trying to import deftype Node and interface INode. In core.clj: (ns linked-list.core) (definterface INode (getCar []) (getCdr []) (setCar [x]) (setCdr [x])) (deftype Node [^:volatile-mutable car ^:volatile-mutable cdr] INode (getCar[_] car) (getCdr[_] cdr) (setCar[_ x] (set! car x) _) (setCdr[_ x] (set! cdr x) _)) In core_test.clj: (ns linked-list.core-test (:require [expectations :refer :all] [linked-list.core :refer :all]) (:import [linked-list.core INode] [linked-list.core Node])) and the output from lein autoexpect: *************** Running tests *************** Error refreshing environment: java.lang.ClassNotFoundException: linked-list.core.INode, compiling:(linked_list/core_test.clj:1:1) Tests completed at 07:29:36.252 The suggestion to use a factory method, however, is a viable work-around. A: Because deftype generates a class, you will probably need to import that Java class in techne.scrub-test with (:import [techne.scrub Scrub]) in your ns definition. I actually wrote up this same thing with respect to defrecord here: * *http://tech.puredanger.com/2010/06/30/using-records-from-a-different-namespace-in-clojure/ Another thing you could do would be to define a constructor function in scrub: (defn new-scrub [state] (Scrub. state)) and then you would not need to import Scrub in test-scrub.
{ "language": "en", "url": "https://stackoverflow.com/questions/3690784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Modulo operator with negative values Why do such operations: std::cout << (-7 % 3) << std::endl; std::cout << (7 % -3) << std::endl; give different results? -1 1 A: a % b in c++ default: (-7 / 3) => -2 -2 * 3 => -6 so a % b => -1 (7 / -3) => -2 -2 * -3 => 6 so a % b => 1 in python: -7 % 3 => 2 7 % -3 => -2 in c++ to python: (b + (a % b)) % b A: The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03), The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined. That is all the language has to say, as far as C++03 is concerned. A: From ISO14882:2011(e) 5.6-4: The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a. The rest is basic math: (-7 / 3) => -2 -2 * 3 => -6 so a % b => -1 (7 / -3) => -2 -2 * -3 => 6 so a % b => 1 Note that If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined. from ISO14882:2003(e) is no longer present in ISO14882:2011(e)
{ "language": "en", "url": "https://stackoverflow.com/questions/7594508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "194" }
Q: c#, ADFS, sso and OAuth2 : how to? I'm working on a front-end app which is developped in C# and which is supposed to access some WS. Those WS are developped in Java. To access those WS, user must be logged. The authentication system uses sso (ssocircle) and ADFS. The front and back (WS) are supposed to use OAuth2; I'm all new to those technologies and cannot find an example or tutorial which explain everything. I have a front mock which is in java (springOauthClient) which works perfectly : when i try to access a WS, i'm redirected on the ssocircle auth form, and then when i put my login/password, i'm redirected back to the mock, and get the WS results, then i can call others WS without being redirected to the login form again. What i'm trying to do now is to implement the real client (front), in c#, with OAuth2 but i have no idea what to do. I've tried : string completeUrl2 = "http://localhost:8080/volta-rest-webservices/oauth/authorize?client_id=volta-client&redirect_uri=http://localhost:63441/&response_type=code&scope=read%20write&state=kz3Ylz"; WebRequest request = WebRequest.Create(completeUrl2); try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); return Redirect(response.ResponseUri.OriginalString); } catch (WebException e) { //TODO log } And i'm redirected to the login form, i put my login/password, authentication is working well, but when i'm supposed to be redirected back to my front app, i get a 405 error : "Request method 'POST' not supported" ... The page url is then : http://localhost:8080/volta-rest-webservices/saml/SSO By the way i'm not sure that this is the correct url to call, am i supposed to call the oauth/token_access before oauth/authorize? I'm not sure about the params as well... Is this the correct way to do, just call some url or do i have to use some external libraries?? I'm quite confused...
{ "language": "en", "url": "https://stackoverflow.com/questions/34531073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to tell if a user clicked on a confirmation email sent with user.sendEmailVerification() in jsx I have this code for send a email, but I do not know how to wait for the answer (if confirm or not) because no matter if it confirms or not, it registers it handleSubmit = (e) => { e.preventDefault() firebaseAuth().createUserWithEmailAndPassword(this.email.value, this.pw.value) .then(function(user) { user.sendEmailVerification() }).then(function () { alert("User signup success"); }).catch(function (error) { var errorCode = error.code; var errorMessage = error.message; if (errorCode === 'auth/wrong-password') { alert('Wrong password.'); } else if(errorCode=='auth/email-already-in-use'){ alert("esa cuenta de correo ya esta en uso"); } else { alert(errorMessage); } console.log(error); }); } A: I don't know much about reactjs or fire base. But what you need to do is before you send the email create a unique id for every user when the submit the sign up form. In the email you genarate you need to add a button(link) to click if user need to get registered to the site. that link should redirect to your site with the id you have saved ex https://yoursite.com/signup-action?id=QSE$#@$WDVVDsfdsfew543 now when user click this you can get the id from the url and check if it is in the database and who is the user and can update the table to activate the user. That is how you know that the user has clicked the email.. then ask the user to log in
{ "language": "en", "url": "https://stackoverflow.com/questions/44912257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Label encoding in Pandas I am working with data set which have numerical and categorical values. I find solution with numerical values, so next step is to make label encoding with categorical values. In order to do that I wrote these lines of code: import pandas as pd dataset_categorical = dataset.select_dtypes(include = ['object']) new_column = dataset_categorical.astype('category') After execution of last line of code in Jupyter I can't see an error, but values are not converted into encoded values. Also this line work for example when I try with only one column but don't work with whole data frame. So can anybody help me how to solve this problem? A: df1 = { 'Name':['George','Andrea','micheal','maggie','Ravi', 'Xien','Jalpa'], 'Is_Male':[1,0,1,0,1,1,0]} df1 = pd.DataFrame(df1,columns=['Name','Is_Male']) Typecast to Categorical column in pandas df1['Is_Male'] = df1.Is_Male.astype('category')
{ "language": "en", "url": "https://stackoverflow.com/questions/67140667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Initial Data Load With ActionBar Indeterminate ProgressBar I have a Indeterminate Progress Bar replacing my MenuItem refresh button while an AsyncTask loads data. All of this works without issue: My create options menu: @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.videos, menu); menuItem = menu.findItem(R.id.button_refresh); super.onCreateOptionsMenu(menu, inflater); } Asynchronous Task: class ReviewLoaderAsyncTask extends AsyncTask<Void, Void, ArrayList<Review>> implements Api { private Context context; private int offset; private FragmentCallback mFragmentCallback; ArrayList<Review> add; public ReviewLoaderAsyncTask(Context _context, int _offset, FragmentCallback _mFragmentCallback) { context = _context; offset = _offset; mFragmentCallback = _mFragmentCallback; } @Override protected void onPreExecute() { super.onPreExecute(); menuItem.setActionView(R.layout.progressbar); //ERROR OCCURS HERE menuItem.expandActionView(); } @Override protected ArrayList<Review> doInBackground(Void... voids) { // Call some data here return add; } @Override protected void onPostExecute(ArrayList<Review> _reviews) { super.onPostExecute(_reviews); menuItem.collapseActionView(); menuItem.setActionView(null); mFragmentCallback.taskIsFinished(_reviews, offset); } } This all works fine. However, I want to begin loading this data as soon as the view is created. I do this inside my onCreateView portion @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.review_fragment_gridview, container, false); mGridView = (StaggeredGridView) view.findViewById(R.id.myGrid); reviews = new ArrayList<Review>(); offset = 0; ReviewLoaderAsyncTask loadRSSTask = new ReviewLoaderAsyncTask(getActivity(), offset, new FragmentCallback() { @Override public void taskIsFinished(ArrayList<Review> add, int _offset) { for (Review v : add) { reviews.add(v); } mReviewsAdapter = new ReviewsAdapter(getActivity(), reviews, getFragmentManager()); offset = _offset; mGridView.setAdapter(mReviewsAdapter); } }); if(savedInstanceState == null){ loadRSSTask.execute(); } else{ reviews = savedInstanceState.getParcelableArrayList(REVIEWS_LIST_TAG); ReviewsAdapter adapter = new ReviewsAdapter(getActivity(), reviews, getFragmentManager()); mGridView.setAdapter(adapter); ((BaseAdapter) mGridView.getAdapter()).notifyDataSetChanged(); } return view; } The problem I run in to is that the AsyncTask starts prior to the inflation of the menu. This results in a NullPointerException when I get to the PreExecute portion of my AsyncTask. Is there a better implementation to begin the data load in the onCreateView and still keep my ProgressBar actionview? A: Based on feedback from cYrixmorten, I moved the Async execute call to the onCreateOptionsMenu. Here is the modified code. Modified onCreateView: @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.review_fragment_gridview, container, false); mGridView = (StaggeredGridView) view.findViewById(R.id.myGrid); bundle = savedInstanceState; reviews = new ArrayList<Review>(); offset = 0; ReviewLoaderAsyncTask loadRSSTask = new ReviewLoaderAsyncTask(getActivity(), offset, new FragmentCallback() { @Override public void taskIsFinished(ArrayList<Review> add, int _offset) { for (Review v : add) { reviews.add(v); } System.out.println(reviews.size() +" is the video size!"); mReviewsAdapter = new ReviewsAdapter(getActivity(), reviews, getFragmentManager()); offset = _offset; mGridView.setAdapter(mReviewsAdapter); } }); if(savedInstanceState!=null){ reviews = savedInstanceState.getParcelableArrayList(REVIEWS_LIST_TAG); ReviewsAdapter adapter = new ReviewsAdapter(getActivity(), reviews, getFragmentManager()); mGridView.setAdapter(adapter); ((BaseAdapter) mGridView.getAdapter()).notifyDataSetChanged(); } return view; } Modified onCreateOptionsMenu: @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.videos, menu); menuItem = menu.findItem(R.id.button_refresh); ReviewLoaderAsyncTask loadRSSTask = new ReviewLoaderAsyncTask(getActivity(), offset, new FragmentCallback() { @Override public void taskIsFinished(ArrayList<Review> add, int _offset) { System.out.println(add.size() + "is the passed array size to the callback"); for (Review v : add) { reviews.add(v); } mReviewsAdapter = new ReviewsAdapter(getActivity(), reviews, getFragmentManager()); offset = _offset; mGridView.setAdapter(mReviewsAdapter); } }); if(bundle == null){ loadRSSTask.execute(); } super.onCreateOptionsMenu(menu, inflater); } This works, but I will not mark it as the solution for now in hopes to promote more discussion and alternative solutions to this question.
{ "language": "en", "url": "https://stackoverflow.com/questions/21419531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Docker: cd into directory using regular expressions I have to build a Docker image and in the Dockerfile I have move into a directory whose name contains a dynamic id, e.g myfolder12345, that can become myfolder56789 in another build. As I don't know which can be this id everytime I do the build, I have tried to use regular expressions to achieve that. I've tried with WORKDIR myfolder* but the current directory remains /. How can be solved? A: If you know, during the build of the docker image, the name of the folder, use a variable: WORKDIR ${workdir} And set the variable value during the build. A: Having a non-deterministic content in a docker image is a bad idea. You should rename the folder first, then the WORKDIR will be easier: # Supposing there is only one folder123 at each build RUN mv /path/to/folder* /path/to/folder WORKDIR /path/to/folder A: how about trying the regex syntax? WORKDIR workdir[\d]+ Let me know if that works for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/44967520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How do I get the directory where the executable is located? I got the filename like this: _TCHAR filename[_MAX_PATH]; GetModuleFileName(NULL,filename,sizeof(filename)); How do I remove the filename from this full path? Should I use regex? A: Since you use VS++, you can use: _splitpath and _wsplitpath functions to break apart path A: You can use the Windows shell API function PathRemoveFileSpec to do this. Example usage is listed on the linked page.
{ "language": "en", "url": "https://stackoverflow.com/questions/4292222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling outer class' syncronized method from inner class I have a program that looks in essence like this class Outer { class Inner implements Runnable { public void run() { doSomething(); } } public synchronized void doSomething() { //... } } Which lock does Inner.run() acquire when it is calling doSomething()? Is it identical to synchronized(Inner.this) or synchronized(Outer.this)? Thanks a lot in advance. A: The receiver for the invocation of doSomething() within run() is Outer.this. The synchronized will therefore lock the monitor on the object referenced by that expression. On computing the target reference in a method invocation expression, the JLS says Otherwise, let T be the enclosing type declaration of which the method is a member, and let n be an integer such that T is the n'th lexically enclosing type declaration of the class whose declaration immediately contains the method invocation. The target reference is the n'th lexically enclosing instance of this. T here is Outer, since that's the class that declares it. n is 1, as Outer is the immediately enclosing type declaration of Inner. The target reference is therefore the 1'th lexically enclosing instance of this, ie. Outer.this. Concerning synchronized methods, the JLS says For an instance method, the monitor associated with this (the object for which the method was invoked) is used.
{ "language": "en", "url": "https://stackoverflow.com/questions/37580062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NaN problem in Java I am converting four bytes to float and I'm getting NaN as a result, but I want the value 0.0. What am I doing wrong? This is my code: public class abc { public static void main(String[] args) { int[] arry = { 255, 255, 255, 255 }; int num = ((arry[0] << 24) & 0xFF000000) | ((arry[1] << 16) & 0xFF0000) | ((arry[2] << 8) & 0xFF00) | (arry[3] & 0xFF); float f = Float.intBitsToFloat(num); f= (float) ((f < 0 ? Math.ceil(f * 10) : Math.floor(f * 10)) / 10); System.out.println(f); } } A: Your main problem is that 0xFFFFFFFF is indeed a NaN. A float with a value of 0 is... 0. Changing the array to int[] arry = { 0x00, 0x00, 0x00, 0x00 }; Will change the resulting value to a 0.0f float. A: Well, your bit pattern happens to actually be NaN: IEEE 754 NaNs are represented with the exponential field filled with ones and some non-zero number in the significand. A bit-wise example of a IEEE floating-point standard single precision NaN: x111 1111 1axx xxxx xxxx xxxx xxxx xxxx where x means don't care. If a = 1, it is a quiet NaN, otherwise it is a signalling NaN. Since all your bits are 1, it obviously fits above criteria and is a quiet NaN (although Java iirc doesn't even support quiet or signalling NaNs). A: NaN = Not a Number, iaw, the bit pattern 0xFFFFFFFF does not represent a float value number. (Joachim, you're right .. again :-) )
{ "language": "en", "url": "https://stackoverflow.com/questions/1807737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to set Selected List Item of RadioButtionList dynamically I have an Asp.net Radio Button List in my aspx page with two list items and values of these list items are "1","0" respectively. I am getting some values from database and performing some condition on that data to set selection of list item on the basis of those condition. Code is working properly but list item selection is not performed when i saw the output on the browser. ASPX Page Control: <asp:RadioButtonList ID="rg_A1S1Q1" runat="server"> <asp:ListItem Text="Yes" Value="1"></asp:ListItem> <asp:ListItem Text="No" Value="0"></asp:ListItem> </asp:RadioButtonList> Server Side Coding: RadioButtonList rbl = (RadioButtonList)cph.FindControl("rg_A1S1Q1"); rbl.Items.FindByValue("1").Selected = true; rbl.SelectedItem.Attributes.Add("style", "color: blue"); rbl.Enabled = false; A: Try this rbl.SelectedValue = "1";
{ "language": "en", "url": "https://stackoverflow.com/questions/58320762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: store a file into a ftp server using apache commons doesn't work I am trying to store a file into a ftp server using apache commons java library. I am using commons-net-3.0.1.jar. The problem is when ever i try to push the file into server, the call StoreFile() returns false always. It doesn't throw any exception. nothing at all,just reply false silently. If i try to push the file manually i.e using normal "ftp" client in linux systems (I meant connecting to ftp server using ftp command and storing the file using put command), then it puts the file into server. I have no idea of how to debug it even. Can you please let me know how i can get to know the problem and its solution. I checked the server logs, when ever i am trying to post through java the log says 425 response code failed to establish connection. But when i use manually it shows 226 response. A: Note: FTP is not a reliable protocol to upload/download data to/from a server with code. If you need a reliable solution, FTP is not for you. Try ssh instead. To answer your question: Add a ProtocolCommandListener to your SocketClient (FTP extends this). Then you can at least print the messages in ProtocolCommandListener() and protocolReplyReceived()
{ "language": "en", "url": "https://stackoverflow.com/questions/10383302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: REST API payment.create not creating payment I have a backend webservice (not a web page) that is attempting to create a payment from a front end client. After a couple of goes where I did not quite have the data matching between details and transaction list, where I got suitable error messages from the sandpit explaining what was wrong, I eventually got the payment.create method to execute without throwing an exception. Unfortunately, while I can see the existence of SSL traffic between the test web service and the paypal, when the routine returns I have no links and no status of created. I may have completely misunderstood the mechanics of the api, but in the absence of any error or exception from the call, I am a little stumped. Here is the code I am using: var config = ConfigManager.Instance.GetProperties(); var clientid = config[BaseConstants.ClientId]; var clientSecret = config[BaseConstants.ClientSecret]; var accessToken = new OAuthTokenCredential(clientid, clientSecret, config).GetAccessToken(); var apiContext = new APIContext(accessToken); var itemList = new ItemList() { items = new List<Item>() }; using (var context = new PETTEntities3()) { SubscriptionType subType = context.SubscriptionTypes.FirstOrDefault(s => s.SubscriptionTypeID == Subscription.SubscriptionTypeID); itemList.items.Add(new Item() { name = subType.SubscriptionName, currency = "NZD", price = (Subscription.Amount / (decimal)1.15).ToString("0.00"), quantity = "1", sku = subType.SubscriptionTypeID.ToString() }); var payer = new Payer() { payment_method = "paypal" }; var redirectUrls = new RedirectUrls() { cancel_url = ConfigurationManager.AppSettings["PaymentConfirmationURL"] + Subscription.PaymentApprovalID, return_url = ConfigurationManager.AppSettings["PaymentCancellationURL"] + Subscription.PaymentApprovalID }; var details = new Details() { tax = (Subscription.Amount - decimal.Parse((Subscription.Amount / (decimal)1.15).ToString("0.00"))).ToString("0.00"), subtotal = (Subscription.Amount / (decimal)1.15).ToString("0.00"), shipping="0" }; var amount = new Amount() { currency = "NZD", total = Subscription.Amount.ToString("0.00"), details = details }; var transactionList = new List<Transaction>(); transactionList.Add(new Transaction() { description = "PETT Subscription.", invoice_number = "PETT1420" + Subscription.SubscriptionID.ToString(), amount = amount, item_list = itemList }); Payment payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirectUrls }; payment.Create(apiContext); .... At this point the payment state is still null and no links are present even though I appear to have a successful call with no exceptions. Any clues or insight as to what I am missing would be greatly appreciated. A: Doh, blindingly obvious. Wasn't paying attention to the function signature payment.create, it returns a new payment. Its that which you need to use, not the payment used to invoke create eg: Payment paymentToUse = payment.Create(apiContext); paymentToUse has all the goods im after.
{ "language": "en", "url": "https://stackoverflow.com/questions/27260047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamically finding the path of C Binary which is invoking python I have a C binary executable called requestAudit in /apps/tools/public/requestAudit . This binary invokes a python script under /apps/tools/sf/audits/audit.py . Now I need to find the absolute path of the Binary i.e. /apps/tools/public/requestAudit inside my audit.py script. This is needed to create log files under the directory where the binary executable resides. is there any way we can get it programmatically. Note that even when I call that binary from anywhere I should always get the absolute path of binary executable. Thanks A: Well, the main thing you need to do is get the current working directory in your C script, and then you can either write some C code to combine the result with argv[0] to create the full path to the file and pass that to your python script as command line argument when you call it. Alternatively, you could pass both argv[0] and the result of getcwd() as parameters to your Python script, which is what I did below: requestAudit.c #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> int main(int argc, const char* argv[]) { char* cwd = getcwd(NULL, 0); char* command = "python audit.py "; char* combine; // I added 2 because 1 for the null terminator and 1 for the space // between cwd and argv[0] size_t len = strlen(command) + strlen(cwd) + strlen(argv[0]) + 2; combine = malloc(sizeof(*combine)*len); strncpy(combine, command, strlen(command) + 1); strncat(combine, cwd, strlen(cwd) + 1); strncat(combine, " ", 2); strncat(combine, argv[0], strlen(argv[0]) + 1); return system(combine); } audit.py import sys if __name__ == "__main__": full_path = sys.argv[1] + sys.argv[2][1:] print(full_path) This is just one way to do it, I'm sure there are other, probably better, ways to do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/62337220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dry method for webapi with multiple routing levels Is there a way to simplify when we have multiple required levels of routing fro each and every method? I have a hypothetical WebAPI project that i'm using for a generic look at the problem. It gives us movies from some source. public class MovieController : ApiController { // GET api/<controller> public IEnumerable<Movie> Get() { return MoviesDB.All(); } // GET api/<controller>/5 public Movie Get(int id) { return MoviesDB.ThisSpecificOne(id); } // POST api/<controller> public void Post([FromBody]Movie value) { } // PUT api/<controller>/5 public void Put(int id, [FromBody]Movie value) { } // DELETE api/<controller>/5 public void Delete(int id) { } } But lets say for some stupid reason movies are stored by Genre. So you need genre + id combo. I'm assuming this is how you would do it config.Routes.MapHttpRoute( name: "MoviesWithGenre", routeTemplate: "api/{controller}/{genre}/{id}", defaults: new { id = RouteParameter.Optional } ); public class MovieController : ApiController { // GET api/<controller>/<genre> public IEnumerable<Movie> Get(string genre) { return MoviesDB.All(genre); } // GET api/<controller>/<genre>/5 public Movie Get((string genre, int id) { return MoviesDB.ThisSpecificOne(string genre, id); } // POST api/<controller>/<genre> public void Post(string genre, [FromBody]Movie value) { } // PUT api/<controller>/<genre>/5 public void Put(string genre, int id, [FromBody]Movie value) { } // DELETE api/<controller>/<genre>/5 public void Delete(string genre, int id) { } } So now MySite.Com/api/movie/horror/12345 might return a movie but I needed to add the optional parameter in every method. Now I find out they are stored by year as well. config.Routes.MapHttpRoute( name: "MoviesWithGenreAndYear", routeTemplate: "api/{controller}/{genre}/{year}/{id}", defaults: new { id = RouteParameter.Optional } ); public class MovieController : ApiController { // GET api/<controller>/<genre>/<year> public IEnumerable<Movie> Get(string genre, int year) { return MoviesDB.All(string genre, int year); } // GET api/<controller>/<genre>/<year>/5 public Movie Get(string genre, int year, int id) { return MoviesDB.ThisSpecificOne(string genre, int year, id); } // POST api/<controller>/<genre>/<year> public void Post(string genre, int year, [FromBody]Movie value) { } // PUT api/<controller>/<genre>/<year>/5 public void Put(string genre, int year, int id, [FromBody]Movie value) { } // DELETE api/<controller>/<genre>/<year>/5 public void Delete(string genre, int year, int id) { } } This all works fine but with each new layer you would need to add a new parameter to each and every method. That doesn't feel very DRY Could I inject these layers into the constructor instead of the methods themselves. Perhaps I would like to initialize the controller differently based on these layers, so I would have a different repo based on genre and/or year or something like that. Is there a solution for this? A: Did you consider using OData? Web Api has support for OData baked in, with it you could write your queries as url's: e.g. ?$filter=Genre eq 'horror'. If, for some reason or other you, don't want your data returned as OData but would like the query syntax of OData then you could: * *use Linq To QueryString: this lib gives you an extension method to IQueryable that parses the query string and applies the query to any IQueryable *transform ODataQueryOptions into a query into your database (see this MSDN article for an example that translates the query into HQL) A: Is moving the optional parameters into the query string a viable option? e.g. GET api/movie?genre=horror&year=2014 This would simplify your route and controller to: config.Routes.MapHttpRoute( name: "Movies", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); public class MovieController : ApiController { // GET api/<controller>?genre=<genre>&year=<year> public IEnumerable<Movie> Get(string genre = null, int? year = null) { return MoviesDB.All(string genre, int year); } // GET api/<controller>/5?genre=<genre>&year=<year> public Movie Get(int id, string genre = null, int? year = null) { return MoviesDB.ThisSpecificOne(string genre, int year, id); } // POST api/<controller>?genre=<genre>&year=<year> public void Post([FromBody]Movie value, string genre = null, int? year = null) { } // PUT api/<controller>/5?genre=<genre>&year=<year> public void Put(int id, [FromBody]Movie value, string genre = null, int? year = null) { } // DELETE api/<controller>/5?genre=<genre>&year=<year> public void Delete(int id, string genre = null, int? year = null) { } } A: If you really mean the movies are stored by genre and the year, then I do believe your not so dry solution is actually correct. This does lead me to question the purpose of constructing such multi part identifier, as for instance the movie used in your example, surely the year and genre are just meta information about the movie, but not parts of the identifier. More generally speaking I'd really argue whether a composite identifier of more than two, or at least more than three parts is ever a good fit for any peace of software. A surrogate key would ease the development pain in such scenario. Also discussing your concern about the DRY:ness of the repetition, I'd argue that as the primary key structure of an object seldom changes, it is not a really big issue. Even more so as a change in the primary key will thus always be a change breaking all backward compatibility. As a gimmick, you could create a new class that contains the complex ID as such: public class MovieId { public int Id { get; set; } public int Yead { get; set; } public string Genre { get; set; } } And then make the controller methods as such: public Movie Get( [FromBody]MovieId id ) { return MoviesDB.ThisSpecificOne( id ); } This works and now the code adheres well to DRY principle. The problem is, the complex type has to be a body parameter, so the query string will not be pretty and self explanatory anymore and you'll have to be creative with the routes to distinguish the different get methods. Moving into a business layer or a DDD layer, this kind of composite key as a value object is a very common scenario and as the query string is of no concern there, it's actually a very viable and recommended solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/22194558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Grouping on a column which has multiple Groups of Duplicate data I need to group some data based on dates at locations including identifying when a range of dates has no location. I'm some of the way there in that I have managed to produce a list of ALL the dates in the range and the location. * *date1 location1 *date2 location1 *date3 location1 *date4 Unknown *date5 Unknown *date6 Unknown *date7 Location2 *date8 Location2 *date9 Location2 *date10 Location2 *date11 location1 *date12 location1 *date13 location1 using a normal group by (showing min(date) and max(date) I would get something like: * *Location1,date1,date13 *Location2,date7,date10 *Unknown, date4,date6 But I want this: * *Location1,date1,date3 *Unknown,date4,date6 *Location2,date7,date9 *Location1,date11,date13 I also need to filter out short ranges of Unknown but that's secondary. I hope this makes sense, it looks like something that should be really easy. A: Take a look into the Islands and Gaps problem and Itzik Ben-gan. There is a set based way to get the results you want. I was looking into using ROW_NUMBER or RANK, but then I stumbled upon LAG and LEAD (introduced in SQL 2012) which are nice. I've got the solution below. It could definitely be simplified, but having it as several CTEs makes my thought process (as flawed as it may be) easier to see. I just slowly transform the data into what I want. Uncomment one select at a time if you want to see what each new CTE produces. create table Junk (aDate Datetime, aLocation varchar(32)) insert into Junk values ('2000', 'Location1'), ('2001', 'Location1'), ('2002', 'Location1'), ('2004', 'Unknown'), ('2005', 'Unknown'), ('2006', 'Unknown'), ('2007', 'Location2'), ('2008', 'Location2'), ('2009', 'Location2'), ('2010', 'Location2'), ('2011', 'Location1'), ('2012', 'Location1'), ('2013', 'Location1'), ('2014', 'Location3') ;WITH StartsMiddlesAndEnds AS ( select aLocation, aDate, CASE(LAG(aLocation) OVER (ORDER BY aDate, aLocation)) WHEN aLocation THEN 0 ELSE 1 END [isStart], CASE(LEAD(aLocation) OVER (ORDER BY aDate, aLocation)) WHEN aLocation THEN 0 ELSE 1 END [isEnd] from Junk ) --select * from NumberedStartsMiddlesAndEnds ,NumberedStartsAndEnds AS --let's get rid of the rows that are in the middle of consecutive date groups ( select aLocation, aDate, isStart, isEnd, ROW_NUMBER() OVER(ORDER BY aDate, aLocation) i FROM StartsMiddlesAndEnds WHERE NOT(isStart = 0 AND isEnd = 0) --it is a middle row ) --select * from NumberedStartsAndEnds ,CombinedStartAndEnds AS --now let's put the start and end dates in the same row ( select rangeStart.aLocation, rangeStart.aDate [aStart], rangeEnd.aDate [aEnd] FROM NumberedStartsAndEnds rangeStart join NumberedStartsAndEnds rangeEnd ON rangeStart.aLocation = rangeEnd.aLocation WHERE rangeStart.i = rangeEnd.i - 1 --consecutive rows and rangeStart.isStart = 1 and rangeEnd.isEnd = 1 ) --select * from CombinedStartAndEnds ,OneDateIntervals AS --don't forget the cases where a single row is both a start and end ( select aLocation, aDate [aStart], aDate [aEnd] FROM NumberedStartsAndEnds WHERE isStart = 1 and isEnd = 1 ) --select * from OneDateIntervals select aLocation, DATEPART(YEAR, aStart) [start], DATEPART(YEAR, aEnd) [end] from OneDateIntervals UNION select aLocation, DATEPART(YEAR, aStart) [start], DATEPART(YEAR, aEnd) [end] from CombinedStartAndEnds ORDER BY DATEPART(YEAR, aStart) and it produces aLocation start end Location1 2000 2002 Unknown 2004 2006 Location2 2007 2010 Location1 2011 2013 Location3 2014 2014 Don't have 2012? Then you can still get the same StartsMiddlesAndEnds CTE using ROW_NUMBER: ;WITH NumberedRows AS ( SELECT aLocation, aDate, ROW_NUMBER() OVER (ORDER BY aDate, aLocation) [i] FROM Junk ) ,StartsMiddlesAndEnds AS ( select currentRow.aLocation, currentRow.aDate, CASE upperRow.aLocation WHEN currentRow.aLocation THEN 0 ELSE 1 END [isStart], CASE lowerRow.aLocation WHEN currentRow.aLocation THEN 0 ELSE 1 END [isEnd] from NumberedRows currentRow left outer join NumberedRows upperRow on upperRow.i = currentRow.i-1 left outer join NumberedRows lowerRow on lowerRow.i = currentRow.i+1 ) --select * from StartsMiddlesAndEnds
{ "language": "en", "url": "https://stackoverflow.com/questions/12938904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Php, bash, sshpass, scp is not working via shell_exec Issue I have php, which run bash script via shell_exec. All is ok, but last step (scp to server) false. sshpass -p 'PASSWORD' scp ../xlsx/"${file_pdf%.*}-$i.xlsx" USER@HOST:/var/www/html/FOLDER 2>&1 Output. Host key verification failed. When I run this script as user on server, all is ok. Is something needed to run scp (or connect) via user www-data? Rights are 777 for folders. Thanks. A: Solution. I added option -o StrictHostKeyChecking=no to scp. sshpass -p 'PASSWORD' scp -o StrictHostKeyChecking=no ../xlsx/"${file_pdf%.*}-$i.xlsx" USER@HOST:/var/www/html/FOLDER 2>&1
{ "language": "en", "url": "https://stackoverflow.com/questions/58270070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I want to close my application when the user touch the notification I want to close my application when the user touch the notification, this is my code for notification code in main activity NotificationCompat.Builder builder=new NotificationCompat.Builder(this); builder.setSmallIcon(R.drawable.earth); builder.setContentTitle("RadioPlanet"); builder.setContentText("Touch here to stop"); int mll=001; NotificationManager mNotification=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); mNotification.notify(mll,builder.build());
{ "language": "en", "url": "https://stackoverflow.com/questions/42021469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to read data from database Possible Duplicate: Best Cocoa/Objective-C Wrapper Library for SQLite on iPhone Can you please refer me how to read data from database in sqlite. I have an sqlite which has four tables and I want to get these four tables details in single view. A: Please read this, 1. Download FMDB files. 2. Add into your project. 3. Read path into your viewController.m Follow the instruction on the website, if problem then feel free to contact. link : https://github.com/ccgus/fmdb A: Well, you can go with any sqlite wrappers written in objective-c. I will suggest FMDB because it is very widely used and easy to learn as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/9091659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: XElement.SetElementValue with xml string paramter and preserve xml wrapping Is that possible to set an element value by already serialized XML string? var obj = new XElement("object"); obj.SetElementValue("InnerXml", "<testXml>Test_data</testXml>"); Result is: <object> <InnerXml>&lt;testXml &gt;Test_data &lt;/testXml&gt;</InnerXml> </object> But I would like to get this: <object> <InnerXml><TestXml>Test_data</TestXml></InnerXml> </object> A: You should create each element at once and add them to the root element. if you are loading the string dynamically you can use XElement.Parse Method (String) something like this var obj = new XElement("object"); //obj.SetElementValue("InnerXml", "<testXml>Test_data</testXml>"); XElement elt = new XElement("InnerXml"); obj.Add(elt); XElement elt2 = XElement.Parse("<testXml>Test_data</testXml>"); elt.Add(elt2);
{ "language": "en", "url": "https://stackoverflow.com/questions/21288368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Amazon Product Advertising API ItemSearch Signature Error in Php I tried ItemLookup like this, http://webservices.amazon.in/onca/xml?AWSAccessKeyId=[AccessId]&AssociateTag=[AssociateId]&IdType=ISBN&ItemId=8129135728&Operation=ItemLookup&ResponseGroup=ItemAttributes%2CImages&SearchIndex=Books&Service=AWSECommerceService&Timestamp=2015-05-12T13%3A42%3A02Z&Version=2011-08-01&Signature=[Signature] It is working fine for me. I tried this for ItemSearch, http://webservices.amazon.in/onca/xml?AWSAccessKeyId=[AccessId]&AssociateTag=[AssociateId]&Operation=ItemSearch&ResponseGroup=Small&SearchIndex=All&Keywords=harry_potter&Service=AWSECommerceService&Timestamp=2015-05-12T13%3A39%3A22Z&Version=2011-08-01&Signature=[Signature] But,it is not working and showing Signature doesn't match error. Can anybody help me in correcting ItemSearch Request? A: I'm assuming that you have started with the following as it looks similar to the URL that you have created http://docs.aws.amazon.com/AWSECommerceService/latest/GSG/SubmittingYourFirstRequest.html Double check the timestamp as the page mentions it can't be more than 15 minutes old But I'm afraid I don't know that API well enough to know how to get the signature setup correctly but have you considered using a library This seems like a nice example of what can be achieved with the library http://exeu.github.io/apai-io/
{ "language": "en", "url": "https://stackoverflow.com/questions/30193706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does dragging (drop/drag) element cause dropzone (div) to partially disappear? Using HTML5 Drag/Drop, when dragging element the dropzone partially disappears from UI, as seen in screenshot. The partial missing div in the image has a red boarder. When I remove the "hr" tag, from the code below, it works and the div does NOT disappear when dragging element! This is only happening in Chrome browser. All the code is below. Does anyone know why this is occurring? <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title></title> <style> .objects { display: inline-block; background-color: #FFF3CC; border: #DFBC6A 1px solid; width: 50px; height: 50px; margin: 10px; padding: 8px; font-size: 18px; text-align: center; box-shadow: 2px 2px 2px #999; cursor: move; } #drop_zone { background-color: #EEE; border: #f00 1px solid; width: 280px; height: 200px; padding: 8px; font-size: 18px; } </style> <script> function _(id){ return document.getElementById(id); } var droppedIn = false; function drag_start(event) { _('app_status').innerHTML = "Dragging the " + event.target.getAttribute('id'); event.dataTransfer.dropEffect = "move"; event.dataTransfer.setData("text", event.target.getAttribute('id') ); } function drag_enter(event) { _('app_status').innerHTML = "You are dragging over the "+event.target.getAttribute('id'); } function drag_leave(event) { _('app_status').innerHTML = "You left the "+event.target.getAttribute('id'); } function drag_drop(event) { event.preventDefault(); /* Prevent undesirable default behavior while dropping */ var elem_id = event.dataTransfer.getData("text"); event.target.appendChild( _(elem_id) ); _('app_status').innerHTML = "Dropped "+elem_id+" into the "+event.target.getAttribute('id'); _(elem_id).removeAttribute("draggable"); _(elem_id).style.cursor = "default"; droppedIn = true; } function drag_end(event) { if(droppedIn == false){ _('app_status').innerHTML = "You let the "+event.target.getAttribute('id')+" go."; } droppedIn = false; } function readDropZone(){ alert('dropzone'); for(var i=0; i < _("drop_zone").children.length; i++){ alert(_("drop_zone").children[i].id+" is in the drop zone"); } /* Run Ajax request to pass any data to your server */ } </script> </head> <body> <h2 id="app_status">App status...</h2> <h1>Drop Zone</h1> <div id="drop_zone" ondragenter="drag_enter(event)" ondrop="drag_drop(event)" ondragover="return false" ondragleave="drag_leave(event)"></div> <div id="object1" class="objects" draggable="true" ondragstart="drag_start(event)" ondragend="drag_end(event)">object 1</div> <div id="object2" class="objects" draggable="true" ondragstart="drag_start(event)" ondragend="drag_end(event)">object 2</div> <div id="object3" class="objects" draggable="true" ondragstart="drag_start(event)" ondragend="drag_end(event)">object 3</div> <hr /> <br /> <button onclick="readDropZone()">Get Object Data</button> </body> </html> A: In my tests, even if I deleted the <hr />, the error was still reproduced. I noticed, that it occurs after changing h2#app_status text. If you wrap div#drop_zone and all next elements like div#object... with div that has inline-block as display style, then there will be no such disappearing. <style> #drop-zone-wrapper {display: inline-block;} </style> <div id="drop-zone-wrapper"> <div id="drop_zone" ondragenter="drag_enter(event)" ondrop="drag_drop(event)" ondragover="return false" ondragleave="drag_leave(event)"></div> <div id="object1" class="objects" draggable="true" ondragstart="drag_start(event)" ondragend="drag_end(event)">object 1</div> <div id="object2" class="objects" draggable="true" ondragstart="drag_start(event)" ondragend="drag_end(event)">object 2</div> <div id="object3" class="objects" draggable="true" ondragstart="drag_start(event)" ondragend="drag_end(event)">object 3</div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/47128047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make my item hidden until all the the animation finishes I'm making a navigation bar and having problem hiding the button that shows the navigation until it's totally disappeared. screen : https://i.stack.imgur.com/pv6wk.png my code : function show(){ var nav = document.getElementsByClassName("navigation")[0]; var phone_button = document.getElementsByClassName("button-phone")[0]; nav.style.transform = "translateX(0)"; phone_button.style.opacity = "0" } function hide(){ var nav = document.getElementsByClassName("navigation")[0]; var phone_button = document.getElementsByClassName("button-phone")[0]; nav.style.transform = "translateX(-100%)"; phone_button.style.opacity = "1" } A: You can use z-index property for .navigation instead of using opacity for phone_button. in CSS file you set z-index:10; for .navigaion class. Besides that, it's better to set the property in one class in CSS and after clicking on phone_button just toggle this specific class for navigation You can do like this: const btn=document.querySelector(".menuBtn"); const nav=document.querySelector('.navigation'); const closeBtn=document.querySelector('.closeBtn'); btn.addEventListener('click',function(){ nav.classList.add('show'); }) closeBtn.addEventListener('click',function(){ nav.classList.remove('show'); }) *{ margin:0; box-sizing:border-box; } .container{ position:relative; display:flex; } .navigation{ position:absolute; width:200px; height:100vh; background-color:#e45; transform:translateX(-100%); transition:transform 0.5s; z-index:10 } .navigation.show{ transform:translateX(0) } li{ list-style:none; margin:0; } a{ text-decoration:none; color:white; padding:0.3rem 1rem; margin-top:0.5rem; display:block; } .closeBtn{ cursor:pointer; color:white; padding:1rem; display:block; margin-left:auto; } <div class="container"> <button class='menuBtn'>click me</button> <nav class="navigation"> <span class="closeBtn">close</span> <ui> <li> <a href="#">home</a> </li> <li> <a href="#">about</a> </li> </ui> </nav> </div> With this snippet code after the user clicked on the click me button, the .show class add to nav item class list. A: You can use the transitionend event and hide the Button in an eventlistener A: You can use this event check this tutorial. var x = document.getElementById("myDIV"); // Code for Chrome, Safari and Opera x.addEventListener("webkitAnimationEnd", myEndFunction); // Standard syntax x.addEventListener("animationend", myEndFunction);
{ "language": "en", "url": "https://stackoverflow.com/questions/72925803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hibernate OGM provider for Spring configuration I created a Java application that can use SQL Server or Neo4j as a database without touching the application layer, I just modify the provider and the connection information, like follows: <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="jpa-tutorial" transaction-type="RESOURCE_LOCAL"> <!--For SQL Server--> <!--provider>org.hibernate.ejb.HibernatePersistence</provider> <!--class>com.mycompany.hibernate.Atom</class--> <!--For Neo4j--> <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider> <properties> <!--For Neo4j--> <property name="hibernate.ogm.datastore.provider" value="neo4j_embedded" /> <property name="hibernate.ogm.neo4j.database_path" value="D:/Stage/Neo4j/NEO4J_HOME_4/data/graph.db" /> <!--For SQL Server--> <!--property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/atom" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="" /> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.hbm2ddl.auto" value="updatr" /--> </properties> </persistence-unit> </persistence> I have now to make the same thing but with a Spring application. I've started learning Spring but found a completely new logic. For example, there is a different provider of JPA: <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> Does that mean that there's no way to do the same as the first application? I mean there's no Hibernate OGM provider that I can just put in the place of HibernateJpaVendorAdapter in order to make the application running on Neo4j rather than SQL Server? Thanks in advance. PS: I checked out Spring Data but found another difference in defining entities (@NodeEntity, @GraphId, @RelatedTo, etc.). I'm asked not to touch the application code. A: Here is the below Java configuration class(Note I'm using spring boot, you could modify according you your requirement) @Configuration @EnableJpaRepositories(basePackages = { "com.kp.swasthik.mongo.dao" }, entityManagerFactoryRef = "mongoEntityManager", transactionManagerRef = "mongoTransactionManager") public class MongDbConfig { @Bean(name = "mongoEntityManager") public LocalContainerEntityManagerFactoryBean mongoEntityManager() throws Throwable { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("javax.persistence.transactionType", "resource_local"); properties.put("hibernate.ogm.datastore.provider","mongodb"); properties.put("hibernate.ogm.datastore.host","localhost"); properties.put("hibernate.ogm.datastore.port","27017"); properties.put("hibernate.ogm.datastore.database", "kpdb"); properties.put("hibernate.ogm.datastore.create_database", "true"); LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean(); entityManager.setPackagesToScan("com.kp.swasthik.mongo.domain"); entityManager.setPersistenceUnitName("mongoPersistenceUnit"); entityManager.setJpaPropertyMap(properties); entityManager.setPersistenceProviderClass(HibernateOgmPersistence.class); return entityManager; } @Bean(name = "mongoTransactionManager") public PlatformTransactionManager transactionManager() throws Throwable { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(mongoEntityManager().getObject()); return transactionManager; } } Regarding your Second question on @NodeEntity @GraphId etc. Similar to hibernate OGM sprig provides jpa implementation for no sql using spring-data for number of nosql datastores such as redis, mongodb,cassandra, hbase, couchdb, solr, elasticsearch etc. @NodeEnity and @GraphId is used in neo4j A: I add Java Config for Neo4j with OGM Hibernate @Configuration @EnableTransactionManagement @JpaPackagesToScan(Entity.class) public class RepositoryConfig { /** * Neo4J OGM EntityManager config */ @Bean public LocalContainerEntityManagerFactoryBean entityManager(JpaPackagesToScanHolder holder) throws Throwable { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("javax.persistence.transactionType", "JTA"); properties.put("hibernate.ogm.datastore.provider", "neo4j_embedded"); properties.put("hibernate.ogm.datastore.database", "my-db"); properties.put("hibernate.ogm.neo4j.database_path", "/mnt/graph.db"); properties.put("hibernate.dialect", "org.hibernate.ogm.datastore.neo4j.Neo4jDialect"); LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean(); entityManager.setPackagesToScan(holder.toStringArray()); entityManager.setPersistenceUnitName("my-pu"); entityManager.setJpaPropertyMap(properties); entityManager.setPersistenceProviderClass(HibernateOgmPersistence.class); return entityManager; } @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) throws Throwable { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory); return transactionManager; } } And added to the pom (for Java 7 project) <dependency> <groupId>org.hibernate.ogm</groupId> <artifactId>hibernate-ogm-neo4j</artifactId> <version>4.1.0.Final</version> </dependency>
{ "language": "en", "url": "https://stackoverflow.com/questions/25341509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Airflow parallelism the Local Executor spawns new processes while scheduling tasks. Is there a limit to the number of processes it creates. I needed to change it. I need to know what is the difference between scheduler's "max_threads" and "parallelism" in airflow.cfg ? A: It's 2019 and more updated docs have come out. In short: AIRFLOW__CORE__PARALLELISM is the max number of task instances that can run concurrently across ALL of Airflow (all tasks across all dags) AIRFLOW__CORE__DAG_CONCURRENCY is the max number of task instances allowed to run concurrently FOR A SINGLE SPECIFIC DAG These docs describe it in more detail: According to https://www.astronomer.io/guides/airflow-scaling-workers/: parallelism is the max number of task instances that can run concurrently on airflow. This means that across all running DAGs, no more than 32 tasks will run at one time. And dag_concurrency is the number of task instances allowed to run concurrently within a specific dag. In other words, you could have 2 DAGs running 16 tasks each in parallel, but a single DAG with 50 tasks would also only run 16 tasks - not 32 And, according to https://airflow.apache.org/faq.html#how-to-reduce-airflow-dag-scheduling-latency-in-production: max_threads: Scheduler will spawn multiple threads in parallel to schedule dags. This is controlled by max_threads with default value of 2. User should increase this value to a larger value(e.g numbers of cpus where scheduler runs - 1) in production. But it seems like this last piece shouldn't take up too much time, because it's just the "scheduling" portion. Not the actual running portion. Therefore we didn't see the need to tweak max_threads much, but AIRFLOW__CORE__PARALLELISM and AIRFLOW__CORE__DAG_CONCURRENCY did affect us. A: The scheduler's max_threads is the number of processes to parallelize the scheduler over. The max_threads cannot exceed the cpu count. The LocalExecutor's parallelism is the number of concurrent tasks the LocalExecutor should run. Both the scheduler and the LocalExecutor use python's multiprocessing library for parallelism. A: parallelism: not a very descriptive name. The description says it sets the maximum task instances for the airflow installation, which is a bit ambiguous — if I have two hosts running airflow workers, I'd have airflow installed on two hosts, so that should be two installations, but based on context 'per installation' here means 'per Airflow state database'. I'd name this max_active_tasks. dag_concurrency: Despite the name based on the comment this is actually the task concurrency, and it's per worker. I'd name this max_active_tasks_for_worker (per_worker would suggest that it's a global setting for workers, but I think you can have workers with different values set for this). max_active_runs_per_dag: This one's kinda alright, but since it seems to be just a default value for the matching DAG kwarg, it might be nice to reflect that in the name, something like default_max_active_runs_for_dags So let's move on to the DAG kwargs: concurrency: Again, having a general name like this, coupled with the fact that concurrency is used for something different elsewhere makes this pretty confusing. I'd call this max_active_tasks. max_active_runs: This one sounds alright to me. source: https://issues.apache.org/jira/browse/AIRFLOW-57 max_threads gives the user some control over cpu usage. It specifies scheduler parallelism.
{ "language": "en", "url": "https://stackoverflow.com/questions/38200666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "54" }
Q: Flume NoSuchMethodError pulling Twitter data into HDFS I can't manage to pull Twitter data using Flume into HDFS due to an error I cant't get rid of. command : bin/flume-ng agent --conf ./conf/ -f conf/twitter.conf -Dflume.root.logger=DEBUG,console -n TwitterAgent console : 2020-12-14 11:38:08,662 (conf-file-poller-0) [ERROR - org.apache.flume.node.PollingPropertiesFileConfigurationProvider$FileWatcherRunnable.run(PollingPropertiesFileConfigurationProvider.java:154)] Unhandled error java.lang.NoSuchMethodError: 'boolean twitter4j.conf.Configuration.isStallWarningsEnabled()' at twitter4j.TwitterStreamImpl.<init>(TwitterStreamImpl.java:60) at twitter4j.TwitterStreamFactory.<clinit>(TwitterStreamFactory.java:40) at org.apache.flume.source.twitter.TwitterSource.configure(TwitterSource.java:110) at org.apache.flume.conf.Configurables.configure(Configurables.java:41) at org.apache.flume.node.AbstractConfigurationProvider.loadSources(AbstractConfigurationProvider.java:325) at org.apache.flume.node.AbstractConfigurationProvider.getConfiguration(AbstractConfigurationProvider.java:105) at org.apache.flume.node.PollingPropertiesFileConfigurationProvider$FileWatcherRunnable.run(PollingPropertiesFileConfigurationProvider.java:145) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305) at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834) flume-env.sh : I added manually the flume-sources-1.0-SNAPSHOT.jar into flume/lib. export JAVA_HOME=/usr/lib/jvm/default-java export JAVA_OPTS="-Xms500m -Xmx2000m -Dcom.sun.management.jmxremote" # export JAVA_OPTS="$JAVA_OPTS -Dorg.apache.flume.log.rawdata=true -Dorg.apache.flume.log.printconfig=true " FLUME_CLASSPATH="/home/jb/flume/lib/flume-sources-1.0-SNAPSHOT.jar" twitter.conf : # Naming the components on the current agent. TwitterAgent.sources = Twitter TwitterAgent.channels = MemChannel TwitterAgent.sinks = HDFS # Describing/Configuring the source TwitterAgent.sources.Twitter.type = org.apache.flume.source.twitter.TwitterSource TwitterAgent.sources.Twitter.consumerKey = xxx TwitterAgent.sources.Twitter.consumerSecret = xxx TwitterAgent.sources.Twitter.accessToken = xxx TwitterAgent.sources.Twitter.accessTokenSecret = xxx TwitterAgent.sources.Twitter.keywords = tutorials point,java, bigdata, mapreduce, mahout, hbase, nosql # Describing/Configuring the sink TwitterAgent.sinks.HDFS.type = hdfs TwitterAgent.sinks.HDFS.hdfs.path = hdfs://localhost:9000/user/Hadoop/twitter_data/ TwitterAgent.sinks.HDFS.hdfs.fileType = DataStream TwitterAgent.sinks.HDFS.hdfs.writeFormat = Text TwitterAgent.sinks.HDFS.hdfs.batchSize = 1000 TwitterAgent.sinks.HDFS.hdfs.rollSize = 0 TwitterAgent.sinks.HDFS.hdfs.rollCount = 10000 TwitterAgent.sinks.HDFS.hdfs.minBlockReplicas = 1 # Describing/Configuring the channel TwitterAgent.channels.MemChannel.type = memory TwitterAgent.channels.MemChannel.capacity = 100 TwitterAgent.channels.MemChannel.transactionCapacity = 100 # Binding the source and sink to the channel TwitterAgent.sources.Twitter.channels = MemChannel TwitterAgent.sinks.HDFS.channel = MemChannel OS: Ubuntu Flume: v1.9.0 Hadoop: v3.3.0 A: I managed to make it works. For those who want to know, please read this. Firstly, change the Flume version. I use now flume 1.7.0 https://flume.apache.org/releases/1.7.0.html. But maybe a newer version would work, I don't want to break it down :) Secondly, clone this repo https://github.com/cloudera/cdh-twitter-example. Inside, there is a flume.conf file. I configured it like that : # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # The configuration file needs to define the sources, # the channels and the sinks. # Sources, channels and sinks are defined per agent, # in this case called 'TwitterAgent' TwitterAgent.sources = Twitter TwitterAgent.channels = MemChannel TwitterAgent.sinks = HDFS TwitterAgent.sources.Twitter.type = org.apache.flume.source.twitter.TwitterSource TwitterAgent.sources.Twitter.channels = MemChannel TwitterAgent.sources.Twitter.consumerKey = xx TwitterAgent.sources.Twitter.consumerSecret = xx TwitterAgent.sources.Twitter.accessToken = xx TwitterAgent.sources.Twitter.accessTokenSecret = xx TwitterAgent.sources.Twitter.keywords = hadoop, bigdata TwitterAgent.sources.Twitter.locations = -54.5247541978, 2.05338918702, 9.56001631027, 51.1485061713 TwitterAgent.sources.Twitter.language = fr TwitterAgent.sinks.HDFS.channel = MemChannel TwitterAgent.sinks.HDFS.type = hdfs TwitterAgent.sinks.HDFS.hdfs.path = hdfs://localhost:9000/user/Hadoop/twitter_data/%Y/%m/%d/%H/ #It specifies the File format. File formats that are currently supported are SequenceFile, DataStream or CompressedStream. #The DataStream will not compress the output file and please don’t set codeC. The CompressedStream requires set hdfs.codeC with an available codeC TwitterAgent.sinks.HDFS.hdfs.fileType = DataStream TwitterAgent.sinks.HDFS.hdfs.writeFormat = Text # It specifies the suffix to append to file. For eg, .avro TwitterAgent.sinks.HDFS.hdfs.fileSuffix = .json #It specifies the number of events written to file before it is flushed to HDFS. TwitterAgent.sinks.HDFS.hdfs.batchSize = 10000 # It specifies the file size to trigger roll, in bytes. If it is equal to 0 then it means never roll based on file size. TwitterAgent.sinks.HDFS.hdfs.rollSize = 0 #It specifies the number of events written to the file before it rolled. If it is equal to 0 then it means never roll based on the number of events. TwitterAgent.sinks.HDFS.hdfs.rollCount = 0 #It specifies the number of seconds to wait before rolling the current file. If it is equal to 0 then it means never roll based on the time interval. TwitterAgent.sinks.HDFS.hdfs.rollInterval = 60 TwitterAgent.sinks.HDFS.hdfs.callTimeout = 180000 TwitterAgent.sinks.HDFS.hdfs.useLocalTimeStamp = true TwitterAgent.channels.MemChannel.type = memory TwitterAgent.channels.MemChannel.capacity = 10000 TwitterAgent.channels.MemChannel.transactionCapacity = 1000 Then, modifie the pom.xml (the version): <dependency> <groupId>org.twitter4j</groupId> <artifactId>twitter4j-stream</artifactId> <version>3.0.3</version> </dependency> Package-it with maven cd flume-sources mvn package It creates a target/flume-sources-1.0-SNAPSHOT.jar Copy it to your <YOUR_FLUME_HOME>/lib cp ./target/flume-sources-1.0-SNAPSHOT.jar ~/flume/lib I changed the CLASSPATH in the file I showed earlier talked to : FLUME_CLASSPATH="/home/jb/flume/lib/flume-sources-1.0-SNAPSHOT.jar" Copy the conf/flume.conf we just write into <YOUR_FLUME_HOME>/conf Thirdly, verify if lib/ twitter4j-core.jar, media-support.jar et stream.jar are in version 3.0.3. If not go download them. An finally : cd $FLUME_HOME bin/flume-ng agent --conf ./conf/ -f ./conf/flume.conf -Dflume.root.logger=INFO,console -n TwitterAgent Halleluja : 2020-12-18 02:48:38,805 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.onStatus(TwitterSource.java:173)] Processed 100 docs 2020-12-18 02:48:40,777 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.onStatus(TwitterSource.java:173)] Processed 200 docs 2020-12-18 02:48:42,017 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.onStatus(TwitterSource.java:173)] Processed 300 docs 2020-12-18 02:48:44,772 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.onStatus(TwitterSource.java:173)] Processed 400 docs 2020-12-18 02:48:46,779 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.onStatus(TwitterSource.java:173)] Processed 500 docs 2020-12-18 02:48:47,875 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.onStatus(TwitterSource.java:173)] Processed 600 docs 2020-12-18 02:48:49,852 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.onStatus(TwitterSource.java:173)] Processed 700 docs 2020-12-18 02:48:52,789 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.onStatus(TwitterSource.java:173)] Processed 800 docs 2020-12-18 02:48:54,791 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.onStatus(TwitterSource.java:173)] Processed 900 docs 2020-12-18 02:48:56,805 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.onStatus(TwitterSource.java:173)] Processed 1 000 docs 2020-12-18 02:48:56,805 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.logStats(TwitterSource.java:295)] Total docs indexed: 1 000, total skipped docs: 0 2020-12-18 02:48:56,805 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.logStats(TwitterSource.java:297)] 47 docs/second 2020-12-18 02:48:56,805 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.logStats(TwitterSource.java:299)] Run took 21 seconds and processed: 2020-12-18 02:48:56,806 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.logStats(TwitterSource.java:301)] 0,013 MB/sec sent to index 2020-12-18 02:48:56,807 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.logStats(TwitterSource.java:303)] 0,266 MB text sent to index 2020-12-18 02:48:56,807 (Twitter4J Async Dispatcher[0]) [INFO - org.apache.flume.source.twitter.TwitterSource.logStats(TwitterSource.java:305)] There were 0 exceptions ignored:
{ "language": "en", "url": "https://stackoverflow.com/questions/65295496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Capacity scheduler in Amazon Elastic MapReduce I am totally new to Amazon Elastic MapReduce. I have a need that I want to use my custom scheduler, which is implemented based on Hadoop capacity scheduler, to schedule my jobs in Amazon Elastic MapReduce. According to my current understanding, to achieve this, I can define only one stage in the job flow, and submit my custom jar file via SSH connection to the master node. However, I cannot find how can I edit the xml configuration files, like capacity-scheduler.xml in the master node. Anyone knows how to do that? Moreover, if I want to add the dynamic sizing property onto it, can I dynamically tune the number of task nodes in the cluster, when the job is currently running? Or in per stage, the size of a cluster should remain the same? Thank you so much. A: You should use a bootstrap action to change Hadoop configuration. The following AWS doc can be referenced for Hadoop configuratio bootstrap action. http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/emr-plan-bootstrap.html#PredefinedbootstrapActions_ConfigureHadoop This blog article that I bookmarked also has some info. http://sujee.net/tech/articles/hadoop/amazon-emr-beyond-basics/ For changing the cluster size dynamically, one option is to use the AWS SDK. http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/calling-emr-with-java-sdk.html Using the following interface you can modify the instance count of the instance group. http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/elasticmapreduce/AmazonElasticMapReduce.html
{ "language": "en", "url": "https://stackoverflow.com/questions/25550492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Locked out of SSIS Package I tried to access one of my SSIS packages only to be presented with the error message (Text in square brackets is not literal): Error 1: Error loading Package.dtsx: Failed to decrypt a package that is encrypted with a user key. You may not be the user who encrypted this package, or you are not using the same machine that was used to save the package. [path to file].[Package].dtsx Error: 2 Error loading 'Package.dtsx' : Failed to remove package protection with error 0x8009000B "Key not valid for use in specified state.". This occurs in the CPackage::LoadFromXML method.[path to file].[Package].dtsx It also prevents me entering the package completely Screen When opening package: A: The problem is that your package was encrypted by a user. This could have been you are you loging in to the pc with a diffrent login or from a diffrent machine? Your not going to be able to open it until you figure out who encrypted it or from what account it was encrypted from.
{ "language": "en", "url": "https://stackoverflow.com/questions/20518423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IndexError when plotting pandas dataframe with subplots I'm working a beginner tutorial on this dataset here: http://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/sonar.all-data I've loaded it like so: dataset = pd.read_csv("sonar.all-data.csv", header=None) All the numbers and metrics seem to be correct. If I try to do a histogram or density plot, it works fine. But if I try to do a box plot, I get an exception: C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py in __setitem__(self, key, value) 975 if is_integer(key) and not self.index.inferred_type == "integer": 976 # positional setter --> 977 values[key] = value 978 else: 979 # GH#12862 adding a new key to the Series IndexError: index 0 is out of bounds for axis 0 with size 0 It has drawn the first box plot. I looked in the CSV file and there doesn't seem to be any weird data in the second column. Just doing: dataset.plot(kind='box', subplots=True, layout=(8,8), sharex=False, sharey=False, fontsize=1) plt.show() Versions: scipy: 1.6.2 numpy: 1.20.1 matplotlib: 3.3.4 pandas: 1.2.4 sklearn: 0.24.1 Sample data if link dies 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 0.02,0.0371,0.0428,0.0207,0.0954,0.0986,0.1539,0.1601,0.3109,0.2111,0.1609,0.1582,0.2238,0.0645,0.066,0.2273,0.31,0.2999,0.5078,0.4797 0.0453,0.0523,0.0843,0.0689,0.1183,0.2583,0.2156,0.3481,0.3337,0.2872,0.4918,0.6552,0.6919,0.7797,0.7464,0.9444,1.0,0.8874,0.8024,0.7818 0.0262,0.0582,0.1099,0.1083,0.0974,0.228,0.2431,0.3771,0.5598,0.6194,0.6333,0.706,0.5544,0.532,0.6479,0.6931,0.6759,0.7551,0.8929,0.8619 0.01,0.0171,0.0623,0.0205,0.0205,0.0368,0.1098,0.1276,0.0598,0.1264,0.0881,0.1992,0.0184,0.2261,0.1729,0.2131,0.0693,0.2281,0.406,0.3973 0.0762,0.0666,0.0481,0.0394,0.059,0.0649,0.1209,0.2467,0.3564,0.4459,0.4152,0.3952,0.4256,0.4135,0.4528,0.5326,0.7306,0.6193,0.2032,0.4636 0.0286,0.0453,0.0277,0.0174,0.0384,0.099,0.1201,0.1833,0.2105,0.3039,0.2988,0.425,0.6343,0.8198,1.0,0.9988,0.9508,0.9025,0.7234,0.5122 0.0317,0.0956,0.1321,0.1408,0.1674,0.171,0.0731,0.1401,0.2083,0.3513,0.1786,0.0658,0.0513,0.3752,0.5419,0.544,0.515,0.4262,0.2024,0.4233 0.0519,0.0548,0.0842,0.0319,0.1158,0.0922,0.1027,0.0613,0.1465,0.2838,0.2802,0.3086,0.2657,0.3801,0.5626,0.4376,0.2617,0.1199,0.6676,0.9402 0.0223,0.0375,0.0484,0.0475,0.0647,0.0591,0.0753,0.0098,0.0684,0.1487,0.1156,0.1654,0.3833,0.3598,0.1713,0.1136,0.0349,0.3796,0.7401,0.9925 0.0164,0.0173,0.0347,0.007,0.0187,0.0671,0.1056,0.0697,0.0962,0.0251,0.0801,0.1056,0.1266,0.089,0.0198,0.1133,0.2826,0.3234,0.3238,0.4333 0.0039,0.0063,0.0152,0.0336,0.031,0.0284,0.0396,0.0272,0.0323,0.0452,0.0492,0.0996,0.1424,0.1194,0.0628,0.0907,0.1177,0.1429,0.1223,0.1104 0.0123,0.0309,0.0169,0.0313,0.0358,0.0102,0.0182,0.0579,0.1122,0.0835,0.0548,0.0847,0.2026,0.2557,0.187,0.2032,0.1463,0.2849,0.5824,0.7728 0.0079,0.0086,0.0055,0.025,0.0344,0.0546,0.0528,0.0958,0.1009,0.124,0.1097,0.1215,0.1874,0.3383,0.3227,0.2723,0.3943,0.6432,0.7271,0.8673 0.009,0.0062,0.0253,0.0489,0.1197,0.1589,0.1392,0.0987,0.0955,0.1895,0.1896,0.2547,0.4073,0.2988,0.2901,0.5326,0.4022,0.1571,0.3024,0.3907 0.0124,0.0433,0.0604,0.0449,0.0597,0.0355,0.0531,0.0343,0.1052,0.212,0.164,0.1901,0.3026,0.2019,0.0592,0.239,0.3657,0.3809,0.5929,0.6299 0.0298,0.0615,0.065,0.0921,0.1615,0.2294,0.2176,0.2033,0.1459,0.0852,0.2476,0.3645,0.2777,0.2826,0.3237,0.4335,0.5638,0.4555,0.4348,0.6433 0.0352,0.0116,0.0191,0.0469,0.0737,0.1185,0.1683,0.1541,0.1466,0.2912,0.2328,0.2237,0.247,0.156,0.3491,0.3308,0.2299,0.2203,0.2493,0.4128 0.0192,0.0607,0.0378,0.0774,0.1388,0.0809,0.0568,0.0219,0.1037,0.1186,0.1237,0.1601,0.352,0.4479,0.3769,0.5761,0.6426,0.679,0.7157,0.5466 0.027,0.0092,0.0145,0.0278,0.0412,0.0757,0.1026,0.1138,0.0794,0.152,0.1675,0.137,0.1361,0.1345,0.2144,0.5354,0.683,0.56,0.3093,0.3226 0.0126,0.0149,0.0641,0.1732,0.2565,0.2559,0.2947,0.411,0.4983,0.592,0.5832,0.5419,0.5472,0.5314,0.4981,0.6985,0.8292,0.7839,0.8215,0.9363 A: * *I don't know why, but using subplots=True with numeric column names seems to be causing the issue. *The resolution is to convert the column names to strings import pandas as pd # load the data df = pd.read_csv("sonar_all-data.csv", header=None) # check the column name type print(type(df.columns[0])) [out]: numpy.int64 # convert the column names to strings df.columns = [f'{v}' for v in df.columns] # check the column name type print(type(df.columns[0])) [out]: str # plot the dataframe df.plot(kind='box', layout=(10, 6), figsize=(20, 20), subplots=True) plt.show() * *With subplots=False the plot works with numeric column names
{ "language": "en", "url": "https://stackoverflow.com/questions/67563612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Plotting multiple columns, grouping by date, and adjusting scale So here I what I want, I want to plot 4 columns (Standing, Sitting, Stepping, Cycling) vs Time, and have 1 plot per date. I also want the Y scale to be scaled between 0.5 and 4.5, BUT the Y axis be invisible and a legend saying which color is which. Here is a sample of my data: > head(graph_pre,30) Date Time Axis1 Axis2 Axis3 VM Standing Stepping Cycling New_Sitting Counter 1 2022-05-10 2022-05-10 09:01:00 21 40 2 45.22 0 0 2 0 0 2 2022-05-10 2022-05-10 09:01:01 0 36 1 36.01 0 0 0 1 1 3 2022-05-10 2022-05-10 09:01:02 24 1 0 24.02 0 0 0 1 0 4 2022-05-10 2022-05-10 09:01:03 48 31 4 57.28 0 0 2 0 1 5 2022-05-10 2022-05-10 09:01:04 0 6 0 6.00 0 0 0 1 1 6 2022-05-10 2022-05-10 09:01:05 0 0 0 0.00 0 0 0 1 0 7 2022-05-10 2022-05-10 09:01:06 0 0 0 0.00 0 0 0 1 0 8 2022-05-10 2022-05-10 09:01:07 0 0 0 0.00 0 0 0 1 0 9 2022-05-10 2022-05-10 09:01:08 0 5 2 5.39 0 0 0 1 0 10 2022-05-10 2022-05-10 09:01:09 20 33 3 38.70 0 0 0 1 0 11 2022-05-10 2022-05-10 09:01:10 14 26 29 41.39 0 0 2 0 1 12 2022-05-10 2022-05-10 09:01:11 11 0 4 11.70 0 0 0 1 1 13 2022-05-10 2022-05-10 09:01:12 0 0 0 0.00 0 0 0 1 0 14 2022-05-10 2022-05-10 09:01:13 0 0 0 0.00 0 0 0 1 0 15 2022-05-10 2022-05-10 09:01:14 82 126 113 188.07 0 3 0 0 1 16 2022-05-10 2022-05-10 09:01:15 60 64 47 99.52 0 0 2 0 1 17 2022-05-10 2022-05-10 09:01:16 98 140 236 291.38 0 0 2 0 0 18 2022-05-10 2022-05-10 09:01:17 151 118 221 292.52 0 0 2 0 0 19 2022-05-10 2022-05-10 09:01:18 44 13 99 109.11 0 0 2 0 0 20 2022-05-10 2022-05-10 09:01:19 6 6 53 53.67 0 0 2 0 0 21 2022-05-10 2022-05-10 09:01:20 39 8 65 76.22 0 0 2 0 0 22 2022-05-10 2022-05-10 09:01:21 17 20 57 62.75 0 0 2 0 0 23 2022-05-10 2022-05-10 09:01:22 51 46 269 277.63 0 0 2 0 0 24 2022-05-10 2022-05-10 09:01:23 15 45 82 94.73 0 3 0 0 1 25 2022-05-10 2022-05-10 09:01:24 22 34 4 40.69 0 0 2 0 1 26 2022-05-10 2022-05-10 09:01:25 114 93 41 152.73 0 0 2 0 0 27 2022-05-10 2022-05-10 09:01:26 74 67 92 135.75 0 0 2 0 0 28 2022-05-10 2022-05-10 09:01:27 117 9 40 123.98 0 0 2 0 0 29 2022-05-10 2022-05-10 09:01:28 33 15 0 36.25 0 0 0 1 1 30 2022-05-10 2022-05-10 09:01:29 0 0 0 0.00 0 0 0 1 0 I have the code to separate by date, and to "kinda" plot, but I need it for the 4 columns. graph_pre <- mutate(graph_pre, day = lubridate::day(Date)) ggplot(graph_pre, aes(x = Time, y = Posture))+ geom_point()+ facet_wrap(~day, scales = "free_x") dput(head(graph_pre,30)) structure(list(Date = structure(c(19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122, 19122), class = "Date"), Time = structure(c(1652187660, 1652187661, 1652187662, 1652187663, 1652187664, 1652187665, 1652187666, 1652187667, 1652187668, 1652187669, 1652187670, 1652187671, 1652187672, 1652187673, 1652187674, 1652187675, 1652187676, 1652187677, 1652187678, 1652187679, 1652187680, 1652187681, 1652187682, 1652187683, 1652187684, 1652187685, 1652187686, 1652187687, 1652187688, 1652187689), class = c("POSIXct", "POSIXt"), tzone = ""), Axis1 = c(21, 0, 24, 48, 0, 0, 0, 0, 0, 20, 14, 11, 0, 0, 82, 60, 98, 151, 44, 6, 39, 17, 51, 15, 22, 114, 74, 117, 33, 0), Axis2 = c(40, 36, 1, 31, 6, 0, 0, 0, 5, 33, 26, 0, 0, 0, 126, 64, 140, 118, 13, 6, 8, 20, 46, 45, 34, 93, 67, 9, 15, 0), Axis3 = c(2, 1, 0, 4, 0, 0, 0, 0, 2, 3, 29, 4, 0, 0, 113, 47, 236, 221, 99, 53, 65, 57, 269, 82, 4, 41, 92, 40, 0, 0), VM = c(45.22, 36.01, 24.02, 57.28, 6, 0, 0, 0, 5.39, 38.7, 41.39, 11.7, 0, 0, 188.07, 99.52, 291.38, 292.52, 109.11, 53.67, 76.22, 62.75, 277.63, 94.73, 40.69, 152.73, 135.75, 123.98, 36.25, 0), Standing = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), Stepping = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0), Cycling = c(2, 0, 0, 2, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 0, 0), New_Sitting = c(0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1), Counter = c(0L, 1L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 1L, 0L)), row.names = c(NA, 30L), class = "data.frame") A: First thing, we should pivot_longer to pull the four posture columns into name-value pairs. Here I've put the names into the "Posture" column. Then we can map that to color and use the values for the y axis. I've specified the range in scale_y_continuous, but it could also be done with coord_cartesian(ylim = c(0.5,4.5)) -- the difference will be that the out of range points are filtered out in this way, but are in some sense "still there" if you use the coord_cartesian option. That can make a difference if you are doing a summary step, like geom_boxplot or geom_smooth. Finally, I use theme to specify the y-axis related elements that should be hidden. library(tidyverse) graph %>% mutate(day = lubridate::day(Date)) %>% pivot_longer(Standing:New_Sitting, names_to = "Posture") %>% ggplot(aes(x = Time, y = value, color = Posture))+ geom_point()+ scale_y_continuous(limits = c(0.5,4.5), expand = expansion(0)) + facet_wrap(~day, scales = "free_x") + labs(title = "Posture vs. Time") + theme(axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank(), panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank()) A: Here you go: library(tidyverse) graph_pre_long <- graph_pre %>% pivot_longer(c(Standing, New_Sitting , Stepping, Cycling), names_to = "Posture") ggplot(graph_pre_long, aes(x = Time, y = value, color = Posture))+ geom_point()+ facet_wrap(~day, scales = "free_x") + ylim(.5, 4.5) + theme(axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank())
{ "language": "en", "url": "https://stackoverflow.com/questions/72563268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: RStudio project with network path When trying to make a new Rproject I get the following message: Fatal error: Unexpected exception: rstudio_boost::filesystem::status: Invalid function "//client/" I have the feeling this has something to do with my working directory being a network location and the use of '\' instead of '/'. The address of the folder I try to make a RProject in is something like this: \client\G$\somefolder\somefolder\some folder with spaces\some folder with spaces Does anyone have a workaround when working with such locations?
{ "language": "en", "url": "https://stackoverflow.com/questions/59175862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: checking for spaces with c++ So I've looked around the site for someone having a similar issue but nothing has come up and it's really been perplexing me. #include <iostream> #include <string> using namespace std; string reverse(string s) { int start = 0; for(int i = 0; i < s.length(); i++) { if(s[i]==' '){ string new_word = s.substr(start,i); cout << new_word << endl; start = i+1; } } return "hi"; } int main(){ cout << reverse("Hey there my name is am"); return 0; } When I run the tidbit of code above this is what I get as an output. Hey there my my name is name is am is am hi as you can see the if condition doesn't seem to break on every space. I have also tried isspace(s[i]) and that produced the same result as above. I cannot for the life of me figure out why the if condition is getting skipped on certain white spaces and not others. Has anyone run into a similar issue? A: Take a look at the reference of string::substr. It clearly states that len takes the number of characters to include in the substring. In your code you are passing the index of ' ' which is simply wrong because it does not correspond to len. Instead of using s.substr(start,i), simply use s.substr(start,i - start + 1). That should fix the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/46693707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery validation with multi field I have a form with three select box and one hidden field. I want to validate a string that is created from three select box's value is included in hidden field. Exampe. <form> <select name="s1"> <option value="1">1</option> <option value="2">2</option> </select> <select name="s2"> <option value="1">1</option> <option value="2">2</option> </select> <select name="s3"> <option value="1">1</option> <option value="2">1</option> </select> <input type="hidden" name="result" value="#123#245#" /> </form> I want to valid join(s1.val, s2.val, s3.val) in result.val by jquery validation. How can I do? I know that I need create custom rule. Please help me. A: As mention above in the comment html code: <form> <select name="s1"> <option value="1"> <option selected value="2"> </select> <select name="s2"> <option selected value="1"> <option value="2"> </select> <select name="s3"> <option value="1"> <option selected value="2"> </select> <input type="hidden" name="result" id="hiddenVal" value="#212#" /> </form> javaScript or jquery code: var str = "#"; $('form select').each(function(){ str = str + $(this).val(); }); str +="#"; alert(str); if($("#hiddenVal").val() == str){ alert("yes value from select and value from hidden field is equal"); } jsFiddle A: var concate_string = ""; $('form select').each(function(){ concate_string = concate_string +"#"+$(this).val(); }); concate_string = concate_string +"#"; if($('[name="result"]:eq(0)')==concate_string){ //your action ? }
{ "language": "en", "url": "https://stackoverflow.com/questions/37269990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: git branch -d : Fatal - Couldn't look up commit object for HEAD Say I am in a bare repository (a remote), if I try to delete a branch with git branch -d <branch_name> I get the following error: fatal: Couldn't look up commit object for HEAD Why? Is there a reason why I should be unable to delete branches from a bare repository? A: To avoid this confusion you can use "git push origin --delete branch_name" this deletes remote branch not local branch. A: Make sure you use a capitol D in the command, in this case you would type git branch -D <branch_name>. Note that this will only delete the branch from your local computer If you are trying to delete a remote branch, type git push origin :<branch_name> (remember to add the colon) A: Find the file .git/refs/heads/branch_name in Windows Explorer and directly delete it. A: This only happens when the default branch (the branch HEAD in the bare repository folder is pointing to - usually master) doesn't exist locally. If it does exist - you would be able to delete the branch with branch -d even from a bare repository folder (-d assuming it was merged). If you are working with git worktrees - issuing the command from the worktree may succeed (same condition regarding HEAD of the worktree should be met) A: From Pyrocks's answer: This only happens when the default branch (the branch HEAD in the bare repository folder is pointing to - usually master) doesn't exist locally This case is addressed with Git 2.39 (Q4 2022), which fixes a bug where git branch -d(man) did not work on an orphaned HEAD. See commit eb20e63 (02 Nov 2022) by Jeff King (peff). (Merged by Taylor Blau -- ttaylorr -- in commit 26734da, 18 Nov 2022) branch: gracefully handle '-d' on orphan HEAD Reported-by: Martin von Zweigbergk Signed-off-by: Jeff King Signed-off-by: Taylor Blau When deleting a branch, "git branch -d"(man) has a safety check that ensures the branch is merged to its upstream (if any), or to HEAD. To do that, naturally we try to resolve HEAD to a commit object. If we're on an orphan branch (i.e., HEAD points to a branch that does not yet exist), that will fail, and we'll bail with an error: $ git branch -d to-delete fatal: Couldn't look up commit object for HEAD This usually isn't that big of a deal. The deletion would fail anyway, since the branch isn't merged to HEAD, and you'd need to use "-D" (or "-f"). See "How do I delete a local git branch when it can't look up commit object in 'refs/heads'?", since Git 2.34 (Q4 2021) added the --force option to git branch -d. And doing so skips the HEAD resolution, courtesy of 67affd5 ("git-branch -D(man): make it work even when on a yet-to-be-born branch", 2006-11-24, Git v1.5.0-rc0 -- merge). But there are still two problems: * *The error message isn't very helpful. We should give the usual "not fully merged" message, which points the user at "branch -D". That was a problem even back in 67affd5. *Even without a HEAD, these days it's still possible for the deletion to succeed. After 67affd5, commit 99c419c (branch -d: base the , 2009-12-29, Git v1.7.0-rc0 -- merge) (branch -d: base the "already-merged" safety on the branch it merges with, 2009-12-29) made it OK to delete a branch if it is merged to its upstream. We can fix both by removing the die() in delete_branches() completely, leaving head_rev NULL in this case. It's tempting to stop there, as it appears at first glance that the rest of the code does the right thing with a NULL. But sadly, it's not quite true. We end up feeding the NULL to repo_is_descendant_of(). In the traditional code path there, we call repo_in_merge_bases_many(). It feeds the NULL to repo_parse_commit(), which is smart enough to return an error, and we immediately return "no, it's not a descendant".
{ "language": "en", "url": "https://stackoverflow.com/questions/16651506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: WSO2 P.PaaS : Access APIM Am new to WSO2. I have installed P.PaaS. How do I access APIM? Can you show me an example, please? using phone. Pardon brevity. A: You do not have to install WSO2 Private PaaS to have API Manager. From WSO2 site, you can download stand-alone API Manager or use the hosted version - WSO2 API Cloud. Once you are familiar with API Manager or API Cloud, if you do decide that you want to spawn it within Private PaaS, you can follow this document to locate the corresponding cartridge and subscribe to it. A: Before getting started with WSO2 Private PaaS, it is worth to watch these well-organized, 6-steps video tutorials on "Getting Started With WSO2 Private PaaS". After watching these, you will have a basic understanding, from there you can move forward without any issues. Step 0 - Finding the Documentation Step 1 - Provisioning an EC2 Instance from WSO2 Private PaaS AMI Step 2 - Provisioning the WSO2 Private Platform as a Service Environment Step 3 - Configuring Private Platform as a Service with Tenants Step 4 - Provisioning Application Platform Services Step 5 - Deploying a Web Application on a Private Platform as a Service Environment running on Amazon EC2
{ "language": "en", "url": "https://stackoverflow.com/questions/31742042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }