_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d16001
val
Figured it out... Let's say you want to link against the file libGoogleAnalyticsServices.a. There are basically three things you should have in your .xcconfig to get it working. First you want to make sure you have the path to the library in your search path. Then you need to pass two flags to make the linker happy -L with the path to the directory, and -l with the library. Putting it all together will get you something like: LIBRARY_SEARCH_PATHS = $(inherited) "$(SRCROOT)/Vendor/Google Analytics" OTHER_LDFLAGS = $(inherited) -L"$(SRCROOT)/Vendor/Google Analytics" -lGoogleAnalyticsServices (You would need to adjust for your relative paths) The most helpful thing in getting this sorted out was the Log Navigator (command+8 in Xcode). By putting the static library in the Build Phases Link Binary With Libraries panel and doing a successful build, you can look details of the linker step in the logs, and see how it was passing the Analytics library to the compiler. From there it's just replicating those flags in the xcconfig.
unknown
d16002
val
I know you asked for VBA, but here's a formula. If this works, you can quickly throw in VBA (use the macro recorder to see how if you're unsure). If that's in row 1, you can use: =AVERAGE(LARGE(A1:L1,{1,2,3,4,5,6,7,8})) You should be able to change A1:l1 to be the range where your numbers are, i.e. =AVERAGE(LARGE(A1:F2,{1,2,3,4,5,6,7,8})) Edit: Per your comment, also no need for VBA. Just use conditional highlighting. Highlight your range of numbers, then go to Conditional Highlighting --> Top/Bottom Rules --> Top 10 Items. Then just change the 10 to 8, and choose a color/format. Then Apply! (each row in the above is treated as it's own range). Edt2: bah, my image has duplicate numbers which is why the top 8 rule is highlighting 9 numbers sometimes. If you request I'll try to edit and tweak A: You can use a simple Excel function to compute the answer =AVERAGE(LARGE(A1:L1, {1,2,3,4,5,6,7,8})) It is a bit more complex in VBA, but here is a function that does the same computation (explicit typing per Mat's Mug): Public Function AvgTop8(r As Range) As Double Dim Sum As Double, j1 As Integer For j1 = 1 To 12 If WorksheetFunction.Rank(r(1, j1), r) <= 8 Then Sum = Sum + r(1, j1) End If Next j1 AvgTop8 = Sum / 8# End Function The Excel RANK function returns the rank of a number in a list of numbers, with the largest rank 1 and so on. So you can search through the 12 numbers for the 8 largest, sum them and divide by 8. A: You don't need VBA for this. You can use: =AVERAGE(LARGE(A1:L1,{1;2;3;4;5;6;7;8}))
unknown
d16003
val
Splitting on a new line works for me. function main(input) { //Enter your code here var arr = input.split("\n") process.stdout.write(JSON.stringify(arr)); } process.stdin.resume(); process.stdin.setEncoding("utf-8"); var stdin_input = ""; process.stdin.on("data", function (input) { stdin_input += input; }); process.stdin.on("end", function () { main(stdin_input); }); It's important to note that process.stdout.write can only write a string. Trying to pass an array as an argument will cause an error. A: just a idea my code is just for many string or number have space between for example if you want sum two number we write in terminal : 23 56 notice i use here string_decoder for any one want to raplace number with string const {StringDecoder} = require('string_decoder'); const decode = new StringDecoder('utf8'); const sum = (a, b) => { let operation = a + b; return console.log('result is : ', operation); } process.stdin.on('readable', () => { const aa = process.stdin.read(); // read string from REPL const buffer = Buffer.from(aa); const j = decode.write(buffer).split(' '); const a = +j[0]; const b = +j[1]; // console.log(a + b) if((a & b) != null) // check if the value not empty { sum(a, b); } });
unknown
d16004
val
Depending upon your i18n end goal, you could just define the word-break property: .content { margin: auto; width: 400px; } p { background-color: #eee; word-break: break-all; } <div class="content"> <p> At vero eos et accusamus et iusto odio digducimusverylongword qui </p> </div> A: Although I realise it's probably not what you're looking for (and that @BenM's answer of using word-break: break-all is probably more appropriate)... another option is simply using text-align:justify... .content { margin: auto; width: 400px; } p { background-color: #eee; text-align:justify; } <div class="content"> <p> At vero eos et accusamus et iusto odio digducimusverylongword qui </p> </div>
unknown
d16005
val
According to this: http://info.meteor.com/blog/meteor-11-microsoft-windows-mongodb-30 Meteor supports development on windows as of version 1.1 You have to have at least windows 7 installed. I would recommend that you upgrade your version of meteor to 1.1 or greater by running npm update meteor. If you want to use the first version of meteor that supports windows you can run npm install [email protected]
unknown
d16006
val
Did you try text-decoration: none; It is hard to guess the problem from your description. You can also try inspecting that perticular div. Right click that div and select inspect element. There the browser will show you the css applied to that div or text.
unknown
d16007
val
You should not use static in such a way. If you need to share state, consider using the singleton pattern; but try to avoid static. Unwise use of "static" can turn into a nightmare (for example regarding unit testing). In addition: it seems that you are a beginner with the Java language. But creating servlets is definitely a "advanced" java topic. I really recommend you to start learning more about Java as preparation for working on servlets. Otherwise the user of your server might have many unpleasant experiences ... A: What you are doing is wrong. You should use Servlets only for the purpose of reading request parameters and sending responses. What you are trying to do, should be implemented in the Business layer of your application and if you have it implemented with EJBs, then your problem can easily be solved with an Stateful EJB.
unknown
d16008
val
Usually the showcase would be an application project in the same Angular workspace as the library project, with both sharing node_modules Here's an example (picked at random) of an Angular npm component library, with the showcase/demo app as part of the same repo (the same Angular CLI workspace) * *https://github.com/zefoy/ngx-color-picker/tree/master/projects
unknown
d16009
val
The order in the result array will be the same as the order of the input list. Like the batch method, the ordering of execution of the actions is not defined but the result will always be in the same order. Since it will have a null in the results array for gets that failed, it would have been difficult to determine which have failed without looking in each Result instance.
unknown
d16010
val
putting here for clarity but its more a comment than an answer add this in your ant build file to debug the classpath used <target name="compile" depends="clean, makedir"> <property name="myclasspath" refid="classpath"/> <echo message="Classpath = ${myclasspath}"/> <javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" includeantruntime="false" /> </target> It will print out the classpath and help you debug if the jars are correctly picked up
unknown
d16011
val
I suggest that you use regex to identify the codes to replace with random codes. This example is deliberately simplified, I have used static codes and not randomly generated one and the regex pattern needs to be defined and refined. import re sentences = ('Your order is on its way with tracking 1234567890. Visit 98765432 for more information.', 'The package has been shipped out with tracking 1245789865. Visit 65659865 for more information.') code1='9999999999' code2='11111111' for x in sentences: y = re.findall(r'(\D*)\d+(\D*)\d+(\D*)' ,x) if y[0][2]: z = y[0][0] + code1 + y[0][1] + code2 + y[0][2] print(z) output Your order is on its way with tracking 9999999999. Visit 11111111 for more information. The package has been shipped out with tracking 9999999999. Visit 11111111 for more information.
unknown
d16012
val
You forgot to project the fields that you're using in $match and $group later on. For a quick fix, use this query instead: Offer.aggregate([ { $project: { myyear: { $year: "$ending_date" }, carer_id: 1, status: 1, ending_date: 1 } }, { $match: { carer_id: req.params.carer_id, myyear: 2015, status: 3 } }, { $group: { _id: { year: { $year: "$ending_date" }, month: { $month: "$ending_date" } }, count: { $sum: 1 } } }], function (err, res) { if (err) {} // TODO handle error console.log(res); }); That said, Blakes Seven explained how to make a better query in her answer. I think you should try and use her approach instead. A: You are doing so many things wrong here, that it really warrants an explanation so hopefully you learn something. Its a Pipeline It's the most basic concept but the one people do not pick up on the most often ( and even after continued use ) that the aggregation "pipeline" is just exactly that, being "piped" processes that feed input into the each stage as it goes along. Think "unix pipe" |: ps -ef | grep mongo | tee out.txt You've seen something similar before no doubt, and it's the basic concept that output from the first thing goes to the next thing and then that manipulates to give input to the next thing and so on. So heres the basic problem with what you are asking: { $project: { myyear: {$year: "$ending_date"} } }, { $match: { carer_id : req.params.carer_id, status : 3, $myyear : "2015" } }, Consider what $project does here. You specify fields you want in the output and it "spits them out", and possibly with manipulation. Does it output these fields in "addition" the the fields in the document? No It does not. Only what you ask to come out actually comes out and can be used in the following pipeline stage(s). The $match here essentially asks for fields that are no longer present, because you only asked for one thing in the output. The same problem occurs further down as again you ask for fields you removed earlier and there simply is nothing to reference, but also everything was already removed by a $match that could not match anything. Also, that is not how field projections work as you have entered So just use a range for the date { "$match": { "carer_id" : req.params.carer_id, "status" : 3, "ending_date": { "$gte": new Date("2015-01-01"), "$lt": new Date("2016-01-01") } }}, { "$group": { "_id": { "year": { "$year": "$ending_date" }, "month": { "$month": "$ending_date" } }, "count": { "$sum": 1 } }} Why? Because it just makes sense. If you want to match the "year" then supply the date range for the whole year. We could play silliness with $redact to match on the extracted year value, but that is just wasted processing time. Doing this way is the fastest to process and can actually use an index to process faster. So don't otherthink the problem and just ask for the date range you want. A: If you want your aggregation to work you have to use $addFields instead of $project in order to keep status and carer_id in the object you pass to the $match { $addFields: { myyear: {$year: "$ending_date"} } }, { $match: { carer_id : req.params.carer_id, status : 3, $myyear : "2015" } },
unknown
d16013
val
Currently, Presto Hive connector does not provide means for creating new partitions at arbitrary locations. If your partition location is under table location, you can use Presto Hive connector procedures: * *system.create_empty_partition -- creates a new empty partition with specified values for partition keys *system.sync_partition_metadata -- synchronizes partition list in Metastore with the partitions on the storage If you want to create/declare partitions somewhere else than under table's location, please file an issue.
unknown
d16014
val
That is still correct. protobuf-net supports unexpected data via the IExtensible / Extensible API, but this is to support a different scenario. There is currently no support for having the DTO types themselves as dynamic. To do so would require significant work: that isn't a problem if there is a genuine problem to address (for example, the meta-programming re-work to allow for full pre-compilation, to support mobile / metro was significant work - but still happened). But in the case of dynamic it is not obvious to me what scenario this would usefully target.
unknown
d16015
val
If you are on Laravel 4, give Revisionable a try. This might suite your needs A: So here is what I am doing: Say this is the revision flow: 1232 -> 1233 -> 1234 1232 -> 1235 So here is what my revision table will look like: +----+--------+--------+ | id | new_id | old_id | +----+--------+--------+ | 1 | 1233 | 1232 | | 2 | 1234 | 1233 | | 3 | 1234 | 1232 | | 4 | 1235 | 1232 | +----+--------+--------+ IDs 2 and 3 show that when I open 1234, it should show both 1233 and 1232 as revisions on the list. Now the implementation bit: I will have the Paste model have a one to many relationship with the Revision model. * *When I create a new revision for an existing paste, I will run a batch insert to add not only the current new_id and old_id pair, but pair the current new_id with all revisions that were associated with old_id. *When I open a paste - which I will do by querying new_id, I will essentially get all associated rows in the revisions table (using a function in the Paste model that defines hasMany('Revision', 'new_id')) and will display to the user. I am also thinking about displaying the author of each revision in the "Revision history" section on the "view paste" page, so I think I'll also add an author column to the revision table so that I don't need to go back and query the main paste table to get the author. So that's about it! A: There are some great packages to help you keeping model revisions: * *If you only want to keep the models revisions you can use: Revisionable * *If you also want to log any other actions, whenever you want, with custom data, you can use: Laravel Activity Logger Honorable mentions: * *Activity Log. It also has a lot of options.
unknown
d16016
val
Yes you can, but should you? Here is the change your code needs: Bitmap b = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height); pictureBox1.DrawToBitmap(b, pictureBox1.ClientRectangle); Color colour = b.GetPixel(X, Y); b.Dispose(); But there is really no way around giving the PictureBox a real Image to work with somewhere if you want to do real work with it, meaning if you want to use its possibilities e.g. its SizeMode. Simply drawing on its background is just not the same. Here is a minimal code to get a real Bitmap assigned: public Form1() { InitializeComponent(); pictureBox1.Image = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height); using (Graphics graphics = Graphics.FromImage(pictureBox1.Image)) { graphics.FillRectangle(Brushes.CadetBlue, 0, 0, 99, 99); graphics.FillRectangle(Brushes.Beige, 66, 55, 66, 66); graphics.FillRectangle(Brushes.Orange, 33, 44, 55, 66); } } However if you really don't want to assign an Image you can make the PictureBox draw itself onto a real Bitmap. Note that you must draw the Rectangles etc in the Paint event for this to work! (Actually you must use the Paint event for other reasons as well!) Now you can test either way e.g. with a Label and your mouse: private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (pictureBox1.Image != null) { // the 'real thing': Bitmap bmp = new Bitmap(pictureBox1.Image); Color colour = bmp.GetPixel(e.X, e.Y); label1.Text = colour.ToString(); bmp.Dispose(); } else { // just the background: Bitmap bmp = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height); pictureBox1.DrawToBitmap(bmp, pictureBox1.ClientRectangle); Color colour = bmp.GetPixel(e.X, e.Y); label1.Text += "ARGB :" + colour.ToString(); bmp.Dispose(); } } private void pictureBox1_Paint(object sender, PaintEventArgs e) { e.Graphics.FillRectangle(Brushes.DarkCyan, 0, 0, 99, 99); e.Graphics.FillRectangle(Brushes.DarkKhaki, 66, 55, 66, 66); e.Graphics.FillRectangle(Brushes.Wheat, 33, 44, 55, 66); }
unknown
d16017
val
The solution to this finally came to this: partial void vwFamilyProcessDatas_Updating(vwFamilyProcessData entity) { if(entity.Details.EntityState.ToString() == "Modified") { var AutoAddMissingListing = entity.AutoAddMissingListing; var AutoAddOddLots = entity.AutoAddOddLots; var DefaultFilterValue = entity.DefaultFilterValue; var ExcludeZeroNumberOfUnits = entity.ExcludeZeroNumberOfUnits; var IgnoreForPricing = entity.IgnoreForPricing; var LimitEndDate = entity.LimitEndDate; var OffsetFromMaxAsAtDate = entity.OffsetFromMaxAsAtDate; var PrefilterConstituents = entity.PrefilterConstituents; var TimeDataExpires = entity.TimeDataExpires; tblFamily objFamily = tblFamilies.Where(f => f.FamilyID == entity.FamilyID).Single(); objFamily.AutoAddMissingListing = AutoAddMissingListing; objFamily.AutoAddOddLots = AutoAddOddLots; objFamily.DefaultFilterValue = DefaultFilterValue; objFamily.ExcludeZeroNumberOfUnits = ExcludeZeroNumberOfUnits; objFamily.IgnoreForPricing = IgnoreForPricing; objFamily.LimitEndDate = LimitEndDate; objFamily.OffsetFromMaxAsAtDate = OffsetFromMaxAsAtDate; objFamily.PrefilterConstituents = PrefilterConstituents; objFamily.TimeDataExpires = TimeSpan.Parse(TimeDataExpires); entity.Details.DiscardChanges(); }}
unknown
d16018
val
If you can show the images and videos in a browser, they will always find a way to copy these. You can't have the cake and eat it. The only thing you can do is to make it harder for the newbie.
unknown
d16019
val
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#syntax const allowedFields = [ "id", "candidate_id", "prospect", "location", "jobs", "name" ]; const txt = [ { "id": 34050740004, "candidate_id": 30068728004, "prospect": false, "applied_at": "2022-06-10T18:00:52.034Z", "rejected_at": null, "last_activity_at": "2022-06-10T18:03:05.070Z", "location": null, "jobs": [ { "id": 4354756004, "name": "E2E Testing", "email": "[email protected]" }, { "id": 65765, "name": "E2E consensys", "email": "[email protected]" } ] }, { "id": 34050740004, "candidate_id": 30068728004, "prospect": false, "applied_at": "2022-06-10T18:00:52.034Z", "rejected_at": null, "last_activity_at": "2022-06-10T18:03:05.070Z", "location": null, "jobs": [ { "id": 4354756004, "name": "E2E Testing", "email": "[email protected]" }, { "id": 65765, "name": "E2E consensys", "email": "[email protected]" } ] } ]; const obj = JSON.stringify(txt, allowedFields); document.getElementById("demo").innerHTML = JSON.stringify(JSON.parse(obj), null, 4); <pre id="demo"></pre>
unknown
d16020
val
Method you are looking for is: CodeRay::Scanners.list #=> [:c, :clojure, :cpp, :css, :debug, :delphi, :diff, :erb, :go, :groovy, # :haml, :html, :java, :java_script, :json, :lua, :php, :python, :raydebug, # :ruby, :sass, :scanner, :sql, :taskpaper, :text, :xml, :yaml]
unknown
d16021
val
With psutil.net_if_stats() to get only up and running network interfaces: import psutil addresses = psutil.net_if_addrs() stats = psutil.net_if_stats() available_networks = [] for intface, addr_list in addresses.items(): if any(getattr(addr, 'address').startswith("169.254") for addr in addr_list): continue elif intface in stats and getattr(stats[intface], "isup"): available_networks.append(intface) print(available_networks) Sample output: ['lo0', 'en0', 'en1', 'en2', 'en3', 'bridge0', 'utun0'] A: There is a python package get-nic which gives NIC status, up\down, ip addr, mac addr etc pip install get-nic from get_nic import getnic getnic.interfaces() Output: ["eth0", "wlo1"] interfaces = getnic.interfaces() getnic.ipaddr(interfaces) Output: {'lo': {'state': 'UNKNOWN', 'inet4': '127.0.0.1/8', 'inet6': '::1/128'}, 'enp3s0': {'state': 'DOWN', 'HWaddr': 'a4:5d:36:c2:34:3e'}, 'wlo1': {'state': 'UP', 'HWaddr': '48:d2:24:7f:63:10', 'inet4': '10.16.1.34/24', 'inet6': 'fe80::ab4a:95f7:26bd:82dd/64'}} Refer GitHub page for more information: https://github.com/tech-novic/get-nic-details
unknown
d16022
val
I have never used the vuex-orm but i think this should work, according to the docs https://vuex-orm.github.io/vuex-orm/guide/store/retrieving-data.html#simple-where-clauses computed: { user() { return this.$store.getters['entities/users/query']().where(user => user.name.toUpperCase() === this.myname.toUpperCase()).first(); } } Or even computed: { user() { return this.$store.getters['entities/users/query']().where('name', value => value.toUpperCase() === this.myname.toUpperCase()).first(); } }
unknown
d16023
val
A product does not have sales rules attached to it and there is no inbuilt method to load rules for a given product. On the cart page it is easy because the rule gets applied to the quote and on each item you can get applied_rule_ids which gives you the ids of any matched rules currently applied to the quote item which is not the same as a product object. So for example, you could have multiple sales rules which apply to the same item so applied_sales_rule_ids would give you all the applied rules not just one. You could try and load a collection of sales rules and add a filter on the product_ids column and then pass in the entity id of the product. This post here explores this with some code examples and may be of some help. A: Try to use Mage_CatalogRule_Model_Resource_Rule::getRulesFromProduct().
unknown
d16024
val
Edit 0 - FQL Solution SELECT uid,first_name,pic FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND uid IN (SELECT uid FROM group_member WHERE gid=GROUP_ID) Wouldn't the below provide you with a list of members that you could loop through to find your friends? Applications can get the list of members that belong to a group by issuing a GET request to /GROUP_ID/members with an app access_token. If the action is successful, the response will contain: Name Description Type ID The id of the user. string Name The name of the user. string administrator The user is administrator of the group. boolean via https://developers.facebook.com/docs/reference/api/app-game-groups/#read_group_members
unknown
d16025
val
Using BinaryReader and BinaryWriter over a MemoryStream tends to be the best way in my opinion. Parsing binary data: byte[] buf = f // some data from somewhere using (var ms = new MemoryStream(buf, false)) { // Read-only var br = new BinaryReader(ms); UInt32 len = br.ReadUInt32(); // ... } Generating binary data: byte[] result; using (var ms = new MemoryStream()) { // Expandable var bw = new BinaryWriter(ms); UInt32 len = 0x1337; bw.Write(len); // ... result = ms.GetBuffer(); // Get the underlying byte array you've created. } They allow you to read and write all of the primitive types you'd need for most file headers, etc. such as (U)Int16, 32, 64, Single, Double, as well as byte, char and arrays of those.  There is direct support for strings, however only if  The string is prefixed with the length, encoded as an integer seven bits at a time. This only seems useful to me if you wrote the string in this way from BinaryWriter in this way. It's easy enough however, say your string is prefixed by a DWord length, followed by that many ASCII characters: int len = (int)br.ReadUInt32(); string s = Encoding.ASCII.GetString(br.ReadBytes(len)); Note that I do not have the BinaryReader and BinaryWriter objects wrapped in a using() block. This is because, although they are IDisposable, all their Dispose() does is call Dispose() on the underlying stream (in these examples, the MemoryStream). Since all the BinaryReader/BinaryWriter are is a set of Read()/Write() wrappers around the underlying streams, I don't see why they're IDisposable anyway. It's just confusing when you try to do The Right Thing and call Dispose() on all your IDisposables, and suddenly your stream is disposed. A: To read arbitrarily-structured data (a struct) from a binary file, you first need this: public static T ToStructure<T>(byte[] data) { unsafe { fixed (byte* p = &data[0]) { return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T)); } }; } You can then: public static T Read<T>(BinaryReader reader) where T: new() { T instance = new T(); return ToStructure<T>(reader.ReadBytes(Marshal.SizeOf(instance))); } To write, convert the struct object to a byte array: public static byte[] ToByteArray(object obj) { int len = Marshal.SizeOf(obj); byte[] arr = new byte[len]; IntPtr ptr = Marshal.AllocHGlobal(len); Marshal.StructureToPtr(obj, ptr, true); Marshal.Copy(ptr, arr, 0, len); Marshal.FreeHGlobal(ptr); return arr; } ...and then just write the resulting byte array to a file using a BinaryWriter. A: Here is an simple example showing how to read and write data in Binary format to and from a file. using System; using System.IO; namespace myFileRead { class Program { static void Main(string[] args) { // Let's create new data file. string myFileName = @"C:\Integers.dat"; //check if already exists if (File.Exists(myFileName)) { Console.WriteLine(myFileName + " already exists in the selected directory."); return; } FileStream fs = new FileStream(myFileName, FileMode.CreateNew); // Instantialte a Binary writer to write data BinaryWriter bw = new BinaryWriter(fs); // write some data with bw for (int i = 0; i < 100; i++) { bw.Write((int)i); } bw.Close(); fs.Close(); // Instantiate a reader to read content from file fs = new FileStream(myFileName, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); // Read data from the file for (int i = 0; i < 100; i++) { //read data as Int32 Console.WriteLine(br.ReadInt32()); } //close the file br.Close(); fs.Close(); } } }
unknown
d16026
val
I ran into this same problem a few days ago. Running the HttpResponse on its own thread fixed the Null response. Try using java threading instead of the android async task. http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html
unknown
d16027
val
Good day sir, I wanna share some of my ideas here and I know it's not a solution but it's too long for a comment. I created a SPA before which used msal.js to make users sign in and generate access token to call graph api, you must know here that when you generate the access token you need to set the scope of the target api, for example, you wanna call 'graph.microsoft.com/v1.0/me', you need a token with the scope 'User.Read, User.ReadWrite' and you also need to add delegated api permission to the azure app. So as the custom api of your own backend program. I created a springboot api which will return 'hello world' if I call 'localhost:8080/hello', if I wanna my api protected by azure ad, I need to add a filter to validate all the request if has a valid access token. So I need to find a jwt library to decode the token in request head and check if it has a token, if the token has expired and whether the token has the correct scope. So here, which scope is the correct scope? It's decided by the api you exposed in azure ad. You can set the scope named like 'AA_Custom_Impression', and then you can add this delegate api permission to the client azure ad app, then you that app to generate an access token with the scope of 'AA_Custom_Impression'. After appending the Bearer token in calling request, it will be filtered by backend code. I don't know about python, so I can just recommend you this sample, you may try it, it's provided by microsoft. A: I've solved the similar issue. I don't found how to directly validate access token, but you can just call graph API on backend with token you've got on client side with MSAL. Node.js example: class Microsoft { get baseUrl() { return 'https://graph.microsoft.com/v1.0' } async getUserProfile(accessToken) { const response = await got(`${this.baseUrl}/me`, { headers: { 'x-li-format': 'json', Authorization: `Bearer ${accessToken}`, }, json: true, }) return response.body } // `acessToken` - passed from client async authorize(accessToken) { try { const userProfile = await this.getUserProfile(accessToken) const email = userProfile.userPrincipalName // Note: not every MS account has email, so additional validation may be required const user = await db.users.findOne({ email }) if (user) { // login logic } else { // create user logic } } catch (error) { // If request to graph API fails we know that token wrong or not enough permissions. `error` object may be additionally parsed to get relevant error message. See https://learn.microsoft.com/en-us/graph/errors throw new Error('401 (Unauthorized)') } } } A: Yes we can validate the Azure AD Bearer token. You can fellow up below link, https://github.com/odwyersoftware/azure-ad-verify-token https://pypi.org/project/azure-ad-verify-token/ We can use this for both Django and flask. You can directly install using pip but I'm not sure in Django. If Django install working failed then try to copy paste the code from GitHub Validation steps this library makes: 1. Accepts an Azure AD B2C JWT. Bearer token 2. Extracts `kid` from unverified headers. kid from **Bearer token** 3. Finds `kid` within Azure JWKS. KID from list of kid from this link `https://login.microsoftonline.com/{tenantid}/discovery/v2.0/keys` 4. Obtains RSA key from JWK. 5. Calls `jwt.decode` with necessary parameters, which inturn validates: - Signature - Expiration - Audience - Issuer - Key - Algorithm
unknown
d16028
val
You should initialize AVPlayer inside bubblePop and keep strong reference to it. Try this: @interface ViewController() @property (strong, nonatomic) NSMutableDictionary *players; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.players = [[NSMutableDictionary alloc] init]; } - (void)bubblePop { NSURL *URL = your sound URL; AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:URL]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem]; AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem]; self.players[playerItem] = player; [player play]; } -(void)itemDidFinishPlaying:(AVPlayerItem *)sender { [self.players removeObjectForKey:sender]; } @end
unknown
d16029
val
Don't try to hide the imports needed in your module in another module - it'll make your code harder to read. And good editors will allow you to collapse the import section if it gets in the way of editing. There's ways of doing this, but they'll make your code harder to understand and it'll increase the odds of errors that are hard to figure out for yourself. Having said that - this is how it can be done, if for some reason you know better, or actually have that rare use case where it makes sense: import_lib.py from django.shortcuts import render, get_object_or_404 other.py from import_lib.py import * # a rare case where a * import actually makes sense Since * imports everything and makes it part of the name space of the module doing the importing, you get exactly what you need. If you feel your use case does warrant this, at least consider a name for the imported module that's a bit more descriptive, like django_imports.py, or whatever the logical grouping for the imports in that file is.
unknown
d16030
val
Might be the for loop end condition. You have this: for (let i = 0; word.length; i++) { Instead of this: for (let i = 0; i < word.length; i++) { A: function find_max_repeat_count_in_word(word) { const chars = word && word.split('').filter(char => (char || '').trim()) || []; let counterMap = {}; let max = 0; // max value can be tracked along side building the counter map chars.forEach(char => { counterMap = {...counterMap, [char]: (counterMap[char] || 0) + 1 }; if (counterMap[char] > max) { max = counterMap[char]; } }); return max; } Considerations It doesn't take into consideration whitespaces Since expected is just max, it doesn't matter if two or more characters have same count Illustration function find_max_repeat_count_in_word(word) { const chars = word && word.split('').filter(char => (char || '').trim()) || []; let counterMap = {}; let max = 0; // max value can be tracked along side building the counter map chars.forEach(char => { counterMap = {...counterMap, [char]: (counterMap[char] || 0) + 1 }; if (counterMap[char] > max) { max = counterMap[char]; } }); return max; } console.log('[Input]', undefined, '[Output]', find_max_repeat_count_in_word(undefined)); console.log('[Input]', null, '[Output]', find_max_repeat_count_in_word(null)); console.log('[Input]', '\'\'', '[Output]', find_max_repeat_count_in_word('')); console.log('[Input]', '\'undefined\'', '[Output]', find_max_repeat_count_in_word('undefined')); console.log('[Input]', 'Hello', '[Output]', find_max_repeat_count_in_word('Hello')); console.log('[Input]', 'passive', '[Output]', find_max_repeat_count_in_word('passive')); console.log('[Input]', 'possessive postman', '[Output]', find_max_repeat_count_in_word('possessive postman')); console.log('[Input]', 'Do something with previous code, it seems to be running in infinite loop', '[Output]', find_max_repeat_count_in_word('Do something with previous code, it seems to be running in infinite loop')); WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET A: The exit condition of the for loop is not written correctly. You can correct by writing : for(let i = 0; i < word.length; i++) otherwise the word.length condition will always be true.
unknown
d16031
val
found > len(string) This condition will never be true, because str.find will always return a result < len(s). The correct return value to check for when there was no result is -1. But you need to be careful with the increment, since that will change the invalid result -1 to 0 continuing the loop. So you should reorder your logic a bit: def new(string): global found fish = string.find('x',found,len(string)) if fish < 0: return 0 found = fish + 1 return new(string) + 1 Note that using global variables for such a function, especially for recursive functions, is a bad idea. You don’t have full control over it, and instead, you also need to make sure that you reset its value when you call the function. Instead, you should keep all the information inside, and pass it around to the recursive calls if necessary. You could change your function like this: def new (string, found = 0): fish = string.find('x', found) if fish < 0: return 0 return new(string, fish + 1) + 1 This uses default parameter values to make sure that found starts with 0. And for the recursive call, it just passes the new found value, so the next function can start there. Finally note, that you should try to use descriptive names for your functions and variables. The function is supposed to count the number of occurrences of 'x', so maybe count_x would be better. Also, the variable found in that context conveys a meaning that it contains the number of occurrences of x that you have already found; but instead, it’s the start offset from which to continue the search; and fish is just bad, as it’s just the index of the next 'x': def count_x (string, offset = 0): index = string.find('x', offset) if index < 0: return 0 return count_x(string, index + 1) + 1 Finally, just in case you don’t know, there is also a built-in function str.count which does the same thing :)
unknown
d16032
val
I've got the same problem and Danny's solution wasn't good for me. I manage thousand of permutation and store them in memory is damn expensive. Here my solution: /** * Calculate permutation of multidimensional array. Without recursion! * Ex. * $array = array( * key => array(value, value), * key => array(value, value, value), * key => array(value, value), * ); * * @copyright Copyright (c) 2011, Matteo Baggio * @param array $anArray Multidimensional array * @param function $isValidCallback User function called to verify the permutation. function($permutationIndex, $permutationArray) * @return mixed Return valid permutation count in save memory configuration, otherwise it return an Array of all permutations */ function permutationOfMultidimensionalArray(array $anArray, $isValidCallback = false) { // Quick exit if (empty($anArray)) return 0; // Amount of possible permutations: count(a[0]) * count(a[1]) * ... * count(a[N]) $permutationCount = 1; // Store informations about every column of matrix: count and cumulativeCount $matrixInfo = array(); $cumulativeCount = 1; foreach($anArray as $aColumn) { $columnCount = count($aColumn); $permutationCount *= $columnCount; // this save a lot of time! $matrixInfo[] = array( 'count' => $columnCount, 'cumulativeCount' => $cumulativeCount ); $cumulativeCount *= $columnCount; } // Save the array keys $arrayKeys = array_keys($anArray); // It needs numeric index to work $matrix = array_values($anArray); // Number of column $columnCount = count($matrix); // Number of valid permutation $validPermutationCount = 0; // Contain all permutations $permutations = array(); // Iterate through all permutation numbers for ($currentPermutation = 0; $currentPermutation < $permutationCount; $currentPermutation++) { for ($currentColumnIndex = 0; $currentColumnIndex < $columnCount; $currentColumnIndex++) { // Here the magic! // I = int(P / (Count(c[K-1]) * ... * Count(c[0]))) % Count(c[K]) // where: // I: the current column index // P: the current permutation number // c[]: array of the current column // K: number of the current column $index = intval($currentPermutation / $matrixInfo[$currentColumnIndex]['cumulativeCount']) % $matrixInfo[$currentColumnIndex]['count']; // Save column into current permutation $permutations[$currentPermutation][$currentColumnIndex] = $matrix[$currentColumnIndex][$index]; } // Restore array keys $permutations[$currentPermutation] = array_combine($arrayKeys, $permutations[$currentPermutation]); // Callback validate if ($isValidCallback !== false) { if ($isValidCallback($currentPermutation, $permutations[$currentPermutation])) $validPermutationCount++; // *** Uncomment this lines if you want that this function return all // permutations //else // unset($permutations[$currentPermutation]); } else { $validPermutationCount++; } // Save memory!! // Use $isValidCallback to check permutation, store into DB, etc.. // *** Comment this line if you want that function return all // permutation. Memory warning!! unset($permutations[$currentPermutation]); } if (!empty($permutations)) return $permutations; else return $validPermutationCount; } // // How to? // $play = array( '4' => array(7, 32), '8' => array(4), '2' => array(9), '12' => array('5'), '83' => array('10', '11', '12', ''), // <-- It accept all values, nested array too '9' => array('3'), ); $start = microtime(true); // Anonymous function work with PHP 5.3.0 $validPermutationsCount = permutationOfMultidimensionalArray($play, function($permutationIndex, $permutationArray){ // Here you can validate the permutation, print it, etc... // Using callback you can save memory and improve performance. // You don't need to cicle over all permutation after generation. printf('<p><strong>%d</strong>: %s</p>', $permutationIndex, implode(', ', $permutationArray)); return true; // in this case always true }); $stop = microtime(true) - $start; printf('<hr /><p><strong>Performance for %d permutations</strong><br /> Execution time: %f sec<br/> Memory usage: %d Kb</p>', $validPermutationsCount, $stop, memory_get_peak_usage(true) / 1024); If someone has a better idea i'm here! A: Here's what you need. I have commented as necessary: function permutations(array $array) { switch (count($array)) { case 1: // Return the array as-is; returning the first item // of the array was confusing and unnecessary return $array; break; case 0: throw new InvalidArgumentException('Requires at least one array'); break; } // We 'll need these, as array_shift destroys them $keys = array_keys($array); $a = array_shift($array); $k = array_shift($keys); // Get the key that $a had $b = permutations($array); $return = array(); foreach ($a as $v) { if(is_numeric($v)) { foreach ($b as $v2) { // array($k => $v) re-associates $v (each item in $a) // with the key that $a originally had // array_combine re-associates each item in $v2 with // the corresponding key it had in the original array // Also, using operator+ instead of array_merge // allows us to not lose the keys once more $return[] = array($k => $v) + array_combine($keys, $v2); } } } return $return; } See it in action. By the way, calculating all the permutations recursively is neat, but you might not want to do it in a production environment. You should definitely consider a sanity check that calculates how many permutations there are and doesn't allow processing to continue if they are over some limit, at the very least. A: I improved Jon's function by merging his algorithm with the one I had initially. What I did, was check if the function was doing a recursion, if so, I use the original array_merge() (which was working), else I use Jon's array_combine() (to keep the arrays keys). I'm marking Jon's answer as correct since he proposed a slick solution to keep the array keys intact. function permutations(array $array, $inb=false) { switch (count($array)) { case 1: // Return the array as-is; returning the first item // of the array was confusing and unnecessary return $array[0]; break; case 0: throw new InvalidArgumentException('Requires at least one array'); break; } // We 'll need these, as array_shift destroys them $keys = array_keys($array); $a = array_shift($array); $k = array_shift($keys); // Get the key that $a had $b = permutations($array, 'recursing'); $return = array(); foreach ($a as $v) { if(is_numeric($v)) { foreach ($b as $v2) { // array($k => $v) re-associates $v (each item in $a) // with the key that $a originally had // array_combine re-associates each item in $v2 with // the corresponding key it had in the original array // Also, using operator+ instead of array_merge // allows us to not lose the keys once more if($inb == 'recursing') $return[] = array_merge(array($v), (array) $v2); else $return[] = array($k => $v) + array_combine($keys, $v2); } } } return $return; } Tested successfully with several array combinations.
unknown
d16033
val
You have 2 mistakes in your sapply function. First you are trying use a character vector (stock_with3) instead of a list (all_stocks). Second the function used inside the sapply is incorrect. the lag closing bracket is before the grep. This should work. stock3_check <- sapply(all_stocks[stocks_with3], function(x) { last(x[, grep("\\.Open", names(x))]) <= lag(x[, grep("\\.Close", names(x))]) }) additional comments I'm not sure what you are trying to achieve with this code. As for retrieving your data, the following code is easier to read, and doesn't first put all the objects in your R session and then you putting them into a list: my_stock_data <- lapply(Symbols , getSymbols, auto.assign = FALSE) names(my_stock_data) <- Symbols
unknown
d16034
val
Perhaps add the invocation to make all .selectpicker elements a selectpicker? You will pretty much hit your head after seeing this. In the source of the Select plugin page you will see countless times where the demo uses a css selector to invoke .selectpicker() on the elements. <script type="text/javascript"> $('.selectpicker').selectpicker(); </script> Please see. http://jsbin.com/anepet/3/edit A: You are including the js twice and not invoking the selectpicker().. remove this line: <script src="http://silviomoreto.github.com/bootstrap-select/javascripts/bootstrap-select.js"></script> and add this: <script type="text/javascript"> $(document).ready(function(){ $('.selectpicker').selectpicker(); }); </script> in the <header> and it will work
unknown
d16035
val
There are a couple ways. The best way to accomplish this is with some unobtrusive JavaScript. Add an event listener like this: # <%= select_tag 'state' ... ' %> => <select name="state" id="state" multiple> <option value="MN">Minnesota</option> <option value="IA">Iowa</option> <option value="WI">Wisconsin</option> <option value="SD">South Dakota</option> </select> <script> let element = document.getElementById('state'); element.addEventListener('blur', event => console.log("blur, baby, blur")); </script> If you prefer to use jQuery and it's already imported, you can use its event handlers. The jQuery version would go something like this: $(document).on('blur', '#state', event => console.log('blur, baby, blur')); Note that passing the event to your function is optional. I'm adding the event handler directly to the document which means that it would work even if the select element is dynamically added to the page after page load. You can alternatively use this more classic jQuery approach if you are not dynamically loading the element. $('#element-id').on('blur', function() { // do stuff }
unknown
d16036
val
Since you are using an anonymous type, you could just as easily switch to using a dictionary: var root = new Dictionary<string, object> { {"$a", "b" }, {"c", "d" }, }; var request = new RestRequest("someApiEndPoint", RestSharp.Method.POST) .AddJsonBody(root); If you were using an explicit type, you could check RestSharp serialization to JSON, object is not using SerializeAs attribute as expected for options.
unknown
d16037
val
link{ color:#275A78; text-decoration:none; } A:hover{ color:#333333; text-decoration:underline; } A:active{ color:#275A78; text-decoration:none; } A:active:hover{ color:#333333; text-decoration:underline; } A:visited{ color:#275A78; text-decoration:none; } A:visited:hover{ color:#333333; text-decoration:underline; } #header{ background:url(../images/headerbg.gif) no-repeat #F4DDB1 top left; width:282px; height:439px; margin-right:auto; /* *margin-left:0; */ margin-bottom:0; text-align:right; float:left; } #wrap{ width:782px; margin-right:auto; margin-left:auto; } #container{ background:#F8EBD2; width:500px; /*margin-left:282px; margin-top:-452px; */ float:right; } #navcontainer{ /* * */position:absolute; width:282px; margin-right:auto; margin-top:435px; margin-left:60px; } #navlist li{ margin-left:15px; list-style-type: none; text-align:right; padding-right: 20px; font-family: 'Lucida Grande', Verdana, Helvetica, sans-serif; font-size:12px; color:#666666; } #navlist li a:link { color: #666666; text-decoration:none; } #navlist li a:visited { color: #999999; text-decoration:none; } #navlist li a:hover {color: #7394A0; text-decoration:none; } h3{ font-size:21px; font-weight:bold; color:#8C7364; } .content{ padding:10px; width: 100% text-align:justify; font: 9pt/14pt 'Lucida Grande', Verdana, Helvetica, sans-serif; } #footer{ background:transparent; height:66px; text-align:center; font: 8pt/14pt 'Lucida Grande', Verdana, Helvetica, sans-serif; color:#333333; } #title{ position:absolute; top:440px; left:9px; padding-left:9px; font: 14pt/12pt 'Lucida Grande', Verdana, Helvetica, sans-serif; color:#275A78; } The code will be in this portion: <div class="content"> <!-- here is your page content --> <%= yield :layout %> <!-- end page content --> </div> http://www.otoplusvn.com/TherapistSurvey/counselor_questionaries/new If you don't click on any radio buttons, and press submit you only see the error messages, but the fields aren't highlighted. Any Advise appreciated, Thanks, Derek A: The highlights from Rails comes from CSS that targets : .field and .field_with_errors These classes are generated with the following HAML in Rails : .field = f.label :type = f.check_box :type In HTML : <% form_for(@plant) do |f| %> <%= f.error_messages %> <b>Plant Name</b> <p> <%= f.label :name %><br /> <%= f.text_field :name %> .. What does your HAML look like for say, one of your fields? A: <table cellpadding ="5" cellspacing="3" width="100%"> <% for rating_option in [0,1,2,3,4,5,6] -%> <td align ="center"> <%= radio_button("counselor_effectiveness", category, @temp[rating_option])%> </td> <% end -%> </table> I'm still really new to css and ruby on rails. The above code is used to generate the radio buttons. Are you saying that in the css i can control the color of the background of the radio buttons (being highlighted) through the css? If so , how is that done? Thanks, D
unknown
d16038
val
If you're able to make changes to the decorated function, it should be possible to use the passed arguments to determine which fields were modified, albeit through a little bit of a workaround. I'm afraid I haven't been able to test this yet, but I hope it helps! @event.listens_for(Post, 'after_update', raw=True) @event.listens_for(Post, 'after_insert', raw=True) def myfunc(mapper, connection, target): # Values have been modified if target.session.is_modified(target, include_collections=False): # view_counter is the only modified value, the hook can be aborted if set(target.dict.keys()) - target.unmodified == {'view_counter'}: return <...the rest of the function...>
unknown
d16039
val
You can simplify a lot your CheckedChanged event handler using a bit of Linq Private Sub AllBoxes_CheckedChanged(sender As Object, e As EventArgs) ' Get all checkboxes in the groupBox8 Dim checks = groupBox8.Controls.OfType(Of CheckBox)() ' Count how many are checked Dim cnt = checks.Where(Function(x) x.Checked).Count() If cnt < 2 Then ' Enable all, avoid an if and don't care if already enabled For Each c In checks c.Enabled = True Next Else ' Disable all except the two checked... For Each k In checks.Where(Function(x) Not x.Checked) k.Enabled = False Next End If End Sub
unknown
d16040
val
That need not have a class style. For example: //config.php $config['name'] = "test1"; $config['name']['subname'] = "test2"; //other php. require_once('{path to config.php}'); echo $config['name']; echo $config['name']['subname'];
unknown
d16041
val
ASP.NET is so called server side code, whilst HTML is client side code. This means there is no direct connection between HTML and ASP.NET, besides the fact that ASP.NET generates the HTML and sends it back to te client. In order to be able to get the value from the select box, you should either use an AJAX request to post the value to the server as soon as the selection changes, or force the user to post a form. Since you appear to be creating a size selection, I think using the AJAX-method should be the best way. A: In codebehind a html-select with runat=server is a HtmlSelect and Items returns a ListItemCollection. You can use the SelectedIndex: string selectedItemValue = null; string selectedItemText = null; if(Combobox.SelectedIndex >= 0) { ListItem selectedItem = Combobox.Items[Combobox.SelectedIndex]; selectedItemValue = selectedItem.Value; selectedItemText = selectedItem.Text; } or use the HtmlSelect.Value property which does the same: string selectedItemValue = Combobox.Value; // String.Empty if no item selected
unknown
d16042
val
I got answer. Change borderColor instead of layer.borderColor: and add this code in .m file: #import <QuartzCore/QuartzCore.h> @implementation CALayer (Additions) - (void)setBorderColorFromUIColor:(UIColor *)color { self.borderColor = color.CGColor; } @end Tick properties in Attribute Inspector A: The explanation, perhaps being lost in some of the other answers here: The reason that this property is not being set is that layer.borderColor needs a value with type CGColor. But only UIColor types can be set via Interface Builder's User Defined Runtime Attributes! So, you must set a UIColor to a proxy property via Interface Builder, then intercept that call to set the equivalent CGColor to the layer.borderColor property. This can be accomplished by creating a Category on CALayer, setting the Key Path to a unique new "property" (borderColorFromUIColor), and in the category overriding the corresponding setter (setBorderColorFromUIColor:). A: Swift 4, Xcode 9.2 - Use IBDesignable and IBInspectable to build custom controls and live preview the design in Interface Builder. Here is a sample code in Swift, place just below the UIKit in ViewController.swift: @IBDesignable extension UIButton { @IBInspectable var borderWidth: CGFloat { set { layer.borderWidth = newValue } get { return layer.borderWidth } } @IBInspectable var cornerRadius: CGFloat { set { layer.cornerRadius = newValue } get { return layer.cornerRadius } } @IBInspectable var borderColor: UIColor? { set { guard let uiColor = newValue else { return } layer.borderColor = uiColor.cgColor } get { guard let color = layer.borderColor else { return nil } return UIColor(cgColor: color) } } } If you go to the Attributes inspectable of the view, you should find these properties visually, edit the properties: The changes are also reflected in User Defined Runtime Attributes: Run in build time and Voila! you will see your clear rounded button with border. A: For Swift: Swift 3: extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { return UIColor(cgColor: layer.borderColor!) } set { layer.borderColor = newValue?.cgColor } } } Swift 2.2: extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { return UIColor(CGColor: layer.borderColor!) } set { layer.borderColor = newValue?.CGColor } } } A: This works for me. Swift 3, Xcode 8.3 CALayer extension: extension CALayer { var borderWidthIB: NSNumber { get { return NSNumber(value: Float(borderWidth)) } set { borderWidth = CGFloat(newValue.floatValue) } } var borderColorIB: UIColor? { get { return borderColor != nil ? UIColor(cgColor: borderColor!) : nil } set { borderColor = newValue?.cgColor } } var cornerRadiusIB: NSNumber { get { return NSNumber(value: Float(cornerRadius)) } set { cornerRadius = CGFloat(newValue.floatValue) } } } A: There is a much better way to do this! You should use @IBInspectable. Check out Mike Woelmer's blog entry here: https://spin.atomicobject.com/2017/07/18/swift-interface-builder/ It actually adds the feature to IB in Xcode! Some of the screenshots in other answers make it appear as though the fields exist in IB, but at least in Xcode 9 they do not. But following his post will add them. A: In case of Swift, function doesn't work. You'll need a computed property to achieve the desired result: extension CALayer { var borderColorFromUIColor: UIColor { get { return UIColor(CGColor: self.borderColor!) } set { self.borderColor = newValue.CGColor } } } A: You have set the data values for the radius and the width set to be a string, but it should properly be to be set to a number, not a string When you get it working, this will not be visible while looking at the storyboard, but will be when the app is running unless you have taken steps to make it @IBDesigneable.
unknown
d16043
val
Add display:none; to the class .dtp-icon-wrapper .dtp-icon-wrapper { width: 40px; height: 40px; background: hsl(0, 100%, 100%); border-radius: 50%; margin: 0 auto; display: inline-block; position: relative; top: -60px; margin-top: -10px; display: none; } Works fine , the icon does't show anymore. To make the whole image clickable(and if your in control of the HTML) , wrap the following element: <div class="view"> </div> inside a <a> tag.
unknown
d16044
val
There's no reason to do this in any language i've seen. (besides the fact that you didn't specify in which language you are trying to achieve this) All languages allow you to get the character code from a keypress. If you know which encoding was used (UTF 8, Ascii, you name it), it's trivial to map the code to the actual character. Assigning a different keyboard layout on OS level means that it no longer matters which keyboard layout you are using. if you have a QWERTY keyboard, switch it to AZERTY and press the button where the q would be, you get an a, despite the letters on the keyboard still saying QWERTY. If you are using a chinese keyboard, the characters no longer map to any western set, so the character codes will not match up with UTF8 or ASCII, but CP963 (or another chinese codepage, depending on several factors), which is so different there is no real way to translate it to UTF8 or ASCII.
unknown
d16045
val
Based on the information provided here by user Jose Martinez, a VM argument is correct for this use case. To elaborate, I have a Cron that kicks off the inner join in the morning by having -DearlyData=TRUE to retrieve early data, and a Cron that utilizes the leftanti join in the evening by using -DearlyData=FALSE in the script for late data.
unknown
d16046
val
If we have a file example.json like: { "rev": "fcc9a7714053acb1aaf6913b99b6f49e0d13b1b7" } We can use the following where fromJSON will return an attribute set: nix-repl> v = builtins.fromJSON (builtins.readFile "/path/to/example.json") nix-repl> v.rev "fcc9a7714053acb1aaf6913b99b6f49e0d13b1b7"
unknown
d16047
val
Add data-callback to your ReCapthca div: <div class="g-recaptcha" data-sitekey="***" data-callback="recaptchaCallback"></div> Add this function to your code. var recaptchachecked; function recaptchaCallback() { //If we managed to get into this function it means that the user checked the checkbox. recaptchachecked = true; } You may now can use the recaptchachecked on your OnSubmit() function. A: You can validate it on callback function by getting response value is null or not. callback function function submit(){ var response = grecaptcha`.`getResponse(); if(response != '0'){ //captcha validated and got response code alert("the captcha has been filled"); }else{ //not validated or not clicked alert("Please fill the captcha!"); } } It will work.
unknown
d16048
val
The problem solved! I appended the Token to the authorization header like so: request.headers['Authorization'] = Token ${token} Except when signing out, every other request did not require the authorization header to be set as above. So after sign out, the authorization header becomes: request.headers.Authorization = Token null That null value of the token would make every request after sign out "Unauthorized". So to solve this, I had to set the Authorization header for every request when there is token and then delete the Authorization from the header object when there is no token like so: delete request.headers.Authorization
unknown
d16049
val
TLDR: my42bytes, err := ioutil.ReadAll(io.LimitReader(myReader, 42)) Full answer: @monicuta mentioned io.ReadFull which works great. Here I provide another method. It works by chaining ioutil.ReadAll and io.LimitReader together. Let's read the doc first: $ go doc ioutil.ReadAll func ReadAll(r io.Reader) ([]byte, error) ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported. $ go doc io.LimitReader func LimitReader(r Reader, n int64) Reader LimitReader returns a Reader that reads from r but stops with EOF after n bytes. The underlying implementation is a *LimitedReader. So if you want to get 42 bytes from myReader, you do this import ( "io" "io/ioutil" ) func main() { // myReader := ... my42bytes, err := ioutil.ReadAll(io.LimitReader(myReader, 42)) if err != nil { panic(err) } //... } Here is the equivalent code with io.ReadFull $ go doc io.ReadFull func ReadFull(r Reader, buf []byte) (n int, err error) ReadFull reads exactly len(buf) bytes from r into buf. It returns the number of bytes copied and an error if fewer bytes were read. The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadFull returns ErrUnexpectedEOF. On return, n == len(buf) if and only if err == nil. If r returns an error having read at least len(buf) bytes, the error is dropped. import ( "io" ) func main() { // myReader := ... buf := make([]byte, 42) _, err := io.ReadFull(myReader, buf) if err != nil { panic(err) } //... } Compared to io.ReadFull, an advantage is that you don't need to manually make a buf, where len(buf) is the number of bytes you want to read, then pass buf as an argument when you Read Instead you simply tell io.LimitReader you want at most 42 bytes from myReader, and call ioutil.ReadAll to read them all, returning the result as a slice of bytes. If successful, the returned slice is guaranteed to be of length 42. A: Note that the bufio.Read method calls the underlying io.Read at most once, meaning that it can return n < len(p), without reaching EOF. If you want to read exactly len(p) bytes or fail with an error, you can use io.ReadFull like this: n, err := io.ReadFull(reader, p) This works even if the reader is buffered. A: I am prefering Read() especially if you are going to read any type of files and it could be also useful in sending data in chunks, below is an example to show how it is used fs, err := os.Open("fileName"); if err != nil{ fmt.Println("error reading file") return } defer fs.Close() reader := bufio.NewReader(fs) buf := make([]byte, 1024) for{ v, _ := reader.Read(buf) //ReadString and ReadLine() also applicable or alternative if v == 0{ return } //in case it is a string file, you could check its content here... fmt.Print(string(buf)) } A: func (b *Reader) Read(p []byte) (n int, err error) http://golang.org/pkg/bufio/#Reader.Read The number of bytes read will be limited to len(p) A: Pass a n-bytes sized buffer to the reader. A: If you want to read the bytes from an io.Reader and into an io.Writer, then you can use io.CopyN CopyN copies n bytes (or until an error) from src to dst. It returns the number of bytes copied and the earliest error encountered while copying. On return, written == n if and only if err == nil. written, err := io.CopyN(dst, src, n) if err != nil { // We didn't read the desired number of bytes } else { // We can proceed successfully } A: To do this you just need to create a byte slice and read the data into this slice with n := 512 buff := make([]byte, n) fs.Read(buff) // fs is your reader. Can be like this fs, _ := os.Open('file') func (b *Reader) Read(p []byte) (n int, err error) Read reads data into p. It returns the number of bytes read into p. The bytes are taken from at most one Read on the underlying Reader, hence n may be less than len(p)
unknown
d16050
val
You can simply do this test = [{'date': '2021-07-01 20:32:48', 'name': 'foo'}, {'date': '2021-02-19 10:07:25', 'name': 'bar'}, {'date': '2022-02-18 04:00:05', 'name': 'baz'}] sortedList = sorted(test, key=lambda x: datetime.strptime(x['date'], '%Y-%m-%d %H:%M:%S'), reverse=True) print(sortedList[0]['name']) > baz A: Try this one from datetime import datetime test = [{'date': '2021-07-01 20:32:48', 'name': 'foo'}, {'date': '2022-02-17 10:07:25', 'name': 'bar'}, {'date': '2022-02-18 04:00:05', 'name': 'baz'}] sorted_list = sorted(test, key=lambda d: datetime.strptime(d['date'], '%Y-%m-%d %H:%M:%S'), reverse=True) print(sorted_list[0]) Output: {'date': '2022-02-18 04:00:05', 'name': 'baz'}
unknown
d16051
val
This is not possible with PHP as far as I know. You should consider this particular snippet of PHP will ALWAYS be executed inside parent2 as parent2 is hardcoded in the PHP file.
unknown
d16052
val
-Ofast enables all optimization options that -O3 enables but includes for instance also -ffast-math. The -ffast-math is most likely the explanation for the difference. It breaks IEEE754 conformance for the sake of speed. You should note that it is "wrong" to implement complex multiplication using the school type formula re(A)*re(B) - im(A)*im(B) + i*(...). I write "wrong" in quotes because it is optional for the compiler to implement correct behavior (correct in the sense that it behaves in the spirit of IEEE754). In case you have Inf or NaN in your source operands A or B the formula gives incorrect results. Since -ffast-math assumes that Inf or NaN do not occur in calculations, the compiler is free to use the school type formula. Otherwise it may emit more complex code that gives correct results for all valid inputs including Inf and/or NaN.
unknown
d16053
val
"Duplicate" is enabled for targets in XCode (pretty much nothing else that I know of). If you have a substantial number of subclasses with the same starting point to replicate, why not make a class template from it? Then you can just use file->New to make new instances. It's fairly quick to do. This is probably the simplest example: http://www.macresearch.org/custom_xcode_templates Otherwise, I'd simply duplicate the files in Finder as many times as you need, name them, and drag them into XCode en-masse. A: In XCode 4.2 (I know this is an old question) there is Duplicate under the File menu. Select the file (you can select multiple files but it doesn't appear to do anything useful) in the Project Navigator and then File->Duplicate. Hooray! A: Careful! When you use duplicate ( CMD + Shift + S ) - Xcode have a problem with indexing headers. Also when u want to make a refactoring it can be next error window: So there a couple of ways what to do, to fix that. * *Delete derived data from menu Window > Projects. Restart Xcode. *Product > Clean A: In Xcode 4.5 we can duplicate using File-> Duplicate or cmd + shift + S A: You could use "Save As..."; you'd still have to go back and re-add the original files to the project, though. It wouldn't be such a bad way to do a bunch of related classes, though: edit file, Save As "class2", edit file, Save As "class3", etc., then "Add Existing Files" and re-add all of the files but the last to your project. A: I use the following perl script to duplicate a file pair in the Terminal. You give it the base name of the original and new file, and it copies the header and implementation (c/cpp/m/mm) file, then replaces all occurances of the base name with the new name, then adds them to subversion. You still have to add the new files in to Xcode and adjust the creation date in the comment (I've got a Keyboard Maestro macro for that), but its quicker than doing a lot of the steps manually. I operate with a Terminal window and four tabs pre-set to the Project, Source, Resources, and English.lproj directory which gives quick access for a lot of operations. #!/usr/bin/perl use lib "$ENV{HOME}/perl"; use warnings; use strict; our $cp = '/bin/cp'; our $svn = '/usr/bin/svn'; our $perl = '/usr/bin/perl'; our $source = shift; our $add = 1; if ( $source =~ m!^-! ) { if ( $source eq '-a' || $source eq '--add' ) { $add = 1; $source = shift; } elsif ( $source eq '-A' || $source eq '--noadd' ) { $add = undef; $source = shift; } else { die "Bad arg $source"; } } our $dest = shift; die "Bad source $source" unless $source =~ m!^(.*/)?[A-Za-z0-9]+$!; die "Bad dest $dest" unless $dest =~ m!^(.*/)?[A-Za-z0-9]+$!; my $cpp; $cpp = 'c' if ( -e "$source.c" ); $cpp = 'cpp' if ( -e "$source.cpp" ); $cpp = 'mm' if ( -e "$source.mm" ); $cpp = 'm' if ( -e "$source.m" ); die "Missing source $source" unless -e "$source.h" && -e "$source.$cpp"; die "Existing dest $dest" if -e "$dest.h" && -e "$dest.$cpp"; our $sourcename = $source; $sourcename =~ s!.*/!!; our $destname = $dest; $destname =~ s!.*/!!; print "cp $source.h $dest.h\n"; system( $cp, "$source.h", "$dest.h" ); print "s/$sourcename/$destname in $dest.h\n"; system( $perl, '-p', '-i', '-e', "s/$sourcename/$destname/g", "$dest.h" ); print "cp $source.$cpp $dest.$cpp\n"; system( $cp, "$source.$cpp", "$dest.$cpp" ); print "s/$sourcename/$destname in $dest.$cpp\n"; system( $perl, '-p', '-i', '-e', "s/$sourcename/$destname/g", "$dest.$cpp" ); if ( $add ) { print "svn add $dest.$cpp $dest.h\n"; system( $svn, 'add', "$dest.$cpp", "$dest.h" ); } A: In my case, one of my folder changed from one place to another place. I have "Home" folder in Controller folder, but unfortunately it's moved from Controller folder to Manager folder. I checked many times everything fine, but I'm getting Command PrecompileSwiftBridgingHeader failed with a nonzero exit code But after 2 hours i realised, my folder structure changed.
unknown
d16054
val
I make some change in second part and add isset : <?php $all_workers=array("worker1","worker2","worker3","worker4"); $count_workers = count($all_workers); $all_jobs=array("j1","j2","j3","j4","j5","j6","j7","j8","j9","j10"); $jobs_for_each=2; $k=0; $day=0; for ($n=0; $n < 3; $n++) { for ($j=0; $j < $count_workers ; $j++) { for ($i=0; $i < $jobs_for_each; $i++) { if(!isset($job_arr[$day])){ $job_arr[$day]=array(); } $job_left = count($all_jobs); if( $job_left <= $jobs_for_each*$count_workers){ $jobs_for_each = ceil($job_left / $count_workers); } if(!isset($all_jobs[($k*$jobs_for_each)+$i])){ echo 'no more job<br />';break(3); }else{ $job_arr[$day][trim($all_workers[$j])][]=trim($all_jobs[($k*$jobs_for_each)+$i]); $distributed_arr[]=trim($all_jobs[($k*$jobs_for_each)+$i]); } } $k++; } $remaining=array_diff ( $all_jobs , $distributed_arr ); if (empty($remaining)) { break; } else { $all_jobs = array_values($remaining); } $k=0; $day++; } ?> Will ouput : no more job array (size=2) 0 => array (size=4) 'worker1' => array (size=2) 0 => string 'j1' (length=2) 1 => string 'j2' (length=2) 'worker2' => array (size=2) 0 => string 'j3' (length=2) 1 => string 'j4' (length=2) 'worker3' => array (size=2) 0 => string 'j5' (length=2) 1 => string 'j6' (length=2) 'worker4' => array (size=2) 0 => string 'j7' (length=2) 1 => string 'j8' (length=2) 1 => array (size=1) 'worker1' => array (size=2) 0 => string 'j9' (length=2) 1 => string 'j10' (length=3)
unknown
d16055
val
I love the object-oriented approach: class Menu_init { public function __construct() { add_action( 'init', array($this, 'register_menus')); } public function register_menus() { register_nav_menus( array( 'top_menu' => __( 'Top Menu', 'test' ), 'footer_menu' => __( 'Footer Menu', 'test' ) 'blog_menu' => __( 'Blog Menu', 'test' ) ) ); } } new Menu_init(); and for your header of course: <?php wp_nav_menu( [ 'theme_location' => 'primary', 'container_id' => 'main-nav', 'menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown' ] ); ?> It is true, you have an extra bracket ( ) ). A: function register_my_menus() { $locations = array( 'primary' => __( 'Top Menu', 'test' ), 'blog' => __( 'Blog Menu', 'test' ), 'footer' => __( 'Footer Menu', 'test' ), ); register_nav_menus( $locations ); } add_action( 'init', 'register_my_menus' ); <?php wp_nav_menu( [ 'theme_location' => 'primary', 'container_id' => 'main-nav','menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown'] ); ?>
unknown
d16056
val
I use this maybe it's help someone YourList = connection.Query<YourQueryClass>(Query, arg) .Select(f => new ClassWithConstructor(f.foo,f.bar)) .ToList(); A: I would use the non-generic Query API here... return connection.Query(sql, args).Select(row => new AnyType((string)row.Foo, (int)row.Bar) { Other = (float)row.Other }).ToList(); Using this you can use both non-default constructors and property assignments, without any changes, by using "dynamic" as an intermediate step. A: I came across this question and it inspired me to think a bit differently than the other answers. My approach: internal class SqlMyObject: MyObject { public SqlMyObject(string foo, int bar, float other): base(foo, bar, other) { } } ... return connection.Query<SqlMyObject>(sql, args); Using a "private" derived class (I used internal to expose it to Unit Tests, personal preference) I was able to specify one constructor that the derived class has, this can also do some mapping or business logic to get to the desired base class/params as necessary; this is useful if the only time that object should be initiated in that way is when it's pulling from the DB. Also, can use Linq's .Cast<MyObject>() on the collection to eliminate any type check issues down the line if need be without having to check for derived/base types.
unknown
d16057
val
I did following : $ echo "/usr/local/staf/lib" > /etc/ld.so.conf.d/staf.conf $ ldconfig Basically, adding STAF library path in /etc/ld.so.conf.d/staf.conf
unknown
d16058
val
You are clearing all axes using cla which includes the logo that you don't want to delete. arrayfun(@cla,findall(0,'type','axes')); Instead of clearing everything, it's better to delete and clear specific objects. cla(handles.axes10) cla(handles.axes11) Alternately, if you keep the handle to the image object, you can ignore the axes that contains it when clearing axes himg = imshow(data); allaxes = findall(0, 'type', 'axes'); allaxes = allaxes(~ismember(allaxes, ancestor(himg, 'axes'))); cla(allaxes) Also, you shouldn't ever do findall(0, ... in your GUI because if I open a figure before opening my GUI you will alter the state of my other figure. Instead, use findall(gcbf, ... which will only alter children of your own GUI. Either that, or use a 'Tag' specific to your GUI and then use findall to filter for that specific tag. figure('Tag', 'mygui') findall(0, 'Tag', 'mygui') Update You should use findall combined with the 'Name' parameter to figure out which of your figures actually exists figs = findall(0, 'Name', 'Vektorkardiogram', ... '-or', 'Name', 'Roviny', ... '-or', 'Name', 'P vlna', ... '-or', 'Name', 'QRS komplex', ... '-or', 'Name', 'T vlna'); delete(figs); And for clearing the axes, you can ensure that they exist ax = findall(0, 'tag', 'axes10', '-or', 'tag', 'axes11', '-or', 'tag', 'axes12'); cla(ax)
unknown
d16059
val
You need too use this, this inside a JQuery event handler is the DOM element that has the handler attached. Use var price=$(this).find("p").html(); var product=$(this).find("h1").html(); instead of var price=$(".box2 p").html(); var product=$(".box2 h1").html(); A: Use $(this).find('p') //or $(this).find('h1') Instead of $(".box2 p").html() A: $(document).ready(function() { $('.box2').click(function(){ var price=$( this).find('p').html(); var product=$( this).find('h1').html(); $(".add li:first-child").text(product+ price); }); }); Your jquery should looks like Demo A: You can use like this (A faster way): $('.box2').click(function(){ var price=$(".box2 p", this).html(); var product=$(".box2 h1", this).html(); $(".add li:first-child", this).text(product); $(".add li:nth-child(2)", this).text(price); }); A: <script type="text/javascript"> $(document).ready(function() { $('.box2').click(function(){ var price=$(this).find("p").html(); var product=$(this).find("h1").html(); }); }); </script> A: try var price=$( this).find('p').html();
unknown
d16060
val
Use columns var dd = { content: [ { columns: [ { width: 'auto', text: 'Test text' }, { width: '*', image: 'sampleImage.jpg', width: 24, height: 24 } ] } ] } A: If you want the image to be inline with your Multiline text you can use columns + stack Example: columns: [ { image: "URL", height: 150, width: 180 }, { stack: [ { columns: [ { text: 'First column first line', width: '35%' }, { text: 'Second column first line', width: '35%' }, { text: 'Third column first line', width: '30%' } ] }, { columns: [ { text: 'First column second line', width: '35%' }, { text: 'Second column second line', width: '35%' }, { text: 'Third column second line', width: '30%' } ] } ], width: '*' }]
unknown
d16061
val
As you've discovered, you can't serialize the BitmapImage. The simplest alternative would be to save this as a separate file and then save the name of the file in the collection you're serializing. Obviously, when deserializing, you'll need to read the file from disk and load it back into a BitmapImage. If you're persisting this data for use across the lifetime of the app it'll probably be easier to just save the images straight to IsolatedStorage and keep the paths in your view model. You can then bind the path to an Image in the ListBoxItemTemplate.
unknown
d16062
val
To use the $id into another page, you must have to store that in such a way that it will be remain exist after submit.That can be done by using the hidden field. You may set the value of $id like: <input type="hidden" name="topic_id" value="<?php echo $id?>"> Once you submit and redirect to add_video.php, you may get the value of $id same as another field video_detail. On submit look like: if(isset($_POST['submit'])) { $topic_id = $_POST['topic_id']; }
unknown
d16063
val
I found the issue.. In my dashboard.component.ts I had imported the NavBar for test a long while ago and forgot to remove it: import { NavbarComponent } from './../../../shared/navbar/navbar.component'; import { Component, OnInit,EventEmitter,Output } from '@angular/core'; import { RouterModule } from '@angular/router'; import { AuthService } from '../../../../services/auth.service'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent implements OnInit { @Output() isLogout = new EventEmitter<void>() constructor(NavbarComponent : NavbarComponent, public auth: AuthService) { } ngOnInit(): void { } } Just had to remove NavbarComponent : NavbarComponent
unknown
d16064
val
Just use this.y instead of point.percentage OR Use below code to format the tooltip. tooltip: { formatter: function () { return '</b>' + this.y + '</b>'; } }
unknown
d16065
val
The defect was in the bottom of the #sendRequest() method. It was ignoring the Builder object returned and re-using the WebTarget to create a new request (which creates a new builder. The last three lines of code in that method should have been: return builder.buildDelete().invoke(); } // default to HttpMethod.GET return builder.buildGet().invoke();
unknown
d16066
val
You basically have this: var gameState = 0; if(gameState === 1) { // never called since gameState = 0 } if(gameState ===2) { // never called since gameState = 0 } Which is probably not want you want. If you aren't familiar with the Javascript debugger, you might want to look up a tutorial on how to use it. You would see that none of your code is being called at the moment. Even if you modify it to this: var gameState = 1; if(gameState === 1) { requestAnimationFrame(main); // main is called after the remaining sync code has executed } if(gameState ===2) { // never called since gameState = 1 } It still will never execute since the gameState===2 if statement will be executed immediately (since it is synchronous) before anything is executed with the requestAnimationFrame callback (since that is done asyncronously).
unknown
d16067
val
Your problem is finite precision and, as presented, there is nothing you can do about it. In your problem you are calculating 2*pi*f*x. Since this appears in a function with period 2*pi, the complex exponential, the only significant part of f*x are the digits after the decimal point. In other words, the information in f*x is only contained in the values in the interval [0,1) so we can think of really needing to calculate f*x modulo 1.0. If we look at the values you provide we find f*x = 28300717126.4719(73) where I have put the "extra" digits, beyond the first 15, in parenthesis. (Roughly we expect about 15 digits of precision, you can be more careful with this if you care but this is sufficient to get the point across.) We thus see that we are only calculating f*x to 4 significant digits. If we now compare the values calculated in your question we find exponent1 = 177818650031.694(37) exponent2 = 177818650031.694(4) where I again have used parenthesis for the extra digits. We see these values agree exactly as we expected them to. For the exponential version we are interested in these values modulo 2*pi, exponent1%(2*pi) = 2.965(4796216371864) exponent2%(2*pi) = 2.965(5101392153114) where now the parenthesis are for the extra digits beyond the 4 significant ones we expected. Again, perfectly good agreement to the level we can expect . We cannot do better unless x and f are calculated in such a way to not have all these extra, unnecessary digits "wasting" our precision.
unknown
d16068
val
Add it as a property on the enum: extension CardRank { var isNumber: Bool { switch self { case .number: return true default: return false } } } let isNumber = cardRank.isNumber
unknown
d16069
val
If you're okay with a REPL that works on the dev server, take a look at the bin/python script that Tipfy creates for you. It just loads the Python REPL with your project and the GAE SDK code. I've pasted my version of it here - YMMV, but you can use it as a starting point.
unknown
d16070
val
The expressions looks OK. You do have some extra sets of parenthesis. I think your IIF should check the DENOMINATOR DateDiff("dd", Fields!CreateDt.Value, Fields!EstimatedImpDt.Value) of the expression rather than the NUMERATOR DateDiff("dd", Fields!EstimatedImpDt.Value, Fields!ActualImpDt.Value) to avoid DIV0 errors. =IIF(DateDiff("dd", Fields!CreateDt.Value, Fields!EstimatedImpDt.Value) = 0, 100, 100 - (DateDiff("dd", Fields!EstimatedImpDt.Value, Fields!ActualImpDt.Value) / DateDiff("dd", Fields!CreateDt.Value, Fields!EstimatedImpDt.Value)) * 100)
unknown
d16071
val
src_path="/media/date/resource" dest_path="/media/date/dir" dir_suffix="0" curr_total="0" ONE_TERRA=$(( 1024 * 1024 * 1024 * 1024 )) # in KB for folder in "${src_path}"*; do if ! [[ -d "${folder}" ]]; then continue; fi if ! [[ -d "${dest_path}${dir_suffix}" ]]; then mkdir "${dest_path}${dir_suffix}" folder_size=$(du -s "${folder}" | grep -E -o "[[:digit:]]+") curr_total=$(( curr_total + folder_size )) mv "${folder}" "${dest_path}${dir_suffix}" if (( curr_total > ONE_TERRA )); then dir_suffix=$(( dir_suffix + 1 )) fi Steps are as follows: * *for each node of the pattern /media/date/resource* *if it isn't a directory, continue *if the dest dir doesn't exist, create it *get the size of the dir to move in KB *add it to the curr total of dest dir *move the dir to dest dir *if the curr dest dir size is over one terra, increment the dest dir suffix. I have not tested the code.
unknown
d16072
val
No. What you're describing is exactly what Nexus Repository Manager designed groups for but your internetless scenario removes that from the equation. Your only recourse is manual upload. A: I have solved the issue as follows: I used a npm-group repository and added a npm-hosted repository and a cache enabled npm-proxy (Only this repository has internet access). Steps to add new packages to the repository: 1) Add the repo to a dummy package.json 2) npm install. (All the required packages get cached) 3) I point proxy-url to some junk url. (To avoid unwanted code to come into my environment). Steps to use the repository: 1) npm set registry [npm-group-repo url] 2) npm install
unknown
d16073
val
You're syntax looks incorrect , You should be declaring ng- as listed below : ng-repeat ng-model ng-init ng-bind ect... docs here: https://docs.angularjs.org/api/ng/directive/ngRepeat upadte - to apply method to radio button try ng-change : ng-change="dosomething()"
unknown
d16074
val
From your code, I suspect that notification is triggered in background thread. In this case, any checks that alert is visible right now will not help. Your code will not start subsequent block execution until first block will finish, because runModal method will block, running NSRunLoop in modal mode. To fix your problem, you can introduce atomic bool property and check it before dispatch_async. Objective-C solution: - (void)operationDidFail:(NSNotification *)note { if (!self.alertDispatched) { self.alertDispatched = YES; dispatch_async(dispatch_get_main_queue(), ^{ self.alert = [NSAlert new]; self.alert.messageText = @"Operation failed"; [self.alert runModal]; self.alertDispatched = NO; }); } } Same code using Swift: func operationDidFail(notification: NSNotification) { if !self.alertDispatched { self.alertDispatched = true dispatch_async(dispatch_get_main_queue(), { self.alert = NSAlert() self.alert.messageText = "Operation failed" self.alert.runModal(); self.alertDispatched = false }) } } A: Instead of run modal you could try - beginSheetModalForWindow:completionHandler: source: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSAlert_Class/#//apple_ref/occ/instm/NSAlert/beginSheetModalForWindow:completionHandler: In the completion handler set the alert property to nil. And only show the alert if the alert property is nil ( which would be every first time after dismissing the alert). EDIT : I don't see the documentation say anything about any kind of flag you look for.
unknown
d16075
val
getActivity() belongs to the instance of the current Fragment; it cannot be part of a static context. When you declare a method static, you are stating that this method will not belong to each particular instance of the Class; it belongs to the Class itself. Since the static method will be available regardless if you instantiate an object of the Class, you cannot guarantee that object members and methods (that are not static) will be available. Hence you cannot reference "things" that will be available only when the object is instantiated inside a static method that will always be available. Like Jems said, if you need to access the Fragment you need to always make it available within the method's scope. This can be accomplished by either passing a Fragment to the static method or by instantiating it inside the static method. A: If it must be static, pass a reference to the Fragment you want to call getActivity on into the method. private static void inflateLayout_keluarga_pp(int counter2, String name, Fragment myFragment) { LayoutInflater inflater = (LayoutInflater)myFragment.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
unknown
d16076
val
Use the OrElse operator. If myDataSet2 IsNot Nothing OrElse myDataSet2.Tables("CurData").Rows.Count > 0 EDIT: See my comment on your original question. You are PROBABLY looking for: If myDataSet2 IsNot Nothing AndAlso myDataSet2.Tables("CurData").Rows.Count > 0 That will check if myDataSet2 isn't null. Assuming that it's not, it will then check that there is at least one row. If it is null, then the second condition won't be checked. A: You need to put the second statement into the first if-clause. Like this: If(statement1) then If(statemtent2) then Else End if Else End If As it is now both are evaluated and if one of them is true the content in your if-clause will be executed.
unknown
d16077
val
The REST for ASP.NET MVC SDK contains a Word file explaining how you could extend it by adding a custom format: ASP .NET MVC provides capability to return HTML. MVC REST adds out of the box support to return the two most popular formats for programmatic access on the web: XML and JSON. In addition, you can also handle additional formats. This section shows how you can add support for a custom format such as Atom using the provided extensibility. The process involves creating a custom Format Handler, and registering it to handle requests, responses, or both. The steps specific to enabling custom formats are described below: * *Create a custom format handler that may implement either or both of the interfaces IRequestFormatHandler and IResponseFormatHandler. *Register the custom format handler in global.asax in Application_Start In the included MovieApp sample you will find an implementation for AtomFormatHandler which you could use as a base for adding the JSONP functionality. I've also written a JsonpResult which you may take a look at.
unknown
d16078
val
import pandas as pd d = {'tax_info': ["CA", "CA", "CB", "CD", "CA"]} df = pd.DataFrame(d) taxable_rows = df[ df["tax_info"].str.contains("CA")] print(taxable_rows) Running the code above will yield tax_info 0 CA 1 CA 4 CA A: You can try this code below: import pandas as pd df = pd.read_csv(r'your csv file path') res = df[(df.apply(lambda s: s.eq('CA').any(), axis=1))] print(res)
unknown
d16079
val
You can prevent javascript object from getting modified by using Object.freeze(obj). So in your case it should be const cursor = Object.freeze(query.docs[query.docs.length - 1])
unknown
d16080
val
follow this article! and you will get better understanding of how to setState. I prefer to use the fat arrow function. try this out! import React, { Component } from 'react'; import styled from 'styled-components'; const BtnBox = styled.ul` display:flex; width:50vw; align-items:center; justify-content:flex-start; font-weight:900; font-size:5vw; letter-spacing:-0.5vw; `; const MyBtn = styled.li` width:30%; font-size:5vw; display:flex; align-items:center; justify-content:flex-start; cursor:pointer; `; class SignAndLog extends Component { constructor(props) { super(props); this.state = { Scolor: 'black', Lcolor: 'grey' }; localStorage.setItem('fuck', this.state.Scolor); } chooseFun =(e)=> { const myName = e.target.dataset.name; if (myName === 'sign') { this.setState({ Scolor: 'black', Lcolor: 'grey' }); localStorage.setItem('status', myName); } else { this.setState({ Scolor: 'grey', Lcolor: 'black' }); localStorage.setItem('status', myName); } } render() { return ( <BtnBox> <MyBtn onClick={(e)=>this.chooseFun(e)} data-name="sign" style={{ color: this.state.Scolor }}>註冊</MyBtn> <MyBtn onClick={(e)=>this.chooseFun(e)} data-name="log" style={{ color: this.state.Lcolor }}>登入</MyBtn> </BtnBox> ); } } export default SignAndLog; <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
unknown
d16081
val
If you will have public $entity_id in you Event file, then you will be able to get that value in Listener's handle method like so: $event->entity_id. A: You only type cast something you may want to use in the listener. if you want to simply access the data/object/array you passed to the event class, assign it to a public property in the event class: class AddedAsFav extends Event { public $entity_id; public function __construct($entity_id) { $this->entity_id = $entity_id; } } You can now access it in your listener like any property: <?php namespace App\Listeners; use App\Events\AddedAsFav; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class GetFullEntity { /** * Create the event listener. * * @return void */ public function __construct() { } /** * Handle the event. * * @param MovieAddedAsToWatch $event * @return void */ public function handle(AddedAsFav $event) { $entity_id = $event->entity_id; } }
unknown
d16082
val
You can easily make the string an enum. Essentially a GraphQL enum can be represented by any object in dotnet. The strings have to follow the GraphQL enum rules. So Up to 5 KB would probably be represented by Up_to_5KB. But in your dotnet API you would just use the Up to 5 KB string. The GraphQL engine would translate it to the enum in GraphQL. You also cannot have arbitrary values anymore, they must be represented by the enum values allowed in this case.
unknown
d16083
val
In my understanding you can solve this issue by implementing a shared queue. The pattern of your problem is more towards Producer Consumer Problem You can also take these examples * *http://msdn.microsoft.com/en-us/library/dd728068.aspx *How should i write producer /consumer code in C#? A: Are the server and clients on different hosts? If so, why don't you take UDP and to methods to serialize your structure to send via network and the second one to get it back to structure? ... A: WM_COPYDATA is specifically meant for transferring structs between processes. Check it out. You mentioned pointers though - and no, you cannot expect pointers to work between processes. If you have variable-length arrays or pointers, it's probably necessary to serialize the data, for example with BSON or XML. A: It sounds like you are looking for an asynchronous IPC mechanism. Sockets are probably the easiest way to achieve this. Pipes would be another obvious alternative, and there are many higher level libraries available, but I think sockets sound like the best fit. A: ReadProcessMemory and WriteProcessMemory ought to be able to do the trick for you.
unknown
d16084
val
You surely have the type QueryUploadTest.FileTransferHandler in both assemblies. Make sure that sitename.dll doesn't have a type name like that or, to make sure this problem won't occur other times, change the namespace of one of the projects. It's good practice to have diferent namespaces for diferent assemblies, exactly to avoid this kind of problem.
unknown
d16085
val
Check whether the server has the same set of certificates as your local computer. The 220 response from the server does not mean that the TLS session is already established, it just means that the client may start negotiating it: After receiving a 220 response to a STARTTLS command, the client MUST start the TLS negotiation before giving any other SMTP commands. If, after having issued the STARTTLS command, the client finds out that some failure prevents it from actually starting a TLS handshake, then it SHOULD abort the connection. (from RFC 3207) At this point, a missing certificate is the most likely problem. A: Check your JRE version on the server and compare it to the version of your local computer. This is an environment related issue as the same code behaves differently on different machines. Without the full picture, I cannot answer with certainty. But I hope providing some insight for further investigation. My analysis follows: * *First, I don't think it's a SSL certificate issue, the root cause error is clear: Caused by: java.net.SocketTimeoutException: Read timed out at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) ... at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367) ... this means the socket has been established, but the handshake phase of converting the socket to TLS has failed. If the certificate is not valid, it will be reported after the handshake, let's look at the code from the SocketFetcher.java class: /* * Force the handshake to be done now so that we can report any * errors (e.g., certificate errors) to the caller of the startTLS * method. */ sslsocket.startHandshake(); /* * Check server identity and trust. */ boolean idCheck = PropUtil.getBooleanProperty(props, prefix + ".ssl.checkserveridentity", false); if (idCheck) checkServerIdentity(host, sslsocket); if (sf instanceof MailSSLSocketFactory) { MailSSLSocketFactory msf = (MailSSLSocketFactory)sf; if (!msf.isServerTrusted(host, sslsocket)) { throw cleanupAndThrow(sslsocket, new IOException("Server is not trusted: " + host)); } } } the socket encountered the timeout at this line: sslsocket.startHandshake(), which is before the certificate validation. * *Second, you have already mentioned that firewalls are disabled, and we can see that the previous socket is correctly established so is the telnet command, so I don't think it's a firewall issue neither. *It seems like a protocol issue, mostly because this happened during the handshake phase, otherwise we should see different and more explicit error, such as certificate error, connection timeout, etc. This is a socketRead timeout, which indicates the client (your server) is expecting some information from the server (office365), but the server doesn't respond, it's like they are not talking together. *The compiled code is not the issue here, but some part of this process is environment related: the SSLSocketImpl.class class is from the JRE not from the compilation. And this is the exact code (decompiled) where the protocol is implemented: private void performInitialHandshake() throws IOException { Object var1 = this.handshakeLock; synchronized(this.handshakeLock) { if (this.getConnectionState() == 1) { this.kickstartHandshake(); if (this.inrec == null) { this.inrec = new InputRecord(); this.inrec.setHandshakeHash(this.input.r.getHandshakeHash()); this.inrec.setHelloVersion(this.input.r.getHelloVersion()); this.inrec.enableFormatChecks(); } this.readRecord(this.inrec, false); this.inrec = null; } } } The above code is from JRE_1.8.0_181, your code or the code from your server may be different. This is way it's necessary to check your server's JRE version. * *Using the same code you provided at the beginning, I could correctly connect to office365 A: Try adding this to your properties, and it should do the trick. props.getProperties().put("mail.smtp.ssl.trust", "smtp.office365.com"); A: The problem was one particular rule in firewall. Deleting the rule in the firewall fixed this issue. No specific code change was needed to make it work.
unknown
d16086
val
You can accomplish it with one-liner reduce: var Test = ["John", "Ivar", "Peter", "Tony"]; var Addres = ["Canada", "Sweden", "England", "Chile"]; var result = Test.reduce((str, name, i) => `${str}${name},${Address[i]}\n`, 'Test,Address\n'); console.log(result);
unknown
d16087
val
Its better to use a tween engine , like http://dotween.demigiant.com/. If you install Dotween the you can simply use transform.DOMove(new vector3(1 ,0 , 1) , duration); You can also set Ease for tweens. or use Oncomplete fucntions; transform.DOMove(new vector3(1 ,0 , 1) , duration).SetEase(Ease.OutCubic).OnCompelete(() => { shouldClose = true; }); But the answer for your question is that positions are not exact numbers so you shouldn't use something like this != , you must use < or > . to fix you problem i would recommend you to do something like this ; if(x > 1.345f) { x = 1.345f } This will fix your problem. A: In this kind of situation, you should use an animation, this allows full control on any aspect of the movement. If you really want to use code, you could use Vector3.MoveTowards which creates a linear translation from position A to position B by a certain step amount per frame: transform.position = Vector3.MoveTowards(transform.position, targetPosition, step * Time.deltaTime); As for your issue, you are checking if the position is a certain float. But comparing float is not accurate in computer due to inaccuracy of value. 1.345 is most likely 1.345xxxxxx and that is not the same as 1.34500000. So it never equal. EDIT: Using equality also results in the fact that you are checking if the value is greater or equal. But consider this: start : 10 movement : 3 if(current >= 0){ move(movement);} frame1 : 10 frame2 : 7 frame3 : 4 frame4 : 1 frame5 : -2 we stop here This is why you should use animation or MoveTowards when wishing to move to exact point. Or add extra: if(current >= 0){ move(movement);} else { position = 0; }
unknown
d16088
val
IIUC you can use groupby.cumsum and then just subtract cost; df['cumsum_'] = df.groupby('Month').Cost.cumsum().sub(df.Cost) print(df) Month Cost cumsum_ 0 1 5 0 1 1 8 5 2 1 10 13 3 2 1 0 4 2 3 1 5 1 4 23 6 3 1 0 A: You can do the following: df['agg']=df.groupby('Month')['Cost'].shift().fillna(0) df['Cumsum']=df['Cost']+df['agg']
unknown
d16089
val
Your synatx is wrong, correct syntax this.socket = io( 'wss://some-url.com', { path :'/v1/url/to/websockets', transports: ['websocket'] }); i.e. both should be within same object
unknown
d16090
val
Posting for the points :) (I love them) Other thing that comes to my mind is to Upgrade your .NET Framework version. If nuget dll was build for higher .NET runtime, there is just a Warning message printed in Output window and Error window stays clear. But Build fails.
unknown
d16091
val
You cannot update a JSON file stored on your server with UI5 or any client side library. You will need a server-side script with some file writing code to do it. You should use an OData service and perform any read/write operations to it.
unknown
d16092
val
You can achieve it without using Picker, use TouchableOpacity to call a function, and in the same function just open a Modal for showing the list of items of Picker and close the Modal when selecting any item from the list.
unknown
d16093
val
I couldn't get it to work with the custom control check boxes but for the standard switches this code worked for me: var trueCount = 0; var falseCount = 0; myapp.TableName.ColumnName_postRender = function (element, contentItem) { // count the true or false values contentItem.dataBind("value", function (newValue) { if (contentItem.value == true) { trueCount ++; falseCount--; } else if (contentItem.value == false) { falseCount++; trueCount--; } }); //count 3 sets both trueCount and falseCount to 0 as they would already be affected by the //post render method. This works by adding or subtracting the amount of false values non //screen (works my my scenario) var count3 = 0; if (contentItem.value == false) { count3++; } falseCount = falseCount - count3; trueCount = trueCount + count3; }; myapp.TableName.Save_execute = function (screen) { window.alert("True Count: " + trueCount + " | falseCount: " + falseCount); //set both count values back to 0 for when the screen is next run trueCount = 0; falseCount = 0; }
unknown
d16094
val
I guess number is passed as a string, so: * *you need to cast it to an integer before passing it to randint *probably need to cast it to a string again before "saying" it What's more, you're not using the correct way to check for wrong integer values; if number will never be False because your randint call will only return integers greater than 0 (or raise an error). A fixed version would be something like: @Bot.command(pass_context=True) async def random1and10(ctx, number): try: arg = random.randint(1, int(number)) except ValueError: await Bot.say("Invalid number") else: await Bot.say(str(arg)) Your mileage may vary, I didn't run it. I'm not sure about the decorated function signature. whenever I try to do this it gives me around 6 different errors that are very long and make no sense to me. Maybe they can make sense to others :) I'm relatively new to this site, but I think including them in your post would have been better. Cheers !
unknown
d16095
val
As per the class reference: WebView has a property named customUserAgent. Just set it to what you want. var customUserAgent: String! If you want to manipulate the application name inside that string use the applicationNameForUserAgent property: var applicationNameForUserAgent: String! To pretend coming from Mobile Safari on iOS 9.3, yourWebViewInstance.customUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13E188a Safari/601.1" should work. A: You can use NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": "Custom-Agent"])
unknown
d16096
val
You can use the StackTrace class from the System.Diagnostics namespace: In the constructor of your ExternalResource class: var stack = new StackTrace(true); var thisFrame = stack.GetFrame(0); // ExternalResource constructor var parentFrame = stack.GetFrame(1); // Sound constructor var grandparentFrame = stack.GetFrame(2); // This is the one! var invokingMethod = grandparentFrame.GetMethod(); var callingAssembly = invokingMethod.Module.Assembly; The references to thisFrame and parentFrame are there simply to aid understanding. I would suggest that you actually walk up the stack frame and do it more robustly, rather than just assuming that it's always frame 2 that you want (which won't give the right answer if you have an additional subclass). A: Using the calling assembly will likely frustrate someone down the road who moves their ExternalResource related code into a new separate assembly without realizing it has an assembly dependency, or wants to move their resources into a separately identified assembly (e.g. for localization). My suggestion would be: * *Add an explicit assembly parameter to the constructor, making it very clear it's doing something with some assembly. *Provide a factory method that determines the calling assembly for the user as a convenience Your factory method could be generic if all of your derived types expect constructor parameters string id, string file and then the new explicit assembly parameter. Something like: public static TExternalResource CreateExternalResource<TExternalResource>(string id, string file, Assembly assembly = null) where TExternalResource : ExternalResource { var ResolvedAssembly = assembly ?? Assembly.GetCallingAssembly(); return Activator.CreateInstance(typeof(TExternalResource), id, file, ResolvedAssembly) as TExternalResource; }
unknown
d16097
val
Try removing the session variable after display. <script> <?php if(isset($_SESSION['error'])) { ?> window.setTimeout(displayErrorMessage(), 2000); function displayErrorMessage(){ if(!displayErrorMessage.called) { var errorMessage = ('<?php echo "ERROR: ".$_SESSION['error']; ?>'); // Here is where you remove the error so it won't persist to the // next pages when user continues to navigate through <?php if(isset($_SESSION['error'])) unset($_SESSION['error']); ?> document.getElementById('errormessage').innerHTML = errorMessage; resetErrorMessage(); } displayErrorMessage.called = true; } <?php } ?> function resetErrorMessage() { var errorMessage = null; setTimeout(function(){ document.getElementById('errormessage').innerHTML = ""; }, 5000); } </script> A: Try this: <?php if( isset($_SESSION['error']) ) : ?> <script> window.setTimeout(displayErrorMessage(), 2000); function displayErrorMessage() { if(!displayErrorMessage.called) { var errorMessage = ("<?php echo "ERROR: ".$_SESSION['error'] ?>"); document.getElementById('errormessage').innerHTML = errorMessage; resetErrorMessage(); } displayErrorMessage.called = true; } function resetErrorMessage() { var errorMessage = null; setTimeout(function() { document.getElementById('errormessage').innerHTML = ""; }, 5000); } </script> <?php endif; ?> <?php unset($_SESSION['error']); ?>
unknown
d16098
val
SELECT a.part_no, sum(a.BUY_QTY_DUE) AS Tot_Ord, sum(nvl(b.REVISED_QTY_DUE,0)) AS S_O_Tot FROM CUSTOMER_ORDER_JOIN a LEFT OUTER JOIN SHOP_ORD b ON (a.part_no= b.part_no AND b.contract = '20' AND b.state = 'Planned') WHERE a.PART_NO = '10002261' AND a.OBJSTATE = 'Released' AND a.CONTRACT = '10' I have deleted grouping because you are filtering on this filed anyway
unknown
d16099
val
You can try this: // Encode $className = get_class($newCar); $jmsSerialize = $this->get('jms_serializer')->serialize($newCar, 'json'); $resultJSONEncode = json_encode([$className=>$jmsSerialize]); var_dump($resultJSONEncode); // Decode $resultJSONDecode = json_decode($resultJSONEncode, true); $jmsDesrialize = $this->get('jms_serializer')->deserialize($resultJSONDecode[$className], $className, 'json'); var_dump($jmsDesrialize);
unknown
d16100
val
If you know, during the build of the docker image, the name of the folder, use a variable: WORKDIR ${workdir} And set the variable value during the build. A: Having a non-deterministic content in a docker image is a bad idea. You should rename the folder first, then the WORKDIR will be easier: # Supposing there is only one folder123 at each build RUN mv /path/to/folder* /path/to/folder WORKDIR /path/to/folder A: how about trying the regex syntax? WORKDIR workdir[\d]+ Let me know if that works for you.
unknown