title
stringlengths
10
150
body
stringlengths
17
64.2k
label
int64
0
3
r split a column into multiple columns
<p>I'm trying to split a column of strings in a dataframe into multiple columns based a delimiting pattern, i.e., a column of strings "a b" and "c d" should be split into two columns, one with "a" and "c", and another with "b" and "d". The delimiting pattern is in my case any sequence of characters that does not contain <code>a-zA-Z0-9@.</code></p> <p>As suggested <a href="https://stackoverflow.com/questions/4350440/split-a-column-of-a-data-frame-to-multiple-columns">here</a> I'm trying to use <code>stringr</code>. However, it seems that <code>str_split</code> is sensitive to the number of spaces?</p> <pre><code>&gt; xxx&lt;-str_split_fixed(c("a b", "c d")," ",3) &gt; xxx [,1] [,2] [,3] [1,] "a" "b" "" [2,] "c" "" "d" &gt; xxx&lt;-str_split_fixed(c("a b", "c d"),"[:space:] ",3) &gt; xxx [,1] [,2] [,3] [1,] "" "b" "" [2,] "" " d" "" &gt; xxx&lt;-str_split_fixed(c("a b", "c d"),"' '+",3) &gt; xxx [,1] [,2] [,3] [1,] "a b" "" "" [2,] "c d" "" "" </code></pre>
3
Can't calculate growth rate of function
<p><a href="https://i.stack.imgur.com/O9aIs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O9aIs.png" alt="enter image description here"></a></p> <p>Hello, I am trying to solve a question in above image, but I can't.</p> <p>Specially, my question is about C(n) in the image, I got "7logn + n^(1/3)" at the end. </p> <p>we know that left side of + sign, "7logn&lt;=n for all n>7 (witness c=1, k=7)", and right side of + sign, "n^(1/3)&lt;=n". </p> <p>Both sides between + sign from my perspective is O(n) and thus whole C(n) is O(n). </p> <p>But why the answer is Big-theta(n^1/3)?</p>
3
Find a particular tag in html inspector
<p>I need to locate all the h1 and h2 tags in a page. I could do this by searching through the code but the issue is that there are multiple includes and many pages, so i'll need to search through many pages.</p> <p>Is there a way to search for a tag in the browser inspector.</p> <p>Is there a search function for the web inspector?</p> <p>Thanks</p>
3
Where to catch crashes in android application?
<p>I want to reset some shared preferences values when application crashed. I know I can implement UncaughExceptionHandler and than reset the shared preference values in the uncaughtException method, but where should I implement it? In a class that extends Application class or in a class that extends Activity and why?</p>
3
Use integer64 as a key with data table
<p>I have a column of <code>integer64</code> and would like to use that as the key, only it does not work as shown below: the value gives <code>NA</code>.</p> <p><strong>This works</strong></p> <pre><code>s = data.table(id=1000000107000008595, value=10) setkey(s, id) s[J(1000000107000008595)] # id value # 1: 1.00000e+18 10 </code></pre> <p><strong>This does not work</strong></p> <pre><code>s = data.table(id=as.integer64(1000000107000008595), value=10) setkey(s, id) s[J(1000000107000008595)] # id value # 1: 1.00000e+18 NA # &lt;- NA is the problem </code></pre>
3
Upload a photo to a DB using servlets
<p>I am trying to make a Servlet that upload and insert an image to the Data base . this image is of blob type in the database . The code gives me this error : org.netbeans.modules.web.monitor.server.MonitorRequestWrapper cannot be cast to org.apache.tomcat.util.http.fileupload.RequestContext [Ljava.lang.StackTraceElement;@30ec706b</p> <p>here is a part of my code : ## web.xml ##</p> <pre><code> &lt;servlet&gt; &lt;servlet-name&gt;UploadServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;Servlet.UploadServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;uploadDir&lt;/param-name&gt; &lt;param-value&gt;/tmp&lt;/param-value&gt; &lt;/init-param&gt; &lt;/servlet&gt; </code></pre> <h2>DataUtente</h2> <pre><code> protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); HttpSession session=request.getSession(false); PrintWriter out = response.getWriter(); try { out.println("&lt;!DOCTYPE html&gt;"); out.println("&lt;html&gt;"); out.println("&lt;head&gt;"); out.println("&lt;title&gt;Servlet DataUtente&lt;/title&gt;"); out.println("&lt;/head&gt;"); out.println("&lt;body&gt;"); Utente utente =(Utente)session.getAttribute("utente"); out.println("&lt;h1&gt; Welcome " + utente.getUsername() + "&lt;/h1&gt;"); out.println(" &lt;form name=\"myWebForm\" action=\"UploadServlet\" method=\"POST\" ENCTYPE=\"multipart/form-data\"&gt;\n" + " &lt;input type=\"file\" name=\"uploadField\" /&gt;\n" + " &lt;INPUT TYPE='submit' VALUE='upload'&gt;"+ "&lt;/form&gt;"); out.println("&lt;/body&gt;"); out.println("&lt;/html&gt;"); } finally { out.close(); } } </code></pre> <h2>UploadServlet</h2> <pre><code>public class UploadServlet extends HttpServlet { DBManager dbman; private int maxFileSize = 50 * 1024; private int maxMemorySize = 4 * 1024; private File file ; private String dirName; public void init(ServletConfig config) throws ServletException{ super.init(config); //read the uploadDir from the servlet parameters dirName=config.getInitParameter("uploadDir"); if(dirName== null){ throw new ServletException("Please supply uploadDir parameters"); } } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); HttpSession session=request.getSession(false); PrintWriter out = response.getWriter(); try { // Apache Commons-Fileupload library classes DiskFileItemFactory factory = new DiskFileItemFactory(); //maximum size that will be stored in memory factory.setSizeThreshold(maxMemorySize); //create a file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax( maxFileSize ); if (! ServletFileUpload.isMultipartContent(request)) { System.out.println("sorry. No file uploaded"); return; } // parse request List items = upload.parseRequest((RequestContext) request); // get uploaded file FileItem file = (FileItem) items.get(0); // Connect to the DB dbman = new DBManager(); Utente utente=(Utente)session.getAttribute("utente"); //String query = "insert into photos values(?)"; PreparedStatement ps = dbman.connectToDB().prepareStatement("insert into Utente(avatar) values(?) where Id='" + utente.getId() + "'"); ps.setBinaryStream(1, file.getInputStream(), (int) file.getSize()); ps.executeUpdate(); // dbman.connectToDB().commit(); dbman.connectToDB().close(); out.println("Proto Added Successfully. &lt;p&gt; &lt;a href='listphotos'&gt;List Photos &lt;/a&gt;"); } catch(Exception ex) { out.println( "Error ==&gt; " + ex.getMessage()); out.print(ex.getStackTrace()); } } </code></pre> <p>and here is the DDmanager:</p> <pre><code>public void closeConnection(){ try { dbConnection.close(); } catch (SQLException ex) { ex.printStackTrace(); Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex); } } public Connection connectToDB() throws SQLException, ClassNotFoundException{ String dbString = null; Class.forName(driver); dbString = "jdbc:derby://localhost:1527/DB"; dbConnection = (Connection) DriverManager.getConnection(dbString, userName, password); return dbConnection; } public boolean connectToDb() { //conneto a db try { String dbString = null; Class.forName(driver); dbString = "jdbc:derby://localhost:1527/DB"; dbConnection = (Connection) DriverManager.getConnection(dbString, userName, password); } catch (Exception e) { e.printStackTrace(); // System.out.print("erore"); return false; } return true; } public ResultSet executeQuery(String command) { try { stmt = dbConnection.createStatement(); ResultSet ress = stmt.executeQuery(command); return ress; } catch (Exception e) { e.printStackTrace(); return null; } } public void executeUpdateQuery(String command) { try { stmt = dbConnection.createStatement(); int ress = stmt.executeUpdate(command); stmt.close(); } catch (Exception e) { e.printStackTrace(); } </code></pre>
3
Any key to produce #{} in a JSF page while working in Eclipse IDE
<p>I am going through the JSF case study based on <strong><em>Ed Burns</em></strong> book <strong><em>The Complete Reference</em></strong>.<br> I am tired of typing <code>#{}</code> Expression Language syntax.<br> Is there any combination of keys provided to achieve it in Eclipse IDE?</p>
3
Activiti Rest - Calling multiple instances concurrently
<p>I have defined some simple BPM flows (F1) and deployed in activiti-rest.war. For simplicity, I have take a simple start-end flow.</p> <p>I have written a REST client to execute the flow (F1) in parallel threads (20) with its required parameters for 1000 http requests. </p> <p><strong>Problem:</strong> I can see the flows are running sequentially, one by one response for the 20 parallel threads. It took a time of around 60 secs to complete with 20 threads (even when increased to 50 threads) it is the same.</p> <p>Activiti Version : 5.15 What should be the problem here ?. Any help will be really useful. activiti-rest/service/runtime/process-instances - Rest URL used to start the instance</p> <p>Thanks,</p> <p>Yoka</p>
3
How is it possible to run functions in unnamed classes (if possible multiple?)
<p>I'm quite new to Python 3 and recently started programming with the tk toolkit in the form of tkinter. I started programming two classes for my Space Invaders Remix, but I came across some problems. Most commonly, I had to create multiple variables for classes for the bullets, but then I couldn't update all of them, as they were all unnamed. Here's my code, if it helps:</p> <pre><code>from tkinter import * import easygui import random import time from pygame import mixer tk = Tk() tk.title('Space Invaders') tk.resizable(600,400) tk.wm_attributes('-topmost', 1) canvas = Canvas(tk,width = 550, height=400,bd=0,highlightthickness = 0) canvas.pack() canvas.update() canvas.create_rectangle(0,0,600,400,fill ='black') position = 0 class Spaceship: def __init__(self, canvas, colour): self.canvas = canvas self.id = canvas.create_rectangle(0,0,30,20, fill=colour) self.canvas.move(self.id, 245, 300) self.x = 0 self.canvas_width = self.canvas.winfo_width() self.canvas.bind_all('&lt;KeyPress-Left&gt;', self.turn_left) self.canvas.bind_all('&lt;KeyPress-Right&gt;', self.turn_right) def update(self): self.canvas.move(self.id, self.x, 0) pos = self.canvas.coords(self.id) if pos[0] &lt;= 0: self.x = 0 elif pos[2] &gt;= self.canvas_width: self.x = 0 def turn_left(self, evt): self.x = -2 def turn_right(self, evt): self.x = 2 class Bullet: def __init__(self, canvas, colour): self.paddle = Spaceship self.canvas = canvas self.id = canvas.create_rectangle(0, 0, 10,20,fill=colour) self.canvas.move(self.id, position, 100) self.x = 0 self.y = -1 self.canvas_height = self.canvas.winfo_height() def update(self): self.canvas.move(self.id, 0, -1) spaceship = Spaceship(canvas, 'white') def add_bullet(event): if event.keysym == 'Up': Bullet(canvas,'white') while 1: canvas.bind_all('&lt;KeyPress-Up&gt;', add_bullet) spaceship.update() Bullet.update() tk.update_idletasks() tk.update() time.sleep(0.01) </code></pre> <p>Again, I'm quite new to Python, and there's probably a simple answer.</p> <p>By the way,I've imported</p>
3
How do I apply this?
<p>I would like to use as the variable for my code below, instead of what comes after ClassName= in 1.txt, I would like what comes in-between this:</p> <p>EntryText=Ship sunk!|Grid AO 77|<strong>Variable</strong>, </p> <p>(notice the comma after the variable and the | before it )</p> <p>So grab after the text line ending with the second | and before the comma.</p> <p>The text line before the variable will be the same and constant EXCEPT after "Grid" there could be any mixture of letters and numbers up until the second |</p> <p>So I am trying to use as a variable, what is in between:</p> <p>EntryText=Ship sunk!|Grid <em>(Any combination of letters or numbers)</em> | <strong>(variable)</strong> , <em>(comma)</em> </p> <p>So grab in between the second | and the comma. Than you. I would like to replace the grabbing of the variable after ClassName= to what is in between the second | and the comma. Please keep in mind that there are other | and commas in the file that I don't want to grab, I just want to grab the variable after | and before comma if its after the "EntryText=Ship sunk!|Grid ....</p> <p>Again, I don't want the Grid part, I'd like what comes after the second | and before the comma. There will be many EntryText lines as well, so I'd like to grab that part of all of them and put in my code.</p> <p>So instead of what is after ClassName=, I'd like to copy what is where the variable listed above.</p> <p>Thank you for your time!!</p> <pre><code>@echo off copy 2.txt 2.txt-backup setlocal enableDelayedExpansion &gt;2.txt ( for /f "tokens=1* delims=:" %%A in ('findstr /n "^" 2.txt-backup') do ( ( echo !ln!| findstr "^Type=206$" &gt;NUL &amp;&amp; set ln=ln ) || ( set "ln=%%B" if "!ln:~0,6!"=="Class=" ( findstr /c:"ClassName=!ln:~6!" "E:\Dropbox\New folder\Log_*.txt" &gt;"E:\Dropbox\New folder\null" &amp;&amp; ( echo Class=ShipDummy set "ln=Type=206" ) ) if #!ln!==# (echo;) else echo !ln! ) ) ) </code></pre> <p>I was given this bottom code by someone, but I don't know if its what I want or how to apply it to the above:</p> <pre><code>for /f "tokens=3 delims=|" %%C in ("%%B") do for /f "tokens=1 delims=," %%D in ("%%C") do echo %%D </code></pre> <p>Thank you!!!!!</p>
3
Does anyone know what in this clearInterval makes it not clear?
<p>This is my js converted from coffee :</p> <pre><code>set_timer: function() { var _this = this; return this.timer = setInterval(function() { _this.set({ time_to_complete: _this.get("time_to_complete") + 1 }); if (_this.get("time_to_complete") &gt; 3) { console.log("End of clear."); return _this.reset_timer(_this.timer); } }, 1000); }, reset_timer: function() { clearInterval(this.timer); return this.set({ time_to_complete: 0 }); } </code></pre> <p>And then its called as :</p> <pre><code>this.model.set_timer(); </code></pre> <p>For some reason this doesn't clear, and my interval keeps producing those <code>console.log</code>'s</p> <p>Here's another example of the same error but in Coffeescript, and namedspaced to <code>$</code> as mixin methods for underscore</p> <pre><code>set_timer: (model) =&gt; $.timer = setInterval =&gt; model.set time_to_complete: model.get("time_to_complete") + 1 if model.get("time_to_complete") &gt; 3 console.log "End of clear." _.reset_timer model , 1000 reset_timer: (model) -&gt; clearInterval $.timer model.set time_to_complete: 0 </code></pre>
3
How to filter some of the application apps?
<p>I need to display a screen with all the installed applications. I can do this already, but I need to filter some of the system applications. I am doing like this:</p> <pre><code>if((appInfo.flags &amp; ApplicationInfo.FLAG_SYSTEM) == 1) </code></pre> <p>This works, but the problem is that it hides apps like System, Video Player, and Sound Recorder. However, I need these apps to show up, too. The question is, how to do this?</p>
3
Several subprojects. duplicate symbols for architecture
<p>I have a workspace with several projects of reusable artifacts, which are compiled into static libraries. Later, I'm using these libraries in other projects by including them as a sub-projects by reference. But I've faced problem of "duplicate symbols" when project A uses libraries B and C, which are both using library D (libraries B and C included as a sub-projects to project A, and all libraries B,C,D are from artifacts workspace). How can I solve this problem? </p>
3
custom cell height from UIImageView size?
<p>I have a UIImageView inside a custom cell. If there is no image to display in cell then cell height should automatically decrease.(ImageView Height should be zero in that case). How to specify constraint for this in xib ? </p>
3
Making @username clickable jquery
<p>Below code works on the Mootools library, I would like it to work on jQuery if possible, I so far had no luck.</p> <p>HTML</p> <pre><code>&lt;p id="test"&gt;@user has an email address of [email protected]. See! the regexp works @people!&lt;/p&gt; </code></pre> <p>MooTools</p> <pre><code>$('test').set('html', $('test').get('html').replace(/\B\@([\w\-]+)/gim, function(match, name){ return '&lt;a href="http://twitter.com/users/' + name + '"&gt;' + match + '&lt;/a&gt;'; })); </code></pre> <p><a href="http://jsfiddle.net/2TQsx/4/" rel="nofollow"><strong>Fiddle</strong></a></p>
3
How to save a nested many-to-many relationship in API-only Rails?
<p>In my Rails (api only) learning project, I have 2 models, Group and Artist, that have a many-to-many relationship with a joining model, Role, that has additional information about the relationship. I have been able to save m2m relationships before by saving the joining model by itself, but here I am trying to save the relationship as a nested relationship. I'm using the <a href="https://github.com/jsonapi-serializer/jsonapi-serializer" rel="nofollow noreferrer">jsonapi-serializer</a> gem, but not married to it nor am I tied to the JSON api spec. Getting this to work is more important than following best practice.</p> <p>With this setup, I'm getting a 500 error when trying to save with the following errors: <code>Unpermitted parameters: :artists, :albums</code> and <code>ActiveModel::UnknownAttributeError (unknown attribute 'relationships' for Group.)</code></p> <p>I'm suspecting that my problem lies in the strong param and/or the json payload.</p> <p><strong>Models</strong></p> <pre><code>class Group &lt; ApplicationRecord has_many :roles has_many :artists, through: :roles accepts_nested_attributes_for :artists, :roles end class Artist &lt; ApplicationRecord has_many :groups, through: :roles end class Role &lt; ApplicationRecord belongs_to :artist belongs_to :group end </code></pre> <p><strong>Controller#create</strong></p> <pre><code>def create group = Group.new(group_params) if group.save render json: GroupSerializer.new(group).serializable_hash else render json: { error: group.errors.messages }, status: 422 end end </code></pre> <p><strong>Controller#group_params</strong></p> <pre><code>def group_params params.require(:data) .permit(attributes: [:name, :notes], relationships: [:artists]) end </code></pre> <p><strong>Serializers</strong></p> <pre><code>class GroupSerializer include JSONAPI::Serializer attributes :name, :notes has_many :artists has_many :roles end class ArtistSerializer include JSONAPI::Serializer attributes :first_name, :last_name, :notes end class RoleSerializer include JSONAPI::Serializer attributes :artist_id, :group_id, :instruments end </code></pre> <p><strong>Example JSON payload</strong></p> <pre><code>{ &quot;data&quot;: { &quot;attributes&quot;: { &quot;name&quot;: &quot;Pink Floyd&quot;, &quot;notes&quot;: &quot;&quot;, }, &quot;relationships&quot;: { &quot;artists&quot;: [{ type: &quot;artist&quot;, &quot;id&quot;: 3445 }, { type: &quot;artist&quot;, &quot;id&quot;: 3447 }] } } </code></pre> <p><strong>Additional Info</strong></p> <p>It might help to know that I was able to save another model with the following combination of json and strong params.</p> <pre><code># Example JSON &quot;data&quot;: { &quot;attributes&quot;: { &quot;title&quot;: &quot;Wish You Were Here&quot;, &quot;release_date&quot;: &quot;1975-09-15&quot;, &quot;release_date_accuracy&quot;: 1 &quot;notes&quot;: &quot;&quot;, &quot;group_id&quot;: 3455 } } # in albums_controller.rb def album_params params.require(:data).require(:attributes) .permit(:title, :group_id, :release_date, :release_date_accuracy, :notes) end </code></pre>
3
display only the values from a list after quering mongodb
<p>I was wondering if it is possible for me to only have the values displayed from the results of query which are returned in a list.</p> <p>I am running the following:</p> <pre><code>a = ast.literal_eval(json.dumps(list(db.bastion.find( { },{ 'counter': 1, '_id': False } )))) </code></pre> <p>Which returns something similar to this:</p> <pre><code>[{'counter': 10447}, {'counter': 25375}, {'counter': 11963}, {'counter': 17297}, {'counter': 5893}, {'counter': 19955}, {'counter': 5159}, {'counter': 3988}, {'counter': 7638}, {'counter': 8250}, {'counter': 29514}, {'counter': 4940}, {'counter': 12834}, {'counter': 31153}, {'counter': 8588}, {'counter': 17585}, {'counter': 7099}, {'counter': 18580}, {'counter': 2575}, {'counter': 3696}, {'counter': 5071}, {'counter': 4074}, {'counter': 15355}, {'counter': 16520}, {'counter': 13850}, {'counter': 18639}, {'counter': 22640}, {'counter': 13962}, {'counter': 14354}, {'counter': 10945}, {'counter': 10330}] </code></pre> <p>So what I would like is just the values and not the key name counter displayed so I can calculate the 95th percentile doing the following:</p> <pre><code>for i in a: print np.percentile(map(int,i),95) </code></pre>
3
Embed a map with satellite terrain active (iframe)
<p>I have this iframe, generated in Google Maps.</p> <pre><code>&lt;iframe src=&quot;https://www.google.com/maps/d/u/0/embed?mid=1ssxg5qgL8pDlVKV4Jcc4axK_O9s2DYm2&amp;ehbc=2E312F&quot; width=&quot;100%&quot; height=&quot;480&quot;&gt;&lt;/iframe&gt; </code></pre> <p>I would like to know if it is possible force the map to be displayed with the satellite image activated. Thanks.</p>
3
R - VScode issues
<p>I've been using R in VScode for quite sometime without issue until I migrated computers.</p> <p>Intellisense does not work anymore even though I followed the same installation steps on both computers. Whenever I try to run R code this error pops up.</p> <pre><code>VSCode R Session Watcher requires jsonlite, rlang. Please install manually in order to use VSCode-R. </code></pre> <p>This used to work on a Windows 10 laptop, and is not working on my current windows 11 laptop.</p> <p>If anyone knows how I can fix this please let me know!</p>
3
Problem regarding the size of the internal memory of AVD platform 2.2 API- lvl 8
<p>i searched the web to find some guides how to increase the capacity of the internal memory of my virtual device, no luck so far, since i think their talking about the memory of their real phone, not the virtual device.</p> <p>my problem is after adding some few files on my app, once i run the project as android project, it is having errors like:</p> <p><em>[2011-07-18 12:04:28 - testproject] Failed to install testproject.apk on device 'emulator-5554': device not found [2011-07-18 12:04:28 - testproject] com.android.ddmlib.InstallException: device not found [2011-07-18 12:04:28 - testproject] Launch canceled!</em></p> <p>and i can't test if my codes are running correctly since it won't install the app..</p> <p>i know you can immediately program the app to install itself on the SD card instead of it using the internal memory of the phone, but i just want to end this problem of mine, can i really increase the size of the internal memory? or the size of the internal memory is already fixed? depending on the android platform, i use android 2.2..</p> <p>i also tinkered through the hardware of the avd adding and increasing the value of the hardwares, no luck, so if someone could just give me advice or assist me on this problem of mine i would be grateful, since i can't continue my study of the android technology because of this minor setback, thanks and godspeed.</p>
3
How to create JS Canvas Top Down Rain Effect or Reverse Warp Speed
<p>I am trying to figure out how to create a canvas rain effect, but from the top down perspective. Basically it's like you are looking down at the ground and you are watching the rain fall around you and fall slightly to the center at an angle, but it falls a short distance before ending. I am not seeing anything in searches except some game development that isn't canvas.</p> <p>I am also looking for a solution that doesn't require an external library.</p> <p>I have been able to modify some warp speed effect code to reverse the direction on the particles to fall to the background instead of off screen, but it is continuing to infinity toward the center and not redrawing or looping the particles that are coming from off screen.</p> <p>I think it has something to do with the particles not dropping off screen in this part of the code. Am I on the right track here or can I not accomplish this effect with the current code?</p> <pre><code>clear(); const cx = w / 2; const cy = h / 2; const count = stars.length; for (var i = 0; i &lt; count; i++) { const star = stars[i]; const x = cx + star.x / (star.z * 0.001); const y = cy + star.y / (star.z * 0.001); if (x &lt; 0 || x &gt;= w || y &lt; 0 || y &gt;= h) { continue; } const d = star.z / 1000.0; const b = 1000 - d * d; putPixel(x, y, b); } </code></pre> <p>Here is the full code that I am looking at. Any help would be appreciated trying to figure this out.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const canvas = document.getElementById("canvas"); const c = canvas.getContext("2d"); let w; let h; const setCanvasExtents = () =&gt; { w = document.body.clientWidth; h = document.body.clientHeight; canvas.width = w; canvas.height = h; }; setCanvasExtents(); window.onresize = () =&gt; { setCanvasExtents(); }; const makeStars = count =&gt; { const out = []; for (let i = 0; i &lt; count; i++) { const s = { x: Math.random() * 1600 - 800, y: Math.random() * 900 - 450, z: Math.random() * 1000 }; out.push(s); } return out; }; let stars = makeStars(1000); const clear = () =&gt; { c.fillStyle = "black"; c.fillRect(0, 0, canvas.width, canvas.height); }; const putPixel = (x, y, brightness) =&gt; { const intensity = brightness * 255; const rgb = "rgb(" + intensity + "," + intensity + "," + intensity + ")"; c.fillStyle = rgb; c.fillRect(x, y, 5, 5); }; const moveStars = distance =&gt; { const count = stars.length; for (var i = 0; i &lt; count; i++) { const s = stars[i]; s.z += distance; while (s.z &lt;= 1) { s.z -= 10; } } }; let prevTime; const init = time =&gt; { prevTime = time; requestAnimationFrame(tick); }; const tick = time =&gt; { let elapsed = time - prevTime; prevTime = time; moveStars(elapsed * 1.5); clear(); const cx = w / 2; const cy = h / 2; const count = stars.length; for (var i = 0; i &lt; count; i++) { const star = stars[i]; const x = cx + star.x / (star.z * 0.001); const y = cy + star.y / (star.z * 0.001); if (x &lt; 0 || x &gt;= w || y &lt; 0 || y &gt;= h) { continue; } const d = star.z / 1000.0; const b = 1000 - d * d; putPixel(x, y, b); } requestAnimationFrame(tick); }; requestAnimationFrame(init);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { position: fixed; left: 0px; right: 0px; top: 0px; bottom: 0px; overflow: hidden; margin: 0; padding: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;canvas id="canvas" style="width: 100%; height: 100%; padding: 0;margin: 0;"&gt;&lt;/canvas&gt;</code></pre> </div> </div> </p>
3
How to search contacts by name and phone number?
<p>I am using Contacts.CONTENT_FILTER_URI to search for contacts.</p> <pre><code>Uri contentUri = Uri.withAppendedPath( ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(searchString)); </code></pre> <p>The <code>searchstring</code> can be either a number or a name. That works great.<br /> My only problem is that the result does not contain a contact phone number.</p> <p>I know that I can get it by querying <code>ContactsContract.Data.CONTENT_URI</code>. However, I would like to find a solution that will give me a contact name and phone number with a single query.</p>
3
Using REPLACE AND LIKE
<p>I am currently trying to update a column in a temporary table using Oracle 11g SQL syntax. In this column there is an Unique ID that is 12 digits long. However I need to join this table with this column holding the Unique ID but the syntax for the Unique ID of this table is slightly different than the syntax for the table that it will be joined (with Unique ID serving as the PK = FK). This may be tough to follow so I will provide what I am doing below.</p> <p>UniqueID Column from TABLE xyz Syntax AB10783421111111</p> <p>UniqueID Column from TABLE zxo Syntax 383421111111</p> <p>You see how the numbers are identical except for the AB107 and first '3' in the zxo table? I would like to know why both these queries are not running</p> <pre><code>UPDATE temp37 SET UNIQUE_ID = REPLACE(UNIQUE_ID, (LIKE 'AB107%'), (LIKE '3%')); UPDATE temp37 SET UNIQUE_ID = '3%' WHERE UNIQUE_ID = 'AB107%'; </code></pre> <p>Essentially I would like to replace every case of an id with AB10755555555555 to 355555555555. Thank you for any help. </p>
3
Dynamic Drop-down search bar results do not parse into my List for Selenium
<p>I'm creating a simple script to visit <em>priceline.com</em> and then searching "<strong>N</strong>" under <strong>Departing Flights</strong> and selecting <strong>New York City (NYC)</strong> from the dropdown list.</p> <p>My code successfully types into the search bar but is still unable to find the dynamic dropdown with all the relevant results. I am not sure why.</p> <pre><code>// Clicks on "Departing from?" textbox and clears it before typing 'N' driver.findElement(By.id("flight-departure-airport0")).click(); driver.findElement(By.id("flight-departure-airport0")).clear(); driver.findElement(By.id("flight-departure-airport0")).sendKeys("N"); // Store all dynamic search results into a list List&lt;WebElement&gt; departureDropdown = driver.findElements(By.id("//*['flight-departure-airport0-dropdown']/div/div/div")); System.out.println("List: "+departureDropdown); </code></pre> <p><strong>Expected:</strong> I expected <code>departureDropdown</code> to have a length of 9 with various airports. (Nadi, New York City, Nagasaki, etc) and expect <code>departureDropdown[i]</code> to return one of the city names in plain text.</p> <p><strong>Actual:</strong> My code is stuck at the list initialization. <code>departureDropdown</code> is empty.</p>
3
different way to write a method
<p>I have a class to define a right hand side terms of differential equation: this class provide the method to compute the rhs function and its derivate the function is store in a vector container in this way the class is suitable for the system of Differential Equation as well.</p> <p>here the interface in which the method that I would to change is defined </p> <pre><code> template &lt;typename Type = double&gt; class rhsODEProblem { using analysisFunction = std::function&lt;const Type(const Type, const std::valarray&lt;Type&gt;)&gt;; public: rhsODEProblem(const std::vector&lt;std::function&lt;const Type(const Type,const std::valarray&lt;Type&gt;)&gt;&gt; numfun , const std::vector&lt;std::function&lt;const Type(const Type,const Type)&gt;&gt; exactfun , const Type,const Type,const Type,const std::valarray&lt;Type&gt;,const std::string ) noexcept ; rhsODEProblem(const std::vector&lt;std::function&lt;const Type(const Type,const std::valarray&lt;Type&gt;)&gt;&gt; numfun, const Type, const Type, const Type, const std::valarray&lt;Type&gt; ) noexcept ; virtual ~rhsODEProblem() = default ; rhsODEProblem(const rhsODEProblem &amp;) = default ; rhsODEProblem(rhsODEProblem&amp;&amp; ) = default ; rhsODEProblem&amp; operator=(const rhsODEProblem&amp;) = default ; rhsODEProblem&amp; operator=(rhsODEProblem&amp;&amp; ) = default ; const std::vector&lt;std::function&lt;const Type(const Type,const std::valarray&lt;Type&gt;)&gt;&gt; numericalFunction ; const std::vector&lt;std::function&lt;const Type(const Type,const Type)&gt;&gt; analiticalFunction ; const std::vector&lt;analysisFunction&gt;&amp; f = numericalFunction ; const auto dfdt(std::size_t indx , const Type t , const std::valarray&lt;Type&gt; u) { return (f[indx](t, u+eps )-f[indx](t,u))/eps ; } auto setRhs (const std::vector&lt; std::function&lt;const Type(const Type,const std::valarray&lt;Type&gt;)&gt;&gt; numfun) noexcept { for(auto i=0 ; i &lt; numfun.size() ; i++) { numericalFunction.push_back(numfun.at(i)) ; } } auto setExact(const std::vector&lt;std::function&lt;const Type(const Type,const Type)&gt;&gt; exactfun) noexcept { for(auto i=0 ; i &lt; exactfun.size(); i++) { analiticalFunction.push_back(exactfun.at(i)); } } auto solveExact() noexcept ; const Type t0() const noexcept { return _t0 ;} const Type tf() const noexcept { return _tf ;} const Type dt() const noexcept { return _dt ;} const std::valarray&lt;Type&gt; u0() const noexcept { return _u0 ;} const std::string fname () const noexcept { return filename ;} //--- private: Type _t0 ; // start time Type _tf ; // final time Type _dt ; // time-step std::valarray&lt;Type&gt; _u0 ; // iv std::string filename ; Type eps = 1e-12 ; }; </code></pre> <p>I would like to change the method dfdt in a way in which I can call it using the following syntax <code>dfdt[index]( t , u_valarray )</code> instead of <code>dfdt(index, t, u_valarray )</code> In which way I can change this method ? </p> <p><strong>EDIT</strong> thank for your answer so in my case it gonna be :</p> <pre><code>foo_helper(foo &amp;, int index); operator()(int n, Type t, std::valarray&lt;Type&gt; u ); </code></pre> <p>right ?</p> <p><strong>EDIT</strong> no I didn't get the point. I wrote :</p> <pre><code>class dfdx { public: dfdx( rhsODEProblem&lt;Type&gt; &amp;r , int index_ ) : index{index_ } {} void operator()(Type t, std::valarray&lt;Type&gt; u){ return (f[index](t, u + eps )-f[index](t,u))/eps ; } int index ; }; dfdx operator[](std::size_t index) { return dfdx(*this, index); } </code></pre> <p>then I call it in this way : </p> <pre><code>rhs.dfdx[j](t , uOld) ) </code></pre> <p>but I got an error :</p> <pre><code>BackwardEulerSolver.H:114:50: error: invalid use of ‘class mg::numeric::odesystem::rhsODEProblem&lt;double&gt;::dfdx’ ( 1- dt() * rhs.dfdx[j](t , uOld) ) ; ~~~~^~~~ </code></pre>
3
Is current row value in other column?
<p>Im trying to determine if a user is a manager by determining if their Id <code>userProfiles.UserProfilesId</code> is anywhere in the field <code>UserProfiles.ManagerId</code>. My current sql statment says id is not valid. Is there any subquery I could create to determine this information?</p> <pre><code>SELECT IsNull(PersonalTimeRemaining, 0) as PTO, UserProfiles.UserProfileId as id, us.Email, us.LastName + ', ' + us.FirstName, managers.Email as 'manager', case when PersonalTimeRemaining is null then 'hourly' else 'salary' end as salaryType, case when EXISTS(SELECT * from UserProfiles where id = UserProfiles.UserProfileId) then 'User' else 'Manager' end as salaryType FROM UserProfiles inner join Users as us on us.UserId = UserProfiles.UserProfileId inner join Users as managers on managers.UserId = UserProfiles.ManagerId </code></pre>
3
Python3 + ctypes callback causes memory leak in simple example
<p>While working on a complex program combining Python 3 code and C++ code using ctypes, I found a memory leak that can easily be reproduced with the stripped down example below.</p> <p>My C++ code creates a Python object using a callback function. Next, it calls another callback on the Python object, that simply returns its argument. The second callback causes the object's reference count to increase. As a result, the object never gets garbage-collected.</p> <p>This is the Python code (file bug.py):</p> <pre><code>import ctypes CreateObjectCallback = ctypes.CFUNCTYPE( ctypes.py_object ) NoopCallback = ctypes.CFUNCTYPE( ctypes.py_object, ctypes.py_object ) lib = ctypes.cdll.LoadLibrary("./libbug.so") lib.test.restype = ctypes.py_object lib.test.argtypes = [ CreateObjectCallback, NoopCallback ] class Foo: def __del__(self): print("garbage collect foo"); def create(): return Foo() def noop(object): return object lib.test(CreateObjectCallback(create), NoopCallback(noop)) </code></pre> <p>This is the C++ code (file bug.cpp):</p> <pre><code>#include &lt;python3.6m/Python.h&gt; #include &lt;iostream&gt; #include &lt;assert.h&gt; extern "C" { typedef void *(*CreateObjectCallback)(); typedef void *(*NoopCallback)(void *arg); void *test(CreateObjectCallback create, NoopCallback noop) { void *object = create(); std::cerr &lt;&lt; "ref cnt = " &lt;&lt; ((PyObject*)(object))-&gt;ob_refcnt &lt;&lt; std::endl; object = noop(object); std::cerr &lt;&lt; "ref cnt = " &lt;&lt; ((PyObject*)(object))-&gt;ob_refcnt &lt;&lt; std::endl; return object; } } </code></pre> <p>And here are the commands I use to compile and run:</p> <pre><code>g++ -O3 -W -Wextra -Wno-return-type -Wall -Werror -fPIC -MMD -c -o bug.o bug.cpp g++ -shared -Wl,-soname,libbug.so -o libbug.so bug.o python3 bug.py </code></pre> <p>The output is:</p> <pre><code>ref cnt = 1 ref cnt = 2 </code></pre> <p>In other words, the call to the noop function incorrectly increases the reference count, and the Foo object is not garbage collected. Without the call to the noop function, the Foo object is garbage collected. The expected output is:</p> <pre><code>ref cnt = 1 ref cnt = 1 garbage collect foo </code></pre> <p>Is this a known issue? Does anyone know a work-around or solution? Is this caused by a bug in ctypes?</p>
3
How to select multiple columns from a table while ensuring that one specific column doesn't contain duplicate values in sql server?
<p><strong>Table:</strong><br/></p> <pre><code>x_id---y---z_id------a-------b-------c 1------0----NULL----Blah----Blah---Blah 2------0----NULL----Blah----Blah---Blah 3------10---6-------Blah----Blah---Blah 3------10---5-------Blah----Blah---Blah 3------10---4-------Blah----Blah---Blah 3------10---3-------Blah----Blah---Blah 3------10---2-------Blah----Blah---Blah 3------10---1-------Blah----Blah---Blah 4------0----NULL----Blah----Blah---Blah 5------0----NULL----Blah----Blah---Blah </code></pre> <p><strong>My Query</strong>:</p> <pre><code>SELECT #temp.x_id, #temp.y, MAX(#temp.z_id) AS z_id FROM #temp GROUP BY #temp.x_id </code></pre> <p><strong>Error</strong>: <code>Column 'y' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.</code></p> <p><strong>Requirement:</strong> I want x_id to be unique and i want to select the MAX value of z_id</p> <p><strong>Expected Output:</strong><br/></p> <pre><code>x_id---y---z_id------a-------b-------c 1------0----NULL---Blah----Blah-----Blah 2------0----NULL---Blah----Blah-----Blah 3------10---6------Blah----Blah-----Blah 4------0----NULL---Blah----Blah-----Blah 5------0----NULL---Blah----Blah-----Blah </code></pre>
3
htaccess - Setting up a root diretory within a subfolder?
<p>The URL is <a href="https://subdomain.domain.com/subfolder" rel="nofollow noreferrer">https://subdomain.domain.com/subfolder</a>. But the subfolder's root folder (the folder that should be read by browsers) is 'web' and it's located in the subfolder. So the URL should be <a href="https://subdomain.domain.com/subfolder/web" rel="nofollow noreferrer">https://subdomain.domain.com/subfolder/web</a>, but I would like it to be shown as <a href="https://subdomain.domain.com/subfolder" rel="nofollow noreferrer">https://subdomain.domain.com/subfolder</a>. How do I set up a htaccess rule in the 'subfolder'? Thanks. </p>
3
Set a maximum year in datepicker jquery
<p>I have the following code </p> <pre><code>&lt;script&gt; $(document).ready(function() { $(".datepicker").datepicker( { year = today.getFullYear, format: " yyyy", // Notice the Extra space at the beginning viewMode: "years", minViewMode: "years", yearRange: '1920 : year', autoclose: true, }); }); &lt;/script&gt; </code></pre> <p>as you can see I only need the year, but I don't want to pick the following years... I mean 2020, 2021, 2022... Shouldn't be even able to be picked.. I looked around but couldn't find a solution, can someone help me with that? Thanks</p> <p>EDIT: </p> <pre><code>&lt;script&gt; $(document).ready(function() { $('#datepicker').keyup(function() { var inputVal = $(this).val(); var dateReg = /^\d{4}$/; if (dateReg.test(inputVal)) { $("#datemsg").html("Valid").css("color", "green"); } else { $("#datemsg").html("Invalid date").css("color", "red"); } }); $("#datepicker").datepicker({ format: " yyyy", // Notice the Extra space at the beginning viewMode: "years", minViewMode: "years", autoclose: true, endDate: new Date(), }); }); &lt;/script&gt; </code></pre>
3
C# global clipboard contents
<p>I am not sure if I am going about this c# form the right way. I want to get the clipboard contents of any ctrl + C events that happen on any window. What is the right way to capture global clipboard information?</p> <pre><code> namespace WindowsFormsApplication1 { public class copydata { public int entry; public string data; } public partial class Form1 : Form { // DLL libraries used to manage hotkeys [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk); [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern bool UnregisterHotKey(IntPtr hWnd, int id); const int COPY_ACTION = 1; const int TOGGLE_FORM = 2; const int WM_HOTKEY = 0x0312; List&lt;copydata&gt; copies; int count; public Form1() { InitializeComponent(); RegisterHotKey(this.Handle, COPY_ACTION, 2, Keys.C.GetHashCode()); RegisterHotKey(this.Handle, TOGGLE_FORM, 6, Keys.L.GetHashCode()); copies = new List&lt;copydata&gt;(); count = 0; } private void button1_Click(object sender, EventArgs e) { Clipboard.SetText(listBox1.Items[listBox1.SelectedIndex].ToString()); } protected override void WndProc(ref Message m) { base.WndProc(ref m); if(m.Msg == WM_HOTKEY) { if(m.WParam.ToInt32() == COPY_ACTION) { string val = Clipboard.GetText(); ++count; copies.Add(new copydata { entry = count, data = val }); this.listBox1.DisplayMember = "data"; this.listBox1.ValueMember = "entry"; this.listBox1.DataSource = copies; } if (m.WParam.ToInt32() == TOGGLE_FORM) { if(!this.Visible) { this.Show(); } else { this.Hide(); } } } } } } </code></pre>
3
String literal binds to a non-const char pointer
<p>Consider the following program:</p> <pre><code>#include &lt;iostream&gt; void myprint(const char* fmt, ...) { std::cout &lt;&lt; "1 "; } void myprint(const char* fmt, char *x) { std::cout &lt;&lt; "2 "; } int main() { const char* s = "c"; myprint("a", s); myprint("a", "b"); } </code></pre> <p>It produces different output:</p> <ul> <li><p><a href="http://rextester.com/FRX58318" rel="nofollow noreferrer">GCC</a> and <a href="http://rextester.com/RAGTP26923" rel="nofollow noreferrer">MSVC</a>: <code>1 2</code></p></li> <li><p><a href="http://rextester.com/IUS58046" rel="nofollow noreferrer">clang</a>: <code>1 1</code></p></li> </ul> <p>My question is two-fold:</p> <ol> <li><p>Why does a string literal bind to a non-const <code>char*</code> even in the presence of <code>-std=c++14</code>? Isn't a string literal <code>const</code> since C++11?</p></li> <li><p>The ellipsis-overload is always ranked lowest. Why does clang select it? (one would think it doesn't allow binding to <code>char*</code> but if I remove the ellipsis overload, it still does - <a href="http://rextester.com/LALIF98887" rel="nofollow noreferrer">demo</a>)</p></li> </ol> <p>What's going on and who is right?</p>
3
Hello, I want to create a javafx project, but does it need Database?
<p>I want to create a javafx project, but does it need Database?</p> <p>when I create this program save these name when I input this name and other. I mean save the result in the program and show me when I run it, I don’t need to be store for along time .just for that time when I will run it?</p>
3
How to judge bmp pictures from clipboard whether they are same using wxpython?
<p>Function that I want to realize: when the bmp picture get from clipboard is changed, refresh window. If not, nothing will be done.</p> <p>Question that I meet: every time my program goes into function UpdateMsgShownArea(), self.oldBmp will be diff with self.bmp, but I have already let self.oldBmp = self.bmp if they are different, and it prints "111111". While next time the program goes into UpdateMsgShownArea(), self.oldBmp will be diff with self.bmp again. It confuses me.</p> <p><a href="https://i.stack.imgur.com/b4j9B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b4j9B.png" alt="my print message image"></a></p> <p>code as follows:</p> <pre><code>#!/usr/bin/env python import wx import os, sys #---------------------------------------------------------------------------- # main window class MyFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(600,480)) self.panel = MyPanel(self) self.CreateStatusBar() # A StatusBar in the bottom of the window # Setting up the menu. filemenu= wx.Menu() # wx.ID_ABOUT and wx.ID_EXIT are standard ids provided by wxWidgets. menuAbout = filemenu.Append(wx.ID_ABOUT, "&amp;About"," Information about this program") menuExit = filemenu.Append(wx.ID_EXIT,"E&amp;xit"," Terminate the program") # Creating the menubar. menuBar = wx.MenuBar() menuBar.Append(filemenu,"&amp;File") # Adding the "filemenu" to the MenuBar self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content. # Set events. self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout) self.Bind(wx.EVT_MENU, self.OnExit, menuExit) self.Show(True) def OnAbout(self,e): # A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets. dlg = wx.MessageDialog( self, "A small text editor", "About Sample Editor", wx.OK) dlg.ShowModal() # Show it dlg.Destroy() # finally destroy it when finished. def OnExit(self,e): self.Close(True) # Close the frame. #---------------------------------------------------------------------------- # main panel class MyPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) # shared path boxsizer, DirPickerCtrl is alternative and better realization for textCtrl + btn sharedPathStaticText = wx.StaticText(self, -1, 'Shared Dir:') self.sharedPathTextCtrl = wx.TextCtrl(self, -1, 'Please choose a dir', style = wx.TE_READONLY|wx.TE_RICH) sharedPathBtn = wx.Button(self, -1, 'Browse', name = 'Shared dir button') box1 = wx.BoxSizer(wx.HORIZONTAL) box1.Add(sharedPathStaticText, 0, wx.ALIGN_CENTER) box1.Add(self.sharedPathTextCtrl, 1, wx.ALIGN_CENTER|wx.LEFT|wx.RIGHT, 5) # proportion = 1, border = 5 box1.Add(sharedPathBtn, 0) self.Bind(wx.EVT_BUTTON, self.OnOpen, sharedPathBtn) # local path boxsizer localPathStaticText = wx.StaticText(self, -1, 'Local Dir: ') self.localPathTextCtrl = wx.TextCtrl(self, -1, 'Please choose a dir', style = wx.TE_READONLY|wx.TE_RICH) localPathBtn = wx.Button(self, -1, 'Browse', name = 'local dir button') box2 = wx.BoxSizer(wx.HORIZONTAL) box2.Add(localPathStaticText, 0, wx.ALIGN_CENTER) box2.Add(self.localPathTextCtrl, 1, wx.ALIGN_CENTER|wx.LEFT|wx.RIGHT, 5) # proportion = 1, border = 5 box2.Add(localPathBtn, 0) self.Bind(wx.EVT_BUTTON, self.OnOpen, localPathBtn) # message show area messageShowStaticText = wx.StaticText(self, -1, 'Sync info shown area: ') box5 = wx.BoxSizer(wx.HORIZONTAL) box5.Add(messageShowStaticText, 0, wx.ALIGN_LEFT) # size (200,200) don't take effect #msgShowAreaID = wx.NewId() #print msgShowAreaID self.msgShowArea = wx.ScrolledWindow(self, -1, size = (200,200), style = wx.SIMPLE_BORDER) box3 = wx.BoxSizer(wx.HORIZONTAL) box3.Add(self.msgShowArea, 1, wx.ALIGN_CENTER, 10) # sync ctrl buttons stopSyncBtn = wx.Button(self, -1, 'Stop Sync', name = 'Stop Sync button') resumeSyncBtn = wx.Button(self, -1, 'Resume Sync', name = 'Resume Sync button') box4 = wx.BoxSizer(wx.HORIZONTAL) box4.Add(stopSyncBtn, 0, wx.ALIGN_CENTER|wx.RIGHT, 20) box4.Add(resumeSyncBtn, 0, wx.ALIGN_CENTER|wx.LEFT, 20) # sizer sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(box1, 0, wx.EXPAND|wx.ALL, 10) sizer.Add(box2, 0, wx.EXPAND|wx.ALL, 10) sizer.Add(box5, 0, wx.EXPAND|wx.ALL, 10) sizer.Add(box3, 0, wx.EXPAND|wx.ALL, 10) sizer.Add(box4, 0, wx.ALIGN_CENTER, 10) self.SetSizer(sizer) self.SetAutoLayout(True) # clipboard self.clip = wx.Clipboard() self.x = wx.BitmapDataObject() self.bmp = None self.oldBmp = None self.msgShowArea.Bind(wx.EVT_IDLE, self.UpdateMsgShownArea) self.msgShowArea.Bind(wx.EVT_PAINT, self.OnPaint) def OnOpen(self, e): """ Open a file""" button = e.GetEventObject() dlg = wx.DirDialog(self, "Choose a dir", "", wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() if button.GetName() == 'Shared dir button': self.sharedPathTextCtrl.SetValue(path) if button.GetName() == 'local dir button': self.localPathTextCtrl.SetValue(path) dlg.Destroy() def UpdateMsgShownArea(self, e): print "UpdateMsgShownArea" self.clip.Open() self.clip.GetData(self.x) self.clip.Close() self.bmp = self.x.GetBitmap() if self.oldBmp == self.bmp: print "same pic" return else: print "diff pic" self.oldBmp = self.bmp if self.oldBmp == self.bmp: print "111111" else: print "222222" print "abcd" #self.Refresh() #self.msgShowArea.Refresh() def OnPaint(self, evt): if self.bmp: dc = wx.PaintDC(self.msgShowArea) dc.DrawBitmap(self.bmp, 20, 20, True) #---------------------------------------------------------------------------- if __name__ == '__main__': app = wx.App(False) frame = MyFrame(None, "EasySync") app.MainLoop() </code></pre>
3
Fatal error: Call to undefined function new_mysqli() in C:\wamp\www\work\conn.php on line 8
<p>I'm making a login page. The connection to mysqli keeps showing me this message:</p> <blockquote> <p>Fatal error: Call to undefined function new_mysqli() in C:\wamp\www\work\conn.php on line 8</p> </blockquote> <p><strong>conn.php</strong>:</p> <pre><code>&lt;?php $dbhost = "loaclhost"; $dbuser = "root"; $dbpass = ""; $dbname = "users"; $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname); ?&gt; </code></pre>
3
How distribute OSX cli / server app
<p>Im building a cli app that can run in server mode for osx in golang. I come from the server world and have no idea how properly distribute a consumer cli tool for osx. The cli can run as a service which can be easily achieved with launchd. </p> <p>Launchd config:</p> <pre><code>&lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;KeepAlive&lt;/key&gt; &lt;true/&gt; &lt;key&gt;Label&lt;/key&gt; &lt;string&gt;focus-daemon&lt;/string&gt; &lt;key&gt;RunAtLoad&lt;/key&gt; &lt;true /&gt; &lt;key&gt;Program&lt;/key&gt; &lt;string&gt;/usr/local/bin/focus&lt;/string&gt; &lt;/dict&gt; &lt;/plist&gt; </code></pre> <p>Building and running is also quite simple:</p> <pre><code>go build main.go sudo cp main /usr/local/bin/focus rm main sudo chown root /usr/local/bin/focus sudo chmod 4555 /usr/local/bin/focus cp focus.plist ~/Library/LaunchAgents/com.21stio.focus.plist launchctl load ~/Library/LaunchAgents/com.21stio.focus.plist </code></pre> <p>When being build the process requires sudo to set a sbit on the binary.</p> <p>I don't want the user having to run a .sh script. Maybe I could use brew and/or a DMG for that. But I have no idea how I can put the <code>Launchd config</code> at the right spot then.</p>
3
Using DATADIFF in a query (PL/SQL)
<p>I'm trying to use a DataDiff in a query so that I can also "print" the difference between the two dates, in seconds. The query looks like this:</p> <pre><code>SELECT vr.CodeR, vi.DateU, vl.originU, vl.destinyU, (DATEDIFF(second,vi.plannedDate,vi.SetDate) AS DiffDate) FROM RegularU vr, Connection vl, InstantU vi WHERE vl.codeU=vr.codeU AND vr.CodeR=vi.CodeR </code></pre> <p>But when I try to run it I have the error "Missing select word". Is there a way so that I can do this in a query?</p> <p>Thanks in advance</p>
3
Passing login information through a URL to a form with changing attribute names
<p>I am working on a project which involves setting up a bunch of dashboards around the office. The plan is to use Screenly on Raspberry Pi 3s, as it seems to fit our needs for the most part at a very low cost. The problem is, some of the webpages that need to be displayed are locked behind a login. Screenly doesn't have a way to get past this, other than passing the login information and the page redirect through the URL itself. I am aware of the potential security issues this could bring, which is why the account we crated for this use can only view (and not edit) very specific pages. </p> <p>I want to pass login information through a URL in order to login to a website and directly access a specific page on that website. I have had success passing login information in the form of:</p> <pre><code>https://website.com/dologin.action?username=CapnCrunch&amp;password=Fr00tl00ps&amp;login=Log+in&amp;os_destination=%2Fpages%2Fviewpage.action%3FpageId%58008 </code></pre> <p>This works nicely when the username and password attribute names are always the same, but not when they change on every refresh. Instead of the HTML attributes for the username box remaining the same every time the login page is accessed, they change slightly every time.</p> <p>For example, these are the HTML attributes for the username upon loading the page for the first time:</p> <pre><code>&lt;input name="ct100$phUser$txtUser8193" type"text" id="txtUser8193" class="login_user border-box" placeholder="My Username"&gt; </code></pre> <p>But when I refresh the page, this same bit of HTML code changes to:</p> <pre><code>&lt;input name="ct100$phUser$txtUser5516" type"text" id="txtUser5516" class="login_user border-box" placeholder="My Username"&gt; </code></pre> <p>I would love to pass the URL arguments in the form of:</p> <pre><code>dologin.action?ct100$phUser$txtUserXxXx=CapnCrunch </code></pre> <p>Where XxXx is just whatever number the page decided to use at that time.</p> <p>All the solutions I have found online include using external scripts of some kind. The problem is, Screenly only accepts URLs. Using a script would involve either editing Screenly's source code, or using a proxy webpage.</p> <p>Is there any way to get around the changing attribute name without using external scripts?</p> <p>Thanks in advance</p>
3
Why to cast a list in another list
<p>I have a method in Spring Data JPA which returns a type of list.</p> <pre><code>List&lt;ModuleAccessEntity&gt; findByNameNotIgnoreCase(String moduleName); </code></pre> <p>Now on ServicesImplimentation. This list is transferred to another list.</p> <pre><code>moduleAccessEntity=(List&lt;ModuleAccessEntity&gt;) moduleAccessRepository.findByNameNotIgnoreCase("self"); </code></pre> <p>here moduleAccessEntity also is list of type.</p> <pre><code>List&lt;ModuleAccessEntity&gt; moduleAccessEntity ; </code></pre> <p>I don't understand why is there a need of putting list in two more lists when we are already getting a list. Can't we do this in easy way like.</p> <pre><code>moduleAccessEntity= moduleAccessRepository.findByNameNotIgnoreCase("self"); </code></pre>
3
Android: Cant connect with database on Remote Server
<p>Good day, I am creating an Android program that connects to MS SQL 2012 database on a remote server.. Im currently using Eclipse Juno.. my code works on Eclipse Helius but when I transfer my code to Juno, I encounter problems with connecting to database... I already added drivers such as "mysql-connector-java-5.1.33" and "jtds-1.2.5" </p> <p>Here is my code:</p> <pre><code>Connection conn = null; int a = 0; try { Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance(); String connString = "jdbc:jtds:sqlserver://xxx.xxx.xxx.xxx:1433/SAMPLEDB;encrypt=false;user=XX;password=XXXXXXX;instance=SQLEXPRESS;"; String username = "XX"; String password = "XXXXXXX"; String sql = ""; conn = DriverManager.getConnection(connString, username, password); a++; Statement stmt = conn.createStatement(); a++; sql = "Select * from NUMBERFILE"; ResultSet reset = stmt.executeQuery(sql); a++; while(reset.next()) { tDisplayS.setText(reset.getString("NUMBER").toString()); } } catch(Exception e) { Toast.makeText(getApplicationContext(), e.getMessage() + " " + a, Toast.LENGTH_LONG).show(); } </code></pre> <p>I used "a" to indicate where it would stop then it only has a value of 1 so meaning it cant establish connection.. I already searched for similar problems with mine but still no luck..</p> <p>Please help.. appreciate all your reply.. </p> <p>Thanks!</p>
3
JPA Replace in database Annotation
<p>I have this class:</p> <pre><code>@Entity @Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "date", "meterTime" }) }) public class Meter { public enum MeterTime { AFTER_FAST, AFTER_MEAL } @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") private Date date; @Enumerated(EnumType.STRING) private MeterTime meterTime; private Float meter; // constructor, getters and setters } </code></pre> <p>now, when I try to insert a row with date and meterTime already existents, the row is not inserted..</p> <p>but! I want to be inserted (and replace the existent row)</p> <p>how can I do this?</p> <p>Thanks!</p>
3
Rewrite Rule in .htaccess file for subdomain
<p>I have a subdomain named </p> <pre><code>http://career.example.com </code></pre> <p>My URL Look Like</p> <pre><code>http://career.example.com/details.php?jid=17 </code></pre> <p>Now I wan to show my URL look Like</p> <pre><code>http://career.example.com/details </code></pre> <p>I use this code in my .htaccess but not work</p> <pre><code>RewriteEngine on RewriteCond %{HTTP_HOST} ^career\.example\.com [NC] RewriteRule ^(.*) http://example.com/$1 [L,R=301] RewriteRule ^details/([0-9]+)/?$ details.php?jid=$1 [NC,L] </code></pre>
3
HTML table in PHP
<p>I have the following code but it's not working like I want it to work. I just want the table header to be shown once but now it repeats the header everytime. And I want the table header to be horizontally but now it is vertically.</p> <p>code:</p> <pre><code>&lt;?php include ("core/db_connectie.php"); //file_get_contents("main.tpl.php"); $query = "SELECT * FROM platen"; $result = mysql_query($query) or die (mysql_error()); $table = "&lt;table&gt;"; $cName = ""; $cValue = ""; while($row = mysql_fetch_assoc($result)) { foreach($row as $columnName=&gt;$columnValue) { $cName .= $columnName; $cValue .= $columnValue; } } $table .= "&lt;tr&gt;&lt;th&gt;". $cName ."&lt;/th&gt;&lt;/tr&gt;"; $table .= "&lt;tr&gt;&lt;td&gt;". $cValue ."&lt;/td&gt;&lt;/tr&gt;"; $table .= "&lt;/table&gt;"; echo $table; </code></pre> <p><strong>EDIT:</strong></p> <p>I changed the code but it's still not working now it just paste everything after eachother</p> <p>Example:</p> <pre><code>IDAlbumBandStijlMediumDatumPrijsIDAlbumBandStijlMediumDatumPrijs 1TestTestereRockLP2013-06-1202TestTestereRockLP2013-06-1213 </code></pre>
3
Unknown name value for Enum exception in concurrent application
<p>I have two grails 2.1.1 application versions running on the same database (SQL Server 2005). Applications are running on different servers. Enum type was introduced in first application.</p> <pre><code> public enum EnumModeType { STARTUP, RUNNING, STOPPED, POSTPONED, FINISHED, NONE } </code></pre> <p>Second application started throwing exception "Unknown name value for Enum exceptionEnumModeType.FINISHED" after deploying changes to first application. First application is running correctly. I changed first application to initial version and exceptions in second application disappeared.</p> <p><strong>UPDATE:</strong> Exception occurs after second application tries insert string value "FINISHED" to other table. This other table column has String datatype. It'is not defined as Enum.</p> <p>How this is possible and where is the root cause?</p>
3
comparing a datagridview cell with an integer value
<p>This coding was recently upgraded from C#.Net 2008 to C#.Net 2012. The value of this cell in this DataGridView = 4 but an exception is thrown every time my program arrives at this line. What am I missing here ?</p> <pre><code>if (((int)dgQueue.SelectedRows[0].Cells["StatusKey"].Value != 1 &amp;&amp; isRequestCheck)) </code></pre> <p>I'm receiving an InvalidCastException with a detail explanation of Specified cast is not valid...</p>
3
return view() for all actions in controller .net mvc
<p>I have one controller <code>HomeController.cs</code>.</p> <p>In this controller I have some actions like about,contact etc.</p> <p>If I want that will work I have to defined function to each view:</p> <pre><code>public ActionResult Index() { return View(); } public ActionResult About() { return View(); } </code></pre> <p>I want that for all the requests to the controller it will be return the <code>View()</code>, so I will not have to defined a function to each view.</p> <p><strong>*Update</strong> I want to know if there is some handler that will work something like this:</p> <pre><code>protected override void OnActionCall() { return View(); } </code></pre>
3
Returning from a function while continuing to execute
<p>I am working on a Django application where I would like to populate several fields within my model when an object is first created. Currently I am able to do this in the <code>save()</code> routine of my model like so:</p> <pre><code>def save(self, *args, **kwargs): file = fileinfo.getfileinfo(self.file_path) if not self.file_size: self.file_size = file.FileSize if not self.file_inode: self.file_inode = file.FileInode if not self.duration: self.duration = file.Duration if not self.frame_width: self.frame_width = file.ImageWidth if not self.frame_height: self.frame_height = file.ImageHeight if not self.frame_rate: self.frame_rate = file.VideoFrameRate super(SourceVideo, self).save(*args, **kwargs) </code></pre> <p>I created a function called <code>getfileinfo</code> within a separate module called <code>fileinfo</code>. This is what part of my function looks like:</p> <pre><code>def getfileinfo(source): fstats = os.stat(source) info = dict({ u'FileSize': fstats.st_size, u'FileInode': fstats.st_ino }) output = subprocess.Popen( [exiftool, '-json', source], stdout=subprocess.PIPE) info.update( json.loads(output.communicate()[0], parse_float=decimal.Decimal)[0]) return DotDict(info) </code></pre> <p>Although all of this works, I would like to avoid blocking the save process should the retrieval process be delayed for some reason. The information is not needed at object creation time and could be populated shortly thereafter. My thought was that I would alter my function to accept both the file path in question <strong>as well</strong> as the primary key for the object. With this information, I could obtain the information and then update my object entry as a separate operation.</p> <p>Something like:</p> <pre><code>def save(self, *args, **kwargs): fileinfo.getfileinfo(self.file_path, self.id) super(SourceVideo, self).save(*args, **kwargs) </code></pre> <p>What I would like help with is how to return from the function prior to the actual completion of it. I want to call the function and then have it return nothing as long as it was called correctly. The function should continue to run however and then update the object on its end once it is done. Please let me know if I need to clarify something. Also, is thing even something work doing?</p> <p>Thanks</p>
3
CSS center an element
<p>Why do 'margin left and right set to auto and max. and min. width' center an element?</p> <pre><code>#header{ max-width: 1400px; min-width: 360px; margin-left: auto; margin-right: auto; } </code></pre> <p>I do not get it. </p>
3
dynamic form funky behavior in vuejs
<p>I am using VueJS 2.6.11 and bootstrap 4 to create two dynamic sections(Category and Product) that contain divs and input fields. The product section is nested within the category section. When someone clicks the New Category button another category should get generated. The same behavior should also happen when someone clicks the New Product button, another Product section should get generated, but only inside the current category section.</p> <p>Issue:</p> <p>When someone clicks the New Product button, the Add Product section will get generated inside all current Category sections. Also, v-model appears to bind to every product name input. When someone clicks the X button for a specific Product section one product section would get deleted from all current Category sections.</p> <p>I'm not exactly sure why this is happening.</p> <p>codepen: <a href="https://codepen.io/d0773d/pen/ExjbEpy" rel="nofollow noreferrer">https://codepen.io/d0773d/pen/ExjbEpy</a></p> <p>code: </p> <pre><code>&lt;!-- Bootstrap CSS --&gt; &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"&gt; &lt;title&gt;Create Categories and Products&lt;/title&gt; </code></pre> <p> </p> <pre><code> &lt;!-- New Category --&gt; &lt;button class="btn btn-success mt-5 mb-5" @click="addNewCategoryForm"&gt; New Category &lt;/button&gt; &lt;div class="card mb-3" v-for="(category, index) in categories"&gt; &lt;div class="card-body"&gt; &lt;span class="float-right" style="cursor:pointer" @click="deleteCategoryForm"&gt; X &lt;/span&gt; &lt;h4 class="card-title"&gt;Add Category&lt;/h4&gt; &lt;div class="category-form"&gt; &lt;input type="text" class="form-control mb-2" placeholder="Category Name" v-model="category.name"&gt; &lt;/div&gt; &lt;!-- New Product --&gt; &lt;button class="btn btn-success mt-5 mb-5" @click="addNewProductForm"&gt; New Product &lt;/button&gt; &lt;div class="card mb-3" v-for="(product, index) in products"&gt; &lt;div class="card-body"&gt; &lt;span class="float-right" style="cursor:pointer" @click="deleteProductForm"&gt; X &lt;/span&gt; &lt;h4 class="card-title"&gt;Add Product&lt;/h4&gt; &lt;div class="product-form"&gt; &lt;input type="text" class="form-control mb-2" placeholder="Product Name" v-model="product.name"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Optional JavaScript --&gt; &lt;!-- jQuery first, then Popper.js, then Bootstrap JS --&gt; &lt;script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"&gt;&lt;/script&gt; &lt;script&gt; var app = new Vue({ el: '.container', data: { categories: [ { name: '', } ], products: [ { name: '', } ] }, methods: { addNewCategoryForm () { this.categories.push({ name: '', }); }, deleteCategoryForm (index) { this.categories.splice(index, 1); }, addNewProductForm () { this.products.push({ name: '', }); }, deleteProductForm (index) { this.products.splice(index, 1); }, } }); &lt;/script&gt; </code></pre> <p> </p>
3
Error when get value in from node father?
<p>I have a sample data:</p> <pre><code>product(id, parent_id, name) 1 | 0 | Windows 2 | 1 | XP 3 | 1 | 7 manufacturer(id, parent_id, name) 1 | 0 | Westwood Studios 2 | 1 | Red Alert 1 3 | 1 | Red Alert 2 product_manufacturer(product_id, manufacturer_id) 2 | 2 3 | 2 3 | 3 </code></pre> <p>And mysql: </p> <pre><code>SELECT prod.name FROM `manufacturer` AS child INNER JOIN `manufacturer` AS parent ON parent.id=child.parent_id INNER JOIN `product_manufacturer` AS pr_ma ON pr_ma.manufacturer_id=child.manufacturer_id INNER JOIN `product` AS prod ON pr_ma.product_id=prod.product_id WHERE parent.id=1 GROUP BY prod.id </code></pre> <p>When <code>parent.id=1 (manufacturer=Westwood Studios)</code> is result is <code>XP, 7</code></p> <p>How to fix when <code>parent.id=1</code> is result is <code>Windows</code></p>
3
Multiple Combobox selection Acess VBA
<p>I am trying to create a VBA code that says, if combobox equals this or this or this then have radio button populate. When i use only one bucket (134) it works fine but when i try ti add multiple sections, i get and err. </p> <p>My code: </p> <pre><code>If Me.cmbBucketFilter = "134,135,136" Then 'Working Echo Triggers Me.fmeReached.Visible = True Me.fmeRecovered.Visible = True Me.fmeError.Visible = False Else 'Working Another Bucket Me.fmeError.Visible = True Me.fmeReached.Visible = False Me.fmeRecovered.Visible = False End If </code></pre>
3
Controlling size of new window for external link
<p>I have a popup on my homepage, and I am happy with the size of that window...I have added a link on the homepage to direct to same popup, but it opens in a full size window. How do I get the linked file to open in same size window as the popup?</p>
3
Java two dimensional array notation and default access
<p>From the following code:</p> <pre><code> /** Array for internal storage of elements. @serial internal array storage. */ private double[][] A; /** Row and column dimensions. @serial row dimension. @serial column dimension. */ private int m, n; public Matrix times (Matrix B) { if (B.m != n) { throw new IllegalArgumentException("Matrix inner dimensions must agree."); } Matrix X = new Matrix(m,B.n); double[][] C = X.getArray(); double[] Bcolj = new double[n]; for (int j = 0; j &lt; B.n; j++) { for (int k = 0; k &lt; n; k++) { Bcolj[k] = B.A[k][j]; } for (int i = 0; i &lt; m; i++) { double[] Arowi = A[i]; double s = 0; for (int k = 0; k &lt; n; k++) { s += Arowi[k]*Bcolj[k]; } C[i][j] = s; } } return X; } </code></pre> <p><code>double[] Arowi = A[i];</code></p> <p>What is this line doing? A is a two dimensional Matrix, why is A[i] allowed? and what exactly is it doing? Is that the same thing as <code>A[i][0]</code>?</p> <p>This notation is confusing.</p> <p>Also could someone translate that line to .NET, how would you do that with a <code>double[,] Matrix</code>?</p> <p>I know there is a Matrix.GetLength() which gives you a specified length of a dimension. But comparison to that line of Java code, how would that be translated?</p> <p><strong>EDIT</strong> I believe I fixed it by just replacing that line and passing in my matrix to copy the first row into a new one dimensional matrix and returning it</p> <pre><code> public double[] ConvertFirstRowOfMultiArrayToOneArray(double[,] p) { double[] array = new double[p.Length]; for (int i = 0; i &lt; p.GetLength(0); i++) { array[i] = p[0, i]; } return array; } </code></pre>
3
MySQL Average unique x for day of the week
<p>I'm trying to get a MySQL query together to get the average amount of unique devices from a table which logs mac addresses, for each day of the week in a given month and year. So far i have this to count all devices.</p> <pre><code>SELECT DAYNAME(date_time) dow, DAYOFWEEK(date_time) day_num, COUNT( DISTINCT (mac) ) as devices FROM detected_devices WHERE client_id = 11 AND venue_id = 1 AND EXTRACT( YEAR FROM date_time) = 2010 AND EXTRACT( MONTH FROM date_time) = 12 GROUP BY dow ORDER BY day_num </code></pre> <p>Thats getting me the total number of devices but i can't seem to use the AVG function too. I've tried this line instead but get error #1111 - Invalid use of group function when i do.</p> <pre><code>AVG( COUNT( DISTINCT (mac) ) ) as devices </code></pre>
3
How to write this code with cakephp 2.2.1 html helper?
<p>I probably made a monster when writing an echo for outputting generated links :( I don't understand how to concatenate all this params when using HtmlHelper. I read article about it twice but don't get it.</p> <p>My code is:</p> <pre><code>echo "&lt;a href=\"/img/filmography/" . $movie['Film']['frameset'] . "_frame_" . $i . ".jpg\"" . "rel=\"lightbox[" . $movie['Film']['id'] . "]\"" . " title=\"\"&gt;" . "&lt;img src=\"/img/filmography/thumb/" . $movie['Film']['frameset'] . "_frame_" . $i . ".jpg\"" . "alt=\"pic from " . $movie['Film']['title'] . "\"" . "/&gt;&lt;/a&gt;"; </code></pre> <p>What I want to achieve in HTML:</p> <pre><code> &lt;a href="/img/filmography/movie_frame_1.jpg" rel="lightbox[1]" title=""&gt; &lt;img src="/img/filmography/thumb/movie_frame_1.jpg" alt="pic from some movie"/&gt; &lt;/a&gt; </code></pre>
3
R package requiring the 'libquadmath' library
<p>I made a R package which uses <code>Rcpp</code> and which requires the <code>libquadmath</code> library (to use the multiprecision numbers of <code>boost</code>). On my personal laptop (Ubuntu 18.04), it works &quot;as is&quot;. On <code>win-builder</code> it works by setting <code>PKGLIBS = -lquadmath</code> or <code>PKGLIBS = $(FLIBS)</code> in the <code>Makevars</code> file. But I also checked on <code>r-hub</code> with these settings and for the Fedora Linux distribution (R-devel, clang, gfortran) I get a failure.</p> <p>This failure is:</p> <pre><code>/home/docker/R/BH/include/boost/multiprecision/float128.hpp:40:10: fatal error: 'quadmath.h' file not found </code></pre> <p>So I'm fearing that my package will not pass the CRAN checks. What is the way to go?</p>
3
Decrease bootstrap table width, colspan not working
<p>I am working with a bootstrap table, which contains in the right corner a table with rowspan = &quot;2&quot;, then it has 2 rows, and then at the other end another rowspan = &quot;2&quot;, looking like this: <a href="https://i.stack.imgur.com/eob6D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eob6D.png" alt="imagen de tabla" /></a></p> <p>The problem I'm having is that I can't &quot;shrink&quot; the width of the table where the image is, that is, the first column, I tried with col-1, with colspan = &quot;1&quot; but so far I can't find a solution, could you help me ?, the TOTAL WIDTH OF THE TABLE WHERE THE IMAGE IS, SHOULD BE THE SAME ROWSPAN = &quot;1&quot;.</p> <p>This is the code:</p> <pre><code>&lt;tr&gt; &lt;td rowspan=&quot;2&quot; colspan=&quot;1&quot;&gt; &lt;img src=&quot;IMAGE&quot;&gt; &lt;/td&gt; &lt;td class=&quot;col-10&quot;&gt; PRODUCT NAME &lt;/td&gt; &lt;td rowspan=&quot;2&quot; colspan=&quot;1&quot;&gt;$PRICE&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;span&gt;DESCRIPCION&lt;/strong&gt;&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre>
3
freeradius doesn't response to accounting packets
<p>I'm using Freeradius for my Radius Server project as the server and the Mysql as the database and daloradius for the web interface for billing and accounting.</p> <p>I am using this server for the AAA of my Mikrotik router. There is no problem with the authentication and authorization of users when using ssh to MikroTik or winbox connection. but when Mikrotik sends the accounting packets the server doesn't send any ack packets to the router and also doesn't save accounting records in the database. <a href="https://i.stack.imgur.com/lHylQ.png" rel="nofollow noreferrer">there is a screenshot of the Wireshark which is monitoring radius packets</a></p> <p>and as you see there is no response after accepting the user authentication request.</p> <p>then I tried to see a log of freeradius while sending the requests I ran this command</p> <pre><code>freeradius -X </code></pre> <p>and here is what I found :</p> <pre><code>(4) sql: ERROR: rlm_sql_mysql: ERROR 1054 (Unknown column 'acctupdatetime' in 'field `list'): 42S22` (4) sql: SQL query returned: server error rlm_sql (sql): Released connection (6) (4) [sql] = fail (4) } # accounting = fail (4) Not sending reply to client. (4) Finished request </code></pre> <p>I used the Freeradius Mysql schema samples in the Freeradius directory for making the database.</p> <p>any idea?</p>
3
React Native Component Renders under other components inside a modal
<p>I have a modal that contains various children components. One of them being a calendar component that is opened after pressing the text &quot;Select Date&quot;</p> <p>Upon opening the Calendar component renders underneath the other components on the page.</p> <p>I have tried using position: 'absolute' with a higher zIndex but I still cannot get the Calendar Component to render on top of everything else...how can I accomplish this?</p> <p><a href="https://i.stack.imgur.com/aNn5R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aNn5R.png" alt="Here is an image of what is occuring" /></a></p> <p><a href="https://i.stack.imgur.com/6eZFr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6eZFr.png" alt="This is wrapped in a View component with position: absolute and a high zindex" /></a></p> <p><a href="https://i.stack.imgur.com/Dz8Ku.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dz8Ku.png" alt="This is wrapped in a View component with position: absolute and a high zindex" /></a></p> <p>JSX For the components</p> <pre><code>&lt;View style={styles.container}&gt; &lt;View style={styles.routineitems}&gt; &lt;TouchableOpacity &gt; &lt;Text style={{ }}&gt;Due Date&lt;/Text&gt; &lt;/TouchableOpacity&gt; &lt;TouchableOpacity onPress={()=&gt;calendarShouldShow(calendarVisible)}&gt; &lt;Text style={{ }}&gt;Select Date&lt;/Text&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; &lt;Calendar style={{position: 'absolute',zIndex: 4}}/&gt; &lt;View style={styles.routineitems}&gt; &lt;Text&gt;Tags&lt;/Text&gt; &lt;DropDownPicker placeholder=&quot;Tags&quot; /&gt; &lt;/View&gt; &lt;View style={styles.routineitems}&gt; &lt;Text&gt;Notes&lt;/Text&gt; &lt;TextInput style={styles.input} onChangeText ={ value =&gt; setNotes(value)} value={notes} laceholder=&quot;Notes&quot; textAlign={'right'} /&gt; &lt;/View&gt; &lt;/View&gt; </code></pre> <p>STYLESHEET</p> <pre><code>const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', width: '100%' }, routineitems: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', width: '90%', marginBottom: '1%', marginTop: '1%', alignItems: 'center', zIndex: 0 }, input: { height: 40, width: '30%', borderRadius: 20, backgroundColor: 'white', fontSize: 50, textAlignVertical:'bottom', paddingTop: 0, paddingBottom:0, textAlign: 'right' } }); </code></pre>
3
limiting access to third party app in google ads api
<p>I have multiple Google ads account(multiple google ads account associated with one email account) . If I give access of my google ads account to third party app will they have access to all the google ads account?</p> <p>If the third party app can access all of my google ads account how do I restrict them to access only 1 account that I want.</p>
3
how to style menu.item on semantic ui React <input> search bar precisely
<p>The code is the menu style of semantic ui available for React including a search input i want to increase the size of the search input and also change the color.</p> <pre><code>&lt;Menu secondary&gt; &lt;Menu.Item&gt; &lt;img alt=&quot;logo&quot; src={logo} active={activeItem === 'home'} onClick={this.handleItemClick} /&gt; &lt;/Menu.Item&gt; &lt;Menu.Item&gt; &lt;Input icon='circle outline' iconPosition='left' placeholder='Search...' /&gt; &lt;/Menu.Item&gt; &lt;Menu.Menu position='right'&gt; &lt;Menu.Item name='logout' active={activeItem === 'logout'} onClick={this.handleItemClick} /&gt; &lt;/Menu.Menu&gt; &lt;/Menu&gt; </code></pre>
3
Where do I put persistent data in Catalyst?
<p>I am writing a Catalyst web application that presents some data that does not change in between requests. I want to load this data when the application starts and stick them somewhere so that the relevant controllers can use them. Where should I load this data and where should I store it? At first I tried to load it in the main <code>App.pm</code> file and put them into the application config. This works, but it’s ugly, since the <code>App.pm</code> file gets littered by a lot of loading subs that don’t really belong together:</p> <pre><code>__PACKAGE__-&gt;config(this =&gt; load_this()); __PACKAGE__-&gt;config(that =&gt; load_that()); # et cetera </code></pre> <p>Then I figured I could load some of the data in the controller that uses them and store them in the controller’s config hash. This is not perfect either, because some of the data is needed in more than one controller.</p> <p>I also thought I could localize the data to the controller instead of sharing them. This feels nice, because I would have all the code that works with the data more or less on one place. The problem is that the controller would also have to render parts of the resulting page for other controllers – for example if the title page controller wanted to display a list of recent news, it would have to ask the news controller to render the list. This does not seem to be the preferred way of doing things in Catalyst.</p> <p>How would you solve this?</p> <p>(The nature of the data: This is a website of a music festival. There is a line-up, a list of sponsors and other simple data pulled from YAML files, because database would be overkill and hard to edit.)</p>
3
OpenCV corrupting HQ Rapsicam data above 4000x3040 resoution?
<h1>The Problem</h1> <p>When I take an image using OpenCV that is larger than 4000 pixels wide, using a high quality picam, the image data appears corrupted (it's offset).</p> <h2>More Detail</h2> <p>As stated, I cannot get a good image when using OpenCV at over 4000 pixels wide of resolution. I know that the hardware is not the issue as I can get a clean full resolution (4056x3040) image when I use the raspistill command:</p> <p><code>sudo raspistill -o testing.tiff -w 4056 -h 3040</code></p> <p>Here is the clean output from raspistill:</p> <p><a href="https://i.stack.imgur.com/EuE8o.jpg" rel="nofollow noreferrer">4056x3040 image - Clean Image produced by raspistill command</a></p> <p>I am able to capture images using OpenCV in either Python:</p> <pre><code>import cv2 as cv def main(): cap = cv.VideoCapture(&quot;/dev/video2&quot;, cv.CAP_V4L2) cap.set(cv.CAP_PROP_FRAME_WIDTH, 4056)#works fine up to 4000 cap.set(cv.CAP_PROP_FRAME_HEIGHT, 3040) if not(cap.isOpened()): print(&quot;could not open video device&quot;) else: print(&quot;cap opened&quot;) ret, frame = cap.read() if(ret): cv.imwrite(&quot;./test_im.jpg&quot;, frame) print(&quot;image saved&quot;) else: print(&quot;no capture data returned&quot;) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>Or I can capture in OpenCV with C++:</p> <pre><code>#include &lt;opencv2/opencv.hpp&gt; #include &lt;iostream&gt; int main(int argc, char *argv[]){ cv::Mat frame; cv::VideoCapture cap(&quot;/dev/video2&quot;, cv::CAP_V4L2); cap.set(cv::CAP_PROP_FRAME_WIDTH, 4056); cap.set(cv::CAP_PROP_FRAME_HEIGHT, 3040); if(cap.isOpened() == false){ std::cout &lt;&lt; &quot;cap not opened&quot; &lt;&lt; std::endl; } else{ std::cout &lt;&lt; &quot;cap opened&quot; &lt;&lt; std::endl; } cap &gt;&gt; frame; if(frame.empty()){ std::cout &lt;&lt; &quot;empy frame&quot;; } else{ std::cout &lt;&lt; &quot;successfully captured image&quot; &lt;&lt; std::endl; cv::imwrite(&quot;test.tiff&quot;, frame); } } </code></pre> <p>The Result is the same either way.</p> <p>Here is the corrupted output from OpenCV:</p> <p><a href="https://i.stack.imgur.com/NFoB5.jpg" rel="nofollow noreferrer">4056x3040 image - Corrupted and captured by OpenCV</a></p> <p>To me it seems as if it something was going wrong with the timing of the capture. The format of which I save it to does not make a difference either. I have tried .png, .jpg, and .tiff. The result is always the same. After reboot the results remain the same.</p> <p>If I reduce the desired capture resolution to only 4000x3040 then I am able to successfully make a capture. Here are the results:</p> <p><a href="https://i.stack.imgur.com/1BMdC.jpg" rel="nofollow noreferrer">4000x3040 image - successfully captured by OpenCV</a></p> <p>I am not sure why this is happening. And would really appreciate any help! Let me know if there is any other information that could be useful!</p> <h1>System</h1> <ul> <li>Raspberry Pi 4B with 4GB RAM.</li> <li>High Quality Picam</li> <li>Running Ubuntu 20.04</li> <li>OpenCV 4.5.5</li> </ul>
3
GitHub integration with Jenkins
<p>There are multiple approaches in integrating Jenkins with GitHub</p> <p>Approach 1) Enable ssh communication between GitHub and Jenkins by copying public key file generated in Jenkins to GitHub account. This is one time task. </p> <p>For any pipeline take any GitHub url(say <code>ssh://[email protected]/account/repo.git</code>) and add using Github plugin for that respective pipeline cocnfiguration</p> <p>So, Jenkins file just need to have <code>checkout SCM</code> to checkout</p> <p>Approach 2) Enable https communication by adding webhook for every new repo by generating token and enable https comunication between GitHub and Jenkins. But this approach should be repeated for every new repo created in GitHub.</p> <p>We are using GitHub repo... in production</p> <p>Which is the best practice of GitHub integration with Jenkins in production?</p>
3
Keras LSTM from for loop, using functional API with custom number of layers
<p>I am trying to build a network through the keras functional API feeding two lists containing the number of units of the LSTM layers and of the FC (Dense) layers. I want to analyse 20 consecutive segments (batches) which contain fs time steps each and 2 values (2 features per time step). This is my code:</p> <pre><code>Rec = [4,4,4] FC = [8,4,2,1] def keras_LSTM(Rec,FC,fs, n_witness, lr=0.04, optimizer='Adam'): model_LSTM = Input(batch_shape=(20,fs,n_witness)) return_state_bool=True for i in range(shape(Rec)[0]): nRec = Rec[i] if i == shape(Rec)[0]-1: return_state_bool=False model_LSTM = LSTM(nRec, return_sequences=True,return_state=return_state_bool, stateful=True, input_shape=(None,n_witness), name='LSTM'+str(i))(model_LSTM) for j in range(shape(FC)[0]): nFC = FC[j] model_LSTM = Dense(nFC)(model_LSTM) model_LSTM = LeakyReLU(alpha=0.01)(model_LSTM) nFC_final = 1 model_LSTM = Dense(nFC_final)(model_LSTM) predictions = LeakyReLU(alpha=0.01)(model_LSTM) full_model_LSTM = Model(inputs=model_LSTM, outputs=predictions) model_LSTM.compile(optimizer=keras.optimizers.Adam(lr=lr, beta_1=0.9, beta_2=0.999, epsilon=1e-8, decay=0.066667, amsgrad=False), loss='mean_squared_error') return full_model_LSTM model_new = keras_LSTM(Rec, FC, fs=fs, n_witness=n_wit) model_new.summary() </code></pre> <p>When compiling I get the following error:</p> <p><strong>ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_1:0", shape=(20, 2048, 2), dtype=float32) at layer "input_1". The following previous layers were accessed without issue: []</strong></p> <p>Which I actually don't quite understand, but suspect it may have something to do with inputs?</p>
3
FakeItEasy assert that method call to method
<p>I have an unit-test written with <em>FakeItEasy v2.2.0</em>.</p> <p>The test tests that a method, let call it <code>MethodA</code> call to <code>MethodB</code>.</p> <p>The simple class:</p> <pre><code>public class Foo { public virtual void MethodA() { MethodB(); } public virtual void MethodB() { } } </code></pre> <p>The simple test:</p> <pre><code>var foo_fake = A.Fake&lt;Foo&gt;(options =&gt; options.CallsBaseMethods()); foo_fake.MethodA(); A.CallTo(() =&gt; foo_fake.MethodA()).MustHaveHappened() .Then(A.CallTo(() =&gt; foo_fake.MethodB()).MustHaveHappened()); </code></pre> <p>With <em>FakeItEasy</em> <strong>2.2.0</strong>, the code passed.</p> <p>But when we upgrade to <strong>5.1.0</strong>, the code throw exception that says:</p> <blockquote> <p>The calls were found but not in the correct order among the calls</p> </blockquote> <p>When we say <strong>the method is called</strong>? At the start of execution, or at the end?</p> <p>Or, what is the right way to test this case?</p>
3
Is it possible to use wildcard with SOLR query field(qf) in WCS?
<p>We have multiple product catalogs with respective categories under each catalog, but same or a sub-set of products are included in all the catalogs. By default WCS/WebSphere Commerce applies 'defaultSearch' and 'categoryname' search scopes for IBM_findProductsBySearchTerm profile, causing it to return more and not relevant products for current keyword search. </p> <p>I could get rid of those items by removing defaultSearch and category name search types from OOB wc-search.xml profile(which would in turn remove those from qf field values during SOLR calls), but would like to know if it's possible to use a wildcard string in qf field something like 100002_* to restrict keyword search to current catalog categories only, and ignore other catalog(s) categories in search and relevancy ranking/scoring. </p> <p>We would still like SOLR to search current catalog categories, just not include other catalog categories that current customer is not entitled for.</p> <p>Thanks</p>
3
Why does the animation not work if I change pages?
<p>I have a Drupal 8 site with Bootstrap 3 theme.</p> <p>I created a homepage with a newsfeed. Whenever there is a publication on the site, it generates a message in the newsfeed. The messages can have the status read or unread.</p> <p>I want that when the <code>.action-flag</code> class is in the page, an animation is applied on the logo of the site.</p> <p>The CSS and JS file is included on all pages of the site.</p> <p>The <code>.action-flag</code> class is only on the home page, when a message is not marked as read.</p> <p>Here is the structure of my homepage :</p> <p><a href="https://i.stack.imgur.com/e9dgg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e9dgg.png" alt="enter image description here"></a></p> <p>Here is my JS code :</p> <pre><code> if ($("#pills-private .action-flag").length) { $(".region-navigation-logo img").addClass("timeline-notification"); }; </code></pre> <p>Here is my CSS code :</p> <pre><code>@keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(138, 186, 18, 1); } 70% { box-shadow: 0 0 0 10px rgba(138, 186, 18, 0); } 100% { box-shadow: 0 0 0 0 rgba(138, 186, 18, 0); } } .region-navigation-logo img { height: 56px; border-radius: 50%; background: #8aba12; } .timeline-notification { box-shadow: 0 0 0 rgba(138, 186, 18, 1); animation: pulse 2s infinite; } </code></pre> <p>Currently, the animation works very well. But only if I'm on the homepage. If I go to another page, the animation does not work anymore.</p> <p><strong>THE PROBLEM</strong></p> <p>It only works when I go to the homepage. I want it to work on the whole site. The goal is to notify the user that a new activity is available in their newsfeed.</p> <p>Is there a solution for this?</p>
3
JSP can not read CSS because of web.xml
<p>This is not a theory. I have proof. I've been on this problem for almost a day. My jsp seem to can't read/find CSS. I've done a lot of solutions but nothing work. Until I decide maybe one of my files is causing it. Then I do trial and error. Deleting file to see which one causes it.</p> <p>Until i'm in web.xml. I deleted web.xml, run the JSP and boom it read the CSS. I copy back the web.xml and then again my css can't be read. </p> <p>By the way i'm using spring mvc, and my project is maven web application.</p> <p>below are my codes:</p> <p>jsp(css link part):</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="../../css/logincss.css"&gt; </code></pre> <p>web.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"&gt; &lt;session-config&gt; &lt;session-timeout&gt; 30 &lt;/session-timeout&gt; &lt;/session-config&gt; &lt;servlet&gt; &lt;servlet-name&gt;DpServlet&lt;/servlet-name&gt; &lt;servlet-class&gt; org.springframework.web.servlet.DispatcherServlet &lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;DpServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt; </code></pre> <p>I think the error is that when i'm requesting a css file, the request goes to dispatcherservlet so that is so error. How can I fix my problem? Please I need solution i've been on this problem for over a DAY! Thanks in advance.</p>
3
Unable to connect to server: Host name may not be null
<p>I am taking the below wso2 course.</p> <p><a href="https://lms.wso2.com/courses/video-live-training-wso2-api-manager-developer-fundamentals-english" rel="nofollow noreferrer">Course Link</a></p> <p><strong>This is the video:</strong></p> <blockquote> <p>In Cloud Native API Management with WSO2 API Manager - an Overview Lab 4 - Using a microgateway (10min)</p> </blockquote> <p>As I used this command, the docker image is not created in the local properly.</p> <pre><code>micro-gw build Petstore --deployment-config E:\wso2-CertificatonPreparation\micorgateway-projects\Petstore\deployment.toml </code></pre> <p>I am getting the below error. Please help me to resolve this issue.</p> <p><code>Generating docker artifacts...</code></p> <p><code>error [docker plugin]: module [wso2/Petstore:3.1.0] unable to connect to server:Host name may not be null</code></p> <p>And also,</p> <p>What should I configure in <strong>target of deployment.toml</strong></p> <p>source =<code>E:/wso2-CertificatonPreparation/wso2-softwares/wso2am-micro-gw-toolkit-windows-3.1.0/resources/conf/micro-gw.conf</code></p> <p><strong>target = <code>/home/ballerina/conf/micro-gw.conf</code></strong></p> <p>I am using version 3.1.0</p> <p>This is the deployment.toml</p> <pre><code>[docker] [docker.dockerConfig] enable = true name = &quot; petstore &quot; registry = ' docker.wso2.com ' tag = ' v1 ' #buildImage = '' #dockerHost = '' #dockerCertPath = '' baseImage = 'wso2/wso2micro-gw:3.0.2' #enableDebug = '' #debugPort = '' #push = '' [docker.dockerCopyFiles] enable = true [[docker.dockerCopyFiles.files]] source ='E:/wso2-CertificatonPreparation/wso2-softwares/wso2am-micro-gw-toolkit-windows-3.1.0/resources/conf/micro-gw.conf' target = '/home/ballerina/conf/micro-gw.conf' isBallerinaConf = true </code></pre>
3
How do you add data of the similar name in parallel arrays
<p>Been trying to figure out how to make add the data of the same numbers only so that it produce and output like this </p> <p>Total Duration Calls from 555-555-5555: 555-555-5555 duration: 90s</p> <p>Calls from 555-555-1234: 555-555-1234 duration: 56s</p> <p>Calls from 555-555-9876: 555-555-9876 duration: 35s</p> <pre><code> public class Activity0D { public static void main(String[] args) { String[] phoneNumbers = new String[100]; int[] callDurations = new int[phoneNumbers.length]; int size = 0; size = addCall(phoneNumbers, callDurations, size, "555-555-5555", 40); size = addCall(phoneNumbers, callDurations, size, "555-555-5555", 20); size = addCall(phoneNumbers, callDurations, size, "555-555-5555", 30); size = addCall(phoneNumbers, callDurations, size, "555-555-1234", 26); size = addCall(phoneNumbers, callDurations, size, "555-555-1234", 30); size = addCall(phoneNumbers, callDurations, size, "555-555-9876", 35); System.out.println("Phone numbers (initially):"); printList(phoneNumbers, callDurations, size); System.out.println("\nTotal Duration"); System.out.println("\nEnd of processing."); } public static void findAllCalls(String[] phoneNumbers, int[] callDurations, int size, String targetNumber) { int matchPos; System.out.println("Calls from " + targetNumber + ":"); matchPos = find(phoneNumbers, size, 0, targetNumber); while (matchPos &gt;= 0) { System.out.println(phoneNumbers[matchPos] + " duration: " + callDurations[matchPos] + "s"); // Find the next match, starting after the last one matchPos = find(phoneNumbers, size, matchPos + 1, targetNumber); } } public static void totalDurations(String[] phoneNumbers, int[] callDurations, int size) { int totalDuration = 0; for (int i = 0; i &lt; size; i++) { if(find(phoneNumbers, size, 0, "555-555-5555") &gt;= 0) { //Add data the total duration for number "555-555-5555" } else if(find(phoneNumbers, size, 0, "555-555-1234") &gt;= 0) { //Add data the total duration for number "555-555-1234" } else if(find(phoneNumbers, size, 0, "555-555-9876") &gt;= 0) { //Add data the total duration for number "555-555-9876" } } } } </code></pre>
3
How do I use SELECT LAST_INSERT_ID() without closing the connection
<p>I have table whose only column is an auto-incrementing primary key. I want to insert a new row into this table, and then get the ID generated by this insert. </p> <p>Reading through StackOverflow, LAST_INSERT_ID() appears to be the standard solution. The caveat given is that it will return the last generated ID per connection. I wrote a new method to INSERT and then SELECT, all without closing the connection. Then I started getting "Operation not allowed after ResultSet closed" errors. Reading up on that in StackOverflow leads me to think I should not be preparing multiple statements on the same connection. </p> <p>How should I be implementing this insert and select model? Am I misunderstanding what counts as the database connection concerning LAST_INSERT_ID()?</p> <p>relevant excerpts:</p> <pre><code>public class ConceptPortal { public static ConceptID createNewConceptID() throws Exception { ConceptID returnConceptID = null; StringBuilder stmt = new StringBuilder("INSERT INTO " + MysqlDefs.CONCEPT_TABLE + " VALUES ()"); ArrayList&lt;Object&gt; parameters = new ArrayList&lt;Object&gt;(); StringBuilder stmt2 = new StringBuilder("SELECT LAST_INSERT_ID()"); ResultSet resultSet = MysqlPortal.specialExecuteStatement(stmt.toString(), parameters, stmt2.toString()); if (resultSet.next()) { returnConceptID = new ConceptID(resultSet.getLong(1)); resultSet.getStatement().close(); } else { throw new Exception("Wait a minute...I can't create new concepts?!!"); } return returnConceptID; } } public class MysqlPortal { private static ConnPool connPool = null; public static void init(String database, boolean startFromScratch) throws Exception { databaseName = database; connPool = new ConnPool(database); } /* * This one doesn't close right away, * so that we can run LAST_INSERT_ID() on it */ static ResultSet specialExecuteStatement(String sqlCommand, ArrayList&lt;Object&gt; parameters, String followUpSelect) throws Exception { ResultSet resultSet = null; if (parameters == null) { System.out.println(sqlCommand + " :: [null]"); } else { System.out.println(sqlCommand + " :: " + Arrays.deepToString(parameters.toArray()) ); } ConnectionImpl connInstance = connPool.aquire(); try { Connection myConn = connInstance.getConnection(); try (PreparedStatement pstmt = myConn.prepareStatement(sqlCommand)) { if (parameters != null) { int i = 1; for (Object parameter : parameters) { pstmt.setObject(i, parameter); i++; } } pstmt.execute(); } try (PreparedStatement pstmt2 = myConn.prepareStatement(followUpSelect)) { resultSet = pstmt2.executeQuery(); } connPool.release(connInstance); return resultSet; } catch (SQLException e) { System.out.println(sqlCommand); throw e; } } } </code></pre>
3
compiled kt files are composed by bytecodes?
<p>I am trying to understand if the compiled kotlin is a java bytecode file. In this example, I show the kt files and the class files, and there certain keywords that I don't know that existed in java. Eg, <code>open val</code>. </p> <p>Are the compiled kt files formed by bytecodes? Are the compiled kt files executed directly by the JVM?</p> <p>Greeting.kt</p> <pre><code>package org.jetbrains.kotlin.demo data class Greeting(val id: Long, val content: String) </code></pre> <p>GrettingController.kt</p> <pre><code>@RestController class GreetingController { val counter = AtomicLong() @GetMapping("/greeting") fun greeting(@RequestParam(value = "name", defaultValue = "World") name: String) = Greeting(counter.incrementAndGet(), "Hello, $name") } </code></pre> <p>Greeting.class</p> <pre><code>public final data class Greeting public constructor(id: kotlin.Long, content: kotlin.String) { public final val content: kotlin.String /* compiled code */ public final val id: kotlin.Long /* compiled code */ public final operator fun component1(): kotlin.Long { /* compiled code */ } public final operator fun component2(): kotlin.String { /* compiled code */ } } </code></pre> <p>GreetingController.class</p> <pre><code>@org.springframework.web.bind.annotation.RestController public open class GreetingController public constructor() { public open val counter: java.util.concurrent.atomic.AtomicLong /* compiled code */ @org.springframework.web.bind.annotation.GetMapping public open fun greeting(@org.springframework.web.bind.annotation.RequestParam name: kotlin.String): org.jetbrains.kotlin.demo.Greeting { /* compiled code */ } } </code></pre>
3
Firefox screen share MediaStreamTrack to Twilio
<p>I use Firefox v55.0.2</p> <p>In documentation (<a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getUserMedia" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getUserMedia</a>), after NavigatorUserMedia.getUserMedia() normally in successCallback i have a MediaStream but in my case i have LocalMediaStream.</p> <p>I need to have MediaStreamTrack to give it at twilio.</p> <p>This is my code :</p> <pre><code>$scope.testShareFirefox = function () { var p = navigator.mediaDevices.getUserMedia({ video: { mediaSource: 'screen', width: 640, height: 480 }, }) .then(function(stream) { const screenLocalTrack = new twilio.Video.LocalVideoTrack(stream); $scope.videoConf.room.localParticipant.addTrack(screenLocalTrack); var video = document.createElement('video'); $('#test-share-screen').append(video); video.srcObject = stream; video.play(); }) .catch(function (err) { console.log(err); }); }; </code></pre> <p>Thank you.</p>
3
How to validate non breaking space in CKEditor
<p>Well i have the <a href="/questions/tagged/ckeditor" class="post-tag" title="show questions tagged &#39;ckeditor&#39;" rel="tag">ckeditor</a> in my page when the user keep entering spaces only, then the empty validation meant that it is not empty because it contains the <code>&amp;nbsp;</code> inside the <code>&lt;p&gt;&lt;/p&gt;</code> so the editor content is not empty but when we see that content in html it will display nothing because its non breaking spaces. </p> <p>Now issue is that how validate that inside the editor no one can put like spaces like that.</p>
3
Operator '==' cannot be applied to operands of type 'Thickness' and 'string'
<p>I am using timer for made animation and when it margins come to the value, I want should stop. "Bir" is my shape and "ZamanSayacıA" is my timer.</p> <pre><code>if (Bir.Margin == "510, 410, 0, 0") { ZamanSayacıA.Stop(); } </code></pre> <p>And gives the following error.</p> <blockquote> <p>Operator '==' cannot be applied to operands of type 'Thickness' and 'string'</p> </blockquote>
3
use c++ method in c program
<p>I want to use C++ library gloox in my C code (easycwmp package for openwrt).</p> <p>I compile with openwrt toolschain the gloox as package: </p> <p>here is the cpp file gloox.cpp :</p> <pre><code>#include "gloox.h" namespace gloox { const std::string XMPP_STREAM_VERSION_MAJOR = "1"; const std::string XMPP_STREAM_VERSION_MINOR = "0"; const std::string GLOOX_VERSION = "1.0.11"; const std::string GLOOX_CAPS_NODE = "http://camaya.net/gloox"; } extern "C" const char* gloox_version() { return gloox::GLOOX_VERSION.c_str(); } </code></pre> <p>the header file gloox.h : </p> <pre><code>#ifndef GLOOX_H__ #define GLOOX_H__ #include "macros.h" extern "C" //--&gt; error: expected identifier or '(' before string constant { GLOOX_API const char* gloox_version(); } #endif // GLOOX_H__ </code></pre> <p>the compilation of gloox package is OK when I include gloox.h in my C code of easycwmp package I get this error :</p> <p>staging_dir/target-i386_uClibc-0.9.33.2/usr/include/gloox.h:12:8: error: expected identifier or '(' before string constant !!</p> <p>I compile libgloox with command :</p> <pre><code>make package/libgloox/compile </code></pre> <p>and then I compile easycwmp package with cmd :</p> <pre><code>make package/easycwmp/compile </code></pre> <p>Any help is appreciated </p>
3
Comparing 4 column values to make a new column
<p>I'd like to hold the non NA values in a row, then pick the first element in the list as the final value for a new column (ncol). </p> <p>Here's an example of what I'm trying to get and the code I've unable to get to run...</p> <pre><code>ID &lt;- c(1,2,3,4) A &lt;- c("A", "NA", "C", "R") B &lt;- c("G", "V", "NA", "T") C &lt;- c("NA", "NA", "NA", "Y") D &lt;- c("U", "W", "NA", "NA") mydf &lt;- data.frame(ID, A, B, C, D, ncol) ID A B C D ncol 1 1 A G NA U A 2 2 NA V NA W V 3 3 C NA NA NA C 4 4 R T Y NA R mycol &lt;- c(mydf$A, mydf$B, mydf$C, mydf$D) for (i in seq(1:nrow(mydf))){ listcolincldata &lt;- lapply(mycol[i],[!is.na(mycols[i])]) print(listcolincldata) mydf$newcol[i] &lt;- (as.character(listcolincldata[1])) } </code></pre>
3
how can i use pointer to move inside of this array (function) instead of array subscribting
<p>my question is at the generate acronym function, how can i make this function work in a pointer arithmetic way instead of array subscripting. without messing up with the structures itself, the prof prhobited array subscribting so i have to do it with pointer arithmetic instead, anyone can land a hand?</p> <pre><code>#define _CRT_SECURE_NO_WARNINGS #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;ctype.h&gt; #define B 2 #define N 8 typedef struct { int course_id; int course_quota; char course_name[50]; char course_code[6]; char course_acronym[N]; }course_t; void generate_course_code(char *course_code, int course_id); void generate_course_acronym(char *, char *); void display(); course_t courses[B]; int main() { int i; for(i = 0; i &lt; B; i++) { printf("Enter the course name: "); fgets(courses[i].course_name, sizeof(courses[i].course_name), stdin); generate_course_acronym(courses[i].course_name, courses[i].course_acronym); printf("Enter the course Quota: "); scanf("%d", &amp;courses[i].course_quota); while ('\n' != getchar()) { } courses[i].course_id = i; generate_course_code(courses[i].course_code, courses[i].course_id); } display(); return 0; } void generate_course_code(char *course_code, int course_id) { char str[6]; course_id++; strcpy(course_code, "CSE"); if (course_id &lt; 10) { sprintf(str, "0%d", course_id); } else sprintf(str, "%d", course_id); strcat(course_code, str); } void generate_course_acronym(char *course_name, char *course_acronym) { int j = 0; char *p = course_name; for (course_acronym[j++] = toupper(*p); *p != '\0'; p++) if (*p == ' ') course_acronym[j++] = toupper(*(++p)); course_acronym[j] = '\0'; } void display() { int x; for (x = 0; x &lt; B; x++) { printf("%d. %s - %s (%s) - %d \n", ++courses[x].course_id, courses[x].course_code, courses[x].course_name, courses[x].course_acronym, courses[x].course_quota); } } </code></pre>
3
PresentViewController with Tabbar and Navigationbar iOS
<p>I am presenting a view controller class using custom navigation bar as follow: </p> <pre><code>CreateShiftRosterEventViewController *objDetailView = [[CreateShiftRosterEventViewController alloc] initWithNibName:@"CreateShiftRosterEventViewController" bundle:nil]; CustomNavigationViewController *navcont = [[CustomNavigationViewController alloc] initWithRootViewController:objDetailView]; // Set the user default to 1 to support landscape orientation also for next view [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"orientationView"]; [self presentViewController:navcont animated:YES completion:nil]; [objDetailView release];objDetailView = nil; [navcont release];navcont=nil; </code></pre> <p>but it hides tab bar at CreateShiftRosterEventViewController class. </p> <p>Can anyone please help me, what is wrong?</p>
3
ResourceNotFoundException ListViewAdapter
<p>I made a constructor <code>DataPembeli</code>for list view item then make the custom List View Adapter <code>DataPembeliListAdapter</code> and used the constructor like this:</p> <pre><code>txtid.setText(dataPembeliItems.get(position).getId()); // THIS IS THE ERROR LINE txtket1.setText(dataPembeliItems.get(position).getNama()); txtket2.setText(dataPembeliItems.get(position).getAlamat()); txtket3.setText(dataPembeliItems.get(position).getNohp()); </code></pre> <p>In the <code>DataPembeliFragment</code> class I've used it like this:</p> <pre><code>public class DataPembeliFragment extends Fragment { private ListView listPembeli; private ImageButton btnTambah; // slide data items private int[] idDataPembeli; private String[] namaDataPembeli, alamatDataPembeli, noHpDataPembeli; private ArrayList&lt;DataPembeli&gt; dataPembeliItems; private DataPembeliListAdapter adapter; public DataPembeliFragment(){} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_data_pembeli, container, false); listPembeli = (ListView) rootView.findViewById(R.id.list_sliderdata); btnTambah = (ImageButton) rootView.findViewById(R.id.btnTambah); btnTambah.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { showEditDialog(); } }); dataPembeliItems = new ArrayList&lt;DataPembeli&gt;(); idDataPembeli = new int[10]; namaDataPembeli = new String[10]; alamatDataPembeli = new String[10]; noHpDataPembeli = new String[10]; idDataPembeli[0] = 1; namaDataPembeli[0] = "ryno"; alamatDataPembeli[0]= "padang"; noHpDataPembeli[0] = "0812874512"; dataPembeliItems.add(new DataPembeli(idDataPembeli[0], namaDataPembeli[0], alamatDataPembeli[0], noHpDataPembeli[0])); idDataPembeli[1] = 2; namaDataPembeli[1] = "yezu"; alamatDataPembeli[1]= "padang"; noHpDataPembeli[1] = "0819232211"; dataPembeliItems.add(new DataPembeli(idDataPembeli[1], namaDataPembeli[1], alamatDataPembeli[1], noHpDataPembeli[1])); idDataPembeli[2] = 3; namaDataPembeli[2] = "test"; alamatDataPembeli[2]= "padangs"; noHpDataPembeli[2] = "0819232xx"; dataPembeliItems.add(new DataPembeli(idDataPembeli[2], namaDataPembeli[2], alamatDataPembeli[2], noHpDataPembeli[2])); listPembeli.setOnItemClickListener(new SlideMenuClickListener()); adapter = new DataPembeliListAdapter(getActivity().getApplicationContext(),dataPembeliItems); listPembeli.setAdapter(adapter); return rootView; } </code></pre> <p>}</p> <p>When I call the Fragment I got <code>ResourceNotFoundException</code> in the logcat at DataPembeliAdapter on the line that I marked above.(at comment "//THIS IS THE ERROR LINE")</p>
3
Posting custom JSON from a text box in ASP.NET
<p>I have a simple web form in ASP.NET. Custom JSON is entered into the form and then posted to the server. In reverse whatever is associated with the parent data object (which the json is attached to) is present in the text box when the page loaded. </p> <p>While the initial set of JSON displays fine, posting the form back causes a validation error and the request to fail. The requirements I have right now are to be able to enter in custom json data. The data could be complex (trees of objects). What would be the best approach to retaining security and validation on the form but allowing for the custom json?</p>
3
How can I exclude certain folders from being indexed by search engines in ASP.net when SSL is forced?
<p>Good day,</p> <p>I've done some research looking for this answer, but haven't had much luck. Hoping someone can help..</p> <p>The situation is that a site I'm working on (built in ASP.net) which forces SSL on most of their pages has some folders (ie. <code>site.com/dontindex</code> )containing files that definitely shouldn't be indexed by search engines. Google has links to these files in its index (ie. <code>https://www.site.com/dontindex/file.pdf</code>). </p> <p>My issue is that I have created a robots.txt file to disallow those folders from indexing, but from what I've read, that isn't going to prevent those files being indexed - as some of them might be referenced through secure pages. I'm thinking that only the non-secure pages are disallowed in this way. <strong>Q1) Is that even correct?</strong> </p> <p>When I tested <code>http://www.site.com/dontindex/file.pdf</code> against the new robots file in Google Webmaster Tools, wit came back as "Blocked by line 5: Disallow: /dontindex/", but when I tried <code>https://www.site.com/dontindex/file.pdf</code> it came back as "Not in domain".</p> <p>From what I can gather, I should have a second robots.txt file somewhere for the secure files/folders. I've read that if the site were running php, I could do some sort of a rewrite rule to cover this, but what to do in my ASP.net situation?? <strong>Q2) If it applies to me to have a second robots file (given that it's an ASP.net site), where should I put this file?</strong></p> <p>Thank-you for any help!</p>
3
How can we create a common component that can be used across the pages for drupal-8 structure for a multipage website?
<p>If a multi-page website has different styling on different pages, how can we create a common component that can be used across the pages for drupal structure. As, when we select a component to be inserted in a page, it comes with its own classes. To manage those classes, we need to create separate CSS file for each page. Can't we have a common component which can be used across the website.</p>
3
How to read MMA8542q Accelerometer sensor in Matlab using Raspberry
<p>I need help please, I try to read the position [x,y,z ] in matlab, here is my code, </p> <p>enter code here</p> <pre><code>mypi = raspi; scanI2CBus(mypi,'i2c-1'); myi2c = i2cdev(mypi,'i2c-1','0x1D'); output-1 = read(myi2c, 8) </code></pre> <p>In my code I have this output</p> <pre><code>enter code here 0 13 248 84 252 254 64 0 </code></pre> <p><strong>My problem here</strong> is all values will be the same even if I change the position of the sensor.(All time the same values). <strong>How I can get the position [x,y,z],my sensor is MMA8542q.</strong></p> <p>Thank you! </p>
3
_BLOCK_TYPE_IS_VALID error on boost::scoped_array
<p>After a huge amount of digging and searching I found the root of my problem. In essence this code is executed and, in its own project it causes the same error. I see that I cannot reset a smart pointer to a new string...but why? Also is there a simple way around this?</p> <pre><code>scoped_array&lt;char&gt; sptr; char* nptr = "Hello"; sptr.reset(""); sptr.reset(nptr); </code></pre> <p>EDIT -</p> <p>I think I've figured it out. While resetting, the smart pointer tries to delete and empty character array ("") which, because the new operator was not used, was not allocated on the heap (ahem !!?!!?!???!?!). Therefore this program will break miserably when it tries to deallocate the memory. So correct me if I'm wrong but would the string itself be stored in the program's executable byte stream itself? If so, just for future reference, is there a way to force the allocation of a new string?</p>
3
Adding a Trailing Twelve Months array feature to VBA code
<p>I have an existing code which is a function that yields an array: Example input: <code>=cellrange(B5,"ytd")</code> [where from <code>B5</code> and below (or above) there are dates] Example output: <code>$B$129:$B$280</code> which is the full date range for this year in column <code>B</code></p> <p>I am trying to add a new <code>case</code> called <code>ttm</code> (trailing twelve months), however I am struggling to find a way to incorporate it.</p> <p>The <code>ttm</code> case should show yield a trailing 12 months range from the latest available date</p> <pre><code>Option Explicit Public Function cellrange(rDates As Range, vFilter As Variant, Optional colOffsetA As Variant, Optional colOffsetB As Variant) As String 'DESCRIPTION: 'This function takes any cell value in a row and a input: YTD, ALL, or any year (i.e. 2014, 2015) and it finds the range in which the date is situated Dim i As Long, ndx1 As Long, ndx2 As Long, r As Range, vA As Variant, bErr As Boolean, bAll As Boolean bErr = True If IsDate(rDates) Then With rDates.EntireColumn i = rDates.Parent.Evaluate("count(" &amp; .Address &amp; ")") Set r = .Cells(1 - i + rDates.Parent.Evaluate("index(" &amp; .Address &amp; ",match(9.9E+307," &amp; .Address &amp; "))").row).Resize(i, 1) End With vA = r.Value If IsMissing(colOffsetA) And IsMissing(colOffsetB) Then colOffsetA = 0: colOffsetB = 0 End If If IsMissing(colOffsetB) = True Then colOffsetB = colOffsetA Select Case LCase(vFilter) Case "all" bErr = 0: bAll = 1 Set r = r.Range(r.Parent.Cells(1, 1 + colOffsetA), r.Parent.Cells(r.Count, 1 + colOffsetB)) Case "ytd" For i = 1 To UBound(vA) If ndx1 = 0 And Year(vA(i, 1)) = Year(Date) Then ndx1 = i If vA(i, 1) &lt;= Date Then ndx2 = i Next Case Else 'year vFilter = Val(vFilter) If vFilter Then For i = 1 To UBound(vA) If ndx1 = 0 And Year(vA(i, 1)) = vFilter Then ndx1 = i If ndx1 And Year(vA(i, 1)) = vFilter Then ndx2 = i Next End If End Select If Not bAll Then If ndx1 &gt; 0 And ndx2 &gt; 0 Then Set r = r.Range(r.Parent.Cells(ndx1, 1 + colOffsetA), r.Parent.Cells(ndx2, 1 + colOffsetB)): bErr = False If Not bErr Then cellrange = r.Address Else cellrange = CVErr(xlErrValue) Else cellrange = CVErr(xlErrValue) 'check if this is the correct error handling End If End Function </code></pre>
3
Raise event whenever object property is added in Javascript?
<p>I have a Javascript object : </p> <p><code>var obj={...};</code></p> <ul> <li><p>How can I execute a function whenever a new property is added/changed : </p> <p>For example:<code>obj["newItem"]=3;</code></p></li> <li><p>is there any way also for arrays ? (excpet override <code>push</code> in prototype)</p></li> <li><p>is there any way to do it also for assign a different object to the same variable ?</p> <p>example : </p> <pre><code>var obj={...}; obj={...}; //redifine </code></pre></li> </ul>
3
Category filter IN and IN for ecommerce
<p>I am writing an ecommerce script but have stumbled upon a problem: MySQL can't use <code>WHERE cat_id = 'software' AND attr_id IN (1,2) AND attr_id IN (3,4)</code> as it consider ambiguous.</p> <p>So, to explain the DB logic it is like this :</p> <p><code>attrTitle</code> is the title of the <code>attr</code>. Example: "<em>Operating System</em>", "<em>License Type</em>"</p> <p><code>attr</code> holds the attribute related to the <code>attrTitle</code>. Each <code>product</code> can have multiple <code>attr</code> and every <code>attr</code> is linked by an FK to an <code>attrTitle</code>. Example of <code>attr</code> : "<em>Windows</em>", "<em>Linux</em>", "<em>Freeware</em>"</p> <p><code>product</code> is... well... products. Example: "<em>Microsoft Office</em>"</p> <p>and <code>category</code> are categories... Each <code>product</code> is linked to only one category... Example: "<em>Office Suites</em>"</p> <p>So, i want the user to be able to filter the products in the "<em>Office Suites</em>" category. For that, he have a menu saying: </p> <pre><code>[FILTERS] *Operating System - Windows - Linux - Mac *Language - English - Español </code></pre> <p>So, suppose an user is looking for an Office suite that works in Windows <em>AND</em> is in English or Español.</p> <p>The query became something like this :</p> <pre><code>SELECT * FROM prd_product p0_ INNER JOIN cat_category c2_ ON p0_.cat_id = c2_.cat_id LEFT JOIN prd_attr p4_ ON p0_.prd_id = p4_.prd_id LEFT JOIN attr_attributeValue e3_ ON e3_.attr_id = p4_.attr_id WHERE c2_.cat_friendlyUrl = 'software' AND e3_.attr_id IN (4) AND e3_.attr_id IN (10,11) GROUP BY p0_.prd_id </code></pre> <p>But, as i said, it becomes ambiguous for MySQL as the espval_id is getting an WHERE IN clause two times, and then it returns an empty result. Could anyone give me a tip on how to solve this ?</p> <p>And yes, i tested and there is a product with attr 4 and attr 10</p> <p><strong>EDIT:</strong> Sql Fiddle : <a href="http://sqlfiddle.com/#!2/be3198/1" rel="nofollow">http://sqlfiddle.com/#!2/be3198/1</a></p>
3
Is there any Python library that separates an URL into scheme, subdomain and domain?
<p><a href="https://docs.python.org/" rel="nofollow noreferrer">https://docs.python.org/</a> should be separated into: <code>https://</code> and <code>docs</code> and <code>python.org</code></p> <p>Other examples can be: <a href="https://shoes.store.com" rel="nofollow noreferrer">https://shoes.store.com</a></p> <p>so regardless of the domain it separates. I've tried with urlparse but it didn't help</p>
3
Warning when running cluster_edge_betweenness in R
<p>I was trying to do community structure detection based on edge betweenness with igraph package in R. When the edges were weighted, some warning showed up:</p> <p>Warning messages:</p> <pre><code>1: In cluster_edge_betweenness(g) : At community.c:460 :Membership vector will be selected based on the lowest modularity score. 2: In cluster_edge_betweenness(g) : At community.c:467 :Modularity calculation with weighted edge betweenness community detection might not make sense -- modularity treats edge weights as similarities while edge betwenness treats them as distances </code></pre> <p>When the edges were not weighted, it worked properly without any warning.</p> <p>Here's the code for generating the warnings:</p> <pre><code>library(igraph) g &lt;- make_full_graph(10) %du% make_full_graph(10) g &lt;- add_edges(g, c(1,11)) E(g)$weight &lt;- seq(1,91) eb &lt;- cluster_edge_betweenness(g) </code></pre> <p>I wonder what do the warning messages mean. And should I be concerned?</p> <pre><code>Session info: R version 3.6.3 (2020-02-29) Platform: x86_64-apple-darwin15.6.0 (64-bit) Running under: macOS Catalina 10.15.6 Matrix products: default BLAS: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRblas.0.dylib LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib Random number generation: RNG: Mersenne-Twister Normal: Inversion Sample: Rounding locale: [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] igraph_1.2.6 loaded via a namespace (and not attached): [1] compiler_3.6.3 magrittr_1.5 tools_3.6.3 pkgconfig_2.0.3 </code></pre>
3
Cannot delete assembly after Load(byte[])
<p>I'm trying to delete assembly after loading, but cannot. Please help me. Thanks.</p> <pre><code>private Assembly AssemblyResolve(object sender, ResolveEventArgs args) { try { AssemblyName assemblyName = new AssemblyName(args.Name); string folderBeyConsPath = FindInstallBeyConsFolderPath(FolderBeyConsPathKey); if (string.IsNullOrEmpty(folderBeyConsPath) || !Directory.Exists(folderBeyConsPath)) return null; string file = Directory.GetFiles(folderBeyConsPath, &quot;*.dll&quot;).Where(x =&gt; Path.GetFileNameWithoutExtension(x) == assemblyName.Name).FirstOrDefault(); if (!string.IsNullOrEmpty(file)) { byte[] content = File.ReadAllBytes(file); return Assembly.Load(content); } } catch { } return null; } </code></pre>
3
How to call a function after subscribe is completed
<p>I have this service call where im subscribing to an Observable and assigning the response to a property. My purpose is to call another function thats gonna use this property after the service call is completed. Whats the best way to do this?</p> <pre><code>export class MapComponent implements AfterViewInit, OnInit { @ViewChild(&quot;mapContainer&quot;, { static: false }) gmap: ElementRef; map: google.maps.Map; markers = []; constructor(private userService : UserService) {} ngOnInit() { console.log(&quot;Point 1 ##################&quot;); this.userService.getUserMarkers().subscribe(markers =&gt; { this.markers = markers; console.log(&quot;Point 2 ##################&quot;); }); } ngAfterViewInit(): void { console.log(&quot;Point 3 ##################&quot;); this.mapInitializer(); } mapInitializer(): void { console.log(&quot;Point 4 ##################&quot;); // function where to use the markers } </code></pre> <p>Now the sequence that happens is, Point 1 -&gt; Point 3 -&gt; Point 4 -&gt; Point 2</p> <p>Whats the best way to make it Point 1 -&gt; Point 2 -&gt; Point 3 -&gt; Point 4</p>
3
In CSS Grid how to remove column 1's matching height of column 2?
<p>Not familiar with CSS Grid I'm trying to create a two column layout. Per reading tutorials it was suggested to use <code>minmax()</code> but for some reason I cannot figure out how to break column 1's full height that matches column 2, example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { display: grid; grid-template-columns: minmax(0, 1fr) 300px; column-gap:32px; } .col1 { background:red; padding:32px; } .col2 { background:orange; padding:32px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="col1"&gt;Bacon ipsum dolor amet boudin andouille pig beef, prosciutto tongue ball tip cow ham. Ground round salami tenderloin, biltong tail pastrami pork shoulder pork loin. Picanha cow ribeye meatloaf tri-tip pork chop burgdoggen salami beef chuck alcatra swine ground round. Tail doner tri-tip flank brisket prosciutto chislic capicola meatloaf picanha swine. Shankle capicola venison beef boudin, strip steak alcatra bacon sirloin cupim spare ribs short ribs kielbasa pork loin ground round. Leberkas short loin boudin meatloaf.&lt;/div&gt; &lt;div class="col2"&gt;Kielbasa pastrami tenderloin, turkey short loin pork loin swine fatback flank leberkas prosciutto hamburger t-bone drumstick. Jowl picanha ham, t-bone filet mignon short ribs turducken leberkas. Turducken ham hock alcatra, shoulder tail sirloin strip steak hamburger picanha jerky tenderloin spare ribs tri-tip. Tenderloin prosciutto picanha, capicola kevin pig biltong t-bone pork chop boudin porchetta bacon salami chicken fatback. Ham hock pancetta tail tenderloin jerky ground round chislic frankfurter shank picanha pork belly strip steak pork chop. Short loin andouille biltong corned beef pig pork chop pork bacon tri-tip jerky. Filet mignon meatloaf drumstick hamburger ham hock landjaeger tri-tip ribeye swine. Ham shankle tongue, kielbasa swine burgdoggen tenderloin beef ribs buffalo meatball hamburger leberkas picanha t-bone. Beef ribs ball tip ham pork loin capicola filet mignon. Hamburger sausage shoulder meatball pork chop tail spare ribs, fatback burgdoggen drumstick short loin swine pork loin. Kielbasa boudin cow beef beef ribs tongue pork chop frankfurter sausage burgdoggen. Flank landjaeger leberkas spare ribs alcatra, swine corned beef boudin shoulder pig prosciutto pancetta pork chop. Pork chop turducken andouille filet mignon alcatra porchetta cupim tri-tip cow tongue beef meatball doner. Beef ribs ham hock chuck shank doner. &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>after research and reading &quot;<a href="https://alligator.io/css/css-grid-layout-minmax-function/" rel="nofollow noreferrer">CSS Grid Layout: The Minmax Function</a>&quot; I tried:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { display: grid; grid-template-columns: minmax(min-content, max-content) 300px; column-gap:32px; } .col1 { background:red; padding:32px; } .col2 { background:orange; padding:32px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="col1"&gt;Bacon ipsum dolor amet boudin andouille pig beef, prosciutto tongue ball tip cow ham. Ground round salami tenderloin, biltong tail pastrami pork shoulder pork loin. Picanha cow ribeye meatloaf tri-tip pork chop burgdoggen salami beef chuck alcatra swine ground round. Tail doner tri-tip flank brisket prosciutto chislic capicola meatloaf picanha swine. Shankle capicola venison beef boudin, strip steak alcatra bacon sirloin cupim spare ribs short ribs kielbasa pork loin ground round. Leberkas short loin boudin meatloaf.&lt;/div&gt; &lt;div class="col2"&gt;Kielbasa pastrami tenderloin, turkey short loin pork loin swine fatback flank leberkas prosciutto hamburger t-bone drumstick. Jowl picanha ham, t-bone filet mignon short ribs turducken leberkas. Turducken ham hock alcatra, shoulder tail sirloin strip steak hamburger picanha jerky tenderloin spare ribs tri-tip. Tenderloin prosciutto picanha, capicola kevin pig biltong t-bone pork chop boudin porchetta bacon salami chicken fatback. Ham hock pancetta tail tenderloin jerky ground round chislic frankfurter shank picanha pork belly strip steak pork chop. Short loin andouille biltong corned beef pig pork chop pork bacon tri-tip jerky. Filet mignon meatloaf drumstick hamburger ham hock landjaeger tri-tip ribeye swine. Ham shankle tongue, kielbasa swine burgdoggen tenderloin beef ribs buffalo meatball hamburger leberkas picanha t-bone. Beef ribs ball tip ham pork loin capicola filet mignon. Hamburger sausage shoulder meatball pork chop tail spare ribs, fatback burgdoggen drumstick short loin swine pork loin. Kielbasa boudin cow beef beef ribs tongue pork chop frankfurter sausage burgdoggen. Flank landjaeger leberkas spare ribs alcatra, swine corned beef boudin shoulder pig prosciutto pancetta pork chop. Pork chop turducken andouille filet mignon alcatra porchetta cupim tri-tip cow tongue beef meatball doner. Beef ribs ham hock chuck shank doner. &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>So far I'm not finding a resolution in my search query or after reading:</p> <ul> <li><a href="https://stackoverflow.com/questions/49636862/remove-wide-gaps-in-css-grid">Remove wide gaps in CSS Grid</a></li> <li><a href="https://stackoverflow.com/questions/55434774/is-it-possible-to-remove-the-height-from-empty-rows-in-grid-with-grid-template">Is it possible to remove the height from empty rows in grid with <code>grid-template-areas</code>?</a></li> <li><a href="https://stackoverflow.com/questions/61471820/why-cant-i-remove-all-the-deadspace-from-css-grid-layout">Why can't I remove all the deadspace from CSS Grid Layout?</a></li> <li><a href="https://stackoverflow.com/questions/54754492/how-to-hide-overflow-part-of-column-in-css-grid-layout-with-specified-row-height">How to hide overflow part of column in css grid layout with specified row height?</a></li> <li><a href="https://stackoverflow.com/questions/51616903/css-grid-white-space-on-the-bottom-and-how-to-remove-it">CSS Grid - White space on the bottom and how to remove it</a></li> <li><a href="https://stackoverflow.com/questions/51962136/why-is-my-grid-elements-height-not-being-calculated-correctly">Why is my Grid element's height not being calculated correctly?</a></li> </ul> <p>With CSS Grid how can I remove column 1's matching height of column 2?</p>
3
How to check whether a class has a String defined by a public String field with an unknown name outside the class?
<p>Assume there is a class:</p> <pre class="lang-java prettyprint-override"><code>public static final class A { public static final String s1 = &quot;String 1&quot;; public static final String s_random = &quot;Another random String&quot;; public A() {throw new SomeException(&quot;NOT TO BE CREATED! For Value Access only!&quot;);} } </code></pre> <p>Then I want to check whether this class has &quot;Another random String&quot; defined inside the class. It can be a method like (it could be in the other form):</p> <pre class="lang-java prettyprint-override"><code>public boolean check(String s, Class className) { // Something } </code></pre> <p>How can I achieve that? Given that all the names of the String fields in that class are <strong>unknown</strong>.</p>
3
I'm creating a locat TS Library for our project, but the TSDoc isn't displayed in the IDE
<p>I'm writing a small TypeScript library to be used by multiple sub-systems.</p> <p>In a different project I linked to the library using npm, but WebStorm only displays the TSDoc for methods, not for classes.</p> <p>package.json:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;name&quot;: &quot;shared-utilities&quot;, &quot;version&quot;: &quot;1.0.0&quot;, &quot;description&quot;: &quot;A package description...&quot;, &quot;main&quot;: &quot;src/index.ts&quot;, &quot;license&quot;: &quot;ISC&quot;, &quot;scripts&quot;: { &quot;prepare&quot;: &quot;npm run build&quot;, &quot;build&quot;: &quot;tsc&quot; }, &quot;devDependencies&quot;: { &quot;typescript&quot;: &quot;^4.5.4&quot; }, &quot;files&quot;: [ &quot;./dist&quot; ] } </code></pre> <p>tsconfig:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;compilerOptions&quot;: { &quot;module&quot;: &quot;commonjs&quot;, &quot;target&quot;: &quot;es2015&quot;, &quot;declaration&quot;: true, &quot;outDir&quot;: &quot;./dist&quot; }, &quot;include&quot;: [ &quot;src/**/*&quot; ] } </code></pre> <p>The TSDoc of a class is not displayed:</p> <p><a href="https://i.stack.imgur.com/IPvyj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IPvyj.png" alt="Class TsDoc" /></a></p> <p>While the TsDoc of a method is displayed:</p> <p><a href="https://i.stack.imgur.com/Nh0cT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nh0cT.png" alt="Method TsDoc" /></a></p> <p>Additionally, WebStorm doesn't import classes automatically when using them, like it does with other libraries. I would have to import it manually.</p> <p>Any ideas on what I might be doing wrong?</p>
3
Fail to load ApplicationContext SpringBoot with SpringSecurity and JUnit Jupiter
<p>I'm working on a REST API using Spring Boot. Currently, the V1 of the API is complete. So, I'm implementing Spring Security to manage authentication and authorization.<br /> Since I've implemented Spring Security, my JUnit Jupiter tests does not work (no one works).</p> <p>I searched a lot a solution on internet, but all answers I found are for JUnit4 and not JUnit5 (so I don't have all required classes).<br /> I got the classical &quot;Fail to load ApplicationContext&quot; error, but I don't know how to solve it.</p> <p>Can you help me?</p> <p>Here is my code for one class (UserController):</p> <p>gradle.build:</p> <pre><code>plugins { id 'jacoco' id 'org.springframework.boot' version '2.6.0' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java' } group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '11' configurations { compileOnly { extendsFrom annotationProcessor } } repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-web:2.5.6' implementation 'org.springframework.boot:spring-boot-starter-data-jpa:2.5.6' implementation 'org.projectlombok:lombok:1.18.22' annotationProcessor 'org.projectlombok:lombok:1.18.22' developmentOnly 'org.springframework.boot:spring-boot-devtools:2.5.6' testImplementation 'org.springframework.boot:spring-boot-starter-test:2.5.6' implementation 'com.h2database:h2' runtimeOnly 'com.h2database:h2' } test { systemProperty 'spring.profiles.active', 'test' useJUnitPlatform() finalizedBy jacocoTestReport } </code></pre> <p>Application:</p> <pre class="lang-java prettyprint-override"><code>@SpringBootApplication public class BackendApplication { public static void main(String[] args) { SpringApplication.run(BackendApplication.class, args); } } </code></pre> <p>UserController sample:</p> <pre class="lang-java prettyprint-override"><code>@RestController @RequestMapping(&quot;/api/v1/users&quot;) public class UserController extends AbstractCrudController&lt;User, Long&gt; { @Autowired public UserController(CrudService&lt;User, Long&gt; service) { super(service); } @GetMapping(&quot;&quot;) @Override @Secured({ &quot;ROLE_XXXXX&quot; }) public ResponseEntity&lt;ResponseListDto&lt;User, Long&gt;&gt; findAll() { return super.findAll(); } // ... } </code></pre> <p>MockedUserControllerTest sample:</p> <pre class="lang-java prettyprint-override"><code>@SpringBootTest public class MockedUserControllerTest { @Mock private UserService service; @InjectMocks private UserController controller; private static User user; private static List&lt;User&gt; users; @BeforeAll public static void beforeAll() { user = new User(); user.setId(1L); user.setUsername(&quot;A user name&quot;); user.setFirstname(&quot;First-Name&quot;); user.setLastname(&quot;Last-Name&quot;); user.setPassword(&quot;A Gre4t P4ssw0rd!&quot;); user.setMail(&quot;[email protected]&quot;); user.setBirthDate(Date.valueOf(&quot;1980-01-15&quot;)); user.setKey(&quot;A-key&quot;); user.setNewsletter(Boolean.TRUE); users = List.of(user); } @Test public void testFindAll() { when(service.findAll()).thenReturn(users); assertEquals(new ResponseEntity&lt;&gt;(new ResponseListDto&lt;&gt;(users, null, null), HttpStatus.OK), controller.findAll()); } //... } </code></pre> <p>Thank you in advance for looking my problem.</p>
3
LinkageError when trying to run Java-project in jdk 18.0.1.1
<p>I have launched a project which was currently running in <code>jdk 17.0.3</code>, in the new <code>jdk 18.0.1.1</code> and got the following error:</p> <pre><code>Fehler: Beim Laden der Klasse launching.Main ist ein LinkageError aufgetreten java.lang.UnsupportedClassVersionError: launching/Main (class file version 61.65535) was compiled with preview features that are unsupported. This version of the Java Runtime only recognizes preview features for class file version 62.65535 </code></pre> <p>I have tried cleaning and rebuilding, and the preview features are also enabled for the new version. (Both in the vm args and the .settings-file). Playing around with the jre-settings hasn't helped, and I'm afraid to break something.</p>
3
Merge CSV files in subfolders
<p>I have found a script which does everything that I need, but it's only useful if you run it in a single folder. What I'd like is:</p> <p>Script is located in c:/temp/. Upon running the script, it would go into each subfolder and execute. Each subfolder would then have a separate Final.csv.</p> <p>Somebody mentioned just add -Recurse, but it doesn't complete the job as described. With -Recurse added, it goes into each subfolder and creates a Final.csv final in the root dir (C:/temp/) instead of creating a Final.csv in each subfolder.</p> <pre><code>$getFirstLine = $true get-childItem *.csv | foreach { $filePath = $_ $lines = Get-Content $filePath $linesToWrite = switch($getFirstLine) { $true {$lines} $false {$lines | Select -Skip 2} } $getFirstLine = $false Add-Content Final.csv $linesToWrite } </code></pre>
3
How to collect a name list from a sub-folder in git
<p>use case is, the git repository is a <a href="https://en.wikipedia.org/wiki/Monorepo" rel="nofollow noreferrer">monorepo</a>, I want to know who worked on a sub-project in history and get the name list.</p> <p>For example, I'd like to know who involved and merged the codes to this sub-folder <code>PackerBuildV1</code>.</p> <p>Only need target on master/main branch.</p> <p><a href="https://github.com/microsoft/azure-pipelines-tasks/tree/master/Tasks/PackerBuildV1" rel="nofollow noreferrer">https://github.com/microsoft/azure-pipelines-tasks/tree/master/Tasks/PackerBuildV1</a></p> <p>any hints for me?</p>
3