_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d17101
val
From the Rx doc for SubscribeOn: The SubscribeOn operator designates which thread the Observable will begin operating on, no matter at what point in the chain of operators that operator is called. ObserveOn, on the other hand, affects the thread that the Observable will use below where that operator appears. For this reason, you may call ObserveOn multiple times at various points during the chain of Observable operators in order to change on which threads certain of those operators operate. The SubscribeOn operator can only be applied once and sets the starting thread. ObserveOn can be used to go from one thread to another at any point in the stream. So I think the following should do what you want: webService.requestGroups() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .flatMap(group -> { view.showGroup(group); return webService.requestItems(group) .subscribeOn(Schedulers.io()); }) .toList() .observeOn(AndroidSchedulers.mainThread()) .subscribe(items -> view.showItems(items)); But in my opinion this is too complicated. I would just subscribe to the first observable, and then start a new chain for each group, like this: webService.requestGroups() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(group -> { view.showGroup(group); webService.requestItems(group) .subscribeOn(Schedulers.io() .observeOn(AndroidSchedulers.mainThread()) .subscribe(items -> view.showItems(items)); }); A: Building on Samuel's answer, you could do it with an even simpler, non-nested syntax: webService.requestGroups() .subscribeOn(Schedulers.io()) // the first operator (requestGroups) on the IO thread .observeOn(AndroidSchedulers.mainThread()) //everything below on the main thread .map(group -> { view.showGroup(group); return group; }) .observeOn(Schedulers.io()) //everything below on the IO thread .flatMap(group -> { return webService.requestItems(group); }) .toList() .observeOn(AndroidSchedulers.mainThread()) //everything below on the main thread .subscribe(items -> view.showItems(items)); Two rules of thumb here: * *subscribeOn dictates on which thread the observable will begin executing, its placement in the chain is irrelevant and it should appear only once. *observeOn tells on which thread all subsequent operators will execute (until another observeOn is encountered); it may appear multiple times in the chain, changing execution thread of different code pieces (like in the example above).
unknown
d17102
val
If you want to bind the Property to a textblock first in public partial class MainWindow : Window { private Person _myWindowModel = new Person() public MainWindow() { InitializeComponent(); DataContext = _myWindowModel; } } and after that in your Window in WPF go to the TextBlock and add: Text="{Binding FullName}"
unknown
d17103
val
In Gmail Sender there is one method protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } which set account from which mail will be sent I am using the same this is my GmailSender public class GMailSender extends javax.mail.Authenticator { private String mailhost = "smtp.gmail.com"; private String user; private String password; private Session session; static { Security.addProvider(new JSSEProvider()); } public GMailSender(String user, String password) { this.user = user; this.password = password; Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", mailhost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.quitwait", "false"); session = Session.getDefaultInstance(props, this); } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception { Log.d("EmailSender", "Sending Mail initiallized"); try { MimeMessage message = new MimeMessage(session); DataHandler handler = new DataHandler(new ByteArrayDataSource( body.getBytes(), "text/plain")); message.setFrom(new InternetAddress(sender)); message.setSender(new InternetAddress(sender)); message.setSubject(subject); message.setDataHandler(handler); if (recipients.indexOf(',') > 0) message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); else message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients)); Transport.send(message); } catch (Exception e) { } } public class ByteArrayDataSource implements DataSource { private byte[] data; private String type; public ByteArrayDataSource(byte[] data, String type) { super(); this.data = data; this.type = type; } public ByteArrayDataSource(byte[] data) { super(); this.data = data; } public void setType(String type) { this.type = type; } public String getContentType() { if (type == null) return "application/octet-stream"; else return type; } public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(data); } public String getName() { return "ByteArrayDataSource"; } public OutputStream getOutputStream() throws IOException { throw new IOException("Not Supported"); } } } Edit 1: GmailSender sender=new GmailSender("YourUserName","YourPassword"); sender.sendMail("This is Subject","This is Body","[email protected]","[email protected]");
unknown
d17104
val
Simply match the limits of the x-axis ax2.set_xlim(g.axes[0,0].get_xlim())
unknown
d17105
val
The problem was solved by switching from RC6 builds to the github builds: This: "@angular/compiler-cli": "github:angular/compiler-cli-builds", "@angular/common": "2.0.0-rc.6", "@angular/compiler": "2.0.0-rc.6", "@angular/core": "2.0.0-rc.6", "@angular/forms": "^2.0.0-rc.6", "@angular/http": "2.0.0-rc.6", "@angular/platform-browser": "2.0.0-rc.6", "@angular/platform-browser-dynamic": "2.0.0-rc.6", "@angular/platform-server": "2.0.0-rc.6", "@angular/router": "3.0.0-rc.2", Was changed to "@angular/common": "github:angular/common-builds", "@angular/compiler": "github:angular/compiler-builds", "@angular/compiler-cli": "github:angular/compiler-cli-builds", "@angular/core": "github:angular/core-builds", "@angular/forms": "github:angular/forms-builds", "@angular/http": "github:angular/http-builds", "@angular/platform-browser": "github:angular/platform-browser-builds", "@angular/platform-browser-dynamic": "github:angular/platform-browser-dynamic-builds", "@angular/platform-server": "github:angular/platform-server-builds", "@angular/router": "github:angular/router-builds", "@angular/tsc-wrapped": "github:angular/tsc-wrapped-builds", And it compiles fine now.
unknown
d17106
val
First off, if you have the means and aren't required to write this code yourself, consider buying a UI component that solves you problem (of find an open source solution). For these types of tasks, there's a good chance that someone else has put a lot of effort into solving problems like this one. For reference, there's a teleric grid control for Silverlight with some demos. If you can't buy a component, here's some approaches I've seen: * *Set up a paging system where the data for the current page is loaded, and new data isn't loaded until the pages are switched. You could probably cache previous results to make this work more smoothly. *Load data when needed, so when the user scrolls down/sideways, data is loaded once cells are reached that haven't had data loaded. One last idea that comes to mind is to gzip the data on the server before sending. If your bottleneck is transmission time, compression speed things up for the type of data you're working with. A: You should take into consideration that you are possibly exceeding the command timeout on your data source. The default for LINQ to SQL for example is 30 seconds. If you wanted to increase this, one option is to go to the constructor and change it as follows: public SomeDataClassesDataContext() : base(global::System.Configuration.ConfigurationManager.ConnectionStrings["SomeConnectionString"].ConnectionString, mappingSource) { this.CommandTimeout = 1200; OnCreated(); }
unknown
d17107
val
Following is the code to get stored value from your xml calss. for (int i = 0 ; i <[array count];i++) { XmlClass *class1 = (XmlClass*) [array objectAtIndex:i]; NSString *strLat = class1.latitude; NSString *strLong = class1.longitude; } A: suppose u have use array in XML file is listofPoint in which u have add your class's object.Now u synthesize a NSMutableArray in app delegate file. And where you are doing parsing event there after completion of parsing make copy of array listofPoint to appdelegate array. and in next class define object of class which you have add in listofPoint array. And use this syntax. yourclass *Object=[[yourclass alloc]init]; Object=[appDelegate.Array objectAtIndex:0]; NSLog(@"%f",Object.var); it will work. A: for (int i = 0 ; i <[array count];i++) { YourXmlClass *x = [array objectAtIndex:i] NSString *s = x.latitude; NSString *s1 = x.longitude; }
unknown
d17108
val
You need either a geo IP capable or latency based DNS service (e.g. AWS Route 53) to make shure visitors from a distinct region connect to the right server. See http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html if it's an option for you to use Route53.
unknown
d17109
val
Detect if “enable system diagnostics” is checked for conditionals in pipeline file and scripts The answer is yes. If we enable the checkbox "enable system diagnostics" in the pipeline run UI, we could get following info in the build log: agent.diagnostic : true So, we could use this variable for conditionals in pipeline file and scripts. But, there is a little different from the Boolean variables we usually use. If we do not enable the checkbox enable system diagnostics, Azure devops will not create this variable to overwrite the variable sysytem.debug. So this variable does not exist at this time, we cannot directly determine whether its value is true or false. We could judge whether this value exists to judge its result. Below is my test bash scripts for this condition: - bash: | if [ -z "$(agent.diagnostic)" ] then echo "enable system diagnostics is Unchecked" else echo "enable system diagnostics is Checked" fi displayName: 'enable system diagnostics' A: This is equivalent to the System.Debug variable. As an environment variable, SYSTEM_DEBUG.
unknown
d17110
val
Found the solution for me - in build.gradle I changed this line: proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' to this: proguardFiles 'proguard-rules.pro' i.e. take out the proguard-android.txt portion out. This was based on this answer which stated that If you don't want to optimize, use the proguard-android.txt configuration file instead of this one, which turns off the optimization flags Not sure it's what you had, but worth a shot. Also, I'd make sure you understand whether you're on R8 (the new minifier) or actually Proguard, which is rapidly transitioning out Cheers!
unknown
d17111
val
The find_all_* methods always return an Array (which could be empty)! CardAssociation.find_all_by_deck_id(3) # => Array of results CardAssociation.find_all_by_deck_id(3).first # => first result of the Array or nil if no result I advise you to first read the Ruby on Rails Style Guide, and then use the Rails3 way of finding object with ActiveRecord: CardAssociation.where(:deck_id => 3) # => Array of results CardAssociation.where(:deck_id => 3).first # => first result of the Array if exists In your case, a scope can be set up on the Card model: You said: "Now I want to be able to return a list of all cards from the join table, given the deck id" class Card < ActiveRecord::Base scope :for_deck, lambda { |deck| joins(:card_associations).where('card_associations.deck_id = ?', deck.try(:id) || deck) } end This scope can be used like following: Card.for_deck(deck) # returns an Array of Card objects matching the deck.id As defined in the scope, the parameter of Card.for_deck(deck) can be a deck object or a deck_id (type Integer) Hope this helped!
unknown
d17112
val
The trick is to add a couple layers of wrapper-divs. The first layer is set to white-space: nowrap and max-width:50% which means that the elements inside can't wrap, and are constrained to 50% of the width of the parent. Then you set the white space back to normal, and make the second layer display:inline-block so that these divs have to play by text alignment rules. Then you set both of them to vertical-align:middle; Just one won't work because vertical align is relative to the baseline of the text, not the containing block element. So in this way we have constrained ourselves to one line of "text", composed of two div elements both aligned such their middle is at the text baseline, and ensured that their size must be no more than 50% of the parent container. EDIT: I discovered after little more playing that you need to add some max-width:100% to keep the image from pushing the text out the right hand side. EDIT 2: I should have mentioned that this requires IE-8 standards mode, added meta-equiv to tell IE-8 to behave itself, but giving a proper doctype or sending an http response header can achieve the same thing google IE8 standards mode for all that stuff. <html > <head> <title>Test</title> <meta http-equiv="X-UA-Compatible" content="IE=8" /> <style type="text/css"> .wrapper1 { white-space:nowrap; max-width:50%; } .wrapper2 { white-space:normal; display:inline-block; vertical-align:middle; max-width:100%; } .variable-img { max-width:100%; } </style> </head> <body> <div class="wrapper1"> <div class="wrapper2"> <img class="variable-img" src="test.png"> </div> <div class="wrapper2"> <div id="box"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</div> </div> </div> </body> </html>
unknown
d17113
val
Array lists in Java have both a size and a capacity. * *Size tells you how many items are there in the list, while *Capacity tells you how many items the list can hold before it needs to resize. When you call ArrayList(int) constructor, you set the capacity, not the size, of the newly created array list. That is why you see zero printed out when you get the size. Having a capacity of 4 means that you can add four integers to the list without triggering a resize, yet the list has zero elements until you start adding some data to it. A: You have used the ArrayList constructor that determines its initial capacity, not its initial size. The list has a capacity of 4, but nothing has been added yet, so its size is still 0. Quoting from the linked Javadocs: Constructs an empty list with the specified initial capacity. Also, don't use set to add to the list. That method replaces an element that is already there. You must add to the list first (or use the other overloaded add method).
unknown
d17114
val
For starters have another look at your indexes. You begin with: if len(arr1) == 0: return arr2[len(arr2)-k-1] elif len(arr2) == 0: return arr1[len(arr1)-k-1] But surely if arr1 is in ascending order, and arr2 is in descending order the kth minimal element will not be found in the same location.
unknown
d17115
val
What you currently do is good , when you set the text of the textView to attributed string make bool flag say it's name is textEdited = true with a string part that the user types say it's name userStr , when textView change method is triggered check that bool and according to it make the search if it's true proceed search with userStr if it's not proceed search with whole textView text , don't forget to make textEdited= false after every zero suggested result Edit: regarding the cursor put a label under the textfield with the same font as the textView and make it's background darkGray , also make background of the textview transparent and every attributed string assign it to the label so plus part of the label will be shown and cursor will be as it is in the textView
unknown
d17116
val
The first step is to join those lines together, either on the shipper side (filebeat can do this), or with the multiline codec in logstash.
unknown
d17117
val
You must ensure that it is impossible for one thread to access an object while another thread might be modifying it. You have not done this, so the results are unpredictable. One solution would be to call pthread_join on all the threads before looking at the values they are setting.
unknown
d17118
val
Does it need to be double-escaped? i.e. (replace-regexp-in-string "\/" "\\\\" path) A: Try using the regexp-quote function, like so: (replace-regexp-in-string "/" (regexp-quote "\\") "this/is//a/test") regexp-quote's documentation reads (regexp-quote string) Return a regexp string which matches exactly string and nothing else. A: What you are seeing in "C:\\foo\\bar" is the textual representation of the string "C:\foo\bar", with escaped backslashes for further processing. For example, if you make a string of length 1 with the backslash character: (make-string 1 ?\\) you get the following response (e.g. in the minibuffer, when you evaluate the above with C-x C-e): "\\" Another way to get what you want is to switch the "literal" flag on: (replace-regexp-in-string "/" "\\" path t t) By the way, you don't need to escape the slash. A: Don't use emacs but I guess it supports some form of specifying unicode via \x e.g. maybe this works (replace-regexp-in-string "\x005c" "\x005f" path)) or (replace-regexp-in-string "\u005c" "\u005f" path))
unknown
d17119
val
This should do it: result = None with open('input.txt') as f: result = [tuple(line.split()) for line in f] for t in result: print(t) A: Try this : # open your_file for line in your_file: t = tuple(line.split()) print t
unknown
d17120
val
Found that it has something to do with jQuery UI CSS file. When I exclude it, the works. When I added an effect to the hide() and show() function, then it worked properly.
unknown
d17121
val
Replace ret=session.run(root) with ret = tf.where(tf.is_nan(root), tf.zeros_like(root), root).eval() Refer tf.where
unknown
d17122
val
Maybe you already have figured this out. if not, please try installing the ssh package. install.packages("ssh")
unknown
d17123
val
Your code has two issues. Firstly, you're defining width as a function, so passing it as a value to the css() setter won't have the effect you expect. Secondly, your selector is not quite right. You need a . prefix on the class selector, and no space between the values as both classes are on the same element. Try this version, with some additional logic amendments: $(document).ready(function() { var person = "Rick"; var var1 = 2; var $element = $('td').filter(function() { return parseInt($(this).text().trim(), 10) == var1; }).append('<br /><span class="calendar_element ' + person + '"></span>'); $(window).on('resize', function() { var length = 3; var width = $element.width() * length; $element.find('.calendar_element.' + person).css('width', width); }).resize(); }); div.class1 { position: relative; } table { border: 1px solid navy; width: 70%; text-align: center; } table th { text-align: center; width: 100px; height: 20px; } table td { width: 100px; height: 100px; vertical-align: top; text-align: right; border: 1px solid #c6c6ec; } span.calendar_element { background-color: purple; height: 14px; display: inline-block; padding: 2px; z-index: 1; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div class="class1"> <table> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> </tr> <tr> <td>7</td> <td>8</td> <td>9</td> <td>10</td> <td>11</td> <td>12</td> </tr> </tbody> </table> </div>
unknown
d17124
val
I figured it out. It's not very elegant (and I invite others to submit a more efficient approach) but... Do NOT create the new column with df$day1count= ifelse(df$day==1, df$count, NA) as I did in the original example. Instead, start by making a duplicate of df, but which only contains rows from day 1 tmpdf = df[df$day==1,] Rename count as day1count, and remove day column tmpdf = rename(tmpdf, c("count"="day1count")) tmpdf$day = NULL Merge the two dataframes by site newdf = merge(x=df,y=tmpdf, by="site") newdf site day count day1count 1 A 1 2 2 2 A 2 10 2 3 B 1 3 3 4 B 2 12 3 A: With tidyverse you could do the following: library(tidyverse) df %>% group_by(site) %>% mutate(day1count = first(count)) Output # A tibble: 4 x 4 # Groups: site [2] day site count day1count <int> <fct> <int> <int> 1 1 A 2 2 2 1 B 3 3 3 2 A 10 2 4 2 B 12 3 Data df <- read.table( text = "day site count 1 A 2 1 B 3 2 A 10 2 B 12", header = T )
unknown
d17125
val
As of PHP 7.3 compact() will trigger an error when referencing undefined variables. This has been fixed in CakePHP 2.10.13, either upgrade your application (preferred), or downgrade your PHP version. https://github.com/cakephp/cakephp/pull/12487
unknown
d17126
val
This query work in sql server. Only question is how to handle those sessions that span or end at midnight, how they are represented. Set up sample data: declare @t table(session_start time, session_stop time) insert @t values ('1:00','1:05'),('1:00','1:10'),('1:00','1:15'),('1:11','1:19') Query based on a CTE. Create the time buckets. If CTEs are not available, create a table containing these entries instead., and rest of the query is unchanged. ;with valid_times as ( select convert(time,'00:00') as valid_start, convert(time,'00:15') as valid_end union all select dateadd(minute,15,valid_start), dateadd(minute,15,valid_end) from valid_times where valid_start<='23:30' ) select valid_start, valid_end, sum(case when datediff(minute, case when session_start<valid_start then valid_start else session_start end, case when session_stop>valid_end then valid_end else session_stop end )>=5 then 1 else 0 end) as AQH from valid_times left join @t t on valid_end>=session_start and valid_start<=session_stop group by valid_start, valid_end
unknown
d17127
val
A right-handed coordinate system always looks down the -Z axis. If +X goes right, and +Y goes up (which is how all of OpenGL works), and the view is aligned to the Z axis, then +Z must go towards the viewer. If the view was looking down the +Z axis, then the space would be left-handed. A: The problem is that I have to turn 180 deg around the y-axis to see my objects. It appears as the identity rotation is looking in -z. Yes it is. The coordinate systems provided yb OpenGL in form for glOrtho and glFrustum are right handed (take your right hand, let the thumb towards the right, the index finger up, then the index finger will point toward you). If you modeled your matrix calculations along those, then you'll get a right handed system as well. A: Alright completely rewrote this last night and I hope you find it useful if you haven't already came up with your own solutions or someone else who comes along with a similar question. By default your forward vector looks down the -Z, right vector looks down the +X, and up vector looks down the +Y. When you decide to construct your world it really doesn't matter where you look if you have a 128x128 X,Z world and you are positioned in the middle at 64x64 how would any player know they are rotated 0 degrees or 180 degrees. They simply would not. Now you mentioned you dislike the glRotatef and glTranslatef. I as well will not use methods that handle the vector and matrix math. Firstly I use a way where I keep track of the Forward, Up, and Right Vectors. So imagine yourself spinning around in a circle this is you rotating your forward vector. So when a player wants to let's say Run Straight ahead. you will move them along the X,Z of your Forward vector, but let's say they also want to strafe to the right. Well you will still move them along the forward vector, but imagine 90 degrees taken off the forward vector. So if we are facing 45 degrees we are pointing to the -Z and -X quadrant. So strafing will move us in the -Z and +X quadrant. To do this you simple do negate the sin value. Examples of both below, but this can be done differently the below is rough example to better explain the above. Position.X -= Forward.X; //Run Forward. Position.Z -= Forward.Z; Position.X += Forward.Z; //Run Backwards. Position.Z += Forward.Z Position.X += Forward.X; //Strafe Right. Position.Z -= Forward.Z; Position.X -= Forward.X; //Strafe Left. Position.Z += Forward.Z; Below is how I initialize my view matrix. These are to only be performed one time do not put this in any looping code. glMatrixMode(GL_MODELVIEW); view_matrix[4] = 0.0f; //UNUSED. view_matrix[3] = 0.0F; //UNUSED. view_matrix[7] = 0.0F; //UNUSED. view_matrix[11] = 0.0F; //UNUSED. view_matrix[15] = 1.0F; //UNUSED. update_view(); glLoadMatrix(view_matrix); Then this is the update_view() method. This is to only to be called during a change in the view matrix. public void update_view() { view_matrix[0] = Forward[0]; view_matrix[1] = Up[1] * Forward[1]; view_matrix[2] = Up[0] * -Forward[1]; view_matrix[5] = Up[0]; view_matrix[6] = Up[1]; view_matrix[8] = Forward[1]; view_matrix[9] = Up[1] * -Forward[0]; view_matrix[10] = Up[0] * Forward[0]; } The Position vectors are matricies [12], [13], and [14] and are negated. You can choose to store these or just use matrix[12], [13], [14] as the vector for position. view_matrix[12] = -Position.x; view_matrix[13] = -Position.y; view_matrix[14] = -Position.z;
unknown
d17128
val
Like-gating is not allowed by the Facebook platform policies (chapter 4.5). See * *https://developers.facebook.com/policy/#properuse Only incentivize a person to log into your app, enter a promotion on your app’s Page, or check-in at a place. Don’t incentivize other actions.
unknown
d17129
val
You can use the sys.columns table to get a list of columns and build a dynamic query. This query will return a 'KeepThese' value for every record you want to keep based on your given criteria. -- insert test data create table EmployeeMaster ( Record int identity(1,1), FirstName varchar(50), LastName varchar(50), EmployeeNumber int, CompanyNumber int, StatusFlag int, UserName varchar(50), Branch varchar(50) ); insert into EmployeeMaster ( FirstName, LastName, EmployeeNumber, CompanyNumber, StatusFlag, UserName, Branch ) values ('Jake','Jones',1234,1,1,'JJONES','PHX'), ('Jake','Jones',1234,1,1,NULL,'PHX'), ('Jake','Jones',1234,1,1,NULL,NULL), ('Jane','Jones',5678,1,1,'JJONES2',NULL); -- get records with most non-null values with dynamic sys.column query declare @sql varchar(max) select @sql = ' select e.*, row_number() over(partition by e.FirstName, e.LastName, e.EmployeeNumber, e.CompanyNumber, e.StatusFlag order by n.NonNullCnt desc) as KeepThese from EmployeeMaster e cross apply (select count(n.value) as NonNullCnt from (select ' + replace(( select 'cast(' + c.name + ' as varchar(50)) as value union all select ' from sys.columns c where c.object_id = t.object_id for xml path('') ) + '#',' union all select #','') + ')n)n' from sys.tables t where t.name = 'EmployeeMaster' exec(@sql) A: Try this. ;WITH cte AS (SELECT Row_number() OVER( partition BY firstname, lastname, employeenumber, companynumber, statusflag ORDER BY (SELECT NULL)) rn, firstname, lastname, employeenumber, companynumber, statusflag, username, branch FROM employeemaster), cte1 AS (SELECT a.firstname, a.lastname, a.employeenumber, a.companynumber, a.statusflag, Row_number() OVER( partition BY a.firstname, a.lastname, a.employeenumber, a.companynumber, a.statusflag ORDER BY (CASE WHEN a.username IS NULL THEN 1 ELSE 0 END +CASE WHEN a.branch IS NULL THEN 1 ELSE 0 END) )rn -- add the remaining columns in case statement FROM cte a JOIN employeemaster b ON a.firstname = b.firstname AND a.lastname = b.lastname AND a.employeenumber = b.employeenumber AND a.companynumbe = b.companynumber AND a.statusflag = b.statusflag) SELECT * FROM cte1 WHERE rn = 1 A: I test with MySQL and use NULL String concat to found the best record. Because LENGTH ( NULL || 'data') is 0. Only if all column not NULL some length exists. Maybe this is not perfekt. create table EmployeeMaster ( Record int auto_increment, FirstName varchar(50), LastName varchar(50), EmployeeNumber int, CompanyNumber int, StatusFlag int, UserName varchar(50), Branch varchar(50), PRIMARY KEY(record) ); INSERT INTO EmployeeMaster ( FirstName, LastName, EmployeeNumber, CompanyNumber, StatusFlag, UserName, Branch ) VALUES ('Jake', 'Jones', 1234, 1, 1, 'JJONES', 'PHX'), ('Jake', 'Jones', 1234, 1, 1, NULL, 'PHX'), ('Jake', 'Jones', 1234, 1, 1, NULL, NULL), ('Jane', 'Jones', 5678, 1, 1, 'JJONES2', NULL); My query idea looks like this SELECT e.* FROM employeemaster e JOIN ( SELECT firstname, lastname, employeenumber, companynumber, statusflag, MAX( LENGTH ( username || branch ) ) data_quality FROM employeemaster GROUP BY firstname, lastname, employeenumber, companynumber, statusflag HAVING count(*) > 1 ) g ON LENGTH ( username || branch ) = g.data_quality
unknown
d17130
val
You have to set the timeout value to 0. This will do the trick. struct timeval time_val_struct; time_val_struct.tv_sec = 0; time_val_struct.tv_usec = 0; A reference can be found here: https://linux.die.net/man/7/socket If the timeout is set to zero (the default) then the operation will never timeout
unknown
d17131
val
You might want to have a look at a similar question: Intercept windows open file Also for the people asking why someone would want to do this or immediately jump to malware conclusions. There are a number of legitimate uses for this. Especially if you are creating a B2B product that deals with automation or control over a customer's PC environment.
unknown
d17132
val
I suggest you to use some ImageLibraries to load Bitmaps efficiently. Some of them are Fresco, Glide, Piccasio. I suggest you to go with Glide. Have a look at it here
unknown
d17133
val
It seems like the most recent version of jdk can be downloaded by wget but not the files in the archives. As such, I'm using casper.js script to login to Oracle and to download. Following is my script to download Japanese version of jdk8u121. The current script will only attempt to download but will fail on redirect. I'm using download.sh bash script to scan the log to get the url with session parameter and using wget to do the actual download. You'll need to replace <username> and <password> with valid ones to login to Oracle site. Change values of jdkTag and jdkFileLink to get the jdk version you want to download. oraclejdk.js var casper = require('casper').create({ verbose: true, logLevel: 'info', // debug pageSettings: { userAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36", loadImages: false, loadPlugins: false } }); // login info var loginUrl='http://www.oracle.com/webapps/redirect/signon?nexturl=https://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html'; var username='<username>'; var password='<password>'; // accept license page info var jdkUrl='http://www.oracle.com/technetwork/'; var jdkTag='jdk-8u121-oth-JPR'; // download jdk info var jdkFileLink='jdk-8u121-oth-JPRXXXjdk-8u121-linux-x64.tar.gz'; // open login page casper.start(loginUrl); casper.thenEvaluate(function(username, password) { // this.capture('loginPage.png', {top:0, left:0, width:600, height:800}); document.querySelector("#sso_username").value = username; document.querySelector("#ssopassword").value = password; doLogin(document.LoginForm); }, { username: username, password: password }); // login to oracle site casper.then(function() { this.waitForUrl(jdkUrl, function() { // this.capture('jdkPage.png', {top:0, left:0, width:1200, height:800}); this.evaluate(function(jdkTag) { disableDownloadAnchors(document, false, jdkTag); hideAgreementDiv(document, jdkTag); writeSessionCookie('oraclelicense', 'accept-securebackup-cookie'); }, { jdkTag: jdkTag }); }, null, null, 5000); }); // accept license casper.then(function() { this.waitFor(function checkLink() { return this.evaluate(function(jdkTag) { return (document.getElementById('agreementDiv' + jdkTag).getAttribute('style') === 'visibility: hidden;'); }, { jdkTag: jdkTag }); }, function then() { // this.capture('acceptedLicense.png', {top:0, left:0, width:1200, height:800}); downlink = this.evaluate(function(jdkFileLink) { var jdkElement = document.getElementById(jdkFileLink); if (jdkElement) { var jdkLink = jdkElement.getAttribute("href"); jdkElement.click(); return jdkLink; } }, { jdkFileLink: jdkFileLink }); }, null, 5000); }); casper.run(); download.sh #!/bin/bash url=$(casperjs --web-security=no oraclejdk.js |grep "http://download.oracle.com/otn/java/jdk" $() | sed -e 's/^.*: //') jdk=$(echo "${url}" | sed -e 's/^.*jdk-/jdk/' |sed -e 's/?.*//') wget -O "${jdk}" "${url}" A: This is not a direct answer to your question...but Here is how i get URL to latest jdk download URL #!/bin/bash jdkwebinstallerDownloadPage="https://www.oracle.com"$(curl -s https://www.oracle.com/technetwork/java/javase/downloads/index.html | unix2dos | grep "<a name=\"JDK8\"" | sed 's/^.*\<a name=\"JDK8\" href=//g' | sed -r 's/>.*//g' | sed s/\"//g) ## Above yields https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html jdkinstallerDownloadURL=$(curl -s $jdkwebinstallerDownloadPage | grep windows | grep downloads | grep x64 | grep jdk | grep -v demos | sed -r 's/^.*https/https/g' | sed -r 's/\".*//g') ## yields https://download.oracle.com/otn/java/jdk/8u221-b11/230deb18db3e4014bb8e3e8324f81b43/jdk-8u221-windows-x64.exe I am now looking to how to download from this url using wget...given that i have cedentials to login into oracle's login webpage which is https://login.oracle.com/mysso/signon.jsp
unknown
d17134
val
file_exists() needs to use a file path on the hard drive, not a URL. So you should have something more like: $thumb_name = $_SERVER['DOCUMENT_ROOT'] . 'images/abcd.jpg'; if(file_exists($thumb_name)) { //your code } A: check your image path and then sever name & document root
unknown
d17135
val
Xcode 11.4 changed the way frameworks are linked and embedded, and you may experience issues switching between iOS devices and simulators. Flutter v1.15.3 and later will automatically migrate your Xcode project. To get unstuck, follow the instructions below; * *Quick fix (make your simulator work) rm -rf ios/Flutter/App.framework * *Official recommended Steps to migrate manually * *From the Flutter app directory, open ios/Runner.xcworkspace in Xcode. *In the Navigator pane, locate the Flutter group and remove App.framework and Flutter.framework. *In the Runner target build settings Build Phases > Link Binary With Libraries confirm App.framework and Flutter.framework are no longer present. Also confirm in Build Phases > Embed Frameworks. *Change the Runner target build settings Build Phases > Thin Binary script as follows: /bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed /bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" thin *In the Runner target Build Settings > Other Linker Flags (OTHER_LDFLAGS) add $(inherited) -framework Flutter Hope it helps! A: Xcode 11.4 changed the way frameworks are linked and embedded, which is causing issues switching between iOS devices and simulators. Please follow official guide on how to migrate your project. A: After several days trying to find a solution to test the Flutter app on iOS device, I finally found this: flutter clean flutter build ios -Open xCode and run app on your device. A: Updated to Xcode 11.4. Ios 13.4, Iphone X. App just fetches data using API. App started on white screen and then finally crashes, both on simulator and device. I followed the offical guide (I also rm -rf ios/Flutter/App.framework) flutter.dev/docs/development/ios-project-migration. I ran several times flutter clean I also tried deleting Pods/ folder and Podfile.lock, then reinstalling using pod install in the ios folder. As I am using async data I also added as 1st line in main() WidgetsFlutterBinding.ensureInitialized(); No help, app did not started either simulator. Then I removed ios/ and android/ folders. After that in project folder I ran command flutter create . that regenerates mentioned folders. After this my app started fine both on simulator and on device. I hope this would be help to others. NOTE!! if you have done any modifications manually to those folders please take backup or commit beforehand. A: * *Select your Target from "TARGETS" *Select 'Build Settings' *Under 'Build Options' -> Set 'Validate Workspace' To 'YES' *After successfully building, set it back to 'NO' Reason : "In Xcode 12+, the default option for Validate Workspace is internally not set. We need to set it manually to avoid this kind of error. There is no problem in setting back to the default 'NO' option. A: I have tried the solution on the official website of flutter but it didn't work for me, so I found a temporary solution which worked for me, but it took me some hard works: Here is my example with project stuck_framework which is a fresh new project (first time run on the simulator) * *I created 2 folders inside flutter project called "ios_simulator" and "ios_real_device". enter image description here *Now my first build was for the simulator, then I want to switch to a real device, I will move ios folder inside Flutter project to the "ios_simulator" *I open the project with visual studio code and run "flutter create ." and now I will choose a real device to rebuild the project ( if your simulator is online, please quit ). enter image description here *Now I wait for the build finish and run on the real device without any errors. Now I have 2 ios project 1 for simulators and one for real devices. *Next time when I want to run on the simulator again, I just remove the current ios folder and copy the ios folder which I placed on "ios_simulator" back out to flutter project folder. Hope this help A: Manually upgrading flutter to version 1.15 solve this issue as well. Running flutter version v1.15.17 helped me. Also, you can switch to beta or dev channels by running flutter channel command but be sure you check your code against all BC changes... A: In my case, it works only simulator(debug). if you want to deploy your app on the app store(release) i highly recommend you to upgrade flutter version using flutter version v1.15.17 otherwise you would encounter crashed app with white screen. just upgrade flutter version then all things work well A: This error is caused by the Xcode 11.4 and can be resolved by Removing / Re-Embedding frameworks and adding a new Run Script Phase. * *Under General -> "Frameworks, Libraries, and Embedded Content" * *Delete the frameworks that are causing errors. *After deleting, re-embed the frameworks in the same location. *Under Build Phases add a new run script phase. * *Select the "+" button in the "Build Phases" pane to create a "New Run Script Phase". *Confirm the script is the bottommost build phase, and configure its fields. * *The Shell text field should read /bin/sh (which is the default value). *In the text-input area, enter the shell command rm -r "FRAMEWORK_DIRECTORY/YOUR_FRAMEWORK.framework/" A: None of the other solutions here worked for me. In my case, the problem was fixed by searching my project for ONLY_ACTIVE_ARCH and changing them all to YES. I found my solution here: https://developer.apple.com/forums/thread/656509
unknown
d17136
val
The After passes a Scenario object (the scenario that just ran) to the block, you've just happened to name the variable page. Frequently, this variable will be called scenario. The undefined_method line is showing what object type (#<Cucumber::Ast::Scenario:0x5878608>) the NoMethodError is coming from in the error message. You should be able to execute code in an After block like you would in any other Cucumber step. After do |scenario| errors = page.execute_script("return window.JSErrorCollector_errors.pump()") if errors.any? STDOUT.puts '-------------------------------------------------------------' STDOUT.puts "Found #{errors.length} javascript #{pluralize(errors.length, 'error')}" STDOUT.puts '-------------------------------------------------------------' errors.each do |error| puts " #{error["errorMessage"]} (#{error["sourceName"]}:#{error["lineNumber"]})" end raise "Javascript #{pluralize(errors.length, 'error')} detected, see above" end end
unknown
d17137
val
I believe this is a solution (Python3, but easily adaptable to Python2). from itertools import combinations johns_animals = {'dog', 'cat', 'rhino', 'flamingo'} animal_sets = { 'house_animals': {'dog', 'cat', 'mouse'}, 'big_animals': {'elephant', 'horse', 'rhino'}, 'bird_animals': {'robin', 'flamingo', 'budgie'}, 'zoo_animals': {'rhino', 'flamingo', 'elephant'} } def minimal_superset(my_set): for n in range(1,len(animal_sets)+1): for set_of_sets in combinations(animal_sets.keys(), n): superset_union = set.union(*(animal_sets[i] for i in set_of_sets)) if my_set <= superset_union: return set_of_sets print(minimal_superset(johns_animals)) We go through all possible combinations of animal sets, returning the first combination that "covers up" the given set my_set. Since we start from smallest combinations, ie. consisting of one set, and advance to two-set, three-set etc., the first one found is guaranteed to be the smallest (if there are several possible combinations of the same size, just one of them is found).
unknown
d17138
val
try this: diff -wBt -u t1.txt t2.txt
unknown
d17139
val
You have three choices for loading DDS and other image files with WIC: * *Use DirectXTex (the library) *Use DDSTextureLoader/WICTextureLoader (the standalone versions) *or use DirectX Tool Kit (the library). There's no reason to use more than one of them in the same program, and it's going to conflict if you try. See this post. Unless you are writing a texture processing tool, or need support for the plethora of legacy DDS pixel formats, using DirectX Tool Kit is usually the simplest. The tutorials for DirectX Tool Kit covers this pretty well. The error you are getting indicates something much more basic to using Visual C++. The DirectXTex, DirectXTK libraries build using the recommended "Multithreaded DLL" version of the C/C++ Runtime (i.e. /MDd and /MD). The error indicates your program is building with "Statically linked" version of the C/C++ Runtime. See Microsoft Docs You didn't mention what compiler toolset you are using other than "not VS". See directx-vs-templates for a bunch of 'basic device and present loop' samples. If you don't use VS, there are 'CMakeLists.txt' available on that site. A: I was confused once again with DirectXTex and DirectXTK. I resolved the issue by: * *Removing DirectXTex *Downloading DirectXTK *Running the DirectXTK_Desktop_2019_Win10 solution *Changing the Build to Release and x64 *Opening the properties *Finding the option Runtime Library *Choosing Multi-threaded /MT *Building the solution In my source file, I include: #include <WICTextureLoader.h> and #include <DDSTextureLoader.h> I can now link to the generated static library directxtk.lib, without getting errors. Plus. If there are people who want to use things like /NODEFAULTLIB:library, but you don't use cl or Visual Studio, you can use the #pragma directive in your source file like this: #pragma comment(linker, "/NODEFAULTLIB:MSVCRT")
unknown
d17140
val
I'm pretty sure it's due to missing meta tags inside header. Here's Bootstrap template I've also added img-responsive class to your logo image and then the logo scales down as it supposed to. A: It does work but only for screen sizes more than 768 and less than 900px as written in your custom-css: @media screen and (min-width: 768px) and (max-width: 900px) { /* ---- Logo Woodtech ---- */ .logo { margin-top: 230px; } /* ---- Title ---- */ h2 { font-size: 5.9rem; margin-top: 130px; margin-bottom: 60px; line-height: 70px; } /* ---- Text ---- */ p { font-size: 34px; padding-bottom: 34px; } /* ---- Button ---- */ .contact-button { width: 400px; font-size: 4rem; height: 100px; } } If you want it to change styles for other widths then you need to add more media queries like the one added in your css. For e.g., if you want the button width to be 300px in between screen size 600px and 800px you can write the following: @media screen and (min-width: 600px) and (max-width: 800px){ .contact-button{ width:300px; } } And likewise you can add styles for other elements at different widths.
unknown
d17141
val
When curl_easy_perform() returns, it is done. It is as simple as that. Check the return code to figure out if it succeeded or not. A: in CURLOPTPROGRESSFUNCTION callback there are few parameters: int function(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow); dltotal is the total bytes to be downloaded, and dlnow is the number of bytes downloaded so far. The download is completed when dltotal == dlnow. dltotal is the total number of bytes libcurl expects to download in this transfer. dlnow is the number of bytes downloaded so far
unknown
d17142
val
Found it....Only static was missing in: private static final int[] STATE_ONE_SET = { R.attr.state_one }; private static final int[] STATE_TWO_SET = { R.attr.state_two }; private static final int[] STATE_THREE_SET = { R.attr.state_three }; But how come this creates a problem...?
unknown
d17143
val
I wonder if, given your data, you are not interested in the dendrogram and are just looking for a standard heatmap? If do, then perhaps using ggplot would give you the control you need? m <- with(Wizard_heatmap, as.matrix(table(factor(Response), factor(Gate)))) for(i in seq(nrow(Wizard_heatmap))) { m[Wizard_heatmap$Response[i], Wizard_heatmap$Gate[i]] <- Wizard_heatmap$n[i] } df <- setNames(as.data.frame(as.table(m)), c("Response", "Gate", "n")) library(ggplot2) ggplot(df, aes(Gate, Response, fill = n)) + geom_tile(color = "gray") + theme_minimal() + scale_fill_gradientn(colours = c("red4", "red", "orange", "yellow", "white"))
unknown
d17144
val
And here's the answer to my own question, should anyone else require a similar piece of code. Sub EditFindLoop() Dim myText As String Dim myFind As String Dim x As Integer myFind = "\[[0-9]*[0-9]*[0-9]\]" myText = "Figure " mySpace = ". " x = 1 Dim oRange As Word.Range Set oRange = ActiveDocument.Range With oRange.Find .Text = myFind .ClearFormatting .MatchWildcards = True .MatchCase = False .MatchWholeWord = False Do While .Execute = True If .Found Then oRange.InsertBefore (myText & x & mySpace) End If oRange.Start = oRange.End oRange.End = ActiveDocument.Range.End x = x + 1 Loop End With End Sub
unknown
d17145
val
To explain what happened, try this as an experiment: $ git checkout -b exp1 master <modify some file; git add; all the usual stuff here> $ git commit -m commit-on-exp1 At this point you have an experimental branch named exp1 with one commit that's not on master: ...--A--B <-- master \ C1 <-- exp1 Now we'll make an exp2 branch pointing to commit B, and copy commit C1 to a new commit C2 on branch exp2: $ git checkout -b exp2 master $ git cherry-pick exp1 The result is: C2 <-- exp2 / ...--A--B <-- master \ C1 <-- exp1 Now let's repeat with exp3, creating it so that it points to commit B and then copying exp1 again: $ git checkout -b exp3 master $ git cherry-pick exp1 Do you expect exp3 to point to commit C2? If so, why? Why did exp2 point to C2 rather than to C1 like exp1? The issue here is that commits C1 and C2 (and now C3 on exp3) are not bit-for-bit identical. It's true they have the same snapshot, the same author, the same log message, and even the same parent (all three have B as their one parent). But all three have different committer date-and-time-stamps, so they are different commits. (Use git show --pretty=fuller to show both date-and-time-stamps. Cherry-pick, and hence rebase too, copies the original author information including date-and-time, but because it's a new commit, uses the current date-and-time for the committer timestamp.) When you use git rebase, in general, you have Git copy commits, as if by cherry-pick. At the end of the copying, Git then moves the branch name so that it points to the last copied commit: ...--A--B <-- mainline \ C--D--E <-- sidebranch becomes: C'-D'-E' <-- sidebranch / ...--A--B <-- mainline \ C--D--E Here C' is the copy of C that's changed to use B as its parent (and perhaps has a different source snapshot than C), D' is the copy of D, and E' is the copy of E. There was only one name pointing to E; that name is now moved, so there is no name pointing to E. But if you have two names pointing to E originally, one of those two names still points to E: C'-D'-E' <-- sidebranch / ...--A--B <-- mainline \ C--D--E <-- other-side-branch If you ask Git to copy C-D-E again, it does that—but the new copies are not C'-D'-E' because they have new date-and-time stamps. So you end up with what you saw. Hence, if you want to move two or more names while copying some chain of commits, you'll be OK using git rebase to move the first name, but you will have to do something else—such as run git branch -f—to move the remaining names, so that they point to the commit copies made during the one rebase. (I've always wanted to have a fancier version of git rebase that can do this automatically, but it's clearly a hard problem in general.) A: Why the Branches Diverged Among the metadata used to calculate the hash for a git commit, not only is there an Author and an AuthorDate; there is also a Committer and a CommitterDate. This can be seen by running e.g. git show --pretty=fuller branch-01 branch-02 Each rebase (or cherry-pick) command updates the committer date in the new commit(s) according to the current time. Since the two rebases in the question were performed at different times, their CommitterDates differ, thus their metadata differ, thus their commit hashes differ. How To Move Branches/Tags Together torek correctly notes that if you want to move two or more names while copying some chain of commits, you'll be OK using git rebase to move the first name, but you will have to do something else—such as run git branch -f—to move the remaining names, so that they point to the commit copies made during the one rebase. About Author vs Committer From Difference between author and committer in Git?: The author is the person who originally wrote the code. The committer, on the other hand, is assumed to be the person who committed the code on behalf of the original author. This is important in Git because Git allows you to rewrite history, or apply patches on behalf of another person. The FREE online Pro Git book explains it like this: You may be wondering what the difference is between author and committer. The author is the person who originally wrote the patch, whereas the committer is the person who last applied the patch. So, if you send in a patch to a project and one of the core members applies the patch, both of you get credit — you as the author and the core member as the committer.
unknown
d17146
val
I've run into the same problem. Assuming you're using Active Record you have to call ActiveRecord::Base.establish_connection for each forked Resque worker to make sure it doesn't have a stale database connection. Try putting this in your lib/tasks/resque.rake task "resque:setup" => :environment do ENV['QUEUE'] = '*' Resque.after_fork = Proc.new { ActiveRecord::Base.establish_connection } end
unknown
d17147
val
Condition + ?Sized, B: Condition + ?Sized { left: Box<A>, right: Box<B>, } impl<A, B> Condition for And<A, B> where A: Condition + ?Sized, B: Condition + ?Sized { fn validate(&self, s: &str) -> bool { self.left.validate(s) && self.right.validate(s) } } and i want to serialize and de-serialize the condition trait (using serde) eg.: fn main() { let c = And { left: Box::new(Equal{ ref_val: "goofy".to_string() }), right: Box::new(Equal{ ref_val: "goofy".to_string() }), }; let s = serde_json::to_string(&c).unwrap(); let d: Box<dyn Condition> = serde_json::from_string(&s).unwrap(); } Because serde cannot deserialize dyn traits out-of-the box, i tagged the serialized markup, eg: #[derive(PartialEq, Debug, Serialize)] #[serde(tag="type")] pub struct Equal { ref_val: String, } and try to implement a Deserializer and a Vistor for Box<dyn Condition> Since i am new to Rust and because the implementation of a Deserializer and a Visitor is not that straightforward with the given documentation, i wonder if someone has an idea how to solve my issue with an easier approach? I went through the serde documentation and searched for solution on tech sites/forums. i tried out typetag but it does not support generic types UPDATE: To be more precise: the serialization works fine, ie. serde can serialize any concrete object of the Condition trait, but in order to deserialize a Condition the concrete type information needs to be provided. But this type info is not available at compile time. I am writing a web service where customers can upload rules for context matching (ie. Conditions) so the controller of the web service does not know the type when the condition needs to be deserialized. eg. a Customer can post: {"type":"Equal","ref_val":"goofy"} or {"type":"Greater","ref_val":"Pluto"} or more complex with any combinator ('and', 'or', 'not') {"type":"And","left":{"type":"Greater","ref_val":"Gamma"},"right":{"type":"Equal","ref_val":"Delta"}} and therefore i need to deserialze to a trait (dyn Condition) using the type tags in the serialized markup... A: I would say the “classic” way to solve this problem is by deserializing into an enum with one variant per potential “real” type you're going to deserialize into. Unfortunately, And is generic, which means those generic parameters have to exist on the enum as well, so you have to specify them where you deserialize. use serde::{Deserialize, Serialize}; use serde_json; // 1.0.91 // 1.0.152 pub trait Condition { fn validate(&self, s: &str) -> bool; } #[derive(PartialEq, Debug, Serialize, Deserialize)] pub struct Equal { ref_val: String, } impl Condition for Equal { fn validate(&self, s: &str) -> bool { self.ref_val == s } } #[derive(PartialEq, Debug, Serialize, Deserialize)] pub struct And<A, B> where A: Condition + ?Sized, B: Condition + ?Sized, { left: Box<A>, right: Box<B>, } impl<A, B> Condition for And<A, B> where A: Condition + ?Sized, B: Condition + ?Sized, { fn validate(&self, s: &str) -> bool { self.left.validate(s) && self.right.validate(s) } } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] enum Expr<A, B> where A: Condition + ?Sized, B: Condition + ?Sized, { Equal(Equal), And(And<A, B>), } fn main() { let c = And { left: Box::new(Equal { ref_val: "goofy".to_string(), }), right: Box::new(Equal { ref_val: "goofy".to_string(), }), }; let s = serde_json::to_string(&c).unwrap(); let d: Expr<Equal, Equal> = serde_json::from_str(&s).unwrap(); println!("{d:?}"); } Prints And(And { left: Equal { ref_val: "goofy" }, right: Equal { ref_val: "goofy" } }) A: I removed the generics from the combinator conditions, so i can now use typetag like @EvilTak suggested: #[derive(Serialize, Deserialize)] #[serde(tag="type")] pub struct And { left: Box<dyn Condition>, right: Box<dyn Condition>, } #[typetag::serde] impl Condition for And { fn validate(&self, s: &str) -> bool { self.left.validate(s) && self.right.validate(s) } } (on the downside, i had to remove the derive macros PartialEq, and Debug) Interesting side fact: i have to keep the #[serde(tag="type")] on the And Struct because otherwise the typetag will be omitted in the serialization (for the primitive consitions it is not needed) UPDATE: typetag adds the type tag only for trait objects so the #[serde(tag="type")] is not needed...
unknown
d17148
val
There are several flaws here: * *You should not use md5. Please use some other hashing algorithm (e.g. sha256) *In order to do what you are saying, the server needs to store the passwords in plaintext. This is a very bad practise, as if you get hacked, all the passwords will be compromised. Instead, you should store a salted hash of the password. More info here: https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet *This method is infeasible, as the timestamp cannot be possibly known by the server, except if the clock of the client and the server are synchronised to the millisecond (don't assume that they will be). Even if the clocks are completely synced, this will still not work. The time from when the client takes the timestamp until the packet reaches the server is variable, and the server would need to know exactly that time. Without the correct timestamp, the server won't be able to calculate the hash. Removing the timestamp will lead to replay attacks. *An attacker performing a man-in-the-middle attack can alter the HTML (or whatever) code on the fly and remove the hashing function (assuming it's performed in JavaScript). The browser will then transmit the password in clear. Of course the authentication will fail, but the attacker will have the password. *Probably other flaws also exist, but these are enough for the method to be inefficient I believe. Bottom line: Do not use HTTP for user authentication. I have not heard of any cases of secure authentication over HTTP. If SSL is very expensive, you can use it only for the login page. It is still a very bad practise, as an attacker can perform session hijacking by stealing session cookies (and other man-in-the-middle attacks), but at least the password will not be revealed this way. A: What you describe is a minor technical detail in a larger procedure, which you do not go into detail at all. I'm assuming that the larger purpose of that procedure is to log in? Then what happens after this token is exchanged? Does the user receive some sort of permanent token like a cookie? Then this is susceptible to: * *man in the middle attacks reading all communication *local network packet sniffing, famously publicised by the Firesheep attack Even if (that's a large if) this particular token scheme were flawless, the entire communication chain is observable by third parties and all private data (including identifying cookies) can be read in the clear by unauthorised users in a privileged network position (→ session hijacking).
unknown
d17149
val
TWCS is a compaction strategy. Compaction strategies have nothing to do with sstables being generated. It's a reconcile and cleanup "algorithm" once they are created. The way that TWCS works is that sstables will be consolidated into windows. The key word here is "consolidated". There is no guarantee that sstables will be "generated" in that timeframe, but whatever IS generated, after the window expires, will be consolidated together. So if you have, say, hourly windows/buckets, during that hour sstables may or may not get generated. If multiple sstables are created during the window they are compacted/consolidated/reconciled using STCS (similar sized sstables consolidated together). After the hour passes, any sstables that remain for that window will be compacted together into a single sstable. Over time you will see one sstable per window (or none if nothing was generated during that window). After your TTL and gc_grace passes, entire windows simply get removed (instead of the large effort of merging with others and then removing expired records). TWCS works very well if there is no overlap for rows within windows. If there is overlap, then the oldest windowed sstable will be unable to be removed until the newest sstable with overlapped records expire. In other words, TWCS works well for INSERTS that do not cross windows (remember updates and deletes are also considered inserts). You need to be sure to use TTL for cleanup (i.e. don't run delete statements as that will cause overlap). Also, from what I have discovered from using this, ensure to turn off repair for the tables that have TWCS as that can cause big problems (unseen overlap). So in short, TWCS does not cause sstables to get generated (there are rules for when sstables are created that have nothing to do with compaction strategies), it simply another method of keep things "clean". Hope that helps. A: There are several resources that may help you: * *https://academy.datastax.com/units/21017-time-window-compaction-dse-operations-apache-cassandra *https://www.youtube.com/watch?v=PWtekUWCIaw *https://thelastpickle.com/blog/2016/12/08/TWCS-part1.html
unknown
d17150
val
PhantomJS is a headless web-browser, it's not an FTP client, so it won't be able to help you. My main goal is synchronizing the files in the FTP with my computer I'd suggest using lftp. lftp -u user,password -e 'mirror /remote/server/files/ /local/computer/files/' ftp.myserver.com This will get files from the remote server to the local computer.
unknown
d17151
val
You can output it in php like this <?php echo do_shortcode( '[contact-form-7 id="617" title="capta contact form"]' ); ?> Search on web little bit before posting, Search on web little bit before posting, I found this on Google.
unknown
d17152
val
I thought about this for quite some time. In fact, I believe you are asking the wrong question (sorry). As was made clear in the comments, the "event" you are looking for is "something that increases the noise in my signal by a significant amount". The correct way to detect this, then, is to do a statistical test of the difference in the standard deviation (variance) between two sets of data. There is a thing called the F-test that does exactly this. Without boring you with the details, if you have two samples and compute their variance, you can answer the question "is the variance different" with the F test. To do this, you need the test statistic, (the ratio of the variances) and the number of degrees of freedom (the number of samples minus one). You can then calculate the probability that the difference is due to chance ("how often would you see a jump this big in two random samples from the same distribution?) - something called the p value. If the p value is small enough, you can say "this wasn't just by chance". Of course when you run 1000 comparisons, you will "by chance" get a 0.1% probability event happening on average one time; so you need to be prepared for some false positives (or accept that you will only see big changes that are VERY unlikely to occur by chance). I implemented this approach - and the Python code is below. The plots show that the signal changes "in a way that is hard to see"; but after analysis, the point where the change occurs stands out above the others (even though I increased the standard deviation by only 10%). A thing to note: I am using the diff of the sequence as my input to the calculation; this largely takes out the effect of a slowly changing underlying value so you are really looking at the pure noise. This works best if the sampling is such that subsequent samples are independent (i.e. it only really works if the samples have not been low-pass filtered; otherwise, just don't take the diff). I hope the code is fairly self-explanatory; let me know if you need further clarification. Your threshold can now be set probabilistically, depending on how many false positives you are willing to accept. # detect a sudden change in standard deviation of a sequence of measurmeents import numpy as np import matplotlib.pyplot as plt import scipy # a sequence of values with a mean and standard deviation # and then a sudden change in the standard deviation mu = 1000 # mean of signal sigma = 100 # standard deviation of signal increase = 1.1 # increase in standard deviation N1 = 10000 # number of datapoints before change L = 2500 # size of rolling window # create a series with a slight increase in noise: before = np.random.normal(mu,sigma,N1) after = np.random.normal(mu, increase*sigma, N1) sequence = np.concatenate((before, after), axis=0) twoD_img = np.histogram2d(range(0,2*N1), sequence, bins=(50,100)) plt.figure(); plt.subplot(4,1,1) plt.imshow(twoD_img[0].T,aspect='auto', extent = (0, 2*N1, np.min(sequence), np.max(sequence))); plt.title('input signal') # rolling standard deviation s = [np.std(sequence[ii:ii+L]) for ii in range(0,2*N1-L)] plt.subplot(4,1,2) plt.plot(s) plt.title('rolling standard deviation') # take the differences, and compute the average noise from that d = np.diff(sequence) d2 = d*d ## rolling mean of the diff squared: SS = [np.mean(d2[ii:ii+L]) for ii in range(0, len(d2)-L)] # compute the F statistic F = np.array([SS[ii]/SS[ii+L] for ii in range(0, (len(d2)-2*L))]) w = np.where(np.less(F,1)) F[w]=1/F[w] # the x coordinate of the point where shift happens is offset by L from the computed F: xi = np.arange(0,len(F))+L plt.subplot(4,1,3) plt.plot(xi, F); plt.title('F values') plt.xlabel('datapoint #') # compute log of probability that this is by chance: logProb = np.log(1-scipy.stats.f.cdf(F, dfn=L-1, dfd=L-1)) plt.subplot(4,1,4) plt.plot(xi, logProb) plt.title('log probability plot') plt.xlabel('datapoint #') # make some space for the labels plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.1, hspace=0.4) # and draw the result: plt.show()
unknown
d17153
val
You need to add loader (activityIndicator) while your process start and hide while process complete . And you need to manage that while process is working user not interact any thing in the current view // Start here dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ [MyApiManager postHitCount:hitCountModel block:^(id object, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ [self setUpCount]; // stop here }); if ([self checkError:error]) // stop here return; }]; });
unknown
d17154
val
def combinations(size: Int = sym.length) : List[List[T]] = { if (size == 0) List(List()) else { for { x <- sym.toList xs <- combinations(size-1) } yield x :: xs } } A: This should work: val input = List('A','C','G') (input ++ input ++ input) combinations(3) toList A: scala> def comb(s:String)=(s * s.length).combinations(s.length) comb: (s: String)Iterator[String] scala> comb("ACG").toList res16: List[String] = List(AAA, AAC, AAG, ACC, ACG, AGG, CCC, CCG, CGG, GGG) And if you wanted the resulting permutations: scala> comb("ACG").flatMap(_.toSeq.permutations.toList).toList res11: List[Seq[Char]] = List(AAA, AAC, ACA, CAA, AAG, AGA, GAA, ACC, CAC, CCA, ACG, AGC, CAG, CGA, GAC, GCA, AGG, GAG, GGA, CCC, CCG, CGC, GCC, CGG, GCG, GGC, GGG) You can leave out the toList but it's there so you can see the results. A: It seems no one has suggested the easiest---or, at least, easiest to read---solution. It is myList = List("A", "C", "G") for { i <- myList j <- myList k <- myList } yield List(i,j,k) (This is syntactic sugar for the following composition of maps: myList.flatMap(i => myList.flatMap(j => myList.map(k => List(i,j,k)))) to which the Scala compiler translates the above for expression.) A: With Scalaz: scala> import scalaz._ import scalaz._ scala> import Scalaz._ import Scalaz._ scala> def combine[A](xs: List[A]): List[List[A]] = { | xs.replicate[List](xs.size).sequence | } combine: [A](xs: List[A])List[List[A]] scala> combine(List('A', 'C', 'G')) res47: List[List[Char]] = List(List(A, A, A), List(A, A, C), List(A, A, G), List (A, C, A), List(A, C, C), List(A, C, G), List(A, G, A), List(A, G, C), List(A, G , G), List(C, A, A), List(C, A, C), List(C, A, G), List(C, C, A), List(C, C, C), List(C, C, G), List(C, G, A), List(C, G, C), List(C, G, G), List(G, A, A), List (G, A, C), List(G, A, G), List(G, C, A), List(G, C, C), List(G, C, G), List(G, G , A), List(G, G, C), List(G, G, G)) A: In ScalaZ 7 import scalaz._ import Scalaz._ def combinine[T](l: List[T]) = l.replicateM(l.size) A: Just making a more generic answers, from @opyate and @monnef: // considering that we want a permutation_size List.fill(permutation_size)(input).flatten.combinations(permutation_size).toList This will generate the permutation with repetition with size permutation_size: val a = List.fill(2)(List("A","B","C")).flatten.combinations(2).toList a: List[List[String]] = List(List(A, A), List(A, B), List(A, C), List(B, B), List(B, C), List(C, C)) and val a = List.fill(3)(List("A","B","C")).flatten.combinations(3).toList a: List[List[String]] = List(List(A, A, A), List(A, A, B), List(A, A, C), List(A, B, B), List(A, B, C), List(A, C, C), List(B, B, B), List(B, B, C), List(B, C, C), List(C, C, C))
unknown
d17155
val
If you are training the model on your own dataset, I would recommend limiting the number of labels/classes in your data to what you seek. For example if you only want your model to see balls, goal-posts and Not players, simply keep the classes as balls and goal-posts. (This reminds me of a classification problem where 0 stands for balls and 1 stands for goal-post). P.S you mentioned object detection and Not Localization, which is the purpose of the YOLO models.
unknown
d17156
val
This isn't self-contained, so it's not really an answer; but it's different to the other options you mentioned, so I'll add it anyway. (defmacro with-foo-functions (&rest forms) `(flet ((addone (x) (1+ x)) (addtwo (x) (+ 2 x))) ,@forms)) (defun foo (x) (with-foo-functions (addtwo x))) (defun bar (x) (with-foo-functions (addone x))) A: Emacs Lisp has dynamic binding. This is different from the lexical binding used by pretty much all other Lisps. For example, if you try to do the following in Common Lisp, you will get an error message saying that FOO is not defined: (defun bar () (foo 10)) (flet ((foo (x) (1+ x))) (bar)) In Emacs Lisp, however, since FOO is dynamically bound this will return 11 as the binding of FOO is available in BAR. Emacs Lisp does not provide lexical bindings for functions, so in order to achieve the same thing in Emacs Lisp you'll have to fake it by binding a lambda to a lexical variable and then use a macro to hide the FUNCALL: (lexical-let ((foo #'(lambda (x) (1+ x)))) (macrolet ((foo (x) `(funcall foo ,x))) (foo 10))) The other answer to this question suggests the use of a macro instead of the flet. This works, but it results in unnecessary code duplication. My solution prevents this at the expense of having to either write the macrolet part, or using funcall every time you want to call the function. One could write a macro to wrap all of this inside a lexical flet version if this is something that is needed often.
unknown
d17157
val
Only if you use the regex will TestNG know that you are not giving an absolute group name but you are indicating a pattern. So going by your example you would need to mention @Test(dependsOnGroups = { "init.* }) public method1() { //code goes here. } for TestNG to basically pick up any groups whose names begin with init
unknown
d17158
val
Use document.querySelectorAll.This will give a collection of all the a tag. Then iterate over it and add event listener. The test is a dummy function, you can replace it with other function function test() { console.log(" Test") } document.querySelectorAll("a").forEach(function(item) { item.addEventListener('click', function(e) { e.preventDefault(); test(); }) }) <a href="http://www.something.com">Some text</a> <a href="http://www.somethingmore.gov">Secret</a> A: I want these links to connect with an onclick function on body load show when i click a link to confirm first. You can use querySelectAll('a') then iterate through the links and add a generic click event. To get the user to confirm first, inside the event you could call confirm() and if the user does not want to continue you can stop the default behavior of the link using preventDefault() to ensure the link does not forward. var links = document.querySelectorAll('a'); links.forEach(function(element){ element.addEventListener('click', function(e){ var isContinue = confirm('Do you want to go to ' + this.href + ' ?'); if(!isContinue){ e.preventDefault(); } }) }) <a href="https://www.something.com">Some text</a> <a href="https://www.somethingmore.gov">Secret</a> A: I used onclick function for a tag function myFunction() { document.getElementById("demo").innerHTML = "Vote Me"; } <a onclick="myFunction()">Click me</a> <p id="demo"></p>
unknown
d17159
val
The code between array and non-array are the same, so you can write a single foreach $return = (array)$return; foreach ($return as $k => $v) { $return[ $k ] = preg_replace( '/\p{C}+/u', '', $v ); $return[ $k ] = ucwords( $v ); foreach ( $exceptions as $exception => $fix ) { $return[$k] = str_replace( $exception, $fix, $return[$k] ); } } Alternatively, this is what you'd use a function for function fix_things($s) { $exceptions = array('DAS' => 'das', 'DA' => 'da', 'DE' => 'de', 'DOS' => 'dos', 'DO' => 'do'); $s = preg_replace( '/\p{C}+/u', '', $s ); $s = ucwords( $s ); foreach ( $exceptions as $exception => $fix ) { $s = str_replace( $exception, $fix, $s ); } return $s; } Then call that function from your main code if (!\is_array($return)) { $return = fix_things($return); else { foreach ($return as $k => $v) { $return[$k] = fix_things($v); } }
unknown
d17160
val
I don't know how, but I deleted the node_module folder and the package-lock.json file and ran npm install and everything started working again. Thank you all.
unknown
d17161
val
You can select that information from the INFORMATION_SCHEMA.COLUMNS table. select DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE, NUMERIC_SCALE, NUMERIC_PRECISION -- And many other properties from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename' and COLUMN_NAME = 'yourcolumn'
unknown
d17162
val
The first is a safe open and close tag variation, the second is the so called short-open tag. The second one is not always available, use the first option if it's possible. You could check the availability of short open tags in php.ini, at the short_open_tag. A: The problem with short open tags is that the following: <?xml version="1.0" ?> will cause problems if you're allowed to use short tags (i.e. <? and ?>). <?php is less open to misinterpretation. Whether or not you're allowed to use short tags is defined by the ini directive short_open_tag. A: Also I think shorttags are being removed in one of the upcomming releases. Edit: I was wrong. Farewell <% They will remove support for the ASP style tags, but the PHP short-code tag will remain - so to those on php general who reckon the short-tag is 'depreceated' - hah! ;) http://phpmysqldev.blogspot.com/2007/05/php-6.html A: There is no difference. The ability to use <? ?> is defined in your php.ini file - usually accessed only by the server host. You can find more information here A: Nothing AFAIK, however I have had servers (shared) where the settings do not support shorthand tags <? ?>, so I usually stick with the <?php ?> for good measure. A: Note short_open_tag = Off did not effect the <?= shorthand tag, which is equivalent to <?php echo A: As @erenon explained here: https://stackoverflow.com/a/1808372/1961535 The difference is that short_open_tag in some cases isnt available. You can check the status by accessing the php.ini file but in case of shared hosting server, the host does not always allow edits to php.ini file. You can easily print the phpinfo as explained here: https://www.php.net/manual/en/function.phpinfo.php phpinfo(); search for short_open_tag as shown below It is always better to use full tag because that will always be supported in every version of PHP weather old file or new.
unknown
d17163
val
As I mentioned in my comments, above, the most obvious problem is that you're invoking methods that use condition before you initialize condition. Make sure initialize condition before you start calling updateCompetitionResults, etc. In terms of a more radical change, I might suggest retiring NSCondition altogether, and use operation queues: * *I might use NSOperationQueue (or you can use dispatch groups, too, if you want, but I like the operation queue's ability to configure how many concurrent operations you can operate ... also if you get to a point that you want to cancel operations, I think NSOperationQueue offers some nice features there, too). You can then define each download and processing as a separate NSOperation (each of the downloads should happen synchronously, because they're running in an operation queue, you get the benefits of asynchronous operations, but you can kick off the post-processing immediately after the download is done). You then just queue them up to run asynchronously, but define a final operation which is dependent upon the other four will kick off as soon as the four downloads are done. (By the way, I use NSBlockOperation which provides block-functionality for NSOperation objects, but you can do it any way you want.) *And whereas your updateProgramContent might download asynchronously, it processes the four downloaded files sequentially, one after another. Thus, if the first download takes a while to download, it will hold up the post-processing of the others. Instead, I like to encapsulate both the downloading and the post processing of each of the four plist files in a single NSOperation, each. Thus, we enjoy maximal concurrency of not only the downloading, but the post-processing, too. *Rather than using the AFNetworking (which I'm generally a big fan of) plist-related method, I might be inclined to use NSDictionary and NSArray features that allow you to download a plist from the web and load them into the appropriate structure. These dictionaryWithContentsOfURL and arrayWithContentsOfURL run synchronously, but because we're doing this in a background operation, everything runs asynchronously like you want. This also bypasses the saving them to files. If you wanted them saved to files in your Documents directory, you can do that easily, too. Clearly, if you're doing something sophisticated in your downloading of the plist files (e.g. your server is engaging in some challenge-response authentication), you can't use the convenient NSDictionary and NSArray methods. But if you don't need all of that, the simple NSDictionary and NSArray methods, ___WithContentsOfURL make life pretty simple. Pulling this all together, it might look like: @interface ViewController () @property (nonatomic, strong) NSArray *competitions; @property (nonatomic, strong) NSDictionary *competitionResults; @property (nonatomic, strong) NSDictionary *competitionRecalls; @property (nonatomic, strong) NSDictionary *competitionProgress; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self transfer]; } - (void)allTransfersComplete { BOOL success; if (self.competitions == nil) { success = FALSE; NSLog(@"Unable to download competitions"); } if (self.competitionResults == nil) { success = FALSE; NSLog(@"Unable to download results"); } if (self.competitionRecalls == nil) { success = FALSE; NSLog(@"Unable to download recalls"); } if (self.competitionProgress == nil) { success = FALSE; NSLog(@"Unable to download progress"); } if (success) { NSLog(@"all done successfully"); } else { NSLog(@"one or more failed"); } } - (void)transfer { NSURL *baseUrl = [NSURL URLWithString:@"http://insert.your.base.url.here/competitions"]; NSURL *competitionsUrl = [baseUrl URLByAppendingPathComponent:@"competitions.plist"]; NSURL *competitionResultsUrl = [baseUrl URLByAppendingPathComponent:@"competitionresults.plist"]; NSURL *competitionRecallsUrl = [baseUrl URLByAppendingPathComponent:@"competitionrecalls.plist"]; NSURL *competitionProgressUrl = [baseUrl URLByAppendingPathComponent:@"competitionprogress.plist"]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; queue.maxConcurrentOperationCount = 4; // if your server doesn't like four concurrent requests, you can ratchet this back to whatever you want // create operation that will be called when we're all done NSBlockOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{ // any stuff that can be done in background should be done here [[NSOperationQueue mainQueue] addOperationWithBlock:^{ // any user interface stuff should be done here; I've just put this in a separate method so this method doesn't get too unwieldy [self allTransfersComplete]; }]; }]; // a variable that we'll use as we create our four download/process operations NSBlockOperation *operation; // create competitions operation operation = [NSBlockOperation blockOperationWithBlock:^{ // download the competitions and load it into the ivar // // note, if you *really* want to download this to a file, you can // do that when the download is done self.competitions = [NSArray arrayWithContentsOfURL:competitionsUrl]; // if you wanted to do any post-processing of the download // you could do it here. NSLog(@"competitions = %@", self.competitions); }]; [completionOperation addDependency:operation]; // create results operation operation = [NSBlockOperation blockOperationWithBlock:^{ self.competitionResults = [NSDictionary dictionaryWithContentsOfURL:competitionResultsUrl]; NSLog(@"competitionResults = %@", self.competitionResults); }]; [completionOperation addDependency:operation]; // create recalls operation operation = [NSBlockOperation blockOperationWithBlock:^{ self.competitionRecalls = [NSDictionary dictionaryWithContentsOfURL:competitionRecallsUrl]; NSLog(@"competitionRecalls = %@", self.competitionRecalls); }]; [completionOperation addDependency:operation]; // create progress operation operation = [NSBlockOperation blockOperationWithBlock:^{ self.competitionProgress = [NSDictionary dictionaryWithContentsOfURL:competitionProgressUrl]; NSLog(@"competitionProgress = %@", self.competitionProgress); }]; [completionOperation addDependency:operation]; // queue the completion operation (which is dependent upon the other four) [queue addOperation:completionOperation]; // now queue the four download and processing operations [queue addOperations:completionOperation.dependencies waitUntilFinished:NO]; } @end Now, I don't know which of your plist's are arrays and which are dictionaries (in my example, I made competitions an array and the rest were dictionaries keyed by the competition id), but hopefully you get the idea of what I was shooting for. Maximize concurrency, eliminate NSCondition logic, really make the most of NSOperationQueue, etc. This may be all to much to take in, but I only mention it as an alternative to NSCondition. If your current technique works, that's great. But the above outlines how I would tackle a challenge like this.
unknown
d17164
val
The mutation to create the task has the following shape: mutation b { createTask( data: { content: "Task1" completed: false dateToDo: { connect: { id: "cjqzjvk6w000e0999a75mzwpx" } } } ) { id } } The type DayCreateOneWithoutTasksInput Prisma is asking for is autogenerated and is the one expected for the field dataToDo. The name means that Prisma would accept a type that creates one Day node but does not have the field tasks or a type that specifies a connection. The WithoutTasksInput part states is there because the type can only be used nested in a mutation where you start from a task, Prisma therefore already has the value to fill in for the tasks field on the nested Day node and you do not need to specify it if you create the day instead of connecting an existing one. If you use the Playground you can explore the schema that contains all the types on the right side. schema explorer in the playground Hope that helps!
unknown
d17165
val
Sorry, I'm still newbie on BeanShell and Java, but can it does works? (It's like a workaround...) String [] tagArray = new String [] { "ACRU", "ANTO", "CHAR", "COUN", "EXEC", "ISDI", "LADT", "LEVY", "LOCL", "LOCO", "MARG", "OTHR", "POST", "REGF", "SHIP", "SPCN", "STAM", "STEX", "TRAN", "TRAX", "VATA", "WITH", "COAX", "ACCA" }; for (i: tagArray) { // it was a test: print(i); eval("String get" + i + " = swiftMessage.getTagData(\"19A\", \":" + i + "//\")"); } (Sorry for my bad english too...) A: It seems that this worked quite well. Store all the values I need in an array: String [] tagArray = new String [] { ":ACRU//",":ANTO//",":CHAR//",":COUN//",":EXEC//",":ISDI//",":LADT//",":LEVY//",":LOCL//",":LOCO//",":MARG//",":OTHR//",":POST//",":REGF//",":SHIP//",":SPCN//",":STAM//",":STEX//",":TRAN//",":TRAX//",":VATA//",":WITH//",":COAX//",":ACCA//" }; And create a function to loop and add: double sumTags(SwiftMessage inboundSwiftmessage, String inboundTagNumber, String [] inboundTagArray){ double getTotal; for( tagArrayData : inboundTagArray ){ String getData = stripData(inboundSwiftmessage.getTagData(inboundTagNumber,tagArrayData)); getTotal = getTotal + Double.parseDouble(getData); } return getTotal; } And this is the function to remove the first 3 characters and convert, then remove, the comma into a period: String stripData(String inboundString){ if (inboundString==null){ return "0"; } else { char strippedString; StringBuffer strippedBuffer = new StringBuffer(""); char [] inboundArray = inboundString.toCharArray(); for (int counter = 3 ; counter < inboundArray.length; counter++) { strippedString = inboundArray[counter]; strippedBuffer.append(strippedString); } return strippedBuffer.toString().replace(",","."); } }
unknown
d17166
val
One of the possible fix to do this is: to limit the max size of window. For example: C# code: /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { if (WindowState == WindowState.Normal) { System.Drawing.Rectangle rec = System.Windows.Forms.Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(this).Handle).WorkingArea; MaxHeight = rec.Height; MaxWidth = rec.Width; ResizeMode = ResizeMode.NoResize; WindowState = WindowState.Maximized; } else { MaxHeight = double.PositiveInfinity; MaxWidth = double.PositiveInfinity; ResizeMode = ResizeMode.CanResize; WindowState = WindowState.Normal; } } } You need to set maxsize just before changing of window state. Otherwise, in some cases it works wrong. Also don't forget about ResizeMode. And xaml: <Window x:Class="WpfApplication2.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" WindowStyle="None" Height="300" Width="300"> <Grid> <Button Content="Button" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Width="75" Click="ButtonBase_OnClick"/> </Grid> </Window>
unknown
d17167
val
Unless otherwise specified in a config.xml, iOS platform will try to use the default icon.png during compilation. To define specific icons please use the guide provided: Configure Icons and Splash Screens. The default icon must be named icon.png and must reside in the root of your application folder. Also,Using a splash screen is rather easy via the PhoneGap Build config.xml file. Write a bit of JavaScript that made use of the PhoneGap Splash Screen API: document.addEventListener("deviceready", function(e) { window.setTimeout(function() { navigator.splashscreen.hide(); },5000); }, "false");
unknown
d17168
val
Short answer: You can't do that, by design. The only way you can send email without display a compose mail view controller is if you have a server that offers mail services, but you will have to collect the user's mail credentials. Apple does not want 3rd party developers sending email from a user's account with the user being the one to click the button and do the sending. This protects the user from apps sending mail without the user's knowledge or permission. Imagine the explosion of spam if this restriction was not in place.
unknown
d17169
val
Answered my question. Resolved it using apache commons library. http://www.webring.org/l/rd?ring=theshogiwebring;id=13;url=http%3A%2F%2Fshogi-software%2Eblogspot%2Ein%2F2009%2F04%2Fgoogle-app-engine-and-file-upload%2Ehtml
unknown
d17170
val
The Symbol Server project master branch hasn't been touched for 4 years as of writing, and there is a queue of pull requests and issues left open for even longer. There is an 'upgrade' branch which hasn't been touched since 2014, but that has updated NuGet version. There is a slightly more recent fork at https://github.com/TrabacchinLuigi/SymbolSource.Community/tree/upgrade which uses more recent versions of NuGet. Also have a look at the GitHub 'network' for other potential maintained forks: https://github.com/SymbolSource/SymbolSource.Community/network And alternative hosting solutions include: * *https://inedo.com/proget *https://github.com/GitTools/GitLink Edit -- I got my own version running: https://github.com/i-e-b/SymbolSourceSane
unknown
d17171
val
I'd type it like this: function groupBy<T extends Record<K, PropertyKey>, K extends keyof T>( items: readonly T[], key: K ) { return items.reduce((acc, item) => { (acc[item[key]] = acc[item[key]] || []).push(item); return acc; }, {} as Record<T[K], T[]>); } The important bits are: mutually constraining K and T so that K is a key of T where the property T[K] is itself suitable to be a key of an object; and asserting that the accumulator will eventually be of type Record<T[K], T[]>, an object whose keys are the same as T[K] and whose values are an array of T. Then you can test that it works: const g = groupBy(['one', 'two', 'three'], 'length'); // const g: Record<number, string[]> console.log( Object.keys(g).map(k => k + ": " + g[+k].join(", ")).join("; ") ); // 3: one, two; 5: three The type of g is inferred as {[k: number]: string[]}, an object with a numeric index signature whose properties are string arrays. As another example, to make sure it works: interface Shirt { size: "S" | "M" | "L" color: string; } const shirts: Shirt[] = [ { size: "S", color: "red" }, { size: "M", color: "blue" }, { size: "L", color: "green" }, { size: "S", color: "orange" }]; const h = groupBy(shirts, "size"); // const h: Record<"S" | "M" | "L", Shirt[]> console.log(JSON.stringify(h)); //{"S":[{"size":"S","color":"red"},{"size":"S","color":"orange"}],"M":[{"size":"M","color":"blue"}],"L":[{"size":"L","color":"green"}]} Here we see that a Shirt has a size property from a limited selection of string literals, and groupBy(shirts, "size") returns a value inferred to be of type {S: Shirt[], M: Shirt[], L: Shirt[]}. Okay, hope that helps; good luck! Playground link to code
unknown
d17172
val
var++ evaluates to var, and then increments var. So your expression is in fact evaluated to var + x. The sequence of actions is the following: * *evaluate var++ : 10 *increment var : var = 11 *add x to 10 : 15 *assign the result of the addition to var : var = 15 Anyone programming like this should be banned from development, IMHO. A: Post increment operator like x++ means first you use the value x then you increment and in our case var=var++ + x; assignment takes precedence. Try this var=++var + x; and you should get the value of 16. A: You assigned a value to var,so the auto increment is executed but overwritten. Your code would be better written as: int var = 10; var += x + 1; System.out.println("var = " + var); A: According to the Java Language Specification The value of the postfix increment expression is the value of the variable before the new value is stored. http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.14.2 A: This is the expected behavior of the post-increment operator. You can see what's going on more clearly by running the following: int var = 10; var = var++; System.out.println("var = " + var); var = 10; var = var++ + var; System.out.println("var = " + var); This should produce the output: 10 21 The post-increment operator returns the current value of the variable in the current expression, then increments it, so the incremented value is only visible the next time that variable is used. In your code, you overwrite the value of var before the incremented value is ever used (so the incrementation is "lost"). I imagine the byte code is something analogous to: // r holds the intermediate value of the expression while it's calculated int x = 5; int var = 10; int r = r + var; var = var + 1; // note var is not read after this point r = r + x; var = r;
unknown
d17173
val
Use this function. Suppoesing .edit class of edit button $('.edit').on('click', function(){ $('input').prop('readonly',true); }); But don't set this property initially A: Use .prop to toggle readonly property of the :input elements. Also note, e.preventDefault() as submit button will submit and relaod the form. var edit = true; function inputToggle(e) { e.preventDefault(); $(':input').prop('readonly', edit = !edit); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <form role="form" data-toggle="validator" method="post"> <div class="container padd bpadd"> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> <!-- Name --> <div class="form-group"> <div class="form-item"> <input type="text" name="RMName" value="" id="inputName" readonly="readonly" class="readonlyinput" /> </div> </div> </div> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="form-item"> <div class="form-group"> <input type="email" id="inputEmail" name="inputEmail" value="" readonly="readonly" class="readonlyinput" /> </div> </div> </div> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="form-item"> <div class="form-group"> <input type="text" name="dob" value="" id="InputDob" readonly="readonly" class="readonlyinput" /> </div> </div> </div> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="form-item"> <div class="form-group"> <input name="Phone" type="text" id="InputNumber" value="" readonly="readonly" class="readonlyinput" /> </div> </div> </div> <div class="col-md-12 col-sm-12 col-xs-12"> <!-- Name --> <div class="form-group"> <div class="form-item"> <input type="text" name="OrgName" value="" id="InputOrgName" readonly="readonly" class="readonlyinput" /> </div> </div> </div> <div class="col-md-12 col-sm-12 col-xs-12"> <!-- Name --> <div class="form-group"> <div class="form-item"> <input type="text" name="OrgId" value="" id="InputOrgId" readonly="readonly" class="readonlyinput" /> </div> </div> </div> <div class="col-md-6 col-sm-6 col-xs-6"> <div class="form-item"> <div class="form-group"> <input type="text" name="City" value="" id="InputCity" readonly="readonly" class="readonlyinput" /> </div> </div> </div> <div class="col-md-6 col-sm-6 col-xs-6"> <div class="form-item"> <div class="form-group"> <input type="text" name="State" value="" id="InputState" readonly="readonly" class="readonlyinput" /> </div> </div> </div> <div class="col-md-6 col-sm-6 col-xs-6"> <div class="form-item"> <div class="form-group"> <input type="text" name="Country" value="" id="InputCountry" readonly="readonly" class="readonlyinput" /> </div> </div> </div> </div> </div> <div class="bbutton"> <footer class="footer text-center"> <div class="button-panel"> <div class="bbutton"> <input type="submit" class="button" title="Edit" value="EDIT" onclick="inputToggle(event)" /> <a> <input type="submit" class="button" title="Save" value="SAVE" hidden="hidden" /> </a> </div> </div> </footer> </div> </form> Fiddle demo
unknown
d17174
val
You can set imageView location using autolayout constraints & give it a size constraint and by taking an outlet from it you can animate height to increase leaving all other constraints working @IBOutlet var myViewHeight: NSLayoutConstraint! UIView.animateWithDuration(0.3, delay: 0.0, options: [], animations: { () -> Void in self.myViewHeight.constant = 300 self.view.layoutIfNeeded() }, completion:nil) You should take the outlet from the constraint itself like control+drag on Label.top = topMargin
unknown
d17175
val
You'll have the adjust this to work with your script, but I hope it gives you the general idea of how to replace a reference path with another. The original code had 2 main issues: 1) You weren't actually changing the contents. Doing newLines = Doesn't actually re-assign previsReadlines, so the changes weren't being recorded. 2) Nothing was being passed to write with. writelines needs a parameter you intend to write with. # Adjust these paths to existing maya scene files. scnPath = "/path/to/file/to/open.ma" oldPath = "/path/to/old/file.ma" newPath = "/path/to/new/file.ma" with open(scnPath, "r") as fp: # Get all file contents in a list. fileLines = fp.readlines() # Use enumerate to keep track of what index we're at. for i, line in enumerate(previsReadlines): # Check if the line has the old path in it. if oldPath in line: # Replace with the new path and assign the change. # Before you were assigning this to a new variable that goes nowhere. # Instead it needs to re-assign the line from the list we first read from. fileLines[i] = line.replace(oldPath, newPath) # Completely replace the file with our changes. with open(scnPath, 'w') as fw: # You must pass the contents in here to write it. fw.writelines(fileLines)
unknown
d17176
val
var data = [{"district":"201","date":"Wed Apr 01 2020","paper":671.24,"mgp":36.5}, {"district":"202","date":"Wed Apr 01 2020","paper":421.89,"mgp":44.2}, {"district":"203","date":"Wed Apr 01 2020","paper":607.85,"mgp":67.36}, {"district":"201","date":"Sun Mar 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Sun Mar 01 2020","paper":421.89,"mgp":36.6}, {"district":"203","date":"Sun Mar 01 2020","paper":607.85,"mgp":69.36}, {"district":"201","date":"Sat Feb 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Sat Feb 01 2020","paper":421.89,"mgp":22.2}, {"district":"203","date":"Sat Feb 01 2020","paper":607.85,"mgp":59.66}, {"district":"201","date":"Wed Jan 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Wed Jan 01 2020","paper":421.89,"mgp":22.2}, {"district":"203","date":"Wed Jan 01 2020","paper":607.85,"mgp":89.26}]; const byDistrict = {}; for (const item of data) { const month = item.date.split(' ')[1]; // eg Apr if (!byDistrict[item.district]) byDistrict[item.district] = { }; byDistrict[item.district][month] = { paper: item.paper, mgp: item.mgp, date: item.date }; } for (const district of Object.keys(byDistrict)) { const District = byDistrict[district]; District.all = { district, paper: (District.Feb.paper + District.Mar.paper + District.Apr.paper) / District.Jan.paper, mgp: (District.Feb.mgp + District.Mar.mgp + District.Apr.mgp) / District.Jan.mgp } } const result = Object.keys(byDistrict).map(it => byDistrict[it].all); console.log(result); A: You could collect the january values first and then omit january in the result set. var data = [{ district: "201", date: "Wed Apr 01 2020", paper: 671.24, mgp: 36.5 }, { district: "202", date: "Wed Apr 01 2020", paper: 421.89, mgp: 44.2 }, { district: "203", date: "Wed Apr 01 2020", paper: 607.85, mgp: 67.36 }, { district: "201", date: "Sun Mar 01 2020", paper: 571.24, mgp: 38.8 }, { district: "202", date: "Sun Mar 01 2020", paper: 421.89, mgp: 36.6 }, { district: "203", date: "Sun Mar 01 2020", paper: 607.85, mgp: 69.36 }, { district: "201", date: "Sat Feb 01 2020", paper: 571.24, mgp: 38.8 }, { district: "202", date: "Sat Feb 01 2020", paper: 421.89, mgp: 22.2 }, { district: "203", date: "Sat Feb 01 2020", paper: 607.85, mgp: 59.66 }, { district: "201", date: "Wed Jan 01 2020", paper: 571.24, mgp: 38.8 }, { district: "202", date: "Wed Jan 01 2020", paper: 421.89, mgp: 22.2 }, { district: "203", date: "Wed Jan 01 2020", paper: 607.85, mgp: 89.26 }], january = data.reduce((r, o) => { if (o.date.includes('Jan')) r[o.district] = o; return r; }, {}), result = data.reduce((r, o) => { if (o.date.includes('Jan')) return r; r.push({ ...o, paper: +(o.paper / january[o.district].paper).toFixed(2), mgp: +(o.mgp / january[o.district].mgp).toFixed(2) }) return r; }, []); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; } A: var data = [{"district":"201","date":"Wed Apr 01 2020","paper":671.24,"mgp":36.5}, {"district":"202","date":"Wed Apr 01 2020","paper":421.89,"mgp":44.2}, {"district":"203","date":"Wed Apr 01 2020","paper":607.85,"mgp":67.36}, {"district":"201","date":"Sun Mar 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Sun Mar 01 2020","paper":421.89,"mgp":36.6}, {"district":"203","date":"Sun Mar 01 2020","paper":607.85,"mgp":69.36}, {"district":"201","date":"Sat Feb 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Sat Feb 01 2020","paper":421.89,"mgp":22.2}, {"district":"203","date":"Sat Feb 01 2020","paper":607.85,"mgp":59.66}, {"district":"201","date":"Wed Jan 01 2020","paper":571.24,"mgp":38.8}, {"district":"202","date":"Wed Jan 01 2020","paper":421.89,"mgp":22.2}, {"district":"203","date":"Wed Jan 01 2020","paper":607.85,"mgp":89.26}] let res = data.filter(it => !it.date.includes('Jan')) .reduce ((acc, rec) => [...acc, {district: rec.district, date: rec.date, paper: +(rec.paper/data.filter(it => (it.district === rec.district && it.date.includes('Jan')))[0].paper).toFixed(2), mgp: +(rec.mgp/data.filter(it => (it.district === rec.district && it.date.includes('Jan')))[0].mgp).toFixed(2)}] ,[]) console.log(JSON.stringify(res))
unknown
d17177
val
The following was compiled with avr-gcc 4.8.0 under ArchLinux. The distribution should be irrelevant to the situation, compiler and compiler version however, may produce different outputs. The code: #include <avr/io.h> #define LED_GREEN PD7 #define led(p, s) { if(s) PORTD |= _BV(p); \ else PORTD &= _BV(p); } __attribute__((OS_main)) int main(void); __attribute__((noinline)) void hwInit(void); void hwInit(void){ DDRD = 0xF0; } int main(void){ hwInit(); led(LED_GREEN, 1); while(1); } Generates: 000000a4 <hwInit>: a4: 80 ef ldi r24, 0xF0 ; 240 a6: 8a b9 out 0x0a, r24 ; 10 a8: 08 95 ret 000000aa <main>: aa: 0e 94 52 00 call 0xa4 ; 0xa4 <hwInit> ae: 5f 9a sbi 0x0b, 7 ; 11 b0: ff cf rjmp .-2 ; 0xb0 <main+0x6> when compiled with avr-gcc -Wall -Os -fpack-struct -fshort-enums -std=gnu99 -funsigned-char -funsigned-bitfields -mmcu=atmega168 -DF_CPU=1000000UL -MMD -MP -MF"core.d" -MT"core.d" -c -o "core.o" "../core.c" and linked accordingly. Commenting __attribute__((OS_main)) int main(void); from the above sources has no effect on the generated assembly. Curiously, however, removing the noinline directive from hwInit() has the effect of the compiler inlining the function into main, as expected, but the function itself still exists as part of the final binary, even when compiled with -Os. This leads me to believe that your compiler version/arguments to the compiler are generating some assembly which is not correct. If possible, can you post the disassembly for the relevant areas for further examination? Edited late to add two contributions, second of which resolves the problem at hand: Hanno Binder states: "In order to remove those 'unused' functions from the binary you would also need -ffunction-sections -Wl,--gc-sections." Asker adds [paraphrased]: "I followed a tutorial which neglected to mention the avr-objcopy step to create the hex file. I assumed that compiling and linking the project for the correct target was sufficient (which it for some reason was for basic functionality). After having added an avr-objcopy step to generate the file everything works."
unknown
d17178
val
If it is 0 or any any then no need for that condition as it ishould return all of them. So aassuming $type will contain the temperaments as an array and 0/any will be single element for that case. if(count($type) == 1 && in_array(($type[0], array('0', 'any'))) { $condition = ""; } else { $condition = "WHERE temperaments IN ('" . implode("','", $type) . "')"; } And the query will be like - "Select dog_temperaments.* from dog_temperaments ".$condition A: Either you can check that the array is empty or not like if(is_array($array)) { Use Select dog_temperaments.* where temperaments IN('happy','shy'); } else { notify Enter proper search key } Else you anyways get the empty results by using the same query if the array is empty like Select dog_temperaments.* where temperaments IN(0);
unknown
d17179
val
if(isset($_POST['username']) && trim($_POST['username'])!=='') { Otherwise, $_POST['username'] will be set even if the form is submitted with an empty field. A: if(isset($_POST['username']) && !empty($_POST['username'])) { ...
unknown
d17180
val
If you connect to secondary directly, not as part of the replica set, then you will not be able to write. Or you can turn on authentication and create read-only users.
unknown
d17181
val
You need to ask the customer what combo they want outside the switch statement. I'll just use psuedo-code, so I'm not directly doing your homework for you: var total = 0; var numCust = "How Many Customers?" for (int i = 0; i < numCust; i++){ var combo = "What Combo do you want?" switch (combo){ case 1: total += 4.25; break; case 2: total += 5.25; break; case 4: total += 5.75; break; } } write("The total is: " + total); A: You will need to add the existing ordering logic inside another loop on the number of customers you read at the beginning of your code. Here's the logic but you should write the code. I don't think it would help you learn anything if someone here would write the code for you. loop (numCust) { read order number; loop (lunchCombo) { add to total; } } A: You need to have one instance of each of the following two lines at the beginning of the for loop and before the switch statement: Console.WriteLine("Enter lunch combo purchased"); lunchCombo = Convert.ToInt32(Console.ReadLine()); Then you switch on which lunchCombo the user chose. Plus, your for loop should either loop from i = 0 to i < numCust or from i = 1 to i <= numCust. You're leaving off a customer with the way you have it. A: It would be easier to start your for loop at i = 0 instead of i = 1. Then inside the for loop, ask for the user's input for the lunch combo outside of the switch statement for (int i = 0; i < numCust; i++) { Console.WriteLine("What is this customer's order?"); lunchCombo = Convert.ToInt32(Console.ReadLine()); switch (lunchCombo) { case 1: total = total + 4.25M; break; case 2: total = total + 5.75M; break; case 3: total = total + 5.25M; break; case 4: total = total + 3.75M; break; default: Console.WriteLine("Invalid input"); break; } } A: Think about the effects of starting at 1 and where you're stopping the counter for i. That is to say you're counting starting at 1 to n-1, which means if you're looping through one time less than you intended to. So, if numCustomers is 4, the loop results in: i starts at | 0 | 1 | 2 | 3 | 4 | --------------------------------- i loop... | 4 | 3 | 2 | 1 | 0 | So i'm not getting through enough times if I start at 1. You'll need to make one of two changes. Change i to start at 0, OR change the comparison to be <=. Either will work. And don't worry, this is a common error! (Credit to Quantic for the comment answer!)
unknown
d17182
val
Inside Nix, you can't run npm install. Each step can only do one of two things: * *either compute a new store path without network access: a regular derivation *or produce an output that satisfies a hardcoded hash using a sufficiently simple* process that can access the network: a fixed output derivation These constraints ensure that the build is highly likely to be reproducible. npm install needs access to the network in order to fetch its dependencies, which puts it in the fixed output derivation category. However, dockerTools.buildImage will execute it in a regular derivation, so it will fail to contact the npmjs repository. For this reason, we generally can't map a Dockerfile directly to a series of buildImage calls. Instead, we can build the software with the Nix language infrastructures, like yarn2nix, node2nix or the various tools for other languages. By doing so, your build becomes reproducible, it tends to be more incremental and you don't have to worry about source files or intermediate files ending up in your container images. I'd also recommend to limit the contents parameter to a pkgs.buildEnv or pkgs.symlinkJoin call, because the contents are copied to the root of the container while also remaining in its store. *: sufficiently simple excludes anything beyond fetching a single resource, because that tends to be too fragile. If, for any reason, the fixed output derivation builder produces a different result and the only way to fix it is by changing the output hash, your entire build is essentially not reproducible.
unknown
d17183
val
The solution is to change Spring Boot version from 2.1.3.RELEASE to 2.1.4.RELEASE in the gateway.
unknown
d17184
val
Add display:inline-block to p tag Try this. <button onclick="myFunction()">Click me</button> <p id="demo" style="display:inline-block"></p> Fiddle:https://jsfiddle.net/9yqs14p4/ A: I'm afraid you need to spend a bit more time learning about this. Realistically you'll need to use CSS to style the HTML that is output by your Javascript. Both CodeSchool and Codecademy have great tutorials on learning the basics of HTML, CSS and Javascript. You'll need to learn these basics if you want to do this sort of thing yourself. https://www.codeschool.com/ https://www.codecademy.com/ I've copied your example into a CodePen, which helps to show you the roles played by HTML, CSS and Javascript. As an example, the CSS could be; http://codepen.io/tombeynon/pen/rVQvMO button{ float:left; margin-right:5px; } #demo{ float:left; } A: First of all you have to know, that in HTML there are inline elements, e.g <span> and block elements, e.g <div>. That means, what the word says. You can test the difference: // block <div>div1</div> <div>div2</div> // inline <span>span1</span><span>span2</span> In the example is used the <p> tag which is a block element. Therefore you see the text below. <button> is an inline element. If you simply use a span: <span id="demo"></span> it works!
unknown
d17185
val
You are misunderstanding .off() Description: Remove an event handler. So it seems that you need to listen focusin and focusout event. $(document).ready(function(){ $('input[type="text"]').focusin(function() { $('.inputFaded').addClass('Focused'); }); $('input[type="text"]').focusout(function() { $('.inputFaded').removeClass('Focused'); }); }); .Focused{ background-color: #FFFFCC; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form name="contactform" method="post"> <div class="row"> <div class="col-md-12 inputFaded"> <span class="larger"><strong>Name</strong> <span class="textGreen">*</span></span><br><br> <span>Please provide your full name</span> <input type="text" maxlength="100" class="form-control discuss" name="projectname"> <br> </div> </div> <div class="row"> <div class="col-md-12"> <input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block"> </div> </div> </form> Updated $(document).ready(function(){ $('input[type="text"]').focusin(function() { $(this).addClass('Focused'); }); $('input[type="text"]').focusout(function() { $(this).removeClass('Focused'); }); }); .Focused{ border-color: red; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form name="contactform" method="post"> <div class="row"> <div class="col-md-12 inputFaded"> <span class="larger"><strong>Name</strong> <span class="textGreen">*</span></span><br><br> <span>Please provide your full name</span> <input type="text" maxlength="100" class="form-control discuss" name="projectname"> <br> </div> </div> <div class="row"> <div class="col-md-12"> <input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block"> </div> </div> </form> A: The .off function is not used for running a function but for removing a function from an Event tied to an element, as already pointed out by @Phong. Instead use the .focusout() function or .on("focusout", ..) Please note that if this is also quite simple in Vanilla JS: // Vanilla JS solution (function(){ let input = document.querySelector("input[type='text']"), inputFaded = document.querySelector(".inputFaded"); input.addEventListener('focus', function() { console.log("focused now!"); inputFaded.classList.add('Focused'); }); input.addEventListener('focusout', function(){ console.log("I will also be run! :)"); inputFaded.classList.remove('Focused'); }) })() $(document).ready(function(){ $('input[type="text"]').on('focus', function() { console.log("focused now!"); $('.inputFaded').addClass('Focused'); }); // Removing function from focus event that does not exist as a function to an eventlistener $('input[type="text"]').off('focus', function() { console.log("I will never be run? :("); $('.inputFaded').removeClass('Focused'); }); // adding focusout eventlistener $('input[type="text"]').on('focusout', function() { console.log("I will be run! :)"); $('.inputFaded').removeClass('Focused'); }); // alternative way of adding focusout eventlistener $('input[type="text"]').focusout( function() { console.log("I will also be run! :)"); $('.inputFaded').removeClass('Focused'); }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <form name="contactform" method="post"> <div class="row"> <div class="col-md-12 inputFaded"> <span class="larger"><strong>Name</strong> <span class="textGreen">*</span></span><br><br> <span>Please provide your full name</span> <input type="text" maxlength="100" class="form-control discuss" name="projectname"> <br> </div> </div> <div class="row"> <div class="col-md-12"> <input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block"> </div> </div> </form> A: You can also try like this : $(document).ready(function(){ $("input").focus(function(){ $('.inputFaded').addClass('Focused'); }); $("input").on('blur', function() { $('div').removeClass('Focused'); }); });
unknown
d17186
val
I see a more or less correct setup. The only part I think is missing is when you do this: const store = createStore( rootReducer, initialState, composeEnhancers(applyMiddleware(thunk)) ); Where is your rootReducer? I mean, I'm missing your root reducer code with something like that: import { combineReducers } from 'redux'; import { TransactionReducer } from 'your/path/TransactionReducer'; import { fooReducer } from 'your/path/fooReducer'; import { barReducer } from 'your/path/barReducer'; export const rootReducer = combineReducers({ transactions: TransactionReducer, foo: fooReducer, bar: barReducer, }); It isn't it?
unknown
d17187
val
Use echarts.connect to connect your charts as follow : echarts.connect([myChart1, myChart2, myChart3]) For this to work on your example, you'll have to remove the ids from the 3 'slider' type dataZoom. dataZoom: [ { type: 'inside', start: 50, end: 100 }, { show: true, //id: 'S3', type: 'slider', top: '8%', start: 50, end: 100, height: 20, handleSize: '100%' } ],
unknown
d17188
val
You can do this creating query from all columns like below import org.apache.spark.sql.types.StringType //Input: scala> df.show +----+-----+--------+--------+ | id| name| salary| bonus| +----+-----+--------+--------+ |1001|Alice| 8000.25|1233.385| |1002| Bob|7526.365| 1856.69| +----+-----+--------+--------+ scala> df.printSchema root |-- id: integer (nullable = false) |-- name: string (nullable = true) |-- salary: double (nullable = false) |-- bonus: double (nullable = false) //solution approach: val query=df.columns.toList.map(cl=>if(cl=="salary" || cl=="bonus") col(cl).cast(StringType).as(cl+"_text") else col(cl)) //Output: scala> df.select(query:_*).printSchema root |-- id: integer (nullable = false) |-- name: string (nullable = true) |-- salary_text: string (nullable = false) |-- bonus_text: string (nullable = false) scala> df.select(query:_*).show +----+-----+-----------+----------+ | id| name|salary_text|bonus_text| +----+-----+-----------+----------+ |1001|Alice| 8000.25| 1233.385| |1002| Bob| 7526.365| 1856.69| +----+-----+-----------+----------+ A: If i was in your shoes, i would make changes in the extraction query or ask BI team to put some effort :P for adding and casting the fields on the fly while extracting, but any how what you are asking is possible. You can add the columns from the existing columns as below. Check the addColsTosampleDF dataframe. I hope the comments below will be enough to understand, if you have any questions feel free to add in the comments and i will edit my answer. scala> import org.apache.spark.sql.functions._ import org.apache.spark.sql.functions._ scala> import org.apache.spark.sql.{DataFrame, Row, SparkSession} import org.apache.spark.sql.{DataFrame, Row, SparkSession} scala> val ss = SparkSession.builder().appName("TEST").getOrCreate() 18/08/07 15:51:42 WARN SparkSession$Builder: Using an existing SparkSession; some configuration may not take effect. ss: org.apache.spark.sql.SparkSession = org.apache.spark.sql.SparkSession@6de4071b //Sample dataframe with int, double and string fields scala> val sampleDf = Seq((100, 1.0, "row1"),(1,10.12,"col_float")).toDF("col1", "col2", "col3") sampleDf: org.apache.spark.sql.DataFrame = [col1: int, col2: double ... 1 more field] scala> sampleDf.printSchema root |-- col1: integer (nullable = false) |-- col2: double (nullable = false) |-- col3: string (nullable = true) //Adding columns col1_string from col1 and col2_doubletostring from col2 with casting and alias scala> val addColsTosampleDF = sampleDf. select(sampleDf.col("col1"), sampleDf.col("col2"), sampleDf.col("col3"), sampleDf.col("col1").cast("string").alias("col1_string"), sampleDf.col("col2").cast("string").alias("col2_doubletostring")) addColsTosampleDF: org.apache.spark.sql.DataFrame = [col1: int, col2: double ... 3 more fields] //Schema with added columns scala> addColsTosampleDF.printSchema root |-- col1: integer (nullable = false) |-- col2: double (nullable = false) |-- col3: string (nullable = true) |-- col1_string: string (nullable = false) |-- col2_doubletostring: string (nullable = false) scala> addColsTosampleDF.show() +----+-----+---------+-----------+-------------------+ |col1| col2| col3|col1_string|col2_doubletostring| +----+-----+---------+-----------+-------------------+ | 100| 1.0| row1| 100| 1.0| | 1|10.12|col_float| 1| 10.12| +----+-----+---------+-----------+-------------------+
unknown
d17189
val
I think I have found the answer myself. The window does not appear unless it receives the nextEventMatchingMask: message. This is probably what triggers the window in a CFRunLoop and is what I wanted to know, although it would be nice if I could dig deeper. For now, I'm happy with the following solution. #import <Cocoa/Cocoa.h> int main (int argc, const char * argv[]){ @autoreleasepool { // Create a default window NSWindow *window = [[NSWindow alloc] init]; // Make it blue just for better visibility [window setBackgroundColor:[NSColor blueColor]]; // Bring to front and make it key [window makeKeyAndOrderFront:nil]; // Custom run loop NSEvent* event; while(1) { do { event = [window nextEventMatchingMask:NSEventMaskAny]; //window shows now if ([event type] == NSEventTypeLeftMouseDown) { NSLog(@"Mouse down"); } else { NSLog(@"Something happened"); } } while (event != nil); } } return 0; } I don't have a reference for that. I can only refer to this article: Handmade Hero for mac in which the window appears due to a similar method. That was not good enough for me because such a method involves NSApp, which I would like to avoid, if possible. A: What you have is not a Cocoa app. You need to use the Xcode template to create a simple, one window, Cocoa app. That template will include a main() that starts the AppKit (NSApplicationMain(argc,argv);). This function performs the (approximately) 5,000 little things that make a Cocoa app run. In the app bundle's Info.plist you either define a custom subclass of NSApplication to run your app or, much more commonly, in MainMenu.xib you define a custom NSApplicationDelegate object. Once the AppKit has initialized and is ready to start your application, both of those objects will receive a message that you can override and add your custom startup code. The standard template does all of that, so just use it to create a new project and then add your code to -applicationDidFinishLaunching:.
unknown
d17190
val
You could check if switching to a ListView Control with checkboxes improves matters. It's not as easy to deal with (but hey, the WinForms ListBox isn't a stroke of genius either), I found that it's resize behavior with DoubleBuffered=true is bearable. Alternatively, you could try to reduce flicker by overriding the parent forms background drawing - either providing a hollow brush, or overriding WM_ERASEBKND by doing nothing and returning TRUE. (that's ok if your control covers the entire client area of the parent form, otherwise you'd need a more complex background drawing method. I've used this successfully in Win32 applications, but I don't know if the Forms control adds some of it's own magic that renders this nonfunctional. A: I was having similar issues albeit with an owner drawn listbox. My solution was to use BufferedGraphics objects. Your mileage may vary with this solution if your list isn't owner drawn, but maybe it will give you some inspiration. I found that TextRenderer had difficulties rendering to the correct location unless I suppled TextFormatFlags.PreserveGraphicsTranslateTransform. The alternative to this was to use P/Invoke to call BitBlt to directly copy pixels between the graphics contexts. I chose this as the lesser of two evils. /// <summary> /// This class is a double-buffered ListBox for owner drawing. /// The double-buffering is accomplished by creating a custom, /// off-screen buffer during painting. /// </summary> public sealed class DoubleBufferedListBox : ListBox { #region Method Overrides /// <summary> /// Override OnTemplateListDrawItem to supply an off-screen buffer to event /// handlers. /// </summary> protected override void OnDrawItem(DrawItemEventArgs e) { BufferedGraphicsContext currentContext = BufferedGraphicsManager.Current; Rectangle newBounds = new Rectangle(0, 0, e.Bounds.Width, e.Bounds.Height); using (BufferedGraphics bufferedGraphics = currentContext.Allocate(e.Graphics, newBounds)) { DrawItemEventArgs newArgs = new DrawItemEventArgs( bufferedGraphics.Graphics, e.Font, newBounds, e.Index, e.State, e.ForeColor, e.BackColor); // Supply the real OnTemplateListDrawItem with the off-screen graphics context base.OnDrawItem(newArgs); // Wrapper around BitBlt GDI.CopyGraphics(e.Graphics, e.Bounds, bufferedGraphics.Graphics, new Point(0, 0)); } } #endregion } The GDI class (suggested by frenchtoast). public static class GDI { private const UInt32 SRCCOPY = 0x00CC0020; [DllImport("gdi32.dll", CallingConvention = CallingConvention.StdCall)] private static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, UInt32 dwRop); public static void CopyGraphics(Graphics g, Rectangle bounds, Graphics bufferedGraphics, Point p) { IntPtr hdc1 = g.GetHdc(); IntPtr hdc2 = bufferedGraphics.GetHdc(); BitBlt(hdc1, bounds.X, bounds.Y, bounds.Width, bounds.Height, hdc2, p.X, p.Y, SRCCOPY); g.ReleaseHdc(hdc1); bufferedGraphics.ReleaseHdc(hdc2); } } A: This used to be handled by sending the WM_SETREDRAW message to the control. const int WM_SETREDRAW = 0x0b; Message m = Message.Create(yourlistbox.Handle, WM_SETREDRAW, (IntPtr) 0, (IntPtr) 0); yourform.DefWndProc(ref m); // do your updating or whatever else causes the flicker Message m = Message.Create(yourlistbox.Handle, WM_SETREDRAW, (IntPtr) 1, (IntPtr) 0); yourform.DefWndProc(ref m); See also: WM_SETREDRAW reference at Microsoft Fixed Link If anyone else has used windows messages under .NET, please update this posting as necessary. A: Although not addressing the specific issue of flickering, a method that is frequently effective for this type of issue is to cache a minimal state of the ListBox items. Then determine whether you need to redraw the ListBox by performing some calculation on each item. Only update the ListBox if at least one item needs to be updated (and of course save this new state in the cache for the next cycle).
unknown
d17191
val
RESTORING is the expected state of a database after a RESTORE with NORECOVERY. You can then apply transaction log backups or a differential backup. Recovery takes the database from RESTORING to ONLINE. A: You can restore log files till the database is no recovery mode. If the database is recovered it will be in operation and it can continue database operation. If the database has another operations we cannot restore further log as the chain of the log file after the database is recovered is meaningless. This is the reason why the database has to be norecovery state when it is restored. There are three different ways to recover the database. 1) Recover the database manually with following command. RESTORE DATABASE database_name WITH RECOVERY 2) Recover the database with the last log file. RESTORE LOG database_name FROM backup_device WITH RECOVERY 3) Recover the database when bak is restored RESTORE DATABASE database_name FROM backup_device WITH RECOVERY
unknown
d17192
val
The answer is based on the usage of xlsxwriter library. With the below snippet of code I finally tried to download the xlsx file and to present my date values in excel as Date format values instead of Number format values used to be by default. snippet: from xlsxwriter.workbook import Workbook from io import BytesIO # create a workbook in memory output = BytesIO() wb = Workbook(output) ws = wb.add_worksheet('export') ... current_date = datetime.now() format2 = wb.add_format({'num_format': 'dd/mm/yy'}) ... ws.write(row_num,1,current_date,format2) wb.close() # construct response output.seek(0) response = HttpResponse(output.read(), content_type='application/ms-excel') response['Content-Disposition'] = "attachment; filename=export.xlsx" return response
unknown
d17193
val
You can try using GROUP_CONCAT in MySQL: SELECT uta.question_id, uta.test_id, GROUP_CONCAT(uta.answers ORDER BY uta.answers) AS user_answer, qa.type, qa.answers correct_answer, CASE WHEN GROUP_CONCAT(uta.answers) = qa.answers THEN 'correct' ELSE 'incorrect' END AS status FROM user_test_answers uta LEFT JOIN questions_answer qa ON qa.question_id = uta.question_id GROUP BY uta.user_id, uta.question_id Check I used ORDER BY in GROUP_CONCAT which means that inquestions_answer table, answers must be in alphabetical order. Also, there seems to be an invalid entry in user_test_answers, with question_id 20. HTH EDIT: SELECT uta.question_id, uta.test_id, uta.user_answer, qa.type, qa.answers correct_answer, CASE WHEN uta.user_answer = qa.answers THEN 'correct' ELSE 'incorrect' END AS status FROM questions_answer qa LEFT JOIN ( SELECT user_id, type, test_id, question_id, GROUP_CONCAT(answers ORDER BY answers) AS user_answer, timestamp from user_test_answers GROUP BY user_id, question_id ) uta ON qa.question_id = uta.question_id EDIT 2: SELECT uta.question_id, uta.test_id, uta.user_answer, qa.type, qa.answers correct_answer, CASE WHEN uta.user_answer = qa.answers THEN 'correct' ELSE 'incorrect' END AS status FROM questions_answer qa LEFT JOIN ( SELECT user_id, type, test_id, question_id, GROUP_CONCAT(answers ORDER BY answers) AS user_answer, timestamp from user_test_answers WHERE user_id = 2 AND test_id = 4 -- for user 2 and test 4 GROUP BY user_id, question_id ) uta ON qa.question_id = uta.question_id WHERE test_id = 4 -- try omitting this one in case you get incorrect results IMHO, you need to look at and improve your DB design and schemas.
unknown
d17194
val
Perhaps a good way to answer your question is from the same reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em New developers are often confused at seeing multiple elements that produce similar results. <em> and <i> are a common example, since they both italicize text. What's the difference? Which should you use? By default, the visual result is the same. However, the semantic meaning is different. The <em> element represents stress emphasis of its contents, while the <i> element represents text that is set off from the normal prose, such a foreign word, fictional character thoughts, or when the text refers to the definition of a word instead of representing its semantic meaning. (The title of a work, such as the name of a book or movie, should use <cite>.) This means the right one to use depends on the situation. Neither is for purely decorational purposes, that's what CSS styling is for. To "emphasize" something is to express "alternate tone or mood". If you want to "emphasize" a certain word or phrase in a paragraph, you can use italics. In editors like MS-Word, you can highlight the text, and select "Italicize". Older versions of HTML provided the <i> element. HTML 5 introduced the "semantic" equivalent, <em>. Distinguishing it from other semantic elements, like <cite>.
unknown
d17195
val
This is just a guess but it appears that jQuery isn't "finished" removing the class before it adds it back in. I know this makes NO sense, but it's how JavaScript works. It can call the next function in the chain before all the stuff from the first one is finished. I poked around the code on Animate.CSS's site and saw that they use a timeout in their animation function. You might try the same. Here's their code: function testAnim(x) { $('#animateTest').removeClass().addClass(x); var wait = window.setTimeout( function(){ $('#animateTest').removeClass()}, 1300 ); } What this is doing is exactly like what you are doing except that it waits for the animation to finish, then removes the classes. That way when the other class is added back in, it is truely "new" to the tag. Here is a slightly modified function: function testAnim(elementId, animClasses) { $(elementId).addClass(animClasses); var wait = window.setTimeout( function(){ $(elementId).removeClass(animClasses)}, 1300 ); } Notice two things: First this code would allow you to change what element gets the animation. Second, you remove the classes you added after 1300 milliseconds. Still not 100% there, but it might get you further down the road. It should be noted that if there is already some animation classes on the object it might break this JS. A: found the right answer at animate.css issue#3 var $at = $('#animateTest').removeClass(); //timeout is important !! setTimeout(function(){ $at.addClass('flash') }, 10); Actually a simpler version can avoid using JQuery too. el.classList.remove('animated','flash'); //timeout is important !! setTimeout(function(){ el.classList.add('animated','flash'); }, 10); A: I believe the issue here is that when I remove the class it was adding the class to quickly. Here is how I solved this issue: (HTML is same as above question). JS: var $j = jQuery.noConflict(); window.setTimeout( function(){ $j('.feature-image').removeClass('animated rotateInDownRight')}, 1300); $j("#replay").click(function() { $j('.feature-image').addClass('animated rotateInDownRight'); }); What I believe is happening is the jQuery code is removing and adding the class to quickly. Regardless of the reason this code works. A: If you wish you can also give a try to this javaScript side development that support animate.css animations. Here is an example of usage. //Select the elements to animate and enjoy! var elt = document.querySelector("#notification") ; iJS.animate(elt, "shake") ; //it return an AnimationPlayer object //animation iteration and duration can also be indicated. var vivifyElt = iJS.animate(elt, "bounce", 3, 500) ; vivifyElt.onfinish = function(e) { //doSomething ...; } // less than 1500ms later...changed mind! vivifyElt.cancel(); Take a look here A: My answer is a trick to add/remove the css class with a tint delay: $('#Box').removeClass('animated').hide().delay(1).queue(function() { $(this).addClass('animated').show().dequeue(); }); Also you can test it without hide/show methods: $('#Box').removeClass('animated').delay(1).queue(function() { $(this).addClass('animated').dequeue(); }); I fill it works smooth in chrome but it works with more unexpected delay in FF, so you can test this js timeout: $('#Box').removeClass('animated'); setTimeout(function(){ $('#Box').addClass('animated'); }, 1); A: This solution relies on React useEffect, and it's rather clean, as it avoids manipulating the class names directly. It doesn't really answers the OP question (which seems to be using jQuery), but it might still be useful to many people using React and Animate CSS library. const [repeatAnimation, setRepeatAnimation] = useState<boolean>(true); /** * When the displayedFrom changes, replay the animations of the component. * It toggles the CSS classes injected in the component to force replaying the animations. * Uses a short timeout that isn't noticeable to the human eye, but is necessary for the toggle to work properly. */ useEffect(() => { setRepeatAnimation(false); setTimeout(() => setRepeatAnimation(true), 100); }, [displayedFrom]); return ( <div className={classnames('block-picker-menu', { 'animate__animated': repeatAnimation, 'animate__pulse': repeatAnimation, })} ... )
unknown
d17196
val
If I understand well, you want those two annotations to be visible with maximum possible zoom. I found this solution that does not reqire any calculations. // You have coordinates CLLocationCoordinate2D user = ...; CLLocationCoordinate2D annotation = ...; // Make map points MKMapPoint userPoint = MKMapPointForCoordinate(user); MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation); // Make map rects with 0 size MKMapRect userRect = MKMapRectMake(userPoint.x, userPoint.y, 0, 0); MKMapRect annotationRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0); // Make union of those two rects MKMapRect unionRect = MKMapRectUnion(userRect, annotationRect); // You have the smallest possible rect containing both locations MKMapRect unionRectThatFits = [mapView mapRectThatFits:unionRect]; [mapView setVisibleMapRect:unionRectThatFits animated:YES]; CoreLocation and MapKit structures are hell. A: For anyone coming here later: The shortest way of doing this is (iOS7+) this: Assuming you have a @property MKMapView *mapView, and an MKPointAnnotation *theAnnotation, call: [self.mapView showAnnotations:@[theAnnotation, self.mapView.userLocation] animated:NO]; Now this could cause some problems if called too early (i.e. when self.mapView.userLocation is not yet set). If so, you can call in viewWillAppear: [self.mapView.userLocation addObserver:self forKeyPath:@"location" options:0 context:NULL]; Then, implement: -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"location"]) { [self.mapView showAnnotations:@[theAnnotation, self.mapView.userLocation] animated:NO]; } } That way you're sure it's set. Don't forget to remove the observer at viewWillDisappear: [self.mapView.userLocation removeObserver:self forKeyPath:@"location"]; A: Use these 4 classes - it works like a charm! //MapViewController.h file #import <UIKit/UIKit.h> #import <MapKit/MapKit.h> @interface MapViewController : UIViewController <CLLocationManagerDelegate> { IBOutlet UIButton *buttonBack; IBOutlet MKMapView *mapView; IBOutlet UILabel *labelTitle; NSString *lon,*lat,*nickName; BOOL isFirstLaunch; } @property(nonatomic,retain) NSString *lon,*lat,*nickName; @property(nonatomic,retain) IBOutlet UIButton *buttonBack; @property(nonatomic,retain) IBOutlet UILabel *labelTitle; @property(nonatomic,retain) IBOutlet MKMapView *mapView; -(IBAction)buttonBackAction:(UIButton *)_btn; -(void)zoomToFitMapAnnotations; @end // // MapViewController.m // #import "MapViewController.h" #import "Annotation.h" @implementation MapViewController @synthesize buttonBack,mapView,labelTitle; @synthesize lon,lat,nickName; // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. /* - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization. } return self; } */ -(IBAction)buttonBackAction:(UIButton *)_btn{ [self.navigationController popViewControllerAnimated:1]; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { CLLocationManager* locationManager = [[CLLocationManager alloc] init]; [locationManager setDelegate:self]; [locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; [locationManager startUpdatingLocation]; NSLog(@"MapViewController"); labelTitle.text = @"anscacorona.blogspot.in" CLLocationCoordinate2D location; location.latitude = [self.lat floatValue]; location.longitude = [self.lon floatValue]; Annotation *annotation = [[Annotation alloc] init]; annotation.theCoordinate = location; annotation.theTitle = [NSString stringWithFormat:@"%@",labelTitle.text]; [mapView addAnnotation:annotation]; [annotation release]; mapView.showsUserLocation = 1; [self zoomToFitMapAnnotations]; [super viewDidLoad]; } // Shows the location of both users. called when the device location changes to move the map accordinly. necessary ONLY once when the window is opened. afterwards the user can move the map as he choises. - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { if (isFirstLaunch) { CLLocationCoordinate2D topLeftCoord; CLLocationCoordinate2D bottomRightCoord; topLeftCoord.longitude = fmin([self.lon floatValue], newLocation.coordinate.longitude); topLeftCoord.latitude = fmax([self.lat floatValue], newLocation.coordinate.latitude); bottomRightCoord.longitude = fmax([self.lon floatValue], newLocation.coordinate.longitude); bottomRightCoord.latitude = fmin([self.lat floatValue], newLocation.coordinate.latitude); MKCoordinateRegion region; region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5; region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5; region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.5; // Add a little extra space on the sides region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.5; // Add a little extra space on the sides region = [mapView regionThatFits:region]; [mapView setRegion:region animated:YES]; isFirstLaunch = NO; } } -(void)zoomToFitMapAnnotations { if([mapView.annotations count] == 0) return; CLLocationCoordinate2D topLeftCoord; CLLocationCoordinate2D bottomRightCoord; topLeftCoord.longitude = fmin(mapView.userLocation.location.coordinate.longitude, [self.lon floatValue]); topLeftCoord.latitude = fmax(mapView.userLocation.location.coordinate.latitude, [self.lat floatValue]); bottomRightCoord.longitude = fmax(mapView.userLocation.location.coordinate.longitude, [self.lon floatValue]); bottomRightCoord.latitude = fmin(mapView.userLocation.location.coordinate.latitude, [self.lat floatValue]); MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } }; CLLocationCoordinate2D userCoord = {[self.lat floatValue],[self.lon floatValue]}; region.center = userCoord; region.span.latitudeDelta = 0.05f;//fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides region.span.longitudeDelta = 0.05f;//fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides [mapView setRegion:region animated:YES]; [mapView regionThatFits:region]; } /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations. return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc. that aren't in use. } #pragma mark - View Lifecycle -(void)viewWillAppear:(BOOL)animated{ isFirstLaunch=YES; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [super dealloc]; } @end //anotation classes- Annotation.h #import <MapKit/MapKit.h> @interface Annotation : NSObject <MKAnnotation>{ CLLocationCoordinate2D theCoordinate; NSString *theTitle; NSString *restId; NSString *theSubtitle; } @property(nonatomic,retain) NSString *restId; @property(nonatomic,retain) NSString *theTitle; @property(nonatomic,retain) NSString *theSubtitle; @property CLLocationCoordinate2D theCoordinate; @end //Annotation.m #import "Annotation.h" @implementation Annotation @synthesize theCoordinate,theTitle,theSubtitle,restId; - (CLLocationCoordinate2D)coordinate; { return theCoordinate; } // required if you set the MKPinAnnotationView's "canShowCallout" property to YES - (NSString *)title { return theTitle; } // optional - (NSString *)subtitle { return theSubtitle; } - (void)dealloc { [super dealloc]; } @end
unknown
d17197
val
The way I use it is add all the external jar to the "lib" folder and use "sbt assembly" to create one fat jar. A: i suggest you bundle the jar file into your applications jar file. you can use jar command for packaging or any such utility offered by the IDE as well.
unknown
d17198
val
I don’t think Windows 7 supports what you’re trying to do. Here’s some alternatives. * *Switch from GDI to something else that can render 2D graphics with D3D11. Direct2D is the most straightforward choice here. And DirectWrite if you want text in addition to rectangles. *If your 2D content is static or only changes rarely, you can use GDI+ to render into in-memory RGBA device context, create Direct3D11 texture with that data, and render a full-screen triangle with that texture. *You can overlay another Win32 window on top of your Direct3D 11 rendering one, and use GDI to render into that one. The GDI window on top must have WS_EX_LAYERED expended style, and you must update it with UpdateLayeredWindow API. This method is the most complicated and least reliable, though.
unknown
d17199
val
From the systemd logs, nginx service appears to be running. (the warning about the pid file not found seems endemic to many distributions). On fedora 19/20 (systemd based), open the firewall with the following commands: firewall-cmd --permanent --zone=public --add-service=http systemctl restart firewalld.service or alternatively: firewall-cmd --permanent --zone=public --add-port=80/tcp systemctl restart firewalld.service The second version syntax lets you open any port/protocol combination.
unknown
d17200
val
Try forcing the Uri returned in step 2 to be unique (append a random or incrementing value to the end of the query string). This works around the caching behaviour in the HttpWebRequest class in the SDK.
unknown