_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d7701
train
Enter the code here. Discord has added a feature (or it was already there, I don't know), which enables you to do what you want to do. const data = b64image.split(',')[1]; const buf = new Buffer.from(data, 'base64'); const file = new Discord.MessageAttachment(buf, 'img.jpeg'); const embed = new Discord.MessageEmbed() .attachFiles(file) .setImage('attachment://img.jpeg') webhookClient.send('', { username: userName, embeds: [embed], }); A: I tried with a smaller image, and the code in the question worked. So it was a problem with the size of the request. I fixed it by setting up an express route to serve images and used the URL in the embed router.get('/thumb/:imgId', (req, res) => { const imgId = req.params.imgId.toString().trim(); let file = Buffer.from(b64Image.split(',')[1], 'base64') res.status(200); res.set('Content-Type', 'image/jpeg'); res.set('Content-Length', file.length) res.send(file) }); const embed = new Discord.MessageEmbed() .setImage(`${base_url}/img/thumb/${imgId}`) webhookClient.send('', { username: userName, embeds: [embed], });
unknown
d7702
train
To augment the correct answers to use math.acos, it is also worth knowing that there are math functions suitable for complex numbers in cmath: >>> import cmath >>> cmath.acos(1j) (1.5707963267948966-0.88137358701954294j) Stick with math.acos if you're only interested in real numbers, A: The result of math.acos() is in radians. So you need to convert that to degrees. Here is how you can do: import math res = math.degrees (math.acos (value)) A: We have the acos function, which returns the angle in radians. >>> import math >>> math.acos(0) 1.5707963267948966 >>> _ * 2 - math.pi 0.0 A: In response to using inverse cosine to find return angles via math.acos, it's all fine and dandy so long as the angle is <=90* once you go past that, python will have no way of differentiating which angle you wanted. Observe. >>> math.cos(5) 0.28366218546322625 Above, I asked python to fetch me the cosine of a 5 radian angle, and it gave me .28~ Great, below I'll ask python to give me the radian which has a .28~ cosine. Should be 5, right? It literally just told me it was. >>> math.acos(0.28366218546322625) 1.2831853071795865 Wrong! Python returns 1.28~ radians. The reason is obvious when plotted visually, 1.28rad has the same cosine as 5rad, they're inverse angles. Every angle shares the same sine with another angle (and -sine with two others). i.e. 5/175* share an equivalent sine. They share inversely proportional cosines .99~/-.99 respectively. Their -sine cousins would be 185 and 355. The relationship meme here is that all these angles share the same angular deflection from the horizontal axis. 5*. The reason python returns 1.28 and not 5 is that all computers/calculators are based on an abacus-like data table of an angle/radian, its sine, cos, tan etc etc. So when i math.acos(x), python asks the kernal to look through that data table for whichever angle has a cosine of x, and when it finds it, it returns the first entry it appears with. and then python gives that angle to me. Due to this shared, proportional symmetry, sin/cos ratios repeat frequently. And you are likely to see the same figure, multiple times. There's no way for python, or the OS, to determine the difference of which of the two angles you actually require without doing additional logic that takes into account the -/+ value of the angle's sine. Or, the angle's tangent. 1.28 Rad has x cosine, y sine, z tan (72*) 1.88 Rad has -x cosine, y sine, -z tan (108*) 4.39 Rad has -x cosine, -y sine, z tan (252*) 5 Rad has x cosine, -y sine, -z tan (288*) or, viewed Cartesianly, negX,posY | posX,posY -----+----- negX,negY | posX,negY 1.88 Rad has -x cosine, y sine (108) | 1.28 Rad has x cosine, y sine (72*) -----+----- 4.39 Rad has -x cosine, -y sine (252)| 5 Rad has x cosine, -y sine (288) So if, for whatever reason, i need 5 radians to be chosen (say for a vector drawing or game to determine the various vectors enemies are from the player), i would have to do some type of if/then logic comparing the sines/tangents. A: You're looking for the math.acos() function. A: You may also use arccos from the module numpy >>> import numpy >>> numpy.arccos(0.5) 1.0471975511965979 WARNING: For scalars the numpy.arccos() function is much slower (~ 10x) than math.acos. See post here Nevertheless, the numpy.arccos() is suitable for sequences, while math.acos is not. :) >>> numpy.arccos([0.5, 0.3]) array([ 1.04719755, 1.26610367]) but >>> math.acos([0.5, 0.3]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: a float is required A: or just write a function of your own for the taylor expansion of cos^{-1} this would be more time consuming (and maybe slower to run) but is the more general approach
unknown
d7703
train
MinGW is actually GCC, so the flags are the same. But some flags depend on platform-specifics. Relocation Read-Only (RELRO) is specifically for ELF binaries, which are not supported on Windows. Instead Windows uses the PE/PE+ format (which is based on the COFF format. There is support for -Wl,--dynamicbase and ASLR (address space layout randomization) that you could take a look at to see if it helps you accomplish your goal.
unknown
d7704
train
Copy below code in one html file and check in IE <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { alert('hi'); var while_counter = 1; var txt = $('textarea.messagetext'); var font_size = txt.css('font-size').replace(/\D/g,''); var scHeight = txt.get(0).scrollHeight; var txtHeight = $(txt).height(); while ( scHeight > (txtHeight+10) ) { font_size = (font_size - 1); txtHeight = (txtHeight + 15); while_counter = while_counter + 1; } var lines = txt.val().split('\n'); var total_lines = lines.length; var span_width = $('#inner-text').width() - 5; var temp_span = $('#temp'); // now calculate line wraps $.each(lines, function(){ // temp write to hidden span temp_span.html(String(this)); // check width if (temp_span.width() > 400) { total_lines = total_lines + 1; } }); $(txt).css('font-size', font_size+'px'); $(txt).innerHeight( (total_lines * font_size) + (total_lines * 1.14) + 10); }); </script> </head> <body> <span id="inner-text"> <textarea readonly="readonly" cols="10" rows="5" class="messagetext" style="width:400px; border:none;height:100px;overflow:hidden;resize:none;color: #D31245;" >1 2 3 4 5 6 7 8 9 10 11 12 13 14 15</textarea> </span><span id="temp" style="visibility:hidden"></span> </body> </html>
unknown
d7705
train
You could just remove these 0s using conditional indexing (also assumed you meant len(l) - 1): a= torch.randperm(len(l)-1) #where l is total no of testing image in dataset, code output->tensor([10, 0, 1, 2, 4, 5]) a=a[a!=0] b=torch.tensor([0]) # code output-> tensor([0]) c=torch.cat((b,a))# gives output as -> tensor([0, 10, 0, 1, 2, 4, 5]) and 0 is used twice so repeated test image Or if you want to make sure it's never put in: a=torch.arange(1,len(l)) a=a[torch.randperm(a.shape[0])] b=torch.tensor([0]) c=torch.cat((b,a)) The second approach is a bit more versatile as you can have whatever values you'd like in your initial a declaration as well as replacement.
unknown
d7706
train
No, but it's quite simple to implement, you only need a linear layout with horizontal orientation, containing a button, a textview and another button. Have an internal value to count and then associate a callback to your buttons, where you add/substract your counter and update the textview, like this: substractButton.setOnClickListener(v -> { count--; countTextView.setText(count); }); sumButton.setOnClickListener(v -> { count++; countTextView.setText(count); });
unknown
d7707
train
Shared variables in CUDA are shared between threads in the same block. I don't know exactly how it is done under the hood but threads in the same thread-block will see __shared__ int sh_arr[BOCK_SIZE]; however, since it has the __shared__ modifier, only one thread will create the array while the others will just use it.
unknown
d7708
train
Your code is running with a docker on another instance so is 127.0.0.1 address is different from your computer's address. You must enter the external IP address of the container A: Try using host.docker.internal...
unknown
d7709
train
I ran into the same error using Rails and RSpec to test an API. I found a helpful blog post for Rails 2.3: http://eddorre.com/posts/using-rack-test-and-rspec-to-test-a-restful-api-in-rails-23x module ApiHelper require 'rack/test' include Rack::Test::Methods def app ActionController::Dispatcher.new end end My solution for Rails 3.2 was (look in config.ru for MyAppName): module ApiHelper require 'rack/test' include Rack::Test::Methods def app MyAppName::Application end end A: try this def app Rails.application end A: For anyone else banging their heads against the wall getting the "NameError: undefined local variable or method `app'" error. It also happens when you are running all your tests at once (multiple files) and one of them does an include Rack::Test::Methods - the include "infects" the other tests. So the symptom is that all tests pass when the files are run individually, but then they fail with the "no app" error when run together. At least this happens with rails 3.0.9 and rspec 3.0 The solution to this issue is to remove the includes. Alternatively you might try something like @ultrasaurus' answer to make sure the includes are properly contained to only the examples that need it.
unknown
d7710
train
Yes, it will. # open and read your HTML file as Nokogiri::HTML document doc = File.open("your_file.html") { |f| Nokogiri::HTML(f) } # collect all links that have not empty href attribute links = doc.css('a').map { |link| link['href'] }.reject { |link| link.blank? }
unknown
d7711
train
The page is loaded by javascript. Try using the requests_html package instead. See below sample. from bs4 import BeautifulSoup from requests_html import HTMLSession url = "https://www.baseball-reference.com/boxes/CLE/CLE202108120.shtml" s = HTMLSession() page = s.get(url, timeout=20) page.html.render() soup = BeautifulSoup(page.html.html, 'html.parser') print(soup.prettify) A: The other tables are there in the requested html, but within the comments. So you need to parse out the comments to get those additional tables: import requests from bs4 import BeautifulSoup, Comment import pandas as pd url = "https://www.baseball-reference.com/boxes/CLE/CLE202108120.shtml" result = requests.get(url).text data = BeautifulSoup(result, 'html.parser') comments = data.find_all(string=lambda text: isinstance(text, Comment)) tables = pd.read_html(url) for each in comments: if 'table' in str(each): try: tables.append(pd.read_html(str(each))[0]) except: continue Output: Oakland print(tables[2].to_string()) Batting AB R H RBI BB SO PA BA OBP SLG OPS Pit Str WPA aLI WPA+ WPA- cWPA acLI RE24 PO A Details 0 Mark Canha LF 6.0 1.0 1.0 3.0 0.0 0.0 6.0 0.247 0.379 0.415 0.793 23.0 19.0 0.011 0.58 0.040 -0.029% 0.01% 1.02 1.0 1.0 0.0 2B 1 Starling Marte CF 3.0 0.0 2.0 3.0 0.0 1.0 4.0 0.325 0.414 0.476 0.889 12.0 7.0 0.116 0.90 0.132 -0.016% 0.12% 1.57 2.8 1.0 0.0 2B,HBP 2 Stephen Piscotty PH-RF 1.0 0.0 1.0 2.0 0.0 0.0 2.0 0.211 0.272 0.349 0.622 7.0 3.0 0.000 0.00 0.000 0.000% 0% 0.00 2.0 1.0 0.0 HBP 3 Matt Olson 1B 6.0 0.0 1.0 2.0 0.0 0.0 6.0 0.283 0.376 0.566 0.941 21.0 13.0 -0.057 0.45 0.008 -0.065% -0.06% 0.78 -0.6 9.0 1.0 GDP 4 Mitch Moreland DH 5.0 3.0 2.0 2.0 0.0 0.0 6.0 0.230 0.290 0.415 0.705 23.0 16.0 0.049 0.28 0.064 -0.015% 0.05% 0.50 1.5 NaN NaN 2·HR,HBP 5 Josh Harrison 2B 0.0 1.0 0.0 0.0 1.0 0.0 1.0 0.294 0.366 0.435 0.801 7.0 3.0 0.057 1.50 0.057 0.000% 0.06% 2.63 0.6 0.0 0.0 NaN 6 Tony Kemp 2B 4.0 3.0 3.0 0.0 1.0 0.0 5.0 0.252 0.370 0.381 0.751 16.0 10.0 -0.001 0.14 0.009 -0.010% 0% 0.24 1.6 2.0 2.0 NaN 7 Sean Murphy C 4.0 3.0 2.0 2.0 2.0 1.0 6.0 0.224 0.318 0.419 0.737 25.0 15.0 0.143 0.38 0.151 -0.007% 0.15% 0.67 2.7 7.0 0.0 2B 8 Matt Chapman 3B 1.0 3.0 0.0 0.0 5.0 1.0 6.0 0.214 0.310 0.365 0.676 31.0 10.0 0.051 0.28 0.051 0.000% 0.05% 0.49 2.2 1.0 3.0 NaN 9 Seth Brown RF-CF 5.0 1.0 1.0 1.0 0.0 1.0 6.0 0.204 0.278 0.451 0.730 18.0 12.0 -0.067 0.40 0.000 -0.067% -0.07% 0.70 -1.7 4.0 0.0 SF 10 Elvis Andrus SS 5.0 2.0 1.0 2.0 1.0 0.0 6.0 0.233 0.283 0.310 0.593 20.0 15.0 0.015 0.42 0.050 -0.034% 0.02% 0.73 -0.1 0.0 4.0 NaN 11 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 12 Chris Bassitt P NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 1.0 0.0 NaN 13 A.J. Puk P NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 0.0 0.0 NaN 14 Deolis Guerra P NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 0.0 0.0 NaN 15 Jake Diekman P NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 0.0 0.0 NaN 16 Team Totals 40.0 17.0 14.0 17.0 10.0 4.0 54.0 0.350 0.500 0.575 1.075 203.0 123.0 0.317 0.41 0.562 -0.243% 0.33% 0.72 12.2 27.0 10.0 NaN
unknown
d7712
train
Please recheck once: 1) Go to Firebase console, select Database. 2) Selecte Rules. paste below one: { "rules": { ".read": true, ".write": true } } Your Activity should be: public class YourActivity extends AppCompatActivity implements View.OnClickListener { public static FirebaseDatabase mFirebaseDatabase; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mFirebaseDatabase = FirebaseDatabase.getInstance(); final EditText edittext = (EditText) findViewById(R.id.edittext); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (edittext.getText().toString().length() > 0) { mFirebaseDatabase.getReference("myref").push().setValue(edittext.getText().toString()); } } }); } } and your_activity.xml will be <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/edittext" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add Item"/> </LinearLayout> A: Please try to give margin at xml like this: <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" /> Note this will solve the error which you mention above . Hope this will help you out..and let me know your feedback
unknown
d7713
train
I think I got this. My code was 'quite' long with different describes, when I minimalized it to 2, it started working :) EDIT: As I mentioned in comment below, each method in Workflow1 and Workflow2 files must have at least one describe and at least one it inside - having only describe without it throws error
unknown
d7714
train
If you really, really must do this, and you are sure you are not making a mistake, check out the @SuppressWarnings annotation. I suppose in your case you need @SuppressWarnings("fallthrough") A: Is the annotation @SuppressWarnings (javadoc) what you are looking for? For example: @SuppressWarnings("unchecked") public void someMethod(...) { ... } A: To complete other answer about SuppressWarnings: @SuppressWarnings("fallthrough") Try to supress all the fall-through warning at the compiler level is a bad thing: as you've explained, the cases where you need to pass through the warning are clearly identified. Thus, it should be explicitly written in the code (the @SuppressWarnings("fallthrough") annotation with an optionnal comment is welcome). Doing so, you'll still have the fall-through warning if you really forget a break somewhere elese in your code. A: You could create a structure of 'if' statements in place of the switch. Might not be as visually pleasing however neither is warning supression. A: @SuppressWarnings("fallthrough") Java has always followed the C-style of switch statements, where you need to explicititly break out of a switch unless you wish to simply fall through and execute the code in the case below. This can be dangerous of course and errors of this kind can be very hard to track down. In the following example, case 1 lacks a break: @SuppressWarnings("fallthrough") public void fallthroughTest(int i) { switch (i) { case 1: // Execute both 1 and 2 case 2: // Execute only 1 } }
unknown
d7715
train
We need to see all your code, but you probably have margin:0 at the html/body. Without it, it works html, body { height: 100%; overflow-y: auto; } .fixed { position: fixed; height: 70px; background-color: blue; top: 0; width: 100% } .content{ height: 2000px } <div class="fixed"></div> <div class="content"> </div> When I add the margin I got the same problem you experience html, body { height: 100%; overflow-y: auto; margin: 0; } .fixed { position: fixed; height: 70px; background-color: blue; top: 0; width: 100% } .content{ height: 2000px } <div class="fixed"></div> <div class="content"> </div> A: You can remove scroll from html, body elements and add it to content wrapper. In this example it is main element. Html example <body> <header>Header</header> <main> <!--All page content goes here--> </main> </body> Remove dafault page scroll body, html { height: 100%; overflow: hidden; } Add scroll and height for content wrapper main { margin-top: 40px; height: calc(100% - 40px); overflow: auto; } 40px here is the height of the fixed header. header { ... height: 40px; ... } body, html { height: 100%; overflow: hidden; /*Some reset styles*/ margin: 0; font-family: sans-serif; } header { position: fixed; top: 0; left: 0; right: 0; display: flex; align-items: center; height: 40px; background-color: gainsboro; } main { margin-top: 40px; height: calc(100% - 40px); overflow: auto; } header, main { padding-left: 15px; padding-right: 15px; } <header>Header</header> <main> <h1>Title</h1> <h2>Title 2</h2> <h3>Title 3</h3> <p>The Lost World is a novel released in 1912 by Sir Arthur Conan Doyle concerning an expedition to a plateau in the Amazon basin of South America where prehistoric animals (dinosaurs and other extinct creatures) still survive. It was originally published serially in the popular Strand Magazine and illustrated by New-Zealand-born artist Harry Rountree during the months of April–November 1912. The character of Professor Challenger was in thrusting book. The novel also describes a war between indigenous people and a vicious tribe of ape-like creatures.</p> <p>The Lost World is a novel released in 1912 by Sir Arthur Conan Doyle concerning an expedition to a plateau in the Amazon basin of South America where prehistoric animals (dinosaurs and other extinct creatures) still survive. It was originally published serially in the popular Strand Magazine and illustrated by New-Zealand-born artist Harry Rountree during the months of April–November 1912. The character of Professor Challenger was in thrusting book. The novel also describes a war between indigenous people and a vicious tribe of ape-like creatures.</p> </main>
unknown
d7716
train
this might help you. Would be better if we could use Stream<char>, but, this does not work, so, we need to use the wrapper class. Since you want the first index, you can use 0. String.charAt(index) returns a char primitive, so, it will use less memory than a String.substring(...) that returns a new String. final String[] array = {"A", "B", "C", "D"}; final Character [] char_array = Arrays.stream(array) .map(s -> s.charAt(0)) .toArray(Character[]::new); for(char a: char_array) { System.out.println(a); } A: You can use streams, this will return a char [] array. Arrays.stream(S).map(s -> s.substring(0,1)).collect(Collectors.joining()).toCharArray(); Full code String [] S = { "A", "B", "C"} ; char [] ch =Arrays.stream(S).map(s -> s.substring(0,1)) .collect(Collectors.joining()).toCharArray(); for(int i=0;i<ch.length;i++){ System.out.println(ch[i]); } For better use, I suggest making a method that implements this stream and returns a char [] public char [] convertToChar(String [] yourArray){ return Arrays.stream(youArray).map(s -> s.substring(0,1)).collect(Collectors.joining()).toCharArray(); }
unknown
d7717
train
For kilobyte divide it by 1048576. Did you need something more complicated than that? $sizeInGB = $sizeInKB / 1048576;
unknown
d7718
train
I've taken a look at your code and altered it. Try this and see if this is what you're looking for. In my example i'm looking for the element by getElementById and then I set it's style.height to window.innerHeight - 10px without taking the 10px it wouldn't show the border fully on the page. So you just remove 10px's. The example has been tested on different screen sizes. Javascript example: function autoResizeDiv() { document.getElementById('body').style.height = window.innerHeight - 10 + 'px'; console.log(window.innerHeight - 10 + 'px'); } window.onresize = autoResizeDiv; autoResizeDiv(); #body { display: block; border: 5px solid black; } body { overflow: hidden; margin: 0; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="body"> </div> A: The following worked for me: $(".body").height($(window).height()); A: I figured out the biggest problem. I was using some absolutely positioned elements without giving a parent any other position. This made things show up wonky when I was trying to size other things. I also needed to have an extra div as a container for all the content on the page that would be the height of the window + the height of the header. Thanks to everyone who answered, it helped!
unknown
d7719
train
You can type the data prop as RnMcharacter. You can also remove the then call as you're using async|await export async function askForList(){ const res = await fetch('http://127.0.0.1:3333/applist'); const { data }: { data: RnMcharacter } = await res.json(); return data; }
unknown
d7720
train
I had a similar problem earlier. I hope this will work for you. As I did not have your data, I created some dummy data. Sorry about the looooong explanation. Here are the steps that should help you reach your goal... This is what I did: * *Order the data and sort it - used pd.Categorical to set the order and then df.sort to sort the data so that the input is sorted by source and then destination. *For the sankey node, you need to set the x and y positions. x=0, y=0 starts at top left. This is important as you are telling plotly the order you want the nodes. One weird thing is that it sometimes errors if x or y is at 0 or 1. Keep it very close, but not the same number... wish I knew why *For the other x and y entries, I used ratios as my total adds up to 285. For eg. Source-Informal starts at x = 0.001 and y = 75/285 as Source-Formal = 75 and this will start right after that *Based on step 1, the link -> source and destination should also be sorted. But, pls do check. Note: I didn't color the links, but think you already have achieved that... Hope this helps resolve your issue... My data - sankey.csv source,destination,value Formal,Formal,20 Formal,Informal, 10 Formal,Unemployed,30 Formal,Inactive,15 Informal,Formal,20 Informal,Informal,15 Informal,Unemployed,25 Informal,Inactive,25 Unemployed,Formal,5 Unemployed,Informal,10 Unemployed,Unemployed,10 Unemployed,Inactive,5 Inactive,Formal,30 Inactive,Informal,20 Inactive,Unemployed,20 Inactive,Inactive,25 The code import plotly.graph_objects as go import pandas as pd df = pd.read_csv('sankey.csv') #Read above CSV #Sort by Source and then Destination df['source'] = pd.Categorical(df['source'], ['Formal','Informal', 'Unemployed', 'Inactive']) df['destination'] = pd.Categorical(df['destination'], ['Formal','Informal', 'Unemployed', 'Inactive']) df.sort_values(['source', 'destination'], inplace = True) df.reset_index(drop=True) mynode = dict( pad = 15, thickness = 20, line = dict(color = "black", width = 0.5), label = ['Formal', 'Informal', 'Unemployed', 'Inactive', 'Formal', 'Informal', 'Unemployed', 'Inactive'], x = [0.001, 0.001, 0.001, 0.001, 0.999, 0.999, 0.999, 0.999], y = [0.001, 75/285, 160/285, 190/285, 0.001, 75/285, 130/285, 215/285], color = ["#305CA3", "#C1DAF1", "#C9304E", "#F7DC70", "#305CA3", "#C1DAF1", "#C9304E", "#F7DC70"]) mylink = dict( source = [ 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3 ], target = [ 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7 ], value = df.value.to_list()) fig = go.Figure(data=[go.Sankey( arrangement='snap', node = mynode, link = mylink )]) fig.update_layout(title_text="Basic Sankey Diagram", font_size=20) fig.show() The output
unknown
d7721
train
Just change public void Login() to public Login() Login is not a method, it is a constructor.
unknown
d7722
train
You can easily send an email from within a shell by piping a complete mail message (header and body) into sendmail. This assumes that the host you're doing this is properly configured with a mail transfer agent (e.g. sendmail or postfix) to send email messages. The easiest way to send email with an attachment is to create a simple template message in your mail user agent (e.g. Thunderbird), and copy its contents as a template with the view source command. Modify that template to suit your needs and place it in the shell script. Here is an example: #!/bin/sh cat <<\EOF | To: Ramesh <[email protected]> From: Diomidis Spinellis <[email protected]> Subject: Here are your Hadoop results Message-ID: <[email protected]> Date: Sun, 3 Apr 2016 09:58:48 +0300 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------030303090406090809090501" This is a multi-part message in MIME format. --------------030303090406090809090501 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit The attachment contains your Hadoop results. --------------030303090406090809090501 Content-Type: application/octet-stream; name="data" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="data" HviDNR105+2Tr0+0fsx3OyzNueQqPuAXl9IUrafOi7Y= --------------030303090406090809090501-- EOF sendmail [email protected] To configure a fixed message with actual data, replace the parts you want to modify with commands that generate them. (Note the missing backslash from the here document EOF marker.) #!/bin/sh cat <<EOF | To: Ramesh <[email protected]> From: Diomidis Spinellis <[email protected]> Subject: Here are your Hadoop results Message-ID: <[email protected]> Date: $(date -R) MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------030303090406090809090501" This is a multi-part message in MIME format. --------------030303090406090809090501 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit The attachment contains your Hadoop results. --------------030303090406090809090501 Content-Type: application/octet-stream; name="data" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="data" $(base64 binary-data-file.dat) --------------030303090406090809090501-- EOF sendmail [email protected]
unknown
d7723
train
It happens because you have to specify urlRoot property of the model. Without it url is not considered. So try this maybe: MessageManager.models.Conversation = Backbone.Model.extend({ defaults: { uid: '', title: '', messages: [], users: [], dateUpdated: null, isNew: true, message: '' }, urlRoot: function() { var url = '/api/conversations'; if (this.get('uid').length > 0) url += '/'+this.get('uid'); return url; } }); Documentation says: urlRootmodel.urlRoot or model.urlRoot() Specify a urlRoot if you're using a model outside of a collection, to enable the default url function to generate URLs based on the model id. "[urlRoot]/id" Normally, you won't need to define this. Note that urlRoot may also be a function. And source code for Backbone.Model url method: url: function() { var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); if (this.isNew()) return base; return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id); }, A: defsq answer is good. The only thing missing is to define the idAttribute on your model, since it's not the convention-based id field, but uid. MessageManager.models.Conversation = Backbone.Model.extend({ idAttribute: 'uid', defaults: { uid: '', title: '', messages: [], users: [], dateUpdated: null, isNew: true, message: '' }, urlRoot: "/api/conversations" }); You don't need to append the "id" manually. Just tell Backbone that your id attribute is uid and everything else will work. In fact, you can event call mymodel.id to get the id of the model -event if it's stored internally as uid. :) http://backbonejs.org/#Model-idAttribute Personally I don't like all that default values. Everything will be undefined if you don't set default values, which you can simply guard against with an if (undefined is a falsey value). if(!model.get("messages")){ //no messages }
unknown
d7724
train
Verify that you have this registry key: HKLM\SOFTWARE\SourceCodeControlProvider\InstalledSCCProviders I've seen some source control tools either not use it, or remove it, and PowerBuilder looks there for the SCC vendors. If there are none there, then PB won't show the SCC options as available. A: Another thing to check - Make sure the workspace file (*.pbw) is not read-only. Right click on the file and verify that the *.pbw file does not have the Read-Only attribute checkbox selected.
unknown
d7725
train
Building a Dynamic UI with Fragments...just use fragments in your application to make it flexible http://developer.android.com/guide/components/fragments.html http://developer.android.com/training/basics/fragments/index.html
unknown
d7726
train
You will need to slightly modify the K2 view (we did this to one of our clients). You will need to create a query that resembles the following in the view: SELECT count(*) FROM #__k2_items WHERE authorid='id'; Now you should pass the result of that query to the template (using the assignRef function on the $this object. That's it! Note: not sure about the field name authorid, I'm sure it's something else but I can't remember it on top of my head.
unknown
d7727
train
The i variable is already defined as part of the for loop. Just remove the following line: int i = 0; A: int i = 0; for(int i = 0; i < upper_limit + 1 ; i++ ) { remove the int inside the for loop or the remove the line above the for loop. now you define int i twice A: you define the variable i twice in your code. It should only be defined on time. I have highlighted the two times below. Scanner input_scanner = new Scanner( System.in ); System.out.print( "Powers of 2 up to? " ); int upper_limit = input_scanner.nextInt(); int i = 0; //First time i is defined for(int i = 0; i < upper_limit + 1 ; i++ ) //second time i is defined { System.out.println( i + " - " + Math.pow( 2, i)); } To fix this either remove one of the int i = 0 lines. Both options shown below: int upper_limit = input_scanner.nextInt(); //First definition removed for(int i = 0; i < upper_limit + 1 ; i++ ) //second time i is defined { System.out.println( i + " - " + Math.pow( 2, i)); } second solution int upper_limit = input_scanner.nextInt(); int i = 0; //First time i is defined for(; i < upper_limit + 1 ; i++ ) //second definition removed { System.out.println( i + " - " + Math.pow( 2, i)); }
unknown
d7728
train
this code should demonstrate the basics of a post test. Assumes you have a repository injected into the controller. I am using MVC 4 RC not Beta here if you are using Beta the Request.CreateResponse(... is a little different so give me a shout... Given controller code a little like this: public class FooController : ApiController { private IRepository<Foo> _fooRepository; public FooController(IRepository<Foo> fooRepository) { _fooRepository = fooRepository; } public HttpResponseMessage Post(Foo value) { HttpResponseMessage response; Foo returnValue = _fooRepository.Save(value); response = Request.CreateResponse<Foo>(HttpStatusCode.Created, returnValue, this.Configuration); response.Headers.Location = "http://server.com/foos/1"; return response; } } The unit test would look a little like this (NUnit and RhinoMock) Foo dto = new Foo() { Id = -1, Name = "Hiya" }; IRepository<Foo> fooRepository = MockRepository.GenerateMock<IRepository<Foo>>(); fooRepository.Stub(x => x.Save(dto)).Return(new Foo() { Id = 1, Name = "Hiya" }); FooController controller = new FooController(fooRepository); controller.Request = new HttpRequestMessage(HttpMethod.Post, "http://server.com/foos"); //The line below was needed in WebApi RC as null config caused an issue after upgrade from Beta controller.Configuration = new System.Web.Http.HttpConfiguration(new System.Web.Http.HttpRouteCollection()); var result = controller.Post(dto); Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Expecting a 201 Message"); var resultFoo = result.Content.ReadAsAsync<Foo>().Result; Assert.IsNotNull(resultFoo, "Response was empty!"); Assert.AreEqual(1, resultFoo.Id, "Foo id should be set"); A: Using AutoFixture, I usually do something like this: [Theory, AutoCatalogData] public void PostToCollectionReturnsCorrectResponse( CategoriesController sut, CategoryRendition categoryRendition) { HttpResponseMessage response = sut.Post(categoryRendition); Assert.Equal(HttpStatusCode.Created, response.StatusCode); } See this other SO answer for more details about this approach. A: Sample code for unit testing API controller with async fundtion in C# * *Prepare test Models: using System; namespace TestAPI.Models { public class TestResult { public DateTime Date { get; set; } public bool Success { get; set; } public string Message { get; set; } } } *Prepare test controller using TestAPI.Models; using System; using System.Net; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Description; namespace TestAPI.Controllers { public class TestController : ApiController { public TestController() { } [HttpPost] [ResponseType(typeof(TestResult))] [Route("api/test/start")] public async Task<IHttpActionResult> StartTest() { DateTime startTime = DateTime.Now; var testProcessor = new TestAsync(); await testProcessor.StartTestAsync(); HttpStatusCode statusCode = HttpStatusCode.OK; return Content(statusCode, new TestResult { Date = DateTime.Now, Success = true, Message = "test" }); } } } *unit test async controller with result check from response using Microsoft.VisualStudio.TestTools.UnitTesting; using TestAPI.Controllers; using TestAPI.Models; using System.Web.Http; using System.Threading.Tasks; using System.Net; using System.Web.Script.Serialization; namespace Unit.Tests.Controllers { /// <summary> /// Summary description for ControllerTest /// </summary> [TestClass] public class ControllerTest { private TestController _testController; [TestInitialize] public void estAPI_Initializer() { _testController = new TestController(); var configuration = new HttpConfiguration(); System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(); request.Headers.Add("Authorization", "Bearer 1232141241"); request.Headers.Add("ContentType", "application/json"); _testController.Request = request; _testController.Configuration = configuration; } [TestCategory("Unit test")] [TestMethod] public async Task API_Async_Controller_Test() { IHttpActionResult asyncResponse = await _testController.StartTest(); var cToken = new System.Threading.CancellationToken(true); var rResult = asyncResponse.ExecuteAsync(cToken); Assert.IsNotNull(rResult); Assert.IsNotNull(rResult.Result); Assert.AreEqual(rResult.Result.StatusCode, HttpStatusCode.OK); Assert.IsNotNull(rResult.Result.Content); var rContent = rResult.Result.Content; string data = await rContent.ReadAsStringAsync(); Assert.IsNotNull(data); JavaScriptSerializer JSserializer = new JavaScriptSerializer(); var finalResult = JSserializer.Deserialize<TestResult>(data); Assert.IsNotNull(finalResult); Assert.IsTrue(finalResult.Success); } } } A: I've created a general solution for calling some action and getting HttpResponseMessage as Dictionary which is very convenient for usage. First some extension for the dictionary: public static class DictionaryExtensions { public static void AddRange<T, S>(this Dictionary<T, S> source, Dictionary<T, S> collection) { if (collection == null) { throw new NullReferenceException("Collection is null"); } foreach (var item in collection) { source.Add(item.Key, item.Value); } } } Now request creating part: public class RequestCreator { protected static void FirstPart(ApiController controller, HttpMethod method,String actionUrl) { // Creating basic request message with message type and requesting // url example : 'http://www.someHostName/UrlPath/' controller.Request = new HttpRequestMessage(method, actionUrl); // Adding configuration for request controller.Request.Properties. Add(HttpPropertyKeys.HttpConfigurationKey,new HttpConfiguration()); } protected static Dictionary<String, Object> SecondPart (HttpResponseMessage response) { // Adding basic response content to dictionary var resultCollection = new Dictionary<String, Object> { {"StatusCode",response.StatusCode}, {"Headers",response.Headers}, {"Version",response.Version}, {"RequestMessage",response.RequestMessage}, {"ReasonPhrase",response.ReasonPhrase}, {"IsSuccessStatusCode",response.IsSuccessStatusCode} }; var responseContent = response.Content; // If response has content then parsing it and // getting content properties if (null != responseContent) { var resultMessageString = response.Content. ReadAsStringAsync().Result; resultCollection.AddRange((new JavaScriptSerializer()). DeserializeObject(resultMessageString) as Dictionary<String, Object>); } return resultCollection; } } And finally response message to dictionary converter class: public class HttpResponseModelGetter : RequestCreator { public Dictionary<String, Object> GetActionResponse(ApiController controller,HttpMethod method, String actionUrl,Func<HttpResponseMessage> callBack) { FirstPart(controller, method, actionUrl); var response = callBack(); return SecondPart(response); } } public class HttpResponseModelGetter<T> : RequestCreator { public Dictionary<String, Object> GetActionResponse(ApiController controller,HttpMethod method, String actionUrl,Func<T,HttpResponseMessage> callBack,T param) { FirstPart(controller, method, actionUrl); var response = callBack(param); return SecondPart(response); } } public class HttpResponseModelGetter<T1,T2> : RequestCreator { public Dictionary<String, Object> GetActionResponse(ApiController controller,HttpMethod method, String actionUrl,Func<T1,T2,HttpResponseMessage> callBack, T1 param1,T2 param2) { FirstPart(controller, method, actionUrl); var response = callBack(param1,param2); return SecondPart(response); } } //and so on... and usage : var responseGetter = new HttpResponseModelGetter(); var result = responseGetter.GetActionResponse(controller,HttpMethod.Get, "http://localhost/Project/api/MyControllerApi/SomeApiMethod", controller.SomeApiMethod); Boolean isComplete = Boolean.Parse(result["isComplete"].ToString());
unknown
d7729
train
You need a having clause in there combined with your where clause: ids = [1,3] Book .select('books.*') # not sure if this is necessary .where(authors_books: { author_id: ids }) .joins(:authors_books) .group('books.id') .having('count(authors_books) >= ?', ids.size) The SQL: https://www.db-fiddle.com/f/i7TXPJgavLwQCHb4GhgH3b/0
unknown
d7730
train
First: your solution is wrong. The question clearly is stating that L and R are the indexes of the subarray (not the value), and you are using as value to find the mean value. Second: Scanner class is very easy, need less typing but not recommended as it is very slow. Instead, use BufferReader. Here is my solution: import java.io.BufferedReader; import java.io.InputStreamReader; public class PlayWithNumbers { public static void main(String[] args) { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); long n=Integer.parseInt(st.nextToken()); long qry=Integer.parseInt(st.nextToken()); long arr[]=new long[(int) n]; st = new StringTokenizer(br.readLine()); // read every number, adding with previous all numbers and store in the array index arr[0] = Integer.parseInt(st.nextToken()); for (int i = 1; i <n ; i++) { arr[i]=arr[i-1]+Integer.parseInt(st.nextToken()); } for (int j = 0; j <qry ; j++) { long sum=0; double ans=0; st = new StringTokenizer(br.readLine()); int L=Integer.parseInt(st.nextToken()); int R=Integer.parseInt(st.nextToken()); // check if the value 1 then don't subtract left value (as in that case there won't be any left value // otherwise subtract just left most value from the array if (L == 1) { sum=arr[R-1]/(R-L+1); } else { sum=(arr[R-1] - arr[L-2])/(R-L+1); } ans=Math.floor(sum); System.out.println((int) ans); } } } Let me know if you need any clarification.
unknown
d7731
train
What is a hyperlink, really? Its a text "button" that, when clicked, brings you to a website or opens a link of some sort. So in this case, use a button in a tab on the Excel ribbon that when clicked brings you to a website. Easy: Private Sub MyRibbonButton_Click(Byval sender as Object, Byval e as EventArgs) Handles MyRibbonButton.Click System.Diagnostics.Process.Start("my website url") End Sub Does it look like a button? Of course, but essentially it's just a hyperlink, right? A: Use a CustomUI to create buttons for macros: 'To send email 'Callback for customButton onAction Sub MyWeb(control As IRibbonControl) Dim oShell As Object Set oShell = CreateObject("Wscript.Shell") oShell.Run ("http://www.plugpro.com.br") End Sub 'To Open URL 'Callback for customButton onAction Sub MyWeb(control As IRibbonControl) Dim oShell As Object Set oShell = CreateObject("Wscript.Shell") oShell.Run ("mailto:[email protected]") End Sub
unknown
d7732
train
It all depends on how secure you want it to be. The simplest solution is to include a parameter in your POST request that only your backend and front-end instances would recognize - any random sequence of characters will do the trick. The next level is to use a secret key to encrypt the contents of the request - there are many implementations depending on the language that you use. This approach is more flexible too, if you decide, for example, to move your backend from App Engine to Compute Engine.
unknown
d7733
train
You might not intend to implement funcationaly but there is no need for imperative code in your example at all and returns and vars cause some serious issues when it comes to reading the intend of the code. I would rewrite the code to something like this sealed trait IP extends Product with Serializable object IP { final case class V4(a: Int, b: Int, c: Int, d: Int) extends IP final case class V6(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int, g: Int, h: Int) extends IP } val ipV4 = """(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})""".r val ipV6 = """([0-9a-fA-F]+):""".r def validIPAddress(ip: String): Either[String, IP] = { def parseV4(s: String) = { val i = Integer.parseInt(s) if (0 <= i && i <= 255) Right(i) else Left(s"$i is not a valid IPv4 number") } def parseV6(s: String) = Integer.parseInt(s, 16) ip match { case ipV4(a, b, c, d) => for { a1 <- parseV4(a) b1 <- parseV4(b) c1 <- parseV4(c) d1 <- parseV4(d) } yield IP.V4(a1, b1, c1, d1) case ipV6(a, b, c, d, e, f, g, h) => // technically speaking this isn't exhausting all possible IPv6 addresses... // as this regexp would ignore e.g. ::1 or :: Right(IP.V6(parseV6(a), parseV6(b), parseV6(c), parseV6(d), parseV6(e), parseV6(f), parseV6(g), parseV6(h))) case _ => Left(s"$ip is neither V4 nor V6 format") } } to make it easier to follow and debug errors, though as I checked this implementation is NOT really conforming to what IPv6 does, as some tuning around regexp usage would be necessary. As a matter of the fact, I would prefer to avoid rolling my own solution altogether if I couldn't afford some time for writing down like 15-20 test cases. So, unless there is a reason to implement your own validator I would delegate that task to some library which already tested handling corner cases. If you have to, however, do the following things: * *don't use return - in Scala it does something different than what you think it does *don't use vars unless you're optimizing - the way you use them have nothing to do with optimization (isValid is never used, so why override it? and other vars are never modified) *don't use string for everything because that is asking for trouble on its own (e.g. "neither" and "Neither" - should the caller use .equalsIgnoreCase on your code to check results?) *start with tests written basing on specification. While I translated your code it fails valid IPv6 addresses. If I skipped the requirement that Iv6 is fixed size, it would be even shorter to: sealed trait IP extends Product with Serializable object IP { final case class V4(a: Int, b: Int, c: Int, d: Int) extends IP final case class V6(values: List[Int]) extends IP } val ipV4 = """(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})""".r val ipV6 = """([0-9a-fA-F]*)((:[0-9a-fA-F]*){2,})""".r def validIPAddress(ip: String): Either[String, IP] = { def parseV4(s: String) = { val i = Integer.parseInt(s) if (0 <= i && i <= 255) Right(i) else Left(s"$i is not a valid IPv4 number") } def parseV6(s: String) = if (s.isEmpty) 0 else Integer.parseInt(s, 16) ip match { case ipV4(a, b, c, d) => for { a1 <- parseV4(a) b1 <- parseV4(b) c1 <- parseV4(c) d1 <- parseV4(d) } yield IP.V4(a1, b1, c1, d1) case ipV6(head, tail, _) => val segments = head +: tail.substring(1).split(':') Right(IP.V6(segments.map(parseV6).toList)) case _ => Left(s"$ip is neither V4 nor V6 format") } } which handled more correct cases but is still far from ready. So if you can - avoid doing it yourself and use a library.
unknown
d7734
train
If a Maven project is configured to use ecj compiler, the following errors appear when importing the project into eclipse: * *No marketplace entries found to handle maven-compiler-plugin:2.3.2:compile in Eclipse. Please see Help for more information. *No marketplace entries found to handle maven-compiler-plugin:2.3.2:testCompile in Eclipse. Please see Help for more information. A fix should be trivial. http://git.eclipse.org/c/m2e/m2e-core.git/tree/org.eclipse.m2e.jdt/lifecycle-mapping-metadata.xml reads: <parameters> <compilerId>javac</compilerId> </parameters> It should read: <parameters> <compilerId>javac</compilerId> <compilerId>eclipse</compilerId> </parameters> Reproducible: Always Steps to Reproduce: 1. Unpack example zip provided 2. Try to import it to Eclipse: File->Import->Maven->Existing Maven Projects A: First you can try to install maven globaly. follow the steps. * *Download maven from maven download link *Create or export M2_HOME="MAVEN ROOT LOCATION". Ex. : E:\SoftwareRepo\building tools\apache-maven-3.5.2 *Create or export MAVEN bin folder location to PATH variable. For example: E:\SoftwareRepo\building tools\apache-maven-3.5.2\bin *Open terminal or cmd and run mvn --version to confirm maven is installed or not. Then go to eclipse. and setup project.follow this steps * *Import existing maven project or create a maven project *Goto project explorer and Right click on your pom.xml *then select Run As maven install. *and then what you want. Hope it will serve your purpose. You can download a sample spring boot project from sample spring boot project Or you can run a maven project from terminal or cmd. Just goto project root folder and then run a maven task like maven clean install . Happy Coding :) A: First install Java and then create the maven project. Install the stable Java version in the system. If Java is not installed then these types of errors will be displayed. No marketplace entries found to handle maven-compiler-plugin:3.1:compile in Eclipse. Take a look at Help for more information.
unknown
d7735
train
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Product product) { ... return View("List"); } or [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Product product) { ... return RedirectToAction("List", "Product"); } A: your controller should work like this: public class ProductController : Controller { IList<Product> products; public ProductController( ) { products = new List<Product>(); products.Add(new Product() { Id = 1, Name = "A", Price = 22.3 }); products.Add(new Product() { Id = 2, Name = "B", Price = 11.4 }); products.Add(new Product() { Id = 3, Name = "C", Price = 26.5 }); products.Add(new Product() { Id = 4, Name = "D", Price = 45.0 }); products.Add(new Product() { Id = 5, Name = "E", Price = 87.79 }); } public ActionResult List( ) { return View(products); } public ActionResult Create() { return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Product product) { products.Add(product); return View("List", products); } } Additionally, you need to call RenderPartial instead of RenderAction, because otherwise your POST method will be invoked (due to you did a post-command by submitting the form): <p> <% Html.RenderPartial("Create"); %> </p> This should work, you only need to persist your products list, as it will reset with every postback. I hope this helped you :) A: Are the names of your text fields the same as the properties in your Product object? Does your product object declare it's properties like this; public string Name {get;set;} You must have getters and setters on your objects. EDIT Wait, are you wanting fields from your list View to be available in the post to your create action? If yes then you need to place the BeginForm at the View level and not the PartialView level. Only fields contained within the begin form will be posted to your controller. EDIT 2 Ah, I think I see it now. In your controller I think you should do a product.IsValid to check first. But in your html you should also do this; <%= Html.TextBox("Id", Model.Id) %> You need to fill in the value for the text box. Hope this is what you were after.
unknown
d7736
train
Use tapply as shown: L <- list(M1, M2, M3, M4, M5, M6) # or mget(ls(pattern = "^M\\d$")) tapply(L, subgroups, Reduce, f = "+") giving: $`1` [,1] [,2] [1,] 5 2 [2,] 3 5 $`2` [,1] [,2] [1,] 0 1 [2,] 0 1 $`3` [,1] [,2] [1,] -1 -6 [2,] 4 -1
unknown
d7737
train
Place the try-except block inside the function. Ex: def add(num1, num2): try: return (float(num1) + float(num2)) except ValueError: return None A: Try needs to be inside a function definition and does not need an else. Basically, the except functions as the try's else. def add(num1, num2): try: return(float(num1) + float(num2)) except ValueError: return(None) A: you should do: def add(num1, num2): try: return float(num1)+float(num2) except: return None The problem is that you are trying to create a function but returning values outside that function, and for the case of your else statement, the function is not even defined at that point and you are calling it.
unknown
d7738
train
I wanted to add a little to the above. In addition to selecting a branch of a tree, you often want descendants of only a certain depth. To accomplish this, many tables using add an additional computed column for "depth" ( something like [Depth] AS (myHierarchy.GetLevel]() ). With this extra column you can run queries like the following to limit by depth. SELECT @MaxDepth = 3, SELECT @theParent = Hierarchy, @theParentDepth = Depth FROM myTreeTable T WHERE T.RowID = @RowID SELECT myHierarchy FROM myTreeTable T WHERE T.myHierarchy.IsDescendantOf(@theParent) = 1 AND T.Depth < (@theParentDepth + @MaxDepth) Note, you may want to index the computed column (probably combined with or including some other columns) if you are relying on it heavily.
unknown
d7739
train
You can change the levels of the variable - levels(df$attend)[levels(df$attend) == 'iap'] <- NA df # attend sex #1 yes male #2 no female #3 no female #4 <NA> male #5 yes female #6 yes male #7 <NA> female This will also automatically drop the 'iap' as level. levels(df$attend) #[1] "no" "yes" Here we can also use forcats::fct_recode to turn specific values to NA. df$attend <- forcats::fct_recode(df$attend, NULL = 'iap') A: Another base R solution would be using exclude: df$attend <- factor(df$attend, exclude = "iap") attend sex 1 yes male 2 no female 3 no female 4 <NA> male 5 yes female 6 yes male 7 <NA> female
unknown
d7740
train
I found a solution, it works for me. instead of using document ready, i changed everything to be a function and then, call it with settimeout at 7 seconds (tried with 3 but the problem persisted). Hope nobody has this problem it was tricky to solve.
unknown
d7741
train
Chat.where(group_id: @arandomthing).where('created_at >= ?', @groupread.updated_at).order('created_at DESC') Concating strings like you're doing is a recipe for disaster, much better to use the tools Rails gives you.
unknown
d7742
train
The signature indicates the names and types of the input arguments, and (with type annotations) the type of the returned result(s) of a function or method. This is not particular to Python, though the concept is more central in some other languages (like C++, where the same method name can exist with multiple signatures, and the types of the input arguments determine which one will be called). A: In general the signature of a function is defined by the number and type of input arguments the function takes and the type of the result the function returns. As an example in C++ consider the following function: int multiply(int x, int y){ return x*y; } The signature of that function, described in an abstract way would be the set {int, int, int}. As Python is a weakly typed language in general the signature is only given by the amount of parameters. But in newer Python versions type hints were introduced which clarify the signature: def multiply(x: int, y: int) -> int: return x*y A: A function signature is its declaration, parameters, and return type. def func(params): #some stuff return modified_params When you call it is an instance of that function. var = func(parameters)
unknown
d7743
train
You'll have to convert the sets to lists too if you want to apply ordering. The sorted() function gives you a sorted list from any iterable, letting you skip a step: for key in sorted(index): print('{:<20}{}'.format(key, ', '.join(str(i) for i in sorted(index[key])))) Short demo: >>> sorted(index) ['connected', 'depth first search', 'neighbor', 'path', 'shortest path', 'spanning tree', 'vertex'] >>> sorted(index['connected']) [28, 54] >>> for key in sorted(index): ... print('{:<20}{}'.format(key, ', '.join(str(i) for i in sorted(index[key])))) ... connected 28, 54 depth first search 55 neighbor 27, 64, 77 path 19, 72 shortest path 55 spanning tree 16, 99 vertex 54 A: You can use the collections module in the standard library which has an OrderedDict type which is just a dict that remembers order of insertion. If you want a dictionary in alphabetical order, where your values are ordered lists: sorted_index = collections.OrderedDict(sorted(zip(index, map(sorted, index.values())))) Since that is a bit of an ugly line you can expand it out as. sorted_items = sorted(index.items()) sorted_items = [(k, sorted(v)) for k, v in sorted_items] sorted_index = collections.OrderedDict(sorted_items)
unknown
d7744
train
Its possible to use the config file as XML and then use XPath to change values: using (TransactionScope transactionScope = new TransactionScope()) { XmlDocument configFile = new XmlDocument(); configFile.Load("PathToConfigFile"); XPathNavigator fileNavigator = configFile.CreateNavigator(); // User recursive function to get to the correct node and set the value WriteValueToConfigFile(fileNavigator, pathToValue, newValue); configFile.Save("PathToConfigFile"); // Commit transaction transactionScope.Complete(); } private void WriteValueToConfigFile(XPathNavigator fileNavigator, string remainingPath, string newValue) { string[] splittedXPath = remainingPath.Split(new[] { '/' }, 2); if (splittedXPath.Length == 0 || String.IsNullOrEmpty(remainingPath)) { throw new Exception("Path incorrect."); } string xPathPart = splittedXPath[0]; XPathNavigator nodeNavigator = fileNavigator.SelectSingleNode(xPathPart); if (splittedXPath.Length > 1) { // Recursion WriteValueToConfigFile(nodeNavigator, splittedXPath[1], newValue); } else { nodeNavigator.SetValue(newValue ?? String.Empty); } } Possible path to Conf1: "configuration/applicationSettings/ExternalConfigReceiver.Properties.Settings/setting[name=\"Conf1\"]/value" A: as far as i know you cant use the System.Configuration.Configuration to access config files of other applications they are xml files and you can use the xml namspace to interact with them
unknown
d7745
train
The enctype of the form should be multipart/form-data A: You have errors in your html. You're missing closing tags for a tr and td tag. Also, close off your file upload input tag />. A: Some of your logic is off: if (!isset($_FILES[$upload_name])) will always pass. For every <input type="file"> in your form, there'll be a matching $_FILES entry, whether a file was actually uploaded or not. If no file was uploaded to being with, then you'll get error code 4. else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0) You don't have to check if the error parameter is set. as long as $upload_name has a valid file field name in it, the error section will be there. You can check for $_FILES[$upload_name], though. in case your variable's set wrong. You've commented it out, but you're checking for valid upload types by checking the user-provided filename. Remember that the ['type'] and ['name'] parameters in $_FILES are user-supplied and can be subverted. Nothing says a malicious user can't rename bad_virus.exe to cute_puppies.jpg and get through your 'validation' check. Always determine MIME type on the server, by using something like Fileinfo. That inspects the file's actual contents, not just the filename. So, your upload validation should look something like: if (isset($_FILES[$upload_name]) && ($_FILES[$upload_name]['error'] === UPLOAD_ERR_OK)) { $fi = finfo_open(FILE_INFO_MIME_TYPE); $mime = finfo_file($fi, $_FILES[$upload_name]['tmp_name']); if (!in_array($valid_mime_type, $mime)) { HandleError("Invalid file type $mime"); } etc... } else { HandleError($uploadErrors[$_FILES[$upload_name]['error']]); }
unknown
d7746
train
To use await in those callbacks, each callback function itself needs to be async: export default { methods: { submitToTheOthers(){ ⋮ return this.idxs.map( (_entry, i) => { return updateGeneralInfoToOther(1, data, this.serverFullAddress[i]).then(async (res) => { // [here2] ✅ await someAsyncMethod() if (res.status == 200) { ⋮ if (logoData.logo) { this.sendFileToOther(/*...*/).then(async (res) => { // [here] ✅ await someAsyncMethod() }) } if (logoData.logo1) { this.sendFileToOther(/*...*/).then(async (res) => { // [here] ✅ await someAsyncMethod() }) } } }) }) }, }, }
unknown
d7747
train
It was quite interesting that I have run about one week behind the inApp pending issue . And I got an answer from apple side that is when we deal the inapp purchase with the below code `for (SKPaymentTransaction * transaction in transactions) { switch (transaction.transactionState) { case SKPaymentTransactionStatePurchased: [self completeTransaction:transaction]; break; case SKPaymentTransactionStateFailed: [self failedTransaction:transaction]; break; case SKPaymentTransactionStateRestored: [self restoreTransaction:transaction]; case SKPaymentTransactionStateDeferred: [self DefferedTransaction:transaction]; break; case SKPaymentTransactionStatePurchasing: [self PurchasingTransaction:transaction]; break; default: break; } when a transaction is happen without any failure it will get SKPaymentTransactionStatePurchased state and we can proceed the applications process with success methods And no need to worry about the pending transaction apple consider this as success transaction and within 48 hours the amount will credit into the account.
unknown
d7748
train
Because the Count method is an extension method on IEnumerable<T> (Once you call Where, you don't have a list anymore, but an IEnumerable<T>). Extension methods don't work with dynamic types (at least in C#4.0). Dynamic lookup will not be able to find extension methods. Whether extension methods apply or not depends on the static context of the call (i.e. which using clauses occur), and this context information is not currently kept as part of the payload. Will the dynamic keyword in C#4 support extension methods? A: Extension methods are syntactic sugar that allow you to call a static method as if it was a real method. The compiler uses imported namespaces to resolve the correct extension method and that is information the runtime doesn't have. You can still use the extension methods, you just have to call them directly in their static method form like below. var aList = new List<string>{"a", "b", "c"}; dynamic a = aList.Where(item => item.StartsWith("a")); dynamic b = Enumerable.Count(a);
unknown
d7749
train
const ws = new WebSocket('URL goes here'); ws.onopen = () => { ws.send('ping') }; ws.onmessage = (data) => { console.log(data); } // this should be pong EDIT the script that you'll need, <script src="https://cdnjs.cloudflare.com/ajax/libs/web-socket-js/1.0.0/web_socket.min.js"></script>
unknown
d7750
train
No, just the references will be cleared. If no reference to an object exists anymore it might be garbage collected, but you'd get no NPE, since you then have no way to get a new reference to that object anyway. A: No, it will not delete objects in the ArrayList if you still have external references to them. ArrayList.clear() does nothing to the objects being referred to unless they are orphaned, in which case you won't be referring to them later on.
unknown
d7751
train
If you are accessing reports locally as file protocol, browser may have restriction to access local files. In such case follow the steps to allow local file access from file for the browser you are using. Firefox: go to about:config set security.fileuri.strict_origin_policy:false. Safari: Click on the Develop menu in the menu bar. Select Disable Local File Restrictions. If develop menu is not available, Click on the Edit > Preferences > Advanced tab. Check "Show Develop menu in the menu bar. chrome: Close down your Chrome browser (make sure you close all instances if you have multiple windows open) Go to Run and type the following command: chrome.exe --allow-file-access-from-file. Hit enter. Reference from local-report-access A: I just want to give more clarity by making little corrections to the existing steps mentioned here: https://github.com/infostretch/qaf-report#local-report-access When you are opening report "dashboard.htm" from local file system, your browser may have local file access restrictions. In that case, you can do following setings: * *Firefox: * *Enter "about:config" in the browser url field & click on the button "Accept the Risk & Continue". *In the "search preference name" field, enter "security.fileuri.strict_origin_policy" & click Enter & click on the toggle button towards the right to set it FALSE. *Safari: * *Click on the Develop menu in the menu bar. *Select Disable Local File Restrictions. If develop menu is not available, 1. Click on the Safari > Preferences > Advanced tab(in MAC, Safari > Preferences > Advanced tab). 2. Check "Show Develop menu in the menu bar. * *Chrome: *In Windows PC: * *Close down your Chrome browser (make sure you close all instances if you have multiple windows open) *Go to Run and type the following command: chrome.exe --allow-file-access-from-file. *In MAC * *Open your terminal anywhere, make sure Google Chrome is currently not running, copy paste this line and hit enter: open /Applications/Google\ Chrome.app --args --allow-file-access-from-files
unknown
d7752
train
In regards to the array being passed around I believe it is indeed a reference and there isn't any real downside to doing this from a performance perspective. It would be better to make the length available on Child Context that way you don't have to manually pass the props through a bunch of components that don't necessarily care. also it seems it would be more clear to pass only the length since the component doesn't care about the actual objects in the array. So in the component that holds the array the 5th level child cares about: var React = require('react'); var ChildWhoDoesntNeedProps = require('./firstChild'); var Parent = React.createClass({ childContextTypes: { arrayLen: React.PropTypes.number }, getChildContext: function () { return { arrayLen: this.state.theArray.length }; }, render: function () { return ( <div> <h1>Hello World</h1> <ChildWhoDoesntNeedProps /> </div> ); } }); module.exports = Parent; And then in the 5th level child, who is itself a child of ChildWhoDoesntNeedProps var React = require('react') var ArrayLengthReader = React.createClass({ contextTypes: { arrayLen: React.PropTypes.number.isRequired }, render: function () { return ( <div> The array length is: {this.context.arrayLen} </div> ); } }); module.exports = ArrayLengthReader; A: I don't see any problems with passing a big array as a props, even the Facebook is doing that in one of their tutorial about Flux. Since you're passing the data down to this many lever you should use react contex. Context allows children component to request some data to arrive from component that is located higher in the hierarchy. You should read this article about The Context, this will help you with your problem.
unknown
d7753
train
Put prompt to something you expect, as... prompt. Here is paramiko interaction example. Please note lines 21, and 37 - PROMPT = 'vagrant@paramiko-expect-dev:~\$\s+' interact.expect(PROMPT) So, when I've updated part of your code to: interact = SSHClientInteraction(client, timeout=10, display=True) interact.expect(PROMPT) interact.send("ls") interact.expect(".*Maildir.*") file.write(interact.current_output_clean) client.close() I have testlog.txt filled with listing of the home directory, of remote host. As a side note - switch to python 3. If you are starting, it is better to use tool that is not well known to be outdated soon. Also you can use ipython, or jupyter - code will be more interactive, faster to test. Maybe netmiko will be interested for you?
unknown
d7754
train
You need to use web socket for real time notification. You can try Ratchet or socket.io.
unknown
d7755
train
This is not recommended. It is generally considered bad practice to chop off the bottoms of bars. However, if you look at ?barplot, it has a ylim argument which can be combined with xpd = FALSE (which turns on "clipping") to chop off the bottom of the bars. barplot(mtcars$mpg, ylim = c(10, 30), xpd = FALSE) Also note that you should be careful here. I followed your question and used 0 and 30 as the y-bounds, but the maximum mpg is 33.9, so I also clipped the top of the 4 bars that have values > 30. The only way I know of to make a "split" in an axis is using plotrix. So, based on Specifically, I want to do this in base R program using only the barplot function and not functions from plotrix (unlike the suggests already provided). Is this possible? the answer is "no, this is not possible" in the sense that I think you mean. plotrix certainly does it, and it uses base R functions, so you could do it however they do it, but then you might as well use plotrix. You can plot on top of your barplot, perhaps a horizontal dashed line (like below) could help indicate that you're breaking the commonly accepted rules of what barplots should be: abline(h = 10.2, col = "white", lwd = 2, lty = 2) The resulting image is below: Edit: You could use segments to spoof an axis break, something like this: barplot(mtcars$mpg, ylim = c(10, 30), xpd = FALSE) xbase = -1.5 xoff = 0.5 ybase = c(10.3, 10.7) yoff = 0 segments(x0 = xbase - xoff, x1 = xbase + xoff, y0 = ybase-yoff, y1 = ybase + yoff, xpd = T, lwd = 2) abline(h = mean(ybase), lwd = 2, lty = 2, col = "white") As-is, this is pretty fragile, the xbase was adjusted by hand as it will depend on the range of your data. You could switch the barplot to xaxs = "i" and set xbase = 0 for more predictability, but why not just use plotrix which has already done all this work for you?! ggplot In comments you said you don't like the look of ggplot. This is easily customized, e.g.: library(ggplot2) ggplot(x, aes(y = mpg, x = id)) + geom_bar(stat = "identity", color = "black", fill = "gray80", width = 0.8) + theme_classic()
unknown
d7756
train
Maybe you need something like this. With a root node named "Credentials" private void CreateXml() { var document = new XmlDocument(); XmlNode rootNode = document.CreateElement("Credentials"); document.AppendChild(rootNode); rootNode.AppendChild(document.CreateElement("EncryptionKey")); rootNode.AppendChild(document.CreateElement("SaltKey")); rootNode.AppendChild(document.CreateElement("VIKey")); rootNode.AppendChild(document.CreateElement("EmailUsername")); rootNode.AppendChild(document.CreateElement("EmailPassword")); XmlNode declaration = document.CreateXmlDeclaration("1.0", "UTF-8", null); document.InsertBefore(declaration, rootNode); document.Save("Credentials.xml"); } EDIT: Added declaration
unknown
d7757
train
Use that, it should work: Word.Application WordApp; Word.Document WordDoc; object misValue = System.Reflection.Missing.Value; WordApp = new Word.ApplicationClass(); WordDoc = WordApp.Documents.Open(filePath2, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue); WordDoc.Activate(); A: You should use: doc = Word.Documents.Add(filename); Instead of: doc = Word.Documents.Open(filename); So Word will use the template to create a document file, and not open the template itself. It seems Word behaves differently when the active document is a Template.
unknown
d7758
train
Is the main if code block that needs to be closed with a } <html> <head> <title><?php echo $firstname; ?> <?php echo $lastname; ?>'s Profile</title> </head> <body> <?php if (isset($_GET['username'])){ $username = $_GET['username']; mysql_connect("localhost","root", "") or die ("Could not connect to the server"); mysql_select_db("users") or die ("That database could not be found."); $userquery = mysql_query("SELECT * FROM users WHERE username='$username'") or die ("The query could not be completed, please try again later."); if(mysql_num_rows($userquery) !=1){ die ("That user could not be found."); } while($row = mysql_fetch_array($userquery, MYSQL_ASSOC)) { $firstname = $row['firstname']; $lastname = $row['lastname']; $email = $row['email']; $dbusername = $row['dbusername']; $access = $row['access']; } if($username != $dbusername){ die ("There has been a fatal error, please try again."); } if($access == 1) { $access = "Level 1 User"; } else if($access == 2) { $access = "Level 2 User"; } else if($access == 3) { $access = "Level 3 User"; } else if($access == 4) { $access = "Administrator."; } else die ("This user has an access level beyond the realms of possibility. Beware."); }//THIS IS WHAT IS MISSING ?> <h2><?php echo $firstname; ?> <?php echo $lastname; ?>'s Profile</h2><br /> <table> <tr><td>Firstname:</td><td><?php echo $firstname; ?></td></tr> <tr><td>Lastname:</td><td><?php echo $lastname; ?></td></tr> <tr><td>email:</td><td><?php echo $email; ?></td></tr> <tr><td>dbusername:</td><td><?php echo $dbusername; ?></td></tr> <tr><td>access:</td><td><?php echo $access; ?></td></tr> </table> </body> </html>
unknown
d7759
train
Unfortunately enum by default doesn't create an enum namespace. So when declaring: enum PlayerType { FORWARD, DEFENSEMAN, GOALIE }; you'll have to use it like this: auto x = FORWARD; Thankfully, though, C++11 introduced enum class or enum struct to solve this issue: enum class PlayerType { FORWARD, DEFENSEMAN, GOALIE }; You'll then be able to access it like you did: auto x = PlayerType::FORWARD; A: enum doesn´t create a namespace. Therefor PlayerType t = PlayerType::FORWARD; should be changed to: PlayerType t = FORWARD; Notice that c++11 introduce enum classes, which have a namespace. Beside this MSVC has an extension which treats (regular) enums like they have namespace. So your code should actually work with MSVC. A: Your error seems to be in this line: PlayerType t = PlayerType::FORWARD; As far as I know, the scope resolution operator (::) is not valid on regular C++98 enums unless your compiler supports them through non-standard extensions (like Visual Studio). Therefore you can't use it to reference an specific value from the enumerator. Also, C++98 enums have the problem of polluting the namespace in which they are defined which can lead to name clash. Luckily C++11 solved this introducing the enum class. For more information check Stroustrup's FAQ: http://www.stroustrup.com/C++11FAQ.html#enum A: add a static function say getForward: class Player { public: Player(); void setType(PlayerType); static PlayerType getForward { return FORWARD; } private: PlayerType type; }; Then use it in main: manager.createPlayer(player, Player::getForward()); This should work.
unknown
d7760
train
Checking timestamp (or something very similar) is the only way you can do it with a generic the FTP protocol API. Your particular FTP server may have better API for that, but we do not know anything about your FTP server.
unknown
d7761
train
Yes, they should have the same password.
unknown
d7762
train
Since you're using fetch to make the request, the response is encapsulated in the Response object, and to access it you have to call the async method json(). Just like the following: const Response = await fetch(apiUrl + '/recipes', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Token token=${user.token}` }, body: JSON.stringify({ recipe: { recipeId: uri } }) }); const json = await Response.json(); console.log(json); You can play with another example in your chrome console. (async () => { const Response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const res = await Response.json(); console.log(res); })(); UPDATE Another way to do that is: (async () => { const response = await ( await fetch('https://jsonplaceholder.typicode.com/todos/1') ).json(); console.log(response); })(); I hope this helps.
unknown
d7763
train
Note that you could change your repo settings to pick up your pages from a docs folder in the master branch: that could be easier to maintain. But regarding gh-pages, check if one of the answers mentioned in "How to fix page 404 on Github Page?" applies, in particular regarding the case of the files (lower/upercase)
unknown
d7764
train
You can try using "alias", try this link http://www.cyberciti.biz/tips/bash-aliases-mac-centos-linux-unix.html
unknown
d7765
train
For some reason you can't enable or disable the full text index from that screen. Instead you have to right-click the table in Object Explorer, then choose Full-Text index > Enable Full-Text index.
unknown
d7766
train
Just wanted to add some coment over the previous answers. The contract of equals mentions that it must be symmetric. This means that a.equals(b) iff b.equals(a). That's the reason why instanceof is usually not used in equals (unless the class is final). Indeed, if some subclass of Book (ComicsBook for example) overrides equals to test that the other object is also an instance of ComicsBook, you'll be in a situation where a Book instance is equal to a ComicsBook instance, but a ComicsBook instance is not equal to a Book instance. You should thus (except when the class is final or in some other rare cases) rather compare the classes of the two objects: if (this.getClass() != o.getClass()) { return false; } BTW, that's what Eclipse does when it generates hashCode and equals methods. A: Don't do this: if(o.getID() == ID) ID is an Integer object, not a primitive. Comparing two different but equal Integer objects using == will return false. Use this: if(o.getID().equals(ID)) You'd also need to check for ID being null. Other than that, your logic is fine - you're sticking with the contract that says two equal objects must have the same hashcode, and you've made the business logic decision as to what equality means -a decision that only you can make (there's no one correct answer). A: If you use Hibernate then you have to consider some Hibernate related concerns. Hibernate create Proxies for Lazy Loading. * *always use getter to access the properties of the other object (you already done that) *even if it is correct to use if (!this.getClass().equals(o.getClass())) { return false;} in a normal Application it WILL fail for hibernate Proxy (and all other proxies). The reason is if one of the two is a proxy, there classes will never be equals. So the test if(!(o instanceof Book)){return false;} is what you need. If you want to do it in the symmetric way than have a look at org.hibernate.proxy.HibernateProxyHelper.getClassWithoutInitializingProxy() with help of this class you can implement: if (!HibernateProxyHelper.getClassWithoutInitializingProxy(this) .equals(HibernateProxyHelper.getClassWithoutInitializingProxy(o))) { return false; } * *An other problem maybe is the ID -- when you assign the id not with the creation of an new object but later on while storing them, then you can run into trouble. Assume this scenario: You create a new Book with id 0, then put the Book in a HashSet (it will assigned to an bucket in the hashset depending on the hashcode), later on you store the Book in the Database and the id is set to lets say 1. But this changes the hashcode, and you will have problems to find the entity in the set again. -- If this is a problem or not for you, strongly depends on your application, architecture and how you use hibernate. A: It is no good idea to compare the two Integers like if(o.getID() == ID) ... This tests for identity. What you want is a test for equality: if(ID!=null && ID.equals(o.getID())) ... A: Just a note: Your equals method public boolean equals(Object o) { if(o == null) { return false; } if(!(o instanceof Book)) { return false; } Book other = (Book)o; if(other.getID() == ID) { return true; } return false; } can be (equivalently) shorter written like this: public boolean equals(Object o) { return (o instanceof Book) && ((Book)o).getID == ID; } Other than this, if your IDs are all different for different books (and same for same books), this is a good implementation. (But note JB Nizet's remark: To make sure this stays symmetric, make equals (or the whole class) final.) A: that depends ! i think this kind of implementation is ok, if you can handle the condition below, you new two books, these two books have the same title, they are same book in fact, but you don't save them into database, so these two books don't have ids yet, the equals will fall when you compare them
unknown
d7767
train
Check your storyboard, the view inside your ViewController should be SKView instead of UIView.
unknown
d7768
train
From the looks of it, an "UML-XMI" is still an XML document, but as mentioned in the comments, it is not well-formed. The issue is with this node element <node xmi:type="uml:OpaqueAction" xmi:id="_ZfIhYC9-EeWyX7UKkcyxiw" name="Load and Enable Timer" visibility="package" outgoing="_lieXcC9-EeWyX7UKkcyxiw" incoming="_jzMLIC9-EeWyX7UKkcyxiw"/> <inputValue xmi:type="uml:ActionInputPin" xmi:id="_82lIMDRBEeWdiarL2UAMaQ" name="interrupt"> <upperBound xmi:type="uml:LiteralInteger" xmi:id="_82lIMTRBEeWdiarL2UAMaQ" value="1"/> </inputValue> </node> If you scroll to the right, the node tag is self-closed (i.e, it ends with />), this means the closing </node> tag doesn't actually match anything. But assuming it was well-formed, the first issue with your XSLT is with namespaces. In your XML the namespace is defined like this: xmlns:uml="http://www.eclipse.org/uml2/4.0.0/UML" But in your XSLT you have defined it like this xmlns:UML="org.omg.xmi.namespace.UML" The prefix don't have to match between XML and XSLT, but the namespace URI does. Additionally, if your XSLT when you use the namespace prefix, you are using it in lower-case <xsl:template match="/uml:Model/packagedElement/edge/"> It is case-sensitive though, so uml won't correspond to the UML which you have defined. The prefix doesn't need to match the XML, but it does need to match the one defined in the XSLT. Additionally, that template match is also not syntactically correct because it ends with an / symbol. That needs to be removed. Although I am not quite clear what output you actually want, try this XSLT to get you on your way: <xsl:stylesheet version="1.0" xmlns:UML="http://www.eclipse.org/uml2/4.0.0/UML" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns='uri:sadf' exclude-result-prefixes="UML"> <xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" /> <xsl:template match="/UML:Model"> <sdf3 xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='some_random_location' type='sadf'> <sadf name='RandomGraphName'> <xsl:apply-templates /> </sadf> </sdf3> </xsl:template> <xsl:template match="packagedElement"> <structure> <xsl:apply-templates select="edge" /> </structure> </xsl:template> <xsl:template match="edge"> <edge name="{@name}" source="{@source}" /> </xsl:template> </xsl:stylesheet> Note the use of a default namespace in the XSLT xmlns='uri:sadf'. This means all elements, which don't have a namespace, will be output in that namespace. Also note, you don't necessarily need to code the full path to child elements such as packagedElement and edge. But given the following well-formed input: <uml:Model xmi:version="20110701" xmlns:xmi="http://www.omg.org/spec/XMI/20110701" xmlns:uml="http://www.eclipse.org/uml2/4.0.0/UML" xmi:id="_OlYJkC9-EeWyX7UKkcyxiw" name="model"> <packagedElement xmi:type="uml:Activity" xmi:id="_OlYJkS9-EeWyX7UKkcyxiw" name="Activity1" node="_XjLyEC9-EeWyX7UKkcyxiw _ZfIhYC9-EeWyX7UKkcyxiw _cK4V8C9-EeWyX7UKkcyxiw _fE2zwC9-EeWyX7UKkcyxiw _F67sgC9_EeWyX7UKkcyxiw"> <edge xmi:type="uml:ControlFlow" xmi:id="_jzMLIC9-EeWyX7UKkcyxiw" name="ControlFlow" source="_XjLyEC9-EeWyX7UKkcyxiw" target="_ZfIhYC9-EeWyX7UKkcyxiw"/> <edge xmi:type="uml:ControlFlow" xmi:id="_lieXcC9-EeWyX7UKkcyxiw" name="ControlFlow1" source="_ZfIhYC9-EeWyX7UKkcyxiw" target="_cK4V8C9-EeWyX7UKkcyxiw"/> <node xmi:type="uml:InitialNode" xmi:id="_XjLyEC9-EeWyX7UKkcyxiw" name="Start" outgoing="_jzMLIC9-EeWyX7UKkcyxiw"/> <node xmi:type="uml:OpaqueAction" xmi:id="_ZfIhYC9-EeWyX7UKkcyxiw" name="Load and Enable Timer" visibility="package" outgoing="_lieXcC9-EeWyX7UKkcyxiw" incoming="_jzMLIC9-EeWyX7UKkcyxiw"> <inputValue xmi:type="uml:ActionInputPin" xmi:id="_82lIMDRBEeWdiarL2UAMaQ" name="interrupt"> <upperBound xmi:type="uml:LiteralInteger" xmi:id="_82lIMTRBEeWdiarL2UAMaQ" value="1"/> </inputValue> </node> <node xmi:type="uml:ActivityFinalNode" xmi:id="_F67sgC9_EeWyX7UKkcyxiw" name="ActivityFinalNode" incoming="_Hcj3UC9_EeWyX7UKkcyxiw"/> </packagedElement> </uml:Model> The following is output <sdf3 xmlns="uri:sadf" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="some_random_location" type="sadf"> <sadf name="RandomGraphName"> <structure> <edge name="ControlFlow" source="_XjLyEC9-EeWyX7UKkcyxiw"/> <edge name="ControlFlow1" source="_ZfIhYC9-EeWyX7UKkcyxiw"/> </structure> </sadf> </sdf3>
unknown
d7769
train
* *first error message (original posted question) SSO_SERVER needs a slash at the end: SSO_SERVER='http://127.0.0.1:8000/server/' *subsequent error message (from comment below): Root cause is the coexistance of server and client in one app. when you request /client/ there will be a request to get a token: (see https://github.com/divio/django-simple-sso/blob/master/simple_sso/sso_client/client.py) class LoginView(View): ... def get(self, request): ... request_token = self.client.get_request_token(redirect_to) ... which will built an url from SSO_SERVER='http://127.0.0.1:8000/server/' + reverse('simple-sso-request-token') because you have the server in your server urls, reverse('simple-sso-request-token') returns "/server/request-token/" Together you get http://127.0.0.1:8000/server/server/request-token/ I am not sure if the path name "simple-sso-request-token" is needed somewhere else - if not, you could just "overwrite" it by adding a line with a dummy view to the urls.py just to make the reverse result change: urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), re_path(r'^server/', include(test_server.get_urls())), re_path(r'^client/', include(test_client.get_urls())), path("request-token/", some_dummy_view , name='simple-sso-request-token'), # this is only to force reverse("simple-sso-request-token") to return "request-token/" ] (reverse() returns the last path in the urlpatterns list) This will lead to http://127.0.0.1:8000/server/request-token/ hope there is no further error messages
unknown
d7770
train
This can be easily handled with schema evaluation with delta format. Quick ref: https://databricks.com/blog/2019/09/24/diving-into-delta-lake-schema-enforcement-evolution.html
unknown
d7771
train
It basically looks like the three.js ColladaLoader simply does not support material animations (it only supports position and rotation animations). I determined this by looking at raw data structure returned by the collada loader. Note how Object 0, which corresponds to the position animation has sids (string ids) and keys etc. Object 1, which corresponds to the material animation, has no sids or keys. While the material animation data is in the raw collada file, the ColladaLoader parser is simply not reading it, thus no color animations. Apparently, the Collada loader is "kind of deprecated" per mrdoob (as of 5/2016). There is a ColladaLoader2, which is supposed to be the next version of the ColladaLoader, but I tried that and it appears to not support any animations at all. I've been reading up on the collada loader and indeed it is an aging format and basically looks likes it's a dead end as far as future growth goes (?) Unfortunately, I've tried the obj, json, and stl loaders and the collada loader is by far the best. I'm currently investigating the gltf format, which basically seems like the next generation of collada (e.g the new and improved version also from the Khronos group). I found this discussion very useful. Basically, a couple of years ago there was a three.js user who wrote his own ColladaLoader, but he has since abandoned Collada and now backs glTF. Update: I tried the GLTFLoader and GLTF2Loader loaders, but unfortunately they are failing on a semi-complex scene (a scene with 20 objects and 310 faces). It looks like a promising format though. I just think that between a test exporter and test loaders, it's just not quite stable at the moment. I was almost able to get animation working with the format (not material animation though) when I tested with a simple cube. Looks like I'll have to stay with Collada for now and just do material animations in javascript.
unknown
d7772
train
Check out this seminar registration demo form on css-tricks. It looks like it could solve your problem with a little tweaking. Here is the source. A: For: <input name='email' type='email' id='email'> and <div id='somediv'></div> This is some untested code: $('#email').on( 'change', function() { if( email_regex_must_be_here ) { //this is a valid email $('#somediv').show(); } else { $('#somediv').hide(); } } ); Harry's link might be better at helping you though.
unknown
d7773
train
The ANSI compliant way to write the query is: UPDATE TABLE_A SET Y = 2 WHERE b.Z = blahblah AND EXISTS (SELECT 1 FROM TABLE_B b WHERE TABLE_A.X = b.X); To the best of my knowledge, neither ANSI nor ISO provide rationales for why they do not do something. I could speculate that the FROM clause causes issues when there are multiple matches on a given row. Personally, I would not want to be in the room during the arguments about which order the updates take place.
unknown
d7774
train
Hi you can use those instructions : df['name'] = df['Names'].mask(df['Subject Grade'] != "Student Name") df['name'] = df['name'].fillna(method='ffill') df = df.query('`Subject Grade`!="Student Name"') df = df.rename(columns={'Names':'Subject', 'Subject Grade':'Grade', 'name':'Names'})
unknown
d7775
train
script.sh & sleep 4h && kill $! script.sql This will wait 4 hours then kill the first script and run the second. It always waits 4 hours, even if the script exits early. If you want to move on immediately, that's a little trickier. script.sh & pid=$! sleep 4h && kill "$pid" 2> /dev/null & wait "$pid"
unknown
d7776
train
Appending is much efficient, as the system is aware of the position. Whole file rewriting will take more time. Go with appending,
unknown
d7777
train
You may use table aliases here: SELECT ticket_id, number AS `ticket number`, (SELECT COUNT(*) FROM ost_thread_entry ote INNER JOIN ost_thread ot ON ote.thread_id = ot.id WHERE ot.object_id = t.ticket_id) AS `number of posts in ticket` FROM ost_ticket t; Note that you might also be able to write your query without the correlated subquery, instead using joins: SELECT t.ticket_id, t.number AS `ticket number`, COUNT(ote.thread_id) AS `number of posts in ticket` FROM ost_ticket t LEFT JOIN ost_thread ot ON ot.object_id = t.ticket_id LEFT JOIN ost_thread_entry ote ON ote.thread_id = ot.id GROUP BY t.ticket_id, t.number;
unknown
d7778
train
THREE.PerspectiveCamera has near and far parameters. These define the distance of the near and far clipping plane. You have to choose clipping planes depending on your scene. For example if you have a large scene, and the near plane is very small, it can cause things you experienced.
unknown
d7779
train
You cannot store a variable like that. Each request will be new execution in sever. In this kind situation we have to use session please check this And another issue with your code is SQL injection, Please read this too A: You can not access the Parameter received at checklogin.php what you can do you can check the the login status and set the current user in session. From session variable you can access and set the current user. A: you can set a session variable for it and on every you can use it like this session_start(); if(isset($_SESSION['current_user_name'])) { $current_user_name = $_SESSION['current_user_name']; } else { $current_user_name = NULL; } and set your session variable as follows session_start(); require_once '/checklogin.php'; ////... mysql_query("INSERT INTO " . tbl_name . " (username, userpassword, userisadmin) VALUES (''" . $_POST['myusername'] . "'," . "'" . md5($_POST['mypassword']). "'," . "0)"); $current_user_name = $_POST['myusername']; $_SESSION['current_user_name'] = $current_user_name; // set your session here header("location:login_success.php");
unknown
d7780
train
The reason why the worst case run time is O(n) is that if you have a careful look at the code, you realize that you visit each array index at most once: observe that index i only increases at size, and index j only decrease, therefore you'll go at most once over each index. For example, if you have an array a[] of size 10, then the initial index i will be 0, and j will be 9. x will be (randlomly) somewhere in between, let's say x=4. Then, the outer while loop enters, and the first inner while loop increases index i until a[i] >= a[x]. The second inner while loop does the same to index j, for the opposite direction. But the sum of total iterations of both inner loops is at most 10. At which point the next outer while loop check will return false and no second iteration will occur. A: Lets start with this: our teacher taught us that we have to multiply the costs whenever we have nested statements which would result in a (n/2+1)*((n/2)+1)+((n/2)+1)) which is clearly n^2 and not O(n) This is only true if the looping variables in inner and outer loops are independent of each other. eg. for i in range(1..10): for j in range(1..10): do something This is because, for every value of i, inner loop iterates for all values of j. So, this is O(n^2). Now, lets look the other example: for i in range(1..10): for i in range(1..10): do something In this case, the outer loop runs only once as when inner loop exits, condition for outer loop also discontinues. So, this is, O(n). Now, lets look at your while loops. The outer condition is while i is less than j. Inside, we are always incrementing i and decreasing j. So, in this case, the total number of times while statements (all 3) are executed will be the upper bound on i + j, which is 2n. So, complexity is O(2n) or, O(n). EDIT: I am making this edit to explain what "complexity" means, practically. It is a way of approximating/calculating, number of iterations that are made in total, all loops and instructions combined, as size of input increases. So, if you really want to know that, just assign a variable, say a and add 1 to a as the 1st line of every loop. Then print a for different input sizes and you will know what O() notation means, theoretically vs practically.
unknown
d7781
train
we just have to enable the CORS in safari-mac browser. So, we'll do it by modifying our function screenshot() as follows: function screenshot(){ html2canvas(document.getElementById('id-screenshot'),{ allowTaint: true, useCORS : true, }).then(function(canvas) { console.log("canvas: " + canvas); document.getElementById('test-s').appendChild(canvas); }); }
unknown
d7782
train
You can use the Three20 photo viewer. You can look at this tutorial for help on using it. There is also a WWDC video from last year which gives you an idea on how this can be implemented. There are other tools that you can look into. Cocoa Controls has a fairly exhaustive list of tools that you can use for your projects. A: At the most basic level, a UIScrollView with paging enabled will work fine for swiping to get to the next image. You'll probably need to be more specific than that.
unknown
d7783
train
I can see no issue with such configuration. Please have a look at the documentation Networks and subnets: Each VPC network consists of one or more useful IP range partitions called subnets. Each subnet is associated with a region. and A network must have at least one subnet before you can use it. Auto mode VPC networks create subnets in each region automatically. Custom mode VPC networks start with no subnets, giving you full control over subnet creation. You can create more than one subnet per region. So, accordingly to the documentation, it's possible to have a network test-network with two subnets subnet-a and subnet-b both in same region us-central1, for example: $ gcloud compute networks create test-network --subnet-mode=custom --mtu=1460 --bgp-routing-mode=regional $ gcloud compute networks subnets create subnet-a --range=10.0.1.0/24 --network=test-network --region=us-central1 $ gcloud compute networks subnets create subnet-b --range=10.0.2.0/24 --network=test-network --region=us-central1 $ gcloud compute networks list NAME SUBNET_MODE BGP_ROUTING_MODE IPV4_RANGE GATEWAY_IPV4 test-network CUSTOM REGIONAL $ gcloud compute networks subnets list NAME REGION NETWORK RANGE subnet-a us-central1 test-network 10.0.1.0/24 subnet-b us-central1 test-network 10.0.2.0/24 In addition have a look at the documentation section Communication within the network: Except for the default network, you must explicitly create higher priority ingress firewall rules to allow instances to communicate with one another. The default network includes several firewall rules in addition to the implied ones, including the default-allow-internal rule, which permits instance-to-instance communication within the network. The default network also comes with ingress rules allowing protocols such as RDP and SSH. Please update your question if you have other doubts.
unknown
d7784
train
A,A2,C:C,">"&C2) B is the Type column, A is the Reference column, and C is the Doc Condition column. So the count is only greater than zero if the Type is 'BD', the Reference Matches the current row's Reference, and the Doc Condition is greater than the current row's Doc Condition. I hope that makes sense? I've tried coming to a solution using GroupBy but I'm not getting any closer to my desired solution and I think I'm overcomplicating this. A: You should include your input data as text. Screenshots are really hard to work with. You can use numpy broadcasting. However, this will have an n^2 computational complexity since you are comparing every row against every other row: reference, type_, doc_condition = df.to_numpy().T match = ( (type_[:, None] == "BD") & (reference[:, None] == reference) & (doc_condition[:, None] < doc_condition) ) df["COUNTIFS"] = match.sum(axis=1) Within the snippet above, you can read reference[:, None] as "the Reference value of the current row; reference as "the Reference values of all rows". This is what enables the comparison between the current row and all other rows (including itself) by numpy.
unknown
d7785
train
You missed to add <router-view/> add it on your app.vue file after the nav section. Example: <div class="nav"> <router-link to="/" class="nav-item">HOME</router-link> <router-link to="/aboutme" class="nav-item">ABOUT ME</router-link> </div> <router-view/>
unknown
d7786
train
In your current code, you are first assigning cat_files to the file name, but then in this line: cat_files = open(cat_files, 'r') You are now assigning cat_files to a file handle, which is not a string. This is why the next statement fails: it is expecting the filename string, not the file handle. You should use a different variable name for the handle, e.g.: #opens catnames file to append end and add names. f = open(cat_files, 'a') f.write('Princess\nFreya\n') f.close() f = open(cat_files, 'r') f = f.read() print(f) f.close()
unknown
d7787
train
You will need to use android:fillViewport <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" > See this blog page written by Romain Guy.
unknown
d7788
train
First, this is not valid: <source node id="{generate-id()}"/> the attribute node must have a value. To answer your question, I would use the generate-id and position() functions on the target element to get a unique id. Something like this. Since I dont have a good input document, I created a sample: <data> <Element type="node" id="Node-a" name="a"/> <Element type="node" id="Node-b" name="b"/> <Element type="node" id="Node-c" name="c"/> </data> XSLT: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"> <xsl:output method="html" indent="yes"/> <xsl:template match="/"> <xsl:for-each select="data"> <xsl:copy> <xsl:apply-templates/> </xsl:copy> </xsl:for-each> </xsl:template> <xsl:template match="Element"> <xsl:element name="source"> <xsl:attribute name="node"> <xsl:value-of select="@type"/> </xsl:attribute> <xsl:attribute name="id"> <xsl:value-of select="generate-id(.)"/> </xsl:attribute> </xsl:element> <xsl:element name="target"> <xsl:attribute name="node"> <xsl:value-of select="@type"/> </xsl:attribute> <xsl:attribute name="id"> <xsl:value-of select="concat(generate-id(.), '-', position())"/> </xsl:attribute> </xsl:element> </xsl:template> </xsl:stylesheet>
unknown
d7789
train
I just learned from that the simultaneous allocation of multiple slaves can be done nicely in a pipeline job, by nesting node clauses: node('label1') { node('label2') { // your code here [...] } } See this question where Mateusz suggested that solution for a similar problem. A: Let me see if I understood the problem. * *You want to have dynamically choose a slave and start the App Server on it. *When the App server is running on a Slave you do not want it to run any other job. *But when the App server is not running, you want to use that Slave as any other Slave for other jobs. One way out will be to label the Slaves. And use "Restrict where this project can be run" to make the App Server and the Test Suite run on the machines with Slave label. Then in the slave nodes, put " # of executors" to 1. This will make sure that at anytime only one Job will run. Next step will be to create a job to start the App Server and then kick off the Test job once the App Server start job is successful.. If your test job needs to know the server details of the machine where your App server is running then it becomes interesting.
unknown
d7790
train
Your problem The .order-* classes are limited at 5. It's in the documentation: Includes support for 1 through 5 across all six grid tiers. If you need more .order-* classes, you can modify the default number via Sass variable. And .order-6 is equal to order: last. Easy solution Add your own CSS classes. @media (min-width: 768px) { .order-md-6 { order: 6; } .order-md-7 { order: 7; } .order-md-8 { order: 8; } .order-md-9 { order: 9; } .order-md-10 { order: 10; } } <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> <div class="container"> <div class="row"> <div class="col-md-6 order-md-1"> img </div> <div class="col-md-6 order-md-2"> text </div> <div class="col-md-6 order-md-4"> img </div> <div class="col-md-6 order-md-3"> text </div> <div class="col-md-6 order-md-5"> img </div> <div class="col-md-6 order-md-6"> text </div> <div class="col-md-6 order-md-8"> img </div> <div class="col-md-6 order-md-7"> text </div> <div class="col-md-6 order-md-9"> img </div> <div class="col-md-6 order-md-10"> text </div> </div> </div> Alternative solution Overwrite the Sass. It can be found in the _utilities.scss. Here it is in Github. If you don't know how to do this, there are many tutorials to get you started, even here on SO.
unknown
d7791
train
Issue : When you are trying to get the Status of the Row/Record by using Parent method of the jQuery, then it is not actually getting the correct element where you can find the status. Solution : Change the following line of code var status = $(e).parent().parent().find('.label-status').text(); to var status = $(e).closest('.AddreqTableCols').find('.label-status').text(); A: i guess this is what you are trying to do, if its not clear enough what is happening, feel free to ask. $("#selectall").click(function (e) { var $this = $(this); $("#tablecontent [type='checkbox']").prop("checked", $this.is(":checked")); }); $("#deletebtn").click(function (e) { if (!confirm("Are you sure you want to delete?")) return; var $checked = $("#tablecontent [type='checkbox']:checked"); var ids = $.map($checked, function (chk) { return $(chk).attr("id"); }); console.log(ids); alert(ids.join(",")); }); http://jsfiddle.net/cdkLkcdk/48/ COMMENT If i was assigned to write the same thing, i would set the status as a data-status on the checkbox itself to make things easier. A: The problem is that status is always empty. When you select a filterstatus it comes in the new if check and status == $('#filterstatus').val() will always be false since status is empty. Change your code to: var status = $(e).parent().parent().parent().find('.label-status').text(); You forgot an extra .parent(). Note: You can always use console.log() to test if your variables are filled in correctly.
unknown
d7792
train
You can define to_csv function on user model like this. def self.to_csv(users, options = {}) header_columns = [ "Email", "First Name", "Last Name" ] CSV.generate(options) do |csv| csv << header_columns users.each do |user| row = [ user.email, user.first_name, user.last_name ] csv << row end end end And call it like this. User.to_csv(@company.users) A: require "csv" dont forget to include the module @company.users.to_a.to_csv
unknown
d7793
train
// this will return true if your int contains the pattern bool intContains(myInt,pattern){ return myInt.toString().contains(pattern.toString()); }
unknown
d7794
train
I guess it has now changed to pandas.plotting.scatter_matrix Have a look at the document below. https://pandas.pydata.org/docs/reference/api/pandas.plotting.scatter_matrix.html
unknown
d7795
train
pip install -U pyasn1 please try to upgrade pyasn1 version
unknown
d7796
train
Why not place these scripts in App_data? It will be deployed along with the rest of the website, and cannot be accessed via client web browsers. That's what it is there for, to store data associated with your website that you don't want to have in the root for security purposes. A: You can include an extra folder for deployment with all its contents editing the publish profile: http://www.asp.net/mvc/tutorials/deployment/visual-studio-web-deployment/deploying-extra-files
unknown
d7797
train
David is going the right direction, such a protocol doesn't exist (simd is from C and C doesn't have protocols, no surprise), but you can just declare one yourself. To make it so you can use +-*/, you have to add them to the protocol: import simd protocol ArithmeticType { func +(lhs: Self, rhs: Self) -> Self func -(lhs: Self, rhs: Self) -> Self func *(lhs: Self, rhs: Self) -> Self func /(lhs: Self, rhs: Self) -> Self } extension float4 : ArithmeticType {} extension float3 : ArithmeticType {} extension float2 : ArithmeticType {} func sum<T: ArithmeticType>(a: T, b: T) -> T { return a + b } You can also extend Double, Float, Int, etc. if you need to A: If there isn't (and there doesn't appear to be), it's easy enough to add your own: protocol SimdFloat {} extension float2 : SimdFloat {} extension float3 : SimdFloat {} extension float4 : SimdFloat {} This doesn't really directly solve your problem, however as it doesn't declare that two SimdFloat's implement +.
unknown
d7798
train
Dictionary lookups return optionals because the key might not exist. You need to unwrap each of the lookups since they are type SKTexture!: runLeft = SKAction.animateWithTextures([states["left1"]!, states["left2"]!, states["left1"]!, states["left3"]!], timePerFrame: 0.1) runRight = SKAction.animateWithTextures([states["right1"]!, states["right2"]!, states["right1"]!, states["right3"]!], timePerFrame: 0.1)
unknown
d7799
train
We may need replicate(4, sample(X, size = 6)) Or replicate(6, sample(X, size = 4)) A: Another base R solution. set.seed(123) X <- c(4,10,15,100,50,31,311,225,85,91) dat <- as.data.frame(lapply(1:4, function(i) sample(X, size = 6))) %>% setNames(paste0("V", 1:4)) dat # V1 V2 V3 V4 # 1 15 50 50 85 # 2 91 100 15 15 # 3 10 31 85 225 # 4 225 225 4 10 # 5 31 4 100 311 # 6 85 10 311 4
unknown
d7800
train
The mapping of inner objects is made with association tag. You need something like this: <resultMap id="resmap" type="A"> <result property="a" column="a"/> <association property="b" javaType="B"> <result property="b" column="b"/> <result property="c" column="c"/> </association> </resultMap> Check documentation as well, it's explained in details.
unknown