_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d16701
val
It's okay. It's probably not ideal, but anyone interested in hacking your sessions will look for it in the other places you might have put it anyway (cookies, etc.), so you're not lowering the bar much if at all. (Java EE stuff does this as a fallback if cookies don't work, appending ;jsessionid=xxx to every URL.) The important thing is to ensure that it's difficult to hijack sessions, regardless of how the hacker got the session ID. (By binding the session to the source IP address and checking that at the server level on every request, using sane timeouts, and the various other techniques.) A: I would argue that it's perfectly fine. My rationale is that PHP sends it in clear text and so does the browser when you use sessions. Here's what happens in the background when you make a web request: > GET / HTTP/1.1 Host: example.com Accept: */* < HTTP/1.1 200 OK < Date: Tue, 12 Jul 2011 07:00:26 GMT < Server: Apache < Set-Cookie: PHP_SESSID=2873fd75b29380bc9d775e43e41dc898; path=/; domain=example.com; secure < P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM" < Vary: Accept-Encoding < Content-Length: 5538 < Content-Type: text/html; charset=UTF-8 As you can see, I made a GET request and the server response with Set-Cookie: PHP_SESSID= followed by my session ID. Anyone that's "sniffing" the request who would be able to see the session ID in the JavaScript would be able to get it from the headers too. The only thing to worry about would be things like malicious browser plugins and other exploits that are not likely but can be avoided by properly securing your code. I'd recommend that you look at http://phpsec.org/projects/guide/4.html for some tips and information on session hijacking. A: I recently did this while working on a google earth plugin project. It didn't use the browser's cookies so I had to pass session variables in the url with javascript which grabbed it from the html. There are no security issues. A: i think it is not severe issue but still is not properly coded.one should not let anyone know ids if possible.From your code it looks like you have encoded your id.you should add some more info in your encoding to make it more secure. for an example one can easily decode "encode(15)" but it is very difficult to decode "encode('php is great'.15.' codint language')"; A: No, I don't think it's ok. You're making the session_id easily accessible, which in turns makes session-hijacking attacks very easy (and likely). If you need the session_id, there are some methods to mitigate the possibility of session hijacking, consider regenerating the session_id after the upload, or having a secondary check to validate the user. If you're trying to prevent unauthorized uploads, I'd consider something a little different - perhaps generating a one-time unique string of characters that is associated with the user for the duration of the upload, but not the session_id itself. Too much risk in that, IMO.
unknown
d16702
val
Found the problem. I extended QLPreviewController and in viewWillDisappear i didn't call [super viewWillDisappear] which was causing the video to still playback in the background.
unknown
d16703
val
I found a solution to my problem as posted in this GitHub issue. My problem was caused by the fact that my model outputs a tfp.Independent distribution, which means the log_prob is returned as a scalar sum over individual log_probs for each element of the tensor. This prevents weighting individual elements of the loss function. You can get the underlying tensor of log_prob values by accessing the .distribution attribute of the tfp.Independent object - this underlying distribution object treats each element of the loss as an independent random variable, rather than a single random variable with multiple values. By writing a loss function that inherits from tf.keras.losses.Loss, the resulting weighted tensor is implicitly reduced, returning the weighted mean of log_prob values rather than the sum, e.g.: class NLL(tf.keras.losses.Loss): ''' Custom keras loss/metric for weighted negative log likelihood ''' def __call__(self, y_true, y_pred, sample_weight=None): # This tensor is implicitly reduced by TensorFlow # by taking the mean over all weighted elements return -y_pred.distribution.log_prob(y_true) * sample_weight
unknown
d16704
val
I solved this issue by enabling DO Not Track option in Firefox. Menu -> Options-> Privacy-> click manage your Do Not Track Settings and uncheck the box. Restart the Firefox. Hope this helps someone facing similar issue in future.
unknown
d16705
val
You can check the current time, and loop until it passes the specified hour before shutting down, e.g.: import os import time def shutdown(threshold=7): while time.gmtime().tm_hour < threshold: time.sleep(300) # wait 5 minutes os.system("shutdown /s /t 90") and call it as you call it now. The threshold sets the hour after which to proceed with the shutdown, by default its set to 7. Keep in mind, tho, that it uses your system clock (most probably UTC) so you have to account for the difference when specifying your threshold. Of course, if you don't want to shutdown the system at all, even when the time passes, if the script was called before the threshold, you can use: def shutdown(threshold=7): if time.gmtime().tm_hour >= threshold: os.system("shutdown /s /t 90") instead.
unknown
d16706
val
The DataGrid does not support horizontal item scrolling. One very mad idea would be to use the Toolkit's LayoutTransformer to rotate the whole grid by 90degrees then template all the headers and cells with a LayoutTransfomer to rotate their contents back. One issue (likely of many, if it's even possible) would be the scrollbar would appear on the top rather than the bottom. You might be able to sort that out with further templating.
unknown
d16707
val
A direct approach to stubbing out the SecureRandom method in rspec would be as follows: before { allow(SecureRandom).to receive(:hex).with(4).and_return('abcd1234') } You can then check that 'abcd1234' is stored in the database. In order to keep the test DRY, you may also wish to reference this as a variable, e.g. let(:random_value) { 'abcd1234' }.
unknown
d16708
val
Which value is bound to your datagrid? streenheidsprijs or eenheidsprijs? The string value is formatted to 2 decimal places, but the double variable doesn't inherit the number of decimal places to show. In actual fact, there is no value in the lines to re-parse the string values that have been formatted: eenheidsprijs = Double.Parse(streenheidsprijs) The data grid columns should either be bound to the string values that have been formatted to 2 dp, or you should configure the display properties of the columns in the data grid so that they only show two decimal places. A: You can provide a format string to the default cell style of the column. In your case, the format F2 would be preferable. At run-time: myDataGridView.Columns("myColumnName").DefaultCellStyle.Format = "F2" At design-time: Sample form Public Class Form1 Public Sub New() Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US") Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US") Me.InitializeComponent() Me.ClientSize = New Size(350, 400) Me.column1 = New DataGridViewTextBoxColumn With {.Name = "Column1", .HeaderText = "Double (F2)", .ValueType = GetType(Double), .Width = 100} Me.column1.DefaultCellStyle.Format = "F2" Me.column2 = New DataGridViewTextBoxColumn With {.Name = "Column2", .HeaderText = "Double (F8)", .ValueType = GetType(Double), .AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, .MinimumWidth = 100} Me.column2.DefaultCellStyle.Format = "F8" Me.grid = New DataGridView With {.Dock = DockStyle.Fill} Me.grid.Columns.AddRange(Me.column1, Me.column2) For i As Double = 0.0R To 9.0R : Me.grid.Rows.Add(i, i) : Next Me.Controls.Add(Me.grid) End Sub Private WithEvents grid As DataGridView Private WithEvents column1 As DataGridViewTextBoxColumn Private WithEvents column2 As DataGridViewTextBoxColumn End Class
unknown
d16709
val
x5c is fairly simple. you need to remove -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- from the Self-Signed Certificate generated from mkjwk.org OR you can use the PHP script: https://control7.net/JWK/generate.php paste your Public and Private Keypair and Self-Signed Certificate into the textbox and click Go
unknown
d16710
val
i have the right script for you but can't upload here lol. import schedule you can use this library for scheduling a function(the upload function), but you will can to keep your program run all the time. or using the microsoft scheduler , which will schedule your whole program.
unknown
d16711
val
echo "<form action='index.php' method='post'> Your Post:<br/> <textarea name='comments' cols='100' rows='100'>".htmlspecialchars($_GET["msg"])."</textarea> <br/> <input type=submit value='submit'> </FORM>"; textarea seems an odd container for it, but that's your call A: I think I get it. header("location:editPost.php?msg=$message"); doesn't smells good. If you simply want to fix the problem use http://php.net/manual/en/function.urlencode.php and when getting the value http://www.php.net/manual/en/function.urldecode.php You're getting a post request and then forwarding it using header location. That's definitely a poor way to do it. The problem probably is taking place when you pass the parameter as a query string on ?msg=$message Since MVC and alike applications (n-layered apps) is the standard now. You should not do that spaghetti code, mixing html and php and using header as your FrontController dispatcher. I'd suggest you to use for example, the SLIM framework. If you do not want to learn this. You should at least follow the standards described here. E.g.: <?php // index.php // load and initialize any global libraries require_once 'model.php'; require_once 'controllers.php'; // route the request internally $uri = $_SERVER['REQUEST_URI']; if ($uri == '/index.php') { list_action(); } elseif ($uri == '/index.php/show' && isset($_GET['id'])) { show_action($_GET['id']); } else { header('Status: 404 Not Found'); echo '<html><body><h1>Page Not Found</h1></body></html>'; } In short, create a FrontController file that will map to the desired actions (controllers) according to the request without using header() to execute specific actions (the exception is only if actually the headers are needed, in fact). A: Use addslashes($message) before passing it in querystring and stripslashe($_GET['msg']) function before displaying it. Click addslashes() and stripslashes() for more references.
unknown
d16712
val
If you need the most recent file having one of the extensions required, then this could be a solution: public FileInfo GetRecent(string path, params string[] extensions) { var list = new List<FileInfo>(); // Getting all files having required extensions // Note that extension is case insensitive with this code foreach (var ext in extensions) list.AddRange( new DirectoryInfo(path) .EnumerateFiles("*" + ext, SearchOption.AllDirectories) .Where(p => p.Extension.Equals(ext,StringComparison.CurrentCultureIgnoreCase)) .ToArray()); return list.Any() // If list has somm file then return the newest one ? list.OrderByDescending(i => i.LastWriteTime) .FirstOrDefault() // else return what you please, it could be null : null; } If you need the most recent file for each extension, then this could be a solution: public Dictionary<string, FileInfo> GetRecents(string path, params string[] extensions) { var ret = new Dictionary<string, FileInfo>(); // Getting all files having required extensions // Note that extension is case insensitive with this code foreach (var ext in extensions) { var files = new DirectoryInfo(path) .EnumerateFiles("*" + ext, SearchOption.AllDirectories) .Where(p => p.Extension.Equals(ext, StringComparison.CurrentCultureIgnoreCase)) .ToArray(); ret.Add(ext, files.Any() ? files.OrderByDescending(i => i.LastWriteTime).FirstOrDefault() : null); } return ret; } A: You could first enumerate the Sub-Directories in the provided path, using Directory.EnumerateDirectories. This enumeration excludes the root, so we can add it back to the Enumerable, if required, using the Prepend()1 or Append()1 methods. Then iterate the collection of extensions, call DirectoryInfo.EnumerateFiles to get Date/Time information about the files in each Directory and filter using the FileInfo.LastWriteTime value and finally order by the most recent and yield return the first result. I've used a public methods that calls a private worker method, so the public method can be used to provide some more filters or it could be more easily overloaded. Here it's used to provide an option to return the most recent file of all. It can be called as: string[] extensions = { ".png", ".jpg", "*.txt" }; var mostRecentFiles = GetMostRecentFilesByExtension(@"[RootPath]", extensions, false); Specify false to get all the files by type and directory, or true to get the most recent file among all files that matched the criteria. public IEnumerable<FileInfo> GetMostRecentFilesByExtension(string path, IEnumerable<string> extensions, bool returnSingle) { var mostRecent = MostRecentFileByExtension(path, extensions).Where(fi => fi != null); if (returnSingle) { return mostRecent.OrderByDescending(fi => fi.LastWriteTime).Take(1); } else { return mostRecent; } } private IEnumerable<FileInfo> MostRecentFileByExtension(string path, IEnumerable<string> exts) { foreach (string dir in Directory.EnumerateDirectories(path, "*", SearchOption.AllDirectories).Prepend(path)) foreach (string ext in exts) { yield return new DirectoryInfo(dir) .EnumerateFiles($"*{ext}") .Where(fi => fi.Extension.Equals(ext, StringComparison.InvariantCultureIgnoreCase)) .OrderByDescending(fi => fi.LastWriteTime).FirstOrDefault(); } } (1) Both Prepend() and Append() require .Net Framework 4.7.1. Core/Standard Frameworks all have them.
unknown
d16713
val
Since you do the getElementById, it only covers one element. And ID must be unique to elements in HTML, you cannot have multiple elements with same ID. You can give all of the video elements the same class and apply all of them at once, or just apply to all video elements directly let myVideos = document.querySelectorAll("video"); myVideos.forEach(vid => { vid.addEventListener("mouseover", () => { vid.play(); }); vid.addEventListener("mouseleave", () => { vid.pause(); }); }) <div id="container"> <video id="my_video_1" loop muted poster="https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fwww.tiverton.ri.gov%2Fimg%2Fcontent%2Ftrees%2Fhome_tree.png&f=1&nofb=1&ipt=c0fbdc7aa01163cdffb57908bb424286af2ebd3b6352a581d61660f31a299a51&ipo=images"> <!-- put your image here --> <source src="VIDEO_URL" type="video/mp4"> <!-- path to your video here --> </video> <video id="my_video_2" loop muted poster="https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fwww.tiverton.ri.gov%2Fimg%2Fcontent%2Ftrees%2Fhome_tree.png&f=1&nofb=1&ipt=c0fbdc7aa01163cdffb57908bb424286af2ebd3b6352a581d61660f31a299a51&ipo=images"> <!-- put your image here --> <source src="VIDEO_URL" type="video/mp4"> <!-- path to your video here --> </video> </div> A: You have multiple elements with the same ID. This is your problem, ID's must be unique. You want something like this Note you also should not use fat arrow functions for event listeners //Get the video elements we want let videos = document.querySelectorAll(".video-container video"); //Loop the elements videos.forEach((el) => { //Add the event listeners el.addEventListener("mouseover", function() { console.log("Play " + this.querySelector("source").src); this.play(); }); el.addEventListener("mouseleave", function() { console.log("Pause " + this.querySelector("source").src); this.pause(); }); }); <div class="video-container"> <video loop muted poster="IMAGE_URL"> <!-- put your image here --> <source src="VIDEO_URL" type="video/mp4"> <!-- path to your video here --> </video> </div> <div class="video-container"> <video loop muted poster="IMAGE_URL"> <!-- put your image here --> <source src="VIDEO_URL2" type="video/mp4"> <!-- path to your video here --> </video> </div>
unknown
d16714
val
I found the solution myself. In Notepad++: * *Select "Encode in ANSI" from Encoding menu. *Paste the corrupted text. *Select "Encode in UTF-8" from Encoding menu. That's it. The correct text will be displayed. If so, how can I do the same with Perl?
unknown
d16715
val
There's certainly no member function on std::string that would allow you to distinguish between a std::string() and a std::string(""). I defer to a philosopher or logician to verify if that satisfies any definition of equality. As for the standard itself, it states that std::string() will leave the capacity unspecified but std::string("") will define a capacity of at least zero. So the internal state of the object could be different. On my particular STL implementation (MSVC2012), std::string() calls a function called _Tidy whereas std::string("") calls _Tidy and assign. (The base class initialisation is identical). assign is a standard std::string function. So could they be different? Yes. Can you tell if they are different? No. A: If we look at the effects of each constructor in the C++ standard, section Β§ 21.4.2 [string.cons] : For explicit basic_string(const Allocator& a = Allocator()) : * *data() : a non-null pointer that is copyable and can have 0 added to it *size() : 0 *capacity() : an unspecified value For basic_string(const charT* s, const Allocator& a = Allocator()) : * *data() : points at the first element of an allocated copy of the array whose first element is pointed at by s *size() : traits::length(s) *capacity() : a value at least as large as size() So strictly speaking, both constructs are not identical : in particular, the capacity of the constructed std::string objects might be different. In practice, it's unlikely that this possible difference will have any observable effect on your code. A: Yes, they are both same. Default constructor of std::string prepares an empty string same as "" explicit basic_string( const Allocator& alloc = Allocator() ); Default constructor. Constructs empty string (zero size and unspecified capacity) basic_string( const CharT* s, const Allocator& alloc = Allocator() ); Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if s does not point at an array of at least Traits::length(s)+1 elements of CharT. A: The only difference is that std::string() knows at compile-time that it will produce a zero-length string, while std::string("") has to use strlen or something similar to determine the length of the string it will construct at run-time. Therefore the default-constructor should be faster.
unknown
d16716
val
The equality and inequality predicates are non-signaling so x = x returning false can be used to test if x is a quiet NaN. Source This is the rule defined in IEEE 754 so full compliance with the specification requires this behavior. A: Nothing is equal to NaN. Any comparison will always be false. In both the strict and abstract comparison algorithms, if the types are the same, and either operand is NaN, the result will be false. If Type(x) is Number, then * *If x is NaN, return false. *If y is NaN, return false. In the abstract algorithm, if the types are different, and a NaN is one of the operands, then the other operand will ultimately be coerced to a number, and will bring us back to the scenario above. A: The following operations return NaN The divisions 0/0, ∞/∞, ∞/βˆ’βˆž, βˆ’βˆž/∞, and βˆ’βˆž/βˆ’βˆž The multiplications 0Γ—βˆž and 0Γ—βˆ’βˆž The power 1^∞ The additions ∞ + (βˆ’βˆž), (βˆ’βˆž) + ∞ and equivalent subtractions. Real operations with complex results: The square root of a negative number The logarithm of a negative number The tangent of an odd multiple of 90 degrees (or Ο€/2 radians) The inverse sine or cosine of a number which is less than βˆ’1 or greater than +1. The following operations return values for numeric operations. Hence typeof Nan is a number. NaN is an undefined number in mathematical terms. ∞ + (-∞) is not equal to ∞ + (-∞). But we get that NaN is typeof number because it results from a numeric operation. From wiki:
unknown
d16717
val
The usort function is the best for you. Just pass this function as Callback: $sorter = function($leftArray, $rightArray) { if ($leftArray[1] == $rightArray[1]) { return 0; } if ($leftArray[1] > $rightArray[1]) { return 1; } return -1; } I assumed you want to sort by the value with index 1. If not just change the Index.
unknown
d16718
val
As per the comment It's passed as a table. - assuming the table is the variable @UserInput with a single column of Value, you can use a WHERE EXISTS clause to check for the existence of that value in the user-input fields, and pull the DISTINCT Class values. Select Distinct Class From YourTable T Where Exists ( Select * From @UserInput U Where T.Value = U.Value ) Your SQL syntax will vary, but this should point you in the right direction, syntactically. A full example of how to implement this would be as follows: Creating the User-defined Table Type Create Type dbo.UserInput As Table ( Value Varchar (10) ) Go Creating the Stored Procedure Create Proc dbo.spGetClassesByUserInput ( @UserInput dbo.UserInput ReadOnly ) As Begin Select Distinct Class From YourTable T Where Exists ( Select * From @UserInput U Where T.Value = U.Value ) End Go Calling the Stored Procedure with user input Declare @Input dbo.UserInput Insert @Input Values ('A'), ('B'), ('C') Execute dbo.spGetClassesByUserInput @Input A: You can create a stored procedure an pass the user entry as it as string for ex. A,B,C Create Procedure dbo.GetClasses @v_UserEntry Varchar(200) As Begin Declare @SQLQuery AS NVarchar(1000) Declare @ParamDefinition AS NVarchar(300) SET @v_UserEntry= REPLACE(@v_UserEntry,',',''',N''') Set @SQLQuery ='Select Class' Set @SQLQuery = @SQLQuery + ' From TableName' Set @SQLQuery = @SQLQuery + ' Where Value in (N'''+@v_UserEntry+''')' Set @SQLQuery = @SQLQuery + ' Group By Class' Execute sp_executesql @SQLQuery End Go
unknown
d16719
val
I guess this might help you div{ width: 48%; height: 100px; background-color: red; float: left; margin: 1%; } <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> or this one div{ width: 23%; height: 100px; background-color: red; float: left; margin: 1%; } <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> A: .frontpageBoxLeft, .frontpageBoxRight { border-radius: 5px; border-color: lightgrey; background: #ffffff; height: 150px; } .left-container { float: left; width: 750px; } .frontpageBoxLeft { margin-bottom: 15px; width: 750px; display: inline-block; min-height: 100px; float: right; position: relative; outline: 1px solid red; } .frontpageBoxRight { width: 540px; float: right; height: 300px; position: relative; vertical-align: top; outline: 1px solid red; } .frontpageBoxContainer { width: 1300px; height: 500px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; } <div class="frontpageBoxContainer"> <p class="newsfeedheadline">NEWS FEED</p> <hr class="hrstarter"> <div class="left-container"> <div class="frontpageBoxLeft" id="1"> et eksempel pΓ₯ en kasse1 </div> <div class="frontpageBoxLeft" id="2"> et eksempel pΓ₯ en kasse2 </div> <div class="frontpageBoxLeft" id="3"> et eksempel pΓ₯ en kasse3 </div> </div> <div class="frontpageBoxRight"> et eksempel pΓ₯ en anden kasse </div> </div> A: Put float: left to the .frontpageBoxLeft selector will solve the problem. A: * *Try set the frontpageBoxContainer to position:relative *Float the left AND the right Containers. *set left or right Offset to the divs you want to align.
unknown
d16720
val
Sure, its called core Location Framework: http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html#//apple_ref/doc/uid/TP40009497-CH2-SW1 A: Here is the apple documentation about CoreLocation.
unknown
d16721
val
You can accomplish this by installing and using Pillow, which can work with most image formats (JPEG, PNG, TIFF, etc.). from PIL import Image from PIL.ImageChops import invert image = Image.open('test.tif') red, green, blue = image.split() image_with_inverted_green = Image.merge('RGB', (red, invert(green), blue)) image_with_inverted_green.save('test_inverted_green.tif') After loading the image from your file, split into its channels with Image.split, invert the green channel/image with ImageChops.invert, and then join it together with the original red and blue bands into a new image with Image.merge. If using a format that's encoded in something other than RGB (such as PNG, which has an additional transparency channel), the image-opening line can be amended to: image = Image.open('test.png').convert('RGB') Testing with this image: Produces this: (ImageChops, by the way, looks like a very odd term, but it's short for "image channel operations".) A: I assume you have a numpy (or torch tensor) image - you can index on the green channel (assuming channels are your last dimension) img[:, :, 1] = 255 - img[:, :, 1] I am assuming by invert you want 0 -> 255 and 255 -> 0 A: T(r) = L – 1 – r L=256 L-1=255(Max) r=Each pixel of the image s=255-r s= T(r) =255-r
unknown
d16722
val
There is a limit of 1000 partitions per partition scheme and you can only partition on a single field, so if you intend to multi-tenant beyond 1000 instances you are going to have to jump through a lot more hoops. You can extend the limit by using a partitioned view on top of multiple partitioned tables, but this increases the management overhead. You can use the DMVs and create your own automated system that generates new partitions per client / tenant and manages the problem but it will be specific to your application and not generic. At present there is no automatic dynamic partitioning in SQL Server, it was mentioned at the PDC09 in relation to the SQL Azure future roadmap, but I did not hear of it for SQL Server. Your alternative choices are a database or SQL Instance per client, there are benefits to this approach in that you give yourself far more opportunity to scale out if the needed arises, and if you start looking at a larger data centre, you can start balancing the SQL Instances across a farm of servers etc. If you automatically have all the data in a single database. Other things to take into consideration: Security: Whilst you have the data in a single database with partitioning, you have no data protection. You risk exposing one client's data to another very trivially with any single bug in the code. Upgrading: If all the clients access the same database, then the upgrades will be an all or nothing approach - you will not be able to easily migrate some users to a new version whilst leaving the others as they were. Backups: You can make each partition occupy a separate file group and try manage the situation. Out of the box so to speak, every client's backups are mingled together. If a single client asks for a rollback to a given data you have to plan carefully in advance how that could be executed without affecting the other users of the system.
unknown
d16723
val
The first idea was using if statement and $status variable but sub_filter can't be used in if only in http, server, location. The same functionality can be implemented with body_filter_by_lua body_filter_by_lua ' if ngx.status == ngx.HTTP_OK then ngx.arg[1] = ngx.re.sub(ngx.arg[1], "</head>", "<script src=\"some-custom-script.js\"></script> </head>") end ';
unknown
d16724
val
The effect that you can see is optical illusion. You can make this visible by grading the colors. See the answer to stackoverflow question Issue getting gradient square in glsl es 2.0, Gamemaker Studio 2.0. To achieve a better result, you can use a shader, which smoothly change the gradient, from a circular (or elliptical) gradient in the middle of the the view, to a square gradient at the borders of the view: void mainImage( out vec4 fragColor, in vec2 fragCoord ) { // Normalized pixel coordinates (from 0 to 1) vec2 uv = fragCoord/iResolution.xy; vec2 uvn=abs(uv-0.5)*2.0; vec2 distV = uvn; float maxDist = max(abs(distV.x), abs(distV.y)); float circular = length(distV); float square = maxDist; vec3 color1 = vec3(0.0); vec3 color2 = vec3(1.0); vec3 mate=mix(color1, color2, mix(circular,square,maxDist)); fragColor = vec4(mate.xyz,1); } Preview:
unknown
d16725
val
ModelCheckpoint is a Callback subclass. You can modify the source code to adapt it to your use case. In particular, you can focus on the constructor and the _save_model method. This can be used as a starting point to write your own code.
unknown
d16726
val
Since you have an error, try first with a simpler solution: Service.ts getItemById(id:number): Observable<any> { return this.http.get(`${this.API}/${id}`); } Component.ts showItem(id: any) { this.ItemService.getItemById(id) .subscribe( (data: any) => { console.log(data); //this.log = data; }); } After this, see if your API works (if it gets data). Once you check this, * *If it doesn't return anything, your solution was right, and the problem is in the back. *If it is returning data, there was a problem. Then, in order to find out what is going on, you can try to left this simplified version and try the error directly in the subscription, with catchError or simply managing the "path" of error (something like this:) this.ItemService.getItemById(id) .subscribe( (data: any) => { console.log(data); //this.log = data; }, err => {console.log(err);} // You'll get the whole object, // If you get [object object] you shoud use the specifics fields, something like console.log(err.error.message) or something like that... (look them up on the internet) ); A: I just figured out that i had to add the responseType to the url in the service.ts. This link was useful : Angular HttpClient "Http failure during parsing"
unknown
d16727
val
It's .parse() Time.zone.parse(params["meetingTime"]).in_time_zone(attendeeZone) Alternatively, if you assign it to a model, then it will be parsed automatically already.
unknown
d16728
val
collect the values of already filled selects, and send them to the server to obtain the filtered values list. let's say you have an car manufacturer / model selector. <select name="manufacturer"> <option value="1">Acura</option> <option value="2">Audi</option> ... </select> <select name="model"></select> the function to fill "model" select with values should look like this: $.get('/get_models_by_manufacturer', {manuf: $('select[name=manufacturer']).val()}, function(data){ // data returned by the server is expected to be html code of options NOT surrounded with <select> $('select[name=model]').html(data); }); A: IF your're using jquery there is an discussion: http://forum.jquery.com/topic/how-to-reload-a-select-in-a-form-using-ajax-via-jquery
unknown
d16729
val
You can use MemoryMarshal.AsBytes to read all data: using var stream = new FileStream(...); var target = new int[stream.Length / 4]; stream.Read(MemoryMarshal.AsBytes(target.AsSpan())); No BinaryReader is used in that case. Be aware of endianness of int representation. This code above might cause problems if the file doesn't match to your hardware. A: If you want to read the array as another type, you can use MemoryMarshal.Cast. using System; using System.Runtime.InteropServices; class Program { public static void Main(string[] args) { byte[] arrayByte = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; Span<int> spanInt = MemoryMarshal.Cast<byte, int>(arrayByte); Console.WriteLine("0x{0:X8}", spanInt[0]); // For little endian it will be 0x44332211. Console.WriteLine("0x{0:X8}", spanInt[1]); // For little endian it will be 0x88776655. } } Another alternative is Unsafe.As. However, there are some problems, such as Length not reflecting the converted type value. I recommend using the MemoryMarshal class. using System; using System.Runtime.CompilerServices; class Program { public static void Main(string[] args) { byte[] arrayByte = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; int[] arrayInt = Unsafe.As<byte[], int[]>(ref arrayByte); Console.WriteLine("Length={0}", arrayInt.Length); // 8!? omg... Console.WriteLine("0x{0:X8}", arrayInt[0]); // For little endian it will be 0x44332211. Console.WriteLine("0x{0:X8}", arrayInt[1]); // For little endian it will be 0x88776655. } }
unknown
d16730
val
You just need to bind the click event to the parent element which already exists on the page. $('#foo-bar-baz').on('click', '.foo-bar-thumbnail-image', function(){ // what you want to happen when click // occurs on elements that match '.foo-bar-thumbnail-image' // within '#foo-bar-baz' alert("I am thumbnail " + $(this).id); }); A: You should be using $(document).on('click','.foo-bar-thumbnail-image',function() ... instead of $.click(function()... since the event handler is on elements that were rendered on the page via JS. That's a "delegated" event handler - you can read more about that here https://learn.jquery.com/events/event-delegation/
unknown
d16731
val
is there a way to set them looks like square/rect buttons, and assign a color to their inside rect area ? Step #1: Copy $ANDROID_HOME/platforms/$API/data/res/drawable/btn_radio.xml to your project, where $ANDROID_HOME is where you have installed the Android SDK and $API is some Android platform (e.g., android-2.1) Step #2: Copy $ANDROID_HOME/platforms/$API/data/res/drawable-hdpi/btn_radio* to your project Step #3: Copy $ANDROID_HOME/platforms/$API/data/res/drawable-mdpi/btn_radio* to your project Step #4: Modify those PNG files from steps #2 and #3 to suit your needs
unknown
d16732
val
a holds the ascii value of 's' (115). Think of a char as just a small integer. If you want it in an integer for whatever reason, just cast it. char a = 's'; int code = a; //or (int)a; A: Use QChar? :) http://doc.trolltech.com/4.6/qchar.html
unknown
d16733
val
I think you are confusing with tab char and sapces. Are you expecting fixed no of white spaces to be added in the end of every word? \t -> is just a tab char The following is generated by the code given by you. Java StackOverflow Banyan Javasun StackOverflow Banyan The above two lines have same tab char b/w the 1st & 2nd Word. if you type one more char in the end of "Javasun" it will extend like the following Javaasunk StackOverflow Banyan A: try StringBuilder stringBuilder = new StringBuilder(); foreach (string field in fields) { stringBuilder.Append(field.Trim()).Append("\t"); } stringBuilder.AppendLine(); return stringBuilder.ToString(); Basically I would just use return string.Join ( "\t", fields ); . A: I would have thought you would want StringBuilder stringBuilder = new StringBuilder(); foreach (string field in fields) { stringBuilder.Append(field); stringBuilder.Append("\t"); } stringBuilder.AppendLine(); return stringBuilder.ToString(); A: Instead of looping, you can use string.Join: StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(string.Join("\t", fields)); Note that you can pass in the string directly to AppendLine as well. A: Sub WarningWindow(ByVal content As String) Dim sw As New StringWriter() Dim hw As New HtmlTextWriter(sw) Dim gridHTML As String = sw.ToString().Replace("""", "'").Replace(System.Environment.NewLine, "") Dim sb As New StringBuilder() Dim a As String = "Welcomeback" 'GridView1.RenderControl(hw) sb.Append("<script type = 'text/javascript'>") sb.Append("window.onload = new function(){") sb.Append("var printWin = window.open('', '', 'left=0") sb.Append(",top=0,width=1400,height=500,resize=yes,scrollbars =yes');") sb.Append("printWin.document.write(""") sb.Append("<INPUT Type=Button Name=Close Size=40 Value='Clsose(GSS)' onclick='self.close()'; / > ") sb.Append("</br><INPUT Type=Button Name=fu Size=40 Value='Alert' onclick=javascript:window.alert('" & a & "'); / > ") sb.Append("<INPUT Type=Text Name=gss Size=40 Value=300 ; / > ") sb.Append(" <P>") sb.Append(content) sb.Append(""");") sb.Append("printWin.focus();") sb.Append("printWin.show;};") sb.Append("</script>") ClientScript.RegisterStartupScript(Me.GetType(), "suvesh", sb.ToString()) End Sub
unknown
d16734
val
Volumes are at the environment variables indentation level, and it is of type list. So you need to indent the app volume as in db service and it should work. version: '3' services: app: image: 'jc21/nginx-proxy-manager:latest' restart: unless-stopped ports: - "80:80" - "81:81" - "443:443" environment: DB_MYSQL_HOST: "db" DB_MYSQL_PORT: 3306 DB_MYSQL_USER: "admin" DB_MYSQL_PASSWORD: "adminpwd" DB_MYSQL_NAME: "nginx" volumes: - '/mnt/nginx/data:/data' - '/mnt/nginx/letsencrypt:/etc/letsencrypt' db: image: 'jc21/mariadb-aria:latest' restart: unless-stopped environment: MYSQL_ROOT_PASSWORD: 'adminpwd' MYSQL_DATABASE: 'nginx' MYSQL_USER: 'admin' MYSQL_PASSWORD: 'adminpwd' volumes: - '/mnt/nginx/data/mysql:/var/lib/mysql'
unknown
d16735
val
You can order updates and inserts with PriorityBlockingQueue to process inserts with priority. A: Thank you for your inputs Everyone I found a solution to the issue i used REENTRANT Locks to solve the issue . made a static Lock object in A global file and made lock.tryLock() in both the file to solve the issue
unknown
d16736
val
You can't catch errors in Beam in this way. You have to use a dead letter queue with Beam and TupleTags. You will have 2 sinks with this system : * *The good sink *The bad sink I didn't used sentry but I think it's possible to sink the a PCollection to sentry. Example of catching errors with a library called Asgarde : https://github.com/tosun-si/pasgarde pip install asgarde==0.16.0 with Pipeline(optins=options) as pipeline: ( input_collection = pipeline | io.ReadFromPubSub(...) // example message {'f': 'b'}, with attribut id: id1 resut = (CollectionComposer.of(input_collection) .map(lambda el : .....) .map(lambda el2 : .....) ) result_outputs: PCollection[YourObjectOrDict] = result.outputs # Failure object contains error and input element and it's given by Asgarde library result_failures: PCollection[Failure] = result.failures result_failure | 'Send errors to Sentry' >> beam.Map(your_method_to_send_to_sentry) If it's not possible to send errors to sentry in Beam pipeline, you can think to another solution : * *The errors can be written to Bigquery for analytics *The errors can be loggued to Cloud Logging and then this can fire an email or Slack alerting You can also catch error and use dead letter queue in native Beam code, I propose you an example from my Github repository : https://github.com/tosun-si/teams-league-python-dlq-native-beam-summit/blob/main/team_league/domain_ptransform/team_stats_transform.py
unknown
d16737
val
Why can't you just create a second implementation which you map to only those columns? public class Table : IJustWantTheseColumnsInterface { public virtual int Id { get; set; } public virtual string FirstName { get; set; } public virtual string MiddleName { get; set; } public virtual string LastName { get; set; } public virtual Address Address { get; set; } public virtual Phone Phone { get; set; } public virtual DateTime BirthDate { get; set; } public virtual Occupation Occupation { get; set; } public virtual Employer Employer { get; set; } } public class SameTable : IJustWantTheseColumnsInterface { public virtual int Id { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public virtual Phone Phone { get; set; } } public interface IJustWantTheseColumnsInterface { int Id { get; set; } string FirstName { get; set; } string LastName { get; set; } Phone Phone { get; set; } } public class SameTableMap : ClassMap<SameTable> { public SameTableMap() { Table("Table"); Id(x => x.Id, "ID"); Map(x => x.FirstName, "FIRST_NAME"); Map(x => x.LastName, "LAST_NAME"); Reference(x => x.Phone, "PHONE_ID"); } } You can also use an Interface as T for ClassMap. Also in case the Phone property was of type interface IPhone in your Table class. You could specify which implementation to return like this. public interface IJustWantTheseColumnsInterface { ... IPhone Phone { get; set; } ... } public class SameTableMap : ClassMap<SameTable> { public SameTableMap() { ... Reference(x => x.Phone, "PHONE_ID").Class(typeof(Phone)); ... } } Now if you want to get your partial entity IJustWantTheseColumnsInterface someVariable = session.Get<SameTable>();
unknown
d16738
val
Based on the exception you are getting, the problem is not in your code, it is in the connection itself. This can be a firewall issue or the process listening on a different port. EDIT: The OP has found that the problem he had was in the IIS and that resetting the IIS solved his problem. To reset IIS, you can do this either manually or through command prompt: Run (Win+R) -> open cmd (with admin privileges) -> type "iisreset" (without "")
unknown
d16739
val
There's a predict.glmnet() in glmnet package. Just define a new function. pred_func2 <- function(z) predict.glmnet(z, newx = newdata)[,1] And run. plan(multiprocess) b2 <- a %>% group_by(id) %>% nest(.key=data) %>% mutate(lasso=map(data, function(z) { glmnet(x=as.matrix(select(z, x1, x2)), y=z$y, intercept=TRUE, alpha=1) })) %>% mutate(myprediction_future=map(lasso, ~future(pred_func2(.x)))) %>% mutate(myprediction=values(myprediction_future)) Yielding > b2 # A tibble: 2 x 5 id data lasso myprediction_future myprediction <chr> <list> <list> <list> <list> 1 a <tibble [100 x 3]> <S3: elnet> <S3: MultisessionFuture> <dbl [200]> 2 b <tibble [100 x 3]> <S3: elnet> <S3: MultisessionFuture> <dbl [200]>
unknown
d16740
val
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.
unknown
d16741
val
https://docs.npmjs.com/files/package.json#git-urls-as-dependencies "dependencies": { "mymodule": "git+ssh://[email protected]/owner/repo.git#commit-ish" } The commit-ish can be any tag, sha, or branch which can be supplied as an argument to git checkout. The default is master.
unknown
d16742
val
You would need to set the PidTagBlockStatus property - see http://msdn.microsoft.com/en-us/library/ee219242(v=exchg.80).aspx. Note that while you can read/write that property using MailItem.PropertyAccessor.SetProperty, you will not be able to calculate its value correctly - Outlook Object Model rounds off the value of the message delivery time, and you would need the raw Extended MAPI value (accessible in C++ or Delphi only) as the FileTime structure. If using Redemption (I am its author) is an option, it exposes the RDOMail.DownloadPictures property. Something like the following should do the job (VB script): set Session = CreateObject("Redemption.RDOSession") Session.MAPIOBJECT = Application.Session.MAPIOBJECT set Item = Session.GetRDOObjectFromOutlookObject(YourOutlookItem) Item.DownloadPictures = true Item.Save A: The Outlook object model doesn't provide any property or method for that.
unknown
d16743
val
I think what you mean - in PyTorch notation - is a kernel size of 3 and a stride of 1. You can use torch.nn.AvgPool1d to perform this kind of operation: mean = nn.AvgPool1d(kernel_size=3, stride=1) Note, you will need one extra dimension, for the channel, to be compatible with this kind of layer: >>> x = torch.tensor([[1, 2, 3, 4, 5]]).unsqueeze(0) tensor([[[1, 2, 3, 4, 5]]]) >>> mean(x) tensor([[[2, 3, 4]]])
unknown
d16744
val
You can use minutes instead of hours: with h ([Minute]) as ( select 420 union all select 450 union all select 480 union all select 510 union all select 540 union all ... Divide the minutes to get fractional hours: select h.[Minute] / 60.0 as [Hour], ... Calculate the start and stop time for the interval to filter the data: ... on T.TimeofArrival >= dateadd(minute, h.[Minute], @DateTimeToFilter) and T.TimeofArrival < dateadd(minute, h.[Minute] + 30, @DateTimeToFilter) A: Below is an example that groups by half-hour intervals and can easily be extended for other intervals. I suggest you avoid applying functions to columns in the WHERE clause as that prevents indexes on those columns from being used efficiently. DECLARE @DateTimeToFilter smalldatetime = '2014-06-05' , @IntervalStartTime time = '07:00:00' , @IntervalEndTime time = '20:00:00' , @IntervalMinutes int = 30; WITH t4 AS (SELECT n FROM (VALUES(0),(0),(0),(0)) t(n)) , t256 AS (SELECT 0 AS n FROM t4 AS a CROSS JOIN t4 AS b CROSS JOIN t4 AS c CROSS JOIN t4 AS d) , t64k AS (SELECT ROW_NUMBER() OVER (ORDER BY (a.n)) AS num FROM t256 AS a CROSS JOIN t256 AS b) , intervals AS (SELECT DATEADD(minute, (num - 1) * @IntervalMinutes, @DateTimeToFilter) AS interval FROM t64k WHERE num <= 1440 / @IntervalMinutes) SELECT interval , CAST(DATEDIFF(minute, @DateTimeToFilter, interval) / 60.0 AS decimal(3, 1)) AS Hour , COUNT(T.BookingID) AS NoOfUsers FROM intervals LEFT JOIN dbo.tbl_Visitor T ON T.TimeofArrival >= intervals.interval AND T.TimeofArrival < DATEADD(minute, @IntervalMinutes, intervals.interval) WHERE interval >= DATEADD(minute, DATEDIFF(minute, '', @IntervalStartTime), @DateTimeToFilter) AND interval < DATEADD(minute, DATEDIFF(minute, '', @IntervalEndTime), @DateTimeToFilter) GROUP BY interval ORDER BY Hour;
unknown
d16745
val
MessageChannels chapter points out to the MessageChannels factory. So, <publish-subscribe-channel> XML config translates to Java config like: @Bean public MessageChannel channel() { return MessageChannels.publishSubscribe(myExecutor()).get(); } Although you can reach the same just with raw Java config: @Bean public MessageChannel channel() { return new PublishSubscribeChannel(myExecutor()); }
unknown
d16746
val
As suggested by Mateo, patching of comments works when using the OAuth 2.0 Client Credentials (Secret key file)
unknown
d16747
val
We can create a function that takes two hex strings and returns the sum of the differences between the individual colour components. If you can't understand how the following works, just comment. def diff(h1, h2): def hexs_to_ints(s): return [int(s[i:i+2], 16) for i in range(1,7,2)] return sum(abs(i - j) for i, j in zip(*map(hexs_to_ints, (h1, h2)))) And we can test it: >>> diff('#ff00ff', '#0000ff') 255 >>> diff('#0000ff', '#00000a') 245 So now, we can create a function that uses this function to complete the task: def get_col_name(hex, colors): return min([(n,diff(hex,c)) for n,c in colors.items()], key=lambda t: t[1])[0] Unfortunately, this doesn't work for your colors, since it chooses gray which is [128, 128, 128] so very near to steelblue which is [74, 125, 172] - nearer than blue which is [0, 0, 255]. This means the difference is smaller to gray that to blue. I'll try to think of a better method, but maybe someone has some insight and can drop a comment? A: How about converting them into RGB and find the dominatant color? For example RED FF0000 rgb(255,0,0) BLUE 0000FF rgb(0,0,255) steelblue 4A7DAC rgb(74,125,172) You can most likely achieve this target with the RGB rather than the HEX The rest you can see this algo: https://stackoverflow.com/a/9018100/6198978 EDIT The thing is RGB and HEX calculation will not be able to work with Grey color as every color just has closest distance to the grey. For that purpose you can use the HSV values of the color, I am editing the code with the HSV implemented as well :D Learned alot :D I was having fun with it here you go: import math colors= { "red":"#FF0000", "yellow":"#FFFF00", "green":"#008000", "blue":"#0000FF", "black":"#000000", "white":"#FFFFFF", "grey": "#808080" } # function for HSV TAKEN FROM HERE: https://gist.github.com/mathebox/e0805f72e7db3269ec22 def rgb_to_hsv(r, g, b): r = float(r) g = float(g) b = float(b) high = max(r, g, b) low = min(r, g, b) h, s, v = high, high, high d = high - low s = 0 if high == 0 else d/high if high == low: h = 0.0 else: h = { r: (g - b) / d + (6 if g < b else 0), g: (b - r) / d + 2, b: (r - g) / d + 4, }[high] h /= 6 return h, s, v # COLOR YOU WANT TO TEST TESTED check = "#808000".lstrip('#') checkRGB = tuple(int(check[i:i+2], 16) for i in (0, 2 ,4)) checkHSV = rgb_to_hsv(checkRGB[0], checkRGB[1], checkRGB[2]) colorsRGB = {} colorsHSV = {} for c, v in colors.items(): h = v.lstrip('#') colorsRGB[c] = tuple(int(h[i:i+2], 16) for i in (0, 2 ,4)) for c, v in colorsRGB.items(): colorsHSV[c] = tuple(rgb_to_hsv(v[0], v[1], v[2])) def colourdistanceRGB(color1, color2): r = float(color2[0] - color1[0]) g = float(color2[1] - color1[1]) b = float(color2[2] - color1[2]) return math.sqrt( ((abs(r))**2) + ((abs(g))**2) + ((abs(b))**2) ) def colourdistanceHSV(color1, color2): dh = min(abs(color2[0]-color1[0]), 360-abs(color2[0]-color1[0])) / 180.0 ds = abs(color2[1]-color1[1]) dv = abs(color2[2]-color1[2]) / 255.0 return math.sqrt(dh*dh+ds*ds+dv*dv) resultRGB = {} resultHSV = {} for k, v in colorsRGB.items(): resultRGB[k]=colourdistanceRGB(v, checkRGB) for k,v in colorsHSV.items(): resultHSV[k]=colourdistanceHSV(v, checkHSV) #THIS WILL NOT WORK FOR GREY print("RESULT WITH RGB FORMULA") print(resultRGB) print(min(resultRGB, key=resultRGB.get)) #THIS WILL WORK FOR EVEN GREY print(resultHSV) print(min(resultHSV, key=resultHSV.get)) #OUTPUT FOR RGB #check = "#808000" output=GREY #check = "#4A7DAC" output=GREY :D #OUTPUT FOR RGB #check = "#808000" output=GREEN #check = "#4A7DAC" output=BLUE:D
unknown
d16748
val
As i mentioned earlier there is no issue with your code. When executing application created using http server for the first time for the Windows platform, you will get the form dialog shown in below Figure. It’s better to check Private Network and then click Allow access In case of failure of Confirming from Windows Firewall to open a port, You will get above error.
unknown
d16749
val
You only bound foo to the class; you didn't make it an instance: foo = FooClass # only creates an additional reference Call the class: foo = FooClass() # creates an instance of FooClass In Python you usually don't use accessor methods; just reference foo.number in your main module, rather than use foo.bar() to obtain it. A: In your example foo is just an alias for FooClass. I assume that your actual problem is more complicated than your snippet. However, if you really need a class method, you can annotate it with @classmethod decorator. class FooClass(object): number = 5 @classmethod def bar(cls): return cls.number To use your the class you could do: from foomodule import Foo Foo.bar() Or you can access the class member directly Foo.number
unknown
d16750
val
I think you need to use an "and_" filter to make sure sqlalchemy returns only rows which fulfil all the requirements (rather than at least one of the filters): from sqlalchemy import and_ department = (Department.get_query(info) .join(EmployeeModel) .filter(and_(DepartmentModel.name == name, EmployeeModel.name.ilike(like_query))) not 100% sure if this works with graphene or whatever (i think this is unrelated in this case...). Also check this link: sqlalchemy tutorial Give it a try!
unknown
d16751
val
The Include merely means that the Jobs property isn't going to defer execution when the query is executed and that each record is going to also return all of the related Jobs records. In your joins you're actually filtering out the files that don't have jobs that meet the given criteria. You aren't filtering out the jobs of those files, you're filtering out all of the files that have those jobs. The Include won't prevent those files from being filtered out. A: After Eren ErsΓΆnmez point me out that there was an Include function for the IQueryable interface, I decided to try to upgrade my EF4 to EF6 and with this update, the function was available! This is not clear in the documentation from Microsoft. If that can help someone else, I have followed this tutorial on how to update from EF4 to EF6.
unknown
d16752
val
Copying between framebuffers: glBlitFramebuffer see here https://www.opengl.org/sdk/docs/man3/xhtml/glBlitFramebuffer.xml This image will have a resolution related with the screen? The resolution can be set in the glBlitFramebuffer function. The default framebuffer has the size of your opengl window (can be different than the screen). Is it possible to copy the default frambuffer to a framebuffer object without showing anything on the screen? The image is usually first rendered offscreen and displayed when calling swapBuffers (double buffering). So without calling swapBuffers nothing is shown on the screen. Keep in mind though, that you can render directly into framebuffers objects and you don't have to first render it into the default framebuffer and then copy it over. To do that just call glBindFramebuffer before your actual draw calls.
unknown
d16753
val
You can try something similar, function DummyComponent(){ const [fullList, setFullList] = useState(['item1', 'item2', 'item3', 'item4']) const [favList setFavList] = useState([]) const handleFavAddClick=(e)=>{ setFavList(preState=>[...preState, e]) setFullList(preState=> preState.filter(item => item !== e)) } return( <div> Full List (add to fav by clicking them) <ul> { fullList.map(e=> <li key={e} onClick={()=>handleFavAddClick(e)}>{e}</li>) } </ul> Fav List <ul> { favList.map(e=> <li key={e}>{e}</li>) } </ul> </div> ) } A: So, let's say you have two lists: const [items, setItems] = useState([]); const [favorites, setFavorites] = useState([]); You can use this function to achieve what you want. If you want to completely move an item from items list to favorites, pass false as the second argument or don't pass it at all. But if you want to just copy the item to favorites list, pass true. function moveToFavorites(id, copy) { setFavorites([...favorites, items.find(item => item.id === id)]); if(!copy) setItems(items.filter(item => item.id !== id)); } A: Your list you received from the api is in the form of a JSON object. Depending on how the data was structured you may have the list in an array or its still flat. Examples: A) List: { name: "john", }, { name: "jane"} } B) List: {list: ["john", "jane"]} Ideally you want option B. This means your list is in an Array. Look up documentation on how to convert JSON to an Array. There are great functions available to you in the lodash library which you can use. Once your list in in an array you should be ready for adding and removing favorites. example: let myList = ["john","jane"] What you will want to do is have another array called favorites. When the user clicks on an item in the list, it will be added to their favorites array. You are removing from one array and another. Here is an example function. let myList = ["john","jane"]; // list from api let favorites = [] // your new list //this function recieves the index (position) of the item the user clicked in the user interface const addFavorites = (index) => { favorites.push(myList[index]) // adds items to favorites array myList.splice(index, 1); // removes same item from myList } // call the function addFavorites(0) // will remove john console.log(favorites) console.log(myList) }
unknown
d16754
val
There's a mistake in your code, when you append to the array of descriptions you now have 2 descriptions. Change it to: let description = container.persistentStoreDescriptions.first! description.shouldInferMappingModelAutomatically = true description.shouldMigrateStoreAutomatically = true // Load A: I noticed, that after loading persistence storage error generated. This error (Can't add the same store twice), can be ignored for SwiftUI previews and Unit Tests. To ignore this type of error needs to check XCTestSessionIdentifier and XCODE_RUNNING_FOR_PREVIEWS in the process info. if let error = error as NSError? { if ProcessInfo.processInfo.environment["XCTestSessionIdentifier"] == nil && ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == nil { fatalError("Unresolved error \(error), \(error.userInfo)") } }
unknown
d16755
val
If one batch file directly invokes another one, the execution flow is transfered to the called file, and not returned to the caller. To retrieve the execution flow after the called file has ended, we need to use the call command call "%SoapUIPath%\testrunner.bat" ....
unknown
d16756
val
It's an issue with your machine running the code, it may work on other machines. If you are behind a proxy, here is an article on how to setup properly with proxies: http://code.google.com/apis/gdata/articles/proxy_setup.html A: I find the reason of the exception there is no problems appears when names are updated like that contact.Name.FullName = value; but when update phone numbers like that the above exception appears contact.Phonenumbers.Add(new Google.GData.Extensions.PhoneNumber(value)); it appears that gmail return the same exception regardless of what error had happened, how can I understand that from just "execution of request failed", that is quite annoying. I hope they add some details, though I do not know what is wrong in updating phone numbers like that.
unknown
d16757
val
NodeJs you installed on Termux doesn't have permission to install dependencies on /storage/emulated/0/Coding/node_modules/.bin/geojsonhint. You can solve it by: * *Changing the directory of the project to somewhere with public permissession. *Running the command with the administration privilege but on Termux, I think. *Using nvm to install node js instead of default ways. This problem comes when you try to install node js with Termux. try not to. NVM repository link: nvm-sh/nvm. pay attention: * *You need to check your dependency tree is compatible with the node version you want to install. *If the project is big be careful because you can break your project easily.
unknown
d16758
val
Yes, it would be best to do so. Imagine.. What if the email address they provided is not correct(misspelled) or not existing or worse--someone else's? Regarding the last case, I don't mean that your service is spam, but simply that the notifications they had hoped to receive would be sent to someone else. I think it would still be beside the point even if no important information is included in the notification--it would be a matter of the wrong person receiving notifications meant for someone else. :) A: I would suggest that you have to confirm the new email before it can be changed so you still have contact with the user. The old email could potentially be stored in a separate database so is not visible to the user and only deleted when he/she has confirmed the new email. A: Yes. Doing so protects users who have had their site accounts compromised from having someone change the main e-mail address and completely lock the user out of his account. This is good practice regardless of whether or not the account protects sensitive information because nobody wants to deal with being locked out of an account by an attacker.
unknown
d16759
val
I was able to solve this by importing a container from a different file. Using this method, you would write a different container for every combination of dependencies you want to inject into a test. For brevity, assume the code example with ninja warriors given by the Inversify docs. // src/inversify.prod-config.ts import "reflect-metadata"; import { Container } from "inversify"; import { TYPES } from "./types"; import { Warrior, Weapon, ThrowableWeapon } from "./interfaces"; import { Ninja, Katana, Shuriken } from "./entities"; const myContainer = new Container(); myContainer.bind<Warrior>(TYPES.Warrior).to(Ninja); myContainer.bind<Weapon>(TYPES.Weapon).to(Katana); myContainer.bind<ThrowableWeapon>(TYPES.ThrowableWeapon).to(Shuriken); export { myContainer }; // test/fixtures/inversify.unit-config.ts import "reflect-metadata"; import {Container, inject, injectable} from "inversify"; import { TYPES } from "../../src/types"; import { Warrior, Weapon, ThrowableWeapon } from "../../src/interfaces"; // instead of importing the injectable classes from src, // import mocked injectables from a set of text fixtures. // For brevity, I defined mocks inline here, but you would // likely want these in their own files. @injectable() class TestKatana implements Weapon { public hit() { return "TEST cut!"; } } @injectable() class TestShuriken implements ThrowableWeapon { public throw() { return "TEST hit!"; } } @injectable() class TestNinja implements Warrior { private _katana: Weapon; private _shuriken: ThrowableWeapon; public constructor( @inject(TYPES.Weapon) katana: Weapon, @inject(TYPES.ThrowableWeapon) shuriken: ThrowableWeapon ) { this._katana = katana; this._shuriken = shuriken; } public fight() { return this._katana.hit(); } public sneak() { return this._shuriken.throw(); } } const myContainer = new Container(); myContainer.bind<Warrior>(TYPES.Warrior).to(TestNinja); myContainer.bind<Weapon>(TYPES.Weapon).to(TestKatana); myContainer.bind<ThrowableWeapon>(TYPES.ThrowableWeapon).to(TestShuriken); export { myContainer }; // test/unit/example.test.ts // Disclaimer: this is a Jest test, but a port to jasmine should look similar. import {myContainer} from "../fixtures/inversify.unit-config"; import {Warrior} from "../../../src/interfaces"; import {TYPES} from "../../../src/types"; describe('test', () => { let ninja; beforeEach(() => { ninja = myContainer.get<Warrior>(TYPES.Warrior); }); test('should pass', () => { expect(ninja.fight()).toEqual("TEST cut!"); expect(ninja.sneak()).toEqual("TEST hit!"); }); }); A: Try exporting the container from your IOC configuration, ioc.ts, like this export { iocContainer, lazyInject, Types }; Then you can rebind the IDataService Symbol to your mocked FakeDataService in the unit test import { Types, iocContainer } from "../tmp/ioc"; import MyComponent from "../tmp/myComponent"; import { IDataService } from "../tmp/dataService"; import { injectable } from "inversify"; @injectable() // Added class FakeDataService implements IDataService { get(): string { return "I am fake!"; } } describe("My Component", () => { let myComponent!: MyComponent; beforeAll(() => { // Rebind the service iocContainer.rebind<IDataService>(Types.IDataService).to(FakeDataService); // Alternatively you could do it like this with the same end result: iocContainer.unbind(Types.IDataService); iocContainer.bind<IDataService>(Types.IDataService).to(FakeDataService); myComponent = new MyComponent(); }); it("should use the mocked service", () => { const val = myComponent.getSomething(); expect(val).toBe("I am fake!"); }); }); I tried it myself and it works fine. I found this via the inversify.js container API docs
unknown
d16760
val
In your for-loop you wait for the first future to complete. This may take 2000 millis. At this time all the other threads will sleep. Hence, all the values of the other threads are 2000 millis less. Then you wait another 2000 millis and perhaps the future you wait for returns. Hence, two or more threads will succeed. In each iteration of your loop you donate 2000 millis to the other thread. Only if one future returns successfully, you donate less to the remaining futures. If you would like to observe all futures to fail, due to the 2000 millis timeout, you would have to process them in parallel as well. If you change some of your code this way: Set<Callable<String>> tasks = new HashSet<>(); for (String word : args) { tasks.add(new WordLengthCallable(word, waitArr[i++])); } List<Future<String>> futures = Executors.newFixedThreadPool(3) .invokeAll(tasks, 2000, TimeUnit.MILLISECONDS); you should observe that none of the tasks will succeed, due to the wait times of: 3000, 3440, 2500, 3000 for each Callable created, which are all greater than 2000. A: EDIT: Thanks to @RQube for warning me about thread's execution order as 3. thread will be finished before 1., 4. thread will start after 3.'s finish instead of 1. First of all your thread pool's size is 3. This means your 4. Future will wait 3. to finish. Lets assume there is no time consuming work other than thread waits. Execution will be like this: * *Future - 3000ms wait time - This will throw timeout exception but keep running since you are not terminating it on timeout. So your 4. Future still waiting for one thread to finish. Total execution time: 2000ms *Future - 1440ms wait since you already wait 2000ms - This will return as you see in your output "am". Also at 2500ms mark 3. Future will be executed and 4. Future will be started at 2500ms mark. Total execution time: 3440ms *Future - no wait time since we already wait 3440ms this will return immediately. Total execution time: 3440ms. *Future - 2060ms wait time to finish since this has been started at 2500ms mark and after start 940ms has passed. This will timeout after 2000ms(at 2940ms of wait) As you can see just 2. and 3. Futures will return when you call get() but actually all of them is executed. Sorry for bad formatting and any typos, as i am writing on mobile.
unknown
d16761
val
You need to use background-size:coverbut propely. That means give 100% height to your .content(and add it to all the parents including html) basically: html, section {height:100%;} body { width: 100%; height: 100%; margin: 0; padding: 0; text-align: center; background: #fff; } *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } /* Structure */ .content{ width: 100%; position: relative; height: 100%; margin: 0 auto; border: 3px solid #fff; background:url(http://jedesigns.uk/img/hd-sunset-river-HD-1200x1920.jpg) no-repeat; background-size:cover; background-position:center, bottom; } .content img { /* max-width: 100%;*/ } and I also removed the styles you add inline. .content img is wrong css as you don't have any <img>in the html to call. JSFIDDLE
unknown
d16762
val
In PowerShell that: @{extensionAttribute2="Neuer Wert"} means a Hashtable literal, not just string. So, in C# you also have to create a Hashtable object: new Hashtable{{"extensionAttribute2","Neuer Wert"}} Although, that is not fully equivalent to PowerShell, since PowerShell create Hashtable with case insensitive key comparer. But, very likely, that you can use any collection implementing IDictionary, not just a Hashtable.
unknown
d16763
val
RecursiveDirectoryIterator::__construct expects a path not a uri. To fix this try: $dir = get_stylesheet_directory() . '/js'; // This gives you a path instead A: You are passing an URL, while you have to pass a path. Check it here: http://php.net/manual/en/class.recursivedirectoryiterator.php
unknown
d16764
val
Use masking - img[(img==zero_val).all(-1)] = new_val , where zero_val is the zero color and new_val is the new color to be assigned at those places where we have zero colored pixels. Sample run - # Random image array In [112]: img = np.random.randint(0,255,(4,5,3)) # Define sample zero valued and new valued arrays In [113]: zero_val = [255,146,0] ...: new_val = [255,255,255] ...: # Set two random points/pixels to be zero valued In [114]: img[0,2] = zero_val In [115]: img[2,3] = zero_val # Use proposed approach In [116]: img[(img==zero_val).all(-1)] = new_val # Verify that new values have been assigned In [117]: img[0,2] Out[117]: array([255, 255, 255]) In [118]: img[2,3] Out[118]: array([255, 255, 255])
unknown
d16765
val
update with $sub_array[] = "<td id=".$row->id.">".$row->program."</td>"; A: $sub_array[] = "<td id='$row->id'>$row->program</td>"; In the above code, you have wrapped $row->id in the single quote(') which causes a problem. Update your code with $sub_array[] = "<td id='".$row->id."'>".$row->program."</td>"; A: You can use onclick function for this task. When you click on the specific td the value get in function and perform ajax. $sub_array[] = "<td onclick='your_function(".$row->id.")'>".$row->program."</td>"; Than in jquery call the function function your_function(id='') { if(id!='') { //your ajax call here } }
unknown
d16766
val
Here is an example for finding all cities, towns, villages and hamlets in the country Andorra: [out:json][timeout:25]; // fetch area β€œAndorra” to search in {{geocodeArea:Andorra}}->.searchArea; // gather results ( node[place~"city|town|village|hamlet"](area.searchArea); ); // print results out body; >; out skel qt; You can view the result at overpass-turbo.eu after clicking the run button. Note: When running this query for larger countries you might need to increase the timeout value. Also rendering the result in the browser might not be possible due to performance reasons. In this case use the export button and download the raw data instead.
unknown
d16767
val
You can do it using getExtra method Google Android getExtra SecondActivity.java public class SecondActivity extends AppCompatActivity { TextView mother,father; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second.xml); mother = (TextView)findViewById(R.id.textView); father = (TextView)findViewById(R.id.textView2); mother.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle bundle = new Bundle(); bundle.putString("id", seciliodaid); bundle.putInt("type", 0); Intent newIntent; newIntent = new Intent(SecondActivity.this, FirstActivity.class); newIntent.putExtras(bundle); startActivityForResult(newIntent, 0); } }); father.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle bundle = new Bundle(); bundle.putString("id", seciliodaid); bundle.putInt("type", 1); Intent newIntent; newIntent = new Intent(SecondActivity.this, FirstActivity.class); newIntent.putExtras(bundle); startActivityForResult(newIntent, 0); } }); } } FirstActivity.java public class FirstActivity extends AppCompatActivity { TextView PersonName; Bundle data; int type=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); PersonName = (TextView)findViewById(R.id.PersonName); try { data = getIntent().getExtras(); type = data.getInt("type"); if(type==0){ PersonName.setText("Mother"); }else if(type==1){ PersonName.setText("Father"); } }catch (Exception e){ } PersonName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent p = new Intent(FirstActivity.this, SecondActivity.class); startActivity(p); } }); } } A: Although you can use Bundle to do so (as another answer suggests), if you just need strings, then you can do the following (which I believe is simpler but it would depend on your implementation): In button onClickListener of FirstActivity.java: Intent intent = new Intent(this, SecondActivity.class); intent.putExtra("Mother", mother.getText().toString()); intent.putExtra("Father", father.getText().toString()); In text view onClickListener of SecondActivity.java: String mother = getIntent().getStringExtra("Mother"); String father = getIntent().getStringExtra("Father");
unknown
d16768
val
I decided to go with GareginSargsyan suggestion. The main problem was that i was trying to inflate the default android list, so i instantiated a new ListView , set the ContentView of the list view and the rest is history. public class NewsActivity extends ActionBarActivity { ListView list; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_platinum_news_list); String[] itemname = { "Bafana crash out of Afcon", "Mali and Guinea face ultimate lottery", "Orlando Pirates eye cup glory", "Ivory Coast advance to Afcon quarters", "Algeria qualify for Afcon quarter-finals", "Reflect on Afcon lessons - Mbalula", "Tovey preaches patience with Bafana", "SuperSport's Brockie harbours lofty goals" }; Integer[] imgid = { R.drawable.bafana, R.drawable.mailguinea, R.drawable.orlando, R.drawable.ivorycoast, R.drawable.algeria, R.drawable.reflection, R.drawable.tovey, R.drawable.supersport, }; // CustomListAdapter adapter = new CustomListAdapter(this, itemname, imgid); // setListAdapter(adapter); CustomListAdapter test = new CustomListAdapter(this, itemname, imgid); list = (ListView) findViewById(R.id.list); list.setAdapter(test); centreLogo(); } private void centreLogo() { // TODO Auto-generated method stub Drawable d = getResources().getDrawable(R.drawable.banner); getSupportActionBar().setBackgroundDrawable(d); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayShowCustomEnabled(true); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setCustomView(R.layout.news_view); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setIcon(R.drawable.icon); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar getMenuInflater().inflate(R.menu.newsmenu, menu); return true; } public void readMore(View view) { Intent read = new Intent(NewsActivity.this, ReadMoreActivity.class); startActivity(read); } } A: Most likely, getActionBar() is causing the exception. Try using getSupportActionBar() instead.
unknown
d16769
val
You can loop through .Values.school.students using range {{- if .Values.school.students }} students: -| {{- range .Values.school.students }} - {{ . | quote }} {{- end }} {{- end -}}
unknown
d16770
val
You never add MainPanel to the applet itself. i.e., add(MainPanel); Also, since MainPanel uses BorderLayout, you will need to add the subPanels with a BorderLayout.XXX constant. i.e., change this: MainPanel.add(buttonPanel); MainPanel.add(calcPanel); MainPanel.add(textPanel); to: MainPanel.add(buttonPanel, BorderLayout.CENTER); MainPanel.add(calcPanel, BorderLayout.PAGE_END); // wherever you want to add this MainPanel.add(textPanel, BorderLayout.PAGE_START); Note that your code can be simplified greatly by using arrays or Lists. Or could simplify it in other ways, for instance: public void assumingCorrectNumberFormats(ActionEvent e) throws DivideByZeroException { String actionCommand = e.getActionCommand(); String numbers = "1234567890"; if (numbers.contains(actionCommand)) { operand.append(actionCommand); // if you need to work with it as a number int num = Integer.parseInt(actionCommand); } Myself, I'd use a different ActionListeners for different functionality, for instance one ActionListener for numeric and . entry buttons and another one for the operation buttons.
unknown
d16771
val
TCP is a "reliable" protocol, which means the data will be received at the other end if there are no socket errors. I have seen numerous efforts at second-guessing TCP with a higher level application confirmation, but IMHO this is usually a waste of time and bandwidth. Typically the problem you describe is handled through normal client/server design, which in its simplest form goes like this... The client sends a request to the server and does a blocking read on the socket waiting for some kind of response. If there is a problem with the TCP connection then that read will abort. The client should also use a timeout to detect any non-network related issue with the server. If the request fails or times out then the client can retry, report an error, etc. Once the server has processed the request and sent the response it usually no longer cares what happens - even if the socket goes away during the transaction - because it is up to the client to initiate any further interaction. Personally, I find it very comforting to be the server. :-) A: I'm not a C# programmer, but the way you've asked this question is slightly misleading. The only way to know when your data has been "received", for any useful definition of "received", is to have a specific acknowledgment message in your protocol which indicates the data has been fully processed. The data does not "leave" your network card, exactly. The best way to think of your program's relationship to the network is: your program -> lots of confusing stuff -> the peer program A list of things that might be in the "lots of confusing stuff": * *the CLR *the operating system kernel *a virtualized network interface *a switch *a software firewall *a hardware firewall *a router performing network address translation *a router on the peer's end performing network address translation So, if you are on a virtual machine, which is hosted under a different operating system, that has a software firewall which is controlling the virtual machine's network behavior - when has the data "really" left your network card? Even in the best case scenario, many of these components may drop a packet, which your network card will need to re-transmit. Has it "left" your network card when the first (unsuccessful) attempt has been made? Most networking APIs would say no, it hasn't been "sent" until the other end has sent a TCP acknowledgement. That said, the documentation for NetworkStream.Write seems to indicate that it will not return until it has at least initiated the 'send' operation: The Write method blocks until the requested number of bytes is sent or a SocketException is thrown. Of course, "is sent" is somewhat vague for the reasons I gave above. There's also the possibility that the data will be "really" sent by your program and received by the peer program, but the peer will crash or otherwise not actually process the data. So you should do a Write followed by a Read of a message that will only be emitted by your peer when it has actually processed the message. A: In general, I would recommend sending an acknowledgment from the client anyway. That way you can be 100% sure the data was received, and received correctly. A: If I had to guess, the NetworkStream considers the data to have been sent once it hands the buffer off to the Windows Socket. So, I'm not sure there's a way to accomplish what you want via TcpClient. A: I can not think of a scenario where NetworkStream.Write wouldn't send the data to the server as soon as possible. Barring massive network congestion or disconnection, it should end up on the other end within a reasonable time. Is it possible that you have a protocol issue? For instance, with HTTP the request headers must end with a blank line, and the server will not send any response until one occurs -- does the protocol in use have a similar end-of-message characteristic? Here's some cleaner code than your original version, removing the delegate, field, and Thread.Sleep. It preforms the exact same way functionally. void SendData(TcpClient tcp, byte[] data) { NetworkStream ns = tcp.GetStream(); // BUG?: should bytWriteBuffer == data? IAsyncResult r = ns.BeginWrite(bytWriteBuffer, 0, data.Length, null, null); r.AsyncWaitHandle.WaitOne(); ns.EndWrite(r); } Looks like the question was modified while I wrote the above. The .WaitOne() may help your timeout issue. It can be passed a timeout parameter. This is a lazy wait -- the thread will not be scheduled again until the result is finished, or the timeout expires. A: I try to understand the intent of .NET NetworkStream designers, and they must design it this way. After Write, the data to send are no longer handled by .NET. Therefore, it is reasonable that Write returns immediately (and the data will be sent out from NIC some time soon). So in your application design, you should follow this pattern other than trying to make it working your way. For example, use a longer time out before received any data from the NetworkStream can compensate the time consumed before your command leaving the NIC. In all, it is bad practice to hard code a timeout value inside source files. If the timeout value is configurable at runtime, everything should work fine. A: How about using the Flush() method. ns.Flush() That should ensure the data is written before continuing. A: Bellow .net is windows sockets which use TCP. TCP uses ACK packets to notify the sender the data has been transferred successfully. So the sender machine knows when data has been transferred but there is no way (that I am aware of) to get that information in .net. edit: Just an idea, never tried: Write() blocks only if sockets buffer is full. So if we lower that buffers size (SendBufferSize) to a very low value (8? 1? 0?) we may get what we want :) A: Perhaps try setting tcp.NoDelay = true
unknown
d16772
val
SQL Server has some built-in encryption capabilities (dead link) encryption capabilities you might take a look at. A: There is no way to keep a DBA out of the data unless you used a public key encryption and the end user would have to control this. If the end user lost their key, they would lose all their data. You could have a separate database where you store the keys and your DBA wouldn't have access to this DB. You would have to have two DBAs, one for the data and one for the keys. This is assuming you don't trust your DBAs, but then you shouldn't have hired them. If you trust your DBAs, then you let them have access to both DBs, but require that they have separate accounts so if one account gets compromised, they(hackers) wouldn't have access to everything. Typically, in a well designed system, the DBA/Admins have separate accounts for their personal work and an elevated account for doing work. I'm assuming the programmers only have access to a test environment. If they have access to the production environment, then they will have access to both the keys and the data. A: Every Encryption has a key and the key is ( to get / not to get ) that key :) The best way is to set the key on web.config which you can do without any programming background And I have seen a beautiful AES Encryption Algorithm implementation at StackOverflow. I would suggest you use that.
unknown
d16773
val
Do you have all the opencv development files installed on centos as well. Run a: grep "OPENVC_" Makefile to check what the Make variables contain. Also you can pipe the linker (undefined symbol) output through c++filt to see the real function name instead of the mangled name. A: I was able to solve this by going to /usr/lib64/pkgconfig and modified opencv.pc to explicitly have all libraries. I also had to move the plugins from /usr/lib/gstreamer-0.10 to /usr/lib64/gstreamer-0.10
unknown
d16774
val
Based on the clarifications you've given in the comments I've used a LocalDateTime to simplify the sample entry and retrieve the hour, but I'm sure that google.protobuf.Timestamp can be converted to a proper date and extract its hour. To keep only one object according to description, date and hour, I've added a helper method to your POJO to get a concatenation of these fields and then group by their result value in order to get a Map where to each key (description, date and hour) there is only one object associated. Lastly, I've collected the Map's values into a List. List<MyObject> list = new ArrayList<>(List.of( new MyObject(LocalDateTime.parse("06-07-2022T01:30:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description"), new MyObject(LocalDateTime.parse("06-07-2022T01:35:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description"), new MyObject(LocalDateTime.parse("06-07-2022T03:20:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description"), new MyObject(LocalDateTime.parse("06-07-2022T04:30:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description2"), new MyObject(LocalDateTime.parse("06-07-2022T04:35:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description2"), new MyObject(LocalDateTime.parse("06-07-2022T06:20:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description2"), new MyObject(LocalDateTime.parse("08-07-2022T01:30:00", DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss")), "some random description") )); List<MyObject> listRes = list.stream() .collect(Collectors.toMap( obj -> obj.getDescrDateHour(), Function.identity(), (obj1, obj2) -> obj1 )) .values() .stream(). collect(Collectors.toList()); POJO Class class MyObject { private LocalDateTime timestamp; private String description; public MyObject(LocalDateTime timestamp, String description) { this.timestamp = timestamp; this.description = description; } public LocalDateTime getTimestamp() { return timestamp; } public String getDescription() { return description; } public String getDescrDateHour() { return description + timestamp.toLocalDate().toString() + timestamp.getHour(); } @Override public String toString() { return timestamp + " - " + description; } } Here is a link to test the code https://www.jdoodle.com/iembed/v0/sZV Output Input: 2022-07-06T01:30 - some random description 2022-07-06T01:35 - some random description 2022-07-06T03:20 - some random description 2022-07-06T04:30 - some random description2 2022-07-06T04:35 - some random description2 2022-07-06T06:20 - some random description2 2022-07-08T01:30 - some random description Output: 2022-07-06T04:30 - some random description2 2022-07-08T01:30 - some random description 2022-07-06T06:20 - some random description2 2022-07-06T03:20 - some random description 2022-07-06T01:30 - some random description A: A quiet simple solution would be a HashMap. You use description as key and timestamp as value. So you always save only the last timestamp to given description and overwrite it automaticly. If you want to hold your Object I would just sort the list by date, then fill in a HashMap and transform the HashMap to List again. It has not the best Performance, but its easy. You can Sort by Date with functional Java sorting a Collection in functional style A: You could define an equality calculating class (or do it in the MyObject class, depending on what it actually represents) and use it to find unique values based on the equality definition. In this case equality would mean: same description and same timestamp with hourly precision. Here's an example (might need some tweaking, just a concept presentation): class UniqueDescriptionWithinHourIdentifier { // equals and hashCode could also be implemented in MyObject // if it's only purpose is data representation // but a separate class defines a more concrete abstraction private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHH"); private Date timestamp; private String description; UniqueDescriptionWithinHourIdentifier(MyObject object) { timestamp = object.timestamp; description = object.description; } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null || getClass() != object.getClass()) { return false; } var other = (UniqueDescriptionWithinHourIdentifier) object; return description.equals(other.description) // compare the timestamps however you want - format used for simplicity && DATE_FORMAT.format(timestamp) .equals(DATE_FORMAT.format(other.timestamp)); } @Override public int hashCode() { // cannot contain timestamp - a single hash bucket will contain multiple elements // with the same definition and the equals method will filter them out return Objects.hashCode(description); } } class MyObjectService { // here a new list without duplicates is calculated List<MyObject> withoutDuplicates(List<MyObject> objects) { return List.copyOf(objects.stream() .collect(toMap(UniqueDescriptionWithinHourIdentifier::new, identity(), (e1, e2) -> e1, LinkedHashMap::new)) .values()); } } A: Add equals & hashcode method to your MyObject class with equals has some logic like below: @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MyObject other = (MyObject) obj; Calendar calendar = Calendar.getInstance(); calendar.setTime(timestamp); int hour1=calendar.HOUR; int date1 = calendar.DATE; calendar.setTime(other.timestamp); int hour2 = calendar.HOUR; int date2 =calendar.DATE; return Objects.equals(hour1, hour2) && Objects.equals(date1, date2); } Here, basically I am checking if 2 objects has same hour & date & if so, just ignore another object. Once you do that, you can just use : List<MyObject> myList = new ArrayList<>(); myList.stream().distinct().collect(Collectors.toList()); // returns you new distinct objects list. Please note, you can use default implementation of hashCode generated via your editor for this case. distinct() method of stream is checking if you have equals & hashcode available for underlying streams class. Note: you can extend equals to check day , date, month, year etc. for verifying exact date.
unknown
d16775
val
A rebuild, a redeploy and a restart solved the problem. Really strange. To me this sounds like a system thing and would not have to do with the app itself. Best regards Fredrik
unknown
d16776
val
As stated in the comments to my question, MatDialog is provided in MatDialogModule's decorator, therefore for each lazy module a new instance of the MatDialog is created, with visibility on that module's components. After all, a dialog service doesn't need to be a singleton and this approach is fine, so I've ended up providing my modal service in the module's metadata too instead of just in the forRoot method.
unknown
d16777
val
I managed to solve it. Debug.Print oHDoc.getElementsByClassName("UpplysningTableSecondTd").Item(0).innerText Debug.Print oHDoc.getElementsByClassName("UpplysningTableSecondTd").Item(1).innerText
unknown
d16778
val
It matters what system you're exporting from, but in this case you tagged the question Blender so I will give an answer for exporting from Blender. With most formats, exporting is just a matter of gathering up and organizing the data (vertices, attributes, meshes, textures and/or texture filename references, and the like) and packing into the exported file according to the format specification. With the particular case of Blender exporting to glTF, there's a little catch. The glTF file format is particular about certain color channels. For example, roughness gets stored in glTF's green channel, metallic in the blue channel, and so on. So if a Blender user supplies a greyscale image for roughness and a separate image for metallic, Blender can't export those images as-is to a glTF file. So the Blender glTF exporter includes a section on image encoding. This bit of Python code will adapt the user-supplied images, when needed, to reassign color channels to match the glTF specification. Having all glTF assets use the same channel assignments makes it much easier for viewers to have shaders that work for all glTF files, particularly those systems that use precompiled shaders with runtime assets. The glTF mesh data may also be different from Blender's mesh. The glTF format specifies the data the way a GPU wants to receive it, with vertex attributes (glTF accessors) and the like. This means that artist-friendly features such as per-face UVs and per-face normals are converted to separate vertices in the exported glTF. Per-face attributes must be unwelded, converted into separate GPU vertices with separate vertex attributes. Some users perceive this as an increase in the number of vertices in the model, but internally the GPU needs this expanded version of the mesh data to function. In both these cases, the difference between artist asset interchange vs. raw GPU data delivery is visible. The glTF format makes the intentional choice to go with the latter, as a "transmission format" for publishing to the end user. This lightens the load on readers and viewers who wish to receive the file and render it quickly. But it does place compute requirements on glTF exporters.
unknown
d16779
val
Here are some ways to do it: * *<a href="" (click)="false">Click Me</a> *<a style="cursor: pointer;">Click Me</a> *<a href="javascript:void(0)">Click Me</a> A: You have prevent the default browser behaviour. But you don’t need to create a directive to accomplish that. It’s easy as the following example: my.component.html <a href="" (click)="goToPage(pageIndex, $event)">Link</a> my.component.ts goToPage(pageIndex, event) { event.preventDefault(); console.log(pageIndex); } A: I have 4 solutions for dummy anchor tag. 1. <a style="cursor: pointer;"></a> 2. <a href="javascript:void(0)" ></a> 3. <a href="current_screen_path"></a> 4.If you are using bootstrap: <button class="btn btn-link p-0" type="button" style="cursor: pointer"(click)="doSomething()">MY Link</button> A: Here is a simple way <div (click)="$event.preventDefault()"> <a href="#"></a> </div> capture the bubbling event and shoot it down A: Updated for Angular 5 import { Directive, HostListener, Input } from '@angular/core'; @Directive({ // tslint:disable-next-line:directive-selector selector : '[href]' }) export class HrefDirective { @Input() public href: string | undefined; @HostListener('click', ['$event']) public onClick(event: Event): void { if (!this.href || this.href === '#' || (this.href && this.href.length === 0)) { event.preventDefault(); } } } A: Not sure why people suggest using routerLink="", for me in Angular 11 it triggers navigation. This is what works for me: <div class="alert">No data yet, ready to <a href="#" (click)="create();$event.preventDefault()">create</a>?</div> A: In my case deleting href attribute solve problem as long there is a click function assign to a. A: If you have Angular 5 or above, just change <a href="" (click)="passTheSalt()">Click me</a> into <a [routerLink]="" (click)="passTheSalt()">Click me</a> A link will be displayed with a hand icon when hovering over it and clicking it won't trigger any route. Note: If you want to keep the query parameters, you should set queryParamsHandling option to preserve: <a [routerLink]="" queryParamsHandling="preserve" (click)="passTheSalt()">Click me</a> A: There are ways of doing it with angular2, but I strongly disagree this is a bug. I'm not familiarized with angular1, but this seems like a really wrong behavior even though as you claim is useful in some cases, but clearly this should not be the default behavior of any framework. Disagreements aside you can write a simple directive that grabs all your links and check for href's content and if the length of it it's 0 you execute preventDefault(), here's a little example. @Directive({ selector : '[href]', host : { '(click)' : 'preventDefault($event)' } }) class MyInhertLink { @Input() href; preventDefault(event) { if(this.href.length == 0) event.preventDefault(); } } You can make it to work across your application by adding this directive in PLATFORM_DIRECTIVES bootstrap(App, [provide(PLATFORM_DIRECTIVES, {useValue: MyInhertLink, multi: true})]); Here's a plnkr with an example working. A: A really simple solution is not to use an A tag - use a span instead: <span class='link' (click)="doSomething()">Click here</span> span.link { color: blue; cursor: pointer; text-decoration: underline; } A: An achor should navigate to something, so I guess the behaviour is correct when it routes. If you need it to toggle something on the page it's more like a button? I use bootstrap so I can use this: <button type="button" class="btn btn-link" (click)="doSomething()">My Link</button> A: I am using this workaround with css: /*** Angular 2 link without href ***/ a:not([href]){ cursor: pointer; -webkit-user-select: none; -moz-user-select: none; user-select: none } html <a [routerLink]="/">My link</a> Hope this helps A: simeyla solution: <a href="#" (click)="foo(); false"> <a href="" (click)="false"> A: That will be same, it doesn't have anything related to angular2. It is simple html tag. Basically a(anchor) tag will be rendered by HTML parser. Edit You can disable that href by having javascript:void(0) on it so nothing will happen on it. (But its hack). I know Angular 1 provided this functionality out of the box which isn't seems correct to me now. <a href="javascript:void(0)" >Test</a> Plunkr Other way around could be using, routerLink directive with passing "" value which will eventually generate blank href="" <a routerLink="" (click)="passTheSalt()">Click me</a> A: you need to prevent event's default behaviour as follows. In html <a href="" (click)="view($event)">view</a> In ts file view(event:Event){ event.preventDefault(); //remaining code goes here.. } A: I wonder why no one is suggesting routerLink and routerLinkActive (Angular 7) <a [routerLink]="[ '/resources' ]" routerLinkActive="currentUrl!='/resources'"> I removed the href and now using this. When using href, it was going to the base url or reloading the same route again. A: Updated for Angular2 RC4: import {HostListener, Directive, Input} from '@angular/core'; @Directive({ selector: '[href]' }) export class PreventDefaultLinkDirective { @Input() href; @HostListener('click', ['$event']) onClick(event) {this.preventDefault(event);} private preventDefault(event) { if (this.href.length === 0 || this.href === '#') { event.preventDefault(); } } } Using bootstrap(App, [provide(PLATFORM_DIRECTIVES, {useValue: PreventDefaultLinkDirective, multi: true})]);
unknown
d16780
val
To do this, you could split the string into 3 parts (the first group of letters, the numbers, and then the second group of letters). Then you can use s.isalpha() and s.isnumeric(). For example: while True: c=input('Password: ') if len(c)==7 and c[:2].isalpha() and c[2:4].isnumeric() and c[4:].isalpha(): break else: print('Invalid input') print('Valid input') A: Could you provide more information regarding the question, is the example you have provided the format you are attempting to match? AA99AAA, so 2-alpha, 2-numeric, 3-alpha? There are two approaches off the top of my head you could take here, one would be to utilize regular expressions to match on something like [\w]{2}[\d]{2}[\w]{3}, alternatively you could iterate through the string (recall that strings are character arrays). For this approach you would have to generate substrings to isolate parts you are interested in. So.. for c in user_input[0:2]: if c.isdigit: print('Invalid Input') for c in user_input[3:5]: ... ... There are definitely more pythonic ways to approach this but this should be enough information to help you formalize a solution. A: I finally did it! After about an hour... So I used [] formatting and .isdigit/.isalpha to check each part of the code, like recommended above, however I did it in a slightly different way: while True: regNo = input("Registration number:") if len(regNo) != 7: print("Invalid Registration Number! Please try again") elif regNo[:2].isdigit(): print("Invalid Registration Number! Please try again!") elif regNo[2:4].isalpha(): print("Invalid Registration Number! Please try again!") elif regNo[4:].isdigit(): print("Invalid Registration Number! Please try again!") else: break Hopefully this helps anyone else who stumbles across this problem!
unknown
d16781
val
Consider the below example having nodes accessibility extended checks and using .click method instead of .submit, since the last one leads to 403 error page for me: Option Explicit Dim objIE, strMsg DropBoxLogin objIE, strMsg MsgBox strMsg Sub DropBoxLogin(objIE, strMsg) Set objIE = CreateObject("InternetExplorer.Application") objIE.Visible = True objIE.Navigate "https://www.dropbox.com/login" Wait objIE If Not IsNull(objIE.Document.getElementById("header-account-menu")) Then strMsg = "Already logged in" Else WaitElementById objIE, "regular-login-forms" With objIE.Document.getElementsByClassName("login-form")(0) .item("login_email").value = "[email protected]" .item("login_password").value = "mypassword" .item("remember_me").checked = False .getElementsByTagName("button")(0).click End With WaitElementById objIE, "header-account-menu" Wait objIE strMsg = "Log in completed" End If End Sub Sub Wait(objIE) Do While objIE.ReadyState < 4 Or objIE.Busy WScript.Sleep 10 Loop Do Until objIE.Document.readyState = "complete" WScript.Sleep 10 Loop End Sub Sub WaitElementById(objIE, strId) Do While IsNull(objIE.Document.getElementById(strId)) WScript.Sleep 10 Loop End Sub
unknown
d16782
val
It's not really a public API, yet. What you're using is what the goo.gl site uses itself, but it's not designed for public use like you're trying to do. They do plan on launching one though, and when they do I'm sure they'll add it as an option. See this post EDIT: This is now possible with the newly launched API. See the docs here.
unknown
d16783
val
Turns out I was missing ts-node as we don't have our build fully set up yet. So I fixed it with yarn add ts-node. Additionally, I had to simplify our tsconfig.json to remove the compilerOptions.rootDir as the prisma code is outside the src directory.
unknown
d16784
val
As Daniel points out you can control whether to open in a new window but not a new tab. If the user has configured their browser so that new windows should open in new tabs (like I do) then you're golden. If not it will open in a new window. You can't control tabs. A: I would do this. <a href="viewfile.asp?file=somefile.pdf" target="_blank">somefile.pdf</a> That way this opens in a new window/tab. Any server side language does not have control of the browser. To serve it as a PDF, call <% response.ContentType="application/pdf" %>
unknown
d16785
val
I found a thread on the project's gitHub ( https://github.com/PhilJay/MPAndroidChart/issues/12 ). Apparently, this feature is not yet implemented. Update Doing a bit of search, I found this alternative library: https://github.com/lecho/hellocharts-android It supports values for x-axis. UPDATE Since 2016, this feature has been included in MPAndroid. See https://github.com/PhilJay/MPAndroidChart/blob/master/MPChartExample/src/main/java/com/xxmassdeveloper/mpchartexample/LineChartTime.java for an exapmle in the docs. A: You can make new array with full dates and fill empty positions with previous values. For example: you making an array may[31] for each day of may, initializate it with zeroes, and then do something like this: may[1] = values[1]; for (int i = 2; i <= may.size(); ++i) { if (may[i] == 0) may[i] = may[i-1]; }
unknown
d16786
val
In lack of better alternatives or if none else answers my question this will be my solution. This is the start of a class with the methods this far to avoid repeated null check statements etc. public class SQLiteStatementExtension { public static void BindNullable(SQLiteStatement statement, int index, String value) { if(value == null){ statement.bindNull(index); } else { statement.bindString(index, value); } } public static void BindNullable(SQLiteStatement statement, int index, Calendar value) { if(value == null){ statement.bindNull(index); } else { statement.bindLong(index, value.getTimeInMillis()); } } public static void BindNullable(SQLiteStatement statement, int index, byte[] value) { if(value == null){ statement.bindNull(index); } else { statement.bindBlob(index, value); } } public static void Bind(SQLiteStatement satement, int index, boolean value) { satement.bindLong(index, value ? 1 : 0); } }
unknown
d16787
val
Consider this: scala> (1 to 5).length res1: Int = 5 and this: >>> len(xrange(1, 5)) 4
unknown
d16788
val
You just need to create an object of the class and access it like variable Suppose class A having @FindBy function and variable is suppose myelement Then use (it is Java, try similar in whatever lang you are using): A aobject= new A(); A.myelement;
unknown
d16789
val
If I understand your problem correct then you need to use ArrayList and HashMap to achieve this: First you can create ArrayList of String to store X nouns. An ex: of Arraylist is: List<String> nouns = new ArrayList<String>(); nouns.add('nounA'); // add related noun //or String nounStr = 'new Noun' nouns.add(nounStr); Then you can categorise particular nouns by HashMap HashMap<String, List<String> > nounCategory = new HashMap<String, List<String> >(); nounCategory.put('madLib1', 'nouns'); // add all list with a unique key madLib1 ... To learn more about using List and HashMap read reference List:here and HashMap:here A: If you have the count of nouns, say, in int nounCount, use arrays like this: String[] nouns = new String[nounCount]; // Create an array for (int i = 0; i < nouns.length; i++) { nouns[i] = scan.next(); // Set each item } Then you would be able to access different words as noun[0], noun[1], etc. You're likely to use loops and store index of selected noun somewhere though. See also: Java arrays tutorial
unknown
d16790
val
If it's really that simple, you can just write it with printf() or similar. For parsing, you're best off using a real XML parser (perhaps the SimpleXML that @netpork suggested). But for something truly this trivial, you could just use regexes -- here's my usual set, from which you'd need mainly 'attrlist' and 'stag' (for attribute list and start-tag). xname = "([_\\w][-_:.\\w\\d]*)"; # XML NAME (imperfect charset) xnmtoken = "([-_:.\\w\\d]+)"; # xncname = "([_\\w][-_.\\w\\d]*)"; # qlit = '("[^"]*"|\'[^\']*\')'; # Includes the quotes attr = "$xname\\s*=\\s*$qlit"; # Captures name and value attrlist = "(\\s+$attr)*"; # startTag = "<$xname$attrlist\\s*/?>"; # endTag = "</$xname\\s*>"; # comment = "(<!--[^-]*(-[^-]+)*-->)"; # Includes delims pi = "(<\?$xname.*?\?>)"; # Processing instruction dcl = "(<!$xname\\s+[^>]+>)"; # Markup dcl (imperfect) cdataStart = "(<!\[CDATA\[)"; # Marked section open cdataEnd = "(]]>)"; # Marked section close charRef = "&(#\\d+|#[xX][0-9a-fA-F]+);"; # Num char ref (no delims) entRef = "&$xname;"; # Named entity ref pentRef = "%$xname;"; # Parameter entity ref xtext = "[^<&]*"; # Neglects ']]>' xdocument = "^($startTag|$endTag|$pi|$comment|$entRef|$xtext)+\$"; A draft of the XML spec even included a "trivial" grammar for XML, that can find node boundaries correctly, but not catch all errors, expanding entity references, etc. See https://www.w3.org/TR/WD-xml-lang-970630#secF. The main drawback is that if you run into fancier data later, it may break. For example, someone might send you data with a comment in there, or a syntax error, or an unquoted attribute, or using &quo;, or whatever. A: You can use XmlPullParser for first time parsing. Then I would suggest storing the data in sqllite or shared preferences depending on the complexity of queries or size of data. https://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
unknown
d16791
val
Simplest I can think of without using some complex regex and assuming the &c and &u are static, is this - first decoding the string as suggested by Jedi var str = "about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&f=regulard=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A" var url = decodeURIComponent(str).split("&u=")[1].split("&c")[0]; console.log(url) And here is why I close as duplicate: function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); } var str = "about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&f=regulard=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A" var url = getParameterByName("u",str); console.log(url); A: What you are trying to do is to retrieve a query parameter from a URL, and then decode it. For this, you should use libraries build for the purpose, not regexp. For example, many regexp approaches will depend on the precise order of the query params, which is something you cannot really (or should not) rely on. Here's an example using the URL API, which is stable and widely supported (other than IE11, and a bug in Firefox for non-http-type URLs such as about:neterror currently in the process of being fixed): var str = "about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&f=regulard=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A"; var url = new URL(str); console.log(url.searchParams.get('u')); A: You can capture the sub string you need and then use back reference to extract and reformat it: var s = "about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&f=regular d=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A" var url = s.replace(/^about:neterror\?e=nssFailure2&u=(https)%3A(.*)&c=UTF[\s\S]*$/, "$1:$2") console.log(url) Using decodeURIComponent: var s = "about:neterror?e=nssFailure2&u=https%3A//revoked.badssl.com/&c=UTF8&f=regular d=An%20error%20occurred%20during%20a%20connection%20to%20revoked.badssl.com.%0A%0APeer%E2%80%99s%20Certificate%20has%20been%20revoked.%0A%0AError%20code%3A%20%3Ca%20id%3D%22errorCode%22%20title%3D%22SEC_ERROR_REVOKED_CERTIFICATE%22%3ESEC_ERROR_REVOKED_CERTIFICATE%3C/a%3E%0A" var url = decodeURIComponent(s).replace(/^about:neterror\?e=nssFailure2&u=(.*)&c=UTF[\s\S]*$/, "$1") console.log(url)
unknown
d16792
val
Try this override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { var defaultHeight = /*your default height*/ if videos.count > 0 { let video = videos[0] return video.height + 10 + 10 // video height + top padding + bottom padding } return defaultHeight } Also remove the collectionView height constraint from the Interface builder. Now you don't have to set constraint in the cellForItemAtIndexPath. A: According to your error report, it seems like the case I was attempting to address in this SO question. If the conflicting constraints contain UIView-Encapsulated-Layout-Height it means the conflict arises during calculating dynamic height based on autolayout. Just lower one of the vertical constraints priority to 999 - if the code works, it's ok and you are good to go.
unknown
d16793
val
also faced the same issue, Finally I found that there is some issue with volley - JSONObject request. (after few googling!) the getParams() doesn't invoke because JsonObjectRequest extended JsonRequest which invoke getBody() directly to encoding the constructor second parameter(call requestBody) as contentType, that's why it ignore your getParam() method. try this solution, it resolved my problem. import java.io.UnsupportedEncodingException; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.toolbox.HttpHeaderParser; public class CustomRequest extends Request<JSONObject> { private Listener<JSONObject> listener; private Map<String, String> params; public CustomRequest(String url, Map<String, String> params, Listener<JSONObject> reponseListener, ErrorListener errorListener) { super(Method.GET, url, errorListener); this.listener = reponseListener; this.params = params; } public CustomRequest(int method, String url, Map<String, String> params, Listener<JSONObject> reponseListener, ErrorListener errorListener) { super(method, url, errorListener); this.listener = reponseListener; this.params = params; } protected Map<String, String> getParams() throws com.android.volley.AuthFailureError { return params; }; @Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } } @Override protected void deliverResponse(JSONObject response) { // TODO Auto-generated method stub listener.onResponse(response); } } In activity/fragment do use this RequestQueue requestQueue = Volley.newRequestQueue(getActivity()); CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, this.createRequestSuccessListener(), this.createRequestErrorListener()); requestQueue.add(jsObjRequest); Volley JsonObjectRequest Post request not working
unknown
d16794
val
Unless you have implemented a push mechanism, or using an external one, such as Google C2DM, which is available for Android (I have not tested it myself, last time I checked it, it was in a beta state), the only way left is use a polling mechanism (ask every so often the web service).
unknown
d16795
val
That line of code indicates the main path of your views, for example if you have this hierarchy: views/index.html views/home/index.html views/home/news/index.html would render your views like this: res.render('/index.html', /*...*/); res.render('home/index.html', /*...*/); res.render('home/news/index.html', /*...*/);
unknown
d16796
val
YES-ish. Although PFX-now-PKCS12 was designed primarily to store or transfer a privatekey and cert and chain cert(s) as a clump, and most commonly is used for that, it is capable of storing one or more 'lone' cert(s) not matched to any privatekey. And you are correct the client wanting to connect to you should have in their truststore ideally the root cert for your server cert's chain, or alternatively your server cert itself, but decidedly not your privatekey. openssl can actually create such a PKCS12: openssl pkcs12 -export -in certfile.pem [-name $name] -nokeys -out blah.p12 # if you don't specify -name it defaults to 1 (the digit one) which can be mildly confusing # instead of being prompted for the password you can use -passout with several forms # described on the openssl man page, but consider the warning below But the result won't work in Java if they use the standard (Sun/Oracle/OpenJDK) cryptoproviders, which (in 8+) support lone cert(s) in a PKCS12 as 'trustedCert' entries in Java only if the(each) certbag has a special Sun-defined attribute which the Java providers write when they create such a file, but OpenSSL doesn't. Instead use Java's keytool in 8: jre8/bin/keytool -importcert -keystore blah.p12 -storetype pkcs12 -file $certfile [-alias $name] or in 9+ where pkcs12 is now the default: jre9+/bin/keytool -importcert -keystore blah.p12 -file $certfile [-alias $name] If you don't specify the alias it defaults to mykey. In both cases you can add -storepass $pw to avoid being prompted for it, but as a result the password will be visible on your screen, in the command history of your shell or other command processor it is has one, and in most cases to other processes run on your system concurrently, (any of) which may be a security issue or not. You can also add -noprompt to avoid the confirmation prompt. But user207421 is (roughly) correct that using such a truststore can break other SSL/TLS connection(s) made from their system, at least from the same JVM, unless the individual calls specify individual, separate truststores, and if they had coded that they would know how to handle (and ask for) a simpler certificate format, such as PEM.
unknown
d16797
val
There is a way using ActiveX, as suggested by Adiel in the Comments. Code example: excelapp = actxserver('Excel.Application'); workbook = excelapp.Workbooks.Open('myspreadsheet.xlsx'); worksheet = workbook.Sheets.Item('sheet_with_data'); worksheet.Activate; row_number = worksheet.Range('FIRST_DATA').Row; Close(workbook); Quit(excelapp); delete(ExcelApp); You should be closing everything properly to to prevent potential memory leaks.
unknown
d16798
val
One connection manager with api usable from your classes would probably be best. By implementing as a service for other classes, it keeps all the code for connections in one place where it can be modified once instead of all over the place. Also, it us usually a good rule to keep your objects to a single purpose so each can do what it needs to do and then aggregate simple objects into components and services.
unknown
d16799
val
In Java 8 Pattern class doesn't override equals. So it uses default implementation which checks whether to references point to the same location in memory.
unknown
d16800
val
The build result of nuxt generate is in the /dist folder, not in the .nuxt/dist folder.
unknown