qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
2,030,886
I am new to WPF and trying to wrap my head around WPF's framework, what it does and does not do for you. To clarify this, I would like to know what is the difference between this: ``` public List<MyCustomObject> MyCustomObjects { get { return (List<MyCustomObject>)GetValue(MyCustomObjectsProperty); } set { SetValue(MyCustomObjectsProperty, value); } } public static readonly DependencyProperty MyCustomObjectsProperty = DependencyProperty.Register("MyCustomObjects", typeof(List<MyCustomObject>), typeof(Main), new UIPropertyMetadata(new List<MyCustomObject>())); ``` and this: ``` public ObservableCollection<MyCustomObject> MyCustomObjects { get; set; } public Main () { MyCustomObjects = new ObservableCollection<<MyCustomObject>(); } ```
2010/01/08
[ "https://Stackoverflow.com/questions/2030886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16241/" ]
In the first case, you're setting up a Dependency Property containing a `List<T>` instance. In the second, you're making a normal CLR property, but having it setup as an `ObservableCollection<T>`. For WPF Data Binding, there are some differences here. Typically, you want all of your properties in the DataContext (which is the object that, by default, things "bind" to) to either implement INotifyPropertyChanged or to be a Dependency Property. This lets the binding framework know when changes are made to that object. Normally, though, you'd only use a Dependency Property if your working with a custom control - it's usually a better idea to have your object to which your data bound be a separate class, assigned to the DataContext. (For details here, see [Josh Smith on MVVM](http://msdn.microsoft.com/en-us/magazine/dd419663.aspx) or [my recent detailed post on MVVM](http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm/)...) However, with a collection, you typically also want the binding system to know when the items within the collection change (ie: an item is added). [`ObservableCollection<T>`](http://msdn.microsoft.com/en-us/library/ms668604.aspx) handles this by implementing [`INotifyCollectionChanged`](http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx). By using the second approach (using an `ObservableCollection<T>`), your UI can tell when items were added or removed from the collection - not just when a new collection is assigned. This lets things work automatically, like a ListBox adding elements when a new item is added to your collection.
45,464,860
In the index.html page I put a .gif before all the tags that laod the files. Then, with JQuery, I removed that loader. But it didn't work. A blank page was shown, because it was waiting for load some .js files. So, I created a script that load the files dynamically. This is the html code: ``` <!doctype html> <html ng-app="myApp"> <head> ...here I'm loading all css files </head> <body> <!-- This is the loader --> <div id="loader" style="background:url('URL_IN_BASE_64')"></div> <div ng-cloak ng-controller="MyAppController"> <div ui-view></div> </div> <script> (function () { var fileList = [ "vendor/angular/angular.min.js", "vendor/jquery/jquery.min.js", "vendor/angular-aria/angular-aria.min.js", .... ] function loadScripts(index) { return function () { var e = document.createElement('script'); e.src = fileList[index]; document.body.appendChild(e); if (index + 1 < fileList.length) { e.onload = loadScripts(index + 1) } else { var loader = document.getElementById("loader"); if (loader) { loader.remove(); } } } } loadScripts(0)(); })(); </script> </body> </html> ``` Now, the problem is that the page first loads all the css files, then angular.min.js, then my gif, and then the other files. Why? How can I immediatly load the gif and, suddently, all other files? [![enter image description here](https://i.stack.imgur.com/yRpig.png)](https://i.stack.imgur.com/yRpig.png) Thank you!
2017/08/02
[ "https://Stackoverflow.com/questions/45464860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210601/" ]
The error `There are multiple modules with names that only differ in casing.` is indicating the wrong import is being targeted with how you are trying to use `Observable`. The import should be with a capital "O" like: `import { Observable } from 'rxjs/Observable';` This will import the individual `Observable` operator, which be used in combination with operators such as `catch` or `throw` on created Observables. ``` import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; ``` To import the full Observable object you'd import it like this: `import { Observable } from 'rxjs/Rx'` **Update:** With newer versions of RxJS (5.5+) operators such as `map()` and `filter()` can used as [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) in combination with `pipe()` rather than chaining. They are imported such as: ``` import { filter, map, catchError } from 'rxjs/operators'; ``` Keep in mind terms such as `throw` are reserved/key words in JavaScript so the RxJS `throw` operator is imported as: ``` import { _throw } from 'rxjs/observable/throw'; ``` **Update:** For newer versions of RxJS (6+), use this: ``` import { throwError } from 'rxjs'; ``` and throw an error like this: ``` if (error.status === 404) return throwError( new NotFoundError(error) ) ```
19,929,215
What does this the following pattern `?:` mean in regexp? It should have something to do with searching for the n-ht occurrence of a pattern, isn't it.
2013/11/12
[ "https://Stackoverflow.com/questions/19929215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1829473/" ]
`?:` denotes non-capturing group: `"Non-capturing groupings, denoted by (?:regexp), still allow the regexp to be treated as a single unit, but don't establish a capturing group at the same time`." <http://perldoc.perl.org/perlretut.html#Non-capturing-groupings>
26,426,574
i am struggle days to find a way for working password strength checker, but still not found solution. I have AjaxBeginForm in partial view for some simple input. Here is my view: @model EntryViewModel ``` <style> input.input-validation-error, textarea.input-validation-error, select.input-validation-error { background: #FEF1EC; border: 1px solid #CD0A0A; } .field-validation-error { color: #C55050; } </style> @using (Ajax.BeginForm("Create", "Entry", new AjaxOptions { HttpMethod = "Post" })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Title, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Title) </div> <div class="editor-label"> @Html.LabelFor(model => model.Username) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Username, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Username) </div> <div class="editor-label"> @Html.LabelFor(model => model.Password) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Password, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Password) </div> <div class="editor-label"> @Html.LabelFor(model => model.Url) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Url, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Url) </div> <div class="editor-label"> @Html.LabelFor(model => model.Description) </div> <div class="editor-field"> @Html.TextAreaFor(model => model.Description, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Description) </div> @Html.HiddenFor(model => model.CategoryId) <div class="modal-footer"> <a href="#" data-dismiss="modal" class="btn">Close</a> <input class=" btn btn-primary" id="submitButton" type="submit" value="Create" /> </div> } ``` I've tried with many methods, including KendoUI, but none of works. Any suggestions for solution?
2014/10/17
[ "https://Stackoverflow.com/questions/26426574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4110768/" ]
What about the [Google Password Strength API?](http://www.codeproject.com/Articles/19245/Google-Password-Strength-API).
41,973,109
I m using following code. I am reading a json file name is "hassan.json". If i read this file in controller through $http everything works fine. but i want to use the data that i read from file, again and again in different controller so i made a service for this. but **in service when i read data from that json file through $http.get()** and in return when i call that service method in my controller and console.log(data) **it returns me this in console "e {$$state: object}."** *this is **Controller**:* ``` app.controller('showdata', function($scope, service){ $scope.mydata = service.getData().then(function(user){ $scope.mydata = (user.data); console.log(($scope.mydata)); }); }); ``` *this is **service** i'm using:* ``` app.service('service', function($http, $q){ var outData; this.getData = function() { if (this.outData === undefined) { var deferred = $q.defer(); $http.get('jsons/hassan.json') .then(function(data){ this.outData = data; deferred.resolve(data); }, function(err) { deferred.reject(err); }); return deferred.promise; } else { return this.outData; } } }); ```
2017/02/01
[ "https://Stackoverflow.com/questions/41973109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7498727/" ]
`$http` by itself is a promise, so there is no need in `$q`, try to rewrite your code using `$http`'s `cache`: ``` app.controller('showdata', function($scope, service){ service.getData().then(function(user) { // no need to call user.data, service handles this $scope.mydata = user; console.log($scope.mydata); }).catch(function (err) { // handle errors here if needed }); }); ``` and ``` app.service('service', function($http){ this.getData = function() { return $http({ method: 'GET', url: 'jsons/hassan.json', // cache will ensure calling ajax only once cache: true }).then(function (data) { // this will ensure that we get clear data in our service response return data.data; }); }; }}); ```
10,423,703
I'm currently working on an application that uses a Windows Form GUI. The main work of the application will be performed on an additional thread - but it is possible that it will be dependent on the state of the form. Because of this, before I create the thread I must make sure that the form is **completely** loaded. Also, I need to make sure the thread is terminated **before** the form begins closing. Possible solutions for this problem might be overriding the `OnShown` and `OnFormClosing` methods. Does the `OnShow` method really gets called only after ALL of the assets of the form have been loaded? And what about the `OnFormClosing` - can I be sure that any code executed in this method will be performed **before** the form begins close / dispose?
2012/05/03
[ "https://Stackoverflow.com/questions/10423703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940723/" ]
I suggest you read through the WinForms event ordering as posted on MSDN: <http://msdn.microsoft.com/en-us/library/86faxx0d.aspx>
7,512,343
I'm new in 3D games developing so I have kinda dummy question - how to move a mesh in 3D engine (under moving I mean a walking animation). And how to dress some skin on it? What I have: 1. open source 3D OpenGL engine - NinevehGL <http://nineveh.gl/>. It's super easy to load a mesh to. I' pretty sure it will be awesome engine when it will be released! 2. a mesh model of the human. <http://www.2shared.com/file/RTBEvSbf/female.html> (it's mesh of a female that I downloaded from some open source web site..) 3. found a web site from which I can download skeleton animation in formats: dao (COLLADA) , XML , BVH (?) - <http://www.animeeple.com/details/bcd6ac4b-ebc9-465e-9233-ed0220387fb9> 4. what I stuck on (see attached image) ![enter image description here](https://i.stack.imgur.com/8dx0t.png) So, how can I join all these things and make simple game when dressed human will walk forward and backward?
2011/09/22
[ "https://Stackoverflow.com/questions/7512343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145792/" ]
The problem is difficult to answer, because it would require knowledge of the engine's API. Also you can't just stick a skeletal animation onto some mesh. You need some connection between both, a process called rigging, in which you add "bones" (also called armatures) to the mesh. This is an artistic process, done in a 3D modeller. Then you need to implement a skeletal animation system, which is a far too complex task to answer in a single Stackoverflow answer (it involves animation curve evaluation, quaternion interpolation, skinning matrices, etc.). You should break down your question into smaller pieces.
250,903
I have SQL server 2017. I have one 3 TB size database there. Somehow due to long running transaction the database got stuck 'IN Recovery' mode after SQL server Restarted. When I checked the sql error logs it says 2 189 255 seconds remaining (Phase 2 of 3) completed which is almost 25 days. My goal is to bring the database online even if I lose some data. So I've ran below commands but no luck. ``` USE [master] GO RESTORE DATABASE test WITH RECOVERY --Msg 3101, Level 16, State 1, Line 6 --Exclusive access could not be obtained because the database is in use. --Msg 3013, Level 16, State 1, Line 6 --RESTORE DATABASE is terminating abnormally. ALTER DATABASE test SET EMERGENCY; GO --Msg 5011, Level 14, State 7, Line 13 --User does not have permission to alter database 'DragonDriveConnect', the database does not exist, or the database is not in a state that allows access checks. --Msg 5069, Level 16, State 1, Line 13 --ALTER DATABASE statement failed. DBCC CHECKDB (DragonDriveConnect, REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS; GO --Msg 922, Level 14, State 1, Line 22 --Database 'DragonDriveConnect' is being recovered. Waiting until recovery is finished. ``` At last I've tried to Delete the database too but that is also not working and giving me error saying Cant Delete. How do I get out of this situation?
2019/10/12
[ "https://dba.stackexchange.com/questions/250903", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/192946/" ]
The error you're seeing in the SQL Server Error Log is this one: > > Recovery of database 'CrashTestDummy' (9) is 0% complete (approximately 42 seconds remain). Phase 2 of 3. This is an informational message only. No user action is required > > > More generically, it will say: > > Recovery of database '`{Database Name}`' (`{Database ID}`) is `{N}`% complete (approximately `{N}` seconds remain). Phase `{N}` of 3. This is an informational message only. No user action is required > > > Because your database was not shut down cleanly on restart, the database *must* go through "crash recovery". This is required to ensure the database remains consistent. When the database is not shut down cleanly, SQL Server must make sure that transactions written to the transaction log have been reconciled properly against the data files. All transactions are guaranteed to be written to the transaction log. However, updating data is initially only done in memory. Updates to the physical data files are done asynchronously via a [checkpoint](https://learn.microsoft.com/en-us/sql/relational-databases/logs/database-checkpoints-sql-server). The asynchronous nature of the data file updates are why a crash or unclean shutdown requires extra work on startup. As indicated by the error message, there are three phases to the recovery. Each of these is essentially a pass through the transaction log: 1. Analysis 2. Redo / Roll Forward 3. Undo / Rollback ### Analysis This phase is simply to review the transaction log & determine what needs to be done. It will identify when the most recent checkpoint was, and what transactions might need to be rolled forward or back to ensure consistency. ### Redo / Roll Forward Completed transactions from the transaction log need to be reviewed to ensure the data file has been completed updated. Without this, changes that were only in-memory might have been lost. This phase will take those transactions that were committed after the most recent checkpoint and redo them, to ensure they are persisted to the data file. If you are using SQL Server Enterprise edition, [Fast Recovery](https://www.sqlskills.com/blogs/paul/fast-recovery-used/) will allow the database to come online & be available after this phase of recovery. If you are not using Enterprise Edition, the database will not be available until after the Undo phase has completed. ### Undo / Rollback Transactions from the transaction log that were rolled back, or were uncommitted at the time of "crash" must be rolled back. SQL Server must verify that if uncommitted changes were made to the data file, they are undone. Without this, a rolled back change could be partially committed, violating the [ACID principles](https://en.wikipedia.org/wiki/ACID) of the database. This phase will perform the rollback of any transactions that were uncommitted at the time of crash, or were rolled back after the final checkpoint. So what can you do about it? ---------------------------- While the database is in recovery, attempts to bring the database online via a `RESTORE` command like this will fail: ``` RESTORE DATABASE CrashTestDummy WITH RECOVERY; ``` SQL Server is *already* attempting to do this. The `RESTORE...WITH RECOVERY;` will simply put the database through the exact same steps in order to bring the database online in a consistent manner. ### Be patient The right thing to do is just be patient. This part of the message from the error log is the one that you should pay attention to: > > No user action is required > > > Note, too, that the time remaining is an estimate. In my experience, it is wildly inaccurate. Sometimes the time remaining will grow larger, rather than reducing. Sometimes it will report a very long completion time, and suddenly complete very fast. Its just an estimate. ### Can you just "throw away" your transaction log and start fresh? **I advise against it.** I would suggest you never, ever do this with a production database. There is a procedure to attach a database without a transaction log, and ask SQL Server to `ATTACH_REBUILD_LOG`. I won't detail all the steps, but the "punchline" for that procedure is to do this: ``` CREATE DATABASE CrashTestDummy ON (FILENAME = 'C:\SQL\MSSQL15.MSSQLSERVER\MSSQL\DATA\CrashTestDummy.mdf') FOR ATTACH_REBUILD_LOG; ``` Running this on a crashed database may result in this error: > > The log cannot be rebuilt because there were open transactions/users when the database was shutdown, no checkpoint occurred to the database, or the database was read-only. This error could occur if the transaction log file was manually deleted or lost due to a hardware or environment failure. > Msg 1813, Level 16, State 2, Line 5 > Could not open new database 'CrashTestDummy'. CREATE DATABASE is aborted. > > > In which case, you're stuck. You'll need to use the original transaction log & be patient. Just wait for it to recover.
1,899,529
i have just started using adobe livecycle . i dont need to understand the livecycle with a developers perspective but as of now i have to get into testing livecycle applications. where should i get started so that i understand basics of livecycle. for instance i would like to know what a watched folder is . please refer me to livecycle tutorial
2009/12/14
[ "https://Stackoverflow.com/questions/1899529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/213574/" ]
I'd suggest checking out the Adobe Evangelism Team's Tour de LifeCycle reference: <http://www.adobe.com/devnet/livecycle/tourdelivecycle/> I've found it to be a good centralized point for blogs, turorials and documentation on all things LiveCycle.
2,683
Time to get it straight once and for all. When do you / do you not make a Brocho on dessert in a meal (where you washed)?
2010/08/27
[ "https://judaism.stackexchange.com/questions/2683", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/128/" ]
There are a lot of different practices (and I believe a stira in the Mishna Brurah), and it may depend on your practice. BUT: Here's what I was told in yeshiva: Fresh fruit (including "ha'adama fruit" like watermelon and bananas), candy, ice cream -- all get a bracha. Anything mezonos, anything liquid, cooked fruit -- included with the meal.
4,312,391
I'm looking for possibly efficient algorithm to detect "win" situation in a gomoku (five-in-a-row) game, played on a 19x19 board. Win situation happens when one of the players manages to get five and NO MORE than five "stones" in a row (horizontal, diagonal or vertical). I have the following data easily accessible: * previous moves ("stones") of both players stored in a 2d array (can be also json notation object), with variables "B" and "W" to difference players from each other, * "coordinates" of the incoming move (move.x, move.y), * number of moves each player did I'm doing it in javascript, but any solution that doesn't use low-level stuff like memory allocation nor higher-level (python) array operations would be good. I've found similiar question ( [Detect winning game in nought and crosses](https://stackoverflow.com/questions/2670217/detect-winning-game-in-nought-and-crosses) ), but solutions given there only refer to small boards (5x5 etc).
2010/11/30
[ "https://Stackoverflow.com/questions/4312391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183918/" ]
A simple to understand solution without excessive loops (only pseudocode provided, let me know if you need more explanation): I assume your 2-d array runs like this: ``` board = [ [...], [...], [...], ... ]; ``` I.e. the inner arrays represent the horizontal rows of the board. I also assume that the array is populated by "b", "w", and "x", representing black pieces, white pieces, and empty squares, respectively. My solution is somewhat divide-and-conquer, so I've divided it into the 3 cases below. Bear with me, it may seem more complex than simply running multiple nested loops at first, but the concept is easy to understand, read, and with the right approach, quite simple to code. Horizontal lines ================ Let's first consider the case of detecting a win situation ONLY if the line is horizontal - this is the easiest. First, join a row into a single string, using something like `board[0].join("")`. Do this for each row. You end up with an array like this: ``` rows = [ "bxwwwbx...", "xxxwbxx...", "wwbbbbx...", ... ] ``` Now join THIS array, but inserting an "x" between elements to separate each row: `rows.join("x")`. Now you have one long string representing your board, and it's simply a matter of applying a regexp to find consecutive "w" or "b" of exactly 5 length: `superString.test(/(b{5,5})|(w{5,5})/)`. If the test returns `true` you have a win situation. If not, let's move on to vertical lines. Vertical lines ============== You want to reuse the above code, so create a function `testRows` for it. Testing for vertical lines is exactly the same process, but you want to **transpose** the board, so that rows become columns and columns become rows. Then you apply the same `testRows` function. Transposing can be done by copying values into a new 2-d array, or by writing a simple `getCol` function and using that within `testRows`. Diagonal lines ============== Again, we want to reuse the `testRows' function. A diagonal such as this: ``` b x x x x x b x x x x x b x x x x x b x x x x x b ``` Can be converted to a vertical such as this: ``` b x x x x b x x x b x x b x b ``` By shifting row `i` by `i` positions. Now it's a matter of transposing and we are back at testing for horizontals. You'll need to do the same for diagonals that go the other way, but this time shift row `i` by `length - 1 - i` positions, or in your case, `18 - i` positions. Functional javascript ===================== As a side note, my solution fits nicely with functional programming, which means that it can be quite easily coded if you have functional programming tools with you, though it's not necessary. I recommend using [underscore.js](http://documentcloud.github.com/underscore/) as it's quite likely you'll need basic tools like `map`, `reduce` and `filter` in many different game algorithms. For example, my section on testing horizontal lines can be written in one line of javascript with the use of `map`: ``` _(board).map(function (row) {return row.join("")}).join("x").test(/(b{5,5})|(w{5,5})/); ```
4,400,908
I have a package com.supercorp.killerapp and within it is a package(com.supercorp.killerapp.views) if I'm not creating the app with the guiformbuilder: * How do I set the icon of a button on a JInternalFrame that is in the views directory? * In general, how do I access images in a different folder? * Should all my images be contained in a seperate folder? The syntax I'm using is: ``` JButton iconButton = new JButton(new ImageIcon("page_delete.png")); ``` The button isn't displaying the image.
2010/12/09
[ "https://Stackoverflow.com/questions/4400908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383986/" ]
I put in the jar that contains my application, in a package called `com.example.GreatApp.resources` and then load it using: ``` getClassLoader().getResourceAsStream( "com/example/GreatApp/resource/icon.png");` ``` **Update. Full example** ``` /** * Creates and returns an ImageIcon from the resource in jar. * @param location resource location in the jar, * like 'com/example/GreatApp/res/icon.png' or null if it was not found. */ public ImageIcon createImageIconFromResource(String location) throws java.io.IOException { java.io.InputStream input = getClassLoader().getResourceAsStream( location); // or throw an ioexception here aka `file not found` if(input == null) return null; return new ImageIcon(ImageIO.read(input)); } ```
66,453,074
I'm trying to use `mark_text` to create a stacked text in a stacked bar chart. I would like to label each bar with the value of 'Time'. Is it possible to have text marks in the corresponding stack of a stacked area chart? Here's how I create bar & text chart: ``` bar = alt.Chart(df_pivot, title = {'text' :'How do people spend their time?', 'subtitle' : 'Average of minutes per day from time-use diaries for people between 15 and 64'}).mark_bar().transform_calculate( filtered="datum.Category == 'Paid work'" ).transform_joinaggregate(sort_val="sum(filtered)", groupby=["Country"] ).encode( x=alt.X('Time', stack='zero'), y=alt.Y('Country', sort=alt.SortField('sort_val', order='descending')), color=alt.Color('Category:N', sort=CatOrder), order=alt.Order('color_Category_sort_index:Q'), tooltip=['Country', 'Category', 'Time'] ).interactive() bar ``` [![bar](https://i.stack.imgur.com/hcBUd.png)](https://i.stack.imgur.com/hcBUd.png) ``` text = alt.Chart(df_pivot).mark_text(align='center', baseline='middle', color='black').transform_calculate( filtered="datum.Category == 'Paid work'" ).transform_joinaggregate(sort_val="sum(filtered)", groupby=["Country"] ).encode( x=alt.X('Time:Q', stack='zero'), y=alt.Y('Country', sort=alt.SortField('sort_val', order='descending')), detail='Category:N', text=alt.Text('Time:Q', format='.0f') ) bar + text ``` [![bar+text](https://i.stack.imgur.com/sIxD8.png)](https://i.stack.imgur.com/sIxD8.png) **Issue:** * The text is not in its proper stack & The order of the text is also wrong. * The Y sorting is reset and they are no longer sorted as expected. It's not that I don't understand why I have these issues. I'm new to this platform, the source code via my notebook: <https://www.kaggle.com/interphuoc0101/times-use>. Thanks a lot.
2021/03/03
[ "https://Stackoverflow.com/questions/66453074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15308498/" ]
Your bar chart specifies a stack order: ``` order=alt.Order('color_Category_sort_index:Q'), ``` You should add a matching `order` encoding to your text layer to ensure the text appears in the same order.
37,134,911
What is the best way to compare two string without case sensitive using c#? Am using the below codes. ``` string b = "b"; int c = string.Compare(a, b); ```
2016/05/10
[ "https://Stackoverflow.com/questions/37134911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3916803/" ]
By explicitly specifying it: ``` int c = string.Compare(a, b, StringComparison.InvariantCultureIgnoreCase) ```
62,870,072
I have a router sample below , now how will I get the details of that when it is done navigating on that page or when it reach the user page ?. I wanted to check on my user.component.ts that the navigation comes from this [routerLink]="['user', user.id, 'details']" ``` [routerLink]="['user', user.id, 'details']" ```
2020/07/13
[ "https://Stackoverflow.com/questions/62870072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using `itertools.groupby` ``` from itertools import groupby result = [] for m,n in groupby(a, lambda x: x[1]): n = list(n) result.extend(n + [[sum(int(i) for i, _ in n), ""]]) print(result) ``` **Output:** ``` [['45', '00128'], ['88', '00128'], ['87', '00128'], [220, ''], ['50', '88292'], ['69', '88292'], [119, ''], ['70', '72415'], ['93', '72415'], ['79', '72415'], [242, '']] ``` Edit as per comment ``` for m,n in groupby(a, lambda x: x[1]): n = list(n) val_1, val_2, val_3 = 0, 0, 0 for i in n: val_1 += int(i[0]) #val_2, val_3.... result.extend(n + [[val_1, ""]]) ``` If you can use `numpy` then the sum of axis 0 is simpler **Ex:** ``` for m,n in groupby(a, lambda x: x[1]): n = np.array(list(n), dtype=int) print(np.delete(np.sum(n, axis=0), 1)) ``` --- ``` np.delete --> Delete element in index 1 np.sum with axis=0 --> sum element in column. ```
47,695
AFAIK people like scripting because it's easier, and it makes development cycle faster. But what about when games are shipped. No one expects shipped binaries to be changed, unless there is an update or a DLC. So why developers don't compile their script files before shipping? **Potential benefits:** 1. Faster run time 2. Obfuscating binary a little mode and I can't think of any possible draw backs. Examples: 1. Civilization 5 had lots of lua scripts inside their assets folder. 2. Angry birds also had a lot those scripts along side binary. 3. Age of Mythology had lots of xs scripts for their AI. 4. Civilization 4 had lots of python scripts. I'm pretty sure the list could have gotten a lot longer if I had more games installed on my device.
2013/01/19
[ "https://gamedev.stackexchange.com/questions/47695", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/7328/" ]
I suspect it's because that one of the advantages of using scripts over C++ code is that there is no compile process so it makes for quick and easy editing during development. Lua also gains no run-time performance from compiling it off-line. [It's just load time it speeds up.](http://www.lua.org/manual/4.0/luac.html) Adding the extra compile step in then just slows down development and makes the process more error-prone (e.g. the script can get out of sync with the compiled version). Compiling all the scripts just before you ship the game has obvious risks that you did all your testing with the scripts in their uncompiled state, and shipping something that's not been tested is a bad idea. On any single player game there's also no harm done if your users want to modify the game in some way by editing scripts.
64,216,176
1. I have a Table In SQL. 2. Then I have created one Table-Valued Function named GetTaxDataSet. So when I execute that function with the Where condition, I'm getting the dataset values that I need. 3. Now, I'm trying to get the dataset using the SQL Table-Valued function using C# code. ``` DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(); string sqlSelect = "Select * From [dbo].[fn_GetTaxRuleDataSet] (@TaxID, @TaxRulesID)"; SqlCommand cmd = new SqlCommand(sqlSelect, Sqlconn); SqlParameter param1 = new SqlParameter(); param1.ParameterName = "@ID"; param1.SqlDbType = SqlDbType.Int; param1.ParameterName = "@TaxID"; param1.SqlDbType = SqlDbType.Int; param1.ParameterName = "TaxRulesID"; param1.SqlDbType = SqlDbType.Int; param1.ParameterName = "@EffectiveDate"; param1.SqlDbType = SqlDbType.DateTime; cmd.Parameters.Add(param1); Sqlconn.Open(); //Executing The SqlCommand. SqlDataReader dr = cmd.ExecuteReader(); Console.ReadLine(); ``` Can you guys suggest me with right code? Thanks
2020/10/05
[ "https://Stackoverflow.com/questions/64216176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14376508/" ]
Hope this answer helps you. Just keep in mind that when you create a method with its return type of DataSet, it should also be set to receive the DataSet. ``` public DataSet GetData() { DataSet output = new DataSet(); try { SqlConnection sqlConn = new SqlConnection(connectionString); if (sqlConn.State == ConnectionState.Closed) { sqlConn.Open(); } String sqlSelect = "Select * From [dbo].[fn_GetTaxRuleDataSet] (@TaxID, @TaxRulesID)"; SqlCommand cmd = new SqlCommand(sqlSelect, sqlConn); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(output); sqlConn.Close(); } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", ex.Message, true); return (null); } return output; } ```
12,259,544
When I enter to my site without using a Google result, I can access without any problems, with and without www. But, when I access throught the Google results, redirects to Google again. This is one of my affected sites: **Before Google Search:** <http://somesite.com/> - All OK <http://www.somesite.com/> - All OK **Using Google Search** <https://www.google.com?q=somesite> - First link refirects to Google **After using Google results, if I access to site typing it:** <http://somesite.com/> - All OK <http://www.somesite.com/> - Redirects to Google
2012/09/04
[ "https://Stackoverflow.com/questions/12259544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989868/" ]
use Firebug(FireFox Add on) to see what is happening ! It will give you more clarity on what is happening.
12,118
How can i set my laptop with ubuntu 10.04 to autoconnect to Wi-Fi (with pass, WPA2-Personal), when i on my laptop without asking password on wi-fi? I wont on my laptop and start surfing without enter pass of my wi-fi.
2010/11/08
[ "https://askubuntu.com/questions/12118", "https://askubuntu.com", "https://askubuntu.com/users/2964/" ]
You must be logged-in to get a network connection with NetworkManager. One ugly workaround is to configure the gdm to auto-login, this poses a security threat if someone can physically access your laptop. **System > Administration > Login Screen** ![alt text](https://i.stack.imgur.com/NWs4d.png) Unlock and select "Login as automatically"
15,935,752
I am using ec2 instance @ ubuntu . I am trying to automatically do "git pull" after i launched a new instance from my AMI. The repo dir is already in my AMI, all i need is update the repo. what i am doing now is I put "git pull origin master" in rc.local.... but it doesn't work....
2013/04/10
[ "https://Stackoverflow.com/questions/15935752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1410231/" ]
`git --git-dir=some/dir/.git pull origin master` should work
41,978,225
I have fetched an HTML page,How i can replace relative img src with these URLs absolute? In my content html: ``` <img width="23" height="23" class="img" src="/static/img/facebook.png" alt="Facebook"> <img width="23" height="23" class="img" src="/static/img/tw.png" alt="tw"> ``` (Paths not stable) ``` <img width="130" =="" height="200" alt="" src="http://otherdomain/files/ads/00905819.gif"> ``` in html contents i have other images src with absolute src,i want change only relative src images. ex : ``` <img width="23" height="23" class="img" src="/static/img/facebook.png" alt="Facebook"> <img width="23" height="23" class="img" src="/images/xx.png" alt="xxx"> ``` to ``` <img width="23" height="23" class="img" src="http://example.com/static/img/facebook.png" alt="Facebook"> ``` My preg\_replace: ``` $html = preg_replace("(]*src\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)", '$1http://www.example.com$2$3', $x1); ``` But this replace all images src
2017/02/01
[ "https://Stackoverflow.com/questions/41978225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3950500/" ]
Try using this code, it should work in your case. ``` $html = str_replace('src="/static', 'src="http://example.com/static', $html); ```
67,952,611
I want to run an npm script that needs the server to be up for the duration the script is being run. My script is like this ``` "scripts" :{ "start": "tsc && node dist/app.js"} ``` That is my basic script to start my server which works fine. However, I have a script within my node project called `get_data.js` that I will use to collect data and save to a database (`npm run save_data`). I want the server to be stopped when `get_data.js` finishes as I am just interested in getting data. ``` "scripts" :{ "start": "tsc && node dist/app.js", "save_data": "tsc && node dist/get_data.js" } ``` Obviously my `save_data` script is not right. Any ideas or recommendation what I can do?
2021/06/12
[ "https://Stackoverflow.com/questions/67952611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652113/" ]
I may be misinterpreting your question but i think what you want is `process.exit(0);` At the end of "get\_data.js" or whenever youve determined that you want the process to end in your script. (Although i should note that get\_data.js should run its course and end itself unless there is something in your code that is preventing this.)
36,228,977
I want to pass a dictionary as an additional argument to a function. The function is to be applied over each row of a data frame. So I use 'apply'. Below I have a small example of my attempt: ``` import pandas as pd import numpy as np def fun(df_row, dict1): return df_row['A']*2*max(dict1['x']) df = pd.DataFrame(np.random.randn(6,2),columns=list('AB')) dict_test = {'x': [1,2,3,4], 'y': [5,6,7,8]} df['D'] = df.apply(fun, args = (dict_test), axis = 1) ``` I get the following error message: ('fun() takes exactly 1 argument (3 given)', u'occurred at index 0') I use \*\*dict1 to indicate key-value pairs in the function 'fun' Curiously enough if I pass two arguements, things work fine ``` def fun(df_row, dict1, dict2): return df_row['A']*2*max(dict1['x']) df = pd.DataFrame(np.random.randn(6,2),columns=list('AB')) dict_test = {'x': [1,2,3,4], 'y': [5,6,7,8]} df['D'] = df.apply(fun, axis = 1, args = (dict_test, dict_test)) ```
2016/03/25
[ "https://Stackoverflow.com/questions/36228977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/491410/" ]
The problem is that you are not passing a tuple, `(dict_test)` is not a tuple, it's just the same as `dict_test`. You want a tuple with `dict_test` as the only element, that is `(dict_test,)`. ``` df['D'] = df.apply(fun, args=(dict_test,), axis=1) ```
79,947
I'm trying to read 4 ints in C in a golfing challenge and I'm bothered by the length of the code that I need to solve it: ``` scanf("%d%d%d%d",&w,&x,&y,&z) ``` that's 29 chars, which is huge considering that my total code size is 101 chars. I can rid of the first int since I don't really need it, so I get this code: ``` scanf("%*d%d%d%d",&x,&y,&z) ``` which is 27 chars, but it's still lengthy. So my question is, is there any other way (tricks, functions, K&R stuff) to read ints that I don't know of that could help me reduce this bit of code? --- Some users have reported that my question is similar to [Tips for golfing in C](https://codegolf.stackexchange.com/questions/2203/tips-for-golfing-in-c) While this topic contain a lot of useful information to shorten C codes, it isn't relevant to my actual use case since it doesn't provide a better way to read inputs. I don't know if there is actually a better way than scanf to read multiple integers (that's why I'm asking the question in the first place), but if there is, I think my question is relevant and is sufficiently different than global tips and tricks. If there is no better way, my question can still be useful in the near future if someone find a better solution. I'm looking for a full program (so no function trick) and all libraries possible. It needs to be C, not C++. Currently, my whole program looks like this: ``` main(w,x,y,z){scanf("%*d%d%d%d",&x,&y,&z)} ``` Any tricks are welcome, as long as they shorten the code (this is code golf) and work in C rather than C++.
2016/05/15
[ "https://codegolf.stackexchange.com/questions/79947", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/53734/" ]
Thanks to @DialFrost for drawing my attention to this question. I believe for reading 4 numbers your solution is optimal. However, I found a solution that saves bytes when reading 5 or more numbers at a time. It will also consume the entire input (i.e. it can't be used in a loop). Depending on the context it might help you with only 4 variables too If you define your variables in a sequence like this: ```c a,b,c,d,e;main(){ ``` In this case, the variables will be layed out in successive memory addresses, we can abuse that. ```c for(;~scanf("%d",&a+e);e++); ``` Full program: ```c // new a,b,c,d,e;main(){for(;~scanf("%d",&a+e);e++);} // original a,b,c,d;main(e){scanf("%d%d%d%d%d",&a,&b,&c,&d,&e);} ``` This 29 byte segment will paste all the input in successive variables starting in `a`. We re-use `e`, (the last variable) as the index variable. This saves declaring one variable. Size comparison --------------- | Number of inputs | Original | New | Original (full program) | new (full program) | | --- | --- | --- | --- | --- | | 1 | 14 | 28 | 24 | 38 | | 2 | 19 | 28 | 31 | 40 | | 3 | 24 | 28 | 38 | 42 | | 4 | 29 | 28 | 45 | 44 | | 5 | 34 | 28 | 52 | 46 | | 6 | 39 | 28 | 59 | 48 | Note that the new method gains a 1 byte disadvantage in full programs because you can't use function arguments, however, this doesn't matter if you can use another variable as the argument to `main`. Note there is also a slot in the initialization portion of the for loop. If you can put another expression there this method can save 1 byte even with only 4 arguments. [Try it online!](https://tio.run/##S9YtSU7@n6iTpJOsk6KTap2bmJmnoVn9Py2/SMPawKY4OTEvTUNJNUVJRy1RO1XTOlVbW9P6f0FRZl4JWBwGlXTgZmha1/43VDBSMFYwUTAFAA "C (tcc) – Try It Online") @JDT ponted out you can save 1 byte at the cost of having 1 added to `e` at the end: ``` for(;0<scanf("%d",&a+e++);); ```
715,485
> > Evaluate $\lim\_{x \to 0+} \frac{x-\sin x}{(x \sin x)^{3/2}}$ > > > This is an exercise after introducing L'Hopital's rule. I directly apply L'Hopital's rule three times and it becomes more and more complex. So I try to substitute $t=\sqrt x$ but there's a square root remained in the denominator $t^3 (sin(t^2))^{3/2}$,apply L'Hopital's rule three times or more I still can't solve it. So I think maybe I have to write $t=\sqrt{x \sin x}$ ,but I can't find a way to convert $x- \sin x$ to a function about $t$ . Thanks in advance.
2014/03/17
[ "https://math.stackexchange.com/questions/715485", "https://math.stackexchange.com", "https://math.stackexchange.com/users/94283/" ]
$$\begin{align\*} \lim\_{x\to0^+}\frac{x-\sin x}{(x\sin x)^{3/2}}&=\lim\_{x\to0^+}\left(\frac{x}{\sin x}\right)^{3/2}\frac{x-\sin x}{x^3}\\ &=\lim\_{x\to0^+}\frac{x-\sin x}{x^3} \end{align\*}$$ And apply L'Hopital's rule three times.
3,702,859
I am new to javascript/jquery . I have a small question. I have some thing like the following in the java script file. ``` <button id="button1" onclick=click() /> <button id="button2" onclick=click() /> <button id="button3" onclick=click() /> ``` so the click function looks like the follwoing ``` click(id){ /do some thing } ``` so my question is when ever the button is clicked how can we pass the button id to the function. ``` <button id="button1" onclick=click("how to pass the button id value to this function") /> ``` how can we pass the button id like "button1" to the click function when ever the button is clicked.. I would really appreciate if some one can answer to my question.. Thanks, Swati
2010/09/13
[ "https://Stackoverflow.com/questions/3702859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436175/" ]
I advise the use of unobtrusive script as always, but if you *have* to have it inline use `this`, for example: ``` <button id="button1" onclick="click(this.id)" /> ``` The unobtrusive way would look like this: ``` $("button").click(function() { click(this.id); }); ```
14,292,555
I am using spring's BasicDataSource in my applicationContext.xml as following: ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" default-autowire="byType"> <bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/school" /> <property name="username" value="root" /> <property name="password" value="" /> <property name="initialSize" value="5" /> <property name="maxActive" value="10" /> </bean> </beans> ``` and when i use this bean in controller as follows: ``` package admin.controller; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import javax.inject.*; @Controller public class Welcome { @Inject BasicDataSource datasource; private static final String WELCOME_PAGE = "welcome"; @RequestMapping("/") public String welcome(ModelMap model){ Connection con=null; PreparedStatement stmt =null; String testQuery = "INSERT INTO ADMIN(ID,USER_NAME,PASSWORD,FIRST_NAME,LAST_NAME) VALUES(?,?,?,?,?)"; try { con = datasource.getConnection(); stmt = con.prepareStatement(testQuery); stmt.setInt(1, 4); stmt.setString(2, "ij"); stmt.setString(3, "kl"); stmt.setString(4, "mn"); stmt.setString(5, "op"); stmt.execute(); //con.commit(); } catch (SQLException e) { e.printStackTrace(); } finally{ try { if(con!=null) con.close(); } catch (SQLException e) { e.printStackTrace(); } } return WELCOME_PAGE; } } ``` then it gives me a nullpointer exception at line: datasource.getConnection(); connection details are 100% correct because when i create a new instance of BasicDatasource inside the controller and add details using its setter methods(eg: datasource.setDriverClassName etc.) then it connects to the database and execute the query without any problem. but when i want to use the bean from application context then it is giving me a null pointer exception.
2013/01/12
[ "https://Stackoverflow.com/questions/14292555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970255/" ]
They are all [unprintable control characters](http://en.wikipedia.org/wiki/C0_and_C1_control_codes), the box is just a way to print them. Another option is to not show them at all but then you wouldn't know about them as easily. There's * `0x1F` Unit separator * `0x7F` Delete * `0x01` Start of Heading * `0x1C` File Separator (You can read all of the above from the boxes already) Since these are almost never used in text, you should probably not treat them as text. If you look at the meaning of them as control characters, they don't make sense even as control characters.
34,491,004
I have a database with a large set of email addresses. Because of a bug in a script, the database is full of wrong email addresses. These addresses has a known pattern. They are made of a true email address, concatenated with a string in the beginning. This string is itself a part of the email address. Example: The correct email should be: ``` [email protected] ``` Instead I have: ``` [email protected] ``` Or also: ``` [email protected] ``` How can I identify these addresses? I thought about creating a regexp that finds repeating text inside a string, but I could find out how to do it. Any ideas?
2015/12/28
[ "https://Stackoverflow.com/questions/34491004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2837813/" ]
You can use below query to take care of `[email protected]` pattern, This will first find the last\_name and then replace that with null in the first part before first `.`. ``` concat(replace(substr(email,1,locate('.',email)),substr(email,LOCATE('.',email)+1,locate('@',email)-LOCATE('.',email)-1),'') , substr(email,locate('.',email)+1,length(email)) ) ``` **See SQL Fiddle example here** <http://sqlfiddle.com/#!9/24fba/2> But this will not take care of `[email protected]` pattern.
54,878,621
I have source code like the code below. I'm trying to scrape out the '11 tigers' string. I'm new to xpath, can anyone suggest how to get it using selenium or beatiful soup? I'm thinking `driver.find_element_by_xpath` or `soup.find_all`. source: ``` <div class="count-box fixed_when_handheld s-vgLeft0_5 s-vgPullBottom1 s-vgRight0_5 u-colorGray6 u-fontSize18 u-fontWeight200" style="display: block;"> <div class="label-container u-floatLeft">11 tigers</div> <div class="u-floatRight"> <div class="hide_when_tablet hide_when_desktop s-vgLeft0_5 s-vgRight0_5 u-textAlignCenter"> <div class="js-show-handheld-filters c-button c-button--md c-button--blue s-vgRight1"> Filter </div> <div class="js-save-handheld-filters c-button c-button--md c-button--transparent"> Save </div> </div> </div> <div class="cb"></div> </div> ```
2019/02/26
[ "https://Stackoverflow.com/questions/54878621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5978130/" ]
You can use same `.count-box .label-container` css selector for both BS and Selenium. BS: ``` page = BeautifulSoup(yourhtml, "html.parser") # if you need first one label = page.select_one(".count-box .label-container").text # if you need all labels = page.select(".count-box .label-container") for label in labels: print(label.text) ``` Selenium: ``` labels = driver.find_elements_by_css_selector(".count-box .label-container") for label in labels: print(label.text) ```
15,922,823
I am implementing a file-based queue of serialized objects, using C#. * `Push()` will serialize an object as binary and append it to the end of the file. * `Pop()` should deserialize an object from the beginning of the file (this part I got working). Then, the deserialized part should be removed from the file, making the next object to be "first". From the standpoint of file system, that would just mean copying file header several bytes further on the disk, and then moving the "beginning of the file" pointer. The question is how to implement this in C#? Is it at all possible?
2013/04/10
[ "https://Stackoverflow.com/questions/15922823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/236660/" ]
Yes see the log eip <http://camel.apache.org/logeip.html> This allows you to log human readable messages to the log. You could have spotted it, by the green tip box on the log component page: <http://camel.apache.org/log>
3,802,669
> > $m^3-3m^2+2m$ is divisible by $79$ and $83$ where $m>2$. Find the > lowest value of $m$ > > > $m^3-3m^2+2m$ is the product of three consecutive integers. Both $79$ and $83$ are prime numbers. The product of three consecutive positive integers is divisible by $6$. So, $m^3-3m^2+2m$ is a multiple of $lcm(6,79,83)=39342$. But I can't go any further. What would be the correct approach to solve problems like this?
2020/08/25
[ "https://math.stackexchange.com/questions/3802669", "https://math.stackexchange.com", "https://math.stackexchange.com/users/632797/" ]
The brute force method: as $m^3−3m^2+2m=m(m−1)(m−2)$, and $79,83$ are prime, you can just solve the following nine congruences: $m\equiv\alpha\pmod{79}$, $m\equiv\beta\pmod{83}$, where $\alpha,\beta\in\{0,1,2\}$. This is possible as per Chinese Remainder Theorem, and the smallest of the nine $m$'s you will get (greater than $2$) is the solution. It is easy to solve all those congruences simultaneously: per [Wikipedia](https://en.wikipedia.org/wiki/Chinese_remainder_theorem#Existence_(direct_construction)), we first express $1$ as $1=79u+83v$, where $u,v$ can be found using Euclidean algorithm. In this case, as $4=83-79$ and $1=20\cdot 4-79$, we have $1=20\cdot 83-21\cdot 79$. Now, $m\equiv\alpha\pmod{79}$ and $m\equiv\beta\pmod{83}$ resolves as $m\equiv 20\cdot 83\alpha-21\cdot 79\beta\pmod{79\cdot 83}$, i.e. $m\equiv 1660\alpha-1659\beta\pmod{6557}$. This gives us the following table: $$\begin{array}{r|r|r|r}\alpha&\beta&m\pmod{6557}&\text{smallest }m\gt 2\\\hline0&0&0&6557\\0&1&4898&4898\\0&2&3239&3239\\1&0&1660&1660\\1&1&1&6558\\1&2&4899&4899\\2&0&3320&3320\\2&1&1661&1661\\2&2&2&6559\end{array}$$ so the smallest solution seems to be $m=1660$.
66,196,249
How do I increase the textarea height automatically so that the columns on the left and right are of the same height? [![enter image description here](https://i.stack.imgur.com/zgJt2.png)](https://i.stack.imgur.com/zgJt2.png)
2021/02/14
[ "https://Stackoverflow.com/questions/66196249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14372041/" ]
The task is to split a string separated by '+'. In the below example, the delimiter ',' is used. Splitting a string into tokens is a very old task. There are many many solutions available. All have different properties. Some are difficult to understand, some are hard to develop, some are more complex, slower or faster or more flexible or not. Alternatives 1. Handcrafted, many variants, using pointers or iterators, maybe hard to develop and error prone. 2. Using old style `std::strtok` function. Maybe unsafe. Maybe should not be used any longer 3. `std::getline`. Most used implementation. But actually a "misuse" and not so flexible 4. Using dedicated modern function, specifically developed for this purpose, most flexible and good fitting into the STL environment and algortithm landscape. But slower. Please see 4 examples in one piece of code. ``` #include <iostream> #include <fstream> #include <sstream> #include <string> #include <regex> #include <algorithm> #include <iterator> #include <cstring> #include <forward_list> #include <deque> using Container = std::vector<std::string>; std::regex delimiter{ "," }; int main() { // Some function to print the contents of an STL container auto print = [](const auto& container) -> void { std::copy(container.begin(), container.end(), std::ostream_iterator<std::decay<decltype(*container.begin())>::type>(std::cout, " ")); std::cout << '\n'; }; // Example 1: Handcrafted ------------------------------------------------------------------------- { // Our string that we want to split std::string stringToSplit{ "aaa,bbb,ccc,ddd" }; Container c{}; // Search for comma, then take the part and add to the result for (size_t i{ 0U }, startpos{ 0U }; i <= stringToSplit.size(); ++i) { // So, if there is a comma or the end of the string if ((stringToSplit[i] == ',') || (i == (stringToSplit.size()))) { // Copy substring c.push_back(stringToSplit.substr(startpos, i - startpos)); startpos = i + 1; } } print(c); } // Example 2: Using very old strtok function ---------------------------------------------------------- { // Our string that we want to split std::string stringToSplit{ "aaa,bbb,ccc,ddd" }; Container c{}; // Split string into parts in a simple for loop #pragma warning(suppress : 4996) for (char* token = std::strtok(const_cast<char*>(stringToSplit.data()), ","); token != nullptr; token = std::strtok(nullptr, ",")) { c.push_back(token); } print(c); } // Example 3: Very often used std::getline with additional istringstream ------------------------------------------------ { // Our string that we want to split std::string stringToSplit{ "aaa,bbb,ccc,ddd" }; Container c{}; // Put string in an std::istringstream std::istringstream iss{ stringToSplit }; // Extract string parts in simple for loop for (std::string part{}; std::getline(iss, part, ','); c.push_back(part)) ; print(c); } // Example 4: Most flexible iterator solution ------------------------------------------------ { // Our string that we want to split std::string stringToSplit{ "aaa,bbb,ccc,ddd" }; Container c(std::sregex_token_iterator(stringToSplit.begin(), stringToSplit.end(), delimiter, -1), {}); // // Everything done already with range constructor. No additional code needed. // print(c); // Works also with other containers in the same way std::forward_list<std::string> c2(std::sregex_token_iterator(stringToSplit.begin(), stringToSplit.end(), delimiter, -1), {}); print(c2); // And works with algorithms std::deque<std::string> c3{}; std::copy(std::sregex_token_iterator(stringToSplit.begin(), stringToSplit.end(), delimiter, -1), {}, std::back_inserter(c3)); print(c3); } return 0; } ```
65,140,738
We have a case like this. ```java class A{ class foo{ //Map with a lot of entries private HashMap<String,String> dataMap; public updater(){ // updates dataMap // takes several milliseconds } public someAction(){ // needs to perform read on dataMap // several times, in a long process // which takes several milliseconds } } ``` The issue is, both someAction and updater both can be called simultaneously, someAction is a more frequent method. If updater is called, it can replace a lot of values from dataMap. And we need consistency in readAction. If the method starts with old dataMap, then all reads should happen with old dataMap. ```java class foo{ //Map with a lot of entries private HashMap<String,String> dataMap; public updater(){ var updateDataMap = clone(dataMap); // some way to clone data from map // updates updateDataMap instead of dataMap // takes several milliseconds this.dataMap = updateDataMap; } public someAction(){ var readDataMap = dataMap; // reads from readDataMap instead of dataMap // several times, in a long process // which takes several milliseconds } } ``` Will this ensure consistency? I believe that the clone method will allocate a different area in memory and new references will happen from there. And are there going to be any performance impacts? And will the memory of oldDataMap be released after it has been used? If this is the correct way, are there are any other efficient way to achieve the same?
2020/12/04
[ "https://Stackoverflow.com/questions/65140738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14008598/" ]
You can use [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) API. In Angular you can write a directive for handle that: ``` @Directive({ selector: '[lazySrc]' }) export class ImgDataDirective implements OnInit, OnChanges { @Input('lazySrc') src: string; constructor( private _elRef: ElementRef, private _renderer: Renderer2, @Inject(PLATFORM_ID) private platformId: Object ) {} ngOnChanges(changes: SimpleChanges): void { this._loadImage(); } ngOnInit(): void { this._renderer.setAttribute(this._elRef.nativeElement, 'src', PLACEHOLDER); if (isPlatformBrowser(this.platformId)) { const obs = new IntersectionObserver(entries => { entries.forEach(({ isIntersecting }) => { if (isIntersecting) { this._loadImage(); obs.unobserve(this._elRef.nativeElement); } }); }); obs.observe(this._elRef.nativeElement); } } private _loadImage() { this._renderer.setAttribute(this._elRef.nativeElement, 'src', this.src); } } ```
66,147,347
I'm trying to create a new column, "condition\_any", in `df` with {data.table} that is TRUE if any of the of the 3 conditions are TRUE, per row. I tried using `any(.SD)` with no luck: ``` library(data.table) df <- data.table(id = 1:3, date = Sys.Date() + 1:3, condition1 = c(T, F, F), condition2 = c(T, F, T), condition3 = c(F, F, F)) df[, condition_any := any(.SD), .SDcols = patterns("^condition")] Error in FUN(X[[i]], ...) : only defined on a data frame with all numeric variables ``` Any ideas on how I can get this to work, I thought it would be an easy thing to do. Thanks Expected output: ``` id date condition1 condition2 condition3 condition_any 1: 1 2021-02-12 TRUE TRUE FALSE TRUE 2: 2 2021-02-13 FALSE FALSE FALSE FALSE 3: 3 2021-02-14 FALSE TRUE FALSE TRUE ```
2021/02/11
[ "https://Stackoverflow.com/questions/66147347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8675075/" ]
This also doesn't use `any` but is a nice way to do it, ``` df[, condition_any := Reduce('|', .SD), .SDcols = patterns("^condition")] ```
160,370
I have been tasked with ensuring the CIS Bechmark on Amazon Linux 2016.09. Does anyone know of an examination tool that will output the difference between the current and the benchmark? Unfortunately I cannot use one of the existing marketplace AMI's.
2017/05/25
[ "https://security.stackexchange.com/questions/160370", "https://security.stackexchange.com", "https://security.stackexchange.com/users/149282/" ]
[Lynis](https://cisofy.com/lynis/) is the open source alternative which not only does CIS but few other compliance tests as well. The ability to modify the code to generate custom reports is handy for large number of systems.
9,626,995
Ive been using the 'event' parameter for my KeyboardEvents and MouseEvents in a recent project ive been working on for my course (VERY BASIC). Im not entirely sure on what the 'e' part of e:KeyboardEvent actually does, and ive been asked to find out what information the parameter 'e' can actually access when using it. Im sorry if the questions badly written, its been a long night! **EDIT: If A method takes the parameter (e:KeyboardEvent). what information could we access through the use of the parameter e?**
2012/03/09
[ "https://Stackoverflow.com/questions/9626995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256106/" ]
I'm assuming you have some function like this ``` function someFunction(e:KeyboardEvent):void { // code } ``` You can access any information from the [KeyboardEvent](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/KeyboardEvent.html) class, just the same as if the parameter were called "event". The name of the parameter doesn't affect what you can access through it; the type does. Edit: "e" is just the *name* of the variable - it could be called `fred`, `banana`, or `tyrannosaurusRex`, and it would make no difference. The thing that determines what sort of information you can access through a variable is its *type* - in this case, `KeyboardEvent`. If you follow the `KeyboardEvent` link above, you will see documentation for the `KeyboardEvent` class, which will tell you all the things you can do with it. For example, one of the properties of `KeyboardEvent` is `keyCode`, which tells you which key was pressed: ``` if (e.keyCode == 32) { // 32 is the keyCode for spacebar, so spacebar was pressed } ```
6,728,212
This is the point, I have a WCF service, it is working now. So I begin to work on the client side. And when the application was running, then an exception showed up: timeout. So I began to read, there are many examples about how to keep the connection alive, but, also I found that the best way, is create channel, use it, and dispose it. And honestly, I liked that. So, now reading about the best way to close the channel, there are two links that could be useful to anybody who needs them: [1. Clean up clients, the right way](http://geekswithblogs.net/SoftwareDoneRight/archive/2008/05/23/clean-up-wcf-clients--the-right-way.aspx) [2. Using Func](http://www.atrevido.net/blog/2007/08/13/Practical+Functional+C+Part+II.aspx) In the first link, this is the example: ``` IIdentityService _identitySvc; ... if (_identitySvc != null) { ((IClientChannel)_identitySvc).Close(); ((IDisposable)_identitySvc).Dispose(); _identitySvc = null; } ``` So, if the channel is not null, then is closed, disposed, and assign null. But I have a little question. In this example the channel has a .Close() method, but, in my case, intellisense is not showing a Close() method. It only exists in the factory object. So I believe I have to write it. But, in the interface that has the contracts or the class that implemets it??. And, what should be doing this method??. Now, the next link, this has something I haven't try before. `Func<T>`. And after reading the goal, it's quite interesting. It creates a funcion that with lambdas creates the channel, uses it, closes it, and dipose it. This example implements that function like a `Using()` statement. It's really good, and a excellent improvement. But, I need a little help, to be honest, I can't understand the function, so, a little explanatino from an expert will be very useful. This is the function: ``` TReturn UseService<TChannel, TReturn>(Func<TChannel, TReturn> code) { var chanFactory = GetCachedFactory<TChannel>(); TChannel channel = chanFactory.CreateChannel(); bool error = true; try { TReturn result = code(channel); ((IClientChannel)channel).Close(); error = false; return result; } finally { if (error) { ((IClientChannel)channel).Abort(); } } } ``` And this is how is being used: ``` int a = 1; int b = 2; int sum = UseService((ICalculator calc) => calc.Add(a, b)); Console.WriteLine(sum); ``` Yep, I think is really, really good, I'd like to understand it to use it in the project I have. And, like always, I hope this could be helpful to a lot of people.
2011/07/18
[ "https://Stackoverflow.com/questions/6728212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/818519/" ]
the UseService method accepts a delegate, which uses the channel to send request. The delegate has a parameter and a return value. You can put the call to WCF service in the delegate. And in the UseService, it creates the channel and pass the channel to the delegate, which should be provided by you. After finishing the call, it closes the channel.
37,945,115
I am using Rfacebook to extract some content from Facebook's API through R. I somehow get sometimes posts two or three times back even though they only appear 1 time in facebook. Probably some problem with my crawler. I extracted already a lot of data and don't want to rerun the crawling. So I was thinking about cleaning the data I have. Is there any handy way with dplyr to do that? The data I got looks like the following: ``` Name message created_time id Sam Hello World 2013-03-09T19:52:22+0000 26937808 Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800 Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800 Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800 Sam Whats Up? 2013-03-09T19:53:22+0000 26937806 Sam Whats Up? 2013-03-09T19:53:22+0000 26937806 Florence Hi guys! 2013-03-09T19:55:16+0000 25688232 Steff How r u? 2013-03-09T19:59:16+0000 64552194 ``` I would now like to have a new data frame in which every post only appears one time so that the three "double" posts from Nicky will be reduced to only one and the two double posts from Sam also get reduced to one post. Any idea or suggestion how to do this in R? It seems like facebook is giving unique ids to posts and comments as well as that the time stamps are almost unique in my data. Both would be working for identification. However, it remains unclear to me how to best do the transformation... Any help with this is highly appreciated! Thanks!
2016/06/21
[ "https://Stackoverflow.com/questions/37945115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5223902/" ]
You just need a brief wait to wait until the `DIV` that contains the error message appears. The code below is working for me. ``` WebDriver driver = new FirefoxDriver(); driver.get("https://app.ghostinspector.com/account/create"); driver.findElement(By.id("input-firstName")).sendKeys("Johnny"); driver.findElement(By.id("input-lastName")).sendKeys("Smith"); driver.findElement(By.id("input-email")).sendKeys("[email protected]"); driver.findElement(By.id("input-password")).sendKeys("abc123"); driver.findElement(By.id("input-terms")).click(); driver.findElement(By.id("btn-create")).click(); WebDriverWait wait = new WebDriverWait(driver, 10); WebElement e = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div[ng-show='errors']"))); System.out.println(e.getText()); ```
17,887,757
I am using JQuery for autocompleting the search textbox with my database. The problem rises when I want to access the text of the search textbox in query string since I am using html textbox. To make it in context, either I have to use `runat="server"` or I can use `asp:Textbox` but in both the cases my autocompleting feature stops working. Here is the aspx code: ``` <div id="search-location-wrapper"> <input type="text" id="txtSearch" class="autosuggest" /> <div id="search-submit-container"> <asp:Button ID="btnSearch" runat="server" Text="Search" onclick="btnSearch_Click"></asp:Button> </div> </div> ``` C# Code: ``` protected void btnSearch_Click(object sender, EventArgs e) { string location = txtSearch.ToString(); /*Here is the error: txtSearch is not in current context */ int id = Convert.ToInt32(ddlCategory.SelectedValue); string url = "SearchResults.aspx?Id="+id+"&location="+location; Response.Redirect(url); } ```
2013/07/26
[ "https://Stackoverflow.com/questions/17887757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/550927/" ]
In short, yes - this will standardize the dummy variables, but there's a reason for doing so. The `glmnet` function takes a matrix as an input for its `X` parameter, not a data frame, so it doesn't make the distinction for `factor` columns which you may have if the parameter was a `data.frame`. If you take a look at the R function, glmnet codes the `standardize` parameter internally as ``` isd = as.integer(standardize) ``` Which converts the R boolean to a 0 or 1 integer to feed to any of the internal FORTRAN functions (elnet, lognet, et. al.) If you go even further by examining the FORTRAN code (fixed width - old school!), you'll see the following block: ``` subroutine standard1 (no,ni,x,y,w,isd,intr,ju,xm,xs,ym,ys,xv,jerr) 989 real x(no,ni),y(no),w(no),xm(ni),xs(ni),xv(ni) 989 integer ju(ni) 990 real, dimension (:), allocatable :: v allocate(v(1:no),stat=jerr) 993 if(jerr.ne.0) return 994 w=w/sum(w) 994 v=sqrt(w) 995 if(intr .ne. 0)goto 10651 995 ym=0.0 995 y=v*y 996 ys=sqrt(dot_product(y,y)-dot_product(v,y)**2) 996 y=y/ys 997 10660 do 10661 j=1,ni 997 if(ju(j).eq.0)goto 10661 997 xm(j)=0.0 997 x(:,j)=v*x(:,j) 998 xv(j)=dot_product(x(:,j),x(:,j)) 999 if(isd .eq. 0)goto 10681 999 xbq=dot_product(v,x(:,j))**2 999 vc=xv(j)-xbq 1000 xs(j)=sqrt(vc) 1000 x(:,j)=x(:,j)/xs(j) 1000 xv(j)=1.0+xbq/vc 1001 goto 10691 1002 ``` Take a look at the lines marked 1000 - this is basically applying the standardization formula to the `X` matrix. Now statistically speaking, one does not generally standardize categorical variables to retain the interpretability of the estimated regressors. However, as pointed out by Tibshirani [here](http://statweb.stanford.edu/~tibs/lasso/fulltext.pdf), "The lasso method requires initial standardization of the regressors, so that the penalization scheme is fair to all regressors. For categorical regressors, one codes the regressor with dummy variables and then standardizes the dummy variables" - so while this causes arbitrary scaling between continuous and categorical variables, it's done for equal penalization treatment.
13,376,682
I have a BizTalk 2010 project containing an orchestration that needs to make an HTTP Post and then examine the Status Code and Body of the Response to determine the next course of action. I can configure the orchestration and port to make the HTTP Post, but I am unable to receive a response. Should I be using a send / receive port or correlation? What schema should I be using for the response (I believe the response is the standard http response: <http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6>).
2012/11/14
[ "https://Stackoverflow.com/questions/13376682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1823305/" ]
If you are looking for a kind of notification ( not in content of the message) that the message has been successfully transmitted, you can set the logical send port property in the orchestration as follows: ``` "Delivery Notification" = Transmitted ``` And delivery failures can be handled using the Microsoft.XLANGs.BaseTypes.DeliveryFailureException