_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
21
37k
language
stringclasses
1 value
title
stringclasses
1 value
d1
train
The SearchDatabase class that SphinxSearch extends was changed from REL1_31 to REL1_32. It now requires you to define doSearchTextInDB and doSearchTitleInDB methods. See REL1_31 https://doc.wikimedia.org/mediawiki-core/REL1_31/php/classSearchDatabase.html vs REL1_32 https://doc.wikimedia.org/mediawiki-core/REL1_32/php/classSearchDatabase.html This is sortof mentioned in the patch notes if you search for Search under deprecation (note this is a Backwards compatibility break instead) https://www.mediawiki.org/wiki/Release_notes/1.32#Compatibility: Overriding SearchEngine::{searchText,searchTitle,searchArchiveTitle} in extending classes is deprecated. Extend related doSearch* methods instead. If you are like me and not comfortable fixing the extension yourself, you will have to wait for one of the extension contributors to update the extension to work with REL1_32. Until then you will have to stay on REL1_31 if you wish to use the extension. A: Just adding these two empty functions to SphinxMWSearch.php under the definition of SphinxMWSearch class seems to do the trick. It makes it stop complaining and - as far as I can tell - search function is working fine. function doSearchTextInDB($term) { } function doSearchTitleInDB($term) { } Hopefully developers of this extension will come up with a proper fix soon.
unknown
d3
train
A table view isn't really designed to display hierarchical views. What's supposed to happen is that you drill down (push a new view controller on the stack) to get to the next level of the hierarchy. However, if your hierarchy is only as deep as you suggest, then you could have your items as headers and subitems as rows. If you don't want to create a custom view (why not?) you'd be limited to just text for your top level items.
unknown
d5
train
Open returns a *sql.DB, a pointer to a sql.Db. Change the function signature to also return a *sql.DB: func establish_db_connection() *sql.DB {
unknown
d9
train
Use synchronous ajax call.Synchronous AJAX (Really SJAX -- Synchronous Javascript and XML) is modal which means that javascript will stop processing your program until a result has been obtained from the server. While the request is processing, the browser is effectively frozen. function getFile(url) { if (window.XMLHttpRequest) { AJAX=new XMLHttpRequest(); } else { AJAX=new ActiveXObject("Microsoft.XMLHTTP"); } if (AJAX) { AJAX.open("GET", url, false); //notice the 'false' attribute AJAX.send(null); return AJAX.responseText; } else { return false; } } If you are using jQuery then put async:false in your ajax call var fileFromServer = getFile('http://somedomain.com/somefile.txt');
unknown
d13
train
You are trying to print byte[] as a String which uses String.valueOf(bytes) and appears as something like: [B@23ab930d which is [B followed by the hashcode of the array. Hence different byte arrays have different string values. Compare these: byte[]a=new byte[]{65}; System.out.println(new String(a)); => A System.out.println(a); // Prints something like: [B@6438a396 Change to print the byte array contents converted as a String: System.out.println(new String(bytes)); OR: read the text file as a String directly: String contents = Files.readString(file.toPath()); System.out.println(contents);
unknown
d15
train
You'll be wanting the - (void)setStatusBarHidden:(BOOL)hidden animated:(BOOL)animated on the UIApplication class. Something like this: [[UIApplication sharedApplication] setStatusBarHidden:YES animated:YES]; That should hide the status bar with a nice fade animation. A: Joining the discusion late, but I think I can save others some trouble. I have a VC several pushes into a NavController (let's call that VC the PARENT). Now I want to display a modal screen (the CHILD) with the nav bar AND status bar hidden. After much experimentation, I know this works... 1) Because I present the CHILD VC by calling presentModalViewController:(UIViewController *)modalViewController animated:(BOOL)animated in the PARENT, the nav bar is not involved anymore (no need to hide it). 2) The view in the CHILD VC nib is sized to 320x480. 3) The CHILD VC sets self.wantsFullScreenLayout = YES; in viewDidLoad 4) just before presenting the CHILD, hide the status bar with [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:YES]; 5) dismiss the CHILD VC using a delegate protocol methods in the PARENT, and call [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:YES]; before dismissModalViewControllerAnimated:YES] to make sure the nav bar is drawn in the correct location Hope this helps.
unknown
d17
train
You are calling urllib.request.urlopen(req).read, correct syntax is: urllib.request.urlopen(req).read() also you are not closing the connection, fixed that for you. A better way to open connections is using the with urllib.request.urlopen(url) as req: syntax as this closes the connection for you. from bs4 import BeautifulSoup import urllib import html5lib class Websites: def __init__(self): self.header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"} def free_proxy_list(self): print("Connecting to free-proxy-list.net ...") url = "https://free-proxy-list.net" req = urllib.request.Request(url, None, self.header) content = urllib.request.urlopen(req) html = content.read() soup = BeautifulSoup(str(html), "html5lib") print("Connected. Loading the page ...") print("Print page") print("") print(soup.prettify()) content.close() # Important to close the connection For more info see: https://docs.python.org/3.0/library/urllib.request.html#examples
unknown
d21
train
fixed it: items.sort(key = lambda x:((float)(x.price), (int)(x.amount)))
unknown
d23
train
you can use the format string in for the date string url = string.Format("someUrl/SomeControllerName/WriteLogFile/{0}/{1}", currentId, DateTime.Now.ToString("MM-dd-yyyy")); and add an entry in to the routes table to route it to the appropriate controller and action routes.MapRoute("SomeRoutename", "SomeControllerName/WriteLogFile/{id}/{date}", new { controller = "SomeControllerName", action = "WriteLogFile", date= DateTime.Now}); A: Add a query string parameter: var toWrite = DateTime.Now; string url = string.Concat(someUrl, "SomeControllerName/", currentId, "/WriteLogFile"); url = string.Concat(url, "?date=", toWrite.ToString("s"));
unknown
d25
train
Nothing stops you from creating claims to store extra information in your token if they can be useful for your client. However I would rely on JWT only for authentication (who the caller is). If you need to perform authorization (what the caller can do), look up the caller roles/permissions from your persistent storage to get the most updated value. For short-lived tokens (for example, when propagating authentication and authorization in a microservices cluster), I find it useful to have the roles in the token. A: As mentioned here, ASP.NET Core will automatically detect any roles mentioned in the JWT: { "iss": "http://www.jerriepelser.com", "aud": "blog-readers", "sub": "123456", "exp": 1499863217, "roles": ["Admin", "SuperUser"] } and 'map' them to ASP.NET Roles which are commonly used to secure certain parts of your application. [Authorize(Roles = "Admin")] public class SettingsController : Controller The server which is giving out (and signing) the JWT is commonly called an authorization server and not just an authentication server, so it makes sense to include role information (or scope) in the JWT, even though they're not registered claims. A: The official JWT site explicitly mentions "authorization" (in contrast to "authentication") as a usecase for JWTs: When should you use JSON Web Tokens? Authorization: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains. That being said, from a security-perspective you should think twice whether you really want to include roles or permissions in the token. (The text below can be understood as a more "in-depth" follow up to the rather short-kept accepted answer) Once you created and signed the token you grant the permission until the token expires. But what if you granted admin permissions by accident? Until the token expires, somebody is now operating on your site with permissions that were assigned by mistake. Some people might argue that the token is short-lived, but this is not a strong argument given the amount of harm a person can do in short time. Some other people advocate to maintain a separate blacklist database table for tokens, which solves the problem of invalidating tokens, but adds some kind of session-state tracking to the backend, because you now need to keep track of all current sessions that are out there – so you would then have to make a db-call to the blacklist every time a request arrives to make sure it is not blacklisted yet. One may argue that this defeats the purpose of "putting the roles into the JWT to avoid an extra db-call" in the first place, since you just traded the extra "roles db-call" for an extra "blacklist db-call". So instead of adding authorization claims to the token, you could keep information about user roles and permissions in your auth-server's db over which you have full control at any time (e.g. to revoke a certain permission for a user). If a request arrives, you fetch the current roles from the auth-server (or wherever you store your permissions). By the way, if you have a look at the list of public claims registered by the IANA, you will see that these claims evolve around authentication and are not dealing with what the user is allowed to do (authorization). So in summary you can... * *add roles to your JWT if (a) convenience is important to you and (b) you want to avoid extra database calls to fetch permissions and (c) do not care about small time windows in which a person has rights assigned he shouldn't have and (d) you do not care about the (slight) increase in the JWT's payload size resulting from adding the permissions. *add roles to your JWT and use a blacklist if (a) you want to prevent any time windows in which a person has rights assigned he shouldn't have and (b) accept that this comes at the cost of making a request to a blacklist for every incoming request and (c) you do not care about the (slight) increase in the JWT's payload size resulting from adding the permissions. *not add roles to your JWT and fetch them on demand if (a) you want to prevent any time windows in which a person has rights assigned he shouldn't have or (b) avoid the overhead of a blacklist or (c) avoid increasing the size of your JWT payload to increase slightly and (d) if you accept that this comes at the cost of sometimes/always querying the roles on incoming requests.
unknown
d29
train
Qt needs it because it is a library that can be dynamically loaded. Users can compile and link without having to worry about implementation details. You can at runtime use many versions of Qt without having to recompile. This is pretty powerful and flexible. This wouldn't be possible if private object instances were used inside classes. A: It depends. Reducing dependencies is definitely a good thing, per se, but it must be weighed against all of the other issues. Using the compilation firewall idiom, for example, can move the dependencies out of the header file, at the cost of one allocation. As for what QT does: it's a GUI framework, which (usually---I've not looked at QT) means lots of polymorphism, and that most classes have identity, and cannot be copied. In such cases, you usually do have to use dynamic allocation and work with pointers. The rule to avoid pointers mainly concerns objects with value semantics. (And by the way, there's nothing "old-fashioned" or "out-of-date" about using too many pointers. It's been the rule since I started using C++, 25 years ago.)
unknown
d33
train
I suggest to add a con.BeginTransaction() before the ExecuteNonQuery and a con.Commit() after the ExecuteNonQuery. A: You should open the connection before you make the command instance, like this: void metroButton1_Click(object sender, EventArgs e) { try { con = new SqlConnection(cs.DBcon); con.Open(); //Open the connection for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { using (SqlCommand cmd = new SqlCommand("INSERT INTO tbl_employee VALUES(@Designation, @Date, @Employee_name,@Leave,@L_Reason,@Performance,@Payment,@Petrol,@Grand_Total)", con)) //Now create the command { cmd.Parameters.AddWithValue("@Designation", dataGridView1.Rows[i].Cells[0].Value); cmd.Parameters.AddWithValue("@Date", dataGridView1.Rows[i].Cells[1].Value); cmd.Parameters.AddWithValue("@Employee_name", dataGridView1.Rows[i].Cells[2].Value); cmd.Parameters.AddWithValue("@Leave", dataGridView1.Rows[i].Cells[3].Value); cmd.Parameters.AddWithValue("@L_Reason", dataGridView1.Rows[i].Cells[4].Value); cmd.Parameters.AddWithValue("@Performance", dataGridView1.Rows[i].Cells[5].Value); cmd.Parameters.AddWithValue("@Payment", dataGridView1.Rows[i].Cells[6].Value); cmd.Parameters.AddWithValue("@Petrol", dataGridView1.Rows[i].Cells[7].Value); cmd.Parameters.AddWithValue("@Grand_Total", dataGridView1.Rows[i].Cells[8].Value); cmd.ExecuteNonQuery(); } } con.Close(); MessageBox.Show("Records inserted."); } catch (Exception ex) { MessageBox.Show(ex.Message); } } A: Perform everything inside connection as below void metroButton1_Click(object sender, EventArgs e) { try { for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { using(SqlConnection connection = new SqlConnection(cs.DBcon)) { connection.Open(); cmd.Parameters.AddWithValue("@Designation", dataGridView1.Rows[i].Cells[0].Value); cmd.Parameters.AddWithValue("@Date", dataGridView1.Rows[i].Cells[1].Value); cmd.Parameters.AddWithValue("@Employee_name", dataGridView1.Rows[i].Cells[2].Value); cmd.Parameters.AddWithValue("@Leave", dataGridView1.Rows[i].Cells[3].Value); cmd.Parameters.AddWithValue("@L_Reason", dataGridView1.Rows[i].Cells[4].Value); cmd.Parameters.AddWithValue("@Performance", dataGridView1.Rows[i].Cells[5].Value); cmd.Parameters.AddWithValue("@Payment", dataGridView1.Rows[i].Cells[6].Value); cmd.Parameters.AddWithValue("@Petrol", dataGridView1.Rows[i].Cells[7].Value); cmd.Parameters.AddWithValue("@Grand_Total", dataGridView1.Rows[i].Cells[8].Value); cmd.ExecuteNonQuery(); connection.Close(); } } MessageBox.Show("Records inserted."); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
unknown
d35
train
to convert json array to tuple: feed = LOAD '$INPUT' USING com.twitter.elephantbird.pig.load.JsonLoader() AS products_json; extracted_products = FOREACH feed GENERATE products_json#'id' AS id:chararray, products_json#'name' AS name:chararray, products_json#'colors' AS colors:{t:(i:chararray)}, products_json#'sizes' AS sizes:{t:(i:chararray)}; to flatten a tuple flattened = foreach extracted_products generate id,flatten(colors);
unknown
d39
train
If I believe issue 1246, you need to have git installed for the hg convert extension to work. Even with Git installed, you might experience some other issues with the import, in which case you could consider other alternatives such as: * *converting the git repo to a svn one, and then importing that svn repo into a mercurial one *or trying the hg-git mercurial plugin, which specifically mentions: This plugin is implemented entirely in Python - there are no Git binary dependencies, you do not need to have Git installed on your system. (But I don't know if hg-git works with recent 1.7+ Mercurial versions)
unknown
d47
train
These conditions can be prioritized using a case expression in order by with a function like row_number. select A,B,frequency,timekey from (select t.* ,row_number() over(partition by A order by cast((B = 'unknown') as int), B) as rnum from tbl t ) t where rnum = 1 Here for each group of A rows, we prioritize rows other than B = 'unknown' first, and then in the order of B values. A: Use row_number analytic function. If you want to select not unknown record first, then use the query below: select A, B, Frequency, timekey from (select A, B, Frequency, timekey, row_number() over(partition by A,Frequency order by case when B='unknown' then 1 else 0 end) rn )s where rn=1 And if you want to select unknown if they exist, use this row_number in the query above: row_number() over(partition by A,Frequency order by case when B='unknown' then 0 else 1 end) rn
unknown
d49
train
Slice a 2D Array * *It is assumed that the data starts in A1 and has a row of headers. *You have to use 7 instead of 8 to copy column G instead of column H. *[A1].CurrentRegion.Rows.Count may yield different results depending on which worksheet is active, so you should rather qualify the range: rp.Range("A1").CurrentRegion.Rows.Count. *rp.Range("A1").CurrentRegion.Rows.Count may be different than rp.Range("H" & rp.Rows.Count).End(xlUp).Row, so you should opt for one (I've opted for the former). *A quick fix could be [a1].CurrentRegion.Rows.Count - 1, but is not recommended due to the previous two reasons. rp.Range("A1").CurrentRegion.Rows.Count - 1 would be better. *Both solutions do the same except for the out-commented 'exclude-headers-parts' in the first solution, which you could use to not include the headers, and the 'clear-contents-part' in the second solution, which you could use to clear the contents below the destination range. *Adjust the values in the constants section, the workbook reference, and if headers should be excluded (and if the contents below the destination range should be cleared). Option Explicit Sub sliceArray() Const sName As String = "RESOURCE_PLANNING" Const sCols As String = "A:H" Const dName As String = "RP_Output" Const dFirst As String = "A1" Dim dCols As Variant: dCols = VBA.Array(1, 2, 4, 6, 8) ' 'VBA': zero-based Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code 'Dim wb As Workbook: Set wb = ActiveWorkbook ' workbook you're looking at ' Source Worksheet Dim sws As Worksheet: Set sws = wb.Worksheets(sName) ' Source/Destination Rows Count Dim rCount As Long: rCount = sws.Range("A1").CurrentRegion.Rows.Count ' No headers 'Dim rCount As Long: rCount = sws.Range("A1").CurrentRegion.Rows.Count - 1 ' Source Array Dim sData As Variant sData = sws.Columns(sCols).Resize(rCount).Value ' No headers 'sData = sws.Columns(sCols).Resize(rCount).Offset(1).Value ' Destination Array Dim dData As Variant dData = Application.Index(sData, Evaluate("Row(1:" & rCount & ")"), dCols) ' Destination Columns Count Dim dcCount As Long: dcCount = UBound(dCols) + 1 ' = UBound(dData, 2) ' Destination Worksheet Dim dws As Worksheet: Set dws = wb.Worksheets(dName) ' Destination Range Dim drg As Range: Set drg = dws.Range(dFirst).Resize(rCount, dcCount) ' Write drg.Value = dData End Sub Sub sliceArrayShort() Const sName As String = "RESOURCE_PLANNING" Const sCols As String = "A:H" Const dName As String = "RP_Output" Const dFirst As String = "A1" Dim dCols As Variant: dCols = VBA.Array(1, 2, 4, 6, 8) Dim wb As Workbook: Set wb = ThisWorkbook ' Read Dim rCount As Long Dim sData As Variant With wb.Worksheets(sName) rCount = .Range("A1").CurrentRegion.Rows.Count sData = .Columns(sCols).Resize(rCount).Value End With ' Slice Dim dData As Variant dData = Application.Index(sData, Evaluate("Row(1:" & rCount & ")"), dCols) ' Write (& Clear) With wb.Worksheets(dName).Range(dFirst).Resize(, UBound(dCols) + 1) .Resize(rCount).Value = dData '.Resize(.Worksheet.Rows.Count - .Row - rCount + 1) _ .Offset(rCount).ClearContents End With End Sub
unknown
d51
train
You can query the "through" table directly with the ORM: UserProfile.favorite_books.through.objects.filter(book_id=book.id).count() A: You'll need to replace appname_* with the name of the M2M table in your DB, but you can do something like this: from django.db import connections cursor = connections['default'].cursor() cursor.execute(""" SELECT count(*) FROM appname_userprofile_books WHERE book_id = {book_id}; """.format(book_id=book_id)) favorited_count_list = cursor.fetchall() You can then pull the number from favorited_count_list.
unknown
d53
train
It's not that difficult once you understand why the second form isn't shown when page is loaded. There's nothing to do with ASP itself, it's rather due to CSS style set to "display: none;" and will only be active once the first Option Select has been filled. Here is a full sample of what you're after, implemented in Selenium, it's similar to machanize I believe. The basic flow should be: * *load the web browser and load the page *find the first Option Select and fill it in *trigger a change event (I chose to send a TAB key) and the second Option Select is shown *fill in the second Select and find the submit button and click it *assign a name to the content you get from the div id=stats text *compared if the text has changed from last fetch a) if YES, do your BEEP and close the driver page etc. b) if NO, set a scheduler (I use Python's Event's Scheduler, and run the crawling function again... That's it! Easy, ok code time -- I used United Kingdom + Working Holiday pair for test: import selenium.webdriver from selenium.webdriver.common.keys import Keys import sched, time driver = selenium.webdriver.Firefox() url = 'http://www.cic.gc.ca/english/work/iec/index.asp' driver.get(url) html_content = '' # construct a scheduler s = sched.scheduler(time.time, time.sleep) def crawl_me(): global html_content driver.refresh() time.sleep(5) # wait 5s for page to be loaded country_name = driver.find_element_by_name('country-name') country_name.send_keys('United Kingdom') # trick's here to send a TAB key to trigger the change event country_name.send_keys(Keys.TAB) # make sure the second Option Select is active (none not in style) assert "none" not in driver.find_element_by_id('category_dropdown').get_attribute('style') cateogory_name = driver.find_element_by_name('category-name') cateogory_name.send_keys('Working Holiday') btn_go = driver.find_element_by_id('submit') btn_go.send_keys(Keys.RETURN) # again, check if the content has been loaded assert "United Kingdom - Working Holiday" not in driver.page_source compared_content = driver.find_element_by_id('stats').text # here we will end this script if content has changed already if html_content != '' and html_content != compared_content: # do whatever you want to play the beep sound # at the end exit the loop driver.close() exit(-1) # if no changes are found, trigger the schedule_crawl() function, like recursively html_content = compared_content print html_content return schedule_crawl() def schedule_crawl(): # set your time interval here, 15*60 = 15 minutes s.enter(15*60, 1, crawl_me, ()) s.run() # and run it of course crawl_me() To be honest, this is quite easy and straight forward however it does require you fully understand how html/css/javascript (not javascript in this case, but you do need to know the basic) and all their elements how they work together. You do need to learn from the basic read => digest => code => experience => do it in cycles, Programming doesn't have a shortcut or the fastest way. Hope this helps (and I really hope you do not just copy & paste mine, but learn and implement your own in mechanize by the way). Good Luck!
unknown
d55
train
1) Windows Sysinternals VMMap can give you quite good insight into the virtual memory layout in a particular process. If comparing visualizations provided by this tool on the 2 PCs does not help then... 2) ...Google: "virtual memory configuration windows 7" should throw you quite quickly in the right direction 3) Also in your original question https://stackoverflow.com/q/25263223/2626313 the problem with exact address may be that the address range is already used by a hardware component. You can check that by using Control Panel → Device Manager, switch menu View → Resources by type and check what you see under the Memory node 4) finally this https://superuser.com/a/61604/304578 article contains link to Mark Russinovich's (original author of the Windows Sysinternals tool set) explaining blog article perhaps related to your problem
unknown
d57
train
Try this below code : $email = 'example@email.com'; $customer = Mage::getModel('customer/customer'); $customer->setWebsiteId(Mage::app()->getWebsite()->getId()); $customer->loadByEmail(trim($email)); Mage::getSingleton('customer/session')->loginById($customer->getId());
unknown
d59
train
In pseudo code using information_schema tables: $rows = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'yourDBName' AND ENGINE LIKE 'engineA'"; foreach ($rows as $table) { $query = 'ALTER TABLE '.$table.' ENGINE = engineB'; }
unknown
d63
train
It is now possible to using bindings even on elements that aren't derived from FrameworkElement however the property of the element being bound must be defined as a DependencyProperty which Header is not. Since Header is simply a place marker for any content to be placed in the header you could simply do this:- <DataGridTextColumn.Header> <TextBlock Text="{Binding Path=Dummy,Source={StaticResource languagingSource},Converter={StaticResource languagingConverter},ConverterParameter=vehicleDescription}" /> </DataGridTextColumn.Header> A: After some further searching I found this thread that answers the question and gives some suggested solutions. Dynamically setting the Header text of a Silverlight DataGrid Column
unknown
d69
train
Tables inside dialogs work just fine in Vuetify: var app = new Vue({ el: '#app', template: '#main', vuetify: new Vuetify(), data: { dlgVisible: false, header: [ { value: 'fname', text: 'First Name' , class: 'font-weight-bold text-subtitle-1', }, { value: 'lname', text: 'Last Name' , class: 'font-weight-bold text-subtitle-1', }, { value: 'salary', text: 'Salary' , class: 'font-weight-bold text-subtitle-1', }, ], rows: [ { fname: 'John', lname: 'Doe', salary: 1000 }, { fname: 'John', lname: 'Doe', salary: 1000 }, { fname: 'John', lname: 'Doe', salary: 1000 }, ], }, }); <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.x/css/materialdesignicons.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"> <div id="app"> </div> <template id="main"> <v-app> <v-btn color="primary" @click="dlgVisible = true">Show dialog</v-btn> <v-dialog v-model="dlgVisible"> <v-card> <v-card-title class="primary white--text py-2">Dialog</v-card-title> <v-card-text> <v-data-table :items="rows" :headers="header"> </v-data-table> </v-card-text> <v-card-actions class="justify-center"> <v-btn color="primary" @click="dlgVisible = false">Close</v-btn> </v-card-actions> </v-card> </v-dialog> </v-app> </template> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
unknown
d71
train
Since you are using LINQ to SQL you should use Convert.ToInt32 for converting to string to number, so your query would be: var bb =(from c in Office_TBLs select Convert.ToInt32(c.CodeNumber)).Max(); See: Standard Query Operator Translation C# casts are supported only in projection. Casts that are used elsewhere are not translated and are ignored. Aside from SQL function names, SQL really only performs the equivalent of the common language runtime (CLR) Convert. That is, SQL can change the value of one type to another. There is no equivalent of CLR cast because there is no concept of reinterpreting the same bits as those of another type. That is why a C# cast works only locally. It is not remoted. A: "999" > "1601" as string comparison - so to get result you want you need to convert string values to numbers. The easiest approach would be to use .Select(s => int.Parse(s)).Max()) (or .Max(s => int.Parse(s))) instead of .Max() which ends up using regular string comparison. Note that depending on where data is coming from there could be much better ways to get integer results (including changing field type in database). Using .Select on query most likely force query to return all rows from DB and only than compute Max in memory. A: Try this var bb=(from c in Office_TBLs select (e => e.CodeNumber).Max()) A: If you use NVarChar then you are asking to have the values sorted alphabetically. "999" comes after "1601" just like "ZZZ" comes after "HUGS". If the column is supposed to only contain numeric values then the best fix is to change the datatype to a more appropriate choice.
unknown
d75
train
You are looking for text-transform: uppercase and nth-child selector. Something like this: header nav ul li:nth-child(-n+2) { text-transform: uppercase; } <header> <h1>Title</h1> <nav> <ul> <li><a href="#">Developers</a></li> <li><a href="#">Designers</a></li> <li><a href="#">How it Works</a></li> <li><a href="#">Our Team</a></li> <li><a href="#">Blog</a></li> </ul> </nav> </header> A: You can use nth-of-type(). For your example you will want to use nth-of-type on the <li>. header nav li:nth-of-type(-n+2) { text-transform: capitalize; } https://jsfiddle.net/qfLrsdwr/1 My JSFiddle has slightly different selectors and markup for demonstration purposes. <header> <h1>Title</h1> <nav class="primary-nav"> <ul> <li><a href="#">Developers</a></li> <li><a href="#">Designers</a></li> <li><a href="#">How it Works</a></li> <li><a href="#">Our Team</a></li> <li><a href="#">Blog</a></li> </ul> </nav> </header> .primary-nav li { text-transform: lowercase; } .primary-nav li:nth-of-type(-n+2) { text-transform: capitalize; }
unknown
d77
train
Unfortunately they cannot. All of the parameters that you can configure through the Google Kubernetes Engine API are here. If you want to customize the nodes beyond what is offered through the API you can create your own instance template as described in this stackoverflow answer. The downside is that you will no longer be able to manage the nodes via the Google Kubernetes Engine API (e.g. for upgrading).
unknown
d85
train
Set both columns in a single foreach loop.
unknown
d87
train
if this is a browser activity, a better way to do this may be a javascript setInverval() with an ajax call to a php function. Otherwise, I'd recommend running the PHP script via CRON. There's no other way that I know to run PHP asynchronously, which is probably what you're trying to accomplish.
unknown
d89
train
You could use the Focused event instead of TextChanged event. <StackLayout> <Entry ClassId="1" x:Name="myWord1" Focused="EntryFocused"/> <Entry ClassId="2" x:Name="myWord2" Focused="EntryFocused"/> </StackLayout> private void EntryFocused(object sender, FocusEventArgs e) { var EntryTapped = (Xamarin.Forms.Entry)sender; if (EntryTapped.ClassId == "1") { myWord2.Text = "Noo"; } else if (EntryTapped.ClassId == "2") { myWord1.Text = "yess"; } } A: There are several ways of doing this: * *Using bindings In this case you would have 2 private variables and 2 public variables, and the entries binded to each one. Check this link how to implement INotifyPropertyChanged private string entry1String; private string entry2String; public string Entry1String { get => entry1String; set { entry2String = "Noo"; entry1String = value; OnPropertyChanged(Entry1String); OnPropertyChanged(Entry2String); } } public string Entry2String { get => entry2String; set { entry1String = "Yees"; entry2String = value; OnPropertyChanged(Entry1String); OnPropertyChanged(Entry2String); } } Another way could be using a variable as a Semaphore. While the variable is True, the method cannot be fired at the same time by another. private bool semaphoreFlag=false; private async void OnEntryTextChange(object sender, TextChangedEventArgs e) { if(semaphoreFlag) return; semaphoreFlag=true; var EntryTapped = (Xamarin.Forms.Entry)sender; Device.BeginInvokeOnMainThread(() => { if (EntryTapped.ClassId == "1") { myWord2.Text="Noo"; } else if (EntryTapped.ClassId == "2") { myWord1.Text="yess"; } }); semaphoreFlag=false; }
unknown
d91
train
The flash messages are stored in the user's session. If a user opens up two browser windows. And performs some action on one window that causes a flash, but the user reloads a page in the second browser before the first one redirects the second one will show the flash. With that said does that sound like your issue? Does it show the flash twice? Please elaborate and be more specific as to when 'it displays when it shouldn't'. A: Maybe the layout of the page where you want the flash message to show doesn't print flash messages and then it shows up in the layout where you print the flash message
unknown
d95
train
This assumes SQL Server, but the SqlParameter type could be changed to match the connection type. As items are added to this list the data type would have to be identified. Imports System.Data.SqlClient Dim Params As List(Of SqlParameter) Public Property ParameterList() As List(Of SqlParameter) Get Return Params End Get Set(ByVal value As List(Of SqlParameter)) Params = value End Set End Property You'll have to loop through the list and add each parameter to a command object.
unknown
d99
train
Emacs lisp only has dynamic scoping. There's a lexical-let macro that approximates lexical scoping through a rather terrible hack. A: Found another solution with lexical-let (defun foo (n) (lexical-let ((n n)) #'(lambda() n))) (funcall (foo 10)) ;; => 10 A: Emacs 24 has lexical binding. http://www.emacswiki.org/emacs/LexicalBinding A: ;; -*- lexical-binding:t -*- (defun create-counter () (let ((c 0)) (lambda () (setq c (+ c 1)) c))) (setq counter (create-counter)) (funcall counter) ; => 1 (funcall counter) ; => 2 (funcall counter) ; => 3 ... A: Real (Not Fake) Closures in Emacs 24. Although Emacs 24 has lexical scooping when the variable lexical-binding has value t, the defun special form doesn’t work properly in lexically bound contexts (at least not in Emacs 24.2.1.) This makes it difficult, but not impossible, to define real (not fake) closures. For example: (let ((counter 0)) (defun counting () (setq counter (1+ counter)))) will not work as expected because the symbol counter in the defun will be bound to the global variable of that name, if there is one, and not the lexical variable define in the let. When the function counting is called, if the global variable doesn’t, exist then it will obviously fail. Hoever if there is such a global variable it be updated, which is probably not what was intended and could be a hard to trace bug since the function might appear to be working properly. The byte compiler does give a warning if you use defun in this way and presumably the issue will be addressed in some future version of Emacs, but until then the following macro can be used: (defmacro defun** (name args &rest body) "Define NAME as a function in a lexically bound context. Like normal `defun', except that it works correctly in lexically bound contexts. \(fn NAME ARGLIST [DOCSTRING] BODY...)" (let ((bound-as-var (boundp `,name))) (when (fboundp `,name) (message "Redefining function/macro: %s" `,name)) (append `(progn (defvar ,name nil) (fset (quote ,name) (lambda (,@args) ,@body))) (if bound-as-var 'nil `((makunbound `,name)))))) If you define counting as follows: (let ((counter 0)) (defun** counting () (setq counter (1+ counter)))) it will work as expected and update the lexically bound variable count every time it is invoked, while returning the new value. CAVEAT: The macro will not work properly if you try to defun** a function with the same name as one of the lexically bound variables. I.e if you do something like: (let ((dont-do-this 10)) (defun** dont-do-this () ......... .........)) I can’t imagine anyone actually doing that but it was worth a mention. Note: I have named the macro defun** so that it doesn’t clash with the macro defun* in the cl package, however it doesn’t depend in any way on that package. A: Stupid idea: how about: (defun foo (x) `(lambda () ,x)) (funcall (foo 10)) ;; => 10 A: http://www.emacswiki.org/emacs/FakeClosures
unknown
d101
train
Some backend Prolog compilers, such as SWI-Prolog when running on Windows, down-case file names when expanding file paths into absolute file paths. This caused a failure in the Logtalk compiler when going from the file argument in the compilation and loading predicates to an absolute file path and its components (directory, name, and extension). A workaround have been found and committed to the current git version. Thanks for the bug report.
unknown
d103
train
I think the problem lies in your views.py. Try getting request.user before saving the form. A: i think you should have made form for Inventory if yes(let InvntoryForm) than in view.py file you have done something like this:- if request.method == 'POST': Inven_form=InventoryForm(data=request.POST) if Inven_form.is_valid(): user=Inven_form.save() #in between add this Inven_form.updated_by=request.user.username user.save() A: I would use the 'commit=False' argument which will create a new object and assign it without saving to your database. You can then set the user attribute and call save() with no arguments. For example, this is how I assigned the user attribute to my blog app. in views.py if form.is_valid(): # Create a new entry and assign to new_article. new_article = form.save(commit=False) # Set the new article attribute to the current user. new_article.user = request.user # Save to database now the object has all the required data. new_article.save() Here is the full code for the add_article view if this helps. @login_required def add_article(request): """ Add a new article. """ if request.method != 'POST': # No data submitted, create a blank form. form = AddArticleForm() else: # POST data submitted, process data. form = AddArticleForm(request.POST, request.FILES) if form.is_valid(): new_article = form.save(commit=False) new_article.author = request.user new_article.save() return back_to_blog_page() context = {'form': form} return render(request, 'add_article.html', context)
unknown
d107
train
You can write something like this: read -p "Enter the answer in Y/N: " value if [[ "$value" = [yY] ]] || [[ "$value" = [yY][eE][sS] ]]; then echo 0; # Operation if true else echo 1; # Operation if false fi A: you can fix this issue in many ways. use this code on awk to fix your problem. #!/bin/bash read -p "choose your answer [Y/N]: " input awk -vs1="$input" 'BEGIN { if ( tolower(s1) == "yes" || tolower(input) == "y" ){ print "match" } else{ print "not match" } }'
unknown
d109
train
You didn't provide any pictures. So, I used css styles. You can remove the background color and add your pic urls. div.image { position: relative; } img#profile { width: 250px; height: 250px; background: blue; border-radius: 50%; z-index: 100; left: 10px; top: 10px; position: absolute; } img#frame { width: 270px; height: 270px; background: tomato; border-radius: 50%; z-index: -1; } JSFIDDLE A: You need to fix it yourself whenever you change the size. div.image { position: fixed; margin: 100px; } img#profile { width: 250px; height: 250px; background: skyblue; border-radius: 100%; z-index: 100; position: absolute; } img#frame { width: 270px; height: 270px; background: orange; border-radius: 100%; z-index: -1; position: absolute; top:-10px; left:-10px; }
unknown
d111
train
First, you need to assign names to the entries in your vector (each entry will get the corresponding file name), as follows: > library(tools) > names(rlist) <- basename(file_path_sans_ext(rlist)) Then, to get a list in the format that you specified, you can simply do: rlist2 <- as.list(rlist) This is the output: > rlist2 $image1 [1] "C:/imagery/Landsat/image1.img" $image2 [1] "C:/imagery/Landsat/image2.img" $image3 [1] "C:/imagery/Landsat/image3.img" And you can access individual entries in the list, as follows: > rlist2$image1 [1] "C:/imagery/Landsat/image1.img" You can read more about the as.list function and its behavior here.
unknown
d113
train
Are you looking for an explanation between the approach where you load in all users at once: # Loads all users into memory simultaneously @users = User.all @users.each do |user| # ... end Where you could load them individually for a smaller memory footprint? @user_ids = User.connection.select_values("SELECT id FROM users") @user_ids.each do |user_id| user = User.find(user_id) # ... end The second approach would be slower since it requires N+1 queries for N users, where the first loads them all with 1 query. However, you need to have sufficient memory for creating model instances for each and every User record at the same time. This is not a function of "DB memory", but of application memory. For any application with a non-trivial number of users, you should use an approach where you load users either individually or in groups. You can do this using: @user_ids.in_groups_of(10) do |user_ids| User.find_all_by_id(user_ids).each do |user| # ... end end By tuning to use an appropriate grouping factor, you can balance between memory usage and performance. A: Can you give a snipet of actual ruby on rails code, our pseudo code is a little confusing? You can avoid the n+1 problem by using eager loading. You can accomplish this by using :includes => tag in your model.find method. http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
unknown
d117
train
Just create two instance method in Your typing indicator cell one for start animation and another for resetAnimation class TypingCell: UITableViewCell { fileprivate let MIN_ALPHA:CGFloat = 0.35 @IBOutlet weak var dot0: UIView! @IBOutlet weak var dot1: UIView! @IBOutlet weak var dot2: UIView! private func startAnimation() { UIView.animateKeyframes(withDuration: 1.5, delay: 0, options: [.repeat, .calculationModeLinear], animations: { UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.1666, animations: { self.dot0.alpha = MIN_ALPHA }) UIView.addKeyframe(withRelativeStartTime: 0.16, relativeDuration: 0.1666, animations: { self.dot0.alpha = 1 }) UIView.addKeyframe(withRelativeStartTime: 0.33, relativeDuration: 0.1666, animations: { self.dot1.alpha = MIN_ALPHA }) UIView.addKeyframe(withRelativeStartTime: 0.49, relativeDuration: 0.1666, animations: { self.dot1.alpha = 1 }) UIView.addKeyframe(withRelativeStartTime: 0.66, relativeDuration: 0.1666, animations: { self.dot2.alpha = MIN_ALPHA }) UIView.addKeyframe(withRelativeStartTime: 0.83, relativeDuration: 0.1666, animations: { self.dot2.alpha = 1 }) }, completion: nil) } func resetAnimation() { dot0.layer.removeAllAnimations() dot1.layer.removeAllAnimations() dot2.layer.removeAllAnimations() DispatchQueue.main.async { self.startAnimation() } } } Reset your animation on tableView(_: willDisplay: cell: forRowAt:) func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let cell = cell as? TypingCell { cell.resetAnimation() } }
unknown
d119
train
You can find the option in the android lint menu: Once "Skip Library Project Dependencies" is checked, that should skip appcompat lint warnings when you are checking your project
unknown
d121
train
Yes they have their values inside. But you can't print them out on the host. For this you will need to copy your data back using cudaMemcpy((void *) array_host_2, (void *) array_device_2, SIZE_INT*size, cudaMemcpyDeviceToHost); And then you can print the values of array_host_2. A bit more explanation: Your array_device_* lives on the GPU and from your CPU (that is printing your output) you do not have direct access to this data. So you need to copy it back to your CPUs memory first before printing it out. A: Example of copying array with data to device, altering values in kernel, copy back to host and printing the new values: // Function to run on device by many threads __global__ void myKernel(int *d_arr) { int idx = blockIdx.x * blockDim.x + threadIdx.x; d_arr[idx] = d_arr[idx]*2; } int main(void) { int *h_arr, *d_arr; h_arr = (int *)malloc(10*sizeof(int)); for (int i=0; i<10; ++i) h_arr[i] = i; // Or other values // Sends data to device cudaMalloc((void**) &d_arr, 10*sizeof(int)); cudaMemcpy(d_arr, h_arr, 10*sizeof(int), cudaMemcpyHostToDevice); // Runs kernel on device myKernel<<< 2, 5 >>>(d_arr); // Retrieves data from device cudaMemcpy(h_arr, d_arr, 10*sizeof(int), cudaMemcpyDeviceToHost); for (int i = 0; i<10; ++i) printf("Post kernel value in h_arr[%d] is: %d\n", i,h_arr[i]); cudaFree(d_arr); free(h_arr); return 0; } A: The code snippet you provided seems correct, other than the first few lines as leftaroundabout pointed out. Are you sure the kernel is correct? Perhaps you are not writing the modified values back to global memory. If you make another set of host arrays and copy the GPU arrays back before running the kernel, are they correct? From what you have, the values inside array_host_* should have been copied to array_device_* properly. A: You can use a kernel function to directly print values on GPU memory. Use can use something like: __global__ void printFunc(int *devArray){ printf("%d", devArray[0]); } Hope it helps.
unknown
d123
train
Define $.fn.findSelf = function(selector) { var result = this.find(selector); this.each(function() { if ($(this).is(selector)) { result.add($(this)); } }); return result; }; then use $.findSelf(selector); instead of $find(selector); Sadly jQuery does not have this built-in. Really strange for so many years of development. My AJAX handlers weren't applied to some top elements due to how .find() works. A: $('selector').find('otherSelector').add($('selector').filter('otherSelector')) You can store $('selector') in a variable for speedup. You can even write a custom function for this if you need it a lot: $.fn.andFind = function(expr) { return this.find(expr).add(this.filter(expr)); }; $('selector').andFind('otherSelector') A: The accepted answer is very inefficient and filters the set of elements that are already matched. //find descendants that match the selector var $selection = $context.find(selector); //filter the parent/context based on the selector and add it $selection = $selection.add($context.filter(selector); A: You can't do this directly, the closest I can think of is using .andSelf() and calling .filter(), like this: $(selector).find(oSelector).andSelf().filter(oSelector) //or... $(selector).find('*').andSelf().filter(oSelector); Unfortunately .andSelf() doesn't take a selector, which would be handy. A: If you want the chaining to work properly use the snippet below. $.fn.findBack = function(expr) { var r = this.find(expr); if (this.is(expr)) r = r.add(this); return this.pushStack(r); }; After the call of the end function it returns the #foo element. $('#foo') .findBack('.red') .css('color', 'red') .end() .removeAttr('id'); Without defining extra plugins, you are stuck with this. $('#foo') .find('.red') .addBack('.red') .css('color', 'red') .end() .end() .removeAttr('id'); A: In case you are looking for exactly one element, either current element or one inside it, you can use: result = elem.is(selector) ? elem : elem.find(selector); In case you are looking for multiple elements you can use: result = elem.filter(selector).add(elem.find(selector)); The use of andSelf/andBack is pretty rare, not sure why. Perhaps because of the performance issues some guys mentioned before me. (I now noticed that Tgr already gave that second solution) A: I know this is an old question, but there's a more correct way. If order is important, for example when you're matching a selector like :first, I wrote up a little function that will return the exact same result as if find() actually included the current set of elements: $.fn.findAll = function(selector) { var $result = $(); for(var i = 0; i < this.length; i++) { $result = $result.add(this.eq(i).filter(selector)); $result = $result.add(this.eq(i).find(selector)); } return $result.filter(selector); }; It's not going to be efficient by any means, but it's the best I've come up with to maintain proper order. A: I was trying to find a solution which does not repeat itself (i.e. not entering the same selector twice). And this tiny jQuery extention does it: jQuery.fn.findWithSelf = function(...args) { return this.pushStack(this.find(...args).add(this.filter(...args))); }; It combines find() (only descendants) with filter() (only current set) and supports whatever arguments both eat. The pushStack() allows for .end() to work as expected. Use like this: $(element).findWithSelf('.target') A: For jQuery 1.8 and up, you can use .addBack(). It takes a selector so you don't need to filter the result: object.find('selector').addBack('selector') Prior to jQuery 1.8 you were stuck with .andSelf(), (now deprecated and removed) which then needed filtering: object.find('selector').andSelf().filter('selector') A: I think andSelf is what you want: obj.find(selector).andSelf() Note that this will always add back the current node, whether or not it matches the selector. A: If you are strictly looking in the current node(s) the you just simply do $(html).filter('selector') A: Here's the right (but sad) truth: $(selector).parent().find(oSelector).filter($(selector).find('*')) http://jsfiddle.net/SergeJcqmn/MeQb8/2/
unknown
d127
train
OK, just solved it:) The answer was to impersonate a room account and then simple decline the invitation. hope it will help to someone...
unknown
d131
train
I use Python, but the main idea is the same. If you directly do cvtColor: bgr -> gray for img2, then you must fail. Because the gray becames difficulty to distinguish the regions: Related answers: * *How to detect colored patches in an image using OpenCV? *Edge detection on colored background using OpenCV *OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection In your image, the paper is white, while the background is colored. So, it's better to detect the paper is Saturation(饱和度) channel in HSV color space. For HSV, refer to https://en.wikipedia.org/wiki/HSL_and_HSV#Saturation. Main steps: * *Read into BGR *Convert the image from bgr to hsv space *Threshold the S channel *Then find the max external contour(or do Canny, or HoughLines as you like, I choose findContours), approx to get the corners. This is the first result: This is the second result: The Python code(Python 3.5 + OpenCV 3.3): #!/usr/bin/python3 # 2017.12.20 10:47:28 CST # 2017.12.20 11:29:30 CST import cv2 import numpy as np ##(1) read into bgr-space img = cv2.imread("test2.jpg") ##(2) convert to hsv-space, then split the channels hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) h,s,v = cv2.split(hsv) ##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV) ##(4) find all the external contours on the threshed S cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] canvas = img.copy() #cv2.drawContours(canvas, cnts, -1, (0,255,0), 1) ## sort and choose the largest contour cnts = sorted(cnts, key = cv2.contourArea) cnt = cnts[-1] ## approx the contour, so the get the corner points arclen = cv2.arcLength(cnt, True) approx = cv2.approxPolyDP(cnt, 0.02* arclen, True) cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA) cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA) ## Ok, you can see the result as tag(6) cv2.imwrite("detected.png", canvas) A: In OpenCV there is function called dilate this will darker the lines. so try the code like below. private Mat edgeDetection(Mat src) { Mat edges = new Mat(); Imgproc.cvtColor(src, edges, Imgproc.COLOR_BGR2GRAY); Imgproc.dilate(edges, edges, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(10, 10))); Imgproc.GaussianBlur(edges, edges, new Size(5, 5), 0); Imgproc.Canny(edges, edges, 15, 15 * 3); return edges; }
unknown
d133
train
Try this... SELECT definition AS Check_Expression ,name AS ConstraintName FROM sys.check_constraints WHERE Parent_object_ID = OBJECT_ID('TableName')
unknown
d155
train
If you have a mixin which is doing something "hacky" with the font size, then you will probably need to reset the font size as you have noticed. I suggest the following: * *Create a Sass partial to record your projects config variables. I suggest _config.sass. *Define your base font-size in _config.sass: $base-font-size: 16px *Add @import _config.sass at the top of your main sass file(s). *Update the mixin to reset the font-size to your $base-font-size: @mixin foo nav font-size: 0 // this is the hacky part > li font-size: $base-font-size // reset font-size Note: If you are using the SCSS syntax, you'll need to update the examples here. A: There's no way to tell the computed value of a property until the styles are actually applied to a document (that's what jQuery examines). In the stylesheet languages, there's no "current" value except the initial value or the value you specify. Save the font size whenever you change it, and pass that seems best, and @BeauSmith has given a good example. This variant lets you pass a size or fallback to a defined global: =block-list($font-size: $base-font-size) font-size: 0 > li font-size: $font-size
unknown
d157
train
Give something like this a shot: <div class="container-fluid"> <div class="row-fluid"> <div class="span9" id="maincontent"> <div class="row"> <div class="span2" style="float: left; width: 15%;">2</div> <div class="span8" style="float: left; width: 65%;">8</div> <div class="span2" style="float: left; width: 15%;">2</div> </div> </div> <div class="span3" id="sidebar"> <!-- sidebar elements go here --> sidebar </div> </div> </div> You'll want to tweak and play with the % to fit your needs, and eventually move those inline styles out into a stylesheet. You may need to slap !important on them to keep them from being overriden by the fluid twitter bootstrap classes. The reason they were stacking with your setup is that the fluid styles took over despite the non-fluid container/row classes you used, and changed them to float: none, width: 100%; display: block divs.
unknown
d159
train
DoString will return what your script return. lua.DoString ("return 10+10")[0]; // <-- will return Double. 20 If you want to get your Lua function as LuaFunction object you need to return your function, or even better just use the [] operator to get the global value of hh. lua.DoString ("function hh() end"); var hh = lua["hh"] as LuaFunction; hh.Call (); Here is a example: https://github.com/codefoco/NLuaBox/blob/master/NLuaBox/AppDelegate.cs#L46 (but Using NLua instead LuaInterface) And remember to release your LuaFunction calling Dispose when you don't need the function anymore.
unknown
d163
train
What you are asking for is not rounding away from zero, it is Ceiling for positive numbers and Floor for negative numbers. A: MidpointRounding.AwayFromZero Is a way of defining how the midpoint value is handled. The midpoint is X.5. So, 4.5 is rounded to 5, rather than 4, which is what would happen in the case of MidpointRounding.ToEven. Round is completely correct. If you want to write a function that rounds all non-integer values to the next highest integer then that operation is Math.Ceiling, not Round.
unknown
d167
train
The problem is that there is no hibernate session in the new asynchronous thread, and the default AsyncTaskExecutor is not logging the exception. You can verify this yourself by putting a try/catch block inside your @Async method and logging the exception yourself. The solution is to use Domain.withNewSession around the GORM code in your service method: import org.springframework.scheduling.annotation.Async class MyService { @Async void myAsyncMethod() { MyDomain.withNewSession { MyDomain m = new MyDomain(...) m.save() } } } If you have many asynchronous methods, you may consider creating your own AsyncTaskExecutor as in this SO answer.
unknown
d169
train
In ES6 you need to do the following to use a var in string `MATCH (productName) AGAINST ${txt}` IF you cannot use `` Just go for the old way with string concatanation, "MATCH (productName) AGAINST '" +txt + "'"
unknown
d171
train
You can cast a DateTime as a Time data type. For example: SELECT [day_shift_flag] FROM [company_working_time] WHERE CAST(GETDATE() AS TIME) BETWEEN CAST([start_time] AS TIME) AND CAST([end_time] AS TIME) A: By Following Way You can Ignore the day,month,year SELECT [day_shift_flag] FROM [company_working_time] WHERE DatePart(HH,GETDATE()) BETWEEN DatePart(HH,[start_time]) AND DatePart(HH,[end_time])
unknown
d173
train
on an atomic object of type A is defined in the standard But we can call GCC will accept it. But on clang you'll get an error. is the above atomic_fetch_add operation on the non-atomic object x guaranteed to be atomic? No. In the standard the behavior of the code you presented is not defined, there is no guarantee of any kind. From https://port70.net/~nsz/c/c11/n1570.html#7.17 : 5 In the following synopses: * *An A refers to one of the atomic types. [...] And then all the functions are defined in terms of A, like in https://port70.net/~nsz/c/c11/n1570.html#7.17.7.5p2 : C atomic_fetch_key(volatile A *object, M operand); Atomic type is a type with _Atomic.
unknown
d175
train
First of all, read the following SO post that is very helpful. Creating USDZ from SCN programmatically In SceneKit, there's the write(to:options:delegate:progressHandler:) instance method that does the trick (the only thing you have to do is to assign a file format for URL). let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] .appendingPathComponent("model.usdz") sceneView.scene.write(to: path) Converting OBJ to USDZ using SceneKit.ModelIO However, if you need to convert OBJ model into USDZ, you have to import SceneKit.ModelIO module at first. Then use the following code: let objAsset = MDLAsset(url: objFileUrl) let destinationFileUrl = URL(fileURLWithPath: "path/Scene.usdz") objAsset.exportToUSDZ(destinationFileUrl: destinationFileUrl) Terminal approach In Xcode 11/12/13/14, you can convert several popular input formats into USDZ via command line: obj, gltf, fbx, abc, usd(x). usdzconvert file.gltf In Xcode 10, only OBJ-to-USDZ, single-frame ABC-to-USDZ and USD(x)-to-USDZ conversion is available via command line: xcrun usdz_converter file.obj file.usdz Preparing files for RealityKit In Xcode 12+ you can use a Reality Composer software for converting any RC scene into usdz file format (right from UI). Also, there's a Reality Converter standalone app. And, of course, you can use Autodesk Maya 2020 | 2022 | 2023 with Maya USD plugin.
unknown
d177
train
I am trying to fetch data from db and mapping it to a different entity but I get ArrayIndexOutOfBoundsException But in the following line, you are not doing that, you are trying to get the list of Student entity list. And what's your different Entity here? entityManager.createNamedQuery("findAll", Student.class); But as you provided another entity Generic, I assume you want your data to be loaded in that. There are different possible solutions to this problem. Lets figure out. Using the SELECT NEW keywords Update your Native query to this @NamedNativeQueries({ @NamedNativeQuery(name = "Student.findAll", query = "SELECT NEW Generic(a.student_id, a.student_code) FROM Student a") }) You have to define a Constructor in the Generic class as well that qualifies this call public void Generic(Long id, String code) { this.id = id; this.code = code; } And update the query execution in DAO as List<Generic> results = em.createNamedQuery("Student.findAll" , Generic.class).getResultList(); Note: You may have to place the fully qualified path for the Generic class in the Query for this Construct from List<Object[]> Alternatively the straight forward and simplest solution would fetch the result list as a list of Object[] and populate to any new Object you want. List<Object[]> list = em.createQuery("SELECT s.student_id, s.student_code FROM Student s") .getResultList(); for (Object[] obj : list){ Generic generic = new Generic(); generic.setId(((BigDecimal)obj[0]).longValue()); generic.setCode((String)obj[1]); }
unknown
d181
train
If you open the file by double-clicking on it, are you able to read the data? Usually a special library like POI is required to write to excel so I would be surprised if it does. If your txt file has data in csv(comma separated) format, then changing the extension to .csv should work for you.
unknown
d185
train
You need to customize Identity Model and add navigation properties. public class ApplicationUser : IdentityUser { public virtual ICollection<ApplicationUserRole> UserRoles { get; set; } } and then add required configuration. protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<ApplicationUser>(b => { // Each User can have many entries in the UserRole join table b.HasMany(e => e.UserRoles) .WithOne(e => e.User) .HasForeignKey(ur => ur.UserId) .IsRequired(); }); modelBuilder.Entity<ApplicationRole>(b => { // Each Role can have many entries in the UserRole join table b.HasMany(e => e.UserRoles) .WithOne(e => e.Role) .HasForeignKey(ur => ur.RoleId) .IsRequired(); }); } and then you can use joins to query users with roles. More information on adding navigation proprieties can be found here
unknown
d191
train
OK, this is a massive simplification because SCD's are very challenging to correctly implement. You will need to sit down and think critically about this. My answer below only handles ongoing daily processing - it does not explain how to handle historical files being re-processed, which could potentially result in duplicate records with different EffectiveStart and End Dates. By definition, you will have an existing record source component (i.e., query from the database table) and an incoming data source component (i.e., a *.csv flatfile). You will need to perform a merge join to identify new records versus existing records. For existing records, you will need to determine if any of the columns have changed (do this in a Derived Column transformation). You will need to also include two columns for EffectiveStartDate and EffectiveEndDate. IncomingEffectiveStartDate = FileDate IncomingEffectiveEndDate = 12-31-9999 ExistingEffectiveEndDate = FileDate - 1 Note on 12-31-9999: This is effectively the Y10K bug. But, it allows users to query the database between date ranges without having to consciously add ISNULL(GETDATE()) in the WHERE clause of a query in the event that they are querying between date ranges. This will prevent the dates on the columns from overlapping, which could potentially result in multiple records being returned for a given date. To determine if a record has changed, create a new column called RecordChangedInd of type Bit. (ISNULL(ExistingColumn1, 0) != ISNULL(IncomingColumn1, 0) || ISNULL(ExistingColumn2, 0) != ISNULL(IncomingColumn2, 0) || .... ISNULL(ExistingColumn_N, 0) != ISNULL(IncomingColumn_N, 0) ? 1 : 0) Then, in your split condition you can create two outputs: RecordHasChanged (this will be an INSERT) and RecordHasNotChanged (this will be an UPDATE to deactivate the exiting record and an INSERT). You can conceivably route both inputs to the same INSERT destination. But, you will need to be careful suppress the update record's ExistingEffectiveEndDate value that deactivates the date.
unknown
d195
train
Yes you can do use a listview and create custom adapter. set your map as header in listview and use your listview rows for data representation. Another thing which you can do is create listview and maps seperate. Align your listview just below to the map Here i am giving you a simple example the code below will create listview. You may need to I have created custom adapter for your purpose. public class my_map_activity extends Activity { ArrayList<String> name = null; ArrayList<String> gender = null; ArrayList<String> latitude = null; ArrayList<String> longitude = null; Context activity_context = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ListView user_listview = (ListView) findViewById(R.id.user_listview); name = new ArrayList<String>(); gender = new ArrayList<String>(); latitude = new ArrayList<String>(); longitude = new ArrayList<String>(); for (int i = 0; i < 10; i++) { name.add ("test user " + i); gender.add ("Male"); latitude.add (""+ i); longitude.add (""+ i); } custom_adapter list_adapter = new custom_adapter (this, android.R.layout.simple_list_item_1, name, gender, latitude, longitude); user_listview.setAdapter(list_adapter); } } Here is my main.xml file. Which will tell you how to create that layout. I am using Relative layout as my parent layout. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/RelativeLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="250dp" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:src="@drawable/ic_launcher" /> <ListView android:id="@+id/user_listview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/imageView1" > </ListView> </RelativeLayout> here i am posting you my custom adapter code which you can use for your listview purpose. public class custom_adapter extends ArrayAdapter<String>{ ArrayList<String> name = null; ArrayList<String> gender = null; ArrayList<String> latitude = null; ArrayList<String> longitude = null; Context activity_context = null; public custom_adapter(Context context, int resource, ArrayList<String> name , ArrayList<String> gender, ArrayList<String> latitude, ArrayList<String> longitude) { super(context, resource, name ); this.name = name; this.gender = gender; this.latitude = latitude; this.longitude = longitude; activity_context = context; } static class ViewHolder { public TextView txt_name; public TextView txt_gender; public TextView txt_latitude; public TextView txt_longitude; public ImageView img_view; } @Override public View getView (final int position, View convertView, ViewGroup parent) { View rowView = convertView; ViewHolder holder = null; if (rowView == null) { LayoutInflater inflater = (LayoutInflater)activity_context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(R.layout.row_file, null, false); holder = new ViewHolder(); holder.txt_name = (TextView) rowView.findViewById(R.id.textView1); holder.txt_gender = (TextView) rowView.findViewById(R.id.textView2); holder.txt_latitude = (TextView) rowView.findViewById(R.id.textView3); holder.txt_longitude = (TextView) rowView.findViewById(R.id.textView4); holder.img_view = (ImageView) rowView.findViewById(R.id.imageView1); rowView.setTag(holder); } else { holder = (ViewHolder) rowView.getTag(); } if (holder != null) { holder.txt_name.setText(name.get(position)); holder.txt_gender.setText(gender.get(position)); holder.txt_latitude.setText(latitude.get(position)); holder.txt_longitude.setText(longitude.get(position)); } return rowView; } } Here is the layout which you can inflate in your custom adapter and set it on listview. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/RelativeLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:src="@drawable/ic_launcher" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:contentDescription="TODO"/> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/imageView1" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_below="@+id/textView1" android:layout_toRightOf="@+id/imageView1" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView2" android:layout_alignParentRight="true" android:layout_below="@+id/textView2" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView3" android:layout_alignParentRight="true" android:layout_below="@+id/textView3" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> </RelativeLayout> So i have given you all four files. Here i am explaining what every file will do. * *my_map_activity : This is the main activity which contains listivew and map both. I am using a big imageview. Instead of that imageview you can place your map. *main.xml : This is layout file which contains both listview and map. *custom_adapter : This is the custom adapter which i have created for you. I am extending array adapter. In this i am taking data from arraylist and inflating the row layout and the i am setting respective values. *row_layout : This is the row layout which will contain imageview for user, name, gender and all other thing. So i have created several things for you if you need any help then you can ask and try to get the concept of each file how i am using.
unknown
d197
train
Two suggestions: * *Make sure you don't have any file or directory permissions problems for the installed eggs and files in the site-packages directory. *If you have installed another instance of Python 2.6 (besides the Apple-supplied one in /usr/bin/python2.6), make sure you have installed a separate version of easy_install for it. As is, your output indicates it was almost certainly installed using the Apple-supplied easy_install in /usr/bin which is for the Apple-supplied Python. The easiest way to do that is to install the Distribute package using the new Python. A: I had the same problem, I tried pip install mrjob, sudo easy_install mrjob. It looked like it installed successfully, but when I ran a simple example script, I got the import error. I got it to work by following the instructions at: http://pythonhosted.org//mrjob/guides/quickstart.html#installation. In a nutshell, I cloned the source code from github and ran python setup.py install. My problem might be different from yours, though. There was nothing in my site-packages directory for mrjob after running pip-install and easy_install. A: mrjob package can be installed by running following command: pip install mrjob After installation, the error will be solved. It worked in my case.
unknown
d199
train
This problem is caused due to many possible reasons, like: * *You are behind the firewall and firewall block it. *Your internet is too slow. (Hope it is not the case) *You are using VPN or PROXY. (Not all VPN causes this error.) *You have both ipv4 and ipv6 enabled (Not sure about this case.) I cannot confirm about the main reason that is caused for you to not being able to create project from composer but you could try some methods like: * *Changing to different ISP. *Try running composer -vvv: This helps to check what actually is doing behind the scene and helps in further more debug. *Try updating composer to latest version. *Try creating some older version of Laravel or any other packages composer create-project laravel/laravel blog "5.1.*" *Try using some VPN. This is only for testing and doesn't have fully confirmed solution. If there is any other reason we could edit this solution. A: If are installing the composer make sure that,you must have to set environment variable for PHP. If your using xampp control panel ->go to xampp installed path->PHP. Then copy location and set in the environment location.Then try to install composer.
unknown
d201
train
One way SELECT (SELECT TOP 1 [a] FROM @T WHERE [a] IS NOT NULL ORDER BY [sort]) AS [a], (SELECT TOP 1 [b] FROM @T WHERE [b] IS NOT NULL ORDER BY [sort]) AS [b], (SELECT TOP 1 [c] FROM @T WHERE [c] IS NOT NULL ORDER BY [sort]) AS [c] Or another ;WITH R AS (SELECT [a], [b], [c], [sort] FROM @T WHERE [sort] = 0 UNION ALL SELECT Isnull(R.[a], T.[a]), Isnull(R.[b], T.[b]), Isnull(R.[c], T.[c]), T.[sort] FROM @T T JOIN R ON T.sort = R.sort + 1 AND ( R.[a] IS NULL OR R.[b] IS NULL OR R.[c] IS NULL )) SELECT TOP 1 [a], [b], [c] FROM R ORDER BY [sort] DESC
unknown
d203
train
Try this: SELECT T1.Id, T2.Relatives FROM SecondTable T2 LEFT JOIN FirstTable T1 ON T1.ID = T2.ID GROUP BY T1.Id, T2.Relatives This is what I get exactly: CREATE TABLE #a ( id int, name varchar(10) ) CREATE TABLE #b ( id int, name varchar(10) ) INSERT INTO #a VALUES (1, 'sam') INSERT INTO #a VALUES (1, 'Dan') INSERT INTO #b VALUES (1, 'Uncle') INSERT INTO #b VALUES (2, 'Aunty') SELECT T1.Id, T2.name FROM #b T2 LEFT JOIN #a T1 ON T1.ID = T2.ID GROUP BY T1.Id, T2.name DROP TABLE #a DROP TABLE #b Output: Id name NULL Aunty 1 Uncle Hope, this is what you ask in your question. A: As your question is not clear, so assuming that you need to retrieve id from table a and name from table b and you also want to avoid duplicate rows, then an option could be to use distinct along with left join: select distinct a.id, b.name from b left outer join a on b.id = a.id order by id desc Result: +------+-------+ | id | name | +------+-------+ | 1 | Uncle | | NULL | Aunty | +------+-------+ DEMO
unknown
d205
train
The error on the page says $.mobile is undefined. Include the proper URL to where $.mobile is defined and try again. A: This line doesn't work: $.mobile.allowCrossDomainPages = false; If you take it off your javascript will work. Just so you know, I'm getting here that "could not connect to service". Next time insert some logs or alerts in your code to debug. I just put one before and one after the line that was not working to see if the ajax request was being sent and saw that this line was the problem. (In chrome ctrl+shift+c opens debug window, open console and you can see js logs (console.log). A lot better than alert for debug) Ps: For cross domain ajax call use jsonp, as Ehsan Sajjad commented: * *jQuery AJAX cross domain *Make cross-domain ajax JSONP request with jQuery Ps2: I never used this, but it might be useful: Cross-origin Ajax
unknown
d207
train
Okay, I found the answer. Had to use some trigonometry. h = tan(fov/2)*dist dist is the distance to the object from the camera. h is half of the screen space in y axis. to get x axis multiply by (screenwidth/screenheight)
unknown
d209
train
The above answer is correct and here's the exact copy-paste code in case you're struggling: Accounts.setPassword(userId, password, {logout: false}); Note: make sure you are doing this call server side. A: Accounts.setPassword(userId, password, options) This method now supports options parameter that includes options.logout option which could be used to prevent the current user's logout. A: You could use Accounts.changePassword (docs) to change the password instead, this will not affect the user's existing tokens (as from) https://github.com/meteor/meteor/blob/devel/packages/accounts-password/password_server.js#L299-L302 If you want to do this from the server without knowing the existing password you would have to fork the accounts-password package and remove this line: https://github.com/meteor/meteor/blob/devel/packages/accounts-password/password_server.js#L338 and add this package into the /packages directory of your app If you want to downgrade your package (so long as the version you're using of meteor supports it): meteor remove accounts-password meteor add accounts-password@1.0.3
unknown
d215
train
One of many ways to do achieve your objective: * *Make an array of checkboxes on your current form that are checked. *Go through the array to build the folder name based on the Text. *Delete the entire folder, then replace it with an empty one. You may want to familiarize yourself with System.Linq extension methods like Where and Any if you haven't already. The [Clear] button should only be enabled if something is checked. Making an array of the checkboxes will be handy. It can be used every time you Clear. At the same time, the [Clear] button shouldn't be enabled unless one or more of the checkboxes are marked. public partial class MainForm : Form { public MainForm() { InitializeComponent(); // Make an array of the checkboxes to use throughout the app. _checkboxes = Controls.OfType<CheckBox>().ToArray(); // This provides a way to make sure the Clear button is // only enabled when one or more checkboxes is marked. foreach (CheckBox checkBox in _checkboxes) { checkBox.CheckedChanged += onAnyCheckboxChanged; } // Attach the 'Click' handler to the button if you // haven't already done this in the form Designer. buttonClear.Enabled = false; buttonClear.Click += onClickClear; } const string basePath = @"D:\java\"; CheckBox[] _checkboxes; . . . } Set the Clear button Enabled (or not) Here we respond to changes in the checkbox state. private void onAnyCheckboxChanged(object sender, EventArgs e) { buttonClear.Enabled = _checkboxes.Any(_=>_.Checked); } Exec Clear Build a subfolder path using the Text of the checkboxes. If the checkbox is selected, delete the entire folder, replacing it with a new, empty one. private void onClickClear(object sender, EventArgs e) { // Get the checkboxes that are selected. CheckBox[] selectedCheckBoxes = _checkboxes.Where(_ => _.Checked).ToArray(); foreach (CheckBox checkBox in selectedCheckBoxes) { // Build the folder path string folderPath = Path.Combine(basePath, checkBox.Text); // Can't delete if it doesn't exist. if (Directory.Exists(folderPath)) { // Delete the directory and all its files and subfolders. Directory.Delete(path: folderPath, recursive: true); } // Replace deleted folder with new, empty one. Directory.CreateDirectory(path: folderPath); } } A: I understand, you have this structure D |-java |-Document |-Person |-Picture And you said "delete the contents of the folder". So, I assume you need to keep folders In this case public void EmptyFolder(string root, IEnumerable<string> subfolders) { foreach(string folder in subfolders) { string dirPath = Path.Combine(root, folder); foreach (string subdir in Directory.EnumerateDirectories(dirPath)) Directory.Delete(subdir, true); foreach (string file in Directory.EnumerateFiles(dirPath)) File.Delete(file); } } // (assuming check box text is the name of folder. Or you can use tag property to set real folder name there) private IEnumerable<string> Getfolders() { foreach(control c in this.Controls) // "this" being a form or control, or use specificControl.Controls { if (c is Checkbox check && check.Checked) yield return check.Text; } } // USAGE EmptyFolder(@"D:\java\", Getfolders()); NOTE: written from memory and not tested
unknown
d217
train
You could seach for same id in the result set and replace if the former type is undefined. var array = [{ id: 1, type: 1 }, { id: 2, type: undefined }, { id: 3, type: undefined }, { id: 3, type: 0 }, { id: 4, type: 0 }], result = array.reduce((r, o) => { var index = r.findIndex(q => q.id === o.id) if (index === -1) r.push(o); else if (r[index].type === undefined) r[index] = o; return r; }, []); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; } A: Try this const testArray = [ {id: 1, type: 1}, {id: 2, type: undefined}, {id: 3, type: undefined}, {id: 3, type: 0}, {id: 4, type: 0} ]; let newArray = []; testArray.forEach(item => { const newArrayIndex = newArray.findIndex(newItemArray => newItemArray.id === item.id); if (newArrayIndex < 0) return newArray.push(item); if (item.type === undefined) return newArray[newArrayIndex].type = item.type; }); console.log(newArray)
unknown
d219
train
You need to create a data frame representing an edge list in the format of: * *column1 = node where the edge is coming from *column2 = node where the edge is going to *columnn... = attributes you want to store in the edge Then you will need to input that df into graph_from_data_frame Two of the attributes you can store in the edge list are color and width which will automatically be plotted in igraph's base plot function. edge_list <- mymodCoef %>% mutate(source = term, target = 'mpg', color = sapply(statistic, function(x){ifelse(x<0, 'red', 'green')}), width = abs(statistic)/(max(abs(statistic))) * 10) %>% filter(p.value <= .05) %>% select(source, target, color, statistic, width) g <- graph_from_data_frame(edge_list, directed = F) plot(g) If you wanted to explicitly plot the color and width, then plot(g, edge.width = E(g)$width, edge.color = E(g)$color) Sometimes you'll need to play around with scales - for instance, the difference in statistic scores are at most 2 and will look identical if you used the raw statistic score as the line width. If you want to get scaling for free, then you can use ggraph: library(ggraph) ggraph(g) + geom_edge_link(aes(edge_colour = color, edge_width = abs(statistic))) + geom_node_text(aes(label = name)) + scale_edge_color_manual(values = c('green' = 'green', 'red' = 'red')) If you want to learn more about plotting with igraph, then some of the best tutorials for plotting in igraph can be found in Katherine Ognyanova's website: http://kateto.net/netscix2016
unknown
d221
train
You can use the :not negation pseudo-class. Note that when combining pseudo-classes, you must put the second pseudo-class inside of brackets as :not(:first-of-type): p:not(:first-of-type) { background: red; } <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> Note that if you're specifically looking to select every element other than the first child of an element, you can use :not(:first-child). Note that the selector goes on the child element in this case though, not the parent: .parent p:not(:first-child) { background: red; } <div class="parent"> <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> </div> A: Very simply: p+p { background: red; } <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> The next-sibling combinator (+) targets an element that is immediately preceded by another element. So in this case, only p elements following another p are selected. This excludes the first p. You may also be interested in the subsequent-sibling combinator (~), which is similar to the above, except the first element does not need to immediately precede the second. A: .text p:not(:first-child) { background: green; } <div class="text"> <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> </div>
unknown
d223
train
try it methood Custom Toast public static void Toast(String textmessage) { LinearLayout layout = new LinearLayout(getContext()); layout.setBackgroundResource(R.drawable.shape_toast); layout.setPadding(30, 30, 30, 30); TextView tv = new TextView(getContext()); tv.setTextColor(Color.WHITE); tv.setTextSize(12); tv.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/font.ttf")); tv.setGravity(Gravity.CENTER); tv.setText(textmessage); layout.addView(tv); Toast toast = new Toast(getContext()); toast.setView(layout); toast.setGravity(Gravity.BOTTOM, 0, 240); toast.show(); } you can try it methood Toast with duration public class ToastExpander { public static final String TAG = "ToastExpander"; public static void showFor(final Toast aToast, final long durationInMilliseconds) { aToast.setDuration(Toast.LENGTH_SHORT); Thread t = new Thread() { long timeElapsed = 0l; public void run() { try { while (timeElapsed <= durationInMilliseconds) { long start = System.currentTimeMillis(); aToast.show(); sleep(1750); timeElapsed += System.currentTimeMillis() - start; } } catch (InterruptedException e) { Log.e(TAG, e.toString()); } } }; t.start(); } } and for show toast use this Toast aToast = Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT); ToastExpander.showFor(aToast, 5000);
unknown
d225
train
:~A() {} class B : public A { public: virtual ~B() { } std::string B_str; }; class BB : public A { public: virtual ~BB() { } std::string BB_str; }; class C : public A { protected: virtual ~C() { } virtual void Print() const = 0; }; class D : public B, public BB, public C { public: virtual ~D() { } }; class E : public C { public: void Print() const { std::cout << "E" << std::endl; } }; class F : public E, public D { public: void Print_Different() const { std::cout << "Different to E" << std::endl; } }; int main() { F f_inst; return 0; } Compiling with g++ --std=c++11 main.cpp produces the error: error: cannot declare variable ‘f_inst’ to be of abstract type ‘F’ F f_inst; note: because the following virtual functions are pure within ‘F’: class F : public E, public D ^ note: virtual void C::Print() const void Print() const = 0; ^ So the compiler thinks that Print() is pure virtual. But, I have specified what Print() should be in class E. So, I've misunderstood some of the rules of inheritance. What is my misunderstanding, and how can I correct this problem? Note: It will compile if I remove the inheritance : public D from class F. A: Currently your F is derived from C in two different ways. This means that an F object has two separate C bases, and so there are two instances of C::Print(). You only override the one coming via E currently. To solve this you must take one of the following options: * *Also override the one coming via D, either by implementing D::Print() or F::Print() *Make Print non-pure *Use virtual inheritance so that there is only a single C base. For the latter option, the syntax adjustments would be: class E : virtual public C and class D : public B, public BB, virtual public C This means that D and E will both have the same C instance as their parent, and so the override E::Print() overrides the function for all classes 'downstream' of that C. For more information , look up "diamond inheritance problem". See also Multiple inheritance FAQ
unknown
d227
train
Define your lists inside the __init__ function. class Unit: def __init__(self): self.arr = [] self.arr.clear() for i in range(2): self.arr.append(random.randint(1, 100)) print("arr in Unit ", self.arr) class SetOfUnits: def __init__(self): self.lst = [] self.lst.clear() for i in range(3): self.lst.append(Unit()) print("arr in SetOfUnits ", self.lst[i].arr) The way you are doing it, you define your variables class-wise, you need it to be instance-wise. See: class variable vs instance variable --Python A: lst and arr are class attributes, not instance attributes.
unknown
d231
train
'p4 files' will print the list of all the files in the repository, and for each file it will tell you the revision number. Then a little bit of 'awk' and 'sort' will find the files with the highest revision numbers.
unknown
d235
train
you go as docker login your.domain.to.the.registr.without.protocol.or.port enter username enter password now you can pull using docker pull your.domain.to.the.registr.without.protocol.or.port/youimage Ensure your registry runs behind a SSL proxy / termination, or you run into security issues. Consider reading this in this case https://docs.docker.com/registry/insecure/
unknown
d241
train
Write a BoolToVisibility IValueConveter and use it to bind to the Visibility property of your contentPanel <StackPanel Visibility="{Binding YourBoolProperty, Converter={StaticResource boolToVisibilityResourceRef ..../> You can find a BoolToVisibility pretty easy anywhere. Check IValueConveter if you are new to that. http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx A: I would recommend setting the ListBoxItem visibility at the ListBoxItem level or you will end up with tiny empty listbox items due to the default padding and border values e.g. <ListBox> <ListBox.Resources> <Style TargetType="ListBoxItem"> <Setter Property="Visibility" Value="{Binding MyItem.IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}" /> </Style> </ListBox.Resources> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Vertical"> <CheckBox Content="{Binding MyItemName}" IsChecked="{Binding IsVisible, Mode=TwoWay}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> This hides the entire ListBoxItem not just the contents of it.
unknown
d245
train
pixi.js (unminified) is 1.3MB, so what do you expect? If you want a smaller filesize you have to use a minification plugin for webpack, like uglify.
unknown
d249
train
Maybe this will be helpful for your needs: Tool Window I dont know your other code parts, but I guess you initiate a window application, where you want to render the history list. This window application needs: private FirstToolWindow window; private void ShowToolWindow(object sender, EventArgs e) { window = (FirstToolWindow) this.package.FindToolWindow(typeof(FirstToolWindow), 0, true); ...
unknown
d251
train
Hypothetically you need the distance between 2 geo locations. From the event geolocation to the the one calculated. An identical thread from stackoverflow : Calculate distance between 2 GPS coordinates
unknown
d253
train
var myFunc = function() { var size = $('.td-hide'); if ($('input#dimensions').is(':checked')) { size.show(); $('.single-select-sm').css('width','148px') } else { size.hide(); $('.single-select-sm').css('width','230px') } } $(document).on("click", ".dimensions", function() { myFunc(); } $(function() { myFunc(); }
unknown
d257
train
Set the form's FormBorderStyle property to None.
unknown
d263
train
I would try to un-install and install again the Java8 JDK. Have you tried that? Have you got multiple JDK installed? If yes try with just Java8 (un-install the others). Or try also to run eclipse with eclipse -vm c:\java8path\jre\bin\javaw.exe or eclipse -vm c:\java8path\jre\bin\client\jvm.dll
unknown
d267
train
Since you cannot have more than five routes, I would suggest you use only one wild-carded route. So you run an if else on the wild card to call the appropriate method. Route::get('{uri?}',function($uri){ if($uri == "/edit") { return app()->call('App\Http\Controllers\HomeController@editROA'); }else if($uri == "something else"){ return app()->call('App\Http\Controllers\SomeController@someMethod'); } // add statements for other routes }); view <a type='button' class='btn-warning' href="{{url('edit')}}">Edit</a>
unknown
d275
train
Something like this as an idea. select t.name,c.name from sys.tables as t left join sys.columns as c on t.object_id=c.object_id order by t.name,c.column_id A: Apparently, there's nothing wrong with the code. It's just the code is too long for the Console, and when copying from there, the content at the top is missing. Disappointing mystery this time. Sorry! Thanks for the answers anyway!
unknown
d277
train
I think the problem is that git detects its own .git files and doesn't allow to work with them. If you however rename your test repo's .git folder to something different, e.g. _git it will work. Only one thing you need to do is to use GIT_DIR variable or --git-dir command line argument in your tests to specify the folder. A: Even though it is not an "externally referenced piece of software", submodules are still a good approach, in that it helps to capture known state of repositories. I would rather put both repo and test-repo within a parent repo "project": project repo rest-repo That way, I can record the exact SHA1 of both repo and test-repo.
unknown
d279
train
You shouldn't push the default route from your OpenVPN server - you push only routes to the network you want to access. For example I have OpenVPN running on internal network, so in OpenVPN server.conf I have this: push "route 10.10.2.0 255.255.255.0" push "route 172.16.2.0 255.255.255.0" This will cause Windows OpenVPN client to add only routes for these 2 networks after connect, so it won't affect the default route and internet traffic. One caveat is that at least Windows 7 recognizes different networks by their gateways. If the network doesn't have a gateway, Windows is unable to recognize the network and you are unable to choose if is it Home/Work/Public network (which would deny samba access if using Windows Firewall). The workaround I use is to add a default gateway route with big metric (999), so that it is never used for routing by Windows. I have this in the clients config file, but probably it can be put also to the server's config. # dummy default gateway because of win7 network identity route 0.0.0.0 0.0.0.0 vpn_gateway 999
unknown
d283
train
You can put any downloadable files you like in a hello-world .war file and they'll be downloadable over HTTP. It's silly to use an application server without an application. A: Liberty is not intended to be used as a generic file server. That said, there are MBean operations supporting file transfer capabilities via the Liberty REST Connector. Javadoc for these operations may be found at <liberty-install-root>/dev/api/ibm/javadoc/com.ibm.websphere.appserver.api.restConnector_1.3-javadoc.zip
unknown
d285
train
By definition all operations on NA will yield NA, therefore x == NA always evaluates to NA. If you want to check if a value is NA, you must use the is.na function, for example: > NA == NA [1] NA > is.na(NA) [1] TRUE The function you pass to sapply expects TRUE or FALSE as return values but it gets NA instead, hence the error message. You can fix that by rewriting your function like this: bobpresent <- function(x) { ifelse(is.na(x), 0, 1) } In any case, based on your original post I don't understand what you're trying to do. This change only fixes the error you get with sapply, but fixing the logic of your program is a different matter, and there is not enough information in your post.
unknown
d287
train
Doing str_replace("\t", ',', $output) would probably work. Here's how you'd get it into an associative array (not what you asked but it could prove useful to helping you understanding how the output is formatted): $output = $ssh->exec('mysql -uMyUser -pMyPassword MyTable -e "SELECT * FROM users LIMIT"'); $output = explode("\n", $output); $colNames = explode("\t", $output[0]); $colValues = explode("\t", $output[1]); $cols = array_combine($colNames, $colValues);
unknown
d289
train
Regex in C# cannot check for external conditions: the result of the match is only dependent on the input string. If you cannot add any other code and you are only able to change the expressions used then it cannot be done.
unknown
d291
train
You have to group by all fields that are not aggregated. So value needs to be summed up or grouped by. Try: var result = TestList .GroupBy(t => t.id) .Select(g => new { id = g.Key, g.OrderByDescending(c => c.dt).First().dt, g.OrderByDescending(c => c.dt).First().value }); A: Based on comments and the question, you want: for each distinct id, the instance with the maximum dt. I would add a help method: MaxBy which allows a whole object to be selected based on the value of a function1: public static T MaxBy<T,TValue>(this IEnumerable<T> input, Func<T,TValue> projector) where TValue : IComparable<TValue> { T found = default(T); TValue max = default(TValue); foreach (T t in input) { TValue p = projector(t); if (max.CompareTo(p) > 0) { found = t; max = p; } } return found; } And then the query becomes: var q = from p in TestList group p by p.id into g select g.MaxBy(w => w.dt); NB. this implementation of MaxBy will only work for objects where the value of the member being compared is greater than its type's default value (e.g. for int: greater than zero). A better implementation of MaxBy would use the enumerator manually and initialise both found and max variables directly from the first element of the input. 1 if you are using The Reactive Extensions (Rx) this is included in the System.Interactive assembly.
unknown
d293
train
Instead of ajaxOptions, use params. If I remember correctly, test and its value will be included in your POST request by x-editable. Try something like this: Html <a id="other1" data-pk="1" data-name="test">First Name</a> AJAX $(document).ready(function() { $('#other1').editable({ type: 'text', url: '/create_post/', params : function(params) { params.csrfmiddlewaretoken = '{{ csrf_token }}'; return params; }, placement: 'top', title: 'New Expense', success: function(response, newValue) { if(response.status == 'error') return response.msg; //ms }, }); });
unknown
d295
train
I have solved this as follows. * *Remote the annotation from the action. *Add the following code at the beginning of the action (news and submit being the relevant controller and action respectively). if (!springSecurityService.isLoggedIn()) { flash.message = "You must be logged in to submit a news story." redirect(controller:"login", action: "auth", params:["spring-security-redirect" : "/news/submit"]) } *Add the following to the login form. <input type='hidden' name='spring-security-redirect' value='${params['spring-security-redirect']}'/> A: Add, for example, this to your login view: <sec:noAccess url="/admin/listUsers"> You must be logged in to view the list of users. </sec:noAccess> See the security taglib's documentation.
unknown
d297
train
You can just use the ŧf.keras.Model API: actor_model = tf.keras.Model(inputs=...,outputs=...) Q_model = tf.keras.Model(inputs=actor_model.outputs, outputs=...)
unknown
d303
train
Modern PC's use floating point numbers to calculate non-integral values. These come in two standardized variants: float and double, where the latter is twice the size of the former. Matlab, by default uses (complex) doubles for all its calculations. You can force it to use float (or as Matlab calls them, single) by specifiying the type: a = single([20, 25.0540913632159, 16.2750000000000, 3.08852992798468]); This should use half the memory, and you lose some precision that may or may not be important in your application. Make sure the optimization is worth it before doing this, as execution speed may even be slower (due to builtin functions only operating on double, hence requiring two conversions extra).
unknown
d305
train
Your var = xmlhttp; is outside of switchText scope and so it's undefined and throws an error. Try this <html> <head> <script type="text/javascript"> var xmlhttp; function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } } function switchText() {loadXMLDoc(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="switchText()">Change Content</button> </body> </html> A: I think the issue you have is that you have not validated your code, even down to whether you have matching curly braces or not (hint, you do not!) moving the open and send commands back into the first function and removing the extra curly brace shoudl work. the below should work : <html> <head> <script type="text/javascript"> var xmlhttp; function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } function switchText() { loadXMLDoc(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="switchText()">Change Content</button> </body> </html> hope that helps Olly A: I think the problem is with the following line in ajax_object.html file: if (xmlhttp.readyState==4 && xmlhttp.status==200) If you run the file with the above line and look at the 'Show Page Source', it will be apparent that the 'Request & Response' header has its -- Status and Code --- set to nothing So, delete the line and you will get: <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!--script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script--> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html> If you run this code it will output the ajax_info.txt file.
unknown
d307
train
yum -y remove php* to remove all php packages then you can install the 5.6 ones. A: Subscribing to the IUS Community Project Repository cd ~ curl 'https://setup.ius.io/' -o setup-ius.sh Run the script: sudo bash setup-ius.sh Upgrading mod_php with Apache This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section. Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted. sudo yum remove php-cli mod_php php-common Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted. sudo yum install mod_php70u php70u-cli php70u-mysqlnd Finally, restart Apache to load the new version of mod_php: sudo apachectl restart You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl: systemctl status httpd
unknown
d311
train
Per the Dockerfile ARG docs, The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg = flag. in order to accept an argument as part of the build, we use --build-arg. Dockerfile ENV docs: The ENV instruction sets the environment variable to the value . We also need to include an ENV statement because the CMD will be executed after the build is complete, and the ARG will not be available. FROM busybox ARG ENVIRONMENT ENV ENVIRONMENT $ENVIRONMENT CMD echo $ENVIRONMENT will cause an environment variable to be set in the image, so that it is available during a docker run command. docker build -t test --build-arg ENVIRONMENT=awesome_environment . docker run -it test This will echo awesome_environment. A: Try changing your RUN command do this: RUN npm run ng build --configuration=$ENVIRONMENT This should work. Check here Thanks.
unknown
d323
train
In Python, do the following where alwayssep is the expression and line is the passed string: line = re.sub(alwayssep, r' \g<0> ', line) A: My Pythonizer converts that to this: line = re.sub(re.compile(alwayssep),r' \g<0> ',line,count=0)
unknown
d325
train
you can try something like this. <table> <thead> <tr> {% for key in groups.keys() %} <th>{{ key|title }}</th> {% endfor %} </tr> </thead> <tbody> <tr> {% for key in groups.keys() %} <td>{{ groups[key]}}</td> {% endfor %} </tr> </tbody> </table>
unknown