id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23531200
<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body> <p>Change the value of the input field:</p> <div ng-app="" ng-init="myCol='lightblue'"> <input style="background-color:{{myCol}}" ng-model="myCol"> </div> <p>AngularJS resolves the expression and returns the result.</p> <p>The background color of the input box will be whatever you write in the input field.</p> </body> </html> A: ng-model provides two-way binding, so although ng-init sets the initial value, if you want to be able to dynamically respond to user input (changing the colour via the input) then you need ng-model.
doc_23531201
Possible Duplicate: how to import from MS excel into MYSQL DB I wish to import some data from excel to mysql database. my query is LOAD DATA LOCAL INFILE 'd:/Book1.csv' INTO TABLE exp FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'; I receive an error File 'd:/Book1.csv' not found. Is there anything i want to do. A: There is a good tool for this called RazorSQL. That's what I use to import data to my database, I'm not sure if it supports a mysql database, but I think it does. Well, this is a good way to do it if you don't want to do it at runtime with code. Tjekkles
doc_23531202
For example d(i,j) = 10, and d(j,i) = infinity or d(i,j) = 10 and d(j,i) = 20 Is it possible to create a new (undirected) graph that has all this information? I can add more nodes and edges if necessary. By undirected I mean this: A graph where d(i,j) = d(j,i) and if d(i,j) exists then d(j,i) exists.
doc_23531203
When using the following line of code, the script calls upon the job and runs it, only if job_name is in the MAIN folder, then prints output or error to job_name.out/.err in the WORK folder. system("$job_name > ./WORK/$job_name.out 2> ./WORK/$job_name.err"); If I move the jobs into SCRIPTS then I cannot seem to find an efficient/simple way to call upon it.. I figured something similar to the following code would work: system("SCRIPTS/$job_name > ./WORK/$job_name.out 2> ./WORK/$job_name.err"); But I get errors like: * *SCRIPTS is not recognized as an internal or external command...... *The system cannot find the path specified. How can I compose this command to get it to work from a subdirectory? A: On Windows, filepaths are specified with backslashes (\). Instead of system("SCRIPTS/$job_name"...), try system("SCRIPTS\\$job_name"...)
doc_23531204
the final part looks something like this: execution_path = os.getcwd() detector = VideoObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath(os.path.join(execution_path , "yolo.h5")) detector.loadModel() print('Model loaded') cap = cv2.VideoCapture(0) video_path = detector.detectObjectsFromVideo(camera_input=cap, output_file_path=os.path.join(execution_path, "captured") , frames_per_second=5, log_progress=True, detection_timeout=120) print(video_path) This is resulting in creating an avi file that is recording the video and detecting the objects. While I can see the progress by opening this file, I have to close it and open again in order to see the ongoing updated progress. Is there a way to display this video with something like %matplotlib inline, etc? A: I have not used it, but if you look at the documentation it has an optional parameter to return the detected frame: – parameter return_detected_frame (optional) : This parameter allows you to return the detected frame as a Numpy array at every frame, second and minute of the video detected. The returned Numpy array will be parsed into the respective per_frame_function, per_second_function and per_minute_function (See details below) and then you need to also pass a function to this parameter: β€”parameter per_frame_function (optional ) : This parameter allows you to parse in the name of a function you define. Then, for every frame of the video that is detected, the function will be parsed into the parameter will be executed and and analytical data of the video will be parsed into the function. The data returned can be visualized or saved in a NoSQL database for future processing and visualization. The new function should look like the one in the documentation: def forFrame(frame_number, output_array, output_count, returned_frame): plt.clf() this_colors = [] labels = [] sizes = [] counter = 0 for eachItem in output_count: counter += 1 labels.append(eachItem + " = " + str(output_count[eachItem])) sizes.append(output_count[eachItem]) this_colors.append(color_index[eachItem]) global resized if (resized == False): manager = plt.get_current_fig_manager() manager.resize(width=1000, height=500) resized = True plt.subplot(1, 2, 1) plt.title("Frame : " + str(frame_number)) plt.axis("off") plt.imshow(returned_frame, interpolation="none") plt.subplot(1, 2, 2) plt.title("Analysis: " + str(frame_number)) plt.pie(sizes, labels=labels, colors=this_colors, shadow=True, startangle=140, autopct="%1.1f%%") plt.pause(0.01) This will also plot a the other analytical data, but you can just plot the frame. Your code will have to change to look like this: video_path = detector.detectObjectsFromVideo(camera_input=cap, output_file_path=os.path.join(execution_path, "captured") , frames_per_second=5, log_progress=True, detection_timeout=120, return_detected_frame=True, per_frame_function=forFrame) Take note of the two last arguments. I hope this helps you
doc_23531205
Great price, but it seems that it has a draw back. It seems to need the bundle.crt in order to work correctly on must browser. I'm not yet really sure what it is, from what I have understand it is an intermediate certificate from Certificate Authority. Correct me if I'm wrong So in my software I have openssl SSL_CTX_set_default_passwd_cb(SSL_ctx, pem_passwd_cb); SSL_CTX_use_PrivateKey_file(SSL_ctx, _private_key, SSL_FILETYPE_PEM); SSL_CTX_use_certificate_file(SSL_ctx, _certificate, SSL_FILETYPE_PEM); SSL_CTX_use_certificate_chain_file(SSL_ctx, "./ssl_key/bundle.pem"); SSL_CTX_set_session_cache_mode(SSL_ctx,SSL_SESS_CACHE_SERVER|SSL_SESS_CACHE_NO_INTERNAL); SSL_CTX_set_quiet_shutdown(SSL_ctx, 1); The error I get is : You didn't run init properly or an error occured. With lasts certs (geotrust) I didn't need the bundle intermediate, I'm really lost here. Since SSL_CTX_use_certificate_chain_file accepts only PEM files, I have converted the bundle.crt file to PEM using openssl. Any idea ? Thanks! EDIT 1 : Apparently Intermediate certificate must be on the /etc/ssl/certs folder. I have putted every intermediate certificate from go-daddy on this folder, and still no luck... I have removed the line SSL_CTX_use_certificate_chain_file(SSL_ctx, "./ssl_key/bundle.pem"); Which seems to be no use for me here... A: Okay, after testing one million things I finally found out. I didn't convert the bundle.crt into PEM. I have pasted the certificate file directly in the bundle.crt (at the beginning of the file) I have removed this line on my code : SSL_CTX_use_certificate_file(SSL_ctx, _certificate, SSL_FILETYPE_PEM); So here's the final code for SSL init : SSL_CTX_set_default_passwd_cb(SSL_ctx, pem_passwd_cb); SSL_CTX_use_PrivateKey_file(SSL_ctx, _private_key, SSL_FILETYPE_PEM); SSL_CTX_use_certificate_chain_file(SSL_ctx, "./ssl_key/bundle.crt"); SSL_CTX_set_session_cache_mode(SSL_ctx,SSL_SESS_CACHE_SERVER|SSL_SESS_CACHE_NO_INTERNAL); SSL_CTX_set_quiet_shutdown(SSL_ctx, 1); Hope this helps someone, and save them a lot of time (1 full day for me ;-))
doc_23531206
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Component { String value() default ""; } @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Configuration { String value() default ""; } How can I konw Configuration is annotated Component? And what's the relationship between @Interface and the interface Annotation. I have a Object annotated @Configuration , obj.getClass().getAnnotation(Configuration.class).getClass()==Configuβ€Œβ€‹ration.class it's false A: Checking whether an annotation is present is rather easy, any Class has an isAnnotationPresent(clazz)-method allowing you to check whether an annotation of a specific type is present. You can only check if an annotation is present when it has a retention policy 'RUNTIME', for otherwise the annotations are stripped by either the compiler or the JVM. I've created a little sample for you: http://ideone.com/CrXGVc
doc_23531207
http://imageshack.us/photo/my-images/850/y1xk.png/ This is the code: int x = canvas.getWidth(); int y = 0; int x_margin = 40; int y_margin = 60; for (int i=1; i < 51; i++) { canvas.drawLine(x_margin, y + y_margin, x - x_margin, y + y_margin, mLinePaint); if (i % 5 == 0) { if ((i % 10 != 0) && (tracks == 2)) { canvas.drawLine(x_margin, y + y_margin, x_margin, y + y_margin + 40, mLinePaint); canvas.drawLine(x - x_margin, y + y_margin, x - x_margin, y + y_margin + 40, mLinePaint); y += 40; } else { y += 60; } } else { canvas.drawLine(x_margin, y + y_margin, x_margin, y + y_margin + 15, mLinePaint); canvas.drawLine(x - x_margin, y + y_margin, x - x_margin, y + y_margin + 15, mLinePaint); y += 15; } } Does anyone know why is this happening? Thanks in advance. A: It's happening because there is a slight difference in the y at the beginning and the end of your line, make sure both y values are exactly the same. You may also try youCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.ANTI_ALIAS_FLAG,Paint.DITHER_FLAG)); A: Have you checked to make sure it isn't the emulator. It may work fine if you run it on your phone. A: I guess this is related to the conversion between the mathematical coordinates and the "real" pixel coordinates. I would recommend to draw the line twice or more to verify the error happens always in the same points. I would also test it on a real device, the issue is maybe related to the conversion of screen coordinates between android and the PC screen... Good luck, this bug is not funny
doc_23531208
A: For me, JavaFX applications hosted in a browser always terminate automatically when the browser is closed. You should implement Application.stop() to detect the application shutdown event. Stage level methods setOnCloseRequest and setOnHiding are not the right methods for detecting an application level shutdown event.
doc_23531209
Let's define both select and unselect events, select one point by clicking on it, and then unselect it by selecting a different one. The thing is, that select event on new point fires before unselect event on the old point. I would prefer that event unselect of the old point would fire before select event on the new point. Any ideas how to achieve that? http://jsfiddle.net/2Wr8v/ A: You can simply compare actual point to be unselected with array of actually selected points. For example: http://jsfiddle.net/2Wr8v/1/ unselect: function(event) { var p = this.series.chart.getSelectedPoints(); if(p.length > 0 && p[0].x == this.x) { $('#label').text('point unselected'); } }
doc_23531210
This error occurs only when I run these 4 lines :- image_batch, label_batch = next(iter(train_ds)) timeit(train_ds) uncached_ds = prepare_for_training(labeled_ds, cache=False) timeit(uncached_ds) filecache_ds = prepare_for_training(labeled_ds, cache="./flowers.tfcache") timeit(filecache_ds) UnknownError: NewRandomAccessFile failed to Create/Open: D:\Deep Learning\Datasets\12 class dataset\motorbike : Access is denied. ; Input/output error [[{{node ReadFile}}]] A: Sorry, my bad I used os and glob library to denote location and access the directory while executing the code in my laptop which produced this error but after using 'pathlib' itself, it works like a charm...
doc_23531211
I can run if I right click on the Web project, click 'Run With' then 'Custom Configuration'. Works great. However, the run item is disabled and I can't figure any way to enable it: http://prntscr.com/f7rsgh A: Try loading the solution using Jetbrains Rider. https://www.jetbrains.com/rider A: This sounds like it may be the same issue: https://developercommunity.visualstudio.com/comments/79790/view.html If you expand the comments, someone says: OK installing 2.1.0-preview1-006776 breaks VS Mac 7.0.1. I see the same problem that you are seeing. There is a NuGetFallbackFolder in the sdk folder and VSMac incorrectly uses that as the latest sdk folder. So for now you can fix this by removing the /usr/local/share/dotnet/sdk/NuGetFallbackFolder/ folder. Although that may break the 2.1 preview version of the dotnet cli if you are using it from the command line. VSMac seems to be OK running and debugging ASP.NET Core projects after removing that folder. It seems to have fixed the OP's question from the forum thread. This is a bug with Visual Studio for Mac that's been fixed in a pending release, but the update doesn't seem to be out just yet. I hope this helps you out in the meantime. A: * *Download and install the latest asp.net core *Download or upgrade to the latest openSSL This helped me
doc_23531212
Here my tasks: - name: ensure openssh-server is present apt: pkg: openssh-server state: latest install_recommends: no force: yes default_release: "{{ sshd_apt_backports_distribution }}" notify: restart sshd - name: ensure ed25519 host key is present command: ssh-keygen -q -t ed25519 -N "" -f ssh_host_ed25519_key args: chdir: /etc/ssh creates: /etc/ssh/ssh_host_ed25519_key The error: failed: [localhost] => {"changed": true, "cmd": ["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", "ssh_host_ed25519_key"], "delta": "0:00:00.012330", "end": "2015-05-17 12:16:51.062852", "rc": 1, "start": "2015-05-17 12:16:51.050522", "warnings": []} stderr: unknown key type ed25519 The second task should only triggered, when OpenSSH 6.5 or greater is present. You can see here my build is failing because the Travis CI tests run under Ubuntu 12.04 LTS and there is no actual OpenSSH version. A: You can do this in two steps. First register the openssh-server version: - name: Get openssh-server version shell: 'dpkg -s openssh-server | grep "^Version" | sed -re "s/^.*:([0-9]+\.[0-9]+).*/\1/"' register: openssh_version Then create the key if needed: - name: ensure ed25519 host key is present command: ssh-keygen -q -t ed25519 -N "" -f ssh_host_ed25519_key args: chdir: /etc/ssh creates: /etc/ssh/ssh_host_ed25519_key when: openssh_version.stdout | version_compare('6.5', '>=') I have not tested, so YMMV, but it should be close to what you need. There might be a simpler way to check openssh-server version too. A: A little follow-up for the previous answer, you don't need to grep or sed the result of dpkg, the command dpkg-query has a --showformat option to get exactly the information you want: dpkg-query --show --showformat '${Version}' openssh-server So you can use it with the simple command module: - name: Get openssh-server version command: /usr/bin/dpkg-query --show --showformat ${Version} openssh-server register: openssh_version
doc_23531213
int a = new int(); a = 111; or int a; a = 111β€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œβ€Œ; What does new int() exactly do? A: The second, and if possible, simply: int a = 111; Value types do not need to use new() Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized. (From MSDN) A: Consider using the var keyword. var i = 111; i will automatically be resolved to an int at compile time. A: The second code is preferred because the first one is equivalent to: int a; a = 0; a = 111; Now its clear tht the second code is more reasnonable.
doc_23531214
I recently came across a situation in a production application where my route composable was being called twice, causing a slight flicker in the UI. After digging into it for a few hours I discovered that the cause for the flicker was from using a hiltViewModel within the route for providing the ViewModel to my compose screen. I dug in further only to find out that any time there was a state change within the ViewModel, the Route's composable was recomposed. I would've thought that only the child composable would've recomposed since it was the only one using the state value? The full project is here but the basic Compose code looks like this. (I removed as much boilerplate as I could) @Composable fun AppNav() { val navController = rememberNavController() NavHost(navController = navController, startDestination = Screen.Home.route) { addHome() } } private fun NavGraphBuilder.addHome() { composable(Screen.Home.route) { Log.i("Home", "Route Composable") val homeViewModel = hiltViewModel<HomeViewModel>() HomeScreen( homeCount = homeViewModel.homeCount, updateCount = { homeViewModel.updateCount() }, ) } } @Composable fun HomeScreen( homeCount: Int, updateCount: () -> Unit, ) { Log.i("Home", "Home Screen") Column(modifier = Modifier.fillMaxSize()) { Spacer(modifier = Modifier.height(25.dp)) Button(onClick = { updateCount() }) { Text("Increment count") } Spacer(modifier = Modifier.height(25.dp)) Text("Count is: $homeCount") } } A: After reading the documentation more carefully and confirming in the Slack Channel I discovered that the core issue was a misunderstanding of how State works with Compose. I was thinking that it only changed the Composable where the State was consumed when in fact any Composable that contains (reads) State will recompose when the State changes. The code in my example is essentially the same as doing: composable(Screen.Home.route) { Log.i("Home", "Route Composable") var homeCount by remember { mutableStateOf(0) } HomeScreen( homeCount = homeCount, updateCount = { homeCount++ }, ) } It makes no difference if the State was being updated directly in the Composable like this version or if the State was updated in the ViewModel like the original code. Either way, the Composable containing the State will recompose. Any time a state is updated a recomposition takes place. and Any changes to value will schedule recomposition of any composable functions that read value. A: I guess you need to look at how to use saveState and restoreState when navigating to different routes. Here is an article for this thing : https://developer.android.com/jetpack/compose/navigation#bottom-nav
doc_23531215
int a[N], b[N]; b[0] = a[0]; b[N] = a[N]; for (i=1; i<N-1; i++) b[i]= a[i-1] + a[i] + a[i+1]; I thought about writing it this way, but I would like to find a better performing solution __kernel void adjacentCopy(__global double *a, __global double *b, const unsigned int n) { int gid = get_global_id(0); if (gid < N) b[gid] = a[gid-1]+a[gid]+a[gid+1]; } // and than execute the two base case into the host Anyone can suggest a way to organize the code to use local memory, and also bringing back the two extremes cases into the kernel, without adding branches divergence A: A kernel in essence is a for-loop, of which every iteration runs in parallel. The exact order of execution is random, so there must not be any data dependencies from one iteration to the next; otherwise you have to use a double buffer (only read from one buffer and only write to the other). In your case, the kernel would read: __kernel void adjacentCopy(const __global double *a, __global double *b, const unsigned int N) { int gid = get_global_id(0); if(gid==0||gid==N-1) return; // guard clause: do not execute the first and last element b[gid] = a[gid-1]+a[gid]+a[gid+1]; // double buffers to resolve data dependencies: only read from a and only write to b } With the extreme cases gid==0||gid==N-1, on such a computational grid you typically use periodic boundary conditions. Then the kernel would become branchless and look like this: __kernel void adjacentCopy(const __global double *a, __global double *b, const unsigned int N) { int gid = get_global_id(0); b[gid] = a[(gid+N-1)%N]+a[gid]+a[(gid+1)%N]; // periodic boundaries with modulo; in "(gid+N-1)" the "+N" ensures that the argument of the modulo operator always is positive } Now for the local memory optimization: Without it, for every thread, you read 3 neighboring values of a from slow global memory. In theory, you could only load one element per thread from global memory and use fast local memory to share the data within the workgroup. But the two threads at gid==0||gid==N-1 will have to load 2 values from global memory, introducing branching, and this will likely kill any potential gain in performance. The added complication, together with no significant gains in performance, make the local memory optimization an unfavourable choice in this case. This is how the kernel would look like: #define def_workgroup_size 128 // set this to the size of the workgroup __kernel void adjacentCopy(const __global double *a, __global double *b, const unsigned int N) { int gid = get_global_id(0); int lid = get_local_id(0); __local double cached_a[def_workgroup_size+2]; // as large as the workgroup, plus neighbors on the left and right sides of the workgroup if(lid==0) cached_a[lid] = a[(gid+N-1)%N]; // first thread in workgroup also has to load left neighbor cached_a[lid+1] = a[gid]; if(lid==def_workgroup_size-1) cached_a[lid+1] = a[(gid+1)%N]; // last thread in workgroup also has to load right neighbor barrier(CLK_LOCAL_MEM_FENCE); // barrier to make sure cached_a is entirely filled up b[gid] = cached_a[lid]+cached_a[lid+1]+cached_a[lid+2]; // read 3 values from local memory }
doc_23531216
I want to check if each list of a list of lists have, at least, one element inside. For example: [[0], [0], [0, s(0), 0], [s(0)]] -> valid [[0], [], [0, s(0), 0], [s(0)]] -> not valid (because of the []) So I check it this way: % Auxiliar Method 1 isList([]). isList([_|Tail]) :- isList(Tail). % Auxiliar Method 2 listLength([], 0). listLength([_|Tail], NumberOfElements) :- listLength(Tail, NumberOfElementsRecursive), NumberOfElements = s(NumberOfElementsRecursive). % Auxiliar Method 3 moreThan(s(X), 0). moreThan(s(X), s(Y)) :- moreThan(X, Y). % Real Method listOfListOfListsNotEmpty([Head|Tail]) :- isList(Head), listLength(Head, N), moreThan(N, 0), listOfListOfListsNotEmpty(Tail). My issue is the last iteration. For example, if I want to check this: listOfListOfListsNotEmpty([[0], [0]]). The iterations are this way: Iteration 1: Head: [0] Tail: [0], [] [0] has at least one element? yes Iteration 2: Head: [0] Tail: [] [0] has at least one element? yes Iteration 3: Head: [] Tail: [] has at least one element? no How can I ignore that last check of an empty list?? A: lls_nonempty([]). lls_nonempty([[_|_]|Ess) :- lls_nonempty(Ess). A: "For all list elements some predicate P holds" is commonly expressed by using maplist/2. So there's no need to define an extra predicate of your own here! Sample queries: ?- maplist(dif([]), [[0],[0],[0,s(0),0],[s(0)]]). true. ?- maplist(dif([]), [[0],[],[0,s(0),0],[s(0)]]). false.
doc_23531217
On a working setup, I noticed that changes to the URL map take a long time to take effect. For example, if I change for a working URL map a host-value from "abc.example.com" to "def.example.com", abc.example.com will remain available for at least a few minutes, while it takes a least some minutes, until def.example.com is available (I am not using any caching). Is there a way to decrease this time, until the change is propagated? A: It is actually really low replication timeframe (just few minutes as you said). It can take up to 24 hours to fully replicate (Through all the worldwide) . DNS does cache it by default so you are actually using. The DNS has a property called TTL (Time to live) that caches the value of your records. So you would need to narrow this window of time to force the DNS to replicate earlier. In the official docs you can read more about it.
doc_23531218
For this, I am using find_by, so I've been trying to do something like: User.find_by("replace(personal_id, '-', '.', ' ') = ?", 'replace(input, '-', '.', ' ')'). This is supposed to remove special characters from stored value and input value, and find the user that matches the search, but it is clearly not working and i can't seem to find the solution to my problem. The output i get with this is No function matches the name and argument types... Any help would be appreciated, thank you.
doc_23531219
position-sensitive-zooming Sample code follows: package test; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; public class FPanel extends javax.swing.JPanel { private Dimension preferredSize = new Dimension(400, 400); private Rectangle2D[] rects = new Rectangle2D[50]; public static void main(String[] args) { JFrame jf = new JFrame("test"); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setSize(400, 400); jf.add(new JScrollPane(new FPanel())); jf.setVisible(true); } public FPanel() { // generate rectangles with pseudo-random coords for (int i=0; i<rects.length; i++) { rects[i] = new Rectangle2D.Double( Math.random()*.8, Math.random()*.8, Math.random()*.2, Math.random()*.2); } // mouse listener to detect scrollwheel events addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { updatePreferredSize(e.getWheelRotation(), e.getPoint()); } }); } private void updatePreferredSize(int n, Point p) { double d = (double) n * 1.08; d = (n > 0) ? 1 / d : -d; int w = (int) (getWidth() * d); int h = (int) (getHeight() * d); preferredSize.setSize(w, h); int offX = (int)(p.x * d) - p.x; int offY = (int)(p.y * d) - p.y; setLocation(getLocation().x-offX,getLocation().y-offY); getParent().doLayout(); } public Dimension getPreferredSize() { return preferredSize; } private Rectangle2D r = new Rectangle2D.Float(); public void paint(Graphics g) { super.paint(g); g.setColor(Color.red); int w = getWidth(); int h = getHeight(); for (Rectangle2D rect : rects) { r.setRect(rect.getX() * w, rect.getY() * h, rect.getWidth() * w, rect.getHeight() * h); ((Graphics2D)g).draw(r); } } } In my opinion,the most important part is in updatePreferredSize(int n, Point p): int offX = (int)(p.x * d) - p.x; int offY = (int)(p.y * d) - p.y; setLocation(getLocation().x-offX,getLocation().y-offY); Now I want to implement it in mxgraph. What I did so far is changing getPageTranslate(new Scale) in mxgraph and make it return int offX = (int)(p.x * d) - p.x; int offY = (int)(p.y * d) - p.y; return new mxPoint(offX,offY) As a result, it does not work. I guess scaleAndTranslate(new Scale,translate.getX(),translate.getY()) in mxgraph is key point to solve this problem. Really appreciate any help.
doc_23531220
This is what I have so far. I want to sum the salary of managers, clerks, and analysts separately. import pandas as pd a = ['manager','sales','clerk','manager','analayst','sales','manager','analayst' ,'sales','clerk','clerk','analayst'] b = [45000,78000,12000,45000,96000,78000,56000,95000,84000,75000,95000, 26000] df = pd.DataFrame({'name':a,'salary':b}) sum = 0 k = 0 c = [] for i in a: if i not in c: c.append(i) for j in range(len(df)): while k < len(c): p = c[k] print(p) d = df[df['name'] == p]['salary'].sum() k += 1[1] A: You can easy separate the sum like of managers, clerks, and analysts etc. using group by function . That is helpful to you easy solve you sum separated form a=['manager','sales','clerk','manager','analayst','sales','manager','analayst' ,'sales','clerk','clerk','analayst'] b=[45000,78000,12000,45000,96000,78000,56000,95000,84000,75000,95000, 26000] df=pd.DataFrame({'name':a,'salary':b}) df.groupby("name")["salary"].sum() A: I m guessing you want an output like this - >>> a=['manager','sales','clerk','manager','analayst','sales','manager','analayst' ,'sales','clerk','clerk','analayst'] >>> b=[45000,78000,12000,45000,96000,78000,56000,95000,84000,75000,95000,26000] >>> import pandas as pd >>> >>> df=pd.DataFrame({'name':a,'salary':b}) >>> >>> >>> df.groupby('name').sum().reset_index() name salary 0 analayst 217000 1 clerk 182000 2 manager 146000 3 sales 240000 >>> If yes you can easily do this by a groupby , it enables you to group/cluster your data points and over each subset you can perform you desired aggregation A: Use: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.sum.html below is the snippet of the result.. >>> import pandas as pd >>> a = ['manager', 'sales', 'clerk', 'manager', 'analyst', 'sales', 'manager', 'analyst', 'sales', 'clerk', 'clerk', 'analyst'] >>> b = [45000, 78000, 12000, 45000, 96000, 78000, 56000, 95000, 84000, 75000, 95000, 26000] >>> df = pd.DataFrame({'name': a, 'salary': b}) >>> df name salary 0 manager 45000 1 sales 78000 2 clerk 12000 3 manager 45000 4 analyst 96000 5 sales 78000 6 manager 56000 7 analyst 95000 8 sales 84000 9 clerk 75000 10 clerk 95000 11 analyst 26000 >>> df.groupby(['name']).sum() salary name analyst 217000 clerk 182000 manager 146000 sales 240000
doc_23531221
for example: let address1 = "Akshardham Temple, Vidyut Nagar, Vaishali Nagar, Chitrakoot, Jaipur, Rajasthan" let address2 = "Statue of Unity, Statue of Unity Road, Kevadia, Gujarat" // and some might be just this let address3 = "New Delhi, Delhi" what I want is however long string is I want to extract last two entire words(state and city) and rest in another variable. A: First split the string by a comma: const arr = address1.split(','); This will give you an array of strings, e.g. ["Akshardham Temple", " Vidyut Nagar", " Vaishali Nagar", " Chitrakoot", " Jaipur", " Rajasthan"] Then you can slice off the last 2 elements of the array: const [city, state] = arr.slice(-2) A: As you say, you have to split the strings. If you want only whole words, it makes sense to use the space character as a separator. const parts = address1.split(" "); Now you have to access the last element and the second last element. Remember that length is always one greater than the last index. const lastWort = parts[parts.length-1]; const secondLastWort = parts[parts.length-2]; If you are bothered by the commas in the result, you can remove them first. address1 = address1.replaceAll(",", ""); All together: let address1 = "Akshardham Temple, Vidyut Nagar, Vaishali Nagar, Chitrakoot, Jaipur, Rajasthan"; address1 = address1.replaceAll(",", ""); const parts = address1.split(" "); const lastWort = parts[parts.length-1]; const secondLastWort = parts[parts.length-2]; console.log(lastWort); console.log(secondLastWort); A: You can use split and splice. The returned elements would need a call to trim() so to avoid optional white space is dangling around the extracted words: function splitAddress(s) { let parts = s.split(","); let [city, state] = parts.splice(-2).map(s => s.trim()); return { address: parts.join(","), city, state }; } let tests = [ "Akshardham Temple, Vidyut Nagar, Vaishali Nagar, Chitrakoot, Jaipur, Rajasthan", "Statue of Unity, Statue of Unity Road, Kevadia, Gujarat", "New Delhi, Delhi" ]; for (let test of tests) { console.log(splitAddress(test)); }
doc_23531222
Error message: https://s4.postimg.org/if3ip9zfh/screenshot000213.jpg A: It'll probably be easier to create a class via a script with DDL. We do it like this: CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "IP6Address" AS import java.math.BigInteger; public class IP6Address { ... -- whatever } / We do that for packages as well because we store these scripts in VCS. Then you just run the script and wait for the compiler messages (as with any other script). A: I had the same issue as you, but the Oracle JDK version was a problem. I fixed this problem by changing the source code to match the JDK version. Please check the version.
doc_23531223
H <- tcrossprod(tcrossprod(X, solve(crossprod(X))), X) with X being a relatively large matrix (i.e 1e5*100), and this line has to run thousands of times. I understand the most limiting part is the inverse computation, but the crossproducts may be time-consuming too. Is there any faster alternative to perform these matrix operations? I tried Rcpp and reviewed several posts but any alternative I tested was slower. Maybe I did not code properly my C++ code, as I am not an advanced C++ programmer. Thanks! A: Chasing the code for this line by line is a little difficult because the setup of R code is a little on the complicated side. But read on, pointers below. The important part is that the topic has been discussed many times: what happens is that R dispatches this to the BLAS (Basic Linear Algebra Subprogram) and LAPACK (Linear Algebra PACKage) libraries. Which contain the most efficient code known to man for this. In general, you cannot gain on it by rewriting. One can gain performance differences by switching one BLAS/LAPACK implementation for another---there are many, many posts on this online too. R itself comes with the so-called 'reference BLAS' known to be correct, but slowest. You can switch to Atlas, OpenBLAS, MKL, ... depending on your operating system; instructions on how to do so are in some of the R manuals that come with your installation. For completeness, per file src/main/names.c the commands %*%, crossprod and tcrossprod all refer to do_matprod. This is in file src/main/array.c and does much argument checking and arranging and branching on types of arguments but e.g. one path then calls F77_CALL(dsyrk)(uplo, trans, &nc, &nr, &one, x, &nr, &zero, z, &nc FCONE FCONE); which is this LAPACK function. It is essentially the same for all others making this an unlikely venue for your optimisation.
doc_23531224
<html> <body> <script>create_a_div()</script> </body> </html> The desired output is: <html> <body> <div></div> </body> </html> Is there any argument I could use in the function render to do this? I would let that JavaScript code to be executed on Client side, but I am not allowed to save it for security reasons. A: If I clearly understand what you are asking for, I'm afraid the answer is no, you cannot execute the JavaScript code in render function. What you could do, is pass the html as a variable into the template with the safe filter. Template: <html> <body> {{ custom_html|safe }} </body> </html> And when rendering, use the following Python code: template.render(custom_html="<div>your html code</div>") This would give you the desired output that you are looking for. You can read more about JINJA2 templates and variables here
doc_23531225
while($row=mysql_fetch_assoc($count_query_result)) $output[]=$row; while($row=mysql_fetch_assoc($average_query_result)) $output2[]=$row; while($row=mysql_fetch_assoc($items_query_result)) $output3[]=$row; print(json_encode(array($output,$output2,$output3))); mysql_close(); My question: How do I take a single column from each of the three query results, and make a JSON array out of it, like so: [{ 'att1' : 'data'}, { 'att2' : 'data'}, { 'att3' : 'data'}] ASSUMING: * *att1 came from the $count_query_result/$output *att2 came from the $average_query_result/$output2 *att3 came from the $items_query_result/$output3 Therefore, encoding only one variable, not 3. A: Well I answered my own issue. I had to get to the very root of the problem. The MySQL queries. I have joined them all so now there is just one. This creates a single JSON array for what I need. I believe there is something to be said about just doing it ... right .. the first time. A: $result = array('att1' => $row['data'], 'att2' => $row['data'] echo json_encode($result) where $row['data'] is the information that you want returned from each of your queries
doc_23531226
The essence of the problem is that in Eclipse application runs, while in terminal (ubuntu) using the following line of code (where the Catalog "m /" indicates the location of the modules * .class): java -jar ModularApp.jar m/ I get the following message: 10:07:24,085 DEBUG main CModuleLoader:findClass:39 - Run of the System Classloader. Exception in thread "main" java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58) Caused by: java.lang.NoClassDefFoundError: ru/intetech/module/CModule at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at java.lang.ClassLoader.defineClass(ClassLoader.java:643) at ru.intetech.moduleloader.CModuleLoader.findClass(CModuleLoader.java:35) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at ru.intetech.modularApp.Main.main(Main.java:42) ... 5 more Caused by: java.lang.ClassNotFoundException: ru.intetech.module.CModule at java.lang.ClassLoader.findClass(ClassLoader.java:531) at ru.intetech.moduleloader.CModuleLoader.findClass(CModuleLoader.java:40) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ... 12 more Here's a snippet of code, the user class loader (extending ClassLoader), where there is an error: protected Class<?> findClass(String className) throws ClassNotFoundException { try { byte b[]=getClassAsBytes(m_pathToBin+className+".class"); return (defineClass(className, b, 0, b.length)); } catch(FileNotFoundException ex) { m_log.debug("Run of the System Classloader."); return (super.findClass(className)); } catch(IOException ex) { m_log.debug("Run of the Bootstrap."); return (super.findClass(className)); } } What could be the problem? P.S. Loader implemented on the basis of this article: http://sysmagazine.com/posts/104229/ A: Look: The stack trace shows the message "Run of the System Classloader", which proves that the first catch was executed. This was caused by a FileNotFoundException, which clearly occurred in the getClassAsBytes method: This is what you must investigate: Find out what file you are trying to read (put a trace showing the the absolute path), and why that file does not exist. (Eventually, that catch block tries to load the required class by the system classloader, which has no acces to that class, and so, it throws the ClassNotFoundException).
doc_23531227
In jmeter-meter a Userdefined Variable is defined (e.g. authkey=1234567) in csv-file is the soap-request: <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"> <soap:Body> <Request AuthKey="${Authkey}}"> <Element1>...</Element1> </Request> </soap:Body> </soap:Envelope> Body date in jmeter is read from file with Variable ${REQUEST}, but the "Authkey" is not set in Request and it fails... I tried with the following Variable-Type "${__V{Authkey}}", "${__evalVar{Authkey}}", but no success. Is it possible to pass through a Variable-name from csv inputfile? A: You need to wrap your variable from the CSV Data Set Config into __eval() function, this way JMeter will resolve all JMeter Functions or Variables in you XML file to their respective values More information: Here’s What to Do to Combine Multiple JMeter Variables
doc_23531228
In the below image, calAge is not returning a value. A: What may be confusing you is that the code of that function, Tschool.Accepted is obviously incomplete; a value is assigned to the result value of the function if the if statement is true, but not otherwise. That's actually a programming error, because it means that the result value is undefined if the if statement returns false. Put another way, what's wrong with Tschool.Accepted is that it breaks the fundamental rule that every execution path through the function should result in the function's result being assigned a value. As written, Tschool.Accepted breaks the rule because it doesn't get a result value assigned if the if ... condition is false. So, one way to correct the programming error is to add an else clause to the end of the if ... statement, e.g. if (Some conditions are true) then Result := True else Result := False; Another way, which is slightly inefficient but covers all bases, is to assign a predefined value to Result as the first statement in the function and then assign another value to Result later on in the function's code if some condition(s) applies. Btw, because Tschool.Accepted is a Boolean function, you can avoid writing an if ... else ... by using a single assignment statement like this function Tschool.Accepted : Boolean; begin Result := (fdeposit) and (fAge >= 4) and (fAge <= 6); end; because what's on the righthand side of the assignment is an expression of Boolean type. In Delphi, there are often situations where execution of some code doesn't result in a useful (or interesting) value. Those are written as procedures rather than functions. So, one answer to your q is that if a method of an object can usefully return a value, write it as a function, otherwise write it as a procedure and if you write it as a function, make sure that it returns a value for any execution path through it.
doc_23531229
This site has provided an excellent solution but not to one with strata (https://stat.ethz.ch/pipermail/r-help/2014-October/422348.html). How can i append (or stack) each strata with an extra column which contains the strata type. solution in the link offered is not applicable to strata groupings library(survival) data(lung) mod <- with(lung, survfit(Surv(time, status)~ 1)) res <- summary(mod) str(res) # Extract the columns you want cols <- lapply(c(2:6, 8:10) , function(x) res[x]) # Combine the columns into a data frame tbl <- do.call(data.frame, cols) str(tbl) Thank you in advanced, R newbie A: The easiest way I see is to use the tidy() function from the broom package. library(survival) library(dplyr) #> #> Attache Paket: 'dplyr' #> The following objects are masked from 'package:stats': #> #> filter, lag #> The following objects are masked from 'package:base': #> #> intersect, setdiff, setequal, union library(broom) survfit( Surv(futime, fustat)~rx, data=ovarian) %>% tidy() #> # A tibble: 26 x 9 #> time n.risk n.event n.censor estimate std.error conf.high conf.low strata #> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr> #> 1 59 13 1 0 0.923 0.0801 1 0.789 rx=1 #> 2 115 12 1 0 0.846 0.118 1 0.671 rx=1 #> 3 156 11 1 0 0.769 0.152 1 0.571 rx=1 #> 4 268 10 1 0 0.692 0.185 0.995 0.482 rx=1 #> 5 329 9 1 0 0.615 0.219 0.946 0.400 rx=1 #> 6 431 8 1 0 0.538 0.257 0.891 0.326 rx=1 #> 7 448 7 0 1 0.538 0.257 0.891 0.326 rx=1 #> 8 477 6 0 1 0.538 0.257 0.891 0.326 rx=1 #> 9 638 5 1 0 0.431 0.340 0.840 0.221 rx=1 #> 10 803 4 0 1 0.431 0.340 0.840 0.221 rx=1 #> # … with 16 more rows Created on 2021-08-04 by the reprex package (v0.3.0) A: It is basically the same as you have there, just an extra column res <- summary( survfit( Surv(futime, fustat)~rx, data=ovarian)) cols <- lapply(c(2:6, 8:11) , function(x) res[x]) tbl <- do.call(data.frame, cols) head(tbl) # time n.risk n.event n.censor surv strata std.err upper lower # 1 59 13 1 0 0.9230769 rx=1 0.0739053 1.0000000 0.7890186 # 2 115 12 1 0 0.8461538 rx=1 0.1000683 1.0000000 0.6710952 # 3 156 11 1 0 0.7692308 rx=1 0.1168545 1.0000000 0.5711496 # 4 268 10 1 0 0.6923077 rx=1 0.1280077 0.9946869 0.4818501 # 5 329 9 1 0 0.6153846 rx=1 0.1349320 0.9457687 0.4004132 # 6 431 8 1 0 0.5384615 rx=1 0.1382642 0.8906828 0.3255265 A: Another option is to use the ggfortify library. library(survival) library(ggfortify) # fit a survival model mod <- survfit(Surv(futime, fustat) ~ rx, data = ovarian) # extract results to a data.frame res <- fortify(mod) str(res) 'data.frame': 26 obs. of 9 variables: $ time : int 59 115 156 268 329 431 448 477 638 803 ... $ n.risk : num 13 12 11 10 9 8 7 6 5 4 ... $ n.event : num 1 1 1 1 1 1 0 0 1 0 ... $ n.censor: num 0 0 0 0 0 0 1 1 0 1 ... $ surv : num 0.923 0.846 0.769 0.692 0.615 ... $ std.err : num 0.0801 0.1183 0.1519 0.1849 0.2193 ... $ upper : num 1 1 1 0.995 0.946 ... $ lower : num 0.789 0.671 0.571 0.482 0.4 ... $ strata : Factor w/ 2 levels "rx=1","rx=2": 1 1 1 1 1 1 1 1 1 1 ... The advantage of this method is that you get the complete data (i.e 26 observations instead of 12) and you can plot your survival curves with ggplot. library(ggplot2) ggplot(data = res, aes(x = time, y = surv, color = strata)) + geom_line() + # plot censor marks geom_point(aes(shape = factor(ifelse(n.censor >= 1, 1, NA)))) + # format censor shape as "+" scale_shape_manual(values = 3) + # hide censor legend guides(shape = "none")
doc_23531230
Lets say person A enters the process A and completed the process and same person enters again and be the part of the process(in progress). What I need is I need to get the unique total enrolled people count, I can get that using the below, unique_count = ProcessPerson.where(status: %[completed inprogress]).select(:person_id).distinct.count The requirement is to show the unique active people count, which should also be unique count. If a person completed the same process and inprogress in the same process means we need to skip them in active people count. The count of person who is in progress for a process and not completed the same process before is the expected result. Total enrolled people = unique(inprogress people + Completed people) Active people = unique(who is in progress and not completed the same process before) Can anyone help me with this? A: You could try this query: SELECT grouped_process_people.* FROM ( SELECT ordered_process_people.* FROM ( SELECT process_id, people_id, status FROM scratch.process_people ORDER BY (status = 'completed') DESC , status /* (1) */ ) as ordered_process_people GROUP BY process_id, people_id /* (2) */ ) as grouped_process_people WHERE status <> 'completed'; /* (3) */ What's going on in that SQL (use the numbers next to the sub-queries), say your table looks like this: +----+------------+-----------+------------+ | id | process_id | people_id | status | +----+------------+-----------+------------+ | 1 | 11 | 21 | inprogress | | 2 | 11 | 21 | completed | | 3 | 11 | 21 | inprogress | | 4 | 12 | 21 | inprogress | | 5 | 12 | 21 | inprogress | | 6 | 12 | 21 | inprogress | | 7 | 13 | 23 | inprogress | | 8 | 13 | 23 | completed | +----+------------+-----------+------------+ * *Order the table so that the rows with status as completed are on the top. +------------+-----------+------------+ | process_id | people_id | status | +------------+-----------+------------+ | 11 | 21 | completed | | 13 | 23 | completed | | 11 | 21 | inprogress | | 11 | 21 | inprogress | | 12 | 21 | inprogress | | 12 | 21 | inprogress | | 12 | 21 | inprogress | | 13 | 23 | inprogress | +------------+-----------+------------+ *Group by process_id and people_id so that only a unique combination of these pairs are selected, with the ones that have status as completed, marked so. +------------+-----------+------------+ | process_id | people_id | status | +------------+-----------+------------+ | 11 | 21 | completed | | 12 | 21 | inprogress | | 13 | 23 | completed | +------------+-----------+------------+ *Now, since we only want the ones that are not completed, the third and the outermost query, would filter out the ones that have status as completed. +------------+-----------+------------+ | process_id | people_id | status | +------------+-----------+------------+ | 12 | 21 | inprogress | +------------+-----------+------------+ The way to run this query would be to store it as a string, for example if it were stored in a variable called active_people_process_query, then it would be run like so: ProcessPerson.find_by_sql(active_people_process_query) A: I don't think this can be done in one step (one query) , but what i think of : * *First we group by person_id & process_id step_1 = ProcessPerson.all.select(:person_id, :process_id, :status).group_by{ |pp| [pp.person_id, pp.process_id]} Result: { [5, 5]=> [ {person_id: 5, process_id: 5, status: "completed"}, {person_id: 5, process_id: 5, status: "inprogress"} ], [4, 1]=>[ {person_id: 4, process_id: 1, status: "completed"}, {person_id: 4, process_id: 1, status: "inprogress"} ], [6, 5]=>[ {person_id: 6, process_id: 5, status: "completed"} ], [2, 5]=>[ {person_id: 2, process_id: 5, status: "completed"} ], [6, 2]=>[ {person_id: 6, process_id: 2, status: "inprogress"} ], [2, 2]=>[ {person_id: 2, process_id: 2, status: "completed"} ], [5, 3]=>[ {person_id: 5, process_id: 3, status: "inprogress"} ], [3, 4]=>[ {person_id: 3, process_id: 4, status: "completed"} ] } *Then we select any groups that is inprogress AND not have completed process step_2 = step_1.filter{ |k, v| v.any? {|h| h[:status] == "inprogress" } && !v.any? {|h| h[:status] == "completed" } } Result: { [6, 2]=>[ {person_id: 6, process_id: 2, status: "inprogress"} ], [5, 3]=>[ {person_id: 5, process_id: 3, status: "inprogress"} ] } *Then we count the Result step_3 = step_2.count Result: 2
doc_23531231
egen afd_lr2 = mean(afd_lire2w) if ost == 0 Now I would like to replace the values with the mean of another variable if ost == 1: replace afd_lr2 = mean(afd_lireo) if ost ==1 This is not possible, as the mean function cannot be used with the replace command. How can I achieve my goal? A: The following works for me: sysuse auto, clear generate price2 = price + 5345 egen a_price = mean(price) if foreign == 0 egen b_price = mean(price2) if foreign == 1 replace a_price = b_price if foreign == 1 A: This should work egen afd_lr2 = mean(cond(ost == 0, afd_lire2w, cond(ost == 1, afd_lireo, .))), by(ost) Here is a test: clear input float(group y1 y2) 1 42 . 1 42 . 2 . 999 2 . 999 end egen mean = mean(cond(group == 1, y1, cond(group == 2, y2, .))), by(group) tabdisp group, c(mean) ---------------------- group | mean ----------+----------- 1 | 42 2 | 999 ---------------------- The key is that the mean() function of egen feeds on an expression, which can be more complicated than a single variable name. That said, this is trickier than I would generally advise, as generate work = afd_lire2w if ost == 0 replace work = afd_lireo if ost == 1 egen mean = mean(work), by(ost) is easier to understand and should occur to a programmer any way.
doc_23531232
* *if 'head' is blank then remove the blank space. *if the next letter of 'head' is blank , remove both the letter and the tail. *if the 'head' and 'tail' are letters, I want the 'head'. *if the 'head' is blank give me the next letter because that's one of acronym. But when comes to a letter like "apple apple", it returns "apape" because I have problems managing with the third condition. acronym :: String -> String acronym [] = [] acronym [x] = [x] acronym (x:y:xs) | x == ' ' = y : acronym xs -- remove if 'head' is blank(space) | y == ' ' = acronym xs -- remove both x and y if y is blank(space) | x `elem` ['a'..'z'] || x `elem` ['A'..'Z'] && y `elem` ['a'..'z'] || y `elem` ['A'..'Z'] = x : acronym xs | x == ' ' && y `elem` ['a'..'z'] || y `elem` ['A'..'Z'] = y :acronym xs | otherwise = x : y : acronym xs A: Some general advice: * *Avoid equality comparisons, unless you know exactly why you want them. Equality is usually better written directly as pattern matches. *Avoid doing a lot of stuff in a function. Prefer composing simple helper functions, especially when they're already defined in a library.In your case, the problem has an obvious factoring into * *Split the string in words *Obtain the first letter for each word Even short of simply invoking the words function to do most of the work for you, it helps a lot to write your own function that splits off a single word from a string. You may do that e.g. based on whitespace and pattern matching, like splitOffWord :: String -> (String, String) splitOffWord "" = ("", "") splitOffWord (' ':cs) = ("", cs) splitOffWord (c:cs) = case splitOffWord cs of (word, rest) -> (c:word, rest) ...or based on letter-ness and with a standard function import Data.Char (isAlpha) splitOffWord = span isAlpha . dropWhile (not . isAlpha) ...or something in between. Then, in your acronym function, you can split off the first entire word, use it for obtaining the first character of the acronym, and recurse over the rest of the input. acronym (' ':str) = acronym str acronym str = case splitOffWord str of (word, rest) -> _ : _ ...filling in the _ left as an exercise.
doc_23531233
From a html form data is passed to a php code.It gives a error. A: This is the standard way to use. $firstname=$_GET['firstname']; $lastname=$_GET['lastname']; $email=$_GET['email']; $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('".$firstname."','".$lastname."','".$email."')"; $stmt = $conn->prepare($sql); $stmt->execute();
doc_23531234
Error:Failed to find target with hash string 'android-25' in: /Users/myuser/Library/Android/sdk <a href="install.android.platform">Install missing platform(s) and sync project</a> Where is the file where I have to set the sdk version, min or max ? Not the folder of sdk the project come from an Ionic 3 project. I've changed the file ./AndroidManifest.xml : <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="19" /> ./project properties: target=android-19 And finally I change on Android Studio menu "File" - "Project Structure" , Tab "Properties" , Fields: "Compile sdk version" = "API 19 Android 4.42" "Build Tools version" = 26.0.0 but the errors keeps.... A: Where is the file where I have to set the sdk ? Anyplace you prefer too What SDK version should I use? Depends in your audiences Make sure your SDK location is referred to where you downloaded it.
doc_23531235
But when the screen size gets smaller, the text and image intercept. I'm looking to make it so the text conform to the boarders of the image. This is what's happening now: Lastly, this is my CSS .image { width: 500px; margin-left: auto; display: block; padding-top: 10%; padding-right: 10%; } .text { font-size: 22px; padding-top: 10%; max-width: 700px; position: absolute; } A: Your issue is with absolute positioning. Whenever you use position:absolute you remove that element from the source flow. You can try to remove the absolute positioning and then try something like the following: Codepen example <div class="parent"> <div class="text"> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p> </div> <div class="image"> Place your image here. </div> And CSS: .parent { display: flex; max-width: 1000px; margin: 0 auto; } .text, .image { padding: 15px; } .image { width: 500px; } .text { width: calc(100% - 500px); }
doc_23531236
Problem: When loading a page, content inside of a JQueryUI tabs fails. Looking at Chrome Developer Tools, the AJAX requests are returning 500 Internal Server Errors. Typically, I'd look at the server's httpd error log (this is a CentOS system), but nothing shows as anything warning or higher. I changed the error logging to debug and captured this. [Fri Jun 10 08:26:57.748313 2022] [authz_core:debug] [pid 15452:tid 139940536825600] mod_authz_core.c(820): [client ::1:58584] AH01626: authorization result of Require all granted: granted, referer: http://localhost:2222/nexgen/index.html [Fri Jun 10 08:26:57.748324 2022] [authz_core:debug] [pid 15452:tid 139940536825600] mod_authz_core.c(820): [client ::1:58584] AH01626: authorization result of <RequireAny>: granted, referer: http://localhost:2222/nexgen/index.html [Fri Jun 10 08:26:57.748338 2022] [proxy:debug] [pid 15452:tid 139940536825600] mod_proxy.c(1254): [client ::1:58584] AH01143: Running scheme unix handler (attempt 0), referer: http://localhost:2222/nexgen/index.html [Fri Jun 10 08:26:57.748341 2022] [proxy_ajp:debug] [pid 15452:tid 139940536825600] mod_proxy_ajp.c(743): [client ::1:58584] AH00894: declining URL fcgi://localhost/var/www/html/nexgen/app/tabs/endpoints.php, referer: http://localhost:2222/nexgen/index.html [Fri Jun 10 08:26:57.748344 2022] [proxy_fcgi:debug] [pid 15452:tid 139940536825600] mod_proxy_fcgi.c(1021): [client ::1:58584] AH01076: url: fcgi://localhost/var/www/html/nexgen/app/tabs/endpoints.php proxyname: (null) proxyport: 0, referer: http://localhost:2222/nexgen/index.html [Fri Jun 10 08:26:57.748346 2022] [proxy_fcgi:debug] [pid 15452:tid 139940536825600] mod_proxy_fcgi.c(1028): [client ::1:58584] AH01078: serving URL fcgi://localhost/var/www/html/nexgen/app/tabs/endpoints.php, referer: http://localhost:2222/nexgen/index.html [Fri Jun 10 08:26:57.748351 2022] [proxy:debug] [pid 15452:tid 139940536825600] proxy_util.c(2315): AH00942: FCGI: has acquired connection for (*) [Fri Jun 10 08:26:57.748355 2022] [proxy:debug] [pid 15452:tid 139940536825600] proxy_util.c(2368): [client ::1:58584] AH00944: connecting fcgi://localhost/var/www/html/nexgen/app/tabs/endpoints.php to localhost:8000, referer: http://localhost:2222/nexgen/index.html [Fri Jun 10 08:26:57.748357 2022] [proxy:debug] [pid 15452:tid 139940536825600] proxy_util.c(2405): [client ::1:58584] AH02545: fcgi: has determined UDS as /run/php-fpm/www.sock, referer: http://localhost:2222/nexgen/index.html [Fri Jun 10 08:26:57.748399 2022] [proxy:debug] [pid 15452:tid 139940536825600] proxy_util.c(2577): [client ::1:58584] AH00947: connected /var/www/html/nexgen/app/tabs/endpoints.php to httpd-UDS:0, referer: http://localhost:2222/nexgen/index.html [Fri Jun 10 08:26:57.748410 2022] [proxy:debug] [pid 15452:tid 139940536825600] proxy_util.c(2948): AH02823: FCGI: connection established with Unix domain socket /run/php-fpm/www.sock (*) [Fri Jun 10 08:26:57.748746 2022] [proxy:debug] [pid 15452:tid 139940536825600] proxy_util.c(2330): AH00943: FCGI: has released connection for (*) I've checked my conf files to make sure that I've granted access to the directory. The error logs seems to show that those are being granted. The problem seems to be with mod_proxy_ajp. However, this shouldn't be a problem since I'm not using AJAX to get content over a reverse proxy. I've checked file permissions, setting everything to 777 (for testing purposes) with no success. I've "flattened" out the directory structure and put all of the tabbed files into the same top directory with the index.html with no success. The initial index.html loads without an issue. I created a test.php file to see if security exceptions were a problem. The test.php loaded successfully, so there's something going on with the AJAX. The JQuery code that governs this is below: $("#tabs").tabs({ beforeLoad: function (event, ui) { ui.jqXHR.fail(function () { ui.panel.html( "Couldn't load this tab. We'll try to fix this as soon as possible. " + "If this wouldn't be a demo."); }); }, load: function (event, ui) { $("#filterTerm").off("keyup").on("keyup", function () { var value = $(this).val().toLowerCase(); $("#dataTable tr").filter(function () { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) }); }); $("#muteSelect").selectmenu({ change: function (event, ui) { var muteValue = $(this).val().toLowerCase(); switch (muteValue) { case "unmuted": muteValue = "on"; break; case "muted": muteValue = "off" break; default: muteValue = ""; } var letter = $(this).val(); if (muteValue === 'Both') { $('tr').show(); } else { $('tr').each(function (rowIdx, tr) { $(this).find('td').find('button').each(function (idx, td) { var check = $(this).attr("current"); if (idx === 0 || idx === 1) { if (check && check.indexOf(muteValue) == 0) { $(tr).show(); } else { $(tr).hide(); } } }); }); } } }); jqAttach(); } }); Thank you for your help and I admit this question could be better, but I'm struggling with concepts and very unfamiliar territory. Please let me know what information I can provide or razzies if I missed the obvious answer. Thanks.
doc_23531237
{ "ID_54321":{ "Name":"John Doe", "Email":"jdoe@gmail123.com", "Q1":"3" } } I am able to retrieve the item. for key in data: for item in data[key]: print item Result Name Email Q1 The issue is that I cannot retrieve the value for the item I am trying to retrieve. for key in data: for item in data[key]: print item["Q1"] I recieve the error : TypeError: string indices must be integers A: While looping in data[key] you can get value with data[key][item]: data = { "ID_54321": { "Name": "John Doe", "Email": "jdoe@gmail123.com", "Q1": "3" } } for key in data: for item in data[key]: print data[key][item] A: First of all I'm assuming you are talking about iterating over dictionary rather than JSON object, because JSON is a string representation of data while dictionary is a data structure. In your case "item" is a string (in fact names of the keys from nested dict) so you can't get your value from it. If your looking just for the value of 'Q1' key you could do something like: for key in data.iterkeys(): print data[key]['Q1'] But assuming you want to print each value from the nested dictionary not just 'Q1' it could be: for key in data.iterkeys(): for k, v in data[key].iteritems(): print k, v Where k is the name of each key and v is the corresponding value. And in Python 3.X it would look like this: for item in data.keys(): for k,v in data[item].items(): print(k,v) A: item["Q1"] gives you an error because item is a string. What you want to do is access the inner dictionary's key-value so try changing it to something like this: for key in data: for item in data[key]: print data[key][item]
doc_23531238
So I wanted to define the primary and foreign keys for each table. Based on this answer, I saw that: * *"city" table has 1 PK (ID) and 1 FK (countrycode) *"countrylanguage" table has 2 PK (Language and countrycode) and 1 FK (countrycode) *"country" table has 1 PK (Code) So I tried to make some magic on a "pre-heated" code: CREATE TABLE `City` ( `ID` int(11) NOT NULL, `Name` varchar(35) NOT NULL , `CountryCode` varchar(3) NOT NULL DEFAULT '', `District` varchar(20) NOT NULL , `Population` int(11) NOT NULL , PRIMARY KEY(`ID`) , FOREIGN KEY(`CountryCode`) REFERENCES `Country`(`Code`) ) ; CREATE TABLE `CountryLanguage` ( `CountryCode` varchar(3) NOT NULL DEFAULT '', `Language` varchar(30) NOT NULL , `IsOfficial` varchar(30) NOT NULL , `Percentage` float(4,1) NOT NULL , PRIMARY KEY(`Language`), FOREIGN KEY(`CountryCode`) REFERENCES `Country`(`Code`) ) ; CREATE TABLE `Country` ( `Code` varchar(3) NOT NULL DEFAULT '', `Name` varchar(52) NOT NULL DEFAULT '', `Continent` varchar(63), `Region` varchar(26) NOT NULL DEFAULT '', `SurfaceArea` float(10,2) NOT NULL DEFAULT '0.00', `IndepYear` smallint(6) DEFAULT NULL, `Population` int(11) NOT NULL DEFAULT '0', `LifeExpectancy` float(3,1) DEFAULT NULL, `GNP` float(10,2) DEFAULT NULL, `GNPOld` float(10,2) DEFAULT NULL, `LocalName` varchar(45) NOT NULL DEFAULT '', `GovernmentForm` varchar(45) NOT NULL DEFAULT '', `HeadOfState` varchar(60) DEFAULT NULL, `Capital` int(11) DEFAULT NULL, `Code2` varchar(2) NOT NULL DEFAULT '', PRIMARY KEY(`Code`) ) ; but my good ol' mysql command line client has the same ERROR 1005 thing twice, and says that it can't create tables 'test.city' and 'test.countrylanguage' with the errno:150 thingy as an explanation. So I searched a bit around here and I found some answers regarding to table elements not having the same type/parameter (f.e. INT(2) to INT(2) NOT NULL). As fas as I could see, Nothing like this happens here. What is my coffee-drained brain missing here? Thank you for your time in advance. A: CREATE TABLE Country first, then CREATE TABLE City, and CREATE TABLE CountryLanguage, since TABLE Country is referenced by the other two tables. A: wrong create sequnce you should create firts Country because City and CountryLanguage refer to country table CREATE TABLE `Country` ( `Code` varchar(3) NOT NULL DEFAULT '', `Name` varchar(52) NOT NULL DEFAULT '', `Continent` varchar(63), `Region` varchar(26) NOT NULL DEFAULT '', `SurfaceArea` float(10,2) NOT NULL DEFAULT '0.00', `IndepYear` smallint(6) DEFAULT NULL, `Population` int(11) NOT NULL DEFAULT '0', `LifeExpectancy` float(3,1) DEFAULT NULL, `GNP` float(10,2) DEFAULT NULL, `GNPOld` float(10,2) DEFAULT NULL, `LocalName` varchar(45) NOT NULL DEFAULT '', `GovernmentForm` varchar(45) NOT NULL DEFAULT '', `HeadOfState` varchar(60) DEFAULT NULL, `Capital` int(11) DEFAULT NULL, `Code2` varchar(2) NOT NULL DEFAULT '', PRIMARY KEY(`Code`) ) ; CREATE TABLE `City` ( `ID` int(11) NOT NULL, `Name` varchar(35) NOT NULL , `CountryCode` varchar(3) NOT NULL DEFAULT '', `District` varchar(20) NOT NULL , `Population` int(11) NOT NULL , PRIMARY KEY(`ID`) , FOREIGN KEY(`CountryCode`) REFERENCES `Country`(`Code`) ) ; CREATE TABLE `CountryLanguage` ( `CountryCode` varchar(3) NOT NULL DEFAULT '', `Language` varchar(30) NOT NULL , `IsOfficial` varchar(30) NOT NULL , `Percentage` float(4,1) NOT NULL , PRIMARY KEY(`Language`), FOREIGN KEY(`CountryCode`) REFERENCES `Country`(`Code`) ) ;
doc_23531239
Thank's A: Try this code in VB.NET: Protected Sub btnExport(ByVal sender As Object, ByVal e As System.EventArgs) Dim TheFile As FileInfo = New FileInfo(MapPath(".") & "\" & "filename.xls") ' Connection String to Excel Workbook 2010 (xlsx) ' Dim excelConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~\directory\filename.xlsx") + ";Extended Properties=""Excel 12.0 Xml;HDR=YES;""" ' Connection String to Excel Workbook 2003 (xls) Dim excelConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~\directory\filename.xls") + ";Extended Properties=""Excel 8.0;HDR=YES;""" ' Create Connection to Excel Workbook Using connection As New OleDbConnection(excelConnectionString) Dim command As New OleDbCommand("Select * FROM [sheetname$] ", connection) connection.Open() ' Create DbDataReader to Data Worksheet Using dr As DbDataReader = command.ExecuteReader() ' SQL Server Connection String Const sqlConnectionString As String = "Data Source=server; Initial Catalog=database; Persist Security Info=True;User ID=userid;Password=password" ' Bulk Copy to SQL Server Using bulkCopy As New SqlBulkCopy(sqlConnectionString) bulkCopy.DestinationTableName = "SqlServerTableName" bulkCopy.WriteToServer(dr) End Using End Using End Using End Sub Additional tip: try to set IIS to run 32-bit applications. A: Yes it is possible. Here is the bird's view of possible basic steps: * *After uploading - save Excel file under temporary unique name *Open OLEDB connection to the uploaded file *Read it (either via OleDbDataReader - if it's a huge file, so you don't have to load it into memory at once, or into DataTable if it's small) *Run your queries, Stored procedures to update SqlServer DB with acquired data *Delete uploaded file A: Try this public void export(string excelfilepath) { string ssqltable = "tdatamigrationtable"; string myexceldataquery = "select student,rollno,course from [sheet1$]"; try { //create our connection strings string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=" + excelfilepath + ";extended properties=" + "\"excel 8.0;hdr=yes;\""; string ssqlconnectionstring = "server=mydatabaseservername;user id=dbuserid;password=dbuserpassword;database=databasename;connection reset=false"; //series of commands to bulk copy data from the excel file into our sql table oledbconnection oledbconn = new oledbconnection(sexcelconnectionstring); oledbcommand oledbcmd = new oledbcommand(myexceldataquery, oledbconn); oledbconn.open(); oledbdatareader dr = oledbcmd.executereader(); sqlbulkcopy bulkcopy = new sqlbulkcopy(ssqlconnectionstring); bulkcopy.destinationtablename = ssqltable; while (dr.read()) { bulkcopy.writetoserver(dr); } oledbconn.close(); } catch (exception ex) { //handle exception } } A: Imports System.Data.Common Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim fname As String Using ofd As New OpenFileDialog If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then fname = ofd.FileName End If End Using Dim olecon As String = "Provider=Microsoft.ACE.OLEDB.12.0 ;Data Source=" & fname & ";Extended Properties=""Excel 12.0;IMEX=1;HDR=YES;""" Dim dBaseConnection As New System.Data.OleDb.OleDbConnection(olecon) dBaseConnection.Open() SSQL = "select [LOT],[IMAGE],[STYLENO],[VENDOR] from [Sheet1$]" Dim cmd As New OleDbCommand(SSQL, dBaseConnection) Dim da As New OleDbDataAdapter(cmd) Dim ds As New DataSet da.Fill(ds) Using dr As DbDataReader = cmd.ExecuteReader If SHCONNECTION.State = ConnectionState.Closed Then Call SHconn(MCONNECTIONSTRING) End If Using bulkCopy As New SqlBulkCopy(MCONNECTIONSTRING) bulkCopy.DestinationTableName = "DBimage" bulkCopy.WriteToServer(ds) End Using End Using End Sub End Class
doc_23531240
end_time_string = data['endTime'] # Get the end time in a string in weird format date_format = "%Y%m%dT%H%M%S.%fZ" # Specify the date format for the datetime parser end_time = datetime.strptime(end_time_string, date_format) # turn the date time string into datetime object current_time = datetime.utcnow() # Get current time in UTC time zone, which is what CoC uses. time_remaining = end_time - current_time # Get the time remaining till end of war My end_time is a datetime object. My current_time is a datetime object. But time_remaining is a timedelta object. I am able to pull the hours, minutes and seconds from the object using: hours, minutes, seconds = map(float, str(time_remaining).split(':')) But the problem is that sometimes the time_remaining has days in it, and sometimes it doesn't. 1 day, 4:55:22.761359 -1 days, 23:59:08.45766 When there are days involved, specifically when the timedelta object goes negative, my script fails. What is the best find the amount of time between my two datetime objects in ONLY hours, minutes, and seconds, without days included? A: timedelta is an object. One of its methods is total_seconds() so dividing by 3600 gives hours. Also dividing by another timedelta gives a float result of the ratio, so divide by timedelta(hours=1) to get the time in hours: >>> import datetime as dt >>> x = dt.timedelta(days=1, seconds=5000) >>> x.total_seconds() / 3600 25.38888888888889 >>> x / dt.timedelta(hours=1) 25.38888888888889 or in hours, minutes, seconds: >>> hours, remaining_seconds = divmod(x.total_seconds(), 3600) >>> minutes, seconds = divmod(remaining_seconds, 60) >>> hours, minutes, seconds (25.0, 23.0, 20.0) A: So, a timedelta object has days, seconds and microseconds. Multiply the days by 24 to convert it into hours, and then some nice math with modulo (%) and the usefull // operator, for which I will quote something: //: Divides the number on its left by the number on its right, rounds down the answer, and returns a whole number. combining everything you get a nice f-string with padding for the zeros: f"{td.seconds//3600 + td.days*24:02}:{(td.seconds//60)%60:02}:{td.seconds%60:02}:{td.microseconds:06}" To put this into code: from datetime import datetime, timedelta # 3670 seconds is 1h1m10s tomorrow = datetime.utcnow() + timedelta(1, 3670, 123) current_time = datetime.utcnow() td = tomorrow - current_time print(td) print(td.days) print(td.seconds) print(td.microseconds) print(f"{td.seconds//3600 + td.days*24:02}:{(td.seconds//60)%60:02}:{td.seconds%60:02}:{td.microseconds:06}") Which generates the following output: 1 day, 1:01:10.000123 1 3670 123 25:01:10:000123
doc_23531241
What I am trying to do is display large images in the fancybox iframe of about width 900 and height 500. Of course right now images render huge and don't fit into that iframe. I am having a hard time capturing the right class or a way to navigate to the image to resize it. What I tried is using beforeShow function and do this: $(".fancybox").fancybox({ type: 'iframe', href: source, title: title, width: 900, height: 500, closeBtn: false, nextSpeed: 0, //important prevSpeed: 0, //important beforeShow: function() { alert('its working!'); $(".fancybox-iframe img").css("width","900px"); $(".fancybox-iframe img").css("height","auto"); $(".fancybox-iframe img").addClass("imageResize"); } }); However, neither $(".fancybox-iframe img") nor $(".fancybox-inner img") are correct ways to trigger the img. How can I use beforeShow function to properly resize my images inside the fancybox iframe. Thanks! A: I figured it out beforeShow: function () { var newWidth = 900; // set new image display width $('.fancybox-iframe').contents().find('img').css({ width : newWidth, height : "auto" }); // apply new size to img } A: for me using fancybox 3 i was having an issue with the fancybox iframe not being loaded, so this helped: This code polls the iframe for an img tag every 100msec for up to 2 seconds to see if an image has been loaded. if it has then it sets the attributes of the image to be max height. If an iframe isn't found, then it should clear the interval straight away. var fancyboxOptions = { onComplete: function( instance, slide ) { var timeCompleted = new Date(); function afterLoading () { clearInterval(pollLoaded); $('iframe',slide.$content[0]).contents().find('img').attr('height','100%'); } var pollLoaded = setInterval(function(){ var iframe = document.getElementById($('iframe',slide.$content[0]).attr('id')); var iframeDoc = iframe.contentDocument || iframe.contentWindow.document; if (iframeDoc) { if (( iframeDoc.readyState === 'complete' ) && ($('iframe',slide.$content[0]).contents().find('img').length > 0)) { afterLoading(); } // try for 2 seconds then stop. if (new Date() - timeCompleted > 2000) { clearInterval(pollLoaded); } } else { clearInterval(pollLoaded); } },100); } };
doc_23531242
My current code: jt stands for journal title, pulled out properly from the file. GBIDs are added to the count as encountered. ... up to this point, the first search is performed, each "pmid" you can think of as a single file, so each "fetch" goes through all the files one at a time... pmid_list.each do |pmid| ncbi_fetch.pubmed(pmid, "medline").each do |pmid_line| if pmid_line =~ /JT.+- (.+)\n/ jt = $1 jt_count = 0 jt_hash[jt] = jt_count ncbi_fetch.pubmed(pmid, "medline").each do |pmid_line_2| if pmid_line_2 =~ /SI.+- GENBANK\/(.+)\n/ gbid = $1 jt_count += 1 gbid_hash["#{gbid}\n"] = nil end end if jt_count > 0 puts "#{jt} = #{jt_count}" end end end end My result: Your search returned 192 results. Virology journal = 8 Archives of virology = 9 Virus research = 1 Archives of virology = 6 Virology = 1 Basically, how do I get it to say Archives of virology = 15, but for any journal title? I tried a hash, but the second archives of virology just overwrote the first... is there a way to make two keys add their values in a hash? Full code: #!/usr/local/bin/ruby require 'rubygems' require 'bio' Bio::NCBI.default_email = 'kepresto@uvm.edu' ncbi_search = Bio::NCBI::REST::ESearch.new ncbi_fetch = Bio::NCBI::REST::EFetch.new print "\nQuery?\s" query_phrase = gets.chomp "\nYou said \"#{query_phrase}\". Searching, please wait..." pmid_list = ncbi_search.search("pubmed", "#{query_phrase}", 0) puts "\nYour search returned #{pmid_list.count} results." if pmid_list.count > 200 puts "\nToo big." exit end gbid_hash = Hash.new jt_hash = Hash.new(0) pmid_list.each do |pmid| ncbi_fetch.pubmed(pmid, "medline").each do |pmid_line| if pmid_line =~ /JT.+- (.+)\n/ jt = $1 jt_count = 0 jt_hash[jt] = jt_count ncbi_fetch.pubmed(pmid, "medline").each do |pmid_line_2| if pmid_line_2 =~ /SI.+- GENBANK\/(.+)\n/ gbid = $1 jt_count += 1 gbid_hash["#{gbid}\n"] = nil end end if jt_count > 0 puts "#{jt} = #{jt_count}" end jt_hash[jt] += jt_count end end end jt_hash.each do |key,value| # if value > 0 puts "Journal: #{key} has #{value} entries associtated with it. " # end end # gbid_file = File.open("temp_*.txt","r").each do |gbid_count| # puts gbid_count # end A: At the top somewhere declare the jt_hash to start with zero's: jt_hash = Hash.new(0) Then, after: puts "#{jt} = #{jt_count}" Put: jt_hash[jt] += jt_count This makes it so that jt_count is incremented in the hash, rather than overwritten. This will print out everything as it happens, so you'll get something like: Your search returned 192 results. Virology journal = 8 Archives of virology = 9 Virus research = 1 Archives of virology = 15 Virology = 1 If you then want everything to just print once just put something right at the end that goes through jt_hash and prints everything: jt_hash.each { |elem| puts "#{elem[1]} = #{elem[0]}" }
doc_23531243
My code: setInterval(function() { y.on('deviceconnected', function(device) { console.log("Power off the device"); var state = false; y.setPower(device, state, 300); }); }, 3000); That function powers off my room bulb and it works fine out of the setInterval. Unfortunately, inside the setInterval it doesn't work at all. Program never enters the function and for example print: Power off the device. How should I call that functions inside the setInterval? A: You are doing it backwards compared to what is needed. Yes, docs write Before attempting to control any devices you must have completed device discovery and connection. but it means that it has to happen before controlling, once. Not once every 3 seconds. You would need the complete opposite: ... y.on('deviceconnected', function(device) { y.setPower(device,true,300); setInterval(function(){ y.setBrightness(device,50,300); setTimout(function(){ y.setBrightness(device,100,300); },1500); },3000); }); Totally ad-hoc example, copied the pieces from docs. 300-s are transition times (in ms), first it powers up the device, then it tries to toggle between 50% and 100% brightness at every 1.5 seconds (more-or-less, that inner timeout is not very nice, it could rather use a state variable instead). A: Sorry that I didnt mantioned but I have function which search the network looking for my device and function which connect my client to the device. Moreover, I have function which takes lux value from my light sensor, using request to my server. Using that value, I want to steer my room bulb in Real Time. By that, I mean running client which use power and brigthness functions which will steer my room bulb (that algorytm isnt done yet) . I thought that setInterval Will be Best for that purpose but I am open to other solutions. Thanks for the help
doc_23531244
Can you please me to get away from this Terminal screen import Tkinter,ttk import tkMessageBox from Tkinter import * import io,sys,os,subprocess from tkFileDialog import askopenfilename def askforvideo(): global process name= askopenfilename(title=[("videopen")],filetypes=[("Video Files","*.h264")]) if name != "": subprocess.call(['vlc',name,'--play-and-exit']) return root = Tk() root.title("Flight Recording Application") mainframe = ttk.Frame(root, padding="200 200 200 200") mainframe.grid() ttk.Button(mainframe, text="Video Open", command=askforvideo).grid(column=10, row=3) ttk.Button(mainframe, text="Exit", command=root.quit).grid(column=95, row=3) root.mainloop() A: The following will work. Click Edit>Preferences>Tools In the terminal field change the value to bash -x %c This will execute your python command from bash instead of the terminal. A: If you are using an older version of Geany, it may be worth updating the repository and using the virtual terminal emulator at the bottom.
doc_23531245
doc_23531246
Count ID size 0 25 0001 1 1 4 0001 2 2 9 0001 3 3 13 0001 4 4 19 0001 5 ... 8 11 0003 10 9 10 0003 12 10 7 0003 14 11 15 0003 16 To create categorized plots I use the following simple code: import seaborn as sns sns.catplot(data=df, x='size', y='Count', col='ID', kind='bar') This gives a perfect result. However, currently I am exploring the possibilities for a much larger and diverse dataset. The problem with the catplot function is that it will use the same bins for all the plots. The new dataset is more like: Count ID size 0 25 0001 1 1 4 0001 2 2 9 0001 3 3 13 0001 4 4 19 0001 5 ... 8 11 0003 100 9 10 0003 150 10 7 0003 200 11 15 0003 250 Therefor, it is not relevant to have the same bins for all IDs. My objective is to create plots for each ID where the range of bins is depended on the largest and smallest size of the ID. Unfortunately, I have been unable to tackle this problem. Thanks for the help in advance! A: Try using for loop. Example: import seaborn as sns for id in df["ID"].unique(): sns.catplot(data=df.where(df["ID"] == id), x='size', y='Count', col='ID', kind='bar') I believe there is more pythonic way, so wait a little bit for another answers.
doc_23531247
I have reviewed several tutorials on how to create a maven project and the file structure in the tutorials is not what I am getting. Why am I missing several files? note: This is what tutorials show This is what I get. A: Both are same . Only view is different . You can change it by going to eclipse->window->show view , and choosing the view you want A: Here are some points for your help: * *Install the maven plugin through Eclipse. *Set the Environment variables, e.g. JAVA_HOME, MAVEN_HOME & add the required paths. *From command-line, check "java -version" & "mvn -version". *If this 2 commands shows proper info, you are set to write your first maven project. *Create a new project as maven project with all the required information. *On completion you will find a similar directory structure with "src/main/java", "src/test/java" & JRE Library along with pom.xml. *Open the "pom.xml", provide all the dependencies, e.g. Selenium, TestNG & save. *You will find all the dependencies being listed in "Maven Dependencies" and you will also find testng.xml *Place the "testng.xml" in the location you specified in "pom.xml" *Your project structure should be looking similar now. Let me know if this helps you.
doc_23531248
You can see in the in the image that there are space on the left and right side. Please tell me how can I do that. A: If you want this permanent for all cells, you can use. self.tableView.contentInset = UIEdgeInsets(top: , left: , bottom: , right) in your viewDidLoad() method just change left and right as you like A: You can set Leading and Trailing of base View with the cell contentView to 'X' pt so that it will align themselves exactly the UI shown above. To add the Constraint Right Click on ImageView and Drag it on to contentView (as per second image), select Leading Space to Container Margin (as per third image)
doc_23531249
<div id="testA"> <ul> <li>...</li> </ul> </div> CSS: div { width: 12em; background: #c6c6c6; padding: 0.5em; float: left; margin-right: 1em; } ul { margin: 0; } #testA ul { border-radius: 6px; background: #f6f6f6; height: 6em; overflow: auto; } A: The issue is actually caused by the border-radius. Having overflow: auto or overflow: scroll on an element which has a border-radius causes paint storms and to repaint on scroll. It would be suggested to remove the border-radius from such elements completely. Demo: http://codepen.io/kevinfarrugia/pen/KgAYyE CSS: #testB .container { border-radius: 6px; background: #f6f6f6; display: inline-block; padding: 0; } #testB ul { height: 6em; overflow: auto; }
doc_23531250
The rules are For a set of given values in control1; control2 is not enabled. For a set of other values in control1; control2 is enabled. I am trying to implement this behaviour: With focus on control1, when the user is pressing tab we evaluate if control2 must be enabled or disabled, if control2 is enabled it gets the focus, if control2 is not enabled, control3 gets the focus. I've attempted to use various events on control1 and control2 but it seems to always miss a beat... using control1_Exit I don't seem to be able to prevent it from jumping to control3 even if control2 should be enabled (I've tried to force the focus to control2 but the cursor lands on control3 anyway, seems that when Exit is triggered the cursor is already in transit to control3). I am scratching my head with this problem for a few hours though it should be a simple one, and searching SE or the web does not seem to lead to a solution... Any help would be appreciated. Thanks in advance Chris A: I suggest to set control2.Enabled in the On Change event of control1. Plus on Form_Current, so that it is set correctly for existing data. Then just set the tab order so that control2 is after control1, and you don't need any code for focus or exit. If control2 is enabled, it receives the focus on tab, if not it won't.
doc_23531251
Kindly assist me on this. A: You need to have at least basic knowledge on using adobe Photoshop. a. You need to know how to deal with layers so you can extract the website carefully. b. Use slicing tool. after you carefully slice each part. then you can now press and hold Ctrl+Shift+Alt+s (all at the same time) then choose save At the bottom option you can see "Format:" choose html and images then save it on your pc. Second option is you can convert you psd to html by going to this site. http://psdtoweb.de/index.php I personally don't recommend you to use these methods because the codes in html is not good. I recommend you is study bootstrap instead.
doc_23531252
I'm getting the error even though the connection is fine. "TypeError: _get_column_info() got an unexpected keyword argument 'generated'" I tried with another databse of a different server it works fine... But not sure whats the issue with this server tables. Can you please help me out with a solution. Table=sa.Table("Tablename" ,metadata,autoload=True,autoload_with=engine) TypeError Traceback (most recent call last) <ipython-input-98-366ec112cf52> in <module> ----> 1 Table=sa.Table("dim_dealer" ,metadata,autoload=True,autoload_with=engine) <string> in __new__(cls, *args, **kw) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy\util\deprecations.py in warned(fn, *args, **kwargs) 126 ) 127 --> 128 return fn(*args, **kwargs) 129 130 doc = fn.__doc__ is not None and fn.__doc__ or "" ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy\sql\schema.py in __new__(cls, *args, **kw) 494 except: 495 with util.safe_reraise(): --> 496 metadata._remove_table(name, schema) 497 498 @property ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy\util\langhelpers.py in __exit__(self, type_, value, traceback) 66 self._exc_info = None # remove potential circular references 67 if not self.warn_only: ---> 68 compat.reraise(exc_type, exc_value, exc_tb) 69 else: 70 if not compat.py3k and self._exc_info and self._exc_info[1]: ~\AppData\Local\Continuum\anaconda3\lib\`enter code here`site-packages\sqlalchemy\util\compat.py in reraise(tp, value, tb, cause) 151 if value.__traceback__ is not tb: 152 raise value.with_traceback(tb) --> 153 raise value 154 155 def u(s): ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy\sql\schema.py in __new__(cls, *args, **kw) 489 metadata._add_table(name, schema, table) 490 try: --> 491 table._init(name, metadata, *args, **kw) 492 table.dispatch.after_parent_attach(table, metadata) 493 return table ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy\sql\schema.py in _init(self, name, metadata, *args, **kwargs) 583 include_columns, 584 _extend_on=_extend_on, --> 585 resolve_fks=resolve_fks, 586 ) 587 ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy\sql\schema.py in _autoload(self, metadata, autoload_with, include_columns, exclude_columns, resolve_fks, _extend_on) 607 exclude_columns, 608 resolve_fks, --> 609 _extend_on=_extend_on, 610 ) 611 else: ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy\engine\base.py in run_callable(self, callable_, *args, **kwargs) 2148 """ 2149 with self._contextual_connect() as conn: -> 2150 return conn.run_callable(callable_, *args, **kwargs) 2151 2152 def execute(self, statement, *multiparams, **params): ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy\engine\base.py in run_callable(self, callable_, *args, **kwargs) 1602 1603 """ -> 1604 return callable_(self, *args, **kwargs) 1605 1606 def _run_visitor(self, visitorcallable, element, **kwargs): ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy\engine\default.py in reflecttable(self, connection, table, include_columns, exclude_columns, resolve_fks, **opts) 429 insp = reflection.Inspector.from_engine(connection) 430 return insp.reflecttable( --> 431 table, include_columns, exclude_columns, resolve_fks, **opts 432 ) 433 ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy\engine\reflection.py in reflecttable(self, table, include_columns, exclude_columns, resolve_fks, _extend_on) 638 639 for col_d in self.get_columns( --> 640 table_name, schema, **table.dialect_kwargs 641 ): 642 found_table = True ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy\engine\reflection.py in get_columns(self, table_name, schema, **kw) 371 372 col_defs = self.dialect.get_columns( --> 373 self.bind, table_name, schema, info_cache=self.info_cache, **kw 374 ) 375 for col_def in col_defs: <string> in get_columns(self, connection, table_name, schema, **kw) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy\engine\reflection.py in cache(fn, self, con, *args, **kw) 54 ret = info_cache.get(key) 55 if ret is None: ---> 56 ret = fn(self, con, *args, **kw) 57 info_cache[key] = ret 58 return ret ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy_redshift\dialect.py in get_columns(self, connection, table_name, schema, **kw) 459 default=col.default, notnull=col.notnull, domains=domains, 460 enums=[], schema=col.schema, encode=col.encode, --> 461 comment=col.comment) 462 columns.append(column_info) 463 return columns ~\AppData\Local\Continuum\anaconda3\lib\site-packages\sqlalchemy_redshift\dialect.py in _get_column_info(self, *args, **kwargs) 666 column_info = super(RedshiftDialect, self)._get_column_info( 667 *args, --> 668 **kw 669 ) 670 if isinstance(column_info['type'], VARCHAR): TypeError: _get_column_info() got an unexpected keyword argument 'generated' print(repr(metadata.tables[Table])) Thanks in advance A: It looks like a backwards compatibility bug between SQLAlchemy and SQLAlchemy-Redshift. Private method RedshiftDialect._get_column_info was overriden in SQLAlchemy-Redshift. generated keyword argument was added to this method in SQLAlchemy v1.3.16 which caused compatibility error. So a fix for this problem was implemented: generated keyword should be used only for the latest versions of SQLAlchemy. Unfortunately it doesn't work: if sa.__version__ >= '1.3.16': # SQLAlchemy 1.3.16 introduced generated columns, # not supported in redshift kw['generated'] = '' As you can see this condition is truthy for your SQLAlchemy version ("1.3.7") because this is how string comparison works. I think I will make a pull request to correct this behaviour. I think the most simple solution for you for now is to update your SQLAlchemy package to the 1.3.10 version or newer. In this case this condition will work as expected. Update: This bug was fixed in the SQLAlchemy-Redshift v0.8.0.
doc_23531253
Example: I sometimes want to tell all other nodes to invalidate cache pages or notify them that something happened. * *Request-reply won't work because I don't want the requester to block waiting for an empty response. I want to allow multiple signals to build up at the server. *Publish-subscribe feels wrong because I'd have to subscribe to everything, and start two sockets, one for each direction of communication. *PAIRs don't support automatically reconnecting and have other limitations. Is pub-sub the best way to go? Or am I better just to use a traditional socket, write to both ends, and handle disconnections/reconnecting? A: What you want is a dealer socket in your client side and a dealer socket on your server side. If you want to be able to send message to a specific node from the server side, then you better use a router socket in the server.
doc_23531254
Here is the image: http://imageshack.us/photo/my-images/841/7a83.png/. But i am stuck with trying to figure out the matrix calculation. For example if the anchor rotates 45degrees, so its facing the x-axis, how can i make the rod still move backwards and forwards? A: Just as scooby37 noticed, combination example provided by Troopers is not valid. You should NOT: new THREE.Matrix4().makeTranslation(0, 0, z).makeRotationZ(Math.PI/2); Instead you can try something like: let rotation = new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0, 1, 0), Math.PI / 6.0); let transformation = new THREE.Matrix4().makeTranslation(0, this.height, 0); this.mesh.applyMatrix(rotation.multiply(transformation)); which introduce matrix multiplication - usual way transformations should be combined. A: For the rotation around z axis : var rotation = new THREE.Matrix4().makeRotationZ(Math.PI/2); For the translation, where z is your delta : var translation = new THREE.Matrix4().makeTranslation(0, 0, z); You can combine the two transformations in beginning with the translation : var transformation = new THREE.Matrix4().makeTranslation(0, 0, z).makeRotationZ(Math.PI/2); var transformation = rotation.multiply(translation); Then apply transformation to your geometry : geometry.applyMatrix(transformation);
doc_23531255
By reading this article that expline what are Expression trees and what they are used for I have some question thats the article those not answer me clearly. A. What is the difference between Data Structure and 'compiled piece of code'. * I know that data structure is Array,List,.. But this is not the answer I am looking for. B. Why is it better to use data structure in Entity Framework than 'compiled piece of code' in terms of efficiency. A: Answer to both A and B. The compiled piece of code can not be reverse engineered into something that you can translate to SQL. There are to many details that made the original concepts you want to translate to SQL go away. The expression trees can be analyzed and understood at run time, when the compiled code can not. Another meta representation of the queries would be possible to use, but the expression trees gives the advantage that existing plumbing in the compiler can be used for a lot of the heavy work. A: An Expression is code representing code. It is not an executable piece of code that you can run until you call Compile(). An Expression contains an object graph that describes some code. So the example function: x => x + 1 Is representing a function that takes 1 parameter, and returns the expression (x + 1). As an object graph, it's something like this: Expression AdditionExpression RightValue VariableExpression (x) LeftValue LiteralExpression (1) You could parse through the expression and figure out the name of the parts of the expression, or what the literal value is, or what the operation is. Once it is compiled, it is a logical sequence of operations, and all of that metadata is lost. In terms of Entity Framework, given a sample expression like so: myObjects.Where(x => x.Id > 10).ToList() The LINQ to SQL IQueryable provider is inspecting this expression, finding the name of the property Id and then finding the literal value of 10 to convert that into a SQL statement. If this was a function (a compiled unit of code), there is no metadata to inspect, and conversion to SQL would be impossible. It also allows you to deconstruct things into supported and unsupported expressions for efficiency in making sure your SQL query returns the requested data only, instead of a large data set.
doc_23531256
I am wondering if there is a way to pick up the domain name in the nuxt.config.js file?
doc_23531257
See first example home,Scripts,Snippet. if Script Parent is 1 it should under home tr,if Snippet parent id is 6 it is under the Script menu <table id="sort-table"> <tbody> <tr> <th>Id</th> <th>Parent</th> <th>Title</th> </tr> <tr> <td>1</td> <td>0</td> <td>home</td> </tr> <tr> <td>2</td> <td>0</td> <td>Code</td> </tr> <tr> <td>3</td> <td>0</td> <td>Contact</td> </tr> <tr> <td>4</td> <td>10</td> <td>PHP</td> </tr> <tr> <td>5</td> <td>2</td> <td>CSS</td> </tr> <tr> <td>6</td> <td>1</td> <td>Scripts</td> </tr> <tr> <td>8</td> <td>4</td> <td>Archive</td> </tr> <tr> <td>9</td> <td>6</td> <td>Snippet</td> </tr> <tr> <td>10</td> <td>0</td> <td>samitha</td> </tr> <tr> <td>7</td> <td>4</td> <td>help</td> </tr> </tbody> </table> <span></span> <br> <button class="sort-table asc">sort</button> jquery $('.sort-table').click(function (e) { var table = $("table tbody"); table.find('tr').each(function () { var $tds = $(this).find('td'), id = $tds.eq(0).text(), parent = $tds.eq(1).text(), title = $tds.eq(2).text(); if (parent === 0) { } }); }); output Id Parent Title 1 0 home 2 0 Code 3 0 Contact 4 10 PHP 5 2 CSS 6 1 Scripts 8 4 Archive 9 6 Snippet 10 0 samitha 7 4 help I want to sort it like bellow 2nd table Id Parent Title 1 0 home 6 1 Scripts 9 6 Snippet 2 0 Code 5 2 CSS 3 0 Contact 10 0 samitha 4 10 PHP 8 4 Archive 7 4 help I want if the parent Id is the id of menu it need to be sort like above 2nd table.I did something with and i need to go though on this ? A: As there is no apparent system to sort by, I guess you have to define something yourself : $('.sort-table').click(function (e) { var sort = [1,6,9,2,5,3,10,4,8,7], table = $("table tbody"), tr = table.find('tr'); $.each(sort, function(_,index) { tr.filter(function() { return parseInt($('td:first', this).text(), 10) == index; }).appendTo(table); }); }); FIDDLE EDIT: I think maybe I get it, but I probably don't? If you are trying to add each TR element after the TR element that has the ID of the given parent element in the current TR etc... ??? Anyway, try this : $('.sort-table').click(function (e) { var table = $("table tbody"), tr = table.find('tr'); $.each(tr, function(_,el) { var par = parseInt($(el).find('td').eq(1).text(), 10); if (par !== 0) { var par_el = tr.find('td:first').filter(function() { return parseInt($(this).text(),10) == par; }).closest('tr'); par_el.after(el); } }); }); FIDDLE
doc_23531258
I am using kerassugeon for this and performing channel pruning. Here are the relevant imports : from kerassurgeon import identify from kerassurgeon.operations import delete_channels, delete_layer Here is the code of the same : #load pre trained Xception model model=tf.keras.applications.xception.Xception(weights='imagenet',include_top=True) weight = model.layers[1].get_weights()[0] weight_dict = {} num_filters = len(weight[0,0,0,:]) for j in range(num_filters) : w_s = np.sum(abs(weight[:,:,:,j])) filt = 'filt_{}'.format(j) weight_dict[filt]=w_s weights_dict_sort = sorted(weight_dict.items(), key = lambda kv:kv[1]) print('L1 norm conv layer {}\n'.format(1), weights_dict_sort) weights_value = [] for elem in weights_dict_sort : weights_value.append(elem[1]) xc = range(num_filters) layer_0 = model.layers[1] model_new = delete_channels(model=model, layer=layer_0, channels=[1,7,2,8,16]) model_new.compile(loss = 'binary_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy']) This is throwing me the following error : TypeError Traceback (most recent call last) <ipython-input-42-8ec328142934> in <module>() 23 24 layer_0 = model.layers[1] ---> 25 model_new = delete_channels(model=model, layer=layer_0, channels=[1,7,2,8,16]) 26 27 model_new.compile(loss = 'binary_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy']) 4 frames /usr/local/lib/python3.7/dist-packages/kerassurgeon/operations.py in delete_channels(model, layer, channels, node_indices, copy) 103 surgeon = Surgeon(model, copy) 104 surgeon.add_job('delete_channels', layer, node_indices=node_indices, channels=channels) --> 105 return surgeon.operate() /usr/local/lib/python3.7/dist-packages/kerassurgeon/surgeon.py in operate(self) 157 # Perform surgery at this node 158 kwargs = self._kwargs_map[node] --> 159 self._mod_func_map[node](node, outputs, output_masks, **kwargs) 160 161 # Finish rebuilding model /usr/local/lib/python3.7/dist-packages/kerassurgeon/surgeon.py in _delete_channels(self, node, inputs, input_masks, channels, layer_name) 317 """ 318 old_layer = node.outbound_layer --> 319 old_layer_output = utils.single_element(node.output_tensors) 320 # Create a mask to propagate the deleted channels to downstream layers 321 new_delete_mask = self._make_delete_mask(old_layer, channels) /usr/local/lib/python3.7/dist-packages/kerassurgeon/utils.py in single_element(x) 141 return x 142 --> 143 if len(x) == 1: 144 x = x[0] 145 return x /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/keras_tensor.py in __len__(self) 238 239 def __len__(self): --> 240 raise TypeError('Keras symbolic inputs/outputs do not ' 241 'implement `__len__`. You may be ' 242 'trying to pass Keras symbolic inputs/outputs ' TypeError: Keras symbolic inputs/outputs do not implement `__len__`. You may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model. This error will also get raised if you try asserting a symbolic input/output directly. I am working on google colab for this : https://colab.research.google.com/drive/1n5uv3d0dBv3uct6pzaB8bs6q0eMO2sID?usp=sharing Will really appreciate any help in debugging this and kindly let me know if any other information is needed to shed some clarity on this. A: So i figured this out. This had something to do with tensorflows version. For what I understood is that kerassurgeon was built over earlier version of tf and new version of tf has some overloaded len method which is causing some issue with this. So you can follow one of these steps : * *Downgrade to TF 1.14 (recommended) *Delete the len overloading in TensorFlow source (not recommended) I did the first step by as follows : MAKE SURE that you reset your colab envt before re-running the code to clear already installed dependencies of tf. Hoping this helps someone.
doc_23531259
As far as I understand it is impossible to update the filter rules in real time. So I try to stop the stream and then start it again. class MyStream(tweepy.StreamingClient): def disconnect(self): self.running=False print('stop stream) stream = MyStream(bearer_token=bearer_token, wait_on_rate_limit=True) stream.disconnect() But it doesn't work. Streaming continues to work. Can you please tell me how to reallocate what I have in mind? update I try to add a rule to the stream, then wait 10 seconds and add another one. But it doesn't work. Can you please tell me what the problem is and how to fix it? import telebot import tweepy import time bot = telebot.TeleBot() api_key = api_key_secret = bearer_token = access_token = access_token_secret = client = tweepy.Client(bearer_token, api_key, api_key_secret, access_token, access_token_secret) auth = tweepy.OAuth1UserHandler(api_key, api_key_secret, access_token, access_token_secret) api = tweepy.API(auth) class MyStream(tweepy.StreamingClient): def on_connect(self): print('Connected') def on_response(self, response): print(response) stream = MyStream(bearer_token=bearer_token, wait_on_rate_limit=True) rules = ['book', 'tree', 'word'] #create the stream for rule in rules: stream.add_rules(tweepy.StreamRule(rule)) print('Showing the rule') print(stream.get_rules().data) stream.filter(tweet_fields=["referenced_tweets"]) # this part of the code no longer works. print('sleep 10 sec') time.sleep(10) # this part not working too print('Final Streaming Rules:') print(stream.get_rules().data) A: In Twitter API v2 (Tweepy using the tweepy.client interface and StreamingClient object) the stream does not need to disconnect in order to update the rules, you do that by adding rules via StreamingClient.add_rules(). Docs: StreamingClient.add_rules() can be used to add rules before using StreamingClient.filter() to connect to and run a filtered stream: streaming_client.add_rules(tweepy.StreamRule("Tweepy")) streaming_client.filter() StreamingClient.get_rules() can be used to retrieve existing rules and StreamingClient.delete_rules() can be used to delete rules.
doc_23531260
Then I should write name either of file or dir and its status to db. Finally, I have to write to a new file, BUT if an item is a directory I have to find all files from this directory and write names of these files instead of the directory name. I see this as two step job when the first step is to read from the file and then write to db and parallelly save items as in-memory list. The second step is to read from this in-memory list and if this is directory substitute it with files names in a reader, then write to file. One thing I worried about is to hold thousands of objects between steps. Can anyone suggest more elegant solution? A: I don't think you need two steps. You can use a single step. * *Your reader would remain same *You expand directory to file using processor( or can be achieved in item reader as well) *Use delegated Item writer and write to database and new file. Here is sample Batch Configuration. @Configuration @EnableBatchProcessing public class BatchConfiguration { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; // tag::readerwriterprocessor[] @Bean public FlatFileItemReader<String> reader() { FlatFileItemReader<String> reader = new FlatFileItemReader<String>(); reader.setResource(new PathResource("MyFile")); reader.setLineMapper(new PassThroughLineMapper()); return reader; } @Bean public CompositeItemReader<String> cpReader(){ final CompositeItemReader<String> reader = new CompositeItemReader<>(); reader.setItemReader(reader()); return reader; } @Bean public CompositeItemWriter<String> cpWriter(){ final CompositeItemWriter<String> delegator = new CompositeItemWriter<>(); delegator.setDelegates(Arrays.asList(fileWriter(), dbWriter())); return cpWriter(); } @Bean public FlatFileItemWriter<String> fileWriter(){ return null; } @Bean public JdbcBatchItemWriter<String> dbWriter(){ return null; } @Bean public ItemWriter<String> writer() { final ItemWriter<String> writer = new ItemWriter<String>() { @Override public void write(List<? extends String> items) throws Exception { items.forEach(System.out::println); } }; return writer; } @Bean public Job kpJob() { return jobBuilderFactory.get("kpJob").incrementer(new RunIdIncrementer()).start(step1()).build(); } @Bean public Step step1() { return stepBuilderFactory.get("step1Child").<String, String>chunk(10).reader(cpReader()).writer(cpWriter()).stream(reader()).build(); } } The compositeItemReader public class CompositeItemReader implements ItemCountAware, ItemReader<String> { private ItemReader<String> itemReader; private int count = 1; private final LinkedList<String> files = new LinkedList<>(); public ItemReader<String> getItemReader() { return itemReader; } public void setItemReader(ItemReader<String> itemReader) { this.itemReader = itemReader; } @Override public String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException { return readFile(); } private String readFile() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException { if (files.size() == 0) { final String item = itemReader.read(); if (item == null) { return null; } else { Path path = Paths.get(item); if (Files.isDirectory(path)) { files.addAll((Collection<? extends String>) Files.walk(path, 1).map(Path::toString) .collect(Collectors.toList())); } else { files.add(path.toString()); } } } return files.poll(); } @Override public void setItemCount(int count) { this.count = count; } } Hope this basic info gets going. A: So, if someone curious, I came to next solution: created in database new table for storing records from file as-is, thus if a line contains filename store it, if a line contains dirname store it too. Then with help of this table, I can do joins to my target table to take a list of filenames from a specific directory. So, the first step is just read from file and store into two tables - new one and target one. And the second step is to read from the database with a query that returns only filenames and just write these records to file without any splitting/enrichment because this had been done by the query.
doc_23531261
auto I=V.array()>0; For now, I always use auto, but I would prefer considering the right type before compilation. I have tried VectorXd, VectorXi, but it does not work. Any ideas?
doc_23531262
I don't know how GitHub works but I do have an account (with nothing on there) and want to start using it sometime. I am assuming this is not the way it is meant to show up. Can someone please tell me why this is happening and how to fix it. (btw I am not logged in to GitHub on my computer in any way if that is how it works but I do have git installed) And while I am here, does anyone know a guide or a tutorial video on how git works. Thanks! A: It looks like you have "initialised" a git repository in ~/, and now it is tracking everything under that folder. To undo this goto ~ (aka HOME) and delete the folder called .git. There's the Git Book you can use to read up on Git.
doc_23531263
<p class="one">Number One</p> <script> $( "p.one" ).click(function() { $( this ).replaceWith( "<p class='two'>Number Two</p>"); }); </script> <script> $( "p.two" ).click(function() { $( this ).replaceWith( "<p class='three'>Number Three</p>"); }); </script> A: You have to delegate the p.two event since it was only created after DOM was loaded. $( "body" ).on('click', 'p.two', function() { $( this ).replaceWith( "<p class='three'>Number Three</p>"); }); Here is a working example on jsfiddle: https://jsfiddle.net/m7k453bv/ -- Reference according to jQuery: Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. https://learn.jquery.com/events/event-delegation/ A: Keep everything in a document.ready function: <script> $(document).ready(function(){ $(document).on('click', "p.one", function() { $( this ).replaceWith( "<p class='two'>Number Two</p>"); }); $( document ).on('click', "p.two", function() { $( this ).replaceWith( "<p class='three'>Number Three</p>"); }); }); </script>
doc_23531264
So in both cases, catgory_1 list and _category_2 list is server by content.php mysite.com/category_1/post/ mysite.com/category_2/post/ So, I need to redirect the user to a different page depending on catgory_? list, but without affecting the post inside that category. Resume : if you visit mysite.com/category_1/post/ or mysite.com/category_2/post/ ( you get the post) But : if you visit mysite.com/category_1/ (you get redirected to page 1) if you visit mysite.com/category_2/ (you get redirected to page 2) A: You can do something like this. First get your url path with $_SERVER["REQUEST_URI"]. Then get all after category_, and if all after category is number then redirect. $uri = $_SERVER["REQUEST_URI"]; $getCategory = substr($uri, strpos($uri, "category_")+9); $getCategory = str_replace("/", "", $getCategory); if (is_numeric($getCategory)) { header('Location: http://www.example.com/1'); } else{ header('Location: http://www.example.com/2'); }
doc_23531265
For example: redirecting www.example.com/index.html to www.example.com <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <rewrite> <rules> <rule name="CanonicalHostNameRule" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{HTTP_HOST}" pattern="^www\.example\.com$" negate="true" /> </conditions> <action type="Redirect" url="http://www.example.com/{R:1}" /> </rule> </rules> </rewrite> </system.webServer> </configuration> Edit: Here is my updated config file. But, its causing a 500 error, now. See CodingGorilla's answer below :) A: In order to get rid of the index.html after the redirect, drop the {R:1}. But then you will need to modify that rule so that it triggers only for /index.html requests and create a new rule that triggers on other pages that includes the {R:1} so that requests for example.com/mypage.html will still get redirected properly. Edit: Edit #2 And the final answer is! Based on our chat conversation, I think this is the final rule set: <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <rewrite> <rules> <rule name="CanonicalHostNameRule1" stopProcessing="true"> <match url="index\.htm(?:l)?" /> <conditions> <add input="{HTTP_HOST}" pattern="example\.com$" /> </conditions> <action type="Redirect" url="http://www.example.com/" /> </rule> <rule name="CanonicalHostNameRule2" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{HTTP_HOST}" pattern="^example\.com$" /> </conditions> <action type="Redirect" url="http://www.example.com/{R:1}" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
doc_23531266
Here is my steps: * *Firstly I create a STFDF object called stfdf: stfdf<-stConstruct(observation,space = list(values = 1:ncol(observation)),time = Node$Time,SpatialObj = loc,interval = T) *Then I compute the empirical variogram with the spatial-temporal data stfdf: var<-variogramST(values~1,data = stfdf,assumeRegular = T) plot(var,wireframe=T) here is the image of the empirical variogram: empirical variogram *Finally I need to fit the empirical model with the theoretic model,here I choose the seperable model: sepvgm<-vgmST("separable",space = vgm(0.02, "Exp", 8000, 0),time = vgm(0, "Exp", 2, 0.001),sill = 0.02) sepvgmST<-fit.stVariogram(var,sepvgm,fit.method=6,method="L-BFGS-B") Now,my question is how should I choose the parameters in the vgm function ? In the example above I set it to space=vgm(0.02,"Exp",8000,0) and time=vgm(0,"Exp",2,0.001) ,but it fails to fit the empirical variogram. Does anyone have idea on this? Thanks for a lot!
doc_23531267
I want a UICollectionViewCell to expand to the whole screen. In this cell, the subviews are placed with Autolayout in IB. I just want each subview to go to the new position. So I tried subview.frame = newSubview.frame in the animation block, but it doesn't work (because of Autolayout I think). I thought to delete the constraints while the animation is occuring, but it doesn't work. I also tried to make @IBOutlets of the constraints and to change constant property. Here's my code : let detailView = detailViewController.view let cellView = self.selectedCell container.addSubview(cellView!) let duration = self.transitionDuration(transitionContext) UIView.animateWithDuration(duration, delay: 0.0, options: .CurveEaseInOut, animations: { let newFrame = detailViewController.view.frame cellView!.frame = newFrame cellView!.imageView.frame = newFrame cellView!.labelTopConstraint.constant = 27 cellView!.labelRightConstraint.constant = 8 cellView!.layoutIfNeeded() } ... Actually, when the animation begins the labels snap to a position, then they move and at the end they are not at the right position... Any ideas ? Thanks A: Check out this repo, I think this is what you are looking for BCMagicTransition: https://github.com/boycechang/BCMagicTransition The issue with your code is that you aren't converting the frames of your subviews of your collection view cell that you want to animate to the coordinates of the container view controller of the transition, and same with the final frames for their positions. Even though you are using AutoLayout you can still manipulate views with their frames. To accomplish this, checkout this method (documentation): func convertRect(rect: CGRect, fromView view: UIView?) -> CGRect You also should look into animating snapshots of the views you wish to animate. Then just add the snapshots to the container view, and animate them to the converted final frames, then remove them when the animation is complete. Hope this helps !
doc_23531268
<style> @font-face { font-family: 'robotoslab'; src: url("file://#{Rails.root.join('app', 'tmp', 'fonts', 'RobotoSlab-Thin.ttf')}"); } </style> And I am calling it like this h5 { text-transform: uppercase; padding: 10px; letter-spacing: 0.2px; margin-top: 50px; font-family: 'robotoslab'; font-size: 10px; } All the other properties are getting applied except font-family. Also I am sure that font file is the path Rails.root.join('app', 'tmp', 'fonts', 'RobotoSlab-Thin.ttf') => #<Pathname:/home/vamsi/code/certificate_generator/app/tmp/fonts/RobotoSlab-Thin.ttf> I am having this in tmp folder because of pdfkit does not like assest pipeline A: You have to encapsulate it in <%= %>. <style> @font-face { font-family: 'robotoslab'; src: url("file://<%= Rails.root.join('app', 'tmp', 'fonts', 'RobotoSlab-Thin.ttf') %>"); } </style> But I'm not sure if this works since you load the font via the file:// protocol. You probably want to load it via http. If so simply remove file://.
doc_23531269
* *Click button, that's easy. *Perform AJAX request and create a database table. *Once the table is created, perform another series of AJAX requests and populate the table according to some parameters gotten from a series of select boxes. *"Animate" the whole thing using a progress bar. Surprisingly, everything is working fine (apart the last point), but I'm getting some troubles. The table gets created and populated but, for some reasons, the very last AJAX requests doesn't fire correctly, since it's not passing a parameter correctly. My ajax requests are ALL asyncronous, if I set them syncronous the whole thing will freeze, but all the requests are executed correctly, even the very last one. For instance, let's say that I don't want to use asyncronous requests in order to DON'T freeze the page and be able to show a progress bar. The questions are the following: * *Is it possible to call the same script twice? *Is there an efficient way to avoid ajax requests executing before other ajax requests? After reading a whole bunch of topics here in stackoverflow, I edited my code and tried to: * *use jQuery.AJAX prototype instead of jQuery.POST *Set everything asyncronously, in order to don't freeze the page and be able to handle a progress bar *perform the very next AJAX request into the "success" callback of the parent AJAX request. At this point, I still have another question: By stacking AJAX requests, is it actually TRUE that everything executed into the "success" callback will be executed AFTER the ajax requests has completed? This is what I'm performing: $.ajax({ type: "POST", url: '../libs/php libraries/agenda.php', data: {'action':'create>agenda', 'sqlname': createInfo}, processData: true, dataType: "json", timeout: 60000, async: true, success: function(res) { $('#popup_content').append(res.log); var dateList = new Array(); var dateObj = new Date(); var m = dateObj.getMonth(); var Y = dateObj.getFullYear(); for (var i = 1; i <= 31; i++) { dateList.push(i+"/"+m+"/"+Y); } for (var i = 0; i < dateList.length; i++) { var rs = false; $.ajax({ type: 'POST', url: '../libs/php libraries/agenda.php', data: {'action':'validate>date', 'date': dateList[i]}, processData: true, timeout: 60000, async: true, dataType: "json", success: function(x) { $('#popup_content').append(x.log); if (x.res == 'true') { rs = dateList[i]; } if (rs != false) { $.ajax({ type: 'POST', url: '../libs/php libraries/agenda.php', data: {'action':'create>day', 'date': rs, 'sqltable': createInfo}, processData: true, timeout: 60000, async: true, dataType: "json", success: function(newResult) { console.log(newResult.res); $('#popup_content').append(newResult.log); } }); } } }); } } }); the first AJAX request executes correctly, the second one does too, but in the third one (the one with data: {'action':'create>day', 'date': rs, 'sqltable': createInfo}) is getting fired but is missing the parameter rs defined above. Also, to be clearer, rs is a temporary variable I've defined when I was trying to make the requests outside the "success" callback and when using $.when and $.done, in this case the variable rs is useless, but It won't change anything. Again, as said above, the whole thing works using a syncronous request, but doesn't by using an asyncronous one. Moreover, I'm just going to use this script locally, so delays or every problematic related to delays caused by servers and client are not important. Is there any reason for the last request to don't work with an asyncronous request? if so is there a valuable solution for this case? I've also checked the topics about the queue, but it didn't solve my problem either. For some reasons, asyncronously, the last AJAX requests get just partially fired, since the variable rs is not getting passed correctly. A: One solution is to use queue() function. This way you can execute as many functions as you want var ajaxQueue = $({}); $.ajaxQueue = function(date, ajaxOpts) { // queue the method. a second call wont execute until this dequeues ajaxQueue.queue(function(next) { // for this example I serialize params, but you can save them in several variables // and concat into ajaxOpts.data var params = method_that_get_params_and_serialize_them(); ajaxOpts.data = params; ajaxOpts.complete = function() { next(); }; $.ajax(ajaxOpts); }); }; Then your functions have no need of shared vars, with the concurrency conflicts that it causes. It should be like this: $.ajax({ type: "POST", url: '../libs/php libraries/agenda.php', data: {'action':'create>agenda', 'sqlname': createInfo}, processData: true, dataType: "json", timeout: 60000, async: true, success: function(res) { $('#popup_content').append(res.log); var dateList = new Array(); var dateObj = new Date(); var m = dateObj.getMonth(); var Y = dateObj.getFullYear(); for (var i = 1; i <= 31; i++) { dateList.push(i+"/"+m+"/"+Y); } for (var i = 0; i < dateList.length; i++) { processDate(dateList[i]); } } }); function processDate(date){ $.ajaxQueue({ type: 'POST', url: '../libs/php libraries/agenda.php', data: {'action':'validate>date', 'date': date}, processData: true, timeout: 60000, async: true, dataType: "json", success: function(x) { $('#popup_content').append(x.log); if (x.res == 'true') { $.ajax({ type: 'POST', url: '../libs/php libraries/agenda.php', data: {'action':'create>day', 'date': date, 'sqltable': createInfo}, processData: true, timeout: 60000, async: true, dataType: "json", success: function(newResult) { console.log(newResult.res); $('#popup_content').append(newResult.log); } }); } } }); }; }
doc_23531270
The accepted answer got the select working with tokens and chunk size, but another problem manifested itself. My table looks like this in cqlsh: key | column1 | value ---------------+-----------------------+------- 85.166.4.140 | county_finnmark | 4 85.166.4.140 | county_id_20020 | 4 85.166.4.140 | municipality_alta | 2 85.166.4.140 | municipality_id_20441 | 2 93.89.124.241 | county_hedmark | 24 93.89.124.241 | county_id_20005 | 24 The primary key is a composite of key and column1. In CLI, the same data looks like this: get ip['85.166.4.140']; => (counter=county_finnmark, value=4) => (counter=county_id_20020, value=4) => (counter=municipality_alta, value=2) => (counter=municipality_id_20441, value=2) Returned 4 results. The problem When using cql with a limit of i.e. 100, the returned results may stop in the middle of a record, like this: key | column1 | value ---------------+-----------------------+------- 85.166.4.140 | county_finnmark | 4 85.166.4.140 | county_id_20020 | 4 leaving these to "rows" (columns) out: 85.166.4.140 | municipality_alta | 2 85.166.4.140 | municipality_id_20441 | 2 Now, when I use the token() function for the next page like, these two rows are skipped: select * from ip where token(key) > token('85.166.4.140') limit 10; Result: key | column1 | value ---------------+------------------------+------- 93.89.124.241 | county_hedmark | 24 93.89.124.241 | county_id_20005 | 24 95.169.53.204 | county_id_20006 | 2 95.169.53.204 | county_oppland | 2 So, no trace of the last two results from the previous IP address. Question How can I use token() for paging without skipping over cql rows? Something like: select * from ip where token(key) > token(key:column1) limit 10; A: Ok, so I used the info in this post to work out a solution: http://www.datastax.com/dev/blog/cql3-table-support-in-hadoop-pig-and-hive (section "CQL3 pagination"). First, I execute this cql: select * from ip limit 5000; From the last row in the resultset, I get the key (i.e. '85.166.4.140') and the value from column1 (i.e. 'county_id_20020'). Then I create a prepared statement evaluating to select * from ip where token(key) = token('85.166.4.140') and column1 > 'county_id_20020' ALLOW FILTERING; (I'm guessing it would work also without using the token() function, as the check is now for equal:) select * from ip where key = '85.166.4.140' and column1 > 'county_id_20020' ALLOW FILTERING; The resultset now contains the remaining X rows (columns) for this IP. The method then returns all the rows, and the next call to the method includes the last used key ('85.166.4.140'). With this key, I can execute the following select: select * from ip where token(key) > token('85.166.4.140') limit 5000; which gives me the next 5000 rows from (and including) the first IP after '85.166.4.140'. Now, no columns are lost in the paging. UPDATE Cassandra 2.0 introduced automatic paging, handled by the client. More info here: http://www.datastax.com/dev/blog/client-side-improvements-in-cassandra-2-0 (note that setFetchSize is optional and not necessary for paging to work)
doc_23531271
HttpParams httpParameters = new BasicHttpParams(); //Setup timeouts HttpConnectionParams.setConnectionTimeout(httpParameters, 15000); HttpConnectionParams.setSoTimeout(httpParameters, 15000); UsernamePasswordCredentials creds = new UsernamePasswordCredentials("myUserName", "myPassword"); ConnectionClient client = new ConnectionClient(creds); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpPost httppost = new HttpPost("http://10.0.2.2:8888/c5/login.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = client.execute(httppost); //HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity();
doc_23531272
col1 200 300 400 200 500 700 0 0 60 0 0 I'm trying to create a new column that is determined based on the current row value but taking into account the next few row values also. So e.g. if (row_col1(i) > 60) & ((row_col1(i+1)+row_col1(i+2)+row_col1(i+3)) > 100), write 'yes' in col2. col1 col2 200 yes 300 yes 400 yes 200 yes 500 yes 700 yes 0 no 0 no 60 no 0 no 0 no Any ideas on how to achieve this? A: You can handle this in a DataFrame using the .shift() method. Refer to this link for an example. Here's one approach which uses zip and list: l1 = df['col1'].tolist() l2 = [] for a,b,c,d in zip(l1,l1[1:],l1[2:],l1[3:]): if a>60 & (b+c+d)>100: l2 += ['yes'] else: l2 += ['no'] l2 += ['','',''] # cater for the last 3 entries. I've left it blank, you can decide whether to go for 'yes' or 'no' or 'NA' df['col2']= pd.Series(l2)
doc_23531273
I have created the first and the last Card views, but I am having trouble creating the cardviews in between, with all their features such as: the vertical divider, and the cut in the edges horizontal divider between the first and the second cardviews. (**red Scissors and the blue circle are png's) I am open to any other suggestions that may accomplish this commplicated "GridView" alike xml code. I added my xml code: <?xml version="1.0" encoding="utf-8" ?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:local="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:background="@color/screen_backround_color" android:orientation="vertical" android:layout_weight="100"> <LinearLayout android:layout_width="wrap_content" android:layout_height="0dp" android:background="@drawable/frame_border" android:orientation="vertical" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_marginTop="15dp" android:layout_marginBottom="15dp" android:layout_weight="90"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" card_view:cardCornerRadius="0dp" card_view:cardElevation="0dp" card_view:contentPadding="15dp" card_view:cardUseCompatPadding="true" android:id="@+id/MainFormFirstRow"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" android:gravity="center_vertical" android:orientation="horizontal"> <!--Model Name--> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center_vertical" android:orientation="vertical"> <TextView style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Model Name" android:textColor="#ec1c24" android:textSize="16dp" android:textStyle="bold" /> <TextView android:id="@+id/editTextModelName" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#666666" android:textSize="30dp" android:textStyle="bold"/> </LinearLayout> <!--Serial Number, IP Address, Version--> <TableLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1"> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="15dp" android:text="Model ID:" android:textColor="#ec1c24" android:textSize="14dp" android:textStyle="bold"/> <TextView android:id="@+id/editTextModelId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14dp" android:textColor="#666666"/> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="20dp" android:text="IP:" android:textColor="#ec1c24" android:textSize="14dp" android:textStyle="bold"/> <TextView android:id="@+id/editTextIPAddress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14dp" android:textColor="#666666"/> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="20dp" android:text="BS Version:" android:textColor="#ec1c24" android:textSize="14dp" android:textStyle="bold"/> <TextView android:id="@+id/editTextPLC" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14dp" android:textColor="#666666"/> </TableRow> </TableLayout> </LinearLayout> </android.support.v7.widget.CardView> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" card_view:cardCornerRadius="0dp" card_view:cardElevation="0dp" card_view:contentPadding="15dp" card_view:cardUseCompatPadding="true" android:id="@+id/MainFormSecondRow"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" android:gravity="center_horizontal" android:orientation="horizontal"> <!--IOMapping1--> <LinearLayout android:id="@+id/tableRowIOMapping1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center_horizontal" android:orientation="horizontal"> <TextView android:id="@+id/textViewIOMapping1" style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Temperature" android:textColor="#6d6e70" android:textSize="16dp" android:textStyle="bold" /> <TextView android:id="@+id/editTextIOMapping1" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#8bc53f" android:textSize="30dp" android:textStyle="bold" android:enabled="false"/> </LinearLayout> <!--IOMapping2--> <LinearLayout android:id="@+id/tableRowIOMapping2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center_horizontal" android:orientation="horizontal"> <TextView android:id="@+id/textViewIOMapping2" style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pressure" android:textColor="#6d6e70" android:textSize="16dp" android:textStyle="bold" /> <TextView android:id="@+id/editTextIOMapping2" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#8bc53f" android:textSize="30dp" android:textStyle="bold" android:enabled="false"/> </LinearLayout> </LinearLayout> </android.support.v7.widget.CardView> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" card_view:cardCornerRadius="0dp" card_view:cardElevation="0dp" card_view:contentPadding="15dp" card_view:cardUseCompatPadding="true" android:layout_marginBottom="1dp" android:id="@+id/MainFormThirdRow"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" android:gravity="center_horizontal" android:orientation="horizontal"> <!--Current Cycle Name--> <LinearLayout android:id="@+id/tableRowIOMapping1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center_horizontal" android:orientation="horizontal"> <TextView android:id="@+id/textViewCycleName" style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Current Cycle Name" android:textColor="#6d6e70" android:textSize="16dp" android:textStyle="bold" /> <LinearLayout android:id="@+id/editTextCycleName" style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="2" android:gravity="center_horizontal" android:orientation="horizontal"> <ImageView android:id="@+id/TwitterImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_weight="1" android:src="@drawable/icon"> </ImageView> <TextView android:id="@+id/editTextCycleName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ff0000" android:layout_weight="1" android:textSize="16dp" android:textStyle="bold" android:enabled="false"/> </LinearLayout> </LinearLayout> <!--System Status--> <LinearLayout android:id="@+id/tableRowIOMapping2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center_horizontal" android:orientation="horizontal"> <LinearLayout android:id="@+id/tableRowIOMapping2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="2" android:gravity="center_vertical" android:orientation="vertical"> <TextView android:id="@+id/textViewSystemStatus" style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_weight="1" android:layout_height="wrap_content" android:text="System Status" android:textColor="#6d6e70" android:textSize="16dp" android:textStyle="bold" /> <TextView android:id="@+id/editTextSystemStatus" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:textColor="#8bc53f" android:textSize="20dp" android:textStyle="bold" android:enabled="false"/> </LinearLayout> </LinearLayout> </LinearLayout> </android.support.v7.widget.CardView> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" card_view:cardCornerRadius="0dp" card_view:cardElevation="0dp" card_view:contentPadding="15dp" card_view:cardUseCompatPadding="true" android:layout_marginBottom="1dp" android:id="@+id/MainFormFirstRow"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" android:gravity="center_vertical" android:orientation="horizontal"> <!--Cycle Stage--> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="100" android:gravity="center_vertical" android:orientation="vertical"> <TextView android:id="@+id/textViewRefTemperature" style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="10" android:text="Cycle Stage" android:textColor="#ec1c24" android:textSize="16dp" android:textStyle="bold" /> <TextView android:id="@+id/editTextCycleStage" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_weight="20" android:layout_marginLeft="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#231f20" android:textSize="30dp" android:textStyle="bold"/> <ImageView android:id="@+id/FacebookImage" android:layout_weight="70" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:src="@drawable/icon"> </ImageView> </LinearLayout> <TableLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_vertical" android:orientation="vertical"> <!--Door State--> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center_vertical" android:orientation="vertical"> <TextView android:id="@+id/textViewChamberTemperature" style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Model Name" android:textColor="#ec1c24" android:textSize="16dp" android:textStyle="bold" /> <TextView android:id="@+id/editTextDoorState" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ff0000" android:textSize="20dp" android:textStyle="bold"/> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_vertical" android:orientation="vertical"> <!--Cycle Error--> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center_vertical" android:orientation="vertical"> <TextView android:id="@+id/textViewRefTemperature" style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Model Name" android:textColor="#6d6e70" android:textSize="16dp" android:textStyle="bold" /> <TextView android:id="@+id/editTextCycleError" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ff0000" android:textSize="30dp" android:textStyle="bold"/> </LinearLayout> </LinearLayout> </TableLayout> </LinearLayout> </android.support.v7.widget.CardView> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" card_view:cardCornerRadius="0dp" card_view:cardElevation="0dp" card_view:contentPadding="15dp" card_view:cardUseCompatPadding="true" android:layout_marginBottom="1dp" android:id="@+id/MainFormSixtRow"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="3" android:gravity="center_vertical" android:orientation="horizontal"> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center_vertical" android:orientation="vertical"> <TextView style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Ster. Temp:" android:textColor="#6d6e70" android:textSize="16dp" android:textStyle="bold" /> <TextView android:id="@+id/plc_ModelName" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#231f20" android:textSize="30dp" android:textStyle="bold"/> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center_vertical" android:orientation="vertical"> <TextView style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Ster. Time:" android:textColor="#ec1c24" android:textSize="16dp" android:textStyle="bold" /> <TextView android:id="@+id/plc_ModelName" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#666666" android:textSize="30dp" android:textStyle="bold"/> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center_vertical" android:orientation="vertical"> <TextView style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Dry Time:" android:textColor="#ec1c24" android:textSize="16dp" android:textStyle="bold" /> <TextView android:id="@+id/plc_ModelName" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#666666" android:textSize="30dp" android:textStyle="bold"/> </LinearLayout> </LinearLayout> </android.support.v7.widget.CardView> </LinearLayout> </LinearLayout> </LinearLayout> thank you for your help. A: After hard work of using CardView, android:layout_below and studying on Vertical and Horizontal Dividers, I got a solution. the following Cardview (it could be in a LinearLayout as well) contains the above mockup: <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="vertical" android:id="@+id/MainFormThirdRow" card_view:cardCornerRadius="0dp" card_view:cardElevation="0dp" card_view:contentPadding="10dp" card_view:cardBackgroundColor="@android:color/white" android:layout_below="@+id/Divider2"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" android:orientation="horizontal"> <!--Cycle Name--> <!--Cycle Stage--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" android:gravity="center_vertical" android:orientation="vertical"> <!--Cycle Name--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_vertical" android:orientation="vertical"> <TextView android:id="@+id/textViewCycleName" style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Current Cycle Name" android:textColor="#6d6e70" android:textSize="15dp"/> <LinearLayout android:id="@+id/tableRowIOMapping1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal" android:padding="5dp"> <!--Cycle Image--> <ImageView android:id="@+id/CycleImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="10dp"> </ImageView> <TextView android:id="@+id/editTextCycleName" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cycle Value" android:textColor="#ff0000" android:textSize="17dp" android:paddingTop="5dp" android:maxLines="2" android:ellipsize="end"/> </LinearLayout> </LinearLayout> <!--Divider--> <View android:layout_width="match_parent" android:background="@drawable/HalfHorizontalDivider" android:layout_height="1dp"/> <!--Cycle Stage--> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_vertical" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center_vertical" android:orientation="vertical"> <TextView android:id="@+id/textViewCycleStage" style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cycle Stage" android:textColor="#6d6e70" android:textSize="15dp" android:gravity="center_horizontal"/> <LinearLayout android:id="@+id/tableRowIOMapping1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical" android:paddingLeft="30dp"> <TextView android:id="@+id/editTextCycleStage" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cycle Stage Value" android:textColor="#231f20" android:textSize="15dp" android:textStyle="bold" android:ellipsize="end"/> <!--Cycle Image--> <WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/MyWebView" android:layout_width="100dp" android:layout_height="100dp"/> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> <!--Vertical Divider--> <View android:layout_width="1dp" android:layout_height="match_parent" android:background="@drawable/FullVerticalDivider"/> <!--System Status--> <!--Door State--> <!--Cycle Error--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical" android:layout_marginLeft="5dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="3" android:gravity="center_vertical" android:orientation="vertical"> <!--System Status--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_weight="1"> <TextView android:id="@+id/textViewSystemStatus" style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="System Status" android:textColor="#6d6e70" android:textSize="15dp"/> <TextView android:id="@+id/editTextSystemStatus" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="System Value" android:textColor="#ff0000" android:textSize="20dp" android:padding="5dp" android:maxLines="2" android:ellipsize="end"/> </LinearLayout> <!--Divider--> <View android:layout_width="match_parent" android:background="@drawable/HalfHorizontalDivider" android:layout_height="1dp"/> <!--Door State--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_weight="1"> <TextView android:id="@+id/textViewDoorState" style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Door State" android:textColor="#6d6e70" android:textSize="15dp" android:ellipsize="end" android:maxLines="1"/> <TextView android:id="@+id/editTextDoorState" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Door State Value" android:textColor="#ff0000" android:textSize="20dp" android:padding="5dp" android:ellipsize="end"/> </LinearLayout> <!--Divider--> <View android:layout_width="match_parent" android:background="@drawable/HalfHorizontalDivider" android:layout_height="1dp"/> <!--Cycle Error--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_weight="1"> <TextView android:id="@+id/textViewCycleError" style="@style/Base.TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#6d6e70" android:textSize="15dp"/> <TextView android:id="@+id/editTextCycleError" style="@style/Base.TextAppearance.AppCompat.Body1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ff0000" android:textSize="20dp" android:padding="5dp" android:ellipsize="end" android:maxLines="1"/> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> </android.support.v7.widget.CardView> Vertical Divider: <shape xmlns:android="http://schemas.android.com/apk/res/android" > <size android:width="1dp"/> <solid android:color="#989898"/> </shape> Horizontal Divider: <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item> <shape android:shape="rectangle" > <solid android:color="@android:color/white" /> </shape> </item> <item android:left="10dp" android:right="10dp"> <shape android:shape="rectangle" > <solid android:color="#989898"/> </shape> </item> </layer-list> I hope it will be of use.
doc_23531274
Given the following options class: public class Options { [Option('i', "int-option", DefaultValue = 10, HelpText = "Set the int")] public int IntOption { get; set; } [ParserState] public IParserState LastParserState { get; set; } [HelpOption] public string GetUsage() { return HelpText.AutoBuild(this, HelpText.DefaultParsingErrorsHandler(this, current)); } } And the following program: var options = new Options(); var parser = new Parser(settings => { settings.HelpWriter = Console.Error; settings.IgnoreUnknownArguments = false; }); if (parser.ParseArgumentsStrict(args, options)) { Console.WriteLine("Int value set: {0}", options.IntOption); } When calling the program with "MyProgram.exe --unknown" I just get the default usage information, but no mention of what error made the parsing fail. I'd like to get some kind of indication to the user what went wrong. A: Long story short: with the current implementation you can't get any info about the unknown options. The long story: If you put a brakepoint into your GetUsage method you will see that the LastParserState is not null but contains 0 element. LastParserState is basically filled from the ArgumentParser.PostParsingState but the the LongOptionParser (which in your case is involved because of the -- double dash) is not adding anything to the PostParsingState collection inside its parse method: Source from Github: var parts = argumentEnumerator.Current.Substring(2).Split(new[] { '=' }, 2); var option = map[parts[0]]; if (option == null) { return _ignoreUnkwnownArguments ? PresentParserState.MoveOnNextElement : PresentParserState.Failure; } So internally the parser doesn't store any info about what went wrong just record that fact.
doc_23531275
Are there any commands that can help me achieve this? I need to parse these commit messages and use them in another place. I have searched everywhere on the internet but I have found nothing useful. Basically, I want to save this in a text file Thank-you in advance...
doc_23531276
app.controller('MainCtrl',['$scope','Post','Pagination','Geolocation' ($scope, Post, Pagination, Geolocation) -> $scope.posts = [] Geolocation.getLocation().then (location) -> Pagination.paginate $scope, Post, 10, (postsRes) -> $scope.posts.push posts for posts in postsRes , params: {location: location} ]) app.factory 'Post', ($resource) -> $resource '/posts/:id.json', { id: '@id' } app.service "Geolocation", ['$q', '$window', ($q, $window) -> @getLocation = -> deferred = $q.defer() return deferred.resolve @loc if @loc if $window.navigator and $window.navigator.geolocation $window.navigator.geolocation.getCurrentPosition (position) -> @loc = position.coords deferred.resolve position.coords deferred.promise ] app.service 'Pagination', -> @paginate = ($scope, @resource, @maxElemPerPage=10, @onNewPage, @query={}) -> @page = 1 @canLoadNextPage = true $scope.loadPage = (promise) => return promise.resolve() unless @canLoadNextPage @load promise @load = (promise) => @canLoadNextPage = false q = angular.extend @query, page: @page @resource.query q, (resources) => @canLoadNextPage = true if resources.length is @maxElemPerPage @page++ @onNewPage resources if @onNewPage promise.resolve() if promise @load() @ A: Create a single service that wraps both, have it create it's own promise do the calls and declare the callbacks for both services and return the promise. Once the second service returns, resolve your promise.
doc_23531277
I've added a method which does the async call and handles the X-Ray based things, which works if I call it only once. However, if I call it again from the same thread, then X-Ray starts throwing .a.x.e.SegmentNotFoundException: Failed to begin subsegment named '30baae07-3a63-4036-807d-dcb0fdbac4eb': segment cannot be found. The async method: public static void runAsync(Runnable runnable) { CompletableFuture.runAsync(() -> { try { Subsegment subsegment = AWSXRay.beginSubsegment(UUID.randomUUID().toString()); runnable.run(); GLOBAL_RECORDER.endSubsegment(subsegment); } catch (Exception e) { log.error("Failed to run async method", e); } }); } And its usage: AsyncUtil.runAsync(() -> alerterService.refreshDataA(...)); // Here is a call of another unrelated method AsyncUtil.runAsync(() -> qualifierService.refreshDataB(...)); The source of this code is taken from https://github.com/aws/aws-xray-sdk-java/issues/227. I've looked through multiple sources about how to make this work and this seemed to be the correct way. Yet it does not work in my case. If I remove one of the async calls, it works as intended, so the issue must be that those 2 async methods are run in parallel alongside the main thread. Do you know how to make this work without running the two async methods in a series using just 1 thread? Please note that I'm very new to X-Ray and this is the first time I'm working with it, even though it's been in our project for a while. EDIT: After changing it to work the way as @lei-wang responded, the issue still persisted. public static void runAsync(Runnable runnable) { Entity traceEntity = Objects.requireNonNull(AWSXRay.getTraceEntity()); new Thread(() -> { try { AWSXRay.beginSegment("Async segment", traceEntity.getTraceId(), traceEntity.getId()); CompletableFuture .runAsync(runnable) .join(); AWSXRay.endSegment(); } catch (Exception e) { log.error("Failed to run async method", e); } }).start(); } It's probably good to note that in this case it can't find the segment named as the service which is used inside the runnable, eg. "Failed to begin subsegment named 'alerter-service': segment cannot be found." A: XRay Subsegment has to be under a living Segment, the issue because 2 runAsyn get started after the main thread finished, so Subsegments cannot find parent Segment. The workaround is to create a new thread to manage these 2 async methods, as the parent Segment of 2 Subsegments: public static CompletableFuture runAsync(Runnable runnable) { return CompletableFuture.runAsync(().....) } // from segment in main thread. traceid = AWSXRay.currentTraceId(); parentid = AWSXRay.currentEntityId(); new Thread() { void run() { AWSXRay.beginSegment("Async management", traceid, parentid); CompletableFuture future = AsyncUtil.runAsync(); future.join(); // wait for asyn complete AWSXRay.endSegment(); } } Or you can beginSegment instead of beginSubsegment in your async thread directly. A: My test code private static void testAsync() throws InterruptedException { AWSXRay.beginSegment("testAsync"); runAsyncUtil(() -> System.out.println("1")); runAsyncUtil(() -> System.out.println("2")); AWSXRay.endSegment(); } private static void runAsyncUtil(Runnable runnable) { CompletableFuture.runAsync(() -> { AWSXRay.beginSubsegment("sub"); runnable.run(); AWSXRay.endSubsegment(); }, SegmentContextExecutors.newSegmentContextExecutor()); }
doc_23531278
I want to change the color of each button depending on the button pressed (to see the active filter) This is my code: <ButtonGroup variant="contained" aria-label="contained primary button group" > <Button value={false} variant="contained" onClick={this.sortOnChange} color={this.state.relevanceColor}>Most Recent</Button> <Button value={true} variant="contained" onClick={this.sortOnChange} color={this.state.recentColor}>Most Relevant</Button> </ButtonGroup> This is the sortOnChange function: sortOnChange = (event) => { const value = event.currentTarget.value; console.log(value); let recent; let relevance; if(value){ recent= "secondary"; relevance="primary"; }else { recent="primary"; relevance="secondary"; } this.setState({relevanceColor: relevance, recentColor: recent}, function () { this.updateResults(); }); } The updateResults function does nothing for now. The state is: relevanceColor: "primary", recentColor: "secondary", For some reason the color is not changed at all. How can I make it so that when you click on one option, them both change color so the clicked button gets the "primary" color and the 'unclicked' button gets the "secondary" color. A: sortOnChange = (value) => { let recent; let relevance; if (value) { recent = "secondary"; relevance = "primary"; } else { recent = "primary"; relevance = "secondary"; } this.setState({ relevanceColor: relevance, recentColor: recent }, function() { this.updateResults(); }); }; <ButtonGroup variant="contained" aria-label="contained primary button group"> <Button variant="contained" onClick={() => this.sortOnChange(false)} color={this.state.relevanceColor} > Most Recent </Button> <Button variant="contained" onClick={() => this.sortOnChange(true)} color={this.state.recentColor} > Most Relevant </Button> </ButtonGroup>;
doc_23531279
<?php //if($_SERVER['REQUEST_METHOD']=='POST'){ //$username = $_POST['username']; $username = "Dave"; require_once('dbConnect.php'); $sql = "SELECT * FROM user WHERE username = '$username'"; $result = mysqli_query($con,$sql); $check = mysqli_fetch_array($result); if(isset($check)){ echo 'Logged in'; } else { echo 'Could not log in'; } //} ?> When I go to myserver.com/login.php, I see Logged in, because Dave is in my database. In my Android app, my Volley Log in button looks like this : private void userLogin() { username = editTextUsername.getText().toString().trim(); // password = editTextPassword.getText().toString().trim(); StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { if(response.trim().equals("Logged in")){ Toast.makeText(LoginActivity.this,"yahoo, you're in",Toast.LENGTH_LONG).show(); openProfile(); }else{ Toast.makeText(LoginActivity.this,"sorry, you're out",Toast.LENGTH_LONG).show(); // Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show(); } } }, etc... etc... But when I click my Log in button, my toast is always, sorry, you're out. Do you know why ? A: Because this: $check = mysqli_fetch_array($result); The function returns an array (success) or boolean false (failure). Either way, $check is ALWAYS going to be set, so isset($check) will always return true. Your logic should be if ($check === false) { which means there's no rows (or the query failed).
doc_23531280
with respect A: You will need to set up two Package Variables at design time to hold x and y. In the General Tab of the Execute SQL component, change the result to SingleRow and ensure the query returns 1 row with the parameter details you require. Go to the Result Set Tab and set the two Package Variable (x, y) to the columns returned from your query. Add two workflows, both from Execute SQL component, both On Success. For the first workflow (going to Task B), set the expression to @[User::x] == 1. For the second workflow (to Task C), set the expression to @[User::y] == 0. If you want the options to be mutually exclusive, you are going to have to include two clauses on each workflow (i.e. @[User::x] == 1 && @[User::y] !=0). You will have to work out all permutations and include them in the expression to avoid both workflows firing.
doc_23531281
paypal_base (Properties: version 5.6.65.1, Runtime Version: v1.1.4322) Questions: Q1. What is URL of latest download? Q2. I downloaded payflow_dotnet_setup_v4.33.zip and I'm reading "PayPal Payflow SDK for .NET Developer's Guide), BUT there is NO MENTION of any of the current calls I'm already using that look like this. Why? DoCaptureRequestType pp_request = new DoCaptureRequestType(); pp_request.AuthorizationID = authorizationId; return (DoCaptureResponseType)caller.Call("DoCapture", pp_request); Q3. Is this API deprecated in liu of REST API? I'm SO confused. Pete A: X.com was the home of the developer site for PayPal, but it is being migrated over to developer.paypal.com. Eventually everything you need for Payflow, PayPal, and etc to get started processing payments will be found on developer.paypal.com. You can find the most recent version of the PayPal SDK's here. The REST API's are newer API's which can be used as well, however they are still new and they are not supported for every country yet and not all of the features are available yet.
doc_23531282
SHKItem *item = [SHKItem text:@"sample tweet"]; [SHKTwitter shareItem:item]; I try to attach UIImage with tweet using SHKItem *item = [SHKItem image:[UIImage imageNamed:@"testImage.png"] title:@"posting test image"]; [SHKTwitter shareItem:item]; Although it posts successfully on twitter but instead of actual image shown within tweet it attaches a shorten URL. i.e. posting test image http://img.ly/sMx0 Please tell what i am doing wrong. Is there any other way to attach image within tweet. I want to give iOS compatibility 4.0 to 6.1 A: You can see from the source code that SHKTwitter always uploads images in tweets to img.ly. There is no option to do otherwise; it only uploads images directly to Twitter when setting the user's profile image. It's pretty much only Twitter's web interface that doesn't show an image on img.ly inline in the tweet, though. Most third-party clients will show the image inline the same as they do with images uploaded directly to Twitter. So, you'll have to choose one of three options: * *Live with img.ly. Depending on what you're uploading, this may be a better option; Twitter compresses every image uploaded with some harsh JPEG compression, whereas img.ly will leave PNGs as PNGs. *Write and submit a patch to Share Kit to use Twitter's own image uploading API (I assume they have one). *Switch to Apple's own Social framework. If you need to support iOS 5, you can use Apple's Twitter framework (Social includes Twitter but requires 6). Neither of Apple's frameworks is an option if you need to have this feature on iOS 4.
doc_23531283
* *I am running tests that I know pass on everyone else's machine, including our build server *Not using IIS Express is not an option, as then my build environment would be inconsistent with the team's. Furthermore, these tests were running just fine not a week ago, so this shouldn't be a problem. *I have uninstalled and reinstalled Visual Studio 2013.5 to no avail. *I have uninstalled IIS 10 Express and installed IIS 8.0 Express to no avail. (I couldn't find any download/installer for IIS 10 Express, but that was definitely what was installed on the machine before.) *I have uninstalled Visual Studio 2015 entirely, in case it was causing conflicts with the 2013 install. Also, no avail. *All of our machines are identical builds, so I know this isn't a hardware problem. *My machine is running Windows 8.1 x64. The project is a mixed ASPX/MVC web project running .NET 4.5.1 I am quickly running out of ideas short of reformatting my hard drive and wiping everything off of the face of the planet - which seems extreme, but if that's my only option, then so be it. Update Here are the errors as shown in the event viewer: ASP.NET 4.0.30319.0, 11:36:44 AM An unhandled exception occurred and the process was terminated. Application ID: /LM/W3SVC/1/ROOT Process ID: 6072 Exception: System.Threading.ThreadAbortException Message: Thread was being aborted. StackTrace: at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags) at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags) Application Error, 11:36:44 AM Faulting application name: iisexpress.exe, version: 8.5.9748.0, time stamp: 0x5384d451 Faulting module name: KERNELBASE.dll, version: 6.3.9600.17278, time stamp: 0x53eeb460 Exception code: 0xe0434352 Fault offset: 0x00012f71 Faulting process id: 0x17b8 Faulting application start time: 0x01d0d90283199962 Faulting application path: C:\Program Files (x86)\IIS Express\iisexpress.exe Faulting module path: C:\WINDOWS\SYSTEM32\KERNELBASE.dll Report Id: c3187027-44f5-11e5-82a2-a0481c829032 Faulting package full name: Faulting package-relative application ID: ASP.NET 4.0.30319.0, 11:36:48 AM An unhandled exception occurred and the process was terminated. Application ID: DefaultDomain Process ID: 6072 Exception: System.Threading.ThreadAbortException Message: Thread was being aborted. StackTrace: .NET Runtime, 11:36:48 AM Application: iisexpress.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.Threading.ThreadAbortException Stack: Application Error, 11:36:48 AM Faulting application name: iisexpress.exe, version: 8.5.9748.0, time stamp: 0x5384d451 Faulting module name: KERNELBASE.dll, version: 6.3.9600.17278, time stamp: 0x53eeb460 Exception code: 0xe0434352 Fault offset: 0x00012f71 Faulting process id: 0x17b8 Faulting application start time: 0x01d0d90283199962 Faulting application path: C:\Program Files (x86)\IIS Express\iisexpress.exe Faulting module path: C:\WINDOWS\SYSTEM32\KERNELBASE.dll Report Id: c5aab60e-44f5-11e5-82a2-a0481c829032 Faulting package full name: Faulting package-relative application ID: Update 2 When catching first-chance exceptions and attaching to the IIS Express process, I get the following exception: A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll Additional information: Thread was being aborted. This occurs when trying to call context.Response.Redirect("~/ErrorPages/AccessDenied.aspx", true); Other pages that redirect to this page can do so successfully. Update 3 Here are the first-chance exceptions when turning off "Just My Code" First System.Globalization.CultureNotFoundException occurred Message: A first chance exception of type 'System.Globalization.CultureNotFoundException' occurred in mscorlib.dll Additional information: Culture is not supported. Second System.Web.HttpException occurred _HResult=-2147024809 _message=Invalid file name for file monitoring: 'D:\Dev\Git\Qualtrax\Web\Content'. Common reasons for failure include: - The filename is not a valid Win32 file name. - The filename is not an absolute path. - The filename contains wildcard characters. - The file specified is a directory. - Access denied. HResult=-2147024809 IsTransient=false Message=Invalid file name for file monitoring: 'D:\Dev\Git\Qualtrax\Web\Content'. Common reasons for failure include: - The filename is not a valid Win32 file name. - The filename is not an absolute path. - The filename contains wildcard characters. - The file specified is a directory. - Access denied. Source=System.Web ErrorCode=-2147024809 WebEventCode=0 StackTrace: at System.Web.DirectoryMonitor.AddFileMonitor(String file) InnerException: Third System.Net.Sockets.SocketException occurred _HResult=-2147467259 _message=A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond HResult=-2147467259 IsTransient=false Message=A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Source=System ErrorCode=10060 NativeErrorCode=10060 StackTrace: at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) InnerException: Fourth System.IO.IOException occurred _HResult=-2146232800 _message=Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. HResult=-2146232800 IsTransient=false Message=Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. Source=System StackTrace: at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) InnerException: System.Net.Sockets.SocketException _HResult=-2147467259 _message=A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond HResult=-2147467259 IsTransient=false Message=A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Source=System ErrorCode=10060 NativeErrorCode=10060 StackTrace: at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) InnerException: Fifth (this one occurrs just before the crash): System.Threading.ThreadAbortException occurred _HResult=-2146233040 _message=Thread was being aborted. Hope some of those help. A: As it turns out, this answer to this other question solved my problem: https://stackoverflow.com/a/24880514/2689694 In short, because I had installed Visual Studio 2015, my IIS configuration had been modified to use a different pipeline mode. Those redirects in our code tended to pass in true as an overload, meaning that the response would end - which throws a thread aborted exception. The fix was that (as the link discusses) to use Context.ApplicationInstance.CompleteRequest() instead of the overload boolean. That means that it will now behave properly independent of the pipeline mode.
doc_23531284
#compdef kubens _arguments "1: :(- $(kubectl get namespaces -o=jsonpath='{range .items[*].metadata.name}{@}{"\n"}{end}'))" This provides completion to the kubens command. However if user provides a certain installation argument, the program is linked with kns name, so I am trying to provide completion for both of these commands uing the same #compdef. How do I achieve that? A: We could use the cmd=service form for the #compdef line: #compdef kubens kns=kubens Although we can use multiple names for the #compdef line, cmd=service forms could be used when the cmd behaves the same way as the service: #compdef name ... [ -{p|P} pattern ... [ -N name ... ] ] The file will be made autoloadable and the function defined in it will be called when completing names, each of which is either the name of a command whose arguments are to be completed ... ... Each name may also be of the form β€˜cmd=service’. When completing the command cmd, the function typically behaves as if the command (or special context) service was being completed instead. -- zshcompsys(1): Completion System, INITIALIZATION, Autoloaded files, #compdef
doc_23531285
'Prompt for chart type Dim chForm As ChartForm Set chForm = New ChartForm chForm.Show However at runtime the code fails at the line where I try to set chForm as a new instance of ChartForm, giving Runtime Error 91 for a missing/undefined object. But I know that ChartForm exists, do I need to do something else to enable a module to see UserForm modules? I assume the issue is something of this sort and not an issue with the initialization of the UserForm but just in case the code within the UserForm module is: Private Sub UserForm_Initialize() 'Get range of possible types Dim typeRng As Range Dim stopCell As Range Dim c As Range typeRng = chartSheet.Range(Cells(4, 1), Cells(Rows.Count, 1).End(xlUp)) For Each c In typeRng If InStr(c.Value, "stDev") Then GoTo endL Else TypeBox.AddItem c.Value 'Add regular fields to dropdown box End If Next endL: End Sub Private Sub CancelButton_Click() Unload Me End Sub Private Sub OKButton_Click() chartType = TypeBox.Value End Sub Which uses a global sheets variable to access a range of cells and populate the combobox in the form.
doc_23531286
My object model is stored in an .xcdatamodeld bundle, with versions 1.0 and 1.1 next to each other. Version 1.1 is set as the active version. Everything works fine when I use the default migration behavior and set NSInferMappingModelAutomaticallyOption to YES. My sqlite storage gets upgraded from the 1.0 version of the model, and everything is good except for, of course, the few transformations I need done. As an additional experimental step, I added a new Mapping Model to the core data model bundle, and have made no changes to what xcode generated. When I run my app (with an older version of the data store), I get the following * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Object's persistent store is not reachable from this NSManagedObjectContext's coordinator' What am I doing wrong? Here's my code for to get the managed object model and the persistent store coordinator. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (_persistentStoreCoordinator != nil) { return _persistentStoreCoordinator; } _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"gti_store.sqlite"]]; NSError *error; NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) { NSLog(@"Eror creating persistent store coodinator - %@", [error localizedDescription]); } return _persistentStoreCoordinator; } - (NSManagedObjectModel *)managedObjectModel { if(_managedObjectModel == nil) { _managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain]; NSDictionary *entities = [_managedObjectModel entitiesByName]; //add a sort descriptor to the 'Foo' fetched property so that it can have an ordering - you can't add these from the graphical core data modeler NSEntityDescription *entity = [entities objectForKey:@"Foo"]; NSFetchedPropertyDescription *fetchedProp = [[entity propertiesByName] objectForKey:@"orderedBar"]; NSSortDescriptor* sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"index" ascending:YES] autorelease]; NSArray* sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil]; [[fetchedProp fetchRequest] setSortDescriptors:sortDescriptors]; } return _managedObjectModel; } A: I haven't thought this out very carefully, it's just an observation as I was having the same problem, and I too have found very few references to this error on the web. In my case the problem was that I had setup one of my application's objects to observe NSManagedObjectContextObjectsDidChangeNotification like so [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(observeContextSave:) name:NSManagedObjectContextDidSaveNotification object:nil]; - (void) observeContextSave:(NSNotification*) notification { [[self managedObjectContext] mergeChangesFromContextDidSaveNotification:notification];} Once I moved this code so that is was executed after the migration, the error went away. Anyway. I'm sure your circumstances are different. But it may help to think about what observations you have setup on notifications from your managedObjectContext. Update: Having thought about this a bit more, I guess it happens because multiple persistent stores are created during migration, which means that NSManagedObjectContextDidSaveNotification will be sent from a context with a different persistent store to the context that is sent mergeChangesFromContextDidSaveNotification. A: First, turn off the automatic migration if you are having a mapping model, fair chance they are colliding. Once you have done that, confirm that the error is gone. A: I had similar issue when persistent store initialization was performed from secondary thread. After I forced initialization in primary thread the problem has gone. Weird. A: Seems you already got it fixed, but worth to mention. I had this error too, the reason was I had multiple MOCs being notified of mergeChangesFromContextDidSaveNotification while they had different persistent stores (or different schemas). They didn't know how to handle changes that didn't belong to their stores.
doc_23531287
Google Chrome has a fantastic feature under it's Print options to Save to PDF. I can view my HTML file and save it as a paged PDF document. I want to programatically, from my .Net app, use Google Chrome for it's PDF feature and automatically produce the PDF from the transformed XML? How can I do this with my .Net code? A: Sounds like overkill. I would write you a little viewer to view the result HTML (using Internet Explorer API, or WebKit). Then API to the PDFCreator COM library to convert it to a PDF with a click of a button... http://pdfcreator.svn.sourceforge.net/viewvc/pdfcreator/trunk/COM/Samples/Dot%20Net/VS2005/C%23/Sample1/Form1.cs?revision=1276&view=markup http://webkitdotnet.sourceforge.net/ Good luck!
doc_23531288
Thanks for the help :) A: Did you try looking in the documentation?
doc_23531289
I want to code this out Array ( [0] => 1 [duration] => 1 [1] => Singapore [ai_Name] => Singapore ) {"duration":"1","ai_Name":"Singapore"} but I am getting this instead Array ( [0] => 1 [duration] => 1 [1] => Singapore [ai_Name] => Singapore ) {"0":"1","duration":"1","1":"Singapore","ai_Name":"Singapore"} below is my code <?php require 'dbfunction.php'; $id = $_GET['staffid']; $con = getDBConnect(); if(!mysqli_connect_errno($con)){ $sqlQueryStr = "SELECT r.duration, a.ai_Name " . "FROM report r " . "JOIN academicinstitution a ON r.ai_Id = a.ai_Id " . "WHERE staff_Id = '$id' "; $result = mysqli_query($con,$sqlQueryStr); $row = mysqli_fetch_array($result); mysqli_close($con); } else { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } print_r($row); echo '<br>'; $json = json_encode($row); echo $json; ?> A: Try using GROUP BY More info here: https://dev.mysql.com/doc/refman/5.1/en/group-by-handling.html A: The problem is that you get a mixed array as result, an indexed and an associative array. Use mysqli_fetch_assoc() instead of mysqli_fetch_array(): $result = mysqli_query($con, $sqlQueryStr); $row = mysqli_fetch_assoc($result); var_dump($row); will return Array ( [duration] => 1 [ai_Name] => Singapore ) which will be parsed to {"duration":"1","ai_Name":"Singapore"}
doc_23531290
I used How to write custom ExpandableListAdapter for my ExpandableListView. As it stands at the moment i apply this t oa child convertView and it works fine on expand, but i cant figure out how it collapses. Animation fadeAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.slide_left_in); convertView.startAnimation(fadeAnimation ); Would anyone be able to help or perhaps there is a better solution for this? A: I wrote a nice implementation that extends an ExpandableListView here: https://github.com/idunnololz/AnimatedExpandableListView/ It uses the idea I explained here Android ExpandableListView using animation to do the animations. A: i do something similar with my ExpandableListView. I use custom child layouts inflated from xml. But this should not matter. You should override the onChildClick onGroupClick and maybe other listeners. In this listeners you can animate your stuff. And you can try to use animateLayoutChanges what was not working fine for me.
doc_23531291
A user is tied to a company. A company has a License. A license has 2 expiration dates. expirationBasic and expirationExtended. What I want: For 50 routes I want to check if the license of the company of the logged in user has an expirationExtended > now. For 50 routes I want to check if the license of the company of the logged in user has an expirationBasic > now. I am using symfony 3.4 A: This question is lacking details, like what you'd like the system to do when the check fails. There are at least two common ways to handle this. The "Symfonic" way would be to add an event filter. Create a new class that extends EventSubscriberInterface and drop it in your EventSubscriber directory / namespace. When the appropriate event is triggered your method can perform the checks and throw and AccessDeniedHttpException. Assuming your 50 routes go to multiple controllers, another solution is to write an abstract controller class which is set as the parent of your final controllers. This base class can then perform the check against the logged in user.
doc_23531292
A: Add a helper column in the source data that indicates whether the row is for the last day in the month. Quick search for "excel last day of quarter" uncovers this possible formula: =DATE(YEAR(A2),CEILING(MONTH(A2),3)+1,0). So if you put "Last day of Quarter" as a label in col X1, then the formula in X2 to return a true or false value could be =A2=DATE(YEAR(A2),CEILING(MONTH(A2),3)+1,0). Now construct a pivot table that uses the helper column X as a filter condition.
doc_23531293
Ξ»> Data.List.cycle [] *** Exception: Prelude.cycle: empty list I know that Haskells tries to use total functions (except for the fundamental functions head and tail) and I'm not entirely sure of why cycle is not one of them. In my mind, the cycle of the empty list is the empty list and I don't see problems with this. Why cycle for empty lists throws an error? EDIT: Based on the first answers, I think my idea is not completely clear: I don't want cycle [] to be a computation that never ends. On contrary, I think cycle [] should be the: cycle :: [a] -> [a] cycle [] = [] cycle xs = xs ++ cycle xs The [] is the cycle [] because all the operations do exactly what I except. For instance, take 3 [] is [] and thus take 3 (cycle []) could be []. What's the problem with this solution? A: cycle is actually defined as returning an infinite list for all input. If it attempted to do that naively with an empty input, it would sit in an infinite loop. The error condition is slightly more informative with the same denotational semantics. Edit: Since people don't seem to understand what I mean when I say that empty output is bad, consider this simple function: labelElements :: [a] -> [b] -> [(a, b)] labelElements labels elements = zip (cycle labels) elements It's nice and simple, with an obvious error condition when the list of labels is empty. If cycle returned an empty list on empty input, it'd make labelElements silently propogate that bug to its output. At the moment, it screams and yells that you messed up instead. One of these is far better than the other. A: The problem arises when it comes to accessing elements in the list. A self-defined cycle function operating on a non-empty list has no problems when being accessed but trying to get, for example, the first 3 elements of the cycled empty list results in an infinite loop: cycle' xs = xs ++ cycle' xs take 3 (cycle' [1,2]) -- returns [1,2,1] take 3 (cycle' []) -- still looping A: I do not have any special insight into the mind(s) of the people who implemented the cycle function. The prelude has the following to say about cycle: cycle ties a finite list into a circular one, or equivalently, the infinite repetition of the original list. It is the identity on infinite lists. Traditionally when you think of a circularly linked list, wiki entry you have: How would I express a circular empty list? A pointer going to itself? But even that does not fit. My best explanation is that circular lists are not normal lists. They are different beasts with different semantics. Just like head is really only full defined on non-empty empty list because there is no first element of an empty list, cycle is only fully defined on non-empty lists because there is no empty circular linked list. A: Note that as it is currently defined, it is consistent with tail. tail [] = error ... cycle is conceptually related to tail. When you cycle a list, that means that you can repeatedly look to its tail and never reach the "end" ([]), because it is a cycle. (See Davorak's image.) In other words, it is always safe to use tail on a cycle'd list, assuming, of course, that it was safe to use cycle on that list in the first place. I, for one, think it is a perfectly reasonable thing to define. tail [] = [] cycle [] = [] But you should redefine both cycle and tail for consistency. A: The intent of cycle as described in the documentation is: import Data.List.Nonempty import Data.Stream.Infinite cycle :: NonEmpty a -> Stream a The authors of the Prelude use a partial function for passing in an empty list, which is conceptually a type error, similar to head and tail. If you'd like a cycle that returns [] it's as easy as: myCycle :: [a] -> [a] myCycle xs = if null xs then xs else cycle xs See: semigroups for the definition of NonEmpty and streams for the definition of Stream and a total definition of cycle.
doc_23531294
Now I want to debug a server that is launched from the client (VSCode), so I added in the debug flags for the spawned JVM process: -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9999 Upon doing this suddenly, the server does not work any more, even though suspend = 0 and I confirmed the port is open and that no firewall malarkey is happening. I decided to run the command line manually, and I see that the first thing that a process does, after it receives the debug parameters is to output the following to stdout: Listening for transport dt_socket at address: 9999 (emitted without double quotes) I believe this is the reason that I cannot debug the language server, because outputting anything to stdout or stdin that is not part of the language server protocol spec forces the client to reject the server. My question therefore, in a roundabout fashion is to ask if it is possible to make internal JVM messages on stdout, stdin, stderr silent via another JVM parameter? A: Update: The answer appears to be ",quiet=y" as an additional parameter. -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9999,quiet=y Thank you to Christian Dietrich for providing the solution on the lsp4j github page.
doc_23531295
$(document).ready(function() { $("#myFormId").formValidate(); //other stuff }); JQuery.fn.formValidate = function() { var myForm = this; $(myForm).validate({ //validation code is here }); $("#exampleInputField").rules("add", { required: true, alphaNumeric: true, minlength: 5, maxlength: 15 }); jQuery.validator.addMethod( "alphaNumeric", function(value, element) { return this.optional(element) || /^[a-z0-9]+$/i.test(value); }, "Only alphanumeric characters are valid." ); } I declared my validation function outside of the document ready function, and I call formValidate() on the form when all of the elements are loaded. This code was able to run in IE and FF perfectly fine. Then, I added some functionality to the code for saving the form. For validations on saving, I don't want to have a 'required' field, but I still want to check if the input fields have valid inputs. I kept the validation function the same, only making the change in the $(document).ready() function, shown here: $(document).ready(function() { $("#myFormId").formValidate(); $("#saveButton").click(function() { $("#myFormId input").each(function() { $(this).rules('remove', 'required');}); //This removes the 'required' field from each input's rule set, but still keeps the other rules }); //other stuff }); After this change, my code does not work in IE anymore, but it works fine in FF. When I try to save in IE, I get a script error with the debugger turned on, saying SCRIPT438: Object doesn't support property or method 'rules' for $(this).rules('remove', 'required');});. I even tried to call $("#myForm").valid() in the console, and it says the form does not support the property or method 'valid' or 'validate'. It seems to me that the validation is not being called, or the validate library isn't getting loaded properly, but I did not make any changes to that. Does anyone know what is going on? Update: So, I also have it set up when a user clicks the submit button, I revert back to the original validations by just calling it again by using $("#myFormId").formValidate();. When they click the submit button, I get a warning again, but it appears that it is performing the validations as it is supposed to. So, to give a better idea, this is what it looks like: $(document).ready(function() { $("#myFormId").formValidate(); $("#saveButton").click(function() { $("#myFormId input").each(function() { $(this).rules('remove', 'required');}); //This removes the 'required' field from each input's rule set, but still keeps the other rules }); $("#submitButton").click(function() { $("#myFormId").formValidate(); //same as before, but debugger complains about //this specifically }); //other stuff }); Another Update: So whenever I call $("#myFormId").formValidate(); in the document.ready function, I'm not getting an error from IE. However, anytime I call it from the console, or inside another event, it says the form does not support it. Could calling it a second time cause errors?
doc_23531296
Is there way to delete all the version and the languages besides default language through Site core Rocks Query? Thanks A: You can delete the language item from the system/Languages and it will remove this language version from all the items automatically. A: You can remove this language from the system and it will take care this item, then publish the site - this will resolve this issue. If you still have any issue - Please remove this explicitly, Below is the sample code I have used this code to add version for all languages, May be this help to remove explicitly. var homeItemA = Sitecore.Context.Database.GetItem(Landings.HomeItem); var languageA = Sitecore.Globalization.Language.Parse("en-SG");//new language version var master = Sitecore.Configuration.Factory.GetDatabase("master"); var allItems = master.GetItem(homeItemA.Paths.FullPath).Axes.GetDescendants(); foreach (var blog in allItems) { Item ca = master.GetItem(blog.Paths.FullPath, languageA); using (new Sitecore.SecurityModel.SecurityDisabler()) { try { if (0 == ca.Versions.Count) { ca.Versions.AddVersion(); } } catch (Exception ex) { ca.Editing.CancelEdit(); } } } See my own blog for more details
doc_23531297
When i display a text of 10 characters it fits to it. But at times i will have to display more than 10 characters. So is there a way to shrink the the font size and make it to fit in my UILabel of length 100 ? UILabel *la = [UILabel alloc]initWithFrame(5,10,100,14)]; A: Just use the adjustsFontSizeToFitWidth property of UILabel [Reference]. la.adjustsFontSizeToFitWidth = YES; From the reference: Normally, the label text is drawn with the font you specify in the font property. If this property is set to YES, however, and the text in the text property exceeds the label’s bounding rectangle, the receiver starts reducing the font size until the string fits or the minimum font size is reached. This property is effective only when the numberOfLines property is set to 1. The default value for this property is NO. If you change it to YES, you should also set an appropriate minimum font size by modifying the minimumFontSize property.
doc_23531298
for (i in 9:ncol(Site1)) { print(qplot(Site1[,i],snowfree, data=Site1, geom_smooth(method = "loess", size = 1.5)) [i]) } It results in a long list of $<NA> NULL The function works outside of the loop, using simple x and y variables.
doc_23531299
How to hide the shortcut bar in iOS9 self.textfield.inputAssistantItem.leadingBarButtonGroups=@[]; self.textfield.inputAssistantItem.trailingBarButtonGroups=@[]; In my current viewController, there is only two textfield and in viewdidLoad the above code, thats it. But, don't know why its resulting in leaks, its a headache for me when interface has many textFields. From the above image we can see the leaks being generated on textfield beings editing. If I set it to nil , instead of empty array, still I get the leaks.