_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d1101
train
For historical reasons, the AltGr (right Alt) key used in non-US keyboard layouts is automatically converted by the operating system as Ctrl + Alt (see Wikipedia about this). So this is not specifically related to SWT. To avoid this problem users should just use the standard Alt (left Alt) key. A: Have you tried disabling shortcut to change language in windows 10.
unknown
d1102
train
You can use this code to generate your desire sequence in order. function generateCandidates(input) { let candidates = []; //associate pointers for each word let words = input.split(" ").map(str => {return {str, ptr:1}}); //First candidate let candidate = words.map(({str,ptr}) => str.substr(0,ptr)).join(""); candidates.push(candidate); //find the first pointer that is still less than the length of the word let word; while( word = words.find(({str,ptr}) => ptr < str.length ) ) { word.ptr++; //increment the pointer candidate = words.map(({str,ptr}) => str.substr(0,ptr)).join(""); candidates.push(candidate); } return candidates; } console.log(generateCandidates("ABC")); console.log(generateCandidates("ABC DEF")); console.log(generateCandidates("ABC DEF GHI")); console.log(generateCandidates("ABC DEF GHI JKL"));
unknown
d1103
train
Last line must be: Data::Table::Excel::tables2xls("results.xls", [$t] ,["Sheet name for your Table"]); And here is colors example like you want: Data::Table::Excel::tables2xls("results.xls", [$t] ,["Sheet name for your Table"], [["white","silver","gray"]]);
unknown
d1104
train
Use a second loop (remove the word echo when you are happy): for i in {1..10}; do for j in {1..100}; do (( dir = 100 * (i - 1) + j )) echo cp -r *_$((dir)) Destination_folder${i}/ done done
unknown
d1105
train
I'm not sure that got the point, but try. Public Sub CheckPrKey() lastRow = Worksheets("ETM_ACS2").Range("A" & Rows.Count).End(xlUp).Row lastRowdashboard = Worksheets("dashboard").Range("B" & Rows.Count).End(xlUp).Row With Worksheets("ETM_ACS2") For r = 2 To lastRow If .Range("I" & r).Value = "Y" If .Range("N" & r).Value < "100" Then Worksheets("dashboard").Range("A" & lastRowdashboard + 1)=.Range("D" & r) Worksheets("dashboard").Range("B" & lastRowdashboard + 1)=.Range("N" & r) lastRowdashboard = lastRowdashboard +1 End if End If Next r End With End Sub
unknown
d1106
train
try this $this->db->select('statistik.domain,statistik.count(DISTINCT(session_id)) as views'); $this->db->from('statistik'); $this->db->join('statistik_strippeddomains', 'statistik_strippeddomains.id = statistik.strippeddomain', 'left'); $this->db->where('angebote_id',$_GET['id']); $this->db->where('strippeddomain !=',1); $this->db->group_by('domain'); $this->db->having('count > '.$film_daten['angebote_views']/100, NULL, FALSE); $this->db->order_by('count','desc'); $this->db->limit('25'); $query = $this->db->get(); Comment me If you have any query.
unknown
d1107
train
You don't need to put your <link rel="stylesheet" href="blah-blah.css"> tag into head to make it work, but it's a bad practice, because it works slower and looks a bit bad, but I understand your situation :) Just put <link> at the end of the <body> and it'll work fine! For example: File styles.css p { color: blue; } File index.html <!DOCTYPE html> <html> <head> <!-- Evil host holders didn't allow access this tag. Well, okay :D --> </head> <body> <p>I am blue, da ba dee da ba dai!</p> <link rel="stylesheet" href="styles.css"/> </body> </html>
unknown
d1108
train
For me, the following screenshot resolved the issue, that is to untick the "include cell output in headings" from the theme tab - Table of Contents, in the settings. Settings β†’ Table of Contents:
unknown
d1109
train
It's a bit unclear from your question. But I think you're trying to break from your while loop on finding the product entered. I changed the redundant for loop to an if statement, so that you can break from the while loop. Your break is just breaking from the for loop, not the while loop. static ArrayList<Product> printOneLine() { ArrayList<Product> oneLineList = new ArrayList<Product>(); Scanner oneLine = readDetails("Products-JavaBikes.txt"); while (oneLine.hasNextLine()) { oneLineList.add(getProduct(oneLine.nextLine())); System.out.print("Please enter a number:"); Scanner input = new Scanner (System.in); if(input.nextInt() < oneLineList.size()) { System.out.println(oneLineList.get(i)); break; } } return oneLineList; }
unknown
d1110
train
Understood correctly you might want the code output as Your number is 5. <b>123</b> <b>123</b> <b>HI!</b>2017-11-30-15.28.09.133 Maybe you might want to try with StringTokenizer (the codes below will hit java.util.NoSuchElementException as the nextToken() call is forced, but hopefully it will become a general idea) import java.util.StringTokenizer; .. String sampleStr= "Hello <br/> there <br/>"; StringTokenizer token = new StringTokenizer(sampleStr); System.out.println(token.nextToken());//You can use .trim() System.out.println(token.nextToken()); Would this help?
unknown
d1111
train
Your public key is not in the correct format. It is not a CSP blob. It is a DER encoded SubjectPublicKeyInfo structure. You can find source code to parse it or you can write your own. Here is one example of such code.
unknown
d1112
train
Before the AJAX call,the data you are sending is not in the right format.Probably that's the reason you are not getting the values in the backend.Try something like this. var file_data = $('#files').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); var files_data = form_data; var act = 'add'; form_data.append('act', act); form_data.append('textarea', $("#addCommentForm").find("textarea").val()); And in the ajax call,the data to passed should be, data: form_data,
unknown
d1113
train
GROUP BY is only being used to compute the aggregate value (average rating in this case). It doesn't have anything to do with the ordering of the results when they are displayed. As you have mentioned, you need to use ORDER BY to get the desired ordering. A: Group By should be used to group rows that have the same value for the specified column, Full explanation here https://stackoverflow.com/a/2421441. In your case, you want to group beers with the respect to aggregate rating and tasters, so you need to GROUP BY a.beers and order by the first and the third column. Thus the view should be like this: create or replace view tasters_avg_ratings1 as select a.taster as taster, a.beer as beer, round(avg(a.rating),1) as rating from allratings a group by a.beer order by 1,3; 1 and 3 are the ordinal positions of columns that appear in the select list. A: The SQL standard defines that a SELECT statement without an ORDER BY may return the resulting rows in an arbitrary order. There is a good explanation of why it might look different at first. GROUP BY is for grouping and aggregating related tuples together. A trivial implementation for grouping is of course sorting the data first and then working your way from top to bottom and aggregate related tuples. If your database chooses to use such an implementation chances are high you will receive an ordered result set. But there are other implementations possible and your database may change to using one of those at any time. And if it does you will receive the same rows but in a different order. So in short, if you want your result set to be ordered use an ORDER BY. Regarding the example you mentioned it is perhaps a bit misleading. The result is ordered by the columns it is also grouped by. This is a possible ordering and given the thoughts before probably quite a likely one. But since the query is without an ORDER BY this is just coincidence and not guaranteed.
unknown
d1114
train
I want re-renders whenever an element is pushed to receivedElements. Note that you won't get a re-render if you use: this.state.receivedElements.push(newElement); // WRONG That violates the restriction that you must not directly modify state. You'd need: this.setState(function(state) { return {receivedElements: state.receivedElements.concat([newElement])}; }); (It needs to be the callback version because it relies on the current state to set the new state.) My question is, can I not trigger rendering when the array becomes empty ? YesΒ β€” by not calling setState in that case. It sounds as though receivedElements shouldn't be part of your state, but instead information you manage separately and reflect in state as appropriate. For instance, you might have receivedElements on the component itself, and displayedElements on state. Then: this.receivedElements.push(newElement); this.setState({displayedElements: this.receivedElements.slice()}); ...and // (...some operation that removes from `receivedElements`...), then: if (this.receivedElements.length) { this.setState({displayedElements: this.receivedElements.slice()}); } Note how we don't call setState if this.receivedElements is empty. A: What about useRef? Documentation says: useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component. So if you change ref value inside useEffect it won’t rerender component. const someValue = useRef(0) useEffect(() => { someValue.current++ },[])
unknown
d1115
train
A simple CSS only approach could be to float your list elements left and give them a width of 25% total. Maybe add some padding so they aren't touching. So a width of 23% and left and right padding of 1% for a total of 25%. ul{list-style-type: none;} li{float: left; width: 23%; padding: 0 1%;} Demo
unknown
d1116
train
For a multi-valued json index, the json paths have to match, so with an index CREATE INDEX categories_index ON products((CAST(categories->'$' AS CHAR(32) ARRAY))) your query has to also use the path ->'$' (or the equivalent json_extract(...,'$')) SELECT * FROM products WHERE "books" MEMBER OF(categories->'$') Make it consistent and it should work. It seems though that an index without an explicit path does not work as expected, so you have to specify ->'$' if you want to use the whole document. This is probably a bug, but could also be an intended behaviour of casting or autocasting to an array. If you specify the path you'll be on the safe side.
unknown
d1117
train
master_list = [] for event in soup.find('dual').find_all('event'): master_list.append(event) for event in soup.find('int').find_all('event'): master_list.append(event) for event in soup.find('whatever').find_all('event'): master_list.append(event) print sorted(event) You may have to write your own comparison function so that sorted knows how to sort the list.
unknown
d1118
train
Given a HttpPostedFileBase named file, then you could do this: byte[] pdfbytes = null; BinaryReader rdr = new BinaryReader(file.InputStream); pdfbytes = rdr.ReadBytes((int)file.ContentLength); PdfReader reader = new PdfReader(pdfbytes); You could, of course, first save the PDF to a file, and then provide the path to that file, but usually, that's not what you want.
unknown
d1119
train
KReporter certainly the best Reporting tool in the Marketing for SugarCRM, regardless of edition - be it PRO, ENT, CORP or CE. The new free Google Charts are really cool A: I suggest KINAMU Reporter, http://www.sugarforge.org/projects/kinamureporter
unknown
d1120
train
The keyword β€˜elifβ€˜ is short for β€˜else if’, and is useful to avoid excessive indentation.Source A: When you really want to know what is going on behind the scenes in the interpreter, you can use the dis module. In this case: >>> def f1(): ... if a: ... b = 1 ... elif aa: ... b = 2 ... >>> def f2(): ... if a: ... b = 1 ... else: ... if aa: ... b = 2 ... >>> dis.dis(f1) 2 0 LOAD_GLOBAL 0 (a) 3 POP_JUMP_IF_FALSE 15 3 6 LOAD_CONST 1 (1) 9 STORE_FAST 0 (b) 12 JUMP_FORWARD 15 (to 30) 4 >> 15 LOAD_GLOBAL 1 (aa) 18 POP_JUMP_IF_FALSE 30 5 21 LOAD_CONST 2 (2) 24 STORE_FAST 0 (b) 27 JUMP_FORWARD 0 (to 30) >> 30 LOAD_CONST 0 (None) 33 RETURN_VALUE >>> dis.dis(f2) 2 0 LOAD_GLOBAL 0 (a) 3 POP_JUMP_IF_FALSE 15 3 6 LOAD_CONST 1 (1) 9 STORE_FAST 0 (b) 12 JUMP_FORWARD 15 (to 30) 5 >> 15 LOAD_GLOBAL 1 (aa) 18 POP_JUMP_IF_FALSE 30 6 21 LOAD_CONST 2 (2) 24 STORE_FAST 0 (b) 27 JUMP_FORWARD 0 (to 30) >> 30 LOAD_CONST 0 (None) 33 RETURN_VALUE It looks like our two functions are using the same bytecode -- So apparently they're equivalent. Careful though, bytecode is an implementation detail of CPython -- There's no telling that all python implementations do the same thing behind the scenes -- All that matters is that they have the same behavior. Working through the logic, you can convince yourself that f1 and f2 should do the same thing regardless of whether the underlying implementation treats it as "syntatic sugar" or if there is something more sophisticated going on. A: elif in Python is syntactic sugar for else if seen in many other languages. That's all. A: The three following code snippets would all execute using the same logic however all use different syntax. elif condition: ... else if conition { ... else { if conition { ... } Python's elif is just syntactic sugar for the common else if statement
unknown
d1121
train
!imporant for apply css forcefully and effects same as bootstrap. .form-control:focus{ box-shadow: 0 0 5px rgba(81, 203, 238, 1) !important; border: 1px solid rgba(81, 203, 238, 1) !important; } Working Fiddle A: If you want an input to have a different/special appearance once selected, use the :focus CSS pseudo-class. A simple example: #myInput:focus { border: 1px solid red; } PS. I assume you mean "glow", not "grow", and certainly not "blow" :-)
unknown
d1122
train
You can use Shared Preferences to store and retrieve information in Android. A: you can use shared preferences for this purpose . Just put the value into shared preference and load when the user need this info like username and password saved locally into any login form.
unknown
d1123
train
You would need to add ManyToOne mapping in your ChauffeurMap class this.ManyToOne(x => x.Adres , m => { m.Column("AdresId"); // AdresId can be insert and update m.Update(true); m.Insert(true); m.Cascade(Cascade.None); m.Fetch(FetchKind.Join); m.NotFound(NotFoundMode.Exception); m.Lazy(LazyRelation.Proxy); m.ForeignKey("AdresId"); }); And you would also need additional mapping class for Adres as AdresMap. I hope you already have it. If not, please add it as below - public class AdresMap : ClassMapping<Adres> { public AdresMap() { this.Table("Adres"); //Your table name this.Id(c => c.Id, c => { c.Generator(Generators.Native); c.Type(NHibernateUtil.Int64); c.Column("Id"); c.UnsavedValue(0); }); Set(x => x.Chauffeurs, c => { c.Key(k => { k.Column("Id"); k.ForeignKey("AdresId"); }); c.Inverse(true); c.Cascade(Cascade.None); }, r => r.OneToMany(o => { })); this.Property(x => x.Straat ); // ... other properties } }
unknown
d1124
train
http://snook.ca/archives/javascript/using_images_as check this out hope thiss will work A: You can do it like this without setting id and label for. Position relative should be used to wrap this section as well. <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Image label</title> <!-- Bootstrap CSS Toolkit styles --> </head> <style type="text/css"> label{ display: inline-block; } label img{ pointer-events: none; width: 100px; height: 100px; border-radius: 50%; box-shadow: 0px 2px 4px rgba(0,0,0,0.2); } input[type="file"]{ position: absolute; top: 5px; left: 5px; width: 108px; height: 130px; font-size: 100px; text-align: right; filter: alpha(opacity=0); opacity: 0; outline: none; background: white; cursor: inherit; display: block; } </style> <body> <form> <label> <img src="http://anniekateshomeschoolreviews.com/wp-content/uploads/2015/05/Online-picture1-300x203.jpg"> </label> <input type="file" id="test"> </form> </body> </html>
unknown
d1125
train
There is a compilation error in your project You must add derbynet.jar dependency in your classpath in order to embed the server. http://db.apache.org/derby/papers/DerbyTut/ns_intro.html#ns_config_env Client and server dependencies are two different jar.
unknown
d1126
train
In this page the author gives several ways to achieve what you want
unknown
d1127
train
Your code is doing exactly what you're telling it to do: it's sleeping your browser's UI thread, which means that your browser can't process any more messages, so it's effectively hanging your browser for the duration of the sleep. Thread.Sleep() in a browser is death: just don't do it, whether in Silverlight or any other framework. A better approach would be to step back and ask yourself why you want to sleep something, and then figure out a reasonable async way of doing that. Having been thrown into the Silverlight async world several years ago, I realize that this can be disorienting at first, but I can also testify that I've always found reasonably clean ways to do it right. Another way to put it: if you can't figure out how to do what it is that you actually need to get done, post a question about that, and you'll likely get some help here. For instance, if you just want to wait 'n' seconds and then perform a callback, you could use a helper class like this one: public class ThreadingHelper { public static void SleepAsync(int millisecondsToSleep, Action action) { var timer = new Timer(o => action()); timer.Change(millisecondsToSleep, Timeout.Infinite); } public static void SleepAsync(TimeSpan interval, Action action) { SleepAsync((int)interval.TotalMilliseconds, action); } public static void DispatcherSleepAsync(int millisecondsToSleep, Action action) { var interval = TimeSpan.FromMilliseconds(millisecondsToSleep); DispatcherSleepAsync(interval, action); } public static void DispatcherSleepAsync(TimeSpan interval, Action action) { var timer = new DispatcherTimer(); EventHandler timerHandler = null; timerHandler = (s, e) => { timer.Tick -= timerHandler; if (action != null) { action(); } }; timer.Tick += timerHandler; timer.Interval = interval; timer.Start(); } } A: You could do this: function begin() { /* do stuff... */ } function afterWait() { /* rest of my code...*/ } begin(); setTimeout(afterWait, 10000); setTimeout has effectively stopped your javascript for 10 seconds, and the browser can still carry on working
unknown
d1128
train
As Eliott Frisch said, the answer is in the next sentence of the paragraph you quoted: … This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). … An addFirst method would break the insertion order and thereby the design idea of LinkedHashSet. If I may add a bit of guesswork too, other possible reasons might include: * *It’s not so simple to implement as it appears since a LinkedHashSet is really implemented as a LinkedHasMap where the values mapped to are not used. At least you would have to change that class too (which in turn would also break its insertion order and thereby its design idea). *As that other guy may have intended in a comment, they didn’t find it useful. That said, you are asking the question the wrong way around. They designed a class with a functionality for which they saw a need. They moved on to implement it using a hash table and a linked list. You are starting out from the implementation and using it as a basis for a design discussion. While that may occasionally add something useful, generally it’s not the way to good designs. While I can in theory follow your point that there might be a situation where you want a double-ended queue with set property (duplicates are ignored/eliminated), I have a hard time imagining when a Deque would not fulfil your needs in this case (Eliott Frisch mentioned the under-used ArrayDeque). You need pretty large amounts of data and/or pretty strict performance requirements before the linear complexity of contains and remove would be prohibitive. And in that case you may already be better off custom designing your own data structure.
unknown
d1129
train
In this expression 'a', * ('b', 'c') You have two primary things going on * *'a', creates a tuple with a single element 'a' ** ('b', 'c') uses extended iterable unpacking (PEP 3132) So the result of #2 is used to continue the tuple definition from #1. To show a more intuitive example this is the same idea >>> 'a', *range(5) ('a', 0, 1, 2, 3, 4)
unknown
d1130
train
The views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the from parameter. Source Try cleaning your project and running it again. My guess is that the R.id values in your R.java file don't match the ones in the compiled Java code. This is entirely possible if you only changed the XML files. R.java will be regenerated, but the classes which use R.id are not recompiled with the new values. Since R.id contains final constants, the compiler can optimize the byte code by using the constant value directly rather than loading it from a variable. This directly causes the problem you are seeing when R.java changes but the rest of your code is not recompiled.
unknown
d1131
train
An ALB listener can only listen on a single port. You must define a listener for each port you want the load balancer to listen on. This isn't a limitation of Terraform, it's the way AWS load balancers are designed. Additionally, since an ALB can only handle HTTP and HTTPS requests you usually don't setup more than two listeners on an ALB (ports 80 and 443), and the listener configuration would of necessity be different since one would have an SSL certificate configuration and one would not.
unknown
d1132
train
When adding items, you need to run refresh: Refresh the sortable items. Triggers the reloading of all sortable items, causing new items to be recognized. In regards to placement, you appear to selecting more than you need. I suspect you just need to insert more items to the same list. Consider the following: $(function() { $('.parent').sortable({ containment: "parent", tolerance: "pointer", axis: "x" }); $('button').on('click', function() { var str = $('#store .parent').html(); $(str).insertBefore($('.parent div:eq(0)')); $('.parent').sortable("refresh"); }); }); .parent { background: silver; margin: 9px 0; } .title { background: gold; display: inline-block; width: auto; cursor: cell; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div id='store'> <div class='parent'> <div class='title'>lorem</div> <div class='title'>ipsum</div> </div> </div> <br> <button>CLICK</button> If you need a new list, then you need to add it and re-assign sortable to the new item. $(function() { $('.parent').sortable({ containment: "parent", tolerance: "pointer", axis: "x" }); $('button').on('click', function() { var str = $('#store .parent:last').prop("outerHTML"); $(str).insertBefore($('.parent:eq(0)')); $("#store .parent").sortable({ containment: "parent", tolerance: "pointer", axis: "x" }); }); }); .parent { background: silver; margin: 9px 0; } .title { background: gold; display: inline-block; width: 25%; cursor: cell; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div id='store'> <div class='parent'> <div class='title'>lorem</div> <div class='title'>ipsum</div> </div> </div> <br> <button>CLICK</button> Hope that helps.
unknown
d1133
train
I seen content overlapping when closing sidebars. May be you want to stop overlapping during open and close sidebar. It can be fixed by css. You can use transition in .wrapper class. see bellow code: .wrapper{ height: 100%; transition:all .25s; } A: You can achieve this with pure CSS. You haven't specified what the requirements are, but you can use flexbox like the below example to achieve a max-width main container flanked by 2 compressing sidebars. body { margin: 0; } .wrapper{ display: flex; } main { width: 1200px; padding: 20px; background-color: #f1f1f1; } .sidebar { flex-grow: 1; height: 100vh; padding: 0 15px; } .sidebar-left { border-right: 1px solid #06A52B; } .sidebar-right { border-left: 1px solid #06A52B; } <div class="wrapper"> <aside class="sidebar sidebar-left"> <h2>Left sidebar</h2> <p>Add content here</p> </aside> <main> <h1>Max width of this block is 1200px</h1> </main> <aside class="sidebar sidebar-right"> <h2>Right sidebar</h2> <p>Add content here</p> </aside> </div> A: You Can Dynamic every css class Using [ngClass] Depending on your logic ..it will render when the value will change..
unknown
d1134
train
Is there a better way than an in-core hash table? Yes. Especially if input files are larger than RAM. You explained that you have a very large number of 1 KiB documents, a large number of file segments. Pre-process them by reading each segment and writing one line per segment to a temporary segments.txt file containing two columns. First column has a copy of segment contents, or SHA224 hash of contents. Second column has segment index number, which is a serial number starting with zero. Feel free to use just the first few bytes of the hash, depending on your sensitivity to hash collisions. Now use /usr/bin/sort (out-of-core mergesort) to create segments_sorted.txt. At this point, your problem is trivial. Simply read each line, while remembering previous hash. If cur_hash == prev_hash you have identified duplicate chunks. The associated index lets you rapidly seek() to find the original contents in case ruling out potential collisions is important in your application.
unknown
d1135
train
I recently had this issue with my app. I was getting the 'Error: secret option required for sessions' ONLY when deployed to Heroku. Here is what my code looked like originally: app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false })) When I deployed to Heroku it kept giving me an "Internal server error". Once checking the logs, it showed me 'Error: secret option required for sessions'. Here is how I fixed it: app.use(session({ secret: 'secretidhere', resave: false, saveUninitialized: false })) Since my .env file wasn't viewable and that's where I had my secret code, it was giving me that error. Now, just by putting an arbitrary string 'secretidhere', I deployed to heroku again and it worked! ** However, please note that this should not be a permanent solution. As the poster above states, you should have a config file in your root directory, or another method so this session stays secret. Hope this helps! A: I was facing the same issue while I was deploying my code into AWS Elastic BeanStalk. In .env we could have - secret='my_secret' While in server.js: app.use(cookieParser()) app.use(session({ resave:true, saveUninitialized:true, secret:process.env.secret, cookie:{maxAge:3600000*24} })) The solution turned out to be adding secret to the environments in there. Just add it to your enviroments for production, be it heroku or AWS. A: Have you added your secret session from your .env file to heroku config? Since your .env is in your .gitignore it will not be pushed up to heroku. Your code is looking for a string from your process.env but the heroku environment does not have it yet. You have two solutions * *Go to your app console and click on settings. Once you are there, click on the box that says reveal config vars and add your secret there. or *In the root directory of your project you can set your config vars there using the command heroku config:set SECRET_SESSION="secretName"
unknown
d1136
train
I think it is an expected result. If you check the json specification you will see that you need to use strings for the names of the elements. So I am afraid you will need something like: val myMap = Map("4" -> Map("a" -> 5))
unknown
d1137
train
You can revert the files a few at a time. As a test, you could run p4 revert //path/to/some/file and verify that it's able to revert that file. Once you know that's working, you just need a way to automate the process. You could script something up that starts in the root directory and runs through all directories breadth-first, running p4 revert //path/to/folder/* at each folder (I think you could also use client paths). A: You can revert via the command line using the p4 tool. I do not think you can revert the files from the UI. The associated documentation shows various examples of how revert all or specific files (see the Examples section): http://www.perforce.com/perforce/r12.1/manuals/cmdref/revert.html
unknown
d1138
train
Just in case there is a different understanding about the unique constraint, I am assuming that the unique constraint is one unique index on both fields. If you have a unique constraint on key1 and a unique constraint on key2, then this will fail when there is a record in t1 with the same t2.key1 value, but a different t2.key2 value, because adding the record would result in two records in t1 with the same key1 value, which is forbidden by a unique constraint on key1. If this is what you have, you need a unique index with both fields, rather than column constraints. One possibility is that a value in t2 has a NULL key1 or a NULL key2. In an expression, a NULL input always results in a NULL result which is considered false. So, if t2 has a record with NULL key1 and a value of 'value2' for key2, then the where clause is evaluating select * from t1 where t1.key1 = NULL and t1.key2 = 'value2' This is not equivalent to select * from t1 where t1.key1 is NULL and t1.key2 = 'value2' instead t1.key1 = NULL will be untrue, the select will fail to ever return a result, the exist will be false and NOT(exist) will be true. But if t1 already has a record like this, the unique constraint will fail. So use this insert statement. insert into t1 select * from t2 where not exist ( select * from t1 where (t1.key1 = t2.key1 or (t1.key1 is null and t2.key1 is null)) and (t1.key2 = t2.key2 or (t1.key2 is null and t2.key2 is null))) A: ideal case for use of MINUS result set operation insert into t1 select * from t2 minus select * from t1
unknown
d1139
train
Use the split action bar option. All items which does not fix in the top action bar will be shown in the second action bar at the bottom of your screen. The remaining items will be centered within the second action bar. protected void onCreate(final Bundle savedInstanceState) { getSherlock().setUiOptions(ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW); super.onCreate(savedInstanceState); }
unknown
d1140
train
Try this: //*[*[1][*[normalize-space()='Hello']]]/*[2]/* It will select the element that contains "World". It's testing the value of the descendant in the first child and then selecting the descendant of the second child.
unknown
d1141
train
You don't need to cast it to NSString to use stringByReplacingCharactersInRange you just need to change the way you create your string range as follow: update: Xcode 7.2 β€’ Swift 2.1.1 let binaryColor = "000" let resultString = binaryColor.stringByReplacingCharactersInRange( Range(start: binaryColor.startIndex, end: binaryColor.startIndex.advancedBy(1)), withString: "1") Or simply let resultString2 = binaryColor.stringByReplacingCharactersInRange( binaryColor.startIndex..<binaryColor.startIndex.advancedBy(1), withString: "1") A: You have to set the variable: var binaryColor: String = "000" binaryColor = (binaryColor as NSString).stringByReplacingCharactersInRange(NSMakeRange(0, 1), withString: "1") println("This is binaryColor0: \(binaryColor)")
unknown
d1142
train
In doit you can write custom rules to check if a task is up-to-date or not. Check uptodate http://pydoit.org/dependencies.html#uptodate
unknown
d1143
train
Assuming I understood your question right that you want to fetch documents with a specific property value only if it exists, you can do something like this var query = QueryBuilder.Select(SelectResult.expression(Meta.id), SelectResult.expression(Expression.property("id"))) .From(DataSource.Database(db)) .Where(Expression.Property("name").NotNullOrMissing() .And(Expression.Property("name").EqualTo(Expression.string("My first test")))) Alternatively, if you know the Id of the document, it would be faster to do a GetDocument with the Id. Once you have the document, do a GetString on the name property. If it returns null, you can assume it does not exist. Refer to the documentation on Couchbase Lite query fundamentals here.There are several examples. You may also want to check out API specs on NotNullOrMissing
unknown
d1144
train
Python's defaultdict type in the collections package is useful for this kind of thing. from collections import defaultdict from pprint import pprint answer = defaultdict(list) for word in open(filename).read().lower().split(): answer[''.join(sorted(word))].append(word) pprint(answer) The defaultdict initialization accepts a function which initializes an object. In this case we initialize an empty list which we can immediately append. You may also find the pprint module useful. It'll nicely format your lists of words. A: This dic = {("".join(sortword(w))):w} is replacing dic with a new dictionary each time. You should be inserting keys or appending to lists instead for w in wordget: key = ''.join(sorted(word)) if key in dic: dic[key].append(word) else: dic[key] = [word] return dic The if/else block can be tidied up using defaultdict as in GrantJ's answer
unknown
d1145
train
One approach for Oracle: SELECT val FROM myTable UNION ALL SELECT 'DEFAULT' FROM dual WHERE NOT EXISTS (SELECT * FROM myTable) Or alternatively in Oracle: SELECT NVL(MIN(val), 'DEFAULT') FROM myTable Or alternatively in SqlServer: SELECT ISNULL(MIN(val), 'DEFAULT') FROM myTable These use the fact that MIN() returns NULL when there are no rows. A: How about this: SELECT DEF.Rate, ACTUAL.Rate, COALESCE(ACTUAL.Rate, DEF.Rate) AS UseThisRate FROM (SELECT 0) DEF (Rate) -- This is your default rate LEFT JOIN ( select rate from d_payment_index --WHERE 1=2 -- Uncomment this line to simulate a missing value --...HERE IF YOUR ACTUAL WHERE CLAUSE. Removed for testing purposes... --where fy = 2007 -- and payment_year = 2008 -- and program_id = 18 ) ACTUAL (Rate) ON 1=1 Results Valid Rate Exists Rate Rate UseThisRate ----------- ----------- ----------- 0 1 1 Default Rate Used Rate Rate UseThisRate ----------- ----------- ----------- 0 NULL 0 Test DDL CREATE TABLE d_payment_index (rate int NOT NULL) INSERT INTO d_payment_index VALUES (1) A: This snippet uses Common Table Expressions to reduce redundant code and to improve readability. It is a variation of John Baughman's answer. The syntax is for SQL Server. WITH products AS ( SELECT prod_name, price FROM Products_Table WHERE prod_name LIKE '%foo%' ), defaults AS ( SELECT '-' AS prod_name, 0 AS price ) SELECT * FROM products UNION ALL SELECT * FROM defaults WHERE NOT EXISTS ( SELECT * FROM products ); A: *SQL solution Suppose you have a review table which has primary key "id". SELECT * FROM review WHERE id = 1555 UNION ALL SELECT * FROM review WHERE NOT EXISTS ( SELECT * FROM review where id = 1555 ) AND id = 1 if table doesn't have review with 1555 id then this query will provide a review of id 1. A: I figured it out, and it should also work for other systems too. It's a variation of WW's answer. select rate from d_payment_index where fy = 2007 and payment_year = 2008 and program_id = 18 union select 0 as rate from d_payment_index where not exists( select rate from d_payment_index where fy = 2007 and payment_year = 2008 and program_id = 18 ) A: One table scan method using a left join from defaults to actuals: CREATE TABLE [stackoverflow-285666] (k int, val varchar(255)) INSERT INTO [stackoverflow-285666] VALUES (1, '1-1') INSERT INTO [stackoverflow-285666] VALUES (1, '1-2') INSERT INTO [stackoverflow-285666] VALUES (1, '1-3') INSERT INTO [stackoverflow-285666] VALUES (2, '2-1') INSERT INTO [stackoverflow-285666] VALUES (2, '2-2') DECLARE @k AS int SET @k = 0 WHILE @k < 3 BEGIN SELECT @k AS k ,COALESCE(ActualValue, DefaultValue) AS [Value] FROM ( SELECT 'DefaultValue' AS DefaultValue ) AS Defaults LEFT JOIN ( SELECT val AS ActualValue FROM [stackoverflow-285666] WHERE k = @k ) AS [Values] ON 1 = 1 SET @k = @k + 1 END DROP TABLE [stackoverflow-285666] Gives output: k Value ----------- ------------ 0 DefaultValue k Value ----------- ------------ 1 1-1 1 1-2 1 1-3 k Value ----------- ------------ 2 2-1 2 2-2 A: Assuming there is a table config with unique index on config_code column: CONFIG_CODE PARAM1 PARAM2 --------------- -------- -------- default_config def 000 config1 abc 123 config2 def 456 This query returns line for config1 values, because it exists in the table: SELECT * FROM (SELECT * FROM config WHERE config_code = 'config1' OR config_code = 'default_config' ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END) WHERE rownum = 1; CONFIG_CODE PARAM1 PARAM2 --------------- -------- -------- config1 abc 123 This one returns default record as config3 doesn't exist in the table: SELECT * FROM (SELECT * FROM config WHERE config_code = 'config3' OR config_code = 'default_config' ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END) WHERE rownum = 1; CONFIG_CODE PARAM1 PARAM2 --------------- -------- -------- default_config def 000 In comparison with other solutions this one queries table config only once. A: If your base query is expected to return only one row, then you could use this trick: select NVL( MIN(rate), 0 ) AS rate from d_payment_index where fy = 2007 and payment_year = 2008 and program_id = 18 (Oracle code, not sure if NVL is the right function for SQL Server.) A: This would be eliminate the select query from running twice and be better for performance: Declare @rate int select @rate = rate from d_payment_index where fy = 2007 and payment_year = 2008 and program_id = 18 IF @@rowcount = 0 Set @rate = 0 Select @rate 'rate' A: Do you want to return a full row? Does the default row need to have default values or can it be an empty row? Do you want the default row to have the same column structure as the table in question? Depending on your requirements, you might do something like this: 1) run the query and put results in a temp table (or table variable) 2) check to see if the temp table has results 3) if not, return an empty row by performing a select statement similar to this (in SQL Server): select '' as columnA, '' as columnB, '' as columnC from #tempTable Where columnA, columnB and columnC are your actual column names. A: Insert your default values into a table variable, then update this tableVar's single row with a match from your actual table. If a row is found, tableVar will be updated; if not, the default value remains. Return the table variable. ---=== The table & its data CREATE TABLE dbo.Rates ( PkId int, name varchar(10), rate decimal(10,2) ) INSERT INTO dbo.Rates(PkId, name, rate) VALUES (1, 'Schedule 1', 0.1) INSERT INTO dbo.Rates(PkId, name, rate) VALUES (2, 'Schedule 2', 0.2) Here's the solution: ---=== The solution CREATE PROCEDURE dbo.GetRate @PkId int AS BEGIN DECLARE @tempTable TABLE ( PkId int, name varchar(10), rate decimal(10,2) ) --- [1] Insert default values into @tempTable. PkId=0 is dummy value INSERT INTO @tempTable(PkId, name, rate) VALUES (0, 'DEFAULT', 0.00) --- [2] Update the single row in @tempTable with the actual value. --- This only happens if a match is found UPDATE @tempTable SET t.PkId=x.PkId, t.name=x.name, t.rate = x.rate FROM @tempTable t INNER JOIN dbo.Rates x ON t.PkId = 0 WHERE x.PkId = @PkId SELECT * FROM @tempTable END Test the code: EXEC dbo.GetRate @PkId=1 --- returns values for PkId=1 EXEC dbo.GetRate @PkId=12314 --- returns default values A: This is what I used for getting a default value if no values are present. SELECT IF ( (SELECT COUNT(*) FROM tbs.replication_status) > 0, (SELECT rs.last_replication_end_date FROM tbs.replication_status AS rs WHERE rs.last_replication_start_date IS NOT NULL AND rs.last_replication_end_date IS NOT NULL AND rs.table = '%s' ORDER BY id DESC LIMIT 1), (SELECT CAST(UNIX_TIMESTAMP (CURRENT_TIMESTAMP(6)) AS UNSIGNED)) ) AS ts;
unknown
d1146
train
git also keeps a log for individual branches : run git reflog feature/crud-suppliers to view only actions that moved that branch. By default : git rebase completely drops merge commits. If your changes were stored in commit Merge pull request #11 from ..., then running git rebase HEAD~2 would discard that commit. You can use -r|--rebase-merges to keep them.
unknown
d1147
train
Define new command, my example is based on ForeColor: (function(wysihtml5) { Β  Β Β  Β Β wysihtml5.commands.setClass = { Β  Β Β exec: function(composer, command, element_class) { Β  Β  Β  Β Β element_class=element_class.split(/:/); Β  Β  Β  Β Β element=element_class[0]; Β  Β  Β  Β Β newclass=element_class[1]; Β  Β  Β Β var REG_EXP = new RegExp(newclass,'g'); Β  Β Β //register custom class Β  Β  Β  wysihtml5ParserRules['classes'][newclass]=1; Β  Β  Β Β return wysihtml5.commands.formatInline.exec(composer, command, element, newclass, REG_EXP); Β  Β Β }, Β  Β Β state: function(composer, command, element_class) { Β  Β  Β  Β Β element_class=element_class.split(/:/); Β  Β  Β  Β Β element=element_class[0]; Β  Β  Β  Β Β newclass=element_class[1]; Β  Β  Β  Β  var REG_EXP = new RegExp(newclass,'g'); Β  Β  Β Β return wysihtml5.commands.formatInline.state(composer, command, element, newclass, REG_EXP); Β  Β Β } Β Β }; })(wysihtml5); usage: HTML: <div id="uxToolbar"> <button data-wysihtml5-command="setClass" data-wysihtml5-command-value="span:my-wysihtml5-custom-class" type="button" title="View HTML" tabindex="-1" class="btn btn-mini"> My class </button> </div> so as you can see value is from two parts: element:class DEMO
unknown
d1148
train
This is a method that doesn't use pandas. The .count() method returns the value count of an item in a list. The .extend() method appends another to the end of an existing list. Lastly, multiplying a list by an integer duplicates and concats it that many times. ['a'] * 3 == ['a', 'a', 'a'] def extend_list(l1, l2, prefixes, final_prefixes, suffix_1, suffix_2, suffix_3): for prefix in prefixes: if l1.count(f'{prefix}_{suffix_2}') < l1.count(f'{prefix}_{suffix_1}'): l1.extend([f'{prefix}_{suffix_2}'] * l2.count(f'{prefix}_{suffix_3}')) for final_prefix in final_prefixes: l1.extend([f'{final_prefix}_{suffix_1}'] * (l2.count(f'{final_prefix}_{suffix_2)') + l2.count(f'{final_prefix}_{suffix_3}'))) l1 = ['aa_#1','bb_#1','bb_#2','aa_#1','aa_#1','aa_#1','bb_#1','aa_#2','bb_#2','aa_#2','bb_#1','bb_#1','bb_#1','bb_#2','bb_#2','cc_#1'] l2 = ['aa_#3','aa_#3','aa_#3','bb_#3','bb_#3','bb_#3','cc_#2','cc_#2','cc_#3','cc_#3'] l1 = extend_list(l1, l2, ["aa", "bb"], ["cc", "dd"], "#1", "#2", "#3")
unknown
d1149
train
The first piece of code tries to get a value from foo associated with key, and if foo does not have the key key, defaults to foobar. So there are two cases here: * *foo has the key key, so bar is set to foo[key] *foo does not have the key key, so bar is set to "foobar" The second looks at the value associated with the key key in foo, and if that value is falsy (that is, if bool(foo[key])==False), it defaults to foobar. If foo does not have the key key it raises a KeyError. So there are three cases here: * *foo has the key key, and bool(foo[key])==True, so bar is set to True *foo has the key key, and bool(foo[key])==False, so bar is set to "foobar" *foo does not have the key key, so the code raises a KeyError A: The 2nd example will raise KeyError if foo['key'] doesn't exist. If you want to assign a default value to bar if foo['key'] doesn't exist or contains falsey value, this would be the Pythonic way to do it: bar = foo.get('key') or 'foobar' A: Yes: foo.get('key', 'foobar') always returns something (if there is a key names 'key' it will return its value, and if there is no such key it will return 'foobar'). but bool(foo['key']) or 'foobar' can raise a KeyError if there is no such key named 'key'. Furthermore - the use of or here is not indicative, so the get method is preferable. A: You should most definitely not use the second form, because it will throw a KeyError if the key does not exist your dictionary. You're only getting acceptable behavior out of the second form because the key was set. A: This is the problem with using bool() one = {"my_key": None} print "Get:", one.get("my_key") print "Bool:", bool(one.get("my_key")) print "Get with falback:", one.get("my_key", "other") Get: None Bool: False Get with falback: None Note that there is a value in there, None, but bool evaluates to false. You should use get("key", "default"), it's designed to do the job. A: If you think foo = dict(key=u"") will produce a dictionary wich default value is an empty string, you are mistaken. You'll need a defaultdict for that: In [6]: bool(foo['key']) or 'foobar' Out[6]: 'foobar' In [7]: foo = dict(key='') In [9]: bool(foo['nokey']) or 'foobar' KeyError: 'nokey' Either use defaultdict, or dict.get, or even dict.setdefault. The good all way works too: In [10]: try: ....: v = foo['nokey'] ....: except KeyError: ....: v = 'foobar' ....: In [11]: v Out[11]: 'foobar'
unknown
d1150
train
You can add/remove necessary characters from the toRemove() array. Sub replaceChars() Dim toRemove() toRemove() = Array("D", "X", "F") For Each itm In toRemove() For Each iCell In ActiveSheet.UsedRange iCell.Replace What:=itm, Replacement:="", MatchCase:=True Next iCell Next itm End Sub
unknown
d1151
train
The cross entropy is a way to compare two probability distributions. That is, it says how different or similar the two are. It is a mathematical function defined on two arrays or continuous distributions as shown here. The 'sparse' part in 'sparse_categorical_crossentropy' indicates that the y_true value must have a single value per row, e.g. [0, 2, ...] that indicates which outcome (category) was the right choice. The model then outputs the y_pred that must be like [[.99, .01, 0], [.01, .5, .49], ...]. Here, model predicts that the 0th category has a chance of .99 in the first row. This is very close to the true value, that is [1,0,0]. The sparse_categorical_crossentropy would then calculate a single number with two distributions using the above mentioned formula and return that number. If you used a 'categorical_crossentropy' it would expect the y_true to be a one-hot encoded vector, like [[0,0,1], [0,1,0], ...]. If you would like to know the details in depth, you can take a look at the source.
unknown
d1152
train
The error is in your include settings, which should simply be strings "aggs": { "anim_fore": { "terms": { "field": "suggest_keywords.autocomplete", "order": { "_count": "desc" }, "include": "anim.*fore.*" <--- here } }, "fore": { "terms": { "field": "suggest_keywords.autocomplete", "order": { "_count": "desc" }, "include": "fore.*" <--- and here } } } A: You have trailing commas after doc_id and after closing array tag for must, your query should look like this "must": [ { "multi_match": { "query": "anim fore", "analyzer": "query_analyzer", "type": "cross_fields", "fields": [ "doc_id" // You have trailing comma here ], "operator": "and" } } ] // And here
unknown
d1153
train
I found this question while looking for the "SyntaxError: Generator expression must be parenthesized" in a "code wars" kata I did in 3.8. My presumably similar example was: max(word for word in x.split(), key=score) I was looking for the word in the given string x with the highest score that was calculated by the existing but (at least here) irrelevant method named score. After reducing my code down to this statement, I found the problem in word for word in x.split() not being in parenthesized seperately from the second argument. Changing that made my code run just fine: max((word for word in x.split()), key=score) Since your example does not have additional arguments but there is a comma between key dan value, I assume there is a hiccup in the parser when faced with comma and generator expressions. Avoiding to unpack the item and thus removing the comma should solve the problem: options = dict(item for item in options.items() if item[1] is not None) We only have to fetch the value from the tuple instead of using a separate variable.
unknown
d1154
train
'datat' is scoped outside your function. twit.search is async and therefore may not return 'data' before you check 'datat' with sys.inspect. This should let you see datat: var datat; twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt}, function(data) { // and output to the console: datat = data; sys.puts(sys.inspect(datat)); }); But ideally you'd use a callback like this... var datat; var callback = function(d){ sys.puts(sys.inspect(d)); datat = d; // do something more with datat }; twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt}, function(data) { callback(data); }); EDIT - simplified as per comment... var datat; var callback = function(d){ sys.puts(sys.inspect(d)); datat = d; // do something more with datat }; twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt},callback(data));
unknown
d1155
train
There are a few issues in your code. * *In your else block, you need to replace (n1<1) with (n2<1). *Replace if(n1==n2) with if(n1!=n2) *You do not need to iterate through all the elements. If at any point you find the index elements of both the arrays do not satisfy the condition, you should break the loop. Use a boolean flag for this. public class CompaibleArrays { public static void main(String []args){ int n1=0; int n2=0; boolean flag=true; int []a1 = new int[20]; int []a2 = new int[20]; Scanner sc = new Scanner(System.in); System.out.println("Enter the size for First array:"); n1 = sc.nextInt(); if(n1<1){ System.out.println("Invalid array size"); } else{ System.out.println("Enter the elements for First array:"); for(int i=0 ; i<n1 ; i++){ a1[i] = sc.nextInt(); } System.out.println("Enter the size for Second array:"); n2 = sc.nextInt(); if(n2<1){ System.out.println("Invalid array size"); } else{ System.out.println("Enter the elements for Second array:"); for(int j=0 ; j<n2 ; j++){ a2[j] = sc.nextInt(); } } } if(n1!=n2){ System.out.println("Arrays are Not Compatible"); } else{ for(int x=0 ; x<n1 ; x++){ if(a1[x]<a2[x]){ flag = false; break; } } if(flag==true){ System.out.println("Arrays are Compatible"); } else{ System.out.println("Arrays are Not Compatible"); } } } }
unknown
d1156
train
Assuming your talking about textFieldDidEndEditing: or textFieldShouldReturn:. You would implement the method in your view controller, and set the text fields delegate to self like so: - (void)viewDidLoad { [super viewDidLoad]; // .... myTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 50, 25)]; myTextField.delegate = self; [self.view addSubview:myTextField]; } - (void)textFieldDidEndEditing:(UITextField *)textField { if (textField == myTextField) { // Do stuff... } } - (BOOL)textFieldShouldReturn:(UITextField *)textField { if (textField == myTextField) { return YES; } return NO; } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if ((myTextField.text.length + string.length) < 5) { return YES; } return NO; } Then, in your header file in the @interface you can specify that you are a UITextFieldDelegate like this: @interface MyViewController : UIViewController <UITextFieldDelegate> { // .... UITextField *myTextField; // .... } // Optionally, to make myTextField a property: @property (nonatomic, retain) UITextField *myTextField; @end UITextField Reference UITextFieldDelegate Reference Edit (as per your comment, this should work): - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if ((myTextField.text.length + string.length) < 5) { return YES; } return NO; }
unknown
d1157
train
These days the location of the emulated SD card is at /storage/emulated/0 A: On linux sdcard image is located in: ~/.android/avd/<avd name>.avd/sdcard.img You can mount it for example with (assuming /mnt/sdcard is existing directory): sudo mount sdcard.img -o loop /mnt/sdcard To install apk file use adb: adb install your_app.apk A: DDMS is deprecated in android 3.0. "Device file explorer"can be used to browse files. A: Drag & Drop To install apk in avd, just manually drag and drop the apk file in the opened emulated device The same if you want to copy a file to the sd card A: if you are using Eclipse. You should switch to DDMS perspective from top-right corner there after selecting your device you can see folder tree. to install apk manually you can use adb command adb install apklocation.apk A: I have used the following procedure. Android Studio 3.4.1 View>Tool Windows>Device File Explorer A: * *switch to DDMS perspective *select the emulator in devices list, whose sdcard you want to explore. *open File Explorer tab on right hand side. *expand tree structure. mnt/sdcard/ refer to image below To install apk manually: copy your apk to to sdk/platform-tools folder and run following command in the same folder adb install apklocation.apk A: I have used the following procedure. Procedure to install the apk files in Android Emulator(AVD): Check your installed directory(ex: C:\Program Files (x86)\Android\android-sdk\platform-tools), whether it has the adb.exe or not). If not present in this folder, then download the attachment here, extract the zip files. You will get adb files, copy and paste those three files inside tools folder Run AVD manager from C:\Program Files (x86)\Android\android-sdk and start the Android Emulator. Copy and paste the apk file inside the C:\Program Files (x86)\Android\android-sdk\platform-tools * *Go to Start -> Run -> cmd *Type cd β€œC:\Program Files (x86)\Android\android-sdk\platform-tools” *Type adb install example.apk *After getting success command *Go to Application icon in Android emulator, we can see the your application A: //in linux // in your home folder .android hidden folder is there go to that there you can find the avd folder open that and check your avd name that you created open that and you can see the sdcard.img that is your sdcard file. //To install apk in linux $adb install ./yourfolder/myapkfile.apk A: Adding to the usefile DDMS/File Explorer solution, for those that don't know, if you want to read a file you need to select the "Pull File from Device" button on the file viewer toolbar. Unfortunately you can't just drag out, or double click to read.
unknown
d1158
train
1) readRDS requires assignment unlike load, so this works: e = local({df <- readRDS("path/to/file.RData"); environment()}) tools:::makeLazyLoadDB(e, "path/to/file") lazyLoad("path/to/file") I should be saving my files according to convention using .rds as an extension when saving data using saveRDS. 2) Probably not the right approach in this case as indexing any element of the "promise" loads the whole file not just the indexed element.
unknown
d1159
train
Try the code below: (however it may be worth it to create a reusable component out of the label/description fields so it’s not duplicated) Array.isArray(keyTerm.value) ? keyTerm.value.map(ele => ( <> <Label>{ele.label}</Label> <Description>{ele.value}</Description> </> )) : ( <> <Label>{keyTerm.label}</Label> <Description>{keyTerm.value}</Description> </> )
unknown
d1160
train
Taking into account that mentioned deleteRequest semantically is asynchronous and there might be, in general, several contacts deleted in one user action, I would do it like below func delete(at offsets: IndexSet) { // preserve all ids to be deleted to avoid indices confusing let idsToDelete = offsets.map { self.contacts[$0].id } // schedule remote delete for selected ids _ = idsToDelete.compactMap { [weak self] id in self?.deleteRequest(id){ success in if success { DispatchQueue.main.async { // update on main queue self?.contacts.removeAll { $0.id == id } } } } } } Note: also some feedback in UI would be needed marking progressed contacts and disabling user from other manipulations with them till end of corresponding deleteRequest
unknown
d1161
train
What about: ClassPathResource resource = new ClassPathResource("classpath:/sw/merlot/config/log4j.xml"); or if it is in a different jar file: ClassPathResource resource = new ClassPathResource("classpath*:/sw/merlot/config/log4j.xml");
unknown
d1162
train
use this but you need to work on the duplicate value creation- <div ng-app="tableApp" ng-controller="tableAppCtrl"> <h3>{{titleString}}</h3> <table> <tr> <th><input type="button" value="{{(selectAllval==true) ? 'UncheckALL' : 'checkALL'}}" ng-click="selectAll(selectAllval)"></th> <th>Product Type</th> <th>Product Name</th> </tr> <tr ng-repeat="d in prodDataTable"> <td><input type="checkbox" ng-checked="selectAllval" ng-click="setProductType(d.productType)"></td> <td>{{d.productType}}</td> <td>{{d.productName}}</td> </tr> </table> {{setProductTypes}} angular.module("tableApp",[]).controller('tableAppCtrl', ['$scope', function($scope) { $scope.titleString="Table Demo"; $scope.selectAllval= false; $scope.setProductTypes= []; $scope.selectAll= function(val){ if(val==false){ $scope.selectAllval= true; } else{ $scope.selectAllval= false; } }; $scope.setProductType= function(type){ $scope.setProductTypes.push(type); }; $scope.prodDataTable = [{ "productType": "A", "productName": "Aaaaaa" }, { "productType": "B", "productName": "Bbbbbb" }, { "productType": "C", "productName": "Cccccc" }]; } ]); A: try the below code - angular.module("tableApp",[]).controller('tableAppCtrl', ['$scope', function($scope) { $scope.titleString="Table Demo"; $scope.selectAllval= false; $scope.selectAll= function(val){ if(val==false){ $scope.selectAllval= true; } else{ $scope.selectAllval= false; } }; $scope.prodDataTable = [{ "productType": "A", "productName": "Aaaaaa" }, { "productType": "B", "productName": "Bbbbbb" }, { "productType": "C", "productName": "Cccccc" }]; } ]); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div ng-app="tableApp" ng-controller="tableAppCtrl"> <h3>{{titleString}}</h3> <table> <tr> <th><input type="button" value="{{(selectAllval==true) ? 'UncheckALL' : 'checkALL'}}" ng-click="selectAll(selectAllval)"></th> <th>Product Type</th> <th>Product Name</th> </tr> <tr ng-repeat="d in prodDataTable"> <td><input type="checkbox" ng-checked="selectAllval" ></td> <td>{{d.productType}}</td> <td>{{d.productName}}</td> </tr> </table> </div>
unknown
d1163
train
You can use lag(): select distinct phone from (select t.*, lag(status) over (partition by phone order by date) as prev_status, lag(status, 2) over (partition by phone order by date) as prev2_status, from t ) t where status in ('Failed', 'Send_Failed') and prev_status in ('Failed', 'Send_Failed') and prev2_status in ('Failed', 'Send_Failed') ; A: Below query gave me the right results for my own question select distinct A.[Phone Number Attempted] from ( Select distinct [Phone Number Attempted], [SMS Return Code], [Date Sent] ,LAG([SMS Return Code]) over (partition by [Phone Number Attempted] order by [Sent Date]) as prev_status ,lag([SMS Return Code], 2) over (partition by [Phone Number Attempted] order by [Sent Date]) as prev2_status from [MyTable] ) A where prev_status in ('FAILED', 'SEND_FAILED') and prev2_status in ('FAILED', 'SEND_FAILED') and [SMS Return Code] in ('FAILED', 'SEND_FAILED') and not exists (Select 1 from [MyTable] B where A.[Phone Number Attempted] =B.[Phone Number Attempted] and B.[Sent Date] > A.[Sent Date])
unknown
d1164
train
Try this. But keep in mind about Academic Integrity, which is posted at the bottom of the page. It may not be the same school you go to, but I'm sure AI is universal regardless of whatever school assignment you're going through. You can also try Googling your problem, I found ~five references for doing so.
unknown
d1165
train
In the declaration: //MULTIDIMENSIONAL ARRAY $array_database= array( array("", "2017-06-30-104",1498858541000,39.3322,-122.9027,2.11,0,"U",36) ); // In the loop: $valori_db[] = " ('','$idserial_db',$milliseconds_db,$latitude_db,$longitude_db,$magnitude_db,$ipocentro_db,'$source_db',$region_db)"; In the query: mysqli_query($connessione,"INSERT INTO earthquakes (id,idserial,milliseconds,latitude,longitude,magnitude,ipocentro,source,region) VALUES $values");
unknown
d1166
train
<div ng-controller="MyCtrl"> <div ng-repeat="person in people | filter:search" ng-show="person.last"> {{person.last}}, {{person.first}} </div> Try testing for person.last instead of just 'last'. I used ng-show instead of ng-if as well. A: If you want to just hide the rows, then mccainz's answer will work. If you want to actually remove them from the DOM, then create a filter: $scope.fullNameFilter = function(person){ return person.last; }; HTML <div ng-repeat="person in people | filter: fullNameFilter"> JSFIddle
unknown
d1167
train
I do not see any problem using @Asyncas this will release the request thread. But this is a simple approach and it has a lot of limitations. Note that if you want to deal with reactive streams, you do not have an API capable of that. For instance, if an @Async method calls another, the second will not be async. The Webflux instead will bring the most complete API (in Java) to deal with things the reactive way. What you cannot do with only @Async. With Flux, for instance, you can process or access with multiple layers reactively and this you cannot reach the way you doing. Nevertheless, it will bring a new universe for you, so if you just want to release the thread of the request, your approach is just fine, but if you need more you will have to deal with it in a more complex way. Now, if you want to answer the HTTP request and then do the work asyncly, this is not what you want. I recommend that you have a JMS provider (like ActiveMQ), where your controller sends the message to be processed by a job and answers the request. Hope it helps!
unknown
d1168
train
You need to declare which exceptions are thrown in a method: the method declaration should be: String reverse(String name) throws IOException A: You have to create the exception before throwing it: if(name.length()==0) throw new IOException("name"); Also main must not throw an IOException. Catch it and print the message to System.err. A: May be this is what you need. package reversestring; // import java.io.* is not needed here. // And if you want to import anything, // prefer specific imports instead and not entire package. // java.lang.* is auto-imported. You needn't import it explicitly. public class Propogate { // There's no reason this method should be an object method. Make it static. public static String reverse(String name) { if (name == null || name.length() == 0) { // RuntimeExceptions are preferred for this kind of situations. // Checked exception would be inappropriate here. // Also, the error message should describe the kind of exception // occured. throw new RuntimeException("Empty name!"); } // Idiomatic method of string reversal: return new StringBuilder(name).reverse().toString(); } public static void main(String[] args) { String name; try { name = Propogate.reverse("java"); System.out.println("Reversed string: " + name); } catch (RuntimeException rx) { System.err.println(rx.getMessage()); } finally { // I don't get the point of `finally` here. Control will reach this // point irrespective of whether string reversal succeeded or failed. // Can you explain what do you mean by "done" below? System.out.println("done"); } } } /* Output:- Reversed string: avaj done */
unknown
d1169
train
See Textmate + RVM + Rake = Rake not using expected gem environment for some answers about this particular problem, and some advice on how to diagnose your own situation.
unknown
d1170
train
It's a simple sum and group by select product, sum(count) from mytable group by product A: Select product, sum(count) from table_name group by product You might want to go through tutorial of group_by clause http://www.techonthenet.com/sql/group_by.php A: i dont know if you looking for pivote result as you done in your question , if yes use this SELECT Sum(CASE WHEN ( product = 'a' ) THEN ` count ` ELSE 0 END)AS a, Sum(CASE WHEN ( product = 'b' ) THEN ` count ` ELSE 0 END)AS b, Sum(CASE WHEN ( product = 'c' ) THEN ` count ` ELSE 0 END)AS c FROM table1 DEMO HERE result: A B C 7 2 6 note this query is only if you have 3 limited values on product.
unknown
d1171
train
Just change your query to this: select c.value('(../groupkey)[1]','int'), c.value('(../groupname)[1]','nvarchar(max)'), c.value('(contactkey)[1]','int'), c.value('(contactname)[1]','nvarchar(max)') from @xml.nodes('contactdata/contacts/contact') as Contacts(c) You need to get a list of all <contact> elements - and then extract that necessary data from those XML fragments. To get the groupkey and groupname, you can use the ../ to navigate "up the tree" one level to the parent node.
unknown
d1172
train
Add CFLAGS=-g -O0 below CC and change the line $(CC) -o @ (SRC) into $(CC) -o $@ $(CFLAGS) $(SRC) This would produce a final Makefile that looks like: CC = gcc CFLAGS = -g -O0 SRC = main.c TARGET = main2 all: $(TARGET) $(TARGET): $(SRC) $(CC) -o $@ $(CFLAGS) $(SRC) clean: rm -f $(TARGET) A: If you're looking for a very simple (if we define simple by very few lines of code), then all I ask is that you rename your source file to main.c instead of main2.c. CFLAGS = -g -O0 all: main Which we can run: $ cat Makefile CFLAGS = -g -O0 all: main $ cat main.c int main() {} $ make gcc -g -O0 main.c -o main
unknown
d1173
train
Yes, you can include external files as part of your main body using \input. For example, assume you have mytable.table that contains \begin{table}[ht] \centering \begin{tabular}{cc} 3 3 \end{tabular} \caption{A table}\label{tab:mytable} \end{table} You can now use \documentclass{article} \begin{document} Look at Table~\ref{tab:mytable}. \input{mytable.table} \end{document} You wouldn't want to use \include here. See When should I use \input vs. \include?
unknown
d1174
train
I've ditched the Where entirely and done it using the Array.BinarySearch using this comparer: class ItemLimitsComparer : Comparer<ItemLimits> { public override int Compare(ItemLimits x, ItemLimits y) { if(Convert.ToInt32(x.strUserCode) < Convert.ToInt32(y.strUserCode)) { return -1; } if(Convert.ToInt32(x.strUserCode) > Convert.ToInt32(y.strUserCode)) { return 1; } if(Convert.ToInt32(x.strUserCode) == Convert.ToInt32(y.strUserCode)) { if(Convert.ToInt64(x.strAccountNumber) < Convert.ToInt64(y.strAccountNumber)) { return -1; } if(Convert.ToInt64(x.strAccountNumber) > Convert.ToInt64(y.strAccountNumber)) { return 1; } if(Convert.ToInt64(x.strAccountNumber) == Convert.ToInt64(y.strAccountNumber)) { return 0; } } return 0; } } (this is the first time I've used this, I suspect I have a bug lurking somewhere) The Where has been replaced by this: int index = Array.BinarySearch(itlaCreditLimits, new ItemLimits { strUserCode = dataset[i].User_UserCode, strAccountNumber = strUnEditedHomingAccountNo }, new ItemLimitsComparer()); if(index < 0) { throw new Exception("Didn't find ItemLimit for UserCode = " + dataset.User_UserCode + " and account number " + strUnEditedHomingAccountNo); } ItemLimits ilItemLimit = itlaCreditLimits[index]; This has got me down from 15 minutes for all 50k items to 25 seconds. A: I think that you are correct to what's causing this problem and I suggest you use something with a fast look-up to speed things up. Something like a dictionary, it's very fast. You already know how to compare and see if you have the correct record and you also only look for one match, or the first... Try something like this, you'll need to change the type of the DataSet (no idea of what you are using) and maybe decide how to handle key-collisions when making the itemLimitDictionary but other than that it should speed things up nicely: public void DoTheNeedfull(ItemLimit[] itemLimits, DataSet dataSet) { var itemLimitDictionary = itemLimits.ToDictionary(i => MakeKey(i.One, i.Two), i => i); for(var i = 0; i < dataSet.Count; i++) { var strUnEditedHomingAccountNo = BlackMagicMethod(dataSet[i]); var key = MakeKey(dataSet[i].User_UserCode, strUnEditedHomingAccountNo); if(itemLimitDictionary.ContainsKey(key)) { // do your thing } else { // maybe this is an error } } } private string MakeKey(string keyPartOne, string keyPartTwo) { return keyPartOne.ToUpperInvariant() + keyPartTwo.ToUpperInvariant(); } A: So as far as i understand you like to iterate through your dataset and than increase a counter. That counter is specific to some properties of the dataset entry. So it sounds to be a job for the GroupJoin() linq statement. With that you would get an ItemLimits object with all matching dataset items as IEnumerable<DataSetItem>. Then you could call Aggregate() on this inner enumeration and write this information into the given ItemLimits object.
unknown
d1175
train
You should set line-height of your heading titles. #MainTitles h1 { line-height: 50px } #LangSelect a { line-height: 20px; } But the problem is not inside these 2 rules. I didn't determinate full code of CSS, I just check small fixes for places which I saw broken A: I found the problem and resolve the Issue. OS X have a rendering issue with some fonts. I start my research searching a common pattern, I has this issue with 3 websites: * *Adjusting the line-height didn't work properly. *Change the ul from inline-block to flexbox, didn't work *The issue is present in any browser in Mac OS (I test Chrome, Firefox and Safari) Continue researching an I found some documentation about the issue. I found this article OS X type rendering - text baseline is shifted upwards, effectively no-longer centered vertically within the line-height I test in the 3 different websites have the issue and VOILA! Everything works fine now. I used in the 3 websites the same fonts (the common pattern): * *Gotham Book *Gotham Black I can confirm this two fonts evoke the rendering issue in Mac Os. The problem is solved right now.
unknown
d1176
train
When return is triggered, the function ends and every other line of code after it is not executed. If you want to delay the return of your data until later in the function, then create a variable, assign value(s), and return the variable when you're ready. For example, you can adapt your code to create an array for $data, like so: function dbGet($conn, $table, $select, $where, $cond) { $data = array(); ... while ( $row = $result->fetch_assoc() ) { $data[] = $row; } $stmt->close(); ... $db->close(); return $data; }
unknown
d1177
train
From Section 3.6.1 of http://smtlib.cs.uiowa.edu/papers/smt-lib-reference-v2.6-r2017-07-18.pdf: Let. The let binder introduces and defines one or more local variables in parallel. Semantically, a term of the form (let ((x1 t1) Β· Β· Β· (xn tn)) t) (3.3) is equivalent to the term t[t1/x1, . . . , tn/xn] obtained from t by simultaneously replacing each free occurrence of xi in t by ti , for each i = 1, . . . , n, possibly after a suitable renaming of t’s bound variables to avoid capturing any variables in t1, . . . , tn. Because of the parallel semantics, the variables x1, . . . , xn in (3.3) must be pairwise distinct. Remark 3 (No sequential version of let). The language does not have a sequential version of let. Its effect is achieved by nesting lets, as in (let ((x1 t1)) (let ((x2 t2)) t)). As indicated in Remark 3, if you want to refer to an earlier definition you have to nest the let-expressions.
unknown
d1178
train
Don't include the CSS file, just echo it. Like: <?php // // your other cods here // $style_services = file_get_contents ("root/css/style-services.css"); echo $style_services; // // your other cods here // ?>
unknown
d1179
train
You can use DatePipe API for this: https://angular.io/api/common/DatePipe @Component({ selector: 'date-pipe', template: `<div> <p>Today is {{today | date}}</p> <p>Or if you prefer, {{today | date:'fullDate'}}</p> <p>The time is {{today | date:'h:mm a z'}}</p> //format in this line </div>` }) // Get the current date and time as a date-time value. export class DatePipeComponent { today: number = Date.now(); } and this is what actually you want: {{myDate | date: 'dd-MM-yyyy'}} Edit: Using built-in pipe in component, import { DatePipe } from '@angular/common'; class MyService { constructor(private datePipe: DatePipe) {} transformDate(date) { return this.datePipe.transform(date, 'yyyy-MM-dd'); } } Please read this topic, I took example from there: https://stackoverflow.com/a/35152297/5955138 Edit2: As I described in comment, you can substring your date using this. var str = '07112018' var d = new Date(str.substring(0, 2)+'.'+str.substring(2, 4)+'.'+str.substring(4, 8)); Output: Wed Jul 11 2018 00:00:00 GMT+0300 A: try this function to convert time format as you require timeFormetChange(){ var date =new Date(); var newDate = date.getDate(); var newMonth = date.getMonth(); var newYear =date.getFullYear(); var Hour = data.getHours(); var Minutes = data.getMinuets(); return `${newDate}-${newMonth }-${newYear} ${Hour}:${Minutes }` }
unknown
d1180
train
You can keep the parameter sent in POST in session variables. This way on your second page, you can still access them. For example on your first page : <?php session_start(); // ... // $_SESSION['value1'] = $_POST['value1']; $_SESSION['value2'] = $_POST['value2']; header('Location: youremailpage.php'); die(); // ... // ?> And on your second page : <?php session_start(); // ... // $value1 = $_SESSION['value1']; $value2 = $_SESSION['value2']; // ... // ?>
unknown
d1181
train
The API mentions Driver#quit as something to "quit the browser". It seems that adding @driver.quit to your rescue would do what you want.
unknown
d1182
train
You are not using them correctly. as specifies the name of the output array of the $lookup. There is only 1 result set per lookup so only 1 as would be needed. let specifies the variables you want to use in the sub-pipeline. You can put them in an object if you want to use multiple variables. Your code should look like this: db.collection.aggregate([ { $lookup: { from: "users", let: { userFrom: "$from", userTo: "$to" }, pipeline: [ { $match: { $expr: { $or: [ { $eq: [ "$$userFrom", "$_id" ] }, { $eq: [ "$$userTo", "$_id" ] } ] } } } ], as: "userLookup" } } ])
unknown
d1183
train
Try this this.geometry = new THREE.CubeGeometry(100, 100, 100); this.mesh = new THREE.Mesh(this.geometry, new THREE.MeshFaceMaterial(materials)); A: maybe try to work with an array. With three.js 49 (dont of if it works with 57) i used this code for a skybox with different materials: var axes = new THREE.AxisHelper(); scene.add( axes ); var materialArray = []; materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) })); materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) })); materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) })); materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) })); materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) })); materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) })); var skyboxGeom = new THREE.CubeGeometry( 5000, 5000, 5000, 1, 1, 1, materialArray ); var skybox = new THREE.Mesh( skyboxGeom, new THREE.MeshFaceMaterial() ); skybox.flipSided = true; scene.add( skybox ); A: Try this also, applying the vertexcolors. var geom = new THREE.BoxGeometry(20, 20, 20); var faceIndices = ['a', 'b', 'c']; var vertexIndex, point; mat = new THREE.MeshBasicMaterial({ vertexColors: THREE.VertexColors }); mesh = new THREE.Mesh(geom, mat); scene.add(mesh); geom.faces.forEach(function (face) { // loop through faces for (var i = 0; i < 3; i++) { vertexIndex = face[ faceIndices]; point = geom.vertices[vertexIndex]; color = new THREE.Color( point.x + 0.5, point.y + 0.5, point.z + 0.5 ); face.vertexColors[ i ] = [![the output will be as in the attached picture][1]][1]color; } });
unknown
d1184
train
On one server you need to receive the data (using express & router): router.get('/v1', function(req, res) { // TODO res.render('something'); }); and on the other you need to fetch: var express = require('express'); var router = express.Router(); var app = express() app.use('api1.abc.com', router); router.post('/v1', function(req, res) { // process res }); A: You can write code at version two apis. In request you can pass version on which you need to call. Call all api's on version 2. If it required to call on second server. Write code on version one to identify the call from version 2. So that it can by pass the basic authentication. Thanks,
unknown
d1185
train
When you are passing Counter in Add<Counter, 1>, it's extending the type number, but it's still unknown number. When it's passed from Add to BuildArray, you then have this check: Arr['length'] extends Length? and based on that check, you have different expected types Arr or BuildArray<Length, Ele, [...Arr, Ele]> which will again have the same issue. Going back to Add, in the case of unknown number, TypeScript won't achieve that this length prop is the prop of an Array, which is already a number. So you get the value correctly, but the type itself is still not sure that this is a number, because the check Arr['length'] extends Length? in BuildArray is not resolved to know that the Arr is the type that we are trying to access length from. I am not sure if this was clear enough, but TL;DR: To achieve what you need with the minimum changes, you need to tell TypeScript that this Add type will always be a number instead of relying on TypeScript to learn that by itself. For example, you can force this info by adding & number: type Add<Num1 extends number, Num2 extends number> = [...BuildArray<Num1>, ...BuildArray<Num2>]['length'] & number // βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’βˆ’^^^^^^^^ or have any kind of type checks. Playground link A: This is because here you are extending with number Counter extends number = 0, Result extends number = 0 and your Add<num1, num2> type returns a narrowed number. For example: type AddResult = Add<2, 5> // type AddResult = 7 when you do typeof AddResult, the output would be 7 (for TS it is unknown) and not number and that's why the error occured.
unknown
d1186
train
Add a non-breaking space as a content in your empty para. More like <row> <entry align="center" valign="top" colname="col1" colsep="1" rowsep="1"><para>&#x00A0;</para></entry> <entry align="left" valign="top" colname="col2" colsep="1" rowsep="1"><para>&#x00A0;</para></entry> </row>
unknown
d1187
train
From the docs unique:table,column,except,idColumn The field under validation must be unique in a given database table. If the column option is not specified, the field name will be used. Specifying A Custom Column Name: 'email' => 'unique:users,email_address' You may need to specify the column to be checked against. A: $feauturescheck= Feauture::where('Columname', '=',Input::get('input'))->count();
unknown
d1188
train
You could try using action caching to have it only render the action once. Then you can utilize cache sweepers to invalidate the cached js when you make any updates that would change the information in the js. I think that really might be your best option. Your going to go through a lot more trouble trying to get precompiled dynamic JS like that, especially if the content has a tendency to change at all.
unknown
d1189
train
Don't manually recurse if you can use standard tools. You can do this with sorting and grouping, but IMO preferrable is to use the types to express that you're building an associative result, i.e. a map from marks to students. import qualified Data.Map as Map splitToGroups :: [Student] -> Map.Map Mark [String] splitToGroups students = Map.fromListWith (<>) [ (sMark, [sName]) | Student sName sMark <- students ] (If you want a list in the end, just use Map.toList.) A: If you view Student as a tupple, your function has this type: splitToGroups :: [(Mark,String)] -> [(Mark, [String])]. So you need a function with type: [(a,b)] -> [(a,[b])]. Using Hoogle: search results I get the following functions: groupSort :: Ord k => [(k, v)] -> [(k, [v])] collectSndByFst :: Ord a => [(a, b)] -> [(a, [b])] They should solve your problem, remember to import the modules listed in the link to make them work. You should make a funtion that maps from Student -> (Mark, String) first.
unknown
d1190
train
Forgot to have public setters in SystemConsumerConfiguration. Should be like this: public class SystemConsumerConfiguration { public int SystemId { get; set; } public Uri CallbackUrl { get; set; } public SystemConsumerConfiguration() { } public SystemConsumerConfiguration(int systemId, Uri callbackUrl) { SystemId = systemId; CallbackUrl = callbackUrl; } } Answered in: Default value in an asp.net mvc view model
unknown
d1191
train
The DataContractJsonSerializer can handle JSON serialization but it's not as powerful as some of the libraries for example it has no Parse method. This might be a way to do it without libraries as I beleive Mono has implemented this class. To get more readable JSON markup your class with attributes: [DataContract] public class SomeJsonyThing { [DataMember(Name="my_element")] public string MyElement { get; set; } [DataMember(Name="my_nested_thing")] public object MyNestedThing { get; set;} } A: Below is my implementation using the DataContractJsonSerializer. It works in mono 2.8 on windows and ubuntu 9.04 (with mono 2.8 built from source). (And, of course, it works in .NET!) I've implemented some suggestions from Best Practices: Data Contract Versioning . The file is stored in the same folder as the exe (not sure if I did that in the best manner, but it works in win and linux). using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using NLog; [DataContract] public class UserSettings : IExtensibleDataObject { ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; } [DataMember] public int TestIntProp { get; set; } private string _testStringField; } public static class SettingsManager { private static Logger _logger = LogManager.GetLogger("SettingsManager"); private static UserSettings _settings; private static readonly string _path = Path.Combine( Path.GetDirectoryName( System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName), "settings.json"); public static UserSettings Settings { get { return _settings; } } public static void Load() { if (string.IsNullOrEmpty(_path)) { _logger.Trace("empty or null path"); _settings = new UserSettings(); } else { try { using (var stream = File.OpenRead(_path)) { _logger.Trace("opened file"); _settings = SerializationExtensions.LoadJson<UserSettings>(stream); _logger.Trace("deserialized file ok"); } } catch (Exception e) { _logger.TraceException("exception", e); if (e is InvalidCastException || e is FileNotFoundException || e is SerializationException ) { _settings = new UserSettings(); } else { throw; } } } } public static void Save() { if (File.Exists(_path)) { string destFileName = _path + ".bak"; if (File.Exists(destFileName)) { File.Delete(destFileName); } File.Move(_path, destFileName); } using (var stream = File.Open(_path, FileMode.Create)) { Settings.WriteJson(stream); } } } public static class SerializationExtensions { public static T LoadJson<T>(Stream stream) where T : class { var serializer = new DataContractJsonSerializer(typeof(T)); object readObject = serializer.ReadObject(stream); return (T)readObject; } public static void WriteJson<T>(this T value, Stream stream) where T : class { var serializer = new DataContractJsonSerializer(typeof(T)); serializer.WriteObject(stream, value); } }
unknown
d1192
train
I cannot replicate the problem, as there is inadequate information about the type of data, thus suggesting a fix to the error message. But from your problem description, I think cdist function from scipy.spatial* could solve your problem. As you have not provided an example data row, I created an integer matrix A. from scipy.spatial.distance import cdist A=np.random.randint(10, size=(10,10)) B=cdist(A, A, metric='euclidean') B is a symmetric matrix, naturally. * https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html
unknown
d1193
train
You can have an autoscale group work across availability zones, but not across regions. Though it is possible to have an ASG in a single AZ, you would certainly want the ASG to be in multiple AZ's, otherwise you have no real fault tolerance in the case where an AZ has problems.
unknown
d1194
train
fwrite is for writing to a file, but you want to set memory to zero, which is not quite the same thing. With this line of code, the whole triple structure is set to zero. memset(&triple, 0, sizeof triple); A: Fourth argument of fwrite should be opened for writing FILE Giving zero has result in exception FILE * aFileYouWrite = fopen("afilename.xyz","wb"); memset(&triple, 0, sizeof triple); fwrite(&triple.rgbtRed, sizeof(uint8_t), 1, aFileYouWrite );
unknown
d1195
train
If all list items are integers, we can use clpfd! :- use_module(library(clpfd)). We define zmin_deleted/2 using maplist/2, (#=<)/2, same_length/2, and select/3: zmin_deleted(Zs1,Zs0) :- same_length(Zs1,[_|Zs0]), maplist(#=<(Min),Zs1), select(Min,Zs1,Zs0). Sample queries: ?- zmin_deleted([3,2,7,8],Zs). Zs = [3,7,8] ; false. ?- zmin_deleted([3,2,7,8,2],Zs). Zs = [3, 7,8,2] ; Zs = [3,2,7,8 ] ; false. Note that zmin_deleted/2 also works in the "other direction": ?- zmin_deleted(Zs,[3,2,7,8]). _A in inf..2, Zs = [_A, 3, 2, 7, 8] ; _A in inf..2, Zs = [ 3,_A, 2, 7, 8] ; _A in inf..2, Zs = [ 3, 2,_A, 7, 8] ; _A in inf..2, Zs = [ 3, 2, 7,_A, 8] ; _A in inf..2, Zs = [ 3, 2, 7, 8,_A] ; false. A: Let me google it for you. How could you find a minimum of a list.. Anyway, there is a nice min_list predicate. ?- min_list([1,2,2,3],X). X = 1. Here is a little example how could you remove some element from a list (notice, that all 2s is gone): ?- delete([1,2,2,3],2,X). X = [1, 3]. If you wanna remove only first occasion of a element, use select: ?- select(2, [2,1,2,2,3], X), !. X = [1, 2, 2, 3]. So your final answer could be something like that: delete_min(A, C) :- min_list(A, B), select(B, A, C), !. And ?- delete_min([1,1,2,3],X). X = [1, 2, 3]. A: Again, just use the structural recursion on lists. Lists are built of nodes, [H|T], i.e. compound data structures with two fields - head, H, and tail, T. Head is the data (list element) held in the node, and T is the rest of the list. We find minimum element by rolling along the list, while keeping an additional data - the minimum element from all seen so far: minimum_elt([H|T],X):- minimum_elt(T,H,X). There is no definition for the empty list case - empty lists do not have minimum elements. minimum_elt([],X,X). If there are no more elements in the list, the one we have so far is the answer. minimum_elt([A|B],M,X):- two cases here: A < M, or otherwise: A < M, minimum_elt(B,A,X). minimum_elt([A|B],M,X):- A >= M, minimum_elt(B,M,X). Nothing more to say about it, so this completes the program. edit: except, you wanted to also delete that element. This changes things. Hmm. One obvious approach is first find the minimum elt, then delete it. We'll have to compare all elements once again, this time against the minimal element found previously. Can we do this in one scan? In Lisp we could have. To remove any element from a list, surgically, we just reset the tail pointer of a previous node to point to the next node after the one being removed. Then using this approach, we'd scan the input list once, keeping the reference to the previous node to the minimum element found so far, swapping it as we find the smaller and smaller elements. Then when we've reached the end of the list, we'd just surgically remove the minimal node. But in Prolog, we can't reset things. Prolog is a set once language. So looks like we're stuck with the need to pass over the list twice ... or we can try to be very smart about it, and construct all possible lists as we go, sorting them out each time we find the new candidate for the smallest element. rem_min([A|B],L):- % two possibilities: A is or isn't the minimum elt rem_min(B,A,([A|Z],Z,Z),L). rem_min([],A,(With,Without,Tail),L):- Tail = [], % A is indeed the minimal element L = Without. rem_min([H|T],A,(With,Without,Tail),L):- H >= A, Tail=[H|Z], rem_min(T,A,(With,Without,Z),L). rem_min([H|T],A,(With,Without,Tail),L):- H < A, % use this H copy_the_list(With,Tail,W2,T2), % no good - quadratic behaviour Tail=[H|Z], T2=Z, rem_min(T,A,(With,W2,Z),L). copy_the_list([A|B],T,[A|C],C):- var(B), !, T=B. % fresh tail copy_the_list([A|B],T,[A|C],T2):- copy_the_list(B,T,C,T2). So looks like we can't avoid the second pass, but at least we can save all the superfluous comparisons: rem_min([A|B],L):- N=[A|_], rem_min(B,A,N,[N|Z],Z,L). rem_min([],_A,N,L2,Z,L):- Z=[], N=[_,1], % finalize the minimal entry scan(L2,L). rem_min([H|T],A,N,L2,Z,L):- H >= A, Z=[H|Z2], rem_min(T,A,N,L2,Z2,L). rem_min([H|T],A,N,L2,Z,L):- H < A, % use this H N2=[H|_], N=[_], % finalize the non-minimal entry Z=[N2|Z2], rem_min(T,H,N2,L2,Z2,L). scan( [], []). scan( [[_,1]|B],C):- !, scan(B,C). % step over the minimal element scan( [[A]|B],[A|C]):- !, scan(B,C). % previous candidate scan( [A|B], [A|C]):- !, scan(B,C).
unknown
d1196
train
if you are not using virtual enivrements, i suggest you install and use ANACONDA. Solution: for this error i think using Numpy==1.21.4 and Numba==0.53.0 will solve your problem.
unknown
d1197
train
initialize the getAll every time as a new object in getItem() make your fragment class static and create one method in PracticeFragment static PracticeFragment newInstance(int num) { PracticeFragment f = new PracticeFragment(); // Supply num input as an argument. Bundle args = new Bundle(); args.putInt("num", num); f.setArguments(args); return f; } and change in adapter @Override public Fragment getItem(int position) { return PracticeFragment.newInstance(position); } A: Subclassing it fixed the problem!
unknown
d1198
train
first install pipfile pip install pipfile. then just use the parser it provides from pipfile import Pipfile parsed = Pipfile.load(filename=pipfile_path)
unknown
d1199
train
@Mir has done a good job describing the problem. Here's one possible workaround. Since the problem is in generating the name, you can supply your own name tbl_grades %>% mutate_all(funs(recode=recode(.,A = '4.0'))) Now this does add columns rather than replace them. Here's a function that will "forget" that you supplied those names dropnames<-function(x) {if(is(x,"lazy_dots")) {attr(x,"has_names")<-FALSE}; x} tbl_grades %>% mutate_all(dropnames(funs(recode=dplyr::recode(.,A = '4.0')))) This should behave like the original. Although really tbl_grades %>% mutate_all(dropnames(funs(recode(.,A = '4.0')))) because dplyr often has special c++ versions of some functions that it can use if it recognized the functions (like lag for example) but this will not happen if you also specify the namespace (if you use dplyr::lag). A: If we call it without the dplyr:: then it works fine. funs(recode(., A = '4.0')) <fun_calls> $ recode: recode(., A = "4.0") tbl_grades %>% mutate_all(funs(recode(. ,A = '4.0'))) # A tibble: 3 x 3 V1 V2 V3 <chr> <chr> <chr> 1 4.0 C C 2 A- D C 3 B B- F The issue lies in the funs call. If we extract that part out the same error appears. funs(dplyr::recode(., A = '4.0')) Error in vapply(dots[missing_names], function(x) make_name(x$expr), character(1)) : values must be length 1, but FUN(X[[1]]) result is length 3 The issue boils down to the fact that :: is a function itself. (see ?`::`). To visualize this a little better, we look at both the infix and prefix ways of writing the function. `::`(dplyr, recode) function (.x, ..., .default = NULL, .missing = NULL) { UseMethod("recode") } <environment: namespace:dplyr> dplyr::recode function (.x, ..., .default = NULL, .missing = NULL) { UseMethod("recode") } <environment: namespace:dplyr> funs attempts to extract the function names of its arguments by grabbing the first element of the call object and calling as.character on it. The first element of the call object is the calling function and subsequent elements are the argument values. For example: as.call(quote(recall(., A = '4.0'))) recall(., A = "4.0") as.call(quote(recall(., A = '4.0')))[[1]] recall as.call(quote(recall(., A = '4.0')))[[2]] . as.call(quote(recall(., A = '4.0')))[[3]] "4.0" as.call(quote(recall(., A = '4.0')))[[4]] Error in as.call(quote(recall(., A = "4.0")))[[4]] : subscript out of bounds This runs into issues when dplyr::recode is used because this creates a nested call object. When we grab the first element, we get not just a name of a function, but an entire function call. as.call(quote(dplyr::recall(., A = '4.0'))) dplyr::recall(., A = "4.0") as.call(quote(dplyr::recall(., A = '4.0')))[[1]] dplyr::recall as.call(quote(dplyr::recall(., A = '4.0')))[[1]][[1]] `::` as.call(quote(dplyr::recall(., A = '4.0')))[[1]][[2]] dplyr as.call(quote(dplyr::recall(., A = '4.0')))[[1]][[3]] recall In contrast to when recode is called without dplyr::. as.call(quote(recall(., A = '4.0')))[[1]][[1]] Error in as.call(quote(recall(., A = "4.0")))[[1]][[1]] : object of type 'symbol' is not subsettable Because the first element when dplyr:: is included is a whole function call, as.character results in a vector that has both the name of a function and its arguments. as.call(quote(dplyr::recall(., A = '4.0')))[[1]] %>% as.character() [1] "::" "dplyr" "recall" Funs reasonably expects the name of the function to have only one element, not three, and thus errors out.
unknown
d1200
train
Try something like this for simplicity. Give them all the same class but use id for Brand or Series. I'm writing this without testing sorry but you can move all you functions into 1. Basic Idea you will need to tweak. Also I may have even over complicated it with static variables. But at least you can keep track of the values. $(".series_select").change(function(){ var value = $(this).val(), type = $(this).attr('id'), data, self = $(this); if(type == "brand"){ data = "brand=" + value; $(".series_select").change.brand = value; } else if (type == "series"){ data = "brand=" + $(".series_select").change.brand + "&series=" + value; $(".series_select").change.series = value; } else if( type == "submit"){ if($(".series_select").change.brand != '' && $(".series_select").change.series != ''){ $('#userVideos').submit(); return; } } $.ajax({ type: "GET", url: "model.php", data: data, success: function(html){ self.html(html); } }); });
unknown