id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23534200
org.apache.commons.dbcp.BasicDataSource and managing it through Spring: org.springframework.jdbc.datasource.DataSourceTransactionManager While using this combination with the Teradata JDBC driver if my database goes down or there is a network glitch I receive the following error: 08S01 804 : I/O Error, Socket closed. Packet stream write error Which reflects the situation correctly but the problem is with reconnecting. When the error is ironed out physically or DB comes back up and my program tries to query it, I still end up getting the same error for some time period which varies e.g. 20 minutes, hours, never. The problem goes away when either I restart my JVM or change the connection string e.g. use IP address instead of hostname. Is there any setting in the DataSource or the Spring Transaction Manager that can rectify this? or maybe a TCP/IP setting? A: I'd look into the settings on Apache DBCP: http://commons.apache.org/dbcp/configuration.html SELECT 1 can be an efficient validation query. Test on return should be set. I'd also ask that it remove and log abandoned connections so you can see what's going on. A: Do you see this error on both Windows and Linux? If you only see it on Linux, then I recommend checking out the Teradata JDBC Guide. When logging on, they use an algorithm which is slow on the Linux version of the JVM. Try adding the following line to teh start of your service command to see if you get any improvement -Djava.security.edg=file:/dev/./urandom Note: this was taken from the troubleshooting portion of the Teradata JDBC Driver User Guide
doc_23534201
IE speed up execution command Browser.speed = :fast Every little bit of help would be really appreciated. A: watir-webdriver builds on top of selenium-webdriver, and the Chrome driver has recently been rewritten with vast improvements in both speed and reliability. Make sure you have the latest version of both gems.
doc_23534202
<!DOCTYPE HTML> <html> <head> <title>Audio</title> </head> <body> <script> function play(){ var audio = document.getElementById("audio"); audio.play(); } function stop(){ var audio = document.getElementById("audio"); audio.stop(); } function pause(){ var audio = document.getElementById("audio"); audio.pause(); } </script> <input type="button" value="PLAY" onclick="play()"> <input type="button" value="STOP" onclick="stop()"> <input type="button" value="PAUSE" onclick="pause()"> <audio id="audio" src="i_am.mp3" ></audio> <audio id="audio" src="311.mp3" ></audio> <audio id="audio" src="thievery_corporation.mp3" ></audio> <audio id="audio" src="saxy.mp3" ></audio> <audio id="audio" src="silent_rider.mp3" ></audio> </body> </html> A: In your stop function, try pausing and setting the current time: function stop() { const audio = document.getElementById('audio'); audio.pause(); audio.currentTime = 0; } See also: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/currentTime
doc_23534203
Lets assume the following theoretical scenario: one has a component Container, which includes two other components (Selection and Display). Now in terms of functionality: Container holds a state, which can be changed by Selection, Display shows data based on said state. Now how would one go about changing the URL as well as the state triggered by a change in state via react router? For a more concrete example please see (React Router V4 - Page does not rerender on changed Route). However, I felt the need to generalize and shorten the question to get anywhere. A: Courtesy to [Tharaka Wijebandara] the solution to this problem is: Have the Container component provide the Selection component with a callback function that has to do at least the following on Container: props.history.push(Selection coming from Selection); Please find below an example of the Container (called Geoselector) component, passing the setLocation callback down to the Selection (called Geosuggest) component. class Geoselector extends Component { constructor (props) { super(props); this.setLocation = this.setLocation.bind(this); //Sets location in case of a reload instead of entering via landing if (!Session.get('selectedLocation')) { let myRe = new RegExp('/location/(.*)'); let locationFromPath = myRe.exec(this.props.location.pathname)[1]; Session.set('selectedLocation',locationFromPath); } } setLocation(value) { const newLocation = value.label; if (Session.get('selectedLocation') != newLocation) { Session.set('selectedLocation',newLocation); Session.set('locationLngLat',value.location); this.props.history.push(`/location/${newLocation}`) }; } render () { return ( <Geosuggest onSuggestSelect={this.setLocation} types={['(cities)']} placeholder="Please select a location ..." /> ) } }
doc_23534204
This version of the algorithm selects a pivot at the end of the array, places a "wall" at the beginning and starts iterating the list. When it finds an item that is smaller than the pivot, it swaps that item with the item on the right side of the wall and moves the wall one position to the right. When all items are compared to the pivot, it places the pivot on the wall, and the wall moves one position to the right. This continues until the wall is at the end of the array. So far, I have come up with this: def quicksort(alist): quicksort_helper(alist) print alist def quicksort_helper(alist): wall = 0 while wall < (len(alist) - 1): pivot = len(alist) - 1 for current in range(wall, pivot): if alist[current] < alist[pivot]: alist[current], alist[wall] = alist[wall], alist[current] wall = wall + 1 alist[wall], alist[pivot] = alist[pivot], alist[wall] wall = wall + 1 When I am trying to run the program I keep having problems with the array indexes of the wall and pivot, as this is the error message I am getting: IndexError: list index out of range I have tried a lot with the indexes, but I cannot seem to figure it out. A: Quicksort works like this: You first partition your array so that there are three subarrays: The left array contains all elements that are smaller than the pivod, in no order. The middle "array" is just one element, the pivot*. The right array contains all elements that are larger than or equal to the pivot. The pivot is now known to be in its correct position. You then have to sort the left and right subarrays. The partitioning is done with the help of the wall. The pivot's position is fixed; it is always the rightmost element. Then you conpare each element with the pivot and move it to the left of the wall if it's smaller. You must move the wall right in oder to make room for the element. After you have looked at all elements, you have the three subarrays, but in the wrong order: left, right, pivot. (The wall is the barrier between the left and right subarrays.) In oder to bring it into the correct order, swap the element to the right of the wall with the pivot, but don't move the wall. This has to be done only once, after the partitioning loop. (Note that if the pivot happens to be the biggest element, you swap the pivot with itself, which is okay, if wasteful.) Your algorithm uses 0 and the ength of the array as bound. That works for the whole array. When you want to sort the subarrays, you have to adjust these bounds. It is therefore a good idea to pass the bounds to the quicksort helper, so that you can recurse. (It is sutomary to make the lower bound inclusive and the upper bound exclusive, just as the index len(a) is one beyond the valid index range for a when indexing starts at zero.) Here's a working solution: def quicksort(alist): quicksort_helper(alist, 0, len(alist)) def quicksort_helper(alist, l, r): if l < r: wall = l pivot = r - 1 for current in range(wall, pivot): if alist[current] < alist[pivot]: alist[current], alist[wall] = alist[wall], alist[current] wall = wall + 1 alist[wall], alist[pivot] = alist[pivot], alist[wall] quicksort_helper(alist, l, wall) quicksort_helper(alist, wall + 1, r) *) There is a three-way Quicksort that groups all pivots of the same value together in order to improve Quicksort's poor performance with arrays that have only a few unique elements. A: The line alist[wall], alist[pivot] = alist[pivot], alist[wall] is executed, in some cases, after wall value was incremented and resulted in len(alist) which triggers IndexError. You can use pdb to debug your code, add the line import pdb;pdb.set_trace() in your function to track the variables values.
doc_23534205
1) var1 = var1 || 'default_value' 2) var1 = typeof(var1) !== 'undefined' ? var1 : 'default_value' 3) var1 = var1 !== 'undefined' ? var1 : 'default_value' 4) var1 = var1 != 'undefined' ? var1 : 'default_value' A: The second one is the most correct of the four. It will work as you intend (if variable is not set, use default value). * *This will also use default value if var1 is falsey (0, false, null, '', as well as undefined) *This will use the default value if var1 is not equivalent to the string 'undefined' *This will use the default value if var1 is not equal to the string 'undefined'. A: The first and second works, but for different conditions. The third and fourth compare the value to the string "undefined" which doesn't at all determine if it's an undefined value. The first method uses the default if the current value evaluates to false. That works for most values, but if you for example used it with true as default for a boolean value, it would not be possible to set it to false and have that survive the test: var var1 = false; var1 = var1 || true; Now it's true eventhough it already had a value. You will have the same problem with some other specific values, like 0 or "". The second one is the one that works most consistently with different data types. The first one is however often used because it's shorter. A: These all do very different things: * *var1 = var1 || 'default_value' var1 will equal 'default_value' if var1 is falsey (NaN, false, 0, '', undefined). This means if var1 is any of those values (perhaps most notably false, 0, or ''), var1 will equal default_value. *var1 = typeof(var1) !== 'undefined' ? var1 : 'default_value' var1 will equal 'default_value' if var1's type is strictly equal to 'undefined'. *var1 = var1 !== 'undefined' ? var1 : 'default_value' var1 will equal 'default_value' only if var1 is not strictly equal to the string 'undefined'. *var1 = var1 != 'undefined' ? var1 : 'default_value' var1 will equal 'default_value' only if var1 is not equal to the string 'undefined'. The last two are probably erroneous. You rarely want to check to see if the value of a variable is the string 'undefined'. You probably meant to check against undefined directly. To fully understand each of these, you should read about the differences between the strict equality (===) operator and the equality operator (==). MDN's comparison operators article is quite good at explaining this.
doc_23534206
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_)) optimizer = tf.train.AdamOptimizer(LEARNING_RATE) for j in range(n_rounds): sample = np.random.randint(row, size=int(batch_size)) batch_xs = temp[sample][:] batch_ys = output[sample][:] vars_with_grads = sess.run(optimizer.compute_gradients(cross_entropy), feed_dict={x: batch_xs, y_: batch_ys}) noiseAddedGradient = [] print(vars_with_grads) for var in vars_with_grads: gaussianNoise = [np.random.normal(MEAN_FOR_AUTOENCODER, SCALE_FOR_AUTOENCODER, var[0].shape) for i in range(int(batch_size))] totalGaussianNoise = [sum(x) for x in zip(*gaussianNoise)] averageGaussianNoise = [x1 / float(batch_size) for x1 in totalGaussianNoise] averageGaussianNoiseList = np.array(averageGaussianNoise).flatten().reshape(var[0].shape) noiseAddedGradient.append((tf.Variable(np.add(var[0], averageGaussianNoiseList), dtype=np.float32), var[1])) appliedGradient = sess.run(optimizer.apply_gradients(noiseAddedGradient)) it returns error function: Traceback (most recent call last): File "/home/Downloads/objectPerturbation.py", line 214, in <module> appliedGradient = sess.run(optimizer.apply_gradients(noiseAddedGradient)) File "/home/anaconda2/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 384, in apply_gradients p = _get_processor(v) File "/home/anaconda2/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 98, in _get_processor if v.op.type == "ReadVariableOp": AttributeError: 'numpy.ndarray' object has no attribute 'op' Can you please help me? A: Try chaging it like this. The gradients should be computed in the graph. cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_)) optimizer = tf.train.AdamOptimizer(LEARNING_RATE) grads = optimizer.compute_gradients(cross_entropy) grad_placeholder = [(tf.placeholder("float", shape=grad[1].get_shape()), grad[1] for grad in grads] apply_placeholder_op = opt.apply_gradients(grad_placeholder) #added in case you don't do this sess.run(tf.initialize_all_variables()) for j in range(n_rounds): sample = np.random.randint(row, size=int(batch_size)) batch_xs = temp[sample][:] batch_ys = output[sample][:] vars_with_grads = sess.run(grads, feed_dict={x: batch_xs, y_: batch_ys}) #Add gaussian noise to gradients feed_dict = {} for i in range(len(grad_placeholder)): feed_dict[grad_placeholder[i][0]] = add_gaussian_noise_fn(grad_vals[i]) sess.run(apply_placeholder_op, feed_dict=feed_dict) #separate function to make it more general to do whatever you want with grads def add_gaussian_noise_fn(x): return x + np.random.normal(size=x.shape) Idea is similar to this previous post: Efficiently grab gradients from TensorFlow?
doc_23534207
Here is what I need to do with it: * *For each face, obtain the neighboring faces *Get the edge any two faces share in common *Store the coordinates (to draw them later) There is no need to manipulate the structure (e.g. delete edge, split faces etc). I have considered using DCEL, but I'm afraid it could be overkill. Could anyone offer me some suggestions?
doc_23534208
in TableA.. I have 5 fields.. ( Empty ) (only structure having Autoincrement-ID field) in TableB ..I have 7 Fields ( Full ..1 million Recs.) TableA is Empty .. i want to add a complete column from TableB .. i.e the field'ID' in the TableB shud be inserted inside the the field'Value' in the TableA.. i.e complete column'ID' from TableB shud be copied/inserted inside the TableA as column'Value' There is no match case here so i cannot use WHERE clause... What exactly shud i use outerjoin or innerjoin or full join.. Pls advise. A: INSERT INTO TableA(value) SELECT id FROM TableB
doc_23534209
I tried to add it to the signature of the invoke like this: public async Task Invoke(HttpContext context,CancellationToken token) But as soon as I add it, it isn't called any more. What am I doing wrong? A: I think the idea is not to be able to cancel invocation of the middleware, from inside the middleware if you call some async task that accepts a cancellation token then you can create one and pass it in to what you are calling from inside there. A common scenario would be to cancel a task if the request is aborted, so you could create the token like this: CancellationToken CancellationToken => context?.RequestAborted ?? CancellationToken.None; and then call some async service like getting data or querying the db, if the request is aborted then the cancellation request should happen
doc_23534210
I have them listed in a table with something like this: <table> <thead> <tr> <th>Project Number</th> <th>Project Name</th> <th>Status</th> </tr> </thead> <tbody> @foreach (var p in projects) { <tr> <td>@p.ProjectId</td> <td>@p.Name</td> <td>@p.ProjectStatus</td> </tr> } </tbody> </table> now, I want that when the user clicks on the "projectId" it navigates to another page that will have the detailed information for this particular project, which I understand is done like this: <button @onclick="() => ButtonHandler(p.ProjectId)">@p.ProjectId</button> @code { private void ButtonHandler(int projectId) { Project = projects.First(x => x.ProjectId == projectId); navigationManager.NavigateTo($"/projectdetail/{projectId}"); } } this projectId I'm passing is because I want to filter the project list into a single object "Project" that I want to pass to my "projectDetail" component. in my projectDetail.razor I have the following: @page "/projectdetail/{ProjectId:int}" @code { [Parameter] public Project Project { get; set; } = null!; } however this doesn't seem to work, the Project property is null when I reach to it. Can I get some help about how to properly pass the object from "ProjectList" to "ProjectDetail"? I have tried with the component passing as well by doing <td>@project.ProjectId <ProjectDetail Project="Project"></ProjectDetail></td> but it seems that as this being inside the foreach loop is doing it every time instead of just the one I need when the users clicks on it. A: You are passing a ProjectId route parameter to the ProjectDetail.razor page which you should use to fetch the Project: @page "/projectdetail/{ProjectId:int}" @code { [Parameter] public int ProjectId { get; set; } private Project project; protected override void OnInitialized() { project = ProjectService.GetProjectById(ProjectId); } } Edit: Only way to pass the entire Project object to the ProjectDetails page would be to serialize it to JSON string and pass it using a string route parameter. ProjectDetails.razor: @page "/productdetails/{ProjectJson}" @using System.Text.Json @code { [Parameter] public string ProjectJson { get; set; } private Project project { get; set; } protected override void OnInitialized() { project = JsonSerializer.Deserialize<Project>(ProjectJson); } } ProjectList.razor: <button @onclick="() => ButtonHandler(p.ProjectId)">@p.ProjectId</button> @code { private void ButtonHandler(int projectId) { Project = projects.First(x => x.ProjectId == projectId); navigationManager.NavigateTo($"projectdetail/{JsonSerializer.Serialize(Project)}"); } } A: From the point of view of UI design, it's better to have the list of projects in a tabular element at the top of the page, and the project detail below it. This allows you to view the project's detail instantly, as you select a project in the list of project. This means that your project detail is no longer a routable component, and it is embedded within the projects component. And now, you can query Project = projects.First(x => x.ProjectId == projectId);, in the ButtonHandler method, the projects list in order to get the selected project, and pass it as a parameter to the embedded component. Note that the above suggested design is also more efficient and fast, as Blazor does not destroy the elements in the Detail component, and recreate them a new. It uses the same objects to dispaly the new data. But if you insist on creating a dedicted page for the project's detail, you should pass only the ProjectId to the Detail component: @page "/projectdetail/{ProjectId:int}" @inject ProjectsService projectsService @code { [Parameter] public int ProjectId { get; set; } private Project project; protected override void OnInitialized() { project = ProjectsService.GetProjectById(ProjectId); } } Note: Your ProjectsService should implement the state pattern. There shouldn't be any issue of querying the database again and again. Its life time should span the duration of the app. Thus when you call the GetProjectById method, it accesses the collection of projects stored in a variable defined in the service, and returns the selected project. No database call. See here how it is done
doc_23534211
If I were creating a new process I would just run: PM2 start [process name] --max-memory-restart 700M or whatever How can I do the same for an existing process? How can I confirm that it works? Thanks! A: To change your existing PM2 process. you can use this command: pm2 restart [existing name] --max-memory-restart 700M To check if it affect or not, you can set it with low memory to restart (like 30M). Then check restart time by : pm2 ls command. Sorry for my bad English. Hope it help. A: For 0 downtime you can now also use (more preferable in production): pm2 reload my_current_name --name my_new_name --max-memory-restart 700M For differences, please see: What is the difference between pm2 restart and pm2 reload A: If you want to edit this setting 'WITHOUT' restarting the process, there doesn't seem to be a way to do it. PM2's docs don't list any way to do this, such options have to be stated along with starting the process.
doc_23534212
A: The short answer is: read the System Interface section of the elisp info manual. More specifically, the time sections: * *Time of day *Time conversion *Time parsing *Time calculations The longer answer: Emacs can work with time values as strings, floats, or a tuple of two or three integers. E.g. call some functions in the *scratch*buffer: (current-time) (19689 59702 984160) (current-time-string) "Sun Nov 21 20:54:22 2010" (current-time-zone) (-25200 "MST") (float-time) 1290398079.965001 Let's some conversions: (decode-time (current-time)) (33 7 21 21 11 2010 0 nil -25200) (decode-time) ; (current-time) by default (51 7 21 21 11 2010 0 nil -25200) (let ((seconds 36) (minutes 10) (hour 21) (day 21) (month 11) (year 2010)) (encode-time seconds minutes hour day month year)) (19689 60732) (format-time-string "%A %e %B" (current-time)) "Sunday 21 November" (seconds-to-time 23) (0 23 0) (time-to-seconds (current-time)) 1290399309.598342 (time-to-days (current-time)) 734097 Finally, to answer your question: (time-add (current-time) (seconds-to-time 23)) (19689 60954 497526) (time-subtract (current-time) (seconds-to-time 45)) (19689 61001 736330)
doc_23534213
I'm using dburles:factory to create a new user with 'administrator' role in the Meteor.users collection. I'm then invoking the validated method using the userId of the 'admin' user, but it is throwing an error. Although I invoke the method using the context of the administrator user as per the documentation, it doesn't seem to be passing it to the method. When I console.log(this.userId); in the method it returns undefined. Can anyone check my code out and tell me why this is happening? Thanks! Method code: import { Meteor } from 'meteor/meteor'; import { Clients } from '../../clients'; import SimpleSchema from 'simpl-schema'; import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { Roles } from 'meteor/alanning:roles'; export const createClient = new ValidatedMethod({ name: 'Clients.methods.create', validate: new SimpleSchema({ name: { type: String }, description: { type: String }, }).validator(), run(client) { console.log(this.userId); //this is undefined for some reason if(!Roles.userIsInRole(this.userId, 'administrator')) { throw new Meteor.Error('unauthorised', 'You cannot do this.'); } Clients.insert(client); }, }); Test code: import { Meteor } from 'meteor/meteor'; import { expect, be } from 'meteor/practicalmeteor:chai'; import { describe, it, before, after } from 'meteor/practicalmeteor:mocha'; import { resetDatabase } from 'meteor/xolvio:cleaner'; import { sinon } from 'meteor/practicalmeteor:sinon'; import { Factory } from 'meteor/dburles:factory'; import { createClient } from './create-client'; import { Clients } from '/imports/api/clients/clients'; describe('Client API Methods', function() { afterEach(function() { resetDatabase(); }); it('Admin user can create a new client', function() { let clientName = "Test", description = "This is a description of the client!", data = { name: clientName, description: description }; Factory.define('adminUser', Meteor.users, { email: 'admin@admin.com', profile: { name: 'admin' }, roles: [ 'administrator' ] }); const admin = Factory.create('adminUser'); console.log(Roles.userIsInRole(admin._id, 'administrator'));// this returns true //invoking the validated method with the context of the admin user as per the documentation createClient._execute(admin._id, data); let client = Clients.findOne(); expect(Clients.find().count()).to.equal(1); expect(client.name).to.equal(clientName); expect(client.description).to.equal(description); }); A: I have worked out the solution to my issue. When you execute a validated method, you need to pass the userId as an object like { userId: j8H12k9l98UjL } I was passing it as a string so the method wasn't being invoked with the context of the user that was being created by Factory. This test now works perfectly Hope this helps someone else
doc_23534214
Here is what I have: MyCustomAttribute in MyDll.dll: namespace MyDll { [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] public sealed class MyCustomAttribute : Attribute { public MyCustomAttribute(String Name) { this.Name= Name; } public string Name { get; private set; } } } PowerShell Script: Add-Type -Path "./MyDll.dll"; function foo { [MyDll.MyCustom(Name = "This is a good function")] # Do stuff } Of note, however, is that if I do this: $x = New-Object -TypeName "MyDll.MyCustomAttribute" -ArgumentList "Hello" It works fine. So the type is clearly being loaded correctly. What am I missing here? A: Seemingly two things you need to change: * *Command attributes need to syntactically precede the param() block. *Using the Name = specifier seems to cause the PowerShell parser to treat the attribute argument as an initializer, at which point the constructor won't get resolved. function foo { [MyDll.MyCustom("This is a good function")] param() # Do stuff }
doc_23534215
http://mywebsite/file.imgext --> C:\path\to\dir\file.imgext A: WinInet APIs are easier than you think Here is a complete win32 console program. Can be built with with VS 2010 Express and down loading windows SDK to get WinInit. // imaged.cpp : Defines the entry point for the console application. // // Copy file from internet onto local file // Uses Wininet API // program takes 1 mandatory command line argument - URL string // it downloads ito the current directory, or whatever is passed // as the second parameter to DownloadURLImage. // optional parameter, the name of the file (excluding path), by default it uses the // filename from the URL string. #include "stdafx.h" #include <iostream> #include <windows.h> #include <WinInet.h> // from SDK #include "string.h" //#include<TCHAR.H> //#include "Tchar.h" using namespace std ; int convertURLtofname (TCHAR * szURL, TCHAR * szname ) // extract the filename from the URL { char aszfilename [100]; HRESULT result; char achar[3], aszURL [100]; size_t nchars, i, j; int fresult; fresult = 0; nchars= _tcslen(szURL); i= nchars -1; while ((i > 0) && (szURL[i] != '/') && (szURL[i] != '\\')) {i--;} j= 0; i++; while (i < nchars) { szname [j++]= szURL[i++]; } szname[j]=_T('\0'); // wcstombs ( aszfilename, szname, 100 ); // cout << aszfilename << endl; //---------------------------------------------- return fresult ; } int determinepathfilename (TCHAR * szURL, TCHAR * szpath, TCHAR * szname, TCHAR * szpathfilename) { // use path and filename when supplied. If filename (e.g. funkypic.jpg) is not supplied, then the // filename will be extracted from the last part of the URL int result ; result= 0; TCHAR szname_copy [100] ; if ((szname == NULL) || (szname[0] == '\0')) convertURLtofname (szURL, szname_copy); else _tcscpy (szname_copy, szname); if ((szpath == NULL) || (szpath[0] == '\0')) _tcscpy (szpathfilename, szname_copy); else { _tcscpy (szpathfilename, szpath); _tcscat (szpathfilename, szname_copy); } return result ; } bool GetFile (HINTERNET hOpen, // Handle from InternetOpen() TCHAR *szURL, // Full URL TCHAR * szpath, TCHAR * szname) { DWORD dwSize; TCHAR szHead[15]; BYTE * szTemp[1024]; HINTERNET hConnect; FILE * pFile; TCHAR szpathfilename [100] ; szHead[0] = '\0'; if ( !(hConnect = InternetOpenUrl( hOpen, szURL, szHead, 15, INTERNET_FLAG_DONT_CACHE, 0))) { std::cout << "Error: InternetOpenUrl" << std::endl; return 0; } determinepathfilename (szURL, szpath, szname, szpathfilename); if ( !(pFile = _tfopen (szpathfilename, _T("wb") ) ) ) { std::cerr << "Error _tfopen" << std::endl; return false; } do { // Keep copying in 1024 bytes chunks, while file has any data left. // Note: bigger buffer will greatly improve performance. if (!InternetReadFile (hConnect, szTemp, 1024, &dwSize) ) { fclose (pFile); std::cerr << "Error InternetReadFile" << std::endl; return FALSE; } if (!dwSize) break; // Condition of dwSize=0 indicate EOF. Stop. else fwrite(szTemp, sizeof (BYTE), dwSize , pFile); } // do while (TRUE); fflush (pFile); fclose (pFile); return TRUE; } int DownloadURLImage (TCHAR * szURL, TCHAR * szpath, TCHAR * szname) { int result ; HINTERNET hInternet; result= 0; hInternet= InternetOpen (_T("imaged"), INTERNET_OPEN_TYPE_DIRECT, //__in DWORD dwAccessType NULL, //__in LPCTSTR lpszProxyName, NULL, //__in LPCTSTR lpszProxyBypass, NULL //_in DWORD dwFlags ); GetFile (hInternet, szURL, szpath, szname) ; InternetCloseHandle(hInternet); return result ; } int _tmain(int argc, _TCHAR* argv[]) { if (argc == 2) { DownloadURLImage (argv[1], NULL, NULL); //DownloadURLImage (argv[1], _T"C:/", NULL); } else if (argc == 3) { DownloadURLImage (argv[1], NULL, argv[2]); //DownloadURLImage (argv[1], _T"C:/", argv[2]); } else { cout << "Usage: imaged <image URL>" << endl ; } system("pause") ; return 0; } A: You could use cURLpp I havn't used it yet, but example20 looks like it could solve your problem. A: If you want an EASY solution, use this amazingly simple one liner: system("C:\\Path\\To\\Wget\\wget.exe http://pixelcaster.com/yosemite/webcams/ahwahnee2.jpg -O C:\\Users\\Me\\Desktop\\ahwahnee2.jpg"); With wget for windows choco install wget See chocolatey.org A: Use Windows Http Services API. A: You could use the WinInet or WinHTTP classes in C++. These are native Win32 APIs the abstract some of the work of getting sending and receiving files from the Internet. I've used WinInet with great success to do just what you're trying to do. A: If starting a new process is ok, you could have a look at WGET. (And even if not, the sources are available; you can look there to see how it's been implemented.) A: Using POCO for this now. :-)
doc_23534216
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php?p=%{REQUEST_URI}&%{QUERY_STRING} [L] </IfModule> Problem is, that in apache 2.2.22, the p and the other query objects don't come through, but it works great in apache 2.4.2 . So basically in apache 2.2.22 it just forwards everything to index.php, but it doesn't have any get objects. Any help, thanks. Update Ok so I changed the line RewriteRule . /index.php?p=%{REQUEST_URI}&%{QUERY_STRING} [L] to RewriteRule ^(.*) /index.php?p=$1 [L,QSA] And now on apache 2.2.22 the p GET doesn't go through, but any specific queries I add go through. So If I do http://localhost/index/fun/buns/funds?man=woman on 2.4.2 I get array (size=2) 'p' => string 'index/fun/buns/funds' (length=20) 'man' => string 'woman' (length=5) and on 2.2.22 I get array(1) { ["man"]=> string(5) "woman" } To be clear What's happening on 2.4.2 is what I want, and 2.2.22 isn't cooperating. Another Update Ok so it seems like what is happening is that when I do /index/whatever, it auto assumes index.php, and ignores that, it auto adds the .php to it, when I don't want it to. Any ideas on how to stop that? A: Problem solved: I needed to add -MultiViews to the httpd.conf file.
doc_23534217
for j in range(1,50): in_file=open(name+j+".dat", "r") I get the error "TypeError: cannot concatenate 'str' and 'int' objects" which I sort of understand. I tried changing this to for j in range(1,50): in_file=open(sys.argv[1]+j.to_eng_string()+".dat", "r") but now I get the error "AttributeError: 'int' object has no attribute 'to_eng_string'" which again I can sort of understand. Having only very minor knowledge of python I am at a loss for what to do. Any suggestions? Thanks A: You need to convert j to a str before concatenating it to other strings. One way to construct a string from variables of different types is to use format, though there are many approaches: for j in range(1,50): in_file=open("{}_{}.dat".format(name, j), "r") A: Try using string formatting: for j in range(1,50): in_file=open("%s_%i.dat"%(sys.argv[1],j.to_eng_string()), "r") You might also look at using os.listdir from the os package. A: Most of the answers here show you how to generate the strings that match the pattern of the file names. If, suppose, the file named name35.dat is not there you will need to catch that exception. Here, I am looking at the files that actually exist by using glob for ALL the files that match that pattern: import glob print glob.glob('name[0-9]*.dat') Use a regex to limit to some subset: import re, glob, sys def expand(x,lo=0,hi=sys.maxint): return lo<=int(re.search(r'\d+', x).group(0))<=hi # all files that match 'name1.dat' to 'name50.dat' inclusive print [e for e in glob.glob('name[0-9]*.dat') if expand(e, 1, 50)] Now you have a list of files that exist and match your given pattern.
doc_23534218
All my questions in this post are regarding composer the php dependency tool not docker-composer the successor of fig. I'm trying to build my own docker image to run WordPress installed as a composer dependency. I'm working on building a docker image using docker PHP image as a base and what I need to do is install composer and run a composer update command either on image creation time or on image build time (don't know if both would be ok). I can run everything just fine by manually executing all the steps (running a docker image, bashing into it, and copying and pasting every step). But when I put all that steps on a Dockerfile I don't get composer to write the files. I've been trying to get a minimum failing example for some time but the one I've got is quite not minimum. My test is composed of the following (links to the relevant github repos below) Dockerfile NFORMATION ~~~# # based on # https://hub.docker.com/r/richarvey/nginx-php-fpm/ # and # https://hub.docker.com/_/wordpress/ FROM php:7.0.2-apache MAINTAINER Miquel Adell <miquel@miqueladell.com> ENV WORDPRESS_VERSION 4.4.1 #~~~ DEPENDENCIES ~~~# # Add PHP repository to apt source RUN apt-get update \ && apt-get install -y \ libpng12-dev \ libjpeg-dev \ curl \ sed \ zlib1g-dev \ && docker-php-ext-install \ zip \ mysqli RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer #~~~ DIRS ~~~# WORKDIR /var/www/html/ #~~~ WORDPRESS ~~~# COPY files/composer.json composer.json ONBUILD RUN composer update docker-compose.yml wordpress: image: miqueladell/composed_wordpress_test links: - wordpress_db:mysql environment: - VIRTUAL_HOST=miqueladell.dev - WORDPRESS_DB_NAME=wordpress ports: - "80" wordpress_db: image: miqueladell/mariadb-utf8mb4 environment: - MYSQL_ROOT_PASSWORD=password My test is as follows * *Build an image executing this command in a directory containing the Dockerfile pasted above docker build -t miqueladell/composed_wordpress_test . (no errors in the log) *Use that image to build a container by running the following command in a directory containing the docker-compose.yml pasted above docker-compose up (no errors in the log) *bash into the running container to be able to see if the files are there docker exec -i -t miqueladellv2_wordpress_1 bash *ls of /var/www/html root@bff14367658b:/var/www/html# ls -al total 12 drwxr-xr-x 2 www-data www-data 4096 Jan 19 10:50 . drwxr-xr-x 5 root root 4096 Jan 19 10:50 .. -rw-r--r-- 1 root root 138 Jan 15 09:18 composer.json You can see in step 4 that composer update seems to not have run at all. I've tried using both RUN composer update and ONBUILD RUN composer update on Dockerfile with the same results. If I go back to the previous step 4 of the test and I manually run composer update on the bash prompt of the docker container I get: root@bff14367658b:/var/www/html# composer update Loading composer repositories with package information Updating dependencies (including require-dev) - Installing johnpbloch/wordpress-core-installer (0.2.1) Downloading: 100% - Installing johnpbloch/wordpress (4.4.1) Downloading: 100% Writing lock file Generating autoload files root@bff14367658b:/var/www/html# ls -al total 24 drwxr-xr-x 4 www-data www-data 4096 Jan 19 11:12 . drwxr-xr-x 6 root root 4096 Jan 19 11:12 .. -rw-r--r-- 1 root root 138 Jan 15 09:18 composer.json -rw-r--r-- 1 root root 3718 Jan 19 11:12 composer.lock drwxr-xr-x 4 root root 4096 Jan 19 11:12 vendor drwxr-xr-x 5 root root 4096 Jan 19 11:12 wordpress root@bff14367658b:/var/www/html# which is exactly the output I was expecting on step 4 github links to the full files * *Dockerfile and its dependencies *docker-composer A: Installing composer like this will avoid this problem: RUN curl -o /tmp/composer-setup.php https://getcomposer.org/installer \ && curl -o /tmp/composer-setup.sig https://composer.github.io/installer.sig \ # Make sure we're installing what we think we're installing! && php -r "if (hash('SHA384', file_get_contents('/tmp/composer-setup.php')) !== trim(file_get_contents('/tmp/composer-setup.sig'))) { unlink('/tmp/composer-setup.php'); echo 'Invalid installer' . PHP_EOL; exit(1); }" \ && php /tmp/composer-setup.php --no-ansi --install-dir=/usr/local/bin --filename=composer --snapshot \ && rm -f /tmp/composer-setup.* A: I ran into this problem today. What solved it for me was to use a different directory than the one that was defined in the image. It seems like changes that are made to the directory during build process are discarded if the directory is defined as a volume. Here's an example of my working Dockerfile FROM richarvey/nginx-php-fpm # Install dependencies RUN apt-get update && \ apt-get install curl nano && \ curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer # Add update nginx config COPY conf/nginx-site.conf /etc/nginx/sites-available/default.conf # Bundle app source COPY app/ /app # Install app dependencies RUN cd /app && \ composer install --no-interaction EXPOSE 80 And then in conf/nginx-site.conf I updated the root for my application (shortened for brevity) server { # ... the rest of your nginx config root /app/public; # ... the rest of your nginx config }
doc_23534219
Here I create POSIXct vectors as the basis for the rows within a dataframe. When I use rbind() withing as.data.frame() and use stringsASFactors = FALSE, the POSIXct values are changed to class character. I do know that it is rbind() and not as.data.frame() that is converting the class and there does not seem to be any way of preventing this. While I'm familiar with various date time structures, I did some research and I have no clue what system it is using to store the date-time or how to convert it back (yes, I already tried as.POSIXct()). So the question is, how do I convert these back to POSIXct? (If there is some magical way to have rbind() not convert POSIXct to character, I'll take that too.) Thanks! ####Build example#### d1 <- as.POSIXct("2020-06-30 8:00") d2 <- as.POSIXct("2020-06-30 9:00") d3 <- as.POSIXct("2020-06-30 10:00") d4 <- as.POSIXct("2020-06-30 16:00") s1 <- c(d1, d2, d3, d4, "", "") d1 <- as.POSIXct("2020-06-30 8:00") d2 <- as.POSIXct("2020-06-30 10:00") d3 <- as.POSIXct("2020-06-30 11:00") d4 <- as.POSIXct("2020-06-30 12:00") d5 <- as.POSIXct("2020-06-30 12:30") d6 <- as.POSIXct("2020-06-30 16:30") s2 <- c(d1, d2, d3, d4, d5, d6) d1 <- as.POSIXct("2020-06-30 8:00") d2 <- as.POSIXct("2020-06-30 13:00") d3 <- as.POSIXct("2020-06-30 13:45") d4 <- as.POSIXct("2020-06-30 16:30") s3 <- c(d1, d2, d3, d4, "", "") d3 <- as.POSIXct("2020-06-30 13:25") s4 <- c(d1, d2, d3, d4, "", "") d2 <- as.POSIXct("2020-06-30 16:00") s5 <- c(d1, d2, "", "", "", "") ####Build data frame#### timedata <- as.data.frame(rbind(s1, s2, s3, s4, s5), stringsAsFactors = FALSE) names(timedata) <- c("T1", "T2", "T3", "T4", "T5", "T6") for(c in seq(from = 1, to = 6, by = 1)) { timedata[,c] <- as.POSIXct(timedata[,c], tzone = "PDT") } P.S. There is some documentation for as.POSIXct() which discusses how to convert gibberish with a specific origin back into a functional POSIXct. But the examples are using the varying structures provided by SAS, SPSS, STATA, and Matlab, not internal R. A: If you wrap s1, ..., s5 in as.character() prior to rbind() it seems to behave as you'd like. timedata <- as.data.frame(rbind(as.character(s1), as.character(s2), as.character(s3), as.character(s4), as.character(s5)), stringsAsFactors = FALSE) Then you can do what you did and convert back. Another option is to keep the rbind() as you are doing, and then change your loop as follows. This is all due to the supported classes of each function. The key is hidden away in the Note section of help(as.POSIXct). the origin of time for the "POSIXct" class, ‘1970-01-01 00:00.00 UTC’ for(c in seq(from = 1, to = 6, by = 1)) { timedata[,c] <- as.POSIXct(as.numeric(timedata[,c]), origin = "1970-01-01 00:00:00", tzone = "PDT") }
doc_23534220
{ "_id" : "5Ci9sLeBu2iPbWtR5", "productId" : "010101111", "description" : "PRODUCT EXAMPLE REF 1001", "prices" : [ { "priceId" : 10, "description" : "Promotions", "price" : 97.99 }, { "priceId" : 15, "description" : "Retail list", "price" : 105.65 }, { "priceId" : 20, "description" : "Standard list", "price" : 109.10 } ]} What I want is query only specific array of priceIds, for example: [10,20], resulting: { "_id" : "5Ci9sLeBu2iPbWtR5", "productId" : "010101111", "description" : "PRODUCT EXAMPLE REF 1001", "prices" : [ { "priceId" : 10, "description" : "Promotions", "price" : 97.99 }, { "priceId" : 20, "description" : "Standard list", "price" : 109.10 } ]} Using $in operator with $filter like this (the perfect imaginary scenario): db.getCollection('products').aggregate([ {$match: { "productId":"010101111" }}, {$project: { "prices": { $filter: { input: "$prices", as: "price", cond: { $in: ["$$price.priceId",[10, 20]] } } } }}]) it doesn't work, because mongodb complains about $in operator ("invalid operator '$in'"). Of course, I can do that with $unwind, but I'll have a performance problem, because I need to group again after all. The closest answers I've found for my question were these two: * *Retrieve only the queried element in an object array in MongoDB collection *Filter array using the $in operator in the $project stage but none of them were about searching with array filter in subdocuments. A: The $in operator is only valid within the aggregation pipeline for MongoDB 3.4+. However, a workaround involves using the set operators. Use $setIsSubset as substitute which returns true if all elements of the first set appear in the second set, including when the first set equals the second set: cond: { $setIsSubset: [["$$price.priceId"],[10, 20]] }
doc_23534221
Error: ENOENT: no such file or directory, open '/home/ira/dev/eshka/http:/192.168.0.104:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false&strict=false&minify=false' at Object.openSync (node:fs:585:3) at Object.readFileSync (node:fs:453:35) at getCodeFrame (/home/ira/dev/eshka/node_modules/metro/src/Server.js:949:18) at Server._symbolicate (/home/ira/dev/eshka/node_modules/metro/src/Server.js:1022:22) at runMicrotasks (<anonymous>) at processTicksAndRejections (node:internal/process/task_queues:96:5) at Server._processRequest (/home/ira/dev/eshka/node_modules/metro/src/Server.js:429:7) { errno: -2, syscall: 'open', code: 'ENOENT', path: '/home/ira/dev/eshka/http:/192.168.0.104:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false&strict=false&minify=false' } Error: ENOENT: no such file or directory, open '/home/ira/dev/eshka/http:/192.168.0.104:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false&strict=false&minify=false' at Object.openSync (node:fs:585:3) at Object.readFileSync (node:fs:453:35) at getCodeFrame (/home/ira/dev/eshka/node_modules/metro/src/Server.js:949:18) at Server._symbolicate (/home/ira/dev/eshka/node_modules/metro/src/Server.js:1022:22) at runMicrotasks (<anonymous>) at processTicksAndRejections (node:internal/process/task_queues:96:5) at Server._processRequest (/home/ira/dev/eshka/node_modules/metro/src/Server.js:429:7) { errno: -2, syscall: 'open', code: 'ENOENT', path: '/home/ira/dev/eshka/http:/192.168.0.104:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false&strict=false&minify=false' }
doc_23534222
DataTable table = new DataTable(); // ... // insert column to table table.Columns.Add("name"); // ... // insert value to table foreach (DataRow row in table.Rows) { row["name"]; row.Field<string>("name"); } My question is: * *Is there a difference between using row["name"] and row.Field<string>("name")? Of course, the second way cast value to some type, but is there another difference? *Which method is better to use? A: See Remarks section, main differences described there: The DataSet class represents null values with the Value instance of the DBNull class. A Language-Integrated Query (LINQ) expression that accessed a column with a null value would generate a InvalidCastException at run time. Additionally, DataSet does not support nullable types. The Field method provides support for accessing columns as nullable types. If the underlying value in the DataSet is Value, the returned nullable type will have a value of null. If the value of the specified DataColumn is null and T is a reference type or nullable type, the return type will be null. The Field method will not return Value. The Field method does not perform type conversions. If type conversion is required, you should first obtain the column value by using the Field method. The column value should then be converted to another type. The last paragraph makes a point as I've often seen numbers stored as strings in database, therefore varchar to int conversion would be required on data retrieval, so in this case using DataColumn is better, e.g.: int test = row.Field<int>("Test"); // InvalidCastException int test = Convert.ToInt32(row["Test"]); // Works like a charm DataRowExtensions.Field<T> Method (DataRow, String) first appeared in .NET 3.5 and it "provides strongly-typed access to each of the column values in the specified row. The Field method also supports nullable types." Afaik, row["name"] returns object, row.Field<string>("name") returns a String. We shouldn't be comparing apples and pears, hence you should be asking what's better: row["name"].ToString() vs row.Field<string>("name") and the answer is: they're same. A: It depends on your purpose but if you look at a definition of both that may tell you; DataRow.Item Property (DataColumn) row["name"] DataRowExtensions.Field Method (DataRow, DataColumn) row.Field<string>("name")
doc_23534223
Please help me guys. A: I have used a packages called flutter_speed_dial that gets this done https://pub.dev/packages/flutter_speed_dial This is an example that you can see it and check it for yourself import 'package:flutter/material.dart'; import 'package:flutter_speed_dial/flutter_speed_dial.dart'; void main(){ runApp(MyApp()); } class MyApp extends StatelessWidget{ @override Widget build(BuildContext context) { return MaterialApp( home: Home(), ); } } class Home extends StatefulWidget{ @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Speed Dial Floating Action Menu"), backgroundColor: Colors.deepOrangeAccent, ), floatingActionButton: SpeedDial( direction: SpeedDialDirection.left, icon: Icons.menu, //icon on Floating action button activeIcon: Icons.close, //icon when menu is expanded on button backgroundColor: Colors.deepOrangeAccent, //background color of button foregroundColor: Colors.white, //font color, icon color in button activeBackgroundColor: Colors.deepPurpleAccent, //background color when menu is expanded activeForegroundColor: Colors.white, visible: true, closeManually: false, curve: Curves.bounceIn, overlayColor: Colors.black, overlayOpacity: 0.5, //background layer opacity onOpen: () => print('OPENING DIAL'), // action when menu opens onClose: () => print('DIAL CLOSED'), //action when menu closes elevation: 8.0, //shadow elevation of button shape: CircleBorder(), //shape of button children: [ SpeedDialChild( //speed dial child child: Icon(Icons.accessibility), backgroundColor: Colors.red, foregroundColor: Colors.white, label: 'First Menu Child', labelStyle: TextStyle(fontSize: 18.0), onTap: () => print('FIRST CHILD'), onLongPress: () => print('FIRST CHILD LONG PRESS'), ), SpeedDialChild( child: Icon(Icons.brush), backgroundColor: Colors.blue, foregroundColor: Colors.white, label: 'Second Menu Child', labelStyle: TextStyle(fontSize: 18.0), onTap: () => print('SECOND CHILD'), onLongPress: () => print('SECOND CHILD LONG PRESS'), ), SpeedDialChild( child: Icon(Icons.keyboard_voice), foregroundColor: Colors.white, backgroundColor: Colors.green, label: 'Third Menu Child', labelStyle: TextStyle(fontSize: 18.0), onTap: () => print('THIRD CHILD'), onLongPress: () => print('THIRD CHILD LONG PRESS'), ), //add more menu item children here ], ), body: Container() ); } }
doc_23534224
Without this I can't test my iOS applications. How can I force Xcode to detect the iOS 7 device? A: If your XCode is updated and working, then your problem could be that you have to add again your device to the portal, it happened to me. From XCode 5: Window -> Organizer Then select your device, and press in "Add to Member Center": A: Antonio MG seems to have solved your specific problem. But for those who've updated their device to iOS7 without upgrading to Xcode 5, note that iOS 7 is not supported by Xcode 4 etc... So download the update version of Xcode (Xcode 5.0) from the developer site and install it on your Mac before attaching your iOS7 device. Check the connected status of the device in the Windows --> Organizer. It should show the Green color in the name of the connected device. For further discussion of using Xcode 4.6 with iOS 7, see: Deploy from XCode 4.6.2 to iOS 7 (beta) device A: For me, updating to iTunes 11.1.1 fixed this. The device has 7.0.2
doc_23534225
A: This isn't so much a Node question as it is a Javascript question, as the part you need help with is executed on the client side. Take a look at this question: jQuery get textarea text. It seems to be exactly what you're looking for. I just want to add - you really should learn something like Express and its res.render() function using templates. Writing HTML and Javascript in Javascript is not a good way to accomplish what you want. A: Theres a few things wrong. Body Parser should be used like this app.use(bodyParser.urlencoded({extended: false})); Your form should specify the method method="post" Your input element should use the name attribute as this is what gets passed to the server when the form is submitted <input type="text" class="form-control" id="inputphonenumber" name="inputphonenumber" put the closing form tag after the submit button <button type="submit" class="btn btn-primary">Submit</button></form> Dont write your html code as one big var :) A: Sending HTML as a long string is a really bad practice. But I guess you can just use plain Javascript to achieve what you want. Just use the following result += '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">'; result += '<link rel="stylesheet" href="https://bootswatch.com/cerulean/bootstrap.min.css">'; result += '<title> Demo </title>'; /* result += '<script type="text/javascript"> function take_number() {'; result += 'phone_number = document.getElementById("inputphonenumber")'; result += 'console.log(phone_number); '; result += 'console.log(ok);} </script>'; result += '<script type="text/javascript"> console.log("test");'; */ result += '</head><body><br /><br /><br /><div class="container">'; result += '<form class="form-horizontal"><fieldset><legend> Demo </legend>'; result += '<br /><h2><center>Please enter your Phone Number</center></h2> <br /> <br />'; result += '<div class="col-lg-2 col-lg-offset-5">'; result += '<input type="text" class="form-control" id="inputphonenumber" placeholder="+33XXXXXXXXX"></div>'; result += '</fieldset></form></div><br /><br /><br />'; result += '<div class="form-group"><div class="col-lg-10 col-lg-offset-6">'; result += '<button type="reset" class="btn btn-default">Cancel</button>'; result += '<button type="submit" class="btn btn-primary" onclick="alertNumber()">Submit</button></div></div>'; result += '<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>'; result += '<script> function alertNumber() {var input = document.getElementById("inputphonenumber").value; alert("You have entered your number: " + input);}</script>'; result += '</body></html>';
doc_23534226
Using UnAuthenticatedServerOAuth2AuthorizedClientRepository I get serverWebExchange must be null, and using AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository I get principalName must be null. Using https://www.baeldung.com/spring-webclient-oauth2 works as long as I call the client as a CommandLineRunner. None of the other suggestions I have found here on stackoverflow has worked. What am I missing here? I am using Spring Security 5.2.0 and Spring Boot 2.2.0. ClientConfig: @Configuration public class ClientSecurityConfig { // UnAuthenticatedServerOAuth2AuthorizedClientRepository version @Bean WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations) { ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, new UnAuthenticatedServerOAuth2AuthorizedClientRepository()); return WebClient.builder() .filter(oauth) .build(); } @Bean ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider(CustomClientConfig clientConfig) { return ReactiveOAuth2AuthorizedClientProviderBuilder.builder() .clientCredentials(clientCredentialsGrantBuilder -> clientCredentialsGrantBuilder.accessTokenResponseClient(new CustomClient(clientConfig))) // Used to send extra parameters to adfs server .build(); } // AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository version @Bean WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) { ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); return WebClient.builder() .filter(oauth) .build(); } } @Bean ReactiveOAuth2AuthorizedClientManager authorizedClientManager( ReactiveClientRegistrationRepository clientRegistrationRepository, ServerOAuth2AuthorizedClientRepository authorizedClientRepository, CustomClientConfig clientConfig) { ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() .clientCredentials(clientCredentialsGrantBuilder -> clientCredentialsGrantBuilder.accessTokenResponseClient(new CustomClient(clientConfig))) // Used to send extra parameters to adfs server .build(); DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager(clientRegistrationRepository, authorizedClientRepository); authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); return authorizedClientManager; } } ResourceServerConfig: @EnableWebFluxSecurity class ResourceServerConfig { @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http .authorizeExchange(exchanges -> exchanges .pathMatchers("/actuators/**", "/api/v1").permitAll() .pathMatchers("/api/v1/**").hasAuthority("SCOPE_read") .anyExchange().authenticated() ) .formLogin().disable() .httpBasic().disable() .oauth2Client(withDefaults()) .oauth2ResourceServer().jwt(); return http.build(); } @RestController() @RequestMapping("/api/v1") static class Ctrl { final static Logger logger = LoggerFactory.getLogger(Ctrl.class); final WebClient webClient; public Ctrl(WebClient webClient) { this.webClient = webClient; } @RequestMapping("protected") Mono<JsonNode> protected(@RequestParam String data) { return webClient.post() .uri("https://other-oauth2-protected-resource") .attributes(clientRegistrationId("myclient")) .bodyValue("{\"data\": \"" + data + "\"}") .retrieve() .bodyToMono(JsonNode.class); } } } application.yml: spring: security: oauth2: resourceserver: jwt: issuer-uri: http://adfsserver.com/adfs/services/trust jwk-set-uri: https://adfsserver.com/adfs/discovery/keys client: registration: myclient: provider: adfs client-id: <client-id> client-secret: <client-secret> authorization-grant-type: client_credentials scope: read provider: adfs: token-uri: https://adfsserver.com/adfs/oauth2/token jwk-set-uri: https://adfsserver.com/adfs/discovery/keys A: This has recently been fixed by the Spring Project Contributors as part of this PR but unfortunately the official Spring doc is not yet updated. The normal servlet approach doc is here If you prefer to choose the "reactive" approach, then configuring a webclient requires only two beans: * *the AuthorizedClientManager Bean, and *the webClient Bean @Bean public ReactiveOAuth2AuthorizedClientManager authorizedClientManager( ReactiveClientRegistrationRepository clientRegistrationRepository, ReactiveOAuth2AuthorizedClientService authorizedClientService) { ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder() .clientCredentials() .build(); AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( clientRegistrationRepository, authorizedClientService); authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); return authorizedClientManager; } @Bean public WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) { ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); return WebClient.builder().filter(oauth).build(); } You can refer to my Github Gist which has all the required configuration.
doc_23534227
Thanks in advance! <ControlTemplate TargetType="{x:Type local:OperationModeIndicator}"> <Grid x:Name="rootGrid" RenderTransformOrigin="0.5,0.525"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="OperationModeStates"> <VisualState x:Name="None"> <Storyboard> <StringAnimationUsingKeyFrames Storyboard.TargetName="contentLabel" Storyboard.TargetProperty="Content" > <DiscreteStringKeyFrame Value="" /> </StringAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(RotateTransform.Angle)" Storyboard.TargetName="rootGrid" > <EasingDoubleKeyFrame KeyTime="0" Value="0"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(RotateTransform.Angle)" Storyboard.TargetName="contentLabel"> <EasingDoubleKeyFrame KeyTime="0" Value="0"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Automatic"> <Storyboard> <StringAnimationUsingKeyFrames Storyboard.TargetName="contentLabel" Storyboard.TargetProperty="Content" > <DiscreteStringKeyFrame Value="A" /> </StringAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(RotateTransform.Angle)" Storyboard.TargetName="rootGrid"> <EasingDoubleKeyFrame KeyTime="0" Value="-30"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(RotateTransform.Angle)" Storyboard.TargetName="contentLabel"> <EasingDoubleKeyFrame KeyTime="0" Value="30"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Grid.RenderTransform> <TransformGroup> <RotateTransform/> </TransformGroup> </Grid.RenderTransform> <Label x:Name="contentLabel" Foreground="#FFDA1D1D" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="48" RenderTransformOrigin="0.5,0.525" > <Label.RenderTransform> <TransformGroup> <RotateTransform/> </TransformGroup> </Label.RenderTransform> </Label> <Path Stroke="Gray" StrokeThickness="5"> <Path.Data> <PathGeometry> <PathFigure StartPoint="35 10" > <ArcSegment Point="65 10" Size="45 45" RotationAngle="0" IsLargeArc="True" /> </PathFigure> </PathGeometry> </Path.Data> </Path> <Line X1="2.5" X2="2.5" Y1="0" Y2="20" StrokeThickness="5" Stroke="Gray" HorizontalAlignment="Center" /> </Grid> </ControlTemplate> A: The animation works as expected. It's Blend that doesn't show it. Anyway, the reason is still unknown.
doc_23534228
I have a problem using Bing Speech SDK in windows. I need to implement speech recognition in my c# application in windows. In my application, I start the recognition, then stop it, produce a response, say it using a TTS, then start listening again. I can use the library included in the Microsoft Cognitive SDK, called Microsoft.ProjectOxford.SpeechRecognition There are two functions in the library: StartMicAndRecognition() starts the recognition. EndMicAndRecognition() stops the recognition. The problem is: EndMicAndRecognition() does not stop the mic from recording and sending the data to the server. So when I start the mic again, it returns words that have been said before the start function is called. How can I stop the mic from recording? Where can I find the source code to this library? (The binary files are included in the SDK and not the source code). A: I think you need to release the micClient with the Dispose method. I use this procedure in my project and it never showed the error you encounter. Hope it can help.
doc_23534229
In a sense, I want to .find a sister. A: $('el').siblings('li'); or $('el').parent().find('li'); A: To traverse to a closest possible parent node $('.someclassname').closest('.parentclassname') And to find a node inside that $('.someclassname').closest('.parentclassname').find('.findwhatever') If the node you are finding is on same level of your current node say <div class="testcls"> <p class="child1">child1</p> <p>child2</p> </div> In above child2 is sibling of child1 so you can find such siblings using $('child1').siblings();
doc_23534230
I am planning to add our project a functionality which will provide users to upload their videos to YouTube directly without the need to logon to Youtube.com and upload it there. I tried creating a sample project using the codes on https://developers.google.com/youtube/v3/code_samples/dotnet But couldn't succeed. Then began googling for an example (working) but all the search results are for older versions of api, or copies of the codes in the link below. In nuget, there is a package: Google.GData.YouTube So, I created a project which has that package installed. What to do next? (.net sample on youtube api documentation not working with that package - Is that nuget package for v2 or smth?) A: NuGet package Google.GData.YouTube uses this API http://gdata.youtube.com/ which refers itself as v2.0. There is also NuGet Google.Apis.YouTube.v3 Client Library which uses YT v3 API. The example you are referring to is using this Client Library. A: Try to use "YouTube Direct Lite" you can read about it on the following link: https://code.google.com/p/youtube-direct-lite/ Also you can see the following video: https://www.youtube.com/watch?v=_ZE89VsBq3o
doc_23534231
like this: <select> <option id="US" value="US"> </option> <option id="Canada" value="Canada"> </option> </select> I want two things: * *I want to post request to server on selection of option *And I want to put html elements inside option Are these two things possible (for all browsers, especially modern browser)? A: Use change event on select. $('select').on('change', function() { $.ajax({ url: '', data: { ... } }); }); Embedding HTML inside option.NOT RECOMMENDED $('option:first').html('<div>Hello</div>'); A: If you are using jquery : $(function() { $('select').on('change', function() { $.post('your/path', $(this).val(), function(data) { var option = $('select option[value="'+$('select').val()+'"]'); // Do what you want with your option }; }); });
doc_23534232
my xaml is like bellow and work fine: <TextBlock x:Name="timer_check_version" Text="60" HorizontalAlignment="Center" FontSize="18"> <TextBlock.Foreground> <SolidColorBrush x:Name="tbBrush" Color="#1e7145"/> </TextBlock.Foreground> <TextBlock.Style> <Style TargetType="TextBlock"> <Style.Triggers> <Trigger Property="Visibility" Value="Visible"> <Trigger.EnterActions> <BeginStoryboard Storyboard="{StaticResource ChronometerStoryboard}"/> </Trigger.EnterActions> </Trigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock> and my ChronometerStoryboard is: <Storyboard x:Key="ChronometerStoryboard"> <ColorAnimation To="#b91d47" From="#1e7145" Duration="0:0:59" Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)"/> <StringAnimationUsingKeyFrames Storyboard.TargetProperty="(TextBlock.Text)"> <DiscreteStringKeyFrame KeyTime="0:0:1" Value="59"/> <DiscreteStringKeyFrame KeyTime="0:0:2" Value="58"/> <DiscreteStringKeyFrame KeyTime="0:0:3" Value="57"/> <DiscreteStringKeyFrame KeyTime="0:0:4" Value="56"/> <DiscreteStringKeyFrame KeyTime="0:0:5" Value="55"/> <DiscreteStringKeyFrame KeyTime="0:0:6" Value="54"/> <DiscreteStringKeyFrame KeyTime="0:0:7" Value="53"/> <DiscreteStringKeyFrame KeyTime="0:0:8" Value="52"/> <DiscreteStringKeyFrame KeyTime="0:0:9" Value="51"/> <DiscreteStringKeyFrame KeyTime="0:0:10" Value="50"/> ...... ...... ...... ...... <DiscreteStringKeyFrame KeyTime="0:0:51" Value="09"/> <DiscreteStringKeyFrame KeyTime="0:0:52" Value="08"/> <DiscreteStringKeyFrame KeyTime="0:0:53" Value="07"/> <DiscreteStringKeyFrame KeyTime="0:0:54" Value="06"/> <DiscreteStringKeyFrame KeyTime="0:0:55" Value="05"/> <DiscreteStringKeyFrame KeyTime="0:0:56" Value="04"/> <DiscreteStringKeyFrame KeyTime="0:0:57" Value="03"/> <DiscreteStringKeyFrame KeyTime="0:0:58" Value="02"/> <DiscreteStringKeyFrame KeyTime="0:0:59" Value="01"/> </StringAnimationUsingKeyFrames> </Storyboard> the goal of above sample is to display a message to users for 60 seconds with TextBlock that counting down from 60 to 1,after 60 seconds the message and timer should be invisible and after some times according to background Threads the display of message and timer(TextBlock that counting down from 60 to 1) should be repeat,this may repeat for some times, all things work fine for first,but first the timer comes to 1,my message and timer collapsed for some minute(according to background threads) and when background threads completed i want to repeat the display of message and timer for 60 second again,but my problem is the timer value equals to 1 and timer Foreground equals to Red and no animated. A: Apply AutoReverse and RepeatBeahvior attributes. AutoReverse will make your storyboard goes exact reverse making your text color changing from Red to Green, and RepeatBehavior will make this to and fro color change continuing forever. You can choose various RepeatBehavior settings according to your need. <Storyboard x:Key="ChronometerStoryboard" AutoReverse="True" RepeatBehavior="Forever"> In reply to your comment : "the visible and invisible of textblock may repeate forever and to time of invisible is random and after each visible it must start from 59 to 1 and it's foreground must start from green to red" Use a Behavior called ControlStoryBoardAction which is present in Blend. And use it to play your storyboard. Complete sample code might look like : <UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" mc:Ignorable="d" x:Class="S32494473W.Chronometer" x:Name="UserControl" d:DesignWidth="632" d:DesignHeight="392"> <UserControl.Resources> <Storyboard x:Key="ChronometerStoryboard"> <ColorAnimation To="#b91d47" From="#1e7145" Duration="0:0:10" Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)" Storyboard.TargetName="timer_check_version"/> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(TextBlock.Visibility)" Storyboard.TargetName="timer_check_version"> <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Visibility.Visible}"/> </ObjectAnimationUsingKeyFrames> <StringAnimationUsingKeyFrames Storyboard.TargetProperty="(TextBlock.Text)" Storyboard.TargetName="timer_check_version"> <DiscreteStringKeyFrame KeyTime="0:0:1" Value="10"/> <DiscreteStringKeyFrame KeyTime="0:0:2" Value="9"/> <DiscreteStringKeyFrame KeyTime="0:0:3" Value="8"/> <DiscreteStringKeyFrame KeyTime="0:0:4" Value="7"/> <DiscreteStringKeyFrame KeyTime="0:0:5" Value="6"/> <DiscreteStringKeyFrame KeyTime="0:0:6" Value="5"/> <DiscreteStringKeyFrame KeyTime="0:0:7" Value="4"/> <DiscreteStringKeyFrame KeyTime="0:0:8" Value="3"/> <DiscreteStringKeyFrame KeyTime="0:0:9" Value="2"/> <DiscreteStringKeyFrame KeyTime="0:0:10" Value="1"/> </StringAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(TextBlock.Visibility)" Storyboard.TargetName="timer_check_version"> <DiscreteObjectKeyFrame KeyTime="0:0:10" Value="{x:Static Visibility.Hidden}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </UserControl.Resources> <Grid x:Name="LayoutRoot"> <Button Content="Chronometer" Height="32" Margin="272,8,272,0" VerticalAlignment="Top" Click="Button_Click"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <ei:ControlStoryboardAction Storyboard="{StaticResource ChronometerStoryboard}"/> </i:EventTrigger> </i:Interaction.Triggers> </Button> <TextBlock x:Name="timer_check_version" Width="100" Background="AliceBlue" Text="10" Visibility="Hidden" HorizontalAlignment="Center" FontSize="18" VerticalAlignment="Center"> <TextBlock.Foreground> <SolidColorBrush x:Name="tbBrush" Color="#1e7145"/> </TextBlock.Foreground> </TextBlock> </Grid> </UserControl> A: i change my trigger to : <Trigger Property="IsEnabled" Value="True"> <Trigger.EnterActions> <BeginStoryboard Storyboard="{StaticResource ChronometerStoryboard}" Name="st1"/> </Trigger.EnterActions> <Trigger.ExitActions> <StopStoryboard BeginStoryboardName="st1"/> </Trigger.ExitActions> </Trigger> and bind TextBlock.IsEnabled to it's Parent.Visibility and solved my problem.
doc_23534233
Error not related with any of my code at least from stack trace. From debug prints seems that it happen after page is loaded. Any thoughts? com.ibm.xsp.FacesExceptionEx: java.io.NotSerializableException: org.openntf.domino.impl.Document com.ibm.xsp.application.AbstractStateManager.saveSerializedView(AbstractStateManager.java:121) com.ibm.xsp.application.StateManagerImpl.saveSerializedView(StateManagerImpl.java:152) com.ibm.xsp.application.ViewHandlerExImpl._saveViewState(ViewHandlerExImpl.java:455) com.ibm.xsp.application.ViewHandlerExImpl.saveViewState(ViewHandlerExImpl.java:449) com.ibm.xsp.application.ViewHandlerExImpl._renderView(ViewHandlerExImpl.java:324) com.ibm.xsp.application.ViewHandlerExImpl.renderView(ViewHandlerExImpl.java:336) com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:103) com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:210) com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:120) com.ibm.xsp.controller.FacesControllerImpl.render(FacesControllerImpl.java:270) com.ibm.xsp.webapp.FacesServlet.serviceView(FacesServlet.java:261) com.ibm.xsp.webapp.FacesServletEx.serviceView(FacesServletEx.java:157) com.ibm.xsp.webapp.FacesServlet.service(FacesServlet.java:160) com.ibm.xsp.webapp.FacesServletEx.service(FacesServletEx.java:138) com.ibm.xsp.webapp.DesignerFacesServlet.service(DesignerFacesServlet.java:103) com.ibm.designer.runtime.domino.adapter.ComponentModule.invokeServlet(ComponentModule.java:588) com.ibm.domino.xsp.module.nsf.NSFComponentModule.invokeServlet(NSFComponentModule.java:1335) com.ibm.designer.runtime.domino.adapter.ComponentModule$AdapterInvoker.invokeServlet(ComponentModule.java:865) com.ibm.designer.runtime.domino.adapter.ComponentModule$ServletInvoker.doService(ComponentModule.java:808) com.ibm.designer.runtime.domino.adapter.ComponentModule.doService(ComponentModule.java:577) com.ibm.domino.xsp.module.nsf.NSFComponentModule.doService(NSFComponentModule.java:1319) com.ibm.domino.xsp.module.nsf.NSFService.doServiceInternal(NSFService.java:662) com.ibm.domino.xsp.module.nsf.NSFService.doService(NSFService.java:482) com.ibm.designer.runtime.domino.adapter.LCDEnvironment.doService(LCDEnvironment.java:357) com.ibm.designer.runtime.domino.adapter.LCDEnvironment.service(LCDEnvironment.java:313) com.ibm.domino.xsp.bridge.http.engine.XspCmdManager.service(XspCmdManager.java:272) java.io.NotSerializableException: org.openntf.domino.impl.Document java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1185) java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346) java.util.TreeMap.writeObject(TreeMap.java:5740) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37) java.lang.reflect.Method.invoke(Method.java:611) java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1059) java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1502) java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433) java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179) java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1555) java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1516) java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433) java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179) java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1555) java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1516) java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433) java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179) java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346) java.util.HashMap.writeObject(HashMap.java:942) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37) java.lang.reflect.Method.invoke(Method.java:611) java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1059) java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1502) java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433) java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179) java.io.ObjectOutputStream.writeUnshared(ObjectOutputStream.java:413) com.ibm.xsp.application.AbstractSerializingStateManager$FastObjectOutputStream.writeObjectEx(AbstractSerializingStateManager.java:438) com.ibm.xsp.application.AbstractSerializingStateManager$FastObjectOutputStream.writeObjectEx(AbstractSerializingStateManager.java:417) com.ibm.xsp.application.AbstractSerializingStateManager$FastObjectOutputStream.writeObjectEx(AbstractSerializingStateManager.java:417) com.ibm.xsp.application.AbstractSerializingStateManager$FastObjectOutputStream.writeObjectEx(AbstractSerializingStateManager.java:417) com.ibm.xsp.application.AbstractSerializingStateManager$FastObjectOutputStream.writeObjectEx(AbstractSerializingStateManager.java:417) com.ibm.xsp.application.AbstractSerializingStateManager.saveSerializedView(AbstractSerializingStateManager.java:294) com.ibm.xsp.application.AbstractSerializingStateManager.doSaveSerializedView(AbstractSerializingStateManager.java:269) com.ibm.xsp.application.FileStateManager.doSaveSerializedView(FileStateManager.java:290) com.ibm.xsp.application.FileStateManager.doSaveSerializedView(FileStateManager.java:270) com.ibm.xsp.application.AbstractStateManager.saveSerializedView(AbstractStateManager.java:114) com.ibm.xsp.application.StateManagerImpl.saveSerializedView(StateManagerImpl.java:152) com.ibm.xsp.application.ViewHandlerExImpl._saveViewState(ViewHandlerExImpl.java:455) com.ibm.xsp.application.ViewHandlerExImpl.saveViewState(ViewHandlerExImpl.java:449) com.ibm.xsp.application.ViewHandlerExImpl._renderView(ViewHandlerExImpl.java:324) com.ibm.xsp.application.ViewHandlerExImpl.renderView(ViewHandlerExImpl.java:336) com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:103) com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:210) com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:120) com.ibm.xsp.controller.FacesControllerImpl.render(FacesControllerImpl.java:270) com.ibm.xsp.webapp.FacesServlet.serviceView(FacesServlet.java:261) com.ibm.xsp.webapp.FacesServletEx.serviceView(FacesServletEx.java:157) com.ibm.xsp.webapp.FacesServlet.service(FacesServlet.java:160) com.ibm.xsp.webapp.FacesServletEx.service(FacesServletEx.java:138) com.ibm.xsp.webapp.DesignerFacesServlet.service(DesignerFacesServlet.java:103) com.ibm.designer.runtime.domino.adapter.ComponentModule.invokeServlet(ComponentModule.java:588) com.ibm.domino.xsp.module.nsf.NSFComponentModule.invokeServlet(NSFComponentModule.java:1335) com.ibm.designer.runtime.domino.adapter.ComponentModule$AdapterInvoker.invokeServlet(ComponentModule.java:865) com.ibm.designer.runtime.domino.adapter.ComponentModule$ServletInvoker.doService(ComponentModule.java:808) com.ibm.designer.runtime.domino.adapter.ComponentModule.doService(ComponentModule.java:577) com.ibm.domino.xsp.module.nsf.NSFComponentModule.doService(NSFComponentModule.java:1319) com.ibm.domino.xsp.module.nsf.NSFService.doServiceInternal(NSFService.java:662) com.ibm.domino.xsp.module.nsf.NSFService.doService(NSFService.java:482) com.ibm.designer.runtime.domino.adapter.LCDEnvironment.doService(LCDEnvironment.java:357) com.ibm.designer.runtime.domino.adapter.LCDEnvironment.service(LCDEnvironment.java:313) com.ibm.domino.xsp.bridge.http.engine.XspCmdManager.service(XspCmdManager.java:272) A: You cannot store any Domino object in a managed bean. As the method says, it's not serializable. ODA cannot work around that issue. My recommendation would be to store either the DominoDocument object (if you need the front-end document, so updating it during the life of the bean but not saving each time) or the UNID (if you just need the backend document). Database.getDocumentByUNID() is extremely fast, so you should not be concerned about the performance impacts of getting the document. If you want to avoid getting the document multiple times in the XPages lifecycle, put the resulting Document object in requestScope and check there before retrieving from the database. Alternatively (I'm not sure how best practice this is or if it is properly cleaned up) it may be an option to set the variable to transient, so it will not be serialized at the end of each request, but will be held in the bean for the duration of each partial refresh.
doc_23534234
Each time I initialise the queue it is empty in the constructor but returns a non-zero size when I call the class method size(). Here is a MWE: / TEST QUEUE #include<iostream> #include<queue> #include<mutex> #include<condition_variable> #include <Eigen/Dense> template <class dtype> class Queue { private: std::queue<dtype> q; std::mutex qmtx; std::condition_variable qcond; bool start = false; bool display = false; public: Queue(bool sstart, bool qdisplay) : start(sstart), display(qdisplay) { std::clog << "In q constructor: " << q.size() << std::endl; } // Method to push values on to queue void push(const dtype & message); dtype pop(); void stop(); bool empty(); bool size(); bool clear(); }; And my .cpp template<typename dtype> dtype Queue<dtype>::pop() { std::unique_lock<std::mutex> lock(qmtx); qcond.wait(lock, [&]() { return !q.empty() | start; } ); if (!start) { std::clog << "The queue has stopped popping." << std::endl; } dtype ret = q.front(); q.pop(); return ret; } // Method to push values on to queue template<typename dtype> void Queue<dtype>::push(const dtype & message) { std::unique_lock<std::mutex> lock(qmtx); if (display) { std::clog << "Qpush Locked." << std::endl; } q.push(message); qcond.notify_one(); } template<typename dtype> void Queue<dtype>::stop() { start = false; qcond.notify_all(); } template<typename dtype> bool Queue<dtype>::empty() { std::unique_lock<std::mutex> lock(qmtx); q.empty(); } template<typename dtype> bool Queue<dtype>::size() { std::unique_lock<std::mutex> lock(qmtx); q.size(); } template<typename dtype> bool Queue<dtype>::clear() { std::unique_lock<std::mutex> lock(qmtx); std::queue<dtype> empty; std::swap(q, empty); } int main () { Queue<Eigen::VectorXd> YQ(false, false); std::cout << YQ.size() << std::endl; } I am not sure what else to write?
doc_23534235
I just want to create a vbs to make my mongodb run automatically once server reboots. My mongod.exe is in the folder: d:\bos\mongodb\bin\mongod.exe My mongodb data is in the folder: d:\bos\data\db I try to write the vbs like this: Set ws = CreateObject("WScript.Shell") 'this one for my nodejs service, and it works ws.Run "CMD /C supervisor ""E:\Inetpub\wwwroot\bos\app.js""" ws.Run "CMD /C d:\bos\mongodb\bin\mongod.exe --dbpath d:\bos\data\db" And I also try to install the mongodb as Windows services, and it doesn't work at all. d:\bos\mongodb\bin>mongod.exe --install --logpath d:\bos\mongodb\logs\MongoDB.Log -- dbpath d:\bos\data\db --directoryperdb --serviceName MongoDB --serviceDisplayName MongoDB It doesn't work, could anybody help me please? Thanks in advance! Best Regards ShengXing Chi A: * *You should be ashamed of trying to get away with a 'problem description' like "it does not work" twice! *The first "it does not work" may well be explained by the "bin>mo" instead of "bin\mo" in your command. Or did you not copy it, but typed it in from memory? *To troubleshoot the second "it does not work" you should: wtf * *execute the command from a console (fix errors until it succeeds) *think about permissions (console user vs script user) *use ws.Run "%comspec% /K d:\bos... in your script *think about 64/32 bit issues
doc_23534236
curl https://domain.com/dir/filename --resolve "domain.com:443:10.10.10.10" Since this is ssl I want to avoid substituting in the IP for the domain as in the following example. curl https://10.10.10.10/dir/filename --header "Host: domain.com" A: OneOfOne's answer above is excellent. I am posting the full working package code here to make it easier for noobs like me. I added a couple of println so that you could see the addr value before and after modification. package main import ( "context" "fmt" "log" "net" "net/http" "time" ) func main() { dialer := &net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, } // or create your own transport, there's an example on godoc. http.DefaultTransport.(*http.Transport).DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { fmt.Println("address original =", addr) if addr == "google.com:443" { addr = "216.58.198.206:443" fmt.Println("address modified =", addr) } return dialer.DialContext(ctx, network, addr) } resp, err := http.Get("https://google.com") log.Println(resp.Header, err) } A: You can provide a custom Transport.DialContext function. func main() { dialer := &net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, // DualStack: true, // this is deprecated as of go 1.16 } // or create your own transport, there's an example on godoc. http.DefaultTransport.(*http.Transport).DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { if addr == "google.com:443" { addr = "216.58.198.206:443" } return dialer.DialContext(ctx, network, addr) } resp, err := http.Get("https://google.com") log.Println(resp.Header, err) }
doc_23534237
A: The iodelay toolbox is available for Scilab: https://atoms.scilab.org/toolboxes/iodelay
doc_23534238
The result set is a one line concatenation, and I want it to be place in every one of the overall result set lines. ---- MAIN QUERY SELECT H.CONNECTION_ID, H.SEQUENTIAL_NO, H.INVOICE_NUMBER, H.INVOICE_DATE, H.LAST_INVOICE_NUMBER, H.LAST_INVOICE_DATE, CAST(CASE WHEN H.COLLECT_DEPOSIT = 1 THEN '-' ELSE CAST(H.PAYMENT_DUE_DATE AS NVARCHAR(20)) END AS SMALLDATETIME) AS PAYMENT_DUE, H.JOB_NUMBER, H.CUST_JOB_NUMBER, HDR.SALES_PERSON, H.INSIDE_SALES_PERSON, H.IS_LAST_INVOICE, CASE WHEN H.COLLECT_DEPOSIT = 1 THEN 'CASH' ELSE H.PAYMENT_TERMS_DESCRIPTION END AS PAYMENT_TERMS, H.PRINTED, H.NOTES, CUR.ID, CUR.CODE, CASE CUR.CODE WHEN 'USD' THEN '001-106624-211' WHEN 'EUR' THEN '001-106624-101' WHEN 'GBP' THEN '001-106624-100' ELSE '001-106624-001' END AS BANK_ACCT, CUR.EXCHANGE_RATE, H.BILL_CONTACT, H.CUST_ACCOUNT, H.CUST_NAME, H.CUST_ADDR1, H.CUST_ADDR2, H.CUST_CITY, H.CUST_STATE, H.CUST_ZIP, H.CONTACT_PHONE_NUMBER, H.CONTACT_PHONE_NUMBER2, H.ORDERED_BY_CONTACT, H.SHIP_TO_NAME, H.SHIP_TO_ADDR1, H.SHIP_TO_ADDR2, H.SHIP_TO_CITY, H.SHIP_TO_STATE, H.SHIP_TO_ZIP, H.SITE_PHONE_NUMBER, H.SITE_PHONE_NUMBER2, H.OFFICE_NAME, H.OFFICE_ADDR1, H.OFFICE_ADDR2, H.OFFICE_CITY, H.OFFICE_STATE, H.OFFICE_ZIP, H.OFFICE_PHONE_NUMBER, H.OFFICE_FAX_NUMBER, H.DELIVERY_TICKET_NUMBER, H.PO_NUMBER, H.DUMMY_INVOICE_TEXT, (SELECT MESSAGE FROM REPORT_MESSAGES WHERE CODE = 'INVOICE') ADVERT_MESSAGE, (SELECT MAX(DISCOUNT_PERCENTAGE) FROM PRTINVITEM I2 WHERE I2.CONNECTION_ID = H.CONNECTION_ID AND I2.INVOICE_NUMBER = H.INVOICE_NUMBER) AS MAX_DISCOUNT, I.ITEM, I.DESCRIPTION, I.QUANTITY, I.UNIT_OF_MEASURE, I.MINIMUM_CHARGE, I.WEEKLY_CHARGE, I.MONTHLY_CHARGE, I.START_OF_BILLING_PERIOD, I.END_OF_BILLING_PERIOD, I.DAYS_USED, I.WEEKS_USED, I.DISCOUNT_PERCENTAGE, I.TAX_CODE_FOR_ITEM, I.INVENTORY_TYPE, I.BILLING_LOGIC_TYPE, I.ACTUAL_WEEKLY_CHARGE_USED, I.DAYS_IN_ACTUAL_WEEKLY_CHARGE, II.CHARGEABLE_DAYS, II.CHARGEABLE_WEEKS, II.CHARGEABLE_MONTHS, II.FREE_DAYS_THIS_INVOICE, CNV.TOTAL_NET_VALUE, CNV.TOTAL_TAX_VALUE, CNV.TOTAL_GROSS_VALUE, CNV.TOTAL_GROSS_VALUE_NS, CNV.NET_LINE_VALUE, CMP.EMAIL_ADDRESS FROM (PRTINVHDR H INNER JOIN PRTINVITEM I ON H.CONNECTION_ID = I.CONNECTION_ID AND H.INVOICE_NUMBER = I.INVOICE_NUMBER) INNER JOIN INVOICEHDR HDR ON I.INVOICE_NUMBER = HDR.INVNO INNER JOIN CUSTOMERS CST ON H.CUST_ACCOUNT = CST.CUSTNUM INNER JOIN JOB JOB ON H.JOB_NUMBER = JOB.JOBNUM INNER JOIN CURRENCY CUR ON HDR.CURRENCY_ID = CUR.ID INNER JOIN VWCURRENCYCONVERSION CNV ON I.CONNECTION_ID = CNV.CONNECTION_ID AND I.INVC_UCOUNTER = CNV.INVC_UCOUNTER INNER JOIN COMPANY CMP ON H.OFFICE_CODE = CMP.OFFICE INNER JOIN INVOICEITEM II ON I.INVOICE_NUMBER = II.INVNO AND I.INVC_UCOUNTER = II.INVC_UCOUNTER ORDER BY H.SEQUENTIAL_NO, I.PRINT_SEQUENCE ASC ---- COALESCE QUERY DECLARE @DTICKET NVARCHAR(20), @PUMPCATEGORYNAME NVARCHAR(3999) SET @DTICKET = '' SET @PUMPCATEGORYNAME = NULL (SELECT @DTICKET = DTICKET, @PUMPCATEGORYNAME = COALESCE(@PUMPCATEGORYNAME + ', ', '' ) + PUMPCATEGORYNAME FROM (SELECT BHDR.DTICKET, SCD.PUMPCATEGORYNAME FROM PRTTICKHDR PHDR INNER JOIN BIDHDR BHDR ON PHDR.DELIV_TICKET_NUMBER = BHDR.DTICKET INNER JOIN PRTTICKITEM PITM ON PHDR.CONNECTION_ID = PITM.CONNECTION_ID AND PHDR.DELIV_TICKET_NUMBER = PITM.DELIV_TICKET_NUMBER LEFT JOIN SUBCATEGORYDESCRIPTION SCD ON PITM.ITEM = SCD.PUMPCATEGORY WHERE SCD.PUMPCATEGORYNAME IS NOT NULL) SUBCATEGORYDESCRIPTION) SELECT @DTICKET, @PUMPCATEGORYNAME A: Not really sure what you are asking for but you can doing something along the lines of Select col1 + ', ' + col2 + ', ' + col3 etc....
doc_23534239
{ "status": "ok", "post": { "id": 25, "type": "post", "slug": "price-list", "url": "http://example.com/2016/02/10/post-title/", "status": "publish", "title": "title", "title_plain": "title", "content": "", "excerpt": "", "date": "2016-02-10 12:23:40", "modified": "2016-06-01 06:27:39", "categories": [], "tags": [], "author": { "id": 1, "slug": "slug", "name": "name", "first_name": "first name", "last_name": "last name", "nickname": "nickname", "url": "", "description": "descp" }, "comments": [], "attachments": [], "comment_count": 0, "comment_status": "open", "custom_fields": { "Regular 95": [ "34200:1" ], "Super 98": [ "34900:0" ], "Gasoil": [ "26100:-1" ], "Diesel": [ "26200:1" ], "Kerosene": [ "20100:-1" ], "Fuel / Ton": [ "773.30:0" ] } }, "previous_url": "http://example.com/2016/02/10/post-title/", "next_url": "http://example.com/2016/02/10/post-title/" } A: Used $.each $.each(response.post.custom_fields, function( index, value ) { console.log( index + ": " + value ); }); $(document).ready(function(){ var response={ "status": "ok", "post": { "id": 25, "type": "post", "slug": "price-list", "url": "http://example.com/2016/02/10/post-title/", "status": "publish", "title": "title", "title_plain": "title", "content": "", "excerpt": "", "date": "2016-02-10 12:23:40", "modified": "2016-06-01 06:27:39", "categories": [], "tags": [], "author": { "id": 1, "slug": "slug", "name": "name", "first_name": "first name", "last_name": "last name", "nickname": "nickname", "url": "", "description": "descp" }, "comments": [], "attachments": [], "comment_count": 0, "comment_status": "open", "custom_fields": { "Regular 95": [ "34200:1" ], "Super 98": [ "34900:0" ], "Gasoil": [ "26100:-1" ], "Diesel": [ "26200:1" ], "Kerosene": [ "20100:-1" ], "Fuel / Ton": [ "773.30:0" ] } }, "previous_url": "http://example.com/2016/02/10/post-title/", "next_url": "http://example.com/2016/02/10/post-title/" }; $.each(response.post.custom_fields, function( index, value ) { console.log( index + ": " + value ); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> A: From w3c doc, diferents ways to accessing JavaScript Properties: objectName.property // person.age objectName["property"] // person["age"] objectName[expression] // x = "age"; person[x] The expression must evaluate to a property name. You can use chaining with nested objects objectName.internalObject.property
doc_23534240
A: The best age validation I have ever come up with is based on Regex. The below logic covers all the breakpoint related age. // regex for validation of date format : dd.mm.yyyy, dd/mm/yyyy, dd-mm-yyyy RegExp regExp = new RegExp( r"^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$", caseSensitive: true, multiLine: false, ); //method to calculate age on Today (in years) int ageCalculate(String input){ if(regExp.hasMatch(input)){ DateTime _dateTime = DateTime( int.parse(input.substring(6)), int.parse(input.substring(3, 5)), int.parse(input.substring(0, 2)), ); return DateTime.fromMillisecondsSinceEpoch( DateTime.now().difference(_dateTime).inMilliseconds) .year - 1970; } else{ return -1; } } void main() { // input values and validations examples var input = "29.02.2008"; print("12.13.2029 : " + regExp.hasMatch("12.13.2029").toString()); print("29.02.2028 : " + regExp.hasMatch("29.02.2028").toString()); print("29.02.2029 : " + regExp.hasMatch("29.02.2029").toString()); print("11/12-2019 : " + regExp.hasMatch("11/12-2019").toString()); print("23/12/2029 : " + regExp.hasMatch("23/12/2029").toString()); print("23/12/2029 : " + regExp.hasMatch(input).toString()); print("sdssh : " + regExp.stringMatch("sdssh").toString()); print("age as per 29.02.2008 : " + ageCalculate(input).toString()); } Output 12.13.2029 : false 29.02.2028 : true 29.02.2029 : false 11/12-2019 : false 23/12/2029 : true 23/12/2029 : true sdssh : null age as per 29.02.2008 : 12 I hope you will find this useful. :) A: Package To easily parse date we need package intl: https://pub.dev/packages/intl#-installing-tab- So add this dependency to youd pubspec.yaml file (and get new dependencies) Solution #1 You can just simple compare years: bool isAdult(String birthDateString) { String datePattern = "dd-MM-yyyy"; DateTime birthDate = DateFormat(datePattern).parse(birthDateString); DateTime today = DateTime.now(); int yearDiff = today.year - birthDate.year; int monthDiff = today.month - birthDate.month; int dayDiff = today.day - birthDate.day; return yearDiff > 18 || yearDiff == 18 && monthDiff >= 0 && dayDiff >= 0; } But it's not always true, because to the end of current year you are "not adult". Solution #2 So better solution is move birth day 18 ahead and compare with current date. bool isAdult2(String birthDateString) { String datePattern = "dd-MM-yyyy"; // Current time - at this moment DateTime today = DateTime.now(); // Parsed date to check DateTime birthDate = DateFormat(datePattern).parse(birthDateString); // Date to check but moved 18 years ahead DateTime adultDate = DateTime( birthDate.year + 18, birthDate.month, birthDate.day, ); return adultDate.isBefore(today); } A: You can use an extension to add a function that checks this to DateTime. For example: extension DateTimeX on DateTime { bool isUnderage() => (DateTime(DateTime.now().year, this.month, this.day) .isAfter(DateTime.now()) ? DateTime.now().year - this.year - 1 : DateTime.now().year - this.year) < 18; } void main() { final today = DateTime.now(); final seventeenY = DateTime(today.year - 18, today.month, today.day + 1); final eighteenY = DateTime(today.year - 18, today.month, today.day); print(today.isUnderage()); print(seventeenY.isUnderage()); print(eighteenY.isUnderage()); } It's worth noting this doesn't require intl or any other external package. Paste this right into dartpad.dev to test it out. A: You can find year difference in following way. String _data = '16-04-2000'; DateTime _dateTime = DateTime( int.parse(_data.substring(6)), int.parse(_data.substring(3, 5)), int.parse(_data.substring(0, 2)), ); int yeardiff = DateTime.fromMillisecondsSinceEpoch( DateTime.now().difference(_dateTime).inMilliseconds) .year - 1970; print(yeardiff); A: import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Home(), ); } } class Home extends StatefulWidget { Home({Key key}) : super(key: key); _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { String dateFormate; @override Widget build(BuildContext context) { var dateNow = new DateTime.now(); var givenDate = "1969-07-20"; var givenDateFormat = DateTime.parse(givenDate); var diff = dateNow.difference(givenDateFormat); var year = ((diff.inDays)/365).round(); return Container( child: (year < 18)?Text('You are under 18'):Text("$year years old"), ); } } A: It is quite simple if you are using intl package. Be sure you have set the same format for your date picker and the function in which you are validating the age. You can use the following code for calculating the difference between today's date and entered date: double isAdult(String enteredAge) { var birthDate = DateFormat('MMMM d, yyyy').parse(enteredAge); print("set state: $birthDate"); var today = DateTime.now(); final difference = today.difference(birthDate).inDays; print(difference); final year = difference / 365; print(year); return year; } And the you can create a condition on the returned value of the function like: Container( child: (isAdult(selecteddate) < 18 ? Text("You are under age") : Text("$selecteddate is your current age") ) A: There are 6570 days in 18 years. So I created a simple operation to check if entered date is greater than 6570 days comparing to difference of today's date. DateTime.now().difference(date) < Duration(days: 6570) if this is true, then user is younger than 18 years old, if it is not, then user is older than 18 years old. Works on days too. This is my if blocks: if (DateTime.now().difference(date) < Duration(days: 6570)) { EasyLoading.showError('You should be 18 years old to register');} else { store.changeBirthday(date);} A: import 'package:intl/intl.dart'; void main() { print(_isAdult('12-19-2004') ? 'over 18' : 'under 18'); } bool _isAdult(String dob) { final dateOfBirth = DateFormat("MM-dd-yyyy").parse(dob); final now = DateTime.now(); final eighteenYearsAgo = DateTime( now.year - 18, now.month, now.day + 1, // add day to return true on birthday ); return dateOfBirth.isBefore(eighteenYearsAgo); } Similar to @Broken's accepted answer but I think this is more readable. Test on DartPad https://dartpad.dev/?id=53885d812c90230f2a5b786e75b6cd82
doc_23534241
A: You can use the runmqsc command to view and administer IBM MQ from the command prompt or a script (For example Powershell or a Batch file). To display all subscriptions to a topic: echo DIS SUB(*) WHERE(TOPICSTR EQ 'Some/Topic/String') | runmqsc QMGRNAME To delete a subscription: echo DELETE SUB('SUBSCRIPTION.NAME') | runmqsc QMGRNAME A: Maybe (although withdrawn) SupportPac MA01 = q.exe can also help you. Works fast but the parameters are a bit tricky
doc_23534242
I've built a simple Flash application via FlashDevelop (AS3) and I want it to communicate to a Server. I created then a simple Socket Java Application with the code: Main.java: import org.xsocket.connection.*; public class Main { protected static IServer srv = null; public static void main(String[] args) { try { srv = new Server(8090, new xSocketDataHandler()); srv.run(); } catch(Exception ex) { System.out.println(ex.getMessage()); } } protected static void shutdownServer() { try { srv.close(); } catch(Exception ex) { System.out.println(ex.getMessage()); } } } and xSocketDataHandler.java: import java.io.IOException; import java.nio.BufferUnderflowException; import java.nio.channels.ClosedChannelException; import java.util.*; import org.xsocket.*; import org.xsocket.connection.*; public class xSocketDataHandler implements IDataHandler, IConnectHandler, IDisconnectHandler { private Set<INonBlockingConnection> sessions = Collections.synchronizedSet(new HashSet<INonBlockingConnection>()); public boolean onData(INonBlockingConnection nbc) throws IOException, BufferUnderflowException, ClosedChannelException, MaxReadSizeExceededException { try { String data = nbc.readStringByDelimiter("\0"); if(data.trim().length() > 0) { System.out.println("Incoming data: " + data); if(data.equalsIgnoreCase("<policy-file-request/>")) { nbc.write("<cross-domain-policy>" + "<allow-access-from domain=\"*\" secure=\"false\" />" + "<allow-access-from domain=\"*\" to-ports=\"8090\"/>" + "</cross-domain-policy>\0"); return true; } String[] message = data.split("~"); sendMessageToAll(nbc, message[0], message[1]); if(message[1].equalsIgnoreCase("SHUTDOWN")) Main.shutdownServer(); } } catch(Exception ex) { System.out.println("onData: " + ex.getMessage()); } return true; } private void sendMessageToAll(INonBlockingConnection nbc, String user, String message) { try { synchronized(sessions) { Iterator<INonBlockingConnection> iter = sessions.iterator(); while(iter.hasNext()) { INonBlockingConnection nbConn = (INonBlockingConnection) iter.next(); if(nbConn.isOpen()) nbConn.write("<b>" + user + "</b>: " + message + "<br />\0"); } } System.out.println("Outgoing data: " + user + ": " + message); } catch(Exception ex) { System.out.println("sendMessageToAll: " + ex.getMessage()); } } public boolean onConnect(INonBlockingConnection nbc) throws IOException, BufferUnderflowException, MaxReadSizeExceededException { try { synchronized(sessions) { sessions.add(nbc); } System.out.println("onConnect"); } catch(Exception ex) { System.out.println("onConnect: " + ex.getMessage()); } return true; } public boolean onDisconnect(INonBlockingConnection nbc) throws IOException { try { synchronized(sessions) { sessions.remove(nbc); } System.out.println("onDisconnect"); } catch(Exception ex) { System.out.println("onDisconnect: " + ex.getMessage()); } return true; } } So, the problem is: I start the Java Application, and it runs perfectly. I start my Flash application and It runs, creates the socket object, connects to my server (all in my computer) the server gets the connection attempt but, at: nbc.readStringByDelimiter("\0"); it says that nbc is closed, and the server catches the exception: "onData: channel is closed (read buffer size=0)" Does anyone knows why always I get this? Doesn't matter how I write it, use Socket, XMLSocket, xSocketDataHandler, or anyhting, I keep getting the closed channel error. What am I doing wrong?? Thanks. EDIT1: The AS3 Code: This is my Socket class: import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.Socket; /** * ... * @author 9MS */ public class GameSocket extends Socket { private var host:String; private var port:int; public function GameSocket(host:String="187.127.89.158", port:int=8090) { super(host, port); socketConnect(); } public function socketConnect():Boolean { addEventListener(Event.CONNECT, onConnect); addEventListener(ProgressEvent.SOCKET_DATA, onResponse); addEventListener(Event.CLOSE, onClose); addEventListener(IOErrorEvent.IO_ERROR, onError); addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecError); try { connect(this.host, this.port); } catch (e:Error) { trace("Error on connect: " + e); return false; } return true; } public function sendData(msg:String):void { msg += "\0"; try { writeUTFBytes(msg); flush(); trace("Message sent: " + msg); } catch(e:Error) { trace("Error sending data: " + e); } } private function onConnect(e:Event):void { trace("Connected: "+e); } private function onResponse(e:ProgressEvent):void { trace("Receiving Data: " + e); var resp:String = readUTFBytes(bytesAvailable); } private function onClose(e:Event):void { trace("Connection Closed: " + e); close(); } private function onError(e:IOErrorEvent):void { trace("IO Error: " + e.text); close(); } private function onSecError(e:SecurityErrorEvent):void { trace("Security Error: " + e.text); close(); } } A: So, I've solved the problem. A very important thing in flash communication throught sockets, is that Flash opens the socket bridge, asks for the policy file, and than closes it after. So, in your server, you must receive the connection, checks for a policy-file-request, send the policy file and close the bridge. After receiving the policy file, Flash will open the connection again, and communicate normally without asking for a policy file again. So, after getting a new connection, you must start your logic normally but, if you receive a policy-file-request, just answer with the policy file and close the connection.
doc_23534243
Is isolated storage a good place to write it? Will the service have access to the user's isolated storage? Any other suggestions for this. Thanks in advance. Fike A: A standard way is to create an event log section for your application and write to the Event log
doc_23534244
So far I don't see any device in /sys/bus/spi/devices Please help What I did are below At the buildroot terminal "make raspberrypi3_defconfig" then enabled those below via "make xconfig" and "make linux-xconfig" * *BR2_ROOTFS_DEVICE_CREATION_DYNAMIC_EUDEV *BR2_PACKAGE_IPROUTE2 *NET *CAN *CAN_DEV *SPI *CAN_MCP251X After that I flashed sdcard.img to an SD card then I add those two lines below to config.txt dtparam=spi=on dtoverlay=mcp2515-can0,oscillator=12000000,interrupt=25 I expected to see spi0.0 but I don't see any device in /sys/bus/spi/devices Can you please help? Thank you
doc_23534245
race class: public class RelayRace { private List<RelayRaceTeam> teamList = new ArrayList<>(10); public RelayRace() { teamList.add(new RelayRaceTeam("FERRARI")); teamList.add(new RelayRaceTeam("BMW")); teamList.add(new RelayRaceTeam("LAMBORGHINI")); teamList.add(new RelayRaceTeam("DACIA")); teamList.add(new RelayRaceTeam("NASCAR")); teamList.add(new RelayRaceTeam("OPEL")); teamList.add(new RelayRaceTeam("MITSUBISHI")); teamList.add(new RelayRaceTeam("HONDA")); teamList.add(new RelayRaceTeam("PORSCHE")); teamList.add(new RelayRaceTeam("MERCEDES")); } public void start() { teamList.forEach(RelayRaceTeam::start); } } TeamClass: public class RelayRaceTeam extends Thread { private static final ThreadRaceContext context = new ThreadRaceContext(); private ArrayList<RelayRaceCompetitor> competitors = new ArrayList<>(4); private String name; public RelayRaceTeam(String name) { this.name = name; for (int i = 0; i < 4; i++) { competitors.add(new RelayRaceCompetitor()); } } @Override public void run() { competitors.forEach(RelayRaceCompetitor::start); for (RelayRaceCompetitor competitor : competitors) { System.out.println("Competitor " + competitor.getNumber() + " from team " + name + " has traversed " + Count.getCounter()); } if (Count.getCounter() == 100) { synchronized (context) { context.announceWhichTeamWon(name, competitors); } } } } Competitor: public class RelayRaceCompetitor extends Thread{ private int number; private static final AtomicInteger count = new AtomicInteger(0); public RelayRaceCompetitor() { number = count.getAndIncrement(); } @Override public void run() { Count.increment(); } public int getNumber() { return number; } } The context where the winner is announced : public class ThreadRaceContext extends Thread { public void announceWhichTeamWon(String name, ArrayList<RelayRaceCompetitor> competitors) { System.out.println(name + " won the competition"); for (RelayRaceCompetitor competitor : competitors) { System.out.println("Competitor number : " + competitor.getNumber()); } } } And the counter : public class Count { private static int counter = 1; public static void increment() { counter++; } public static int getCounter() { return counter; } }
doc_23534246
My attempt at recreating this axes arrangement is below. Specifically, my problem is that the axes are not properly aligned. For example, the axis object for the blue histogram is taller than the axis object for the image with various shades of green; the orange histogram seems to properly align in terms of width, but I attribute this to luck. How can I properly align these axes? Unlike the original figure, I would like to add/pad extra empty space between axes such that there borders do not intersect; the slice notation in the code below does this by adding a blank row/column. (In the interest of not making this post longer than it has to be, I did not make the figures "pretty" by playing with axis ticks and the like.) Unlike the original picture, the axes are not perfectly aligned. Is there a way to do this without using constrained layout? By this, I mean some derivative of fig, ax = plt.subplots(constrained_layout=True)? The MWE code to recreate my figure is below; note that there was no difference between ax.imshow(...) and ax.matshow(...). import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import Normalize ## initialize figure and axes fig = plt.figure() gs = fig.add_gridspec(6, 6, hspace=0.2, wspace=0.2) ax_bottom = fig.add_subplot(gs[4:, 2:]) ax_left = fig.add_subplot(gs[:4, :2]) ax_big = fig.add_subplot(gs[:4, 2:]) ## generate data x = np.random.normal(loc=50, scale=10, size=100) y = np.random.normal(loc=500, scale=50, size=100) ## get singular histograms x_counts, x_edges = np.histogram(x, bins=np.arange(0, 101, 5)) y_counts, y_edges = np.histogram(y, bins=np.arange(0, 1001, 25)) x_mids = (x_edges[1:] + x_edges[:-1]) / 2 y_mids = (y_edges[1:] + y_edges[:-1]) / 2 ## get meshed histogram sample = np.array([x, y]).T xy_counts, xy_edges = np.histogramdd(sample, bins=(x_edges, y_edges)) ## subplot histogram of x ax_bottom.bar(x_mids, x_counts, width=np.diff(x_edges), color='darkorange') ax_bottom.set_xlim([x_edges[0], x_edges[-1]]) ax_bottom.set_ylim([0, np.max(x_counts)]) ## subplot histogram of y ax_left.bar(y_mids, y_counts, width=np.diff(y_edges), color='steelblue') ax_left.set_xlim([y_edges[0], y_edges[-1]]) ax_left.set_ylim([0, np.max(y_counts)]) ## subplot histogram of xy-mesh ax_big.imshow(xy_counts, cmap='Greens', norm=Normalize(vmin=np.min(xy_counts), vmax=np.max(xy_counts)), interpolation='nearest', origin='upper') plt.show() plt.close(fig) EDIT: One can initialize the axes by explicitly setting width_ratios and height_ratios per row/column; this is shown below. This doesn't affect the output, but maybe I'm using it incorrectly? ## initialize figure and axes fig = plt.figure() gs = gridspec.GridSpec(ncols=6, nrows=6, figure=fig, width_ratios=[1]*6, height_ratios=[1]*6) ax_bottom = fig.add_subplot(gs[4:, 2:]) ax_left = fig.add_subplot(gs[:4, :2]) ax_big = fig.add_subplot(gs[:4, 2:]) A: The problem is with imshow, which resizes the axes automatically to maintain a square pixel aspect. You can prevent this by calling: ax_big.imshow(..., aspect='auto')
doc_23534247
if (prefs.getBoolean("backgroundupdates", true)) { Intent setAlarm = new Intent(Splash.this, UpdateLocation.class); PendingIntent pendingIntent = PendingIntent.getService( Splash.this, 0, setAlarm, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ssaa"); History.addHistory(sdf.format(calendar.getTime()), "App Started", ""); calendar.setTimeInMillis(System.currentTimeMillis()); int UPDATE_TIME = prefs.getInt("Update_time", 30); calendar.add(Calendar.MINUTE, UPDATE_TIME); alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); } This checks if background updates are on and sets an alarm for UPDATE_TIME mins (default 30) in my UpdateLocation.class I have this in the bottom Intent setAlarm = new Intent(UpdateLocation.this, UpdateLocation.class); PendingIntent pendingIntent = PendingIntent.getService( UpdateLocation.this, 0, setAlarm, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); int UPDATE_TIME = prefs.getInt("Update_time", 30); calendar.add(Calendar.MINUTE, UPDATE_TIME); alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); This is so that the alarm will call itself again in UPDATE_TIME mins. The reason I'm doing it this way is because UPDATE_TIME may change (depending on user preferences) Thanks! EDIT here is my UpdateLocation.class public class UpdateLocation extends IntentService { public static final String id = ""; public UpdateLocation() { super("UpdateLocation"); } @Override protected void onHandleIntent(Intent intent) { SharedPreferences prefs = getSharedPreferences("Settings", 0); final String id = prefs.getString("ID", ""); if (prefs.getBoolean("backgroundupdates", true)) { HttpParams httpParams = new BasicHttpParams(); // 30seconds and it stops HttpConnectionParams.setConnectionTimeout(httpParams, 30000); HttpConnectionParams.setSoTimeout(httpParams, 30000); DefaultHttpClient httpclient = new DefaultHttpClient(httpParams); HttpPost httpost = new HttpPost( "http://iphone-radar.com/gps/gps_locations"); JSONObject holder = new JSONObject(); try { holder.put("id", id); LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); String bestProvider = locationManager.getBestProvider(criteria, false); LocationListener loc_listener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub } }; try { Looper.prepare(); locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener); } catch (Exception e) { e.printStackTrace(); } Location location = locationManager .getLastKnownLocation(bestProvider); Calendar c = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat( "hh:mmaa MM/dd/yyyy"); holder.put("time", sdf.format(c.getTime())); holder.put("time_since_epoch", System.currentTimeMillis()/1000); try { holder.put("lat", location.getLatitude()); holder.put("lon", location.getLongitude()); } catch (NullPointerException e) { try { holder.put("lat", -1.0); holder.put("lon", -1.0); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } StringEntity se = new StringEntity(holder.toString()); httpost.setEntity(se); httpost.setHeader("Accept", "application/json"); httpost.setHeader("Content-type", "application/json"); ResponseHandler responseHandler = new BasicResponseHandler(); String response = httpclient.execute(httpost, responseHandler); org.json.JSONObject obj; SimpleDateFormat sdf2 = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ssaa"); try{ History.addHistory(sdf2.format(c.getTime()), "GPS", "Latitude: " + location.getLatitude() + "\n" + "Longitude: " + location.getLongitude());} catch(NullPointerException e){ History.addHistory(sdf2.format(c.getTime()), "GPS", "Latitude: " + "No Signal" + "\n" + "Longitude: " + "No Signal"); } obj = new org.json.JSONObject(response); Intent setAlarm = new Intent(UpdateLocation.this, UpdateLocation.class); PendingIntent pendingIntent = PendingIntent.getService( UpdateLocation.this, 0, setAlarm, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); int UPDATE_TIME = prefs.getInt("Update_time", 30); calendar.add(Calendar.MINUTE, UPDATE_TIME); alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } Note, I do not have a broadcast receiver, I'm not quite sure how to use it so any examples would be very helpful. A: Could you possibly post all of your UpdateLocation.class? It needs to extend BroadcastReceiver so that may be where your problem lies. As for your alarm, if it's being set to go off every xx minutes without end, you're better off using alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), UPDATE_TIME * 60000, pendingIntent); to have your alarm reset on a regular basis. Edit 1 Regarding putting the PendingIntent into a static function for easy access, it could go something like this: public static PendingIntent getPendingIntent(int update_time) { Intent setAlarm = new Intent(this.getBaseContext(), UpdateLocation.class); PendingIntent pendingIntent = PendingIntent.getService(this.getBaseContext(), 0, setAlarm, 0) return pendingIntent; } And then you can set your alarm with alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), UPDATE_TIME * 60000, MyClass.getPendingIntent());
doc_23534248
SELECT T1.*, T2.* FROM T1 INNER JOIN T2 ... etc. In SQL Server Management Studio, I want the results to show in the grid with the table names prepended to the column names What I get by default is this: ID | A1 | ... | ID | B1 But I want this: T1.ID | T1.A1 | ... | T2.ID | T2.B1 Is there any command or setting which will make the table names be displayed in the results grid? (There are many columns, so I want to use the *. I am not looking to ask for the columns individually).
doc_23534249
In thanks to the countless suggestions from Stackoverflow and because of the complete lack of a proper solution (here and on the tinyMCE Documentation) I wanted to post the solution here. Although you can add any tags that you'd like, for the purposes of this example, I'm going to add <h1> tags: //Add the plugin to tinyMCE.init tinymce.init({ selector: \"div.editable\", inline: true, plugins: 'addh1s' toolbar: 'addh1s' //etc... }); //Then create a folder entitled, 'addh1s' in the tinyMCE 'plugins' folder //and add the plugin.min.js file that contains the following code. //*Please note that the number '27' below is the number in order of the //'addh1s' button on my tinyMCE toolbar. In your case it can be the //number of where your button appears on your toolbar. tinymce.PluginManager.add('addh1s', function(editor, url) { editor.addButton('addh1s', { title: 'Add H1 tags', image: '../images/h1.png', onPostRender: function() { editor.on('NodeChange', function(e) { if (editor.formatter.match('h1')) { tinymce.activeEditor.theme.panel.find('toolbar *')[27].active(true); } else { tinymce.activeEditor.theme.panel.find('toolbar *')[27].active(false); } }); }, onclick: function() { tinyMCE.activeEditor.execCommand('FormatBlock', false, 'h1'); } }); }); I hope this saves you countless frustrating hours!!! A: This is exactly what I was looking for! (however I spent a couple of frustrating hours while trying to get there :P) Just wanted to note down a more reliable and generic way I found to identify the button, to get rid of the customization for the 28th button. onPostRender: function() { var _this = this; // reference to the button itself editor.on('NodeChange', function(e) { _this.active(editor.formatter.match('h1')); }) } A: I wanted to do this with an element's class, rather than its node type. Here's my solution (uses jQuery, which is included already - this being a Wordpress build ) ed.addButton('add_top_margin',{ title : 'Add extra margin to the top of this element', text : 'Add Top Margin', onclick : function(){ ed.dom.toggleClass( ed.selection.getNode(), 'top_margin' ); this.active( !this.active() ); //toggle the button too }, onPostRender: function() { var _this = this; // reference to the button itself ed.on('NodeChange', function(e) { //activate the button if this parent has this class var is_active = jQuery( ed.selection.getNode() ).hasClass('top_margin'); _this.active( is_active ); }) } }) and the css: .top_margin{ margin-top: 1rem; }
doc_23534250
any help? Thanks.. A: Use android Locale Hope this helps you.
doc_23534251
Are there alternatives that will allow them to use Interdev securely, or must we disable WebDav and make the sites FTP-only? A: It has been a while but I believe that the WebDav ( or Front Page Server Extentions as I remember them) were only used for deployment. Back when we used Interdev we would usually develop locally with Interdev and deploy via FTPS, so I don't believe you should run into your applications if you aren't explicitly using WebDAV for anything.
doc_23534252
Currently, I have this snippet: StringTokenizer tokenizer = new StringTokenizer(request, "{}:,\""); Map<String, String> properties = new HashMap<String, String>(); while(tokenizer.hasMoreTokens()) { String key = tokenizer.nextToken(); String value = tokenizer.nextToken(); properties.put(key, value); } This snippet allows me to tokenize a regular (non-complex) json object so that I can get the value using the key as the lookup. However, it does not work for complex objects in the form like [{"Foo":"Bar", "XYZ":12}, {"ABC":16, "Foo": "Bar"}...] So I was wondering how can I tokenize an array of json objects? A: Regex is not suitable for parsing or tokenizing JSON. Instead parse JSON with a parser e.g. Gson: String json = "[{\"Foo\":\"Bar\", \"XYZ\":12}, {\"ABC\":16, \"Foo\": \"Bar\"}]"; Map<String, String>[] result = new Gson().fromJson(json, new TypeToken<Map<String, String>[]>() {}.getType()); System.out.println(Arrays.toString(result)); will output below showing two Map objects: [{Foo=Bar, XYZ=12}, {ABC=16, Foo=Bar}]
doc_23534253
Marcus PS. Please be clear, noobie alert! one-liners & cryptic examples hardly do it for me. URL http://api.usno.navy.mil/rstt/oneday?date=today&coords=9S,147E&tz=10 JSON { "error":false, "apiversion":"2.0.0", "year":2017, "month":3, "day":4, "dayofweek":"Saturday", "datechanged":false, "lon":147.000000, "lat":9.000000, "tz":10, "sundata":[ {"phen":"BC", "time":"06:04"}, {"phen":"R", "time":"06:25"}, {"phen":"U", "time":"12:24"}, {"phen":"S", "time":"18:23"}, {"phen":"EC", "time":"18:44"}], "moondata":[ {"phen":"R", "time":"10:50"}, {"phen":"U", "time":"17:12"}, {"phen":"S", "time":"23:36"}], "closestphase":{"phase":"First Quarter","date":"March 5, 2017","time":"21:32"}, "fracillum":"34%", "curphase":"Waxing Crescent" } UPDATED! STATE OF CODE $.getJSON("http://api.usno.navy.mil/rstt/oneday?date=today&coords=9S,147E&tz=10", function(data) { data.sundata.forEach(function (sd) { $('#'+sd.phen).text(sd.time) }) var rise = data.moondata[0].time; var tran = data.moondata[1].time; var sets = data.moondata[2].time; // Set the table td text $('#R').text(rise); $('#U').text(tran); $('#S').text(sets); } }) CODE AS EARLIER <script> $.getJSON("http://api.usno.navy.mil/rstt/oneday?date=today&coords=9S,147E&tz=10", function(data) { console.log(data); // Set the variables from the results array var dusk = ["sundata"][0]["BC.time"]; console.log(data); var rise = ["sundata"][0]["R.time"]; console.log(data); var noon = ["sundata"][0]["U.time"] console.log(data); var sets = ["sundata"][0]["S.time"]; console.log(data); var dawn = ["sundata"][0]["EC.time"]; console.log(data); // Set the table td text $('BC').text(dusk); $('R').text(rise); $('U').text(noon); $('S').text(sets); $('EC').text(dawn); }); </script> </head> <body> <h1>MOONSUN</h1> <hr/> <table border="1"> <td>DAWN:</td> <td id="BC"></td> </tr> <tr> <td>RISE:</td> <td id="R"></td> </tr> <tr> <td>NOON:</td> <td id="U"></td> </tr> <tr> <td>SET:</td> <td id="S"></td> </tr> <tr> <td>DUSK:</td> <td id="EC"></td> </tr> </table> </div> </body> API LINK http://aa.usno.navy.mil/data/docs/api.php NEW JSFIDDLE [link]http://jsfiddle.net/kmg747/4egLxu2e/ A: First thing, you need to access the data object to get any information var dusk = data["sundata"][0]["BC.time"]. Pay attention to the data object there. The way you are accessing/handling data from array and nested objects are wrong too. The endpoint is returning an object with properties as String, Boolan or Array ([]) of Objects ({}). To access an Array you do by index, as in arr[0], for an Object you do obj.propertyIWant or obj['propertyIWant'] And to access an element by id with jQuery you need the # before the element id, like $('#BC'). For what you want to do you should do something like: var dusk = data.sundata[0].time; var rise = data.sundata[1].time; var noon = data.sundata[2].time; var sets = data.sundata[3].time; var dawn = data.sundata[4].time; Or, in a more direct way, without setting those variables, using the information you got from the endpoint: data.sundata.forEach(function (sd) { $('#'+sd.phen).text(sd.time) }) Fetching the url from your JSFiddle link doesn't work because you are using an HTTPS connection and are trying to fetch from an HTTP link. To work, you need to use the Fiddle from HTTP. More information here. After checking the API for it, here is an updated version of what you are trying to do. You may need to treat some values that may or may not be returned.
doc_23534254
for example: from pandas import Series, DataFrame import pandas as pd import numpy as np #read data from DataFrame data_ThisYear_Period=[[' 序 号','北 京','上 海',' 广州'],\ [' 总计','11232',' 2334','3 4'],\ [' 温度','1223','23 23','2323'],\ ['人 口','1232','21 321','1222'],\ ['自行车', '1232', '21321', '12 22']] data_LastYear_Period=DataFrame(data_ThisYear_Period) print(type(data_LastYear_Period)) data_ThisYear_Period.apply(data_ThisYear_Period.str.strip(),axis=1) Traceback (most recent call last): File "C:/test/temp.py", line 17, in data_ThisYear_Period.apply(data_ThisYear_Period.str.strip(),axis=1) AttributeError: 'list' object has no attribute 'apply' How to strip whitespaces from Python DataFrame in this example A: use applymap to the dataframe, applymap applies a lambda function on each cell. In the lambda function split the string (white spaces are ignored in it) and then join it. If there is an int, then you can use if else in lambda function. from pandas import Series, DataFrame import pandas as pd import numpy as np #read data from DataFrame data_ThisYear_Period=[[' 序 号','北 京','上 海',' 广州'],\ [' 总计','11232',' 2334','3 4'],\ [' 温度','1223','23 23','2323'],\ ['人 口',1232,'21 321','1222'],\ ['自行车', '1232', '21321', '12 22']] data_LastYear_Period=DataFrame(data_ThisYear_Period) print data_LastYear_Period data_LastYear_Period = data_LastYear_Period.applymap((lambda x: "".join(x.split()) if type(x) is str else x )) print data_LastYear_Period results in 0 1 2 3 0 序 号 北 京 上 海 广州 1 总计 11232 2334 3 4 2 温度 1223 23 23 2323 3 人 口 1232 21 321 1222 4 自行车 1232 21321 12 22 0 1 2 3 0 序号 北京 上海 广州 1 总计 11232 2334 34 2 温度 1223 2323 2323 3 人口 1232 21321 1222 4 自行车 1232 21321 1222 on a side note, you are getting this particular error because data_ThisYear_Period.apply(data_ThisYear_Period.str.strip(),axis=1) data_ThisYear_Period is a list and not a pandas dataframe (data_LastYear_Period)
doc_23534255
For this i need some sort of mechanism to guard, but not block the read method, so the reading thread is blocked by a write, but not by other reads. I can't use a normal lock for this because invoking the lock method in the read method would cause other read threads to wait. The rules should be as such: When a thread is inside write(), no other threads must enter read() or write() When a thread is inside read(), no other threads must enter write(), but they may enter read() I have tried building a couple of homemade locks to deal with this problem. WriteLock is a fairly standard reenterant lock, except that it blocks if read is being executed (Using the readcounter) ReadLock should only cause threads to wait, if write() is being traversed. Otherwise it should simply allow the thread to go about its business and increment WriteLocks counter. Code: package sync; public class SyncTest { Long testlong = new Long(0L); int reads = 0; int writes = 0; WriteLock w = new WriteLock(); ReadLock r = new ReadLock(w); public SyncTest() { // TODO Auto-generated constructor stub } public static void main(String args[]){ final SyncTest s = new SyncTest(); for(int i = 0 ; i<3 ; i++){ //Start a number of threads to attack SyncTest final int ifinal = i; new Thread(){ int inc = ifinal; @Override public void run() { System.out.println("Starting "+inc); long starttime = System.currentTimeMillis(); try { while(System.currentTimeMillis()-starttime < 10){ if (inc < 2){ s.readLong(); }else{ s.writeLong(inc+1); } } System.out.println(inc + " done"); if(inc == 0){ Thread.sleep(1000); System.out.println(s.reads+" "+s.writes); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated method stub } @Override public String toString() { // TODO Auto-generated method stub return "Thread "+inc+" "+super.toString(); } }.start(); } } public Long readLong() throws InterruptedException{ Long l; r.lock(); //Lock for reading //System.out.println("Read "+reads); l = testlong; reads++; r.unlock(); //Unlock after reading return l; } public void writeLong(int i) throws InterruptedException{ w.lock(); //Lock for writing //System.out.println("Write "+writes); int curreads = reads; int curwrites = writes; testlong = testlong + i; writes++; Thread.sleep(100); //Simulate long write if(curreads != reads){ System.out.println("Reads did not lock"); } if(curwrites+1 != writes){ System.out.println("Writes did not lock"); } w.unlock(); //Unlock writing } protected class WriteLock{ boolean isLocked = false; Thread lockedBy = null; int lockedCount = 0; int readers = 0; //The number of readers currently through the reading lock. public synchronized void lock() throws InterruptedException { System.out.println("Locking: "+Thread.currentThread()); Thread callingThread = Thread.currentThread(); while ((isLocked && lockedBy != callingThread) || readers > 0) { //Wait if locked or readers are in read() wait(); } isLocked = true; lockedCount++; lockedBy = callingThread; System.out.println("Is locked: "+Thread.currentThread()); } public synchronized void unlock() { //System.out.println("Unlocking: "+Thread.currentThread()); if (Thread.currentThread() == this.lockedBy) { lockedCount--; if (lockedCount == 0) { System.out.println("Is unlocked: "+Thread.currentThread()); isLocked = false; notify(); } } } } protected class ReadLock{ WriteLock lock; public ReadLock(WriteLock lock) { super(); this.lock = lock; } public synchronized void lock() throws InterruptedException { //If write() then wait System.out.println("Waiting to read: "+Thread.currentThread()); Thread callingThread = Thread.currentThread(); while (lock.isLocked && lock.lockedBy != callingThread) { wait(); } lock.readers++; //Increment writelocks readers System.out.println("Reading: "+Thread.currentThread()); } public synchronized void unlock() { lock.readers--; //Subtract from writelocks readers notify(); } } } This is not working however, the reading lock works so far that it locks readers when a thread is writing, but it doesn't release them when WriteLock unlocks, as far as i can tell. Is this just not conceptually sound, or is there something i don't understand with monitors? Or something else? A: (Answered before the question was edited in terms of it being an exercise.) It sounds like you want a ReadWriteLock implementation. A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive. One implementation is ReentrantReadWriteLock. For concurrency in particular, it's always worth looking in the existing libraries (java.util.concurrent et al) before you try to implement your own code. If you're anything like me, even if you can make it correct in terms of concurrency, it won't be as efficient as the code written by experts... and of course it's all work to start with ;) A: Your ReadLock and WriteLock are synchronizing on different objects and calling wait and notify on different objects. This allows the ReadLock to modify the counts in WriteLock while WriteLock is validating them. It will also cause the different locks not to wake from the calls to wait. If you modify your ReadLock to use the WriteLock as a monitor you're get better results (I didn't check if this was the only problem) protected class ReadLock{ WriteLock lock; public ReadLock(WriteLock lock) { super(); this.lock = lock; } public void lock() throws InterruptedException { //If write() then wait synchronized (lock) { System.out.println("Waiting to read: "+Thread.currentThread()); Thread callingThread = Thread.currentThread(); while (lock.isLocked && lock.lockedBy != callingThread) { lock.wait(); } lock.readers++; //Increment writelocks readers System.out.println("Reading: "+Thread.currentThread()); } } public void unlock() { synchronized (lock) { lock.readers--; //Subtract from writelocks readers lock.notify(); } } }
doc_23534256
<ion-item-sliding #item *ngFor="let order of orders"> <ion-item> <div class="pending-order-list"> <div class="row custom-padding-xs custom-padding"> <div class="col-xs-3"></div> <div class="col-xs-9"> <div class="panel-order-date"> <span class="list-label">{{ "pendingOrder.date" | translate }}</span> <span class="list-input">{{ order.orderDate | date }}</span> </div> <div class="panel-order-number"> <span class="list-label">{{ "pendingOrder.orderNo" | translate }}</span> <span class="list-input">{{order.orderNo}}</span> </div> </div> </div> <div class="row custom-padding-xs"> <div class="col-xs-3"> <span class="list-label">{{ "pendingOrder.customer" | translate }}</span> </div> <div class="col-xs-6 bold"> {{order.customer}} </div> <div class="col-xs-3 bold text-right"> {{order.sum | numberFormat}} </div> </div> <div class="row custom-padding-xs"> <div class="col-xs-3"> <span class="list-label">{{ "pendingOrder.chain" | translate }}</span> </div> <div class="col-xs-6 "> {{order.chain}} </div> <div class="col-xs-3 status"> {{order.status}} </div> </div> </div> </ion-item> <ion-item-options side="right"> <div class="row custom-padding-xs"> <div class="col-xs-6"> <input type="text" name="" id="" class="input-custom" /> </div> <div class="col-xs-3"> <button class="btn-small" (click)="confirmOrder(order)">{{ "pendingOrder.confirm" | translate }}</button> </div> <div class="col-xs-3"> <button class="btn-small black">{{ "pendingOrder.reject" | translate }}</button> </div> </div> </ion-item-options>
doc_23534257
#! /bin/bash output_dir="$2" # an_level1/an_level2/an_level3 for file in ls "$1"/*.fa; do cbf="$(readlink -e "$(file)")" cbf_fn="$(basename "$cbf")" #*.fa filename_WO_ext="${cbf_fn%.*}" #* RNAfold < "$file" > "${output_dir}/${filename_WO_ext}/.txt";done
doc_23534258
function clockGen() { var time = new Date(); var hour = time.getHours(); var min = time.getMinutes(); var sec = time.getSeconds(); document.getElementById('time').innerHTML = hour + ":" min + ":" + sec; var refresh = setTimeout("clockGen()", 1000); } It keeps giving me the error shown in the title for some reason. Can you please get me in the right direction? A: Your a missing a plus sign here: document.getElementById('time').innerHTML = hour + ":" min + ":" + sec; Instead it should be: document.getElementById('time').innerHTML = hour + ":" + min + ":" + sec; A: You don't have any missing semicolons. But the "missing semicolon" really means "The interpreter found what it thinks to be the end of a statement, but it didn't have a semicolon. So I don't know what to do with this code. Maybe it was supposed to be the end of a statement, maybe it wasn't. Since the author wasn't explicit, the safest option is to complain and ask them to be clearer." Check this line: document.getElementById('time').innerHTML = hour + ":" min + ":" + sec; // ^^^^^^
doc_23534259
I was wondering what my options are for dealing with this problem? I read that it's possible to stream large files into cloud storage but I don't know how to do this from a cloud function or while unzipping. Any help would be appreciated. Here is the code of the cloud function so far: storage_client = storage.Client() bucket = storage_client.get_bucket("bucket-name") destination_blob_filename = "large_file.zip" blob = bucket.blob(destination_blob_filename) zipbytes = io.BytesIO(blob.download_as_string()) if is_zipfile(zipbytes): with ZipFile(zipbytes, 'r') as myzip: for contentfilename in myzip.namelist(): contentfile = myzip.read(contentfilename) blob = bucket.blob(contentfilename) blob.upload_from_string(contentfile) A: Your target process is risky: * *If you stream file without unzipping it totally, you can't validate the checksum of the zip *If you stream data into GCS, file integrity is not guaranteed Thus, you have 2 successful operation without checksum validation! Before having Cloud Function or Cloud Run with more memory, you can use Dataflow template to unzip your files
doc_23534260
Thanks! Specifics, if they help: Amplified spontaneous emission (ASE) in an optical fibre amplifier. Rows act as storage for a discretised ASE spectrum, columns are a given position along the fibre amplifier (it is this position -- the distance along the fibre corresponding to the column -- which I want to use as the label) and each element contains power information. The plot gives spectral power of ASE in the fibre for different positions along its length. A: If by labels you mean the plot legend, you can do that by using cells. Consider matrix A A = repmat([1:3], 3, 1) A = 1 2 3 1 2 3 1 2 3 You can call plot to plot the columns of the matrix plot(A); Here, you will get 3 horizontal lines at y=1, 2 and 3. You can create your legend as follows l{1} = 'dataset1'; l{2} = 'dataset2'; l{3} = 'dataset3'; Then you type legend(l) to show the legend. However, no one will create the legend for you, so you must create the cell array yourself. You can do it automatically, of course, e.g. the above legend can be created by a simple loop for i=1:size(A, 2) l{i} = ['dataset' num2str(i)]; end
doc_23534261
My idea in that: * *I have th in each column. *So th may be a detector of new column. *I need to find tr td in each column. *I need to create new table-N with th-N value in th *I need to paste each tr td-N after th So according to my idea, I have written following code: jQuery(document).ready(function($) { function tableshoot() { $("table th").each(function() { var $this = $(this); var thistext = $this.html(); var index = $this.index(); var tdList = $this.closest("table").find("tr").find("td:eq(" + index + ")").html(); $this.closest("table").append('<table class="mob-table-' + index + '"><tbody><tr><th>' + thistext + '</th></tr></tbody></table>'); $this.closest("table").find("tr").find("td:eq(" + index + ")").each(function() { var tdcontent = $(this).html(); $('table.mob-table-' + index + ' tbody').append('<tr><td>' + tdcontent + '</td></tr>'); }); }); }; tableshoot(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tbody> <tr> <th> COL 1 </th> <th> COL 2 </th> <th> COL 3 </th> </tr> <tr> <td>VAL 1</td> <td>VAL 2</td> <td>VAL 3</td> </tr> <tr> <td>VAL 11</td> <td>VAL 22</td> <td>VAL 33</td> </tr> <tr> <td>VAL 111</td> <td>VAL 222</td> <td>VAL 333</td> </tr> </tbody> </table> My question is: Is it right way? Or are there more clean ways to do it? No matter my code is workable. Hope this helps somebody. A: Few small things: * *"find("tr").find("td:eq(..." change to "find(tr td:eq..." *"$("table th").each(function()" change to "$("table th").each(function(index, value)", for clean access to index and value. jQuery doc each
doc_23534262
Grid(viewModel.cards) { card in CardView(card: card, theme: self.viewModel.getTheme()) .onTapGesture { withAnimation(.linear(duration: 0.8)) { self.viewModel.choose(card: card) } self.viewModel.resetGame() } .padding(5) } HStack { Text("Score : \(self.viewModel.score)") } } After withAnimation inside onTapGesture I want to run self.viewModel.resetGame() I can't use AnimatableModifier because I'm inside onTapGesture. A: Maybe just wrap your reset function to asyncAfter DispatchQueue with length of your animation? DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { self.viewModel.resetGame() }
doc_23534263
Image Name Image drop.png rain0.png rain1.png rain2.png rain3.png import pygame as pg import sys, os import random pg.init() clock = pg.time.Clock() size = width, height = (800,800) screen = pg.display.set_mode(size) class Rain(pg.sprite.Sprite): def __init__(self): pg.sprite.Sprite.__init__(self) self.image = pg.image.load("rain/drop/drop.png").convert_alpha() self.rect = self.image.get_rect() self.speed = random.randint(4,10) self.rect.x = random.randint(0,800) self.rect.y = random.randint(-400,-1) self.splash_current = 0 self.splash = [] self.splash_frames() def update(self): self.rect.y += self.speed if self.rect.y > 700: self.speed = 0 if not self.splash_anim(): pass def splash_frames(self): for i in os.listdir("rain/frames"): for j in range(5): self.splash.append(pg.image.load(f"rain/frames/{i}").convert_alpha()) def splash_anim(self): self.splash_current += 1 if self.splash_current == len(self.splash): self.image = pg.image.load("rain/drop/drop.png").convert_alpha() self.splash_current = 0 self.rect.y = -200 self.speed = random.randint(4,10) return False else: self.image = self.splash[self.splash_current] rain_group = pg.sprite.Group() for i in range(200): rain = Rain() rain_group.add(rain) while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() screen.fill((93, 109, 110)) rain_group.update() rain_group.draw(screen) pg.display.flip() clock.tick(60) When the values in self.speed are changed from (4,10) to anything else, it seems to be more noticeable, but it's still (slightly) noticable with (4,10). The goal is to have the rain all start and fall at the same time, which it does after that first awkward pass. I've spent quite some time looking over the code and changing things, but I'm unsure why the first pass is happening the way it does. Any suggestions?
doc_23534264
According to documentation it is possible to add @Ignore on class level. @Ignore public class BasicOperationsTest extends TestBaseClass{ I did it like above but it doesn't work - all test methods are executed. When I add ignore before @Test method in this case annotation works and test is not executed.
doc_23534265
If a client disconnects the clients messages stored in respective Actor's mailbox.But if jvm crashes all the messages in the actor mailbox will flushed. If i use persistence actor i will store each messages of an actor in disk?? then reply to actor like mailbox on disk? A: The broad approach would be to use Akka Persistence (this sounds like a reasonable fit for event sourcing) so that the state of the actor can be recovered. You would choose and set-up a persistence backend (e.g. the local leveldb one or a DB at network distance like MySQL/Postgres or Cassandra) for the events to be stored. Note that messages in the mailbox are not persisted; only those messages which get processed by the actor can persist state changes.
doc_23534266
Also, can we set height/width of all replaced elements even if they're inline? A: The HTML5 specification now has a whole section on Button Layout Sometimes it's treated like a replaced element, and sometimes like an inline-block element. But it's never treated as a non-replaced inline element. In detail, it says that: Button layout is as follows: The 'display' property is expected to act as follows: If the computed value of 'display' is 'inline-grid', 'grid', 'inline-flex', or 'flex', then behave as the computed value. Otherwise, if the computed value of 'display' is a value such that the outer display type is 'inline', then behave as 'inline-block'. Otherwise, behave as 'flow-root'. ... If the element is absolutely-positioned, then for the purpose of the CSS visual formatting model, act as if the element is a replaced element. [CSS] If the computed value of 'inline-size' is 'auto', then the used value is the fit-content inline size. For the purpose of the 'normal' keyword of the 'align-self' property, act as if the element is a replaced element. ... A: If you want more clarification...it seems that the button element is a replaced element in most modern browsers today and in the past, which means no matter how you style it, even after changing the default UA browser styles, it still retains width and height characteristics regardless of display properties. It therefore does have design characteristics tied to the browser and OS that override both the default UA style sheet in the browser and the author's styles, UNLIKE the non-replaced elements which can be changed. Take the following test that demonstrates that: <style type="text/css"> button, p, div { all:revert; all:unset; all:initial; display:initial; width:initial; height:initial; display:inline !important; width:100px; height:100px; background:green; color:white; text-align:center; } </style> <button>button</button> <br /> <p>paragraph</p> <br /> <div>div</div> When the <button>, <p>, and <div> elements are completely cleared of their CSS properties (all:revert and display:initial), then display:inline set with width and height, only <p> and <div> lose dimension. But the button element in modern browsers (Chrome and Firefox) still retains its "special" replaced ability to regain dimensions, regardless. Therefore, yes its "replaced" status affects its width and height characteristics. Additional: If you set the dimensions above to "0px", the button element's background collapses but the "clickable" interface dimensions on the button element do not. The text area on the button is still clickable in most modern browsers. In Safari and Internet Explorer, the button becomes tiny but still exists with dimensions and is clickable. The point is, yes these replaced elements have dimensions you can control but not entirely erase.
doc_23534267
Here is an example of our issue and hope there is an answer for this problem. Data Classes: public class TestContact { public List<TestContactItem> Studio { get; set; } public List<TestContactItem> StudioExecutive { get; set; } public TestContact() { Studio = new List<TestContactItem>(); StudioExecutive = new List<TestContactItem>(); } } public class TestContactItem { public int Id { get; set; } public string Name { get; set; } } Controller Methods: public ActionResult TestContactView() { var vm = new TestContact(); vm.Studio.Add(new TestContactItem(){Id=1, Name = "Studio Contact ID=1"}); vm.StudioExecutive.Add(new TestContactItem() { Id = 2, Name = "Studio Exec Contact ID=2" }); return View(vm); } [HttpPost] public ActionResult SaveTestContact(TestContact model) { return Content("success"); } View / JavaScript with Ajax POST: @using System.Web.Script.Serialization @model TestContact <button type="button" onclick="SaveTestContact();">Click Here to Post</button> <script type="text/javascript"> $(document).ready(function() { globalTestModel = @Html.Raw(new JavaScriptSerializer().Serialize(Model)); }); function SaveTestContact() { // passing additional studio & studio executive parameter to controller because it was not mapping correctly to the server side viewmodel without it $.ajax({ type: "POST", url: "/Test/SaveTestContact", data: JSON.stringify(globalTestModel), dataType: "json", contentType: "application/json; charset=utf-8", success: function (msg) { } }); } </script> In this example we are populating our object with at least one Studio and one StudioExecutive and render the view. When the button in the view is clicked, we POST the same object to the controller method but the ViewModel is not binding correctly the Studio property is set to null. *Unfortunately I'm not able to post images I have a screenshot of the object showing that the Studio count was 0 and the StudioExecutive count was 1 We did put a breakpoint before the POST to make sure the serialization on the JavaScript was correct and the object was populated. We have concluded that this has to do with the naming convention of the 2 properties one being a substring of the other. Any one who has encounter the same problem and can point us on the right direction. A: I know this is not the "complete answer" to the question but I feel that this will give additional insight to the issue, that (I hope) will eventually lead to the "complete solution". Say we have a single item in each of Studio and StudioExecutive fields as shown in the example of the OP, and do the following in js: globalTestModel = '@Html.Raw(new JavaScriptSerializer().Serialize(Model))'; $.ajax({ type: "POST", url: "/Test/SaveTestContact", data: JSON.stringify(globalTestModel), dataType: "json", contentType: "application/json; charset=utf-8", success: function (msg) { } }); The controller method will only receive StudioExecutive as already mentioned. Now if we do the same and build the object in js as shown below, we get the same result. o = { Studio: [{ Id: 1, Name: 'Studio Contact ID=1', }], StudioExecutive: [{ Id: 2, Name: 'Studio Exec Contact ID=2', }] }; $.ajax({ type: "POST", url: "/Test/SaveTestContact", data: JSON.stringify(o), dataType: "json", contentType: "application/json; charset=utf-8", success: function (msg) { } }); Now here comes the interesting part. If we add another item to the Studio field and post the same way we will get the same result. // Do this in the controller and do the same ajax post public ActionResult TestContactView() { var vm = new TestContact(); vm.Studio.Add(new TestContactItem(){Id=1, Name = "Studio Contact ID=1"}); vm.Studio.Add(new TestContactItem(){Id=3, Name = "Studio Contact ID=3"}); vm.StudioExecutive.Add(new TestContactItem() { Id = 2, Name = "Studio Exec Contact ID=2" }); return View(vm); } But if we will build the object in js as shown below the controller will receive both the Studio, with 2 items, and the StudioExecutive, with one item. o = { Studio: [{ Id: 1, Name: 'Studio Contact ID=1', }, { Id: 2, Name: 'Studio Contact ID=2', }], StudioExecutive: [{ Id: 2, Name: 'Studio Exec Contact ID=2', }] }; // then do the ajax post So what have we learned This tells us two things: * *There is something wrong with the default model binder in that it cannot bind two, or more, fields that starts with the same name *JSON.stringify can also NOT do it if there is only one item, but it can do it if there are more than one item in the field that has the shortest name (e.g. Studio)
doc_23534268
candidate function not viable: no known conversion from 'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >') to 'std::string *' (aka 'basic_string<char, char_traits<char>, allocator<char> > *') here is my code (I work with multiple files) : main.cpp (My test file) #include <iostream> #include <string> #include "miniUI.hpp" using namespace std; const int textLenght = 20; string text[textLenght]; int main(){ cout << "Running" << endl; std::string text = "test"; slachesDachesMiniUI(4, 4, text); return 0; }; miniUI.cpp (The library that i'm working on) /* * Filename: CGUI Lib/src/miniUI.cpp * Created Date: Wednesday, November 2nd 2022, 2:36:34 pm * Author: Theodore ROY * * Copyright (c) 2022 Théodore ROY * Licensed under the CC-BY-SA 4.0 International license */ #include "miniUI.hpp" #include <iostream> #include <string> using namespace std; // This Module will look like this : -------------------------------- // | Text here | // -------------------------------- string lines[20]; string slash = "|"; string slachesDachesMiniUI(int lenght, int height, std::string text[]){ //Slashes and dashes based Mini UI if (lenght < 0){ return "ERROR: Invalid lenght ! please choose a lenght beetween 1 and 15"; } if (lenght > 20) { return "ERROR: Invalid lenght ! please choose a lenght beetween 1 and 15"; } if (height < 3){ return "ERROR: Invalid height ! please choose a height beetween 3 and 15"; // Sizes verification } if (height > 20) { return "ERROR: Invalid height ! please choose a height beetween 1 and 15"; } for (int i = 0; i < lenght; i++){ lines[0] = (lines[0] + '-'); // Calculate line1 (only calculate the numbre of '-' characters to // print in the first line }; for (int i = 1; i < height; i++) { // intermediate line constructor // Calculate all the lines beetween the header and the footer lines[i] = '|'; for (int j = 0; j < lenght; j++){ if (i == (height / 2)){ // if the constrctor is at the half of the height string textLineSpaces; if (j == lenght / 2 - text->size() ) { cout << "test" << endl; } lines[i] = slash; // number of the line = | + lenght of the line / 2 times ' ' } }; } string returnedValue = lines[0] + lines[1] + lines[2] + lines[3]; return returnedValue; }; miniUI.hpp (The header file for the miniUI.cpp file) #ifndef MINIUI_INTEGRATION #define MINIUI_INTEGRATION #include <string> std::string slachesDachesMiniUI(int lenght, int height, std::string text[]); //function that create a little windows #endif //MINIUI_INTEGRATION My error when compiling /usr/bin/g++ -fdiagnostics-color=always -g "/Users/Theod/Desktop/CGUI-main/source code/main.cpp" -o "/Users/Theod/Desktop/CGUI-main/source code/main" /Users/Theod/Desktop/CGUI-main/source code/main.cpp:18:5: error: no matching function for call to 'slachesDachesMiniUI' slachesDachesMiniUI(4, 4, text); ^~~~~~~~~~~~~~~~~~~ /Users/Theod/Desktop/CGUI-main/source code/miniUI.hpp:6:17: note: candidate function not viable: no known conversion from 'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >') to 'std::string *' (aka 'basic_string<char, char_traits<char>, allocator<char> > *') for 3rd argument; take the address of the argument with & std::string slachesDachesMiniUI(int lenght, int height, std::string text[]); ^ 1 error generated. Please help me finding how to fix this "conversion" error (i'm a newbie) A: The function slachesDachesMiniUI is called with an object of the type std;:string std::string text = "test"; slachesDachesMiniUI(4, 4, text); However the function corresponding parameter has the array type string[] string slachesDachesMiniUI(int lenght, int height, std::string text[]){ ^^^^^^^^^^^^^^^^^^ So the compiler issues an error. Pay attention for example to the inconsistent if (lenght > 20) { return "ERROR: Invalid lenght ! please choose a lenght beetween 1 and 15"; } Why the length must be between 1 and 15 and not 1 and 20? Also this for loop for (int i = 0; i < lenght; i++){ lines[0] = (lines[0] + '-'); // Calculate line1 (only calculate the numbre of '-' characters to // print in the first line }; invokes undefined behavior because you are trying to change an empty object of the type std::string. Moreover the loop changes the same elements of the array lines length times. The following loop for (int i = 1; i < height; i++) { // intermediate line constructor // Calculate all the lines beetween the header and the footer lines[i] = '|'; Also invokes undefined behavior.
doc_23534269
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel"stylesheet" type="text/css" href="style.min.css"> <title>Document</title> </head> <body> <h1>This is a square</h1> <div class="square"></div> </body> </html> and this is what I have in my style.scss which when complied makes style.min.css //Variables $lightblue: #b8fdfb; //CSS .square { width: 100px; height: 100px; background-color: $lightblue; } This is all that shows up in my local server A: You cannot attach SASS to HTML. You first need to compile it first to CSS & then link it to your HTML using <link> tag in the header. Like: <link rel="stylesheet/css" type="text/css" href="style.min.css" /> You need a preprocessor to convert SASS into CSS. You can use many tools such as Webpack, Prepros, etc. Have a look at this reference. Hope this helps!
doc_23534270
doc_23534271
I've tried to change the refX so the marker would finish at the end but since the line is thick it displays the rest of the line after the marker. I can reduce change this refX in a way that I don't see the rest of the line but I want to see the whole marker within the limits of the svg. I could also reduce the length of the line so the line + the marker takes the whole place but then I cannot find the correct amount of pixels I need to remove. The line is rendered dynamically which means it won't always be in that way. In a svg(x,y) from (0,0) to (100,100) it can go from (100,0) to (100,100). Current code displays the arrow overflowing the svg, I would like to have everything in it. <svg class="svg" style="height: 190px; width: 328px; border:1px solid blue;"> <marker class="red_arrow_normal" markerUnits="strokeWidth" viewBox="0 0 10 10" refY="6" orient="auto" markerHeight="10" markerWidth="10" id="red-3" refX="10"> <path d="M2,2 L10,6 L2,10 L6,6 L2,2" style="fill: red;"></path> </marker> <line x1="0" y1="0" x2="328" y2="190" stroke="red" stroke-width="10" marker-end="url(#red-3)"></line> </svg> A: There doesn't look to be a clean solution to this problem that doesn't involve some javascript, but you can solve it with some math: function drawArrow(x1, y1, x2, y2) { const svg = document.getElementById("my-svg") let dx = x2 - x1; let dy = y2 - y1; const length = Math.sqrt(dx * dx + dy * dy); if (length > 0) { dx /= length; dy /= length; } const SHORTEN = 6 const x3 = x1 + dx * (length - SHORTEN) const y3 = y1 + dy * (length - SHORTEN) svg.innerHTML += `<line x1=${x1} y1=${y1} x2=${x3} y2=${y3} stroke="red" stroke-width="5" marker-end="url(#arrow)"></line>` } You will first have to make sure your arrow head extends past the end of the line, so that the square end of the line isn't showing. Then you will have to adjust the SHORTEN variable to offset the extra length of the arrow head. My fiddle: https://jsfiddle.net/h4pgoaLw/ A: You can edit it online in codepen here. I have modified the width and height. <svg class="svg" style="height: 190px; width: 328px; border:1px solid blue;"> <marker class="red_arrow_normal" markerUnits="strokeWidth" viewBox="0 0 10 10" refY="6" orient="auto" markerHeight="10" markerWidth="10" id="red-3" refX="9"> <path d="M2,2 L10,6 L2,10 L6,6 L2,2" style="fill: red;"></path> </marker> <line x1="0" y1="0" x2="320" y2="180" stroke="red" stroke-width="10" marker-end="url(#red-3)"></line> </svg>
doc_23534272
Officail document link Deploy and Invoke for blockchain seems to work fine. But whenever I perform query it fails and blockchain stops displaying the below error. Error starting Simple chaincode: Error handling message: [1e85621d-4ea5-4f7c-85bd-d532370416bb]Chaincode handler FSM cannot handle message (RANGE_QUERY_STATE) with payload size (10) while in state: ready While debugging I came accross this issue https://github.com/hyperledger-archives/fabric/issues/905 but it isnt helping. Have someone else faced similar issue before? Thanks. A: Well got the issue. I was using docker images for deploying the peer and memberservice while fetching the latest chain code from git on my local machine in order to build and deploy. So the code which was in docker image and the latest chain code had different version hence there were some conflicts giving that error. Solved it by deploying the chaincode which was present inside the dockerimage.
doc_23534273
* *Components - All uncheck except typography? what about Responsive utilities? *Glyphicons - only Glyphicons? 3 JavaScript components - Any or None? A: You have to disable everything except for the Components -> Glyphicons If you only need glyphicons.
doc_23534274
seriesClick: function (e) { //console.log(e.category); // use scope.$emit to pass it to controller scope.$emit('feederValue', e.category); }, In my controller I am using $scope.$on('feederValue', function (evt, value) { console.log(value); $scope.feederFitBoundValue = value; $scope.getFitBoundForFeederID($scope.feederFitBoundValue); }); I want to define this function in my different directive And I want to use it My code function getFitBoundForFeederID(feederFitBoundValue){ alert(feederFitBoundValue); } I am getting error TypeError: undefined is not a function My project is in Angular framework I want to use logic of $emit and $on Please suggest if any optimus solution. I just want to pass value from One directive to different directive. same time I want to pass some value from one directive to another. I want to do event triggering. A: An easy fix would be to emit the event on the $rootScope and watching this event on the $rootScope as well, but i'm not sure it's the best way to do that. A: To pass value from one directive to another you can use factory to create your service which holds the shared data. app.factory("sharedDataService", function() { return { yourData: "anything" }; });
doc_23534275
function createRow1(i) // start create row { row1 = Ti.UI.createView({ backgroundColor: 'white', borderColor: '#bbb', borderWidth: 1, width:'100%', height: 70, top: 0, left: 0 }); var tfield1 = []; var label1 = []; var label2 = []; for (i=0;i<6;i++) { tfield1[i] = Ti.UI.createTextField(baseAttrs); label1[i] = Ti.UI.createLabel(lbAttrs1); label2[i] = Ti.UI.createLabel(lbAttrs2); } tfield1[0].addEventListener('change', function() { if (tfield1[0].value > 10) { tfield1[0].value = ""; showMessageTimeout("More than 10.",15); } }); // 6 listeners created, one for each element in the // tfield[] array. Omitted for brevity. tfield1[0].left ="0%"; tfield1[1].left ="12%"; tfield1[2].left ="24%"; tfield1[3].left ="36%"; tfield1[4].left ="48%"; tfield1[5].left ="60%"; for (i=0;i<6;i++) { row1.add(tfield1[i]); row1.add(label1[i]); row1.add(label2[i]); } return row1; } /// end of createrow1 for(i = 0; i < 10; i++){ row1 = createRow1(i); scrollView1.add(row1); } /* all six rows are added to a scrollview. A button click fires a listener that sums each row which should also calc a running total of all rows. When called the calc function either shows tfield[] as undeclared or as a blank, depending on where tfield[] is declared. */ A: I was answering your last question, but it was deleted. First of all, your question now isn't so clear as before. I think is the lack of code. But don't worry, I have all the code you posted. So: What you are really doing its a matrix of elements, I think an easy way for you to have access to all the textField elements would be: var tfields = []; buttonCalc.addEventListener('click',function(e) { showMessageTimeout("calc pressed",15); alert(tfields[0][0].value); // alert(tfield1[0].value); // reference to tfield[0] blows up. }); ... function createRow1(i) // start create row { ... tfields.push(tfield1); //Add this line here return row1; } /// end of createrow1 I already had answers to all of your other questions, you can make a new question with them :-)
doc_23534276
How could I partition a big table in the postgreSQL with Active Record on Rails 4 I prefer PostgreSQL or other RDBMS, because I tried it in MongoDB. It is really slow on it. Is Rails 4 supporting good solution for a one whole big table ? (my case: more than 50 billions of records, size is about 20TB) Data description There are a User table containing name, personal_data, year fields. The data can be divided by year and the data will be divided evenly. Ideas I think it is not practical to create multiple model like User_1950, User_2001,..., User_2015 I want to partition whole data by year There are two approached I can think of * *split into different physical table in the same database. (sharding ?) *split into different physical database on the different databases. (could it works well with Rails) I want the solution can compatible with Active Record it will act like User.find(name: xxx, year: 1988) User.find(name: xxx, year: 2012) So that I don't care about how to access the partitioned multiple tables. As far as I know I found a gem partitioned but which is not supporting Rails 4 A: Since you are storing the data by years, maybe you can use sharded data based on years. I would suggest octopus for use with activerecord. Your queries will become something like: User.using(:year_2012).find(name: xxx)
doc_23534277
public function index(Request $request) { $clients = Client::orderBy('identifier', 'name')->paginate(15); return view('admin.clients.index')->with('clients', $clients); } public function closed() { $sortBy = 'name'; $query = Client::onlyTrashed()->orderBy($sortBy, $sortBy == 'created_at' ? 'name' : 'asc') ->orderBy('created_at', 'name'); $projects = $query->get(); return view('admin.clients.index')->with(['clients' => $projects, 'sortBy' => $sortBy]); } A: orderBy(string $column, string $direction = 'asc') orderBy has two parameters, the second one is direction. Before version 5.8, if the direction value you passed is not asc, it will automatically set desc as direction value: $this->{$this->unions ? 'unionOrders' : 'orders'}[] = [ 'column' => $column, 'direction' => strtolower($direction) == 'asc' ? 'asc' : 'desc', ]; After Laravel 5.8+, if the direction value is not asc or desc, it will show the error: if (! in_array($direction, ['asc', 'desc'], true)) { throw new InvalidArgumentException('Order direction must be "asc" or "desc".'); } So if you want to order by two column, you can use two orderBy: $clients = Client::orderBy('identifier')->orderBy('name')->paginate(15); # Raw SQL: # select * from clients order by identifier asc, name asc
doc_23534278
$sql1 = "SELECT * FROM videos WHERE user_id = $user_id"; $sql2 = "SELECT * FROM photos WHERE user_id = $user_id"; $sql3 = "SELECT * FROM audios WHERE user_id = $user_id"; SORT DESC BY $result['upload_date']; A: You want to create a JOIN. If you only want rows where there are existing relationships, you can use an inner join, set up like this: SELECT * FROM videos v JOIN photos p ON p.user_id = v.user_id JOIN audios a ON a.useR_id = p.user_id ORDER BY upload_date DESC; The above will select all columns, which may have some repeated things. For example I believe user_id will show up once for each table you joined, so I would narrow down your select clause.
doc_23534279
A: There are so many good modules which generate single installer *exe file. Check out any of these: * *electron-builder (genrates executable for Windows,Mac and Linux, have server-less app auto-update feature,code signing, publishing etc, less boilerplate) *electron-forge (genrates executable for Windows,Mac and Linux, it not just package apps but helps you create them as well, more boilerplate) *windows-installer (easy to use, light weight, and generates only exe file) (still confused which one to pick? compare here) A: You can also try with the electron-boilerplate. Which has 'release' task of gulp and it will create single ready to go executable file for all cross platform. You only need to build application from all three platform to generate particular platform executable.So you don't need to install any third party tool. A: To package the electron app as installable or executable. electron-builder should be the best choice. And it's easy to configure and we can use electron auto-updater too. Here is the example of electron-builder.json { "publish": { // This can be also 's3', 'github'... based on which server you are using for publish // https://www.electron.build/configuration/publish "provider": "generic", // Feed URL but github provider case, other fields will be required. 'repo', 'owner'... "url": "https://myappserver.com/updates/" }, "productName": "My App", "appId": "com.myapp.app", "directories": { // The icon and background in 'buildResources' will be used as app Icon and dmg Background "buildResources": "buildResources", // output is directory where the packaged app will be placed "output": "release" }, // The files which will be packed "files": ["src/", "node_modules/", "package.json"], "mac": { "target": ["dmg", "zip"], // Also can be, 'pkg', ... "artifactName": "${productName}-${version}-${os}.${ext}" }, "win": { "target": ["nsis", "zip"], // Also can be, 'portable', ... "artifactName": "${productName}-${version}-${os}.${ext}" }, "linux": { "target": ["AppImage"], "artifactName": "${productName}-${version}-${os}.${ext}" }, "dmg": { "title": "${productName}-${version}", "contents": [ { "x": 300, "y": 360 }, { "x": 490, "y": 360, "type": "link", "path": "/Applications" } ] } } Of course, we can add other configurations such as nsis, extraFiles, afterPack, afterSign... The above are well-used. You can check details and other fields at here https://www.electron.build/configuration/publish We can define this configuration at the inside of package.json or as an isolated file but the name should be electron-builder.json or electron-builder.yml at the project root directory. And in addition, for auto-update. We should upload the installers(dmg, exe, appImage) among with zip, blockmap and latest-{OS_Name}.ymlfiles. A: You can package your program using electron-packager and then build a single setup EXE file using InnoSetup. A: npm install -g electron-packager --save-dev npx electron-packager <appDirectory> appName --platform=win32 --arch=x64 npx electron-packager <appDirectory> appName --overwrite --asar --electron-version=13.4.0 --platform=win32 --arch=x64 --prune=true --out=release-builds --icon=./build/icon.ico" A: Since most answers dont have step by step instructions on packaging, let me post how i got to package the electron app. We will be installing electron-packager first. Electron Packager is a command line tool and Node.js library that bundles Electron-based application source code with a renamed Electron executable and supporting files into folders ready for distribution. Install electron-packager : run following command in windows cmd npm install -g electron-packager --save-dev Next, lets package our app for windowsx64: electron-packager appdirectory appName --platform=win32 --arch=x64 --electron-version=1.4.3 A: This worked for me in 2021/2022: * *Install Electron Packager globally. Run the following command in command prompt npm install electron-packager -g *Run the following command in command prompt: electron-packager D:\sample MySample --platform=win32 --arch=x64 The above command shows the following output: Packaging app for platform win32 x64 using electron v16.0.5 After 5-10 minutes, it creates the folder with the necessary files and shows the following output in the screen: Wrote new app to D:\sample\MySample-win32-x64 The above output directory in my case was 1.09 GB in size. So ensure that you have enough space in your hard drive before you run the command mentioned in the 2nd point above. *If you navigate to the above directory, you will see the following EXE file in it: MySample.exe Double clicking on the MySample.exe will launch the file with the app ready for your use. Also note that it will work on localhost. So enjoy! A: 2020 Update You can use electron-builder to create portable .exe file for your electron app. All you need to do is install electron-builder with yarn add electron-builder --dev Then create a package.json file like this(this is just for portable .exe): { "name": "my-electron-app", "productName": "electron app", "version": "1.0.0", "description": "an electron app", "main": "main.js", "scripts": { "start": "electron .", "dist": "electron-builder" }, "devDependencies": { "electron": "^8.0.2", "electron-builder": "^22.3.2" }, "build": { "appId": "com.electron.app", "win": { "target": "portable" }, "portable": { "unicode": false, "artifactName": "my_electron_app.exe" } } } A: well ... this will work but the idea is to run the .exe without need of install it in the pc ... another solution is use Autoplay media Studio for wrap you package generated by electron and make one executable or other solution is to use thinstall vmware... The cons both are commercial so you have to paid for them... A: There's a lot of solutions, I recommend using the 3rd option but these are all the ones I know * *Use electron-packager *Use electron-forge *Try this: https://stackoverflow.com/a/69807948/15233276 A: You need to install electron-packager You can follow the below steps. # for use in npm scripts npm install electron-packager --save-dev # for use from cli npm install electron-packager -g electron-packager <sourcedir> <appname> --platform=win32 --arch=x64 Here is an example command. electron-packager . app --platform win32 --arch x64 --out dist/ A: You might be able to "wrap" the entire electron app in a .NET project. Then the single executable that it creates can then just "internally" run the electron app. A: I first tried the electron-packager but it produced a lot of .dll files and still could not run. What did work for me was: npm install npm run dist --ia32 This produced a single self contained exe, no other files needed to run the application.
doc_23534280
Everything was working fine until a couple of days ago, when twitter started to give strange error messages I have never seen before, such as NULL or 0. When I try to connect with twitter to authorize again my own app, after an the eternity it gets to connect, all I get is "NULL Could not connect to Twitter. Refresh the page or try again later.". Is this happening to me only? I have seen that the API has had issues these days, but not today they say. I don't know what the problem can be. Twitter starts to be embarassingly difficult to manage, for one who is not a professional developer at least. Thanks in advance for any suggestions to resolve this. EDIT: I have tried a good number of libraries now and what was working until a week ago isn't working now. Neither twitteroauth nor thmOauth work anymore and I'd pay to know the reason. The black-out has been going on for a week now and my users might have started to realize. The Twitter support, contacted, says that everything is fine on their side. I have tried everything I think, to no avail. A: I had the same problem with the twitter api in ASP code. The problem was that the 'user-agent' header had to be sent with the request. If you leave it out it will give strange results. See the ASP question So make sure your request to the api includes the user-agent header, doesnt matter what the value is. A: well in the end I figured out. Just a matter of shared IP blacklisted. Thanks for your suggestion, which might have worked.
doc_23534281
View code: <% @json = Map.find_by_id('39').to_gmaps4rails %> <%= gmaps("markers" => {"data" => @oldjson, "options" => { "draggable" => true } } ) %> <script> Gmaps.map.replaceMarkers(<%= @json %>); </script> Thanks. A: I guess you"re facing a js error with this current code. The reason is the following: * *the js used and created by gmaps4rails is put within the yield :scripts *so your additionnal js here is called before the map is created Solution: <% @json = Map.find_by_id('39').to_gmaps4rails %> <%= gmaps("markers" => {"data" => @oldjson, "options" => { "draggable" => true } } ) %> <% content_for :scripts do %> <script> Gmaps.map.replaceMarkers(<%= @json %>); </script> <% end %>
doc_23534282
originale<-read.table("file.txt", header=TRUE,sep=";") require(ggplot2) require(ggmap) map <- get_map(location = c(lon=13.781693, lat=45.623124), zoom = 14, maptype = "terrain",source = "google") p <- ggmap(map) p_punti <- p + geom_point(data=originale, aes(x=lon, y=lat),size=5) plot(p_punti) Now I'd like to plot them using a set of 5-6 colours based on the number of observation located on that point. Like this one that I've created on CartoDB: http://i.stack.imgur.com/Be1DL.png The map plotted with CartoDB is, indeed, too approximate: I need to set my own range for each colour. A: I found a working solution counting recurrence for each observations in a new dataframe and then plotting the map using geom_point combined with scale_colour_discrete and breaks. ThanksJosh and Ista for your suggestions! Here's the code: require(plyr) df <-read.table("input.txt", header=TRUE,sep=";") ##selection original <- df[(df$Year==2013),] # ##count recurrence conteggi2 <- ddply(original, .(original$lon, original$lat), nrow) names(conteggi2) <- c("lon", "lat", "Freq") ##sort conteggi2 <- conteggi2[with(conteggi2, order(Freq)), ] ##Classification verdi <- conteggi2$Freq <= 5 conteggi2$classe[verdi] <- "1-5" gialli <- conteggi2$Freq > 5 & conteggi2$Freq <= 20 conteggi2$classe[gialli] <- "6-20" rossi <- conteggi2$Freq > 20 & conteggi2$Freq <= 50 conteggi2$classe[rossi] <- "21-50" neri <- conteggi2$Freq > 50 & conteggi2$Freq <= 500 conteggi2$classe[neri] <- "51-500" ##plot map require(ggplot2) require(ggmap) library(reshape2) Trieste <- qmap(location = c(lon=13.781693, lat=45.623124), zoom = 13, legend = "topleft", color="bw")#maptype = "terrain", Trieste1 <- Trieste + geom_point(aes(x = lon, y = lat, colour = classe, title='Year 2013'), data = conteggi2) + guides(size=FALSE) + #remove useless label scale_colour_discrete(name="Legend Title", breaks=c("1-5","6-20","21-50", "51-500")) plot(Trieste1)
doc_23534283
What's wrong with my syntax ? AddressItem_Callback_ContextType *context; //check if icons need to be downloaded if (pEntity->cBigIcon[0] != 0){ if (res_get(RES_BITMAP,RES_SKIN, pEntity->cBigIcon) == NULL){ context = {pEntity->iID, pEntity->cBigIcon}; //context->Icon = pEntity->cBigIcon; //context->iID = pEntity->iID; res_download(RES_DOWNLOAD_IMAGE, pEntity->cBigIcon, NULL, "",TRUE, 1, addressItem_icon_download_callback, context ); } } I get syntax error for this as well: AddressItem_Callback_ContextType *context = {0,NULL}; //check if icons need to be downloaded if (pEntity->cBigIcon[0] != 0){ if (res_get(RES_BITMAP,RES_SKIN, pEntity->cBigIcon) == NULL){ //context = {pEntity->iID, pEntity->cBigIcon}; context->Icon = pEntity->cBigIcon; context->iID = pEntity->iID; res_download(RES_DOWNLOAD_IMAGE, pEntity->cBigIcon, NULL, "",TRUE, 1, addressItem_icon_download_callback, context ); } } if (pEntity->cSmallIcon[0] != 0){ if (res_get(RES_BITMAP,RES_SKIN, pEntity->cSmallIcon) == NULL){ //context = {pEntity->iID, pEntity->cSmallIcon}; context->Icon = pEntity->cSmallIcon; context->iID = pEntity->iID; res_download(RES_DOWNLOAD_IMAGE, pEntity->cSmallIcon, NULL, "",TRUE, 1, addressItem_icon_download_callback, context ); } } then this (3) should work? AddressItem_Callback_ContextType context = {0,NULL}; //check if icons need to be downloaded if (pEntity->cBigIcon[0] != 0){ if (res_get(RES_BITMAP,RES_SKIN, pEntity->cBigIcon) == NULL){ //context = {pEntity->iID, pEntity->cBigIcon}; context.Icon = pEntity->cBigIcon; context.iID = pEntity->iID; res_download(RES_DOWNLOAD_IMAGE, pEntity->cBigIcon, NULL, "",TRUE, 1, addressItem_icon_download_callback, context ); } } if (pEntity->cSmallIcon[0] != 0){ if (res_get(RES_BITMAP,RES_SKIN, pEntity->cSmallIcon) == NULL){ //context = {pEntity->iID, pEntity->cSmallIcon}; context.Icon = pEntity->cSmallIcon; context.iID = pEntity->iID; res_download(RES_DOWNLOAD_IMAGE, pEntity->cSmallIcon, NULL, "",TRUE, 1, addressItem_icon_download_callback, context ); } } A: context = {pEntity->iID, pEntity->cBigIcon}; {} initializer list can only be used at declaration time, it cannot be used in an assignment expression. You have to break this down in two assignment statements (and for this you'll also have to initialize the uninitialized context pointer). A: As ouah says initializers must be used at declaration time, but in C99 you can make use of compound literals: #include <stdio.h> struct st { int a, b; }; int main(void) { struct st *t; t = &(struct st){1, 2}; printf("%d %d\n", t->a, t->b); return 0; } in your case context = &(struct AddressItem_Callback_ContextType){pEntity->iID, pEntity->cBigIcon};
doc_23534284
Any suggestions regarding this? Thanks. Here is the column format I am using: colModel:[ {name:'id_no',index:'id_no', sorttype:"string"} ] A: As you mentioned in your comments, your web service is truncating the zero's, not jqGrid. To further isolate the problem I recommend you post some of your server-side code to retrieve data from the database and serialize it to JSON.
doc_23534285
My RecyclerView is defined as follows: // 1. get a reference to recyclerView mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView); // 2. set layoutManger mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); // 3. create an adapter mAdapter = new ItemsAdapter(itemsData); // 4. set adapter mRecyclerView.setAdapter(mAdapter); And the data that I am showing is something like: ItemData itemsData[] = { new ItemData("Mary Richards"), new ItemData("Tom Brown"), new ItemData("Lucy London") }; So when when I want to give the adapter another set of data, another array (with one item for example), what should I do? A: Just re-initialize your adapter: mAdapter = new ItemsAdapter(newItemsData); or if you only need to remove add a few specific items rather than a whole list: mAdapter.notifyItemInserted(position); or mAdapter.notifyItemRemoved(position); A: If you want to change the complete Adapter in the recycler view. you can just simply set by recycler.setAdapter(myAdapter); It will automatically remove the old adapter from recycler view and replace it with your new adapter. A: This is my answer - thanks to Ivan Skoric from his site: http://blog.lovelyhq.com/creating-lists-with-recyclerview-in-android/ I created an extra method inside my adapter class: public void updateList(List<Data> data) { mData = data; notifyDataSetChanged(); } Then each time your data changes, you just call this method passing in your new data and your view should change to reflect it. A: If you have stable ids in your adapter, you can get pretty good results (animations) if you create a new array containing the filtered items and call recyclerView.swapAdapter(newAdapter, false); Using swapAdapter hints RecyclerView that it can re-use view holders. (vs in setAdapter, it has to recycle all views and re-create because it does not know that the new adapter has the same ViewHolder set with the old adapter). A better approach would be finding which items are removed and calling notifyItemRemoved(index). Don't forget to actually remove the item. This will let RecyclerView run predictive animations. Assuming you have an Adapter that internally uses an ArrayList, implementation would look like this: // adapter code final List<ItemData> mItems = new ArrayList(); //contains your items public void filterOut(String filter) { final int size = mItems.size(); for(int i = size - 1; i>= 0; i--) { if (mItems.get(i).test(filter) == false) { mItems.remove(i); notifyItemRemoved(i); } } } It would perform even better if you can batch notifyItemRemoved calls and use notifyItemRangeRemoved instead. It would look sth like: (not tested) public void filterOut(String filter) { final int size = mItems.size(); int batchCount = 0; // continuous # of items that are being removed for(int i = size - 1; i>= 0; i--) { if (mItems.get(i).test(filter) == false) { mItems.remove(i); batchCount ++; } else if (batchCount != 0) { // dispatch batch notifyItemRangeRemoved(i + 1, batchCount); batchCount = 0; } } // notify for remaining if (batchCount != 0) { // dispatch remaining notifyItemRangeRemoved(0, batchCount); } } You need to extend this code to add items that were previously filtered out but now should be visible (e.g. user deletes the filter query) but I think this one should give the basic idea. Keep in mind that, each notify item call affects the ones after it (which is why I'm traversing the list from end to avoid it). Traversing from end also helps ArrayList's remove method performance (less items to shift). For example, if you were traversing the list from the beginning and remove the first two items. You should either call notifyItemRangeRemoved(0, 2); // 2 items starting from index 0 or if you dispatch them one by one notifyItemRemoved(0); notifyItemRemoved(0);//because after the previous one is removed, this item is at position 0 A: As ygit answered, swapAdapter is interesting when you have to change the whole content. But, in my FlexibleAdapter, you can update the items with updateDataSet. You can even configure the adapter to call notifyDataSetChanged or having synchronization animations (enabled by default). That, because notifyDataSetChanged kills all the animations, but it's good to have for big lists. Please have a look at the description, demoApp and Wiki pages: https://github.com/davideas/FlexibleAdapter
doc_23534286
SQL_REGEX = %r((?-mix:SQL query error)|(?-mix:MySQL Query Error)|(?-mix:expects parameter)|(?-mix:You have an error in your SQL syntax)) I would like a regex that will find the error messages on a website if they have incorrectly closed SQL syntax, the one above works, but it seems to me that it's a little slower then it could be, any suggestions on how to make a better more reliable regex?
doc_23534287
{"profiles":[ {"ID": "39780b57-9181-4a41-a31e-5d4b3fa59a50", "Name": "Mihai - BP Dev Team","CountryCode": "ro","PictureID": "a30d750a-38e6-407f-a722-943fe3711807","IsStandard": true,"IsOnline": true,"IsPremium": true,"IsVerified": true,"Age": 27,"CityStateCode": "Bucharest"}, {"ID": "e1dd5bab-1eeb-4729-a4f6-0baeb851f750", "Name": "Nicolai", "CountryCode": "dk", "PictureID": "af1345b5-8380-4300-abf0-1d5f15c90040", "IsStandard": true, "Age": 32, "CityStateCode": "Valby"}, {"ID": "2c8535ec-25a4-4a3e-a333-c3797aff491f", "Name": "Testing", "CountryCode": "ca", "PictureID": "ba44bf9b-1592-40a8-b60c-068603bfb9c1", "IsStandard": true, "Age": 30, "CityStateCode": "Centre-Sud North"}} ]} This is my PHP code : $accessDb = new Connexion("gaiurba_MyBD"); $connexion2 = $accessDb->openConnexion(); if ($query2 = $connexion2->prepare("SELECT u.UserName as UserName, u.PictureID as PictureID, u.CountryCode as CountryCode, u.DateOfBirth as DateOfBirth, u.CityCode as CityCode, u.VerifiedTimestamp as VerifiedTimestamp, u.OnlineStatus as OnlineStatus, u.IsPaying as IsPaying, u.StatusAvailableForDates as StatusAvailableForDates, cc.$languageCode as CityStateCode, os.$languageCode as LabelOnlineStatus FROM Users u INNER JOIN CityCode cc ON u.CityCode = cc.id INNER JOIN OnlineStatus os ON u.OnlineStatus = os.id WHERE u.ID = ?")) { $query2->bind_param('s', $id); $query2->execute(); $query2->bind_result($UserName, $PictureID, $CountryCode, $DateOfBirth, $CityStateCode, $VerifiedTimestamp, $OnlineStatus, $IsPaying, $StatusAvailableForDates, $CityStateCode, $LabelOnlineStatus); $query2->store_result(); $affected2 = $connexion2->affected_rows; // TRACE echo "[affected2 row 2 = $affected2]"; if ($affected2 == 1) { while ($query2->fetch()) { echo "[ID = $id - UserName = $UserName - PictureID = $PictureID - CountryCode = $CountryCode - DateOfBirth = $DateOfBirth - CityStateCode = $CityStateCode - VerifiedTimestamp = $VerifiedTimestamp - OnlineStatus = $OnlineStatus - IsPaying = $IsPaying - StatusAvailableForDates = $StatusAvailableForDates - CityStateCode = $CityStateCode - LabelOnlineStatus = $LabelOnlineStatus]"; } } else { $result = '{"exception":false,"success":false,"status":0,"message":"ERROR SQL Query : SELECT-ULL-ID Number of row !","confirmMessage":null,"html":null,"data":null}'; } } else { $result = '{"exception":false,"success":false,"status":0,"message":"ERROR SQL Query : SELECT-ULL-ID Number of row !","confirmMessage":null,"html":null,"data":null}'; } I know the right code is on my while($query2->fetch()) condition because my echo see me good information read from my BD. The first thing i need to create an array in PHP and append each row fetched from BD and at the end use echo json_encode($result); Do not pay attention to my data return by me SELECT and the data in the JSON string. I know I'll have to format some data in my while loop to get the right result. I just need to know how to create an array in which I add a new array for each rows returned by MySQL. Thank you for your helping ! A: Creating an array is as simple as: $profiles = array(); or just // Add an item. Array is created if $x didn't contain an array already. $profiles[] = 'foo'; So to create something with the structure you like, you'll need an object with a property that contains an array of objects representing the rows. You can create a simple object in a similar fashion as arrays: just start assigning properties. So to create the array of profiles, just do this for each row: $profile = null; $profile->UserName = $UserName; $profile->PictureID = $PictureID; // Etc Maybe your database class supports a method to return an entire row as an object instead of calling fetch() combined with outbound parameters. That way you don't need to create the object yourself, saving a couple of lines. // Add profile object to array. $profiles[] := $profile; Maybe your database class supports a way to return the entire dataset as an array of objects. If so, you don't need to loop and build the array yourself. Saving yet another couple of lines of code. However you have built the array, afterwards, wrap it in another object, in its profiles property to be precise. $result = null; $result->profiles = $profiles; And output: echo json_encode($result); It's not strictly necessary to make a variable null before starting to assign properties, but it prevents accidental reuse of an old variable. Especially in the loop this is required, otherwise you'll just reassign the properties of the same object and add the same object a number of times to the array, leading to undesired results (every row being the same). Instead of just assigning properties, you can actually create an object before doing so: $profile = new StdClass(); This is a little more verbose and therefor maybe a little more readable, just as using array() to initialize an empty array. It's a matter of personal taste.
doc_23534288
Here's the code sample from my friend's end: DelegateExecution delEx = delegateTask.getExecution(); for(TransactionItem itemTransItem : transItem) { List forRequest = daoManager.getLaptopsForRequest(BigInteger.valueOf(itemTransItem.getAssetType().getId()), BigInteger.valueOf(approverId)); forRequest.forEach(System.out::println); System.out.print(itemTransItem.getId()); forReqeustMap.put(String.valueOf(itemTransItem.getId()), forRequest); } delEx.setVariable("forRequestMap", forReqeustMap); The for loop sets the hashmap. Of note is that the value is a List, of (presumably) raw type. The last line sets the hashmap in the delegate execution. Now, here's the code on my end: DelegateExecution delEx = delegateTask.getExecution(); HashMap<String,List> forReqeustMap = (HashMap<String, List>) delEx.getVariable("forRequestMap"); if (forReqeustMap.isEmpty()){ System.out.println("Uh oh."); } else{ System.out.println("Something else is wrong."); forReqeustMap.forEach((k,v) -> System.out.println("key: "+k+" value:"+v)); } for (TransactionItem itemTransItem : transItem) { System.out.println(itemTransItem.getId()); List forRequest = new List(forReqeustMap.get(String.valueOf(itemTransItem.getId()))); if (forRequest.isEmpty()){ System.out.println("Uh oh."); } else { System.out.println("What"); } } Testing the hashmap forRequestMap for values yields true; the values are there. The problem is extracting the list. The code I have simply doesn't work, yielding a null. I'm assuming it has something to do with either the way I'm trying to get the values, or the list itself - it won't even reach my if-else block without conking out. I tried: * *adding a <?> to the List *this: List forRequest = forReqeustMap.get(itemTransItem.getId()); *as well as adding @SuppressWarnings("rawtypes"), But none seems to work. Any ideas? EDIT: Here's an output log: Output from the first batch of code: forRequest.forEach(System.out::println); System.out.print(itemTransItem.getId()); {asset_type_id=1, asset_id=1, id=1} {asset_type_id=1, asset_id=2, id=2} 161 And here's the output from the 2nd batch (modified slightly from initial code): forReqeustMap.forEach((k,v) -> System.out.println("key: "+k+" value:"+v)); System.out.println(itemTransItem.getId()); key: 161 value:[{asset_type_id=1, asset_id=1, id=1}, {asset_type_id=1, asset_id=2, id=2}] 161 EDIT: Update: Changed this: if (forRequest.isEmpty()){ System.out.println("Uh oh."); } To this: if (forRequest == null){ System.out.println("Uh oh."); } And then I get an "Uh oh". Which means my forRequest is null. I then printed out the following: System.out.println(forReqeustMap.get(itemTransItem.getId())); Which gave me back a null, despite just printing out the k and v earlier. Now I'm really stumped. Any ideas?
doc_23534289
I want to display a set of tags side by side in an Android app. Conditions are: * *Each tag appear next to the previous tag. *If the horizontal space runs out, the next tag appears in a new line. *If there are multiple words in a tag and there's only a space for some of the words of a tag, move the whole tag in a new line. However, if the tag was already in a new line, let the tag break in two lines. I'm not sure what this technique is called. Any help on the issue, whether by code or link to a library, will be greatly appreciated. A: You can use simple libraries for tags, fo instance: AndroidTagGroup Add to your xml: <me.gujun.android.taggroup.TagGroup android:id="@+id/tag_group" style="@style/TagGroup" /> And add code: TagGroup mTagGroup = (TagGroup) findViewById(R.id.tag_group); mTagGroup.setTags(new String[]{"Tag1", "Tag2", "Tag3"}); Anoter solution is: AutoLabelUI Add to xml: <com.dpizarro.autolabel.library.AutoLabelUI android:id="@+id/label_view" android:layout_width="match_parent" android:layout_height="wrap_content"/> And add to code: AutoLabelUI mAutoLabel = (AutoLabelUI) view.findViewById(R.id.label_view); AutoLabelUISettings autoLabelUISettings = new AutoLabelUISettings.Builder() .withMaxLabels(5) .withIconCross(R.drawable.cross) .withBackgroundResource(android.R.color.holo_blue_bright) .withLabelsClickables(false) .withShowCross(true) .withTextColor(android.R.color.holo_red_dark) .withTextSize(R.dimen.label_title_size) .build(); mAutoLabel.setSettings(autoLabelUISettings); Also, you may use HashtagView A: @Umair you could also do the same thing from Xml as : <com.dpizarro.autolabel.library.AutoLabelUI android:id="@+id/label_view" android:layout_width="wrap_content" android:layout_height="wrap_content" autolabel:icon_cross="@drawable/cross" autolabel:label_background_res="@color/light_greylabel" autolabel:label_clickable="true" autolabel:label_padding="5dp" autolabel:max_labels="10" autolabel:show_cross="true" autolabel:text_color="@color/app_grey" autolabel:text_size="@dimen/label_title_size" /> you could get the library from Here
doc_23534290
My next step before removing the container, see the list of existing container sts@Yudi:~/docker$ sudo docker ps -as CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES SIZE 78479ffeba5c ubuntu "/bin/bash" 42 hours ago Exited (0) 42 hours ago sharp_wescoff 81 B (virtual 187.7 MB) 0bd2b54678c7 training/webapp "python app.py" 5 days ago Exited (0) 5 days ago backstabbing_ritchie 0 B (virtual 323.7 MB) 0adbc74a3803 training/webapp "python app.py" 5 days ago Exited (143) 5 days ago drunk_feynman 0 B (virtual 323.7 MB) one I want to delete the list, namely "training / webapp" but an error that occurred sts@Yudi:~/docker$ sudo docker rmi training/webapp Error response from daemon: conflict: unable to remove repository reference "training/webapp" (must force) - container 0bd2b54678c7 is using its referenced image 54bb4e8718e8 Error: failed to remove images: [training/webapp] Whether the container is running in the images? Please help A: First, remove the container names $ sudo docker rm backstabbing_ritchie The result $ sudo docker rm backstabbing_ritchie backstabbing_ritchie delete the second part, which is listed on the container to be deleted $ sudo docker rm drunk_feynman drunk_feynman Second, remove the container $ sudo docker rmi training/webapp The result $ sudo docker rmi training/webapp Untagged: training/webapp:latest Deleted: 54bb4e8718e8600d78a5d7c62208c2f13c8caf0e4fe73d2bc0e474e93659c0b5 Deleted: f74dd040041eb4c032d3025fe38ea85de8075992bdce6789b694a44b20feb8de Deleted: 7cbae69141977b99c44dc6957b032ad50c1379124d62b7d7d05ab7329b42348e Deleted: abb991a4ed5e4cde2d9964aec4cccbe0015ba9cc9838b696e7a32e1ddf4a49bd Deleted: 1952e3bf3d7e8e6a9b1e23bd4142e3c42ff7f4b7925122189704323593fd54ac Deleted: f95ebd363bf27a7546deced7a41a4099334e37a3d2901fa3817e62bb1ade183f Deleted: 20dd0c75901396d41a7b64d551ff04952084cc3947e66c67bae35759c80da338 Deleted: 2505b734adda3720799dde5004302f5edb3f2a2ff71438f6488b530b728ba666 Deleted: 2ee0b8f351f753f78f1178000ae37616eb5bf241d4ef041b612d58e1fd2aefdc Deleted: 2ce633e3e9c9bd9e8fe7ade5984d7656ec3fc3994f05a97d5490190ef95bce8d Deleted: 98b15185dba7f85308eb0e21196956bba653cf142b36dc08059b3468a01bf35d Deleted: 515565c29c940355ec886c992231c6019a6cffa17ff1d2abdfc844867c9080c5 Deleted: 2880a3395eded9b748c94d27767e1e202f8d7cb06f1e40e18d1b1c77687aef77 Check the continer $ sudo docker ps -as CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES SIZE 78479ffeba5c ubuntu "/bin/bash" 43 hours ago Exited (0) 43 hours ago sharp_wescoff 81 B (virtual 187.7 MB) A: 1-Stop running container: docker stop <container-id> 2-Remove container docker rm <container-id> 3-Remove docker image docker rmi <image-id> A: list all your docker images: docker images list all existed docker containers: docker ps -a delete all the targeted containers, which is using the image that you want to delete: docker rm <container-id> delete the targeted image: docker rmi <image-name:image-tag or image-id> A: Noticed this is a 2-years old question, but still want to share my workaround for this particular question: Firstly, run docker container ls -a to list all the containers you have and pinpoint the want you want to delete. Secondly, delete the one with command docker container rm <CONTAINER ID> (If the container is currently running, you should stop it first, run docker container stop <CONTAINER ID> to gracefully stop the specified container, if it does not stop it for whatever the reason is, alternatively you can run docker container kill <CONTAINER ID> to force shutdown of the specified container). Thirdly, remove the container by running docker container rm <CONTAINER ID>. Lastly you can run docker image ls -a to view all the images and delete the one you want to by running docker image rm <hash>. A: If you want to cleanup docker images and containers CAUTION: this will flush everything stop all containers docker stop $(docker ps -a -q) remove all containers docker rm $(docker ps -a -q) remove all images docker rmi -f $(docker images -a -q) A: you can use -f option to force delete the containers . sudo docker rmi -f training/webapp You may stop the containers using sudo docker stop training/webapp before deleting A: Deleting "network not found" in docker Inspect the network which we are unable to delete docker network inspect [<id> or <name>] Disconnect the network docker network disconnect -f [<networkID> or <networkName>] [<endpointName> or <endpointId>] Delete unused networks docker network prune A: There is a difference between docker images and docker containers. Check this SO Question. In short, a container is a runnable instance of an image. which is why you cannot delete an image if there is a running container from that image. You just need to delete the container first. docker ps -a # Lists containers (and tells you which images they are spun from) docker images # Lists images docker rm <container_id> # Removes a stopped container docker rm -f <container_id> # Forces the removal of a running container (uses SIGKILL) docker rmi <image_id> # Removes an image # Will fail if there is a running instance of that image i.e. container docker rmi -f <image_id> # Forces removal of image even if it is referenced in multiple repositories, # i.e. same image id given multiple names/tags # Will still fail if there is a docker container referencing image Update for Docker 1.13+ [Since Jan 2017] In Docker 1.13, we regrouped every command to sit under the logical object it’s interacting with Basically, above commands could also be rewritten, more clearly, as: docker container ls -a docker image ls docker container rm <container_id> docker image rm <image_id> Also, if you want to remove EVERYTHING you could use: docker system prune -a WARNING! This will remove: * *all stopped containers *all networks not used by at least one container *all unused images *all build cache A: If you have multiples docker containers launched, use this $ docker rm $(docker ps -aq) It will remove all the current dockers listed in the "ps -aq" command. Source : aaam on https://github.com/docker/docker/issues/12487 A: Remove docker images > List all containers docker container ls List all images docker image ls Stop container by container id docker container stop <container_id> Remove container by container id docker container rm <container_id> If don't want stop and remove, can force remove docker container rm -f <container_id> Remove image docker image rm <image_id> Done! A: Remove just the containers associated with a specific image docker ps -a | grep training/webapp | cut -d ' ' -f 1 | xargs docker rm * *ps -a: list all containers *grep training/webapp : filter out everything but the containers started from the training/webapp image *cut -d ' ' -f 1: list only the container ids (first field when delimited by space) *xargs docker rm : send the container id list output to the docker rm command to remove the container A: Simply these two commands solve my issue. Stop the particular container. docker stop <container_id> Forces removal of the image even if it is referenced in multiple repositories. docker rmi -f <container_id>
doc_23534291
But i am facing an unusual issue here, if i try to change the background colour it is working but the font size change is not working. Following is the my CSS:- @font-face { font-family: myFirstFont; src: url(../fonts/JosefinSlab-regular.ttf); } .frontback{ font-family:myFirstFont; font-size:30px; margin-top:10%; } @media screen and (max-width: 480px) { .frontback{ font-family:myFirstFont; font-size:10px; background-color:red; } } The background colour is getting changed when i reduce the screen size but font size is not getting changed. Can someone please help me on this? A: @media screen and (max-width: 480px) { .frontback{ font-family: myFirstFont; font-size: 10px !important; background-color:red; } } Please try this :)
doc_23534292
Currently :: Supervisor script > Runs Test Scripts > Test Scripts output status What I am trying to do :: Supervisor script > Runs Test Scripts > Test Scripts output status > Supervisor script writes previous step to a file A: I would use python's logging library: import logging # setup log name. default location is the same as the script logging.basicConfig(filename="master.log") script_output = "sample output" print(script_output) logging.info(script_output) See the docs for more info
doc_23534293
My code: <script> function datepick() { var weekend_strtday = 1; var dva = 2; var tri = 3; var cetiri = 4; var pet = 0; var weekend_endday = 5; $('#datum').datepicker({ firstDay: 1, minDate: 0, dateFormat: 'yy-mm-dd', beforeShowDay: function(date) { var day1 = date.getDay(); return [(day1 != weekend_strtday && day1 != weekend_endday && day1 != dva && day1 != tri && day1 != cetiri && day1 != pet)]; } }); } datepick(); </script> A: Try this example: Saturdays can be simplified to day 6, or the month and date is Dec 31. function datepick() { $('#datum').datepicker({ firstDay: 1, minDate: 0, dateFormat: 'yy-mm-dd', beforeShowDay: function(date) { var day = date.getDay(); // Saturdays or Dec 31st return [(day == 6) || ((date.getMonth() + 1) == 12 && date.getDate() == 31)]; } }); } datepick(); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> Date: <input class="form-control" id="datum"></input>
doc_23534294
While we archive the app developed in XCode, it will code sign the app for once before the Organizer windows pop up and show the archive history. For Example: We can see that the app was signed which we can know signing identity and provisioning profile by looking into the log for archive. But when we export the app in Organizer Window, for example export for ad hoc deployment, and following window show the details for the export, This Window also show the provisioning profile, but different from the one that i see from log. (which i set the provisioning profile which shown in the log as the release provisioning profile in Build Settings) May i ask are these two provisioning profile same thing? Can i use different pp when i export the archived app as ipa? Thanks a lot for the help A: You can use different provisioning profiles between your build/archive and when you export them. If you look in the right side of the organizer window, you'll see the "Upload to App Store..." button over the "Export..." button. The organizer re-codesigns your archived app with your App Store distribution certificate if you are uploading that version into the store or TestFlight review, or you can export that binary for ADHOC distribution (to specified devices), Enterprise distribution (distributing within your company) or a development version to people on your team that have the development certificates installed. If you select ADHOC, you have the choice between Automatically Signing (which is the "XC iOS ADHOC" cert you see in that window or Manually (i.e. here is where you can choose from different provisioning profiles: In real life, you'll really want to have your provisioning profile named two different things so you'll know what you're really setting the app to. A: It is depend upon the type of provisioning you are using for type of job. Development : If you want to create .ipa file just to installed in to the registered device you have to choose development provisioning profile. Adhoc : If you want to distribute the app through 3rd party like DiawiIt is suggested to use Adhoc provisioning. App Store distribution : For Test flight release or if you want to upload the binary to app store it required distribution provisioning profile with distribution certificate. Now you are triggering your issue because of mismatching purpose and profile. please create valid provisioning as per your requirement . Let me know if this works.
doc_23534295
<object text="this is a <a>some text</a>" /> My SAXParser is unable to parse this XML as it contains <> tag in its attribute. Anyway to solves this? I tried an online syntax checker and it failed. So does it mean that you cannot define <> tag in an XML attribute? A: Absolutely this is not valid XML. You will need to ensure you escape these characters as discussed in the W3C document http://www.w3.org/TR/xml/#dt-escape For the sake of completeness here is your example and what it will look like if you escape it <object text="this is a &lt;a&gt;some text&lt;/a&gt;" /> or; <object text="this is a &#38;#60;a&#62;some text&#38;#60;/a&#62;" />
doc_23534296
print('a' + [10, 100]) With this I am getting below error Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "list") to str Could you please help hoe to do that? I could use some for loop but I believe there may be more straightforward way to achieve the same. A: You can create a new concatenated array as: >>> ['{0}{1}'.format('a', num) for num in [10, 100]] ['a10', 'a100'] Read String format and List Comprehensions from doc. A: If I understand your question, you want a new string array (list). You could try this: new_lst = ['a'+str(x) for x in [10, 100]] # just use string concatentation
doc_23534297
My Code for (final day in daysRunOn) { databaseReference .collection('users') .document(user.uid) .collection(day) .snapshots() .documents((snapshot) { }); } This post suggests I should not use a stream so I removed it. I am trying to now run this but I keep getting an error on the .documents part which says "The method 'documents' isn't defined for the type 'Stream'." but I don't understand how or why this is still a stream. Suggested method from stack overflow double queryValues() async { total = 0.0; docs = await Firestore.instance .collection('myCollection') .snapshots() .documents((snapshot); docs.forEach((doc) => this.total += doc.data['amount'])); debugPrint(this.total.toString()); return total; } Any help would be greatly appreciated! A: Try something like this: getDocs() async { total = 0.0; snapshot = await Firestore.instance .collection('myCollection') .snapshots(); docs = snapshot.data.documents; docs.forEach((doc) => this.total += doc.data['amount'])); debugPrint(this.total.toString()); return total; } A: try this code List<String> daysRunOn = ['day1','day2','...']; int x = 0; double total = 0.0; Future<double> getTotal() async { if(x == 0) total = 0.0; var querySnapshot = await Firestore.instance.collection('users/${user.uid}/${daysRunOn[x]}').getDocuments(); querySnapshot.documents.forEach((doc) => total += doc.data['amount']); if(x == daysRunOn.length-1){ // the loop has finished x = 0; debugPrint(total.toString()); return total; } else { x++; return getTotal(); } }
doc_23534298
* *The code I came with goes into a infinit redirect loop. *I am receiving the following php error I think related to $_SESSION: [Mon May 25 12:45:40.651325 2015] [:error] [pid 6568] [client 127.0.0.1:48900] PHP Fatal error: Uncaught exception 'Dropbox\\WebAuthException_Csrf' with message 'Expected '0_2rtH-FFcAqzX4JLKPVKw==', got 'zdmJEkNgto3lA7qAgGW2SQ=='.' in /var/www/php/oauth/vendor/dropbox/dropbox-sdk/lib/Dropbox/WebAuth.php:242\nStack trace:\n#0 /var/www/php/oauth/web/dropbox_finish.php(11): Dropbox\\WebAuth->finish(Array)\n#1 {main}\n thrown in /var/www/php/oauth/vendor/dropbox/dropbox-sdk/lib/Dropbox/WebAuth.php on line 242 This is my code start.php: session_start(); require_once __DIR__.'/../vendor/autoload.php'; $key = "fttwagu78r37ped"; $secret = "9s10lkjhrwpujbl"; $GLOBALS['app_name'] = "oauth-php/1.0"; $GLOBALS['redirectURI'] = "https://oauth.dev/dropbox_finish.php"; $GLOBALS['HomeURI'] = "https://oauth.dev"; $appInfo = new Dropbox\AppInfo($key, $secret); $csrfTokenStore = new Dropbox\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token'); $webAuth = new Dropbox\WebAuth($appInfo, $GLOBALS['app_name'], $GLOBALS['redirectURI'], $csrfTokenStore); $authURL = $webAuth->start(); header("Location: $authURL"); and this dropbox_finish.php: require_once "../app/start.php"; try { list($accessToken, $userId, $urlState) = $webAuth->finish($_GET); assert($urlState === null); // Since we didn't pass anything in start() } catch (dbx\WebAuthException_BadRequest $ex) { error_log("/dropbox-auth-finish: bad request: " . $ex->getMessage()); // Respond with an HTTP 400 and display error page... } Can anyone help me with this one? A: It looks like you're including start.php in dropbox_finish.php, but start.php calls $webAuth->start() and then redirects the user. Make sure that the part you're including in dropbox_finish.php doesn't have that call and doesn't set the Location header.
doc_23534299
What is supposed to happen is the page loads, and three videos from the database are loaded, followed by a span. The span has a button to activate a script, a script to send a request to retrieve 3 new items and a button, and a value of 0. You press the button, and 3 new items and a new span, with a new button and script, replace the old button. This way, to the user it looks like there are three items and a button, then you click the button and there are 6 items and the same button, then 9 and a button, etc. Here's the code for the page that loads: $newVideos = mysqli_query($con, "SELECT * FROM videos ORDER BY id DESC LIMIT 0,3"); while ($row = mysqli_fetch_array($newVideos)) { echo '<br> The video "'.$row["title"].'"'; } ?> <span id="newvideos"> <br><button onclick="newvideos(this.value)" value="0">More Videos</button><br> <script> function newvideos(x) { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("newvideos").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET","videosearch.php?morevideos="+x,true); xmlhttp.send(); } </script> </span> And this is what that script is sending a request to: if (isset($_GET['morevideos'])) { $morevideos = $_GET['morevideos']; if (isset($morevideos)) { $y = 3 + $morevideos; $newVideos = mysqli_query($con, "SELECT * FROM videos ORDER BY id DESC LIMIT ".$y.",3"); //DESC is descending, last to first //ASC is ascending, first to last while ($row = mysqli_fetch_array($newVideos)) { echo '<br> The video "'.$row["title"].'"'; } echo '<span id="newvideos'.$y.'">'; echo '<br><button onclick="newvideos(this.value)" value="'.$y.'">More Videos</button><br>'; ?> <script> function newvideos(x) { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("newvideos<?php echo $y; ?>").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET","videosearch.php?morevideos="+x,true); xmlhttp.send(); } </script> </span> <?php } } ?> So what happens instead is that when the first button is clicked, the first button is replaced with 3 new video items, a new script, and a new button inside of a span called "newvideos3". And the script says to replace the innerhtml of an element with the ID "newvideos3". But what happens instead is the still existing parent "newvideos" span is replaced instead with videos 7-9 and a "newvideos6" span, rather than all that being appended to the list. Why, when the script says to replace "newvideos3", would this happen? I also tried going directly to videosearch.php?morevideos=0, and the videos from "newvideos3" loaded. I clicked the button and the next videos, 7-9 and a new button, were appended to the list. Then I clicked that new button, and 7-9 were replaced. Is there some policy or rule about innerhtml replacing parent nodes when scripts are generated from other scripts or something, and I just don't know about it? UPDATE I've made some revisions based on comments by barmar (thanks!), however it still doesn't work. It seems the script was, indeed, not being updated. Here is the revised code. This is what the user sees loaded: $newVideos = mysqli_query($con, "SELECT * FROM videos ORDER BY id DESC LIMIT 0,3"); //DESC is descending, last to first //ASC is ascending, first to last while ($row = mysqli_fetch_array($newVideos)) { echo '<br> The video "'.$row["title"].'"'; } ?> <span id="newvideos"> <br><button onclick="fetchvideos(this.value)" value="0">More Videos</button><br> <script> function fetchvideos(x) { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("newvideos").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET","videosearch.php?morevideos="+x,true); xmlhttp.send(); } </script> </span> And here is what the request is sent to: if (isset($_GET['morevideos'])) { $morevideos = $_GET['morevideos']; if (isset($morevideos)) { $y = 3 + $morevideos; $newVideos = mysqli_query($con, "SELECT * FROM videos ORDER BY id DESC LIMIT ".$y.",3"); //DESC is descending, last to first //ASC is ascending, first to last while ($row = mysqli_fetch_array($newVideos)) { echo '<br> The video "'.$row["title"].'"'; } echo '<span id="newvideos'.$y.'">'; ?> <br><button onclick="fetchvideos<?php echo $y; ?>(this.value, 'newvideos<?php echo $y; ?>')" value="<?php echo $y; ?>">More Videos</button><br>'; <script> function fetchvideos<?php echo $y; ?>(x, z) { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById(z).innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET","videosearch.php?morevideos="+x,true); xmlhttp.send(); } </script> </span> <?php } } Now that the newly generated script is renamed to something different, the web console says that the function fetchvideos3 doesn't exist. It appears that html is not updated with AJAX. Inspector shows that the script is added to the page, but the debugger does not show that the script is added. I would think that since the new script isn't added that the button calling the new script shouldn't technically be able to call the script either, don't really understand that. I've also given everything a unique, generated name, and made it so onclick and the new functions use 2 arguments instead of one. How do I get the newly generated from AJAX scripts to run?