text
stringlengths
70
452k
dataset
stringclasses
2 values
Animate view from top to center of screen i am trying to move image view from top of screen to center or middle of the screen using translation animation i.e when activity is started image view is start moving from top of screen to middle or center of screen where top of image view space and bottom of image view space shows equal on screen exactly as we do like in relative layout use tag center In Parent true in xml file of layout. generally we find these kind of animation in facebook and whatsapp application they have used for images to translate or move image view animation.i have tried lots of SO question and answer also googling but not find proper solution. what i have done so far as following.Please help me to solve these issue.thanks. public class MainActivity extends AppCompatActivity { ImageView imageview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageview = (ImageView) findViewById(R.id.imagview); RelativeLayout root = (RelativeLayout) findViewById(R.id.rel); TranslateAnimation anim = new TranslateAnimation(0, 0, 0, 50); anim.setInterpolator((new AccelerateDecelerateInterpolator())); anim.setAnimationListener(new MyAnimationListener()); anim.setDuration(500); anim.setFillAfter(true); imageview.startAnimation(anim); } }); } Assuming you have a View which is position on top left corner of screen, we want to animate it to the centre of screen. Layout file: <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/root"> <View android:id="@+id/animated_view" android:layout_width="50dp" android:background="#6eed57" android:layout_height="50dp"/> </FrameLayout> In onCreate(): final View root = findViewById(R.id.root); final View animatedView = findViewById(R.id.animated_view); root.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { animatedView.animate() .translationX((root.getWidth() - animatedView.getWidth()) / 2) .translationY((root.getHeight() - animatedView.getHeight()) / 2) .setInterpolator(new AccelerateInterpolator()) .setDuration(500); } }); Result: How you do it, if the same need from Right Top to Center, Bottom both corners to Center You don't start an animation in onCreate() because the screen isn't completely visible for the user. You also don't need to get root view if your root view uses the entire area of the screen. boolean hasAnimationStarted; public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus && !hasAnimationStarted) { hasAnimationStarted=true; DisplayMetrics metrics = getResources().getDisplayMetrics(); ObjectAnimator translationY = ObjectAnimator.ofFloat(imageview, "y", metrics.heightPixels / 2 - imageview.getHeight() / 2); // metrics.heightPixels or root.getHeight() translationY.setDuration(500); translationY.start(); } } i have tried but image is not moving center of the screen it is move to bottom of the screen i.e some parts of image is showing and half part of image is out of screen at bottom i think something wrong in calculation help me brother. im sorry i fixed. use metrics.heightPixels / 2 instead of metrics.heightPixels still not working imageview is moving to top of screen. i have fixed using this line of code ObjectAnimator translationY = ObjectAnimator.ofFloat(imageview, "y", (relativeLayout.getHeight() - imageview.getHeight()) / 2 ); // metrics.heightPixels or root.getHeight() translationY.setDuration(500); translationY.start();
common-pile/stackexchange_filtered
how to initialize an array of std::vector? As we all know, it's normal to initialize an array of int like this: int intAry[] = {7, 8, 9}; So, I want to know, how can initialize an array of std::vector in the same way(just in the initial list): typedef std::vector<int> type; type vecAry[] = {vec1, vec2, vec3}; I know it's legal to write code as fllows, now my question how to initialize vecAry in one line of code: type vec1; type vec2; type vec3; type vecAry = {vec1, vec2, vec3}; And why would you need array of vector ? @0x499602D2, are you kidding me? you can't compile in C++. @Hitesh Vaghani, why ask my requirement? I want to implement design pattern in my code. Because vector of vectors is always there. in your post should be type vecAry[] = {vec1, vec2, vec3}; ? @HiteshVaghani: Why use a vector (with the overhead of memory allocation and an extra level of indirection) when an array will suffice? Especially in C++03, where vectors are more awkward to initialise. @MikeSeymour yeah you are right. In C++11, type vecAry[] {{},{},{}}; or if you want non-empty vectors type vecAry[] {{1,2,3},{4,5,6},{7,8,9}}; If you're stuck in the past, you can initialise it with empty vectors: type vecAry[] = {type(), type(), type()}; but you can't initialise it with arbitrary values without some kind of helper like those in the Boost Assignment library: type vecAry[] = {list_of(1)(2)(3), list_of(4)(5)(6), list_of(7)(8)(9)};
common-pile/stackexchange_filtered
Common resolution of singularities Suppose that $X$ and $Y$ are varieties over a field $K$ of characteristic $0$. If $X$ and $Y$ are birational, in the sense that there exist open dense $U\subset X$ and $V\subset Y$ which are isomorphic, can we then find a smooth variety $Z$ and maps $Z\rightarrow X$ and $Z\rightarrow Y$ which are resolutions of singularities? I think this should be a) true and b) well-known in the literature, but it seems like I cannot find a reference. Any help is much appreciated! Start with a birational map $f$ from $X$ to $Y$. Let $Z$ be the closure of $f$ in $X\times Y$. Take $W$ to be a resolution of $Z$. This has all the properties you require.
common-pile/stackexchange_filtered
Bulk rename file(s) using Powershell from csv\txt file As the title suggests I am trying to create a Powershell script to rename multiple files. The script refers to a csv file which contains a string in a csv file "column A". If the result is true then I would like to rename the file from "Column B". Ive managed to get my code to work based on a string but this is the next stage - can anyone help me please? Current Code: Get-ChildItem -Path C:\ -Recurse -ErrorAction SilentlyContinue | Where {($_.Name -like "*blah*")} | Rename-Item -NewName {[System.IO.Path]::GetFileNameWithoutExtension($_.fullname) + ".BackupFile"} Thanks as always! The following assumes that your CSV file contains the file names with extension - adjust as needed. Build a hashtable from the CSV whose entries are keyed by Column A values and each contain the corresponding Column B value. Filter the Get-ChildItem output with Where-Object to only process files whose name is present as a key in the hashtable. Note that switch -File is added to the Get-ChildItem call below, so as to process files only (not also directory objects). Rename each matching file to the value of the relevant hashtable entry. # Build a hashtable from the CSV that with old-name-new-name pairs. $ht = [ordered] @{} # Note: you can omit [ordered] in this case. Import-Csv file.csv | ForEach-Object { $ht[$_.'Column A'] = $_.'Column B' } Get-ChildItem -Path C:\ -File -Recurse -ErrorAction SilentlyContinue | Where-Object { $ht.Contains($_.Name) } | Rename-Item -NewName { $ht[$_.Name] } -WhatIf Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want. Note: As an alternative to filtering Get-ChildItem output with Where-Object after the fact, you could use the former's -Include parameter as follows: -Include $ht.Keys However, up to at least PowerShell 7.2.x, -Include is actually slower than a post-filtering solution - see this answer.
common-pile/stackexchange_filtered
Show a language is context-free I'm asked to show that the set of songs of the form ABA^R is context-free(where A^R is A reversed). I don't know how to show a language is context-free. We haven't studied specifically how to show that a language is context-free so it can't be too complicated. The only thing I can think of is making a context-free grammar for the language but I don't really know if that's sufficient to show that it is context-free or how I'd make a grammar for a set of songs. There is an answer here: http://stackoverflow.com/questions/3510109/how-can-i-determine-if-a-language-is-context-free-or-not Also note that creating context-free grammar is fine for showing a language is context free. You cannot use pumping lemma to show a language is context free. It can only be used to show it is not. There are non-context free languages which satisfy the pumping lemma. Are A and B set of strings or what? @NuriTasdemir Yeah I guess. This is all the information I have. Guess I'll try to make a grammar for it. Use push down automata. But what do you mean by A^R is A reverse. Can you be more specific It's important to know what A and B are in this formulation. If each is simply any string over a given alphabet (i.e., the same alphabet for both), then you don't need to construct a CFG for the language, you can just reason it out. (Hint: "any string" could be the empty string.) Assuming A and B are set of strings and they are Context Free, then there are context free grammars for language A and B, say G_A and G_B. You can obtain the context free grammar for language A^R from G_A, quite easily. Just reverse the right hand side of the grammar rules and voila you have the grammar for A^R. If the starting variable of G_A is S_A, G_B is S_B and G_A^R is S_A' then the final grammar will be the combination of these grammars (each variable of the three grammar should be named uniquely) with the new starting variable and the new rule stating S -> S_A S_B S_A' In deriving a sentence ("song") from your S, S_A' is not constrained to derive a phrase that is the reverse of what S_A derives, which I think is what the original question requires. @MichaelDyck S_A derives a string from A and S_A' derives a string from A^R. Those two string may not be the reverse of each others and that is intentional. That is what the OP asks. If those should be the reverse of each other (I take it you think this way) then question should be asked as L = {xyx^R| x \in A AND y \in B}
common-pile/stackexchange_filtered
In REST what is the effective approach to design pagination in nested resources? Let us imagine we have a domain structure as follows Ledger can have one or more logs, each logs has different types and ledger itself has a type. Office ----< Department ---< Ledger (name, type) ---- < Logs (message, time) We need to filter specific type of logs during a time range and return responses grouped by department. Request parameters (log_type, from_time, to_time) Possibly the response would look like Ledger_Statement Office_id, Department_id, Ledger : [List (Logs : [List]) ] We can assume that it is possible to load the relevant data by querying only the on logs table and load by page How can I map the pagination to the response I have mentioned above, What could be the design approach in such a case? The Link Relations Registry includes entries for first, previous, next, and last that can be used to indicate to clients which identifiers to use to navigate the pagination protocol. The URI spelling doesn't matter at all, but if can be convenient to encode into the identifier the parameters that the server will need to generate the correct page. If your "pages" of information are something like a timeline, then the Twitter timeline documentation may offer you insights into how you might prefer to organize the information and which parameters you need to acquire the desired page of data.
common-pile/stackexchange_filtered
Why does this type error keep occurring? I have an ocaml function in which I am pattern matching several cases. I keep getting a type error and I can't see how to deal with it. Any help would be appreciated. This is the error message I'm getting : "File "eval.ml", line 40, characters 18-35: Error: This expression has type Env.symEntry". Line 40 is the line with "let l = binding_of env x in" (* eval_expr: expr -> proc_state -> env -> store -> value *) (* eval_expr: expr -> proc_state -> env -> store -> int *) let rec eval_expr (expr:expr) (ps:proc_state) (env:environment) (store:store) : int = match expr with Add (e1, e2) -> let r1 = eval_expr e1 ps env store in let r2 = eval_expr e2 ps env store in r1 + r2 | Sub (e1, e2) -> let r1 = eval_expr e1 ps env store in let r2 = eval_expr e2 ps env store in r1 - r2 | Mul (e1, e2) -> let r1 = eval_expr e1 ps env store in let r2 = eval_expr e2 ps env store in r1 * r2 | Div (e1, e2) -> let r1 = eval_expr e1 ps env store in let r2 = eval_expr e2 ps env store in r1 / r2 | Neg (e1) -> let r1 = eval_expr e1 ps env store in r1 * -1 | IntConst i -> i (* - variable reads: handle the Id constructor from expr. use binding_of and value_at *) | Id(x) -> let l = binding_of env x in let i = value_at store l in i;; Here is the code for some of the functions and types I used : module IntMap = Map.Make(struct type t = int let compare = compare end);; type store = int IntMap.t;; let value_at store loc = IntMap.find loc store;; let insert_value store loc v = IntMap.add loc v store;; let enter_scope env scope = scope::env;; let exit_scope env = List.tl env;; let current_scope env = List.hd env;; type expr = (* Expressions in C-flat *) (* int operations *) Add of expr * expr | Sub of expr * expr | Mul of expr * expr | Div of expr * expr | Neg of expr (* constants/variables *) | Id of string | IntConst of int (* array/pointer operations *) | At of expr * expr | Deref of expr | AddressOf of expr (* function *) | Call of string * expr list (* pre- & post-increment *) | Pre of expr | Post of expr ;; let binding_of env name = let lookup name symTab = List.assoc name symTab in try lookup name (List.hd env) with Not_found -> lookup name (List.hd (List.tl env)) ;; You’re not showing enough of your definitions to see what’s happening on the line you mention. My guess is that binding_of_env doesn’t return a location, but value_at expects a location. Possibly you need to extract the location from the binding. I added in the code for "binding_of" please look at it. I’m looking, but there’s still not enough detail to see the type of a scope. If you just work through the types of the sub-expressions on line 40 you will almost certainly figure out the problem. As a side comment, this binding_of function doesn’t traverse the whole list. It only looks in the first two environments (it seems to me).
common-pile/stackexchange_filtered
Using ncurses for basic GUI on a process started inside an init script I have a custom written application that runs on a embedded setup (buildroot). My application has to run every time the target device boots up and so I wrote an init script to do this and it works fine. However, part of the application has a very basic 'GUI' written with ncurses. The problem I have is that it works fine when I log onto directly or over ssh, but when the binary starts through init, I am unable to access the functionality of the ncurses code. I presume that this is because the console I am logged into is not the same as the console that starts the binary. So my question is do applications/daemons have an associated console, and if so, is there any way to transfer it to another console? If not are there any other ways I could go about solving this problem? I was thinking perhaps enforcing an automated login and then getting the application to start through the login console so that when a monitor is attached to the device at least the GUI will be accessible. Or is there a better way? First, instead of using an init script, try running the application in the foreground at the end of rc.local. If that fails, you'll have to specify what init system you are using (sysV, systemd, upstart...), because I doubt you are going to find an easily portable solution. @goldilocks It is a busybox init system. Unfortunately there is no rc.local file. I do not need it to be portable at all. I will try the autologin approach for the time being and pray that a nicer solution is possible You can try to transfer the program with reptyr I'm no quite sure I've understood your problem. I assume that your application starts some kind of curses GUI and you want to log in remotely and the - somehow - connect to that GUI (but the application is already running). I suggest to use screen (http://www.gnu.org/software/screen/) to start the application on a detached 'screen' (actually a pseudo tty with a simple terminal emulator). Then after logging in, your user(s) can use 'screen -D -r' or variations thereof to attach to virtual screen. That would be what you called "to transfer it to another console" PS: Another way to do that "right" would possibly be to separate service (the part that is always running) and UI into 2 separate processes. Might be too much hassle, though, since it requires to invent some kind of IPC between those two processes. OK thanks for this. I was thinking about implementing a separate application for the GUI and using IPC as you suggest but that involves a large amount of work. If all else fails I will try that
common-pile/stackexchange_filtered
How to assign the radius value for the dynamically created circle in paper.js I want to draw a circle like in paint, if the mousedown means it takes the point and if dragging the mouse means the radius of the circle should be increased accordingly, can anyone help me on mousedown log the point where the mouse was clicked. On mouseup log the point where the mouse was up. The math becomes pretty simple to find the direct line between these 2 points - which is your circle radius thank u.. i understood @ Nicholas You can calculate the distance between the mouse downpoint and the current mouse position. Then use that distance as the radius of your circle. Here's some code that does just that: function onMouseDrag(event) { var trackingCircle = new Path.Circle({ position: event.downPoint, radius: event.downPoint.subtract(event.point).length, dashArray: [2, 2], strokeColor: 'red' }) trackingCircle.removeOn({ drag: true, down: true, up:true }) } function onMouseUp(event) { var circle = new Path.Circle({ position: event.downPoint, radius: event.downPoint.subtract(event.point).length, strokeColor: 'black' }) } and here's the actual Sketch, (click-and-drag on the canvas).
common-pile/stackexchange_filtered
QGIS 3.38.3-Grenoble Points to path drawing lines that are not part of the track I am working on a project for measuring the effort from our GPS tracks. The tracks were imported from .gpx files only with track_points. When I use the Points to path for some tracks the lines are not drawn correctly, I need the lines to be drawn only over the points. How can I easily remove the unnecessary line from the tracks, so I can measure the length correctly? I have already tried with Edit Geometry - Delete part/ Trim/extend feature with no success. The only solution that I've found is to delete or separate the tracks, but this does not work every time, and it is very time consuming. Is "Create closed paths" unticked? What variable in the table above tracks the order of points (e.g. the first point, second, etc.), other than the time? Yes "created closed paths" is unticked. Only in these fields there are available data: fid,track_fid,track_seg_,track_se_1,ele,time. In the other fields from attribute table the data is NULL: magvar,geoidheigh,name,cmt,desc,src,link1_href,link1_text,link1_type,link2_href,link2_text,link2_type,sym,type,fix,sat,hdop,vdop,pdop,ageofdgpsd,dgpsid
common-pile/stackexchange_filtered
Iterate through a table and then creating multiple rows after queries I have 2 separate sheets One called Roster Another called tasks What I need to do on a third sheet, is iterate over the Roster and for each row, look at the tasks table for a match Department AND Role. and create a new row containing a mix of data from both tables, this however can lead to needing multiple rows from a single row on Roster. The below is a sample of the output I am aiming for Could anyone advise how this can be achieved via formula ? Does this answer your question? Google spreadsheet "=QUERY" join() equivalent function? It does not seem to I'm afraid I had a very similair need a little while ago. Go check the below link out. There were two answers posted and both work perfectly. I've adapted the methods to do exactly what you are looking to do many times. Good luck, hope this helps. P.S Im not actually posting this as an answer. I cant respond to your original question so have just posted it this way. perform lookup on two arrays and add element from second array to first array Thanks, but I am looking for a formula based solution rather than script
common-pile/stackexchange_filtered
AttributeError: 'PosixPath' object has no attribute 'write' i am using the spectrographic library spectrographic library to generate audio file from an image, from the library documentation i execute this code: python spectrographic.py --image ./source.png --min_freq 10000 --max_freq 20000 --duration 10 --save sound.wav --play and i am able to hear the generated output audio file successfully, but after the audio finishes, i get this error in terminal: ** Traceback (most recent call last): File "spectrographic.py", line 457, in <module> run() File "spectrographic.py", line 453, in run main(sys.argv[1:]) File "spectrographic.py", line 447, in main sg.save(wav_file=args.save_file) File "spectrographic.py", line 173, in save wavio.write(wav_file, self.sound_array, self.SAMPLE_RATE) File "/home/mohamed/.local/lib/python3.8/site-packages/wavio.py", line 390, in write w.writeframes(wavdata) File "/usr/lib/python3.8/wave.py", line 438, in writeframes self.writeframesraw(data) File "/usr/lib/python3.8/wave.py", line 427, in writeframesraw self._ensure_header_written(len(data)) File "/usr/lib/python3.8/wave.py", line 468, in _ensure_header_written self._write_header(datasize) File "/usr/lib/python3.8/wave.py", line 472, in _write_header self._file.write(b'RIFF') AttributeError: 'PosixPath' object has no attribute 'write' Exception ignored in: <function Wave_write.__del__ at 0x7fd831e82820> Traceback (most recent call last): File "/usr/lib/python3.8/wave.py", line 327, in __del__ self.close() File "/usr/lib/python3.8/wave.py", line 445, in close self._ensure_header_written(0) File "/usr/lib/python3.8/wave.py", line 468, in _ensure_header_written self._write_header(datasize) File "/usr/lib/python3.8/wave.py", line 472, in _write_header self._file.write(b'RIFF') AttributeError: 'PosixPath' object has no attribute 'write' ** i am using python 3.8.10 on linux ubuntu. any help would be much appreciated. You should probably file a bug with them on their github page. ^yep, what he said i filed a bug in their repo's page, and i hoop they fix it soon, i really liked the easiness of using this library to output audio from images, isn't there any way we can get rid of the error above and save the output file successfully....i can hear the output playback....but no saving :(
common-pile/stackexchange_filtered
Mapping array of object values to Interface type in Typescript I have an array called dealers in a JSON document that contains several object as shown below. "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : "Audi Dealer", "country" : "France", "code" : "124" }, { "name" : "VW Dealer", "country" : "Germany", "code" : "125" } ] I also have an interface type as shown below and a variable of this interface type. interface IDealer extends IZone { dealerName: string; dealerCode: string; dealerCountry: string } var countryDealers IDealer; I'd like to iterate through the dealers array of objects and populate the countryDealers variable. How can I achieve this please? what countryDealers should have? @Sajeetharan countryDealers will have all the properties from the interface and respective data retrieved from dealers array i.e. name, code and country. have you tried with the .map() function of ES6 ? like: let myInterfacesArray = countryDealers.map(xx=>{ return <IDealer> { dealerName : xx.name, dealerCode : xx.code, dealerCountry : xx.country // and so on }; }); Hope it help you!! I could not use return <IInterface> { ... } in a tsx files because I started getting errors. You will have to use return { ... } as IInterface; instead
common-pile/stackexchange_filtered
Text is not even between two cells when inserting an image and text in the same cell, ITextSharp I have table with 3 columns and one row. In cell 1 I have a phrase and in cell 2, next to the phrase I have an Image and a text. I am able to combine the image and the text in a same cell but. The problem I have now is that the text in cell 1 is in a higher position than the text in cell 2 and I don't know why. And I need them to be even. this is the result: this is my code: private void btnCrear_Click(object sender, EventArgs e) { Document doc = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream((Application.StartupPath+"\\PSC.pdf"), FileMode.Create)); doc.AddTitle("Recibo de Pago de Derechos Laborales"); doc.AddCreator("Errol"); doc.Open(); /*Get Image and set size*/ iTextSharp.text.Image SC = iTextSharp.text.Image.GetInstance(Application.StartupPath+"\\SimboloColones.png"); SC.ScaleAbsolute(5, 8); PdfPTable table = new PdfPTable(3);/*3 columns*/ table.TotalWidth = 588; table.LockedWidth = true; /*Cell 1*/ PdfPCell cell = new PdfPCell(new Phrase("Preaviso")); cell.Colspan = 1; cell.HorizontalAlignment = 2; cell.BorderColor = BaseColor.BLACK; cell.BorderWidthBottom = 0; cell.BorderWidthTop = 0; cell.BorderWidthRight = 0; cell.BorderWidthLeft = 0; table.AddCell(cell); /*Cell 2*/ cell = new PdfPCell(); cell.Colspan = 1; cell.HorizontalAlignment = 0; cell.BorderColor = BaseColor.BLACK; /*Insert Image and text into the cell*/ Phrase pPreaviso = new Phrase(); pPreaviso.Add(new Chunk(SC, 0, 0)); pPreaviso.Add(new Chunk("Cant Pre")); cell.AddElement(pPreaviso); table.AddCell(cell); /*Cell 3*/ cell = new PdfPCell(new Phrase(" ")); cell.Colspan = 1; cell.HorizontalAlignment = 1; cell.BorderColor = BaseColor.BLACK; cell.BorderWidthBottom = 0; cell.BorderWidthTop = 0; cell.BorderWidthRight = 0; cell.BorderWidthLeft = 0; table.AddCell(cell); doc.Add(table); doc.Close(); writer.Close(); System.Diagnostics.Process.Start(Application.StartupPath+"\\PSC.pdf"); } I don't know what is wrong with the code. Thanks in advance You have one cell that uses text mode (new PdfPCell(new Phrase("Preaviso"))) and one cell that uses composite mode (cell.AddElement(pPreaviso)). You are mixing text mode and composite mode in the same table. Since text mode and composite mode deal differently with spacing, you shouldn't be surprised about the difference. Use composite mode for all cells. If you don't understand this comment, Google for text mode and composite mode. Better yet: if you just started using iText, throw away your iText 5 code, and start writing iText 7 code. @BrunoLowagie Thanks for answering, I am new to Itext and I did not know about the dfference between "Text mode" and "composite mode" and your answer was exactly what I needed. If you put your updated code in an answer, and add a screen shot of the result, I'll upvote your answer. Sure! And again, thank you very much @BrunoLowagie. OK, done! Glad to see that my comment helped you to fix the problem. Thanks to @BrunoLowagie I was able to come up with a solution. However, I also nedded the text alignment to be centered, therefore I ended up using Paragraph instead of Phrase for all the texts in the cells. This is the final result: And, this is the code that ended up working for me: private void btnCrear_Click(object sender, EventArgs e) { Document doc = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream((Application.StartupPath+"\\PSC.pdf"), FileMode.Create)); doc.AddTitle("Recibo de Pago de Derechos Laborales"); doc.AddCreator("Errol"); doc.Open(); /*Get Image and set size*/ iTextSharp.text.Image SC = iTextSharp.text.Image.GetInstance(Application.StartupPath+"\\SimboloColones.png"); SC.ScaleAbsolute(5, 8); PdfPTable table = new PdfPTable(3);/*3 columns*/ table.TotalWidth = 588; table.LockedWidth = true; /*Cell 1*/ Paragraph Preaviso = new Paragraph(); Preaviso.Add(new Chunk("Preaviso")); Preaviso.Alignment = 2; PdfPCell cell = new PdfPCell(); cell.Colspan = 1; cell.HorizontalAlignment = 2; cell.BorderColor = BaseColor.BLACK; cell.BorderWidthBottom = 0; cell.BorderWidthTop = 0; cell.BorderWidthRight = 0; cell.BorderWidthLeft = 0; cell.AddElement(Preaviso); table.AddCell(cell); /*Cell 2*/ Paragraph pPreaviso = new Paragraph(); SC.ScaleAbsolute(5, 8); pPreaviso.Add(new Chunk(SC, 0, 0)); pPreaviso.Add(new Chunk("Cant Pre")); pPreaviso.Alignment = 0; cell = new PdfPCell(); cell.Colspan = 1; cell.HorizontalAlignment = 0; cell.BorderColor = BaseColor.BLACK; cell.AddElement(pPreaviso); table.AddCell(cell); /*Cell 3*/ cell = new PdfPCell(new Phrase(" ")); cell.Colspan = 1; cell.HorizontalAlignment = 1; cell.BorderColor = BaseColor.BLACK; cell.BorderWidthBottom = 0; cell.BorderWidthTop = 0; cell.BorderWidthRight = 0; cell.BorderWidthLeft = 0; table.AddCell(cell); doc.Add(table); doc.Close(); writer.Close(); System.Diagnostics.Process.Start(Application.StartupPath+"\\PSC.pdf"); }
common-pile/stackexchange_filtered
How to forcibly close Process in c# after some period of time? I got following code System.Diagnostics.Process capp = new System.Diagnostics.Process(); capp.StartInfo.UseShellExecute = false; capp.StartInfo.RedirectStandardOutput = true; capp.StartInfo.RedirectStandardError = true; capp.EnableRaisingEvents = false; capp.StartInfo.FileName = "app.exe"; capp.StartInfo.Arguments = "-i -v -mj"; capp.Start(); consoleOutput = capp.StandardOutput.ReadToEnd() + capp.StandardError.ReadToEnd(); if (!capp.WaitForExit(10000)) capp.Kill(); and problem, if outside application works correctly it takes less than 10 seconds for it to complete its tasks. If it stop/hung for some reason despite of using if (!capp.WaitForExit(10000)) capp.Kill(); as suggested in some other topic, it keeps working. Above line seem not to work at all in my case, i guess it has to do with fact i read StandardOutput and StandardError. How to fix my code to make reading output and WaitForExit() to work aside? If you don't always read from both StandardOutput and StandardError the buffers can fill causing the process to block. You first try to read StandardOutput to the end. The process you run might be writing a lot of data to StandardError until it blocks and can't write more. Then this results in your application blocking as it doesn't even start reading from StandardError until the process closes its StandardOutput. This creates a deadlock and neither process will continue. I suggest you use the solution I've posted here. It uses asynchronous reads to read from both StandardOutput and StandardError, avoiding deadlocks.
common-pile/stackexchange_filtered
Ignoring "wrong name on certificate" type error in Java ssl connection I'm trying to set up a connection with an https url, but since it's still in testing, the url redirects to the test environment, causing a browser to prompt the user with a message saying roughly that the certificate is trusted, valid, but doesn't match the domainname, and if they want to continue. I'm having a hard time dealing with this in Java. All the answers I've found suggest using a TrustManager like this TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { return; } public void checkServerTrusted(X509Certificate[] certs, String authType) { return; } }}; sslContext.init(kmf.getKeyManagers(), trustAllCerts, new SecureRandom()); But this doesn't change anything. The authentication involves entering a password on reading the client certificate's private key, and this works identically and correctly both from a browser and my application, it's after this authentication that either the prompt pops up in the browser or the connection returns a 'bad_certificate' error in my application. Is there some other way to either ignore the domain validation entirely or make the same prompt appear? For clarity, my application doesn't cause the password prompt to appear because I programmed it in or anything, I think it just originates from windows detecting my application trying to access the certificate's private key, so I would assume that the second prompt would work in a similar fashion, but I haven't found any parameters to make that happen yet. Let me warn you that if you are doing this for testing your code then this is not the right thing to do as. Browsers often ignore the errors and prompt the user if he would like to contnue despite the problems. If he decides to continue then he owns the decision. In your java application, if you are using the JDK provided default SSLSocketFactory then the SSL sessionis only established if the SSL handshake succeeds. And this is for security reasons. If you need to have a funcationalty like your browsers; to proceed irrespective of the security issues then you need to have your own custom implementation. Or better dont use SSL at all. This is a valid warning. However, I've downvoted this for not being an answer: there are situations where Java code needs to connect to a legitimate HTTPS URL, where that Java code (like any good browser) tells the user that "name X in certificate does not match hostname Y in the URL", and where the user wants the connection made anyway. Is there some other way to either ignore the domain validation... Yes. See Java's HostnameVerifier interface: During handshaking, if the URL's hostname and the server's identification hostname mismatch, the verification mechanism can call back to implementers of this interface to determine if this connection should be allowed.
common-pile/stackexchange_filtered
Does a mod p mod q = a mod q mod p? How to prove/disprove that (a mod p) mod q = (a mod q)mod p ? Supposing $p < q$, we have 3 situations: $a{\space}{\epsilon}{\space}[0, p)$, obviously the statement is true for this case $a{\space}{\epsilon}{\space}[p, q)$ $a{\space}mod{\space}p{\space}mod{\space}q=(a-a/p)mod{\space}q=a{\space}mod{\space}q-a/p{\space}mod{\space}mod{\space}q=a-a/p$ and $a{\space}mod{\space}q{\space}mod{\space}p=a{\space}mod{\space}p=a-a/p$ and $a > q$ which reduces to first two situations. Taking these three situation I have found that the statement is true. I am missing something ? Your solution is pretty sloppy, and as usual, sloppiness leads to wrong results. Yes, if $a<p$, the equality holds, but it isn't enough to just say "obviously." Your solution for $p\leq a < q$ makes no sense. I have no idea what you were trying to prove. How exactly does $a>q$ reduce to the first two situations? You can't just say it does without proving it. Also: Try the values of $a=10, p=10, q=3$. A number theorist somewhere dies when people write things like let $p=10$. :) @Jake Well OP didn't specify if $p$ is prime. But even so, $a=p=3$ works just as well if $q=2$. I know, I know. I was just making a joke. :) +1 @Jake I thought so. In fact, I was sure with a $p$ value of $<0.05$ :). Oh wow. That just took it to a whole new level. I do not think talking about an element modulo $p$ and then modulo $q$ makes much sense because when we talk about $3\pmod 7$ we are simultaneously talking about all integers that leave a remainder of $3$ when divided by $7$. This includes numbers like $3,10,17$ etc. So if you want to talk about $3 \pmod 7 \pmod 2$, should this be $1$ because $3$ is $1\pmod 2$ or should this be $0$ because $10$ is $0\pmod 2$? It's pure chaos.
common-pile/stackexchange_filtered
Using magic to replicate modern technology In a fantasy world that operates with magic, can wizards and mages use their abilities to replicate modern technology? For example either a flashlight or a modern aircraft? How would they accomplish this? I don't have boundaries for the magic of this world yet i just wanna know if it can work Edit: what if a boeing 747 ends up on this fantasy world, would they have been able to mass produce more boeing's? why shouldn't magic work? magic is not bound to the laws of physics.. You just need a starting magic system that is self-consistent, and derive technologies from that. Like using D&D, a continual light spell at the bottom of a tube is a flashlight. Well, it is your world so you make the rules. For example, the Flintstones replicated modern technology with stone age tools and friendly domesticated dinosaurs. On the other hand, if magic is available then many modern tools would be utterly useless; who needs a washing machine when one can simply will the dirt away? @AlexP, ooh, ooh, I know! Because the washing machine is what "houses" the spell. Duh . Mages sell washing machines to folks that can't do magic. (Seriously, that exact question came up in a story I'm writing — note. Yes, a magic user could "simply will the dirt away"... but why bother, when they can just toss dirty clothes in a washing machine and not have to exert themselves? Mind, the washing machine does use magic instead of soap.) While I disagree with that specific example, the overall sentiment is correct. Two items that don't exist in my story, at least in households, are dishwashers and lawn mowers. To wash dishes, you just run some water over them, and they are pretty much instantly clean and sanitary, and as soon as you take away the water, dry. To cut grass, there is a stick you drag over your lawn (on wheels or runners) that cuts the grass where it touches the stick. Depending on how your magic works, there will surely be other examples! (Mine is metabolism-powered, which severely limits its power budget.) Unfortunatley the edit has not helped; rather than making it more focussed, you've just added a further question. Please review the part of the [help] relating to how to write an on-topic question and have a good think about how to focus your efforts to best effect here. This question is too open-ended if you're asking about a magic system that can replicate modern technology without giving any restrictions for the magic system. Magic systems are incredibly diverse. Yes, if you do it correctly. They'd likely use a combination of magics with effects similar to what you want. For example a cannon could be made through the use of explosion magic instead of gunpowder. A blowdrier could be made through a small electric spell, a simple resistance that heats up and wind magic (substitute the resistance with fire magic though and you might get something closer to a flamethrower). The main differences between you magic tools is that most physical and chemical reactions that allow them to work would be substituted by combinations of magic spells happening simultaneously to reach the desired effect. Cars and other vehicles could be simply modified golems (artificial beings) with wheel like structures for locomotion and internal space for the passengers, and a system similar to GPS could be achieved through the use of multiple flying golems communicating with the car golems, again using messaging spells, on which routes are available and how is the road. With soft magic systems very little is truly impossible. Regarding your aircrafts, you could make an intelligent golem with a plane shape and moving wing parts, grant it the ability to use wind magic as a means of propulsion and allow it to communicate to towers through message magic. If your golem is "programmed" to do the correct calculations and is built correctly you'll get your aircraft. Alternatively, you could use programmed magic crystals as board computers and controls; and use powerful wind magic for the propulsion system and to keep the chambers pressurized, along with glass (that's important for the pilots and passengers). That way you'd get something decently close. Finnaly, the Boeing. If they already didn't have some kind of magic parallel to the plane, they'd likely take a while to, but I think they'd manage. The main issue here is that, unless the plane is kept on good state and the magicians can observe it working properly, they'll basically need to go through an alternative version of the entire history of the planes to reach the knowledge necessary to replicate the Boeing and its capabilities. Summing it up: its magic, magic is the best way to justify things simply because, unless it has rules saying it can't do something, the answer to "Can magic do this? " will always be "yes". The real challenge here will come after you define your magic system and its rules, which is when it will gain limitations that could interfere with this machinery replication. The short answer is yes. How they would accomplish it is a whole other topic that could fill a thousand pages trying to go into specifics. The wonderful thing about introducing magic in a world that's your own creation is your ability to allow it to work however YOU want it to. Taking that into consideration, of course modern technology can be replicated. However, I don't understand what you mean when you ask how they would accomplish it. This should be based on the rules of the magic system that you create, which you can shape in any way that you wish. It seems like the magic of your world (is it your world?) is very undeveloped. You should start by creating its structure and seeing where modern technology fits within that structure. I will add that magic not bound by a system or rules establishes a very sloppy foundation. It's very lazy and can induce massive inconsistencies across the board. Not to mention plot holes in stories. Also, keep in mind that magic itself can be just a different form of technology. Magic usually makes things more effective, more purposeful, more dynamic, more convenient, more diverse and more productive. Does technology not do the same thing? Would these magic users even want to use something as "primitive" and "human" as modern technology? Would it be in their best interest? There's a lot of questions here, and your question is very broad and invokes a lot of would-be assumptions and head-scratching. If you can provide more detail, I'll be more than happy to provide a more definitive answer.
common-pile/stackexchange_filtered
Use TagHelper inside another TagHelper I have build a custom tag helper that dynamicaly build a form with input tags. Example foreach(var foo in foos) { htmlOutput += $"<input asp-for='{foo.FieldName}' />"; } then i want to model bind this, but my custom tag helper output the asp-for attribute instead of model bind it, probably because im trying to use a tag helper inside my custom tag helper. Any way to get around this? You can nest them as in this answer but I dont think you can add them from within the TagHelper Process method
common-pile/stackexchange_filtered
Why do i keep getting a run time error 6 overflow error message? So I'm trying to essentially filter my data set in a certain way. There may be a better way of doing this and I may be over complicating things, so if that's the case, feel free to chime in any ideas. So, essentially I'm filtering my data set. However based on that filter, I will only take some specific data based on a criteria. I will therefore be hiding the data that don't fit that criteria, which is shown here: If Sheet1.Cells(i, 11) = StandardW And Sheet1.Cells(i, 32) > Date1 Then Rows("i:i").Select Selection.EntireRow.Hidden = True I will then be copying the first column of my data set and pasting it elsewhere to use it afterwards. However, for some reason, I keep getting a "Run time error 6 overflow error message." Not sure why. Any ideas? As mentioned above, maybe there's a simpler way of arranging my data around that I haven't thought about. If that's the case, feel free to chip in. Thanks! Sub CopyingCodesCALG() Dim Standard As Date Dim i As Integer Dim lastrow As Long lastrow = ActiveSheet.Cells(Rows.count, "B").End(xlUp).Row Standard = Date - 3 StandardW = Date - 2 Date1 = Date - 1 'this utilizes Activesheets, may have to find a workaround for this depending on the data. Maybe add it to the MF and use thisworkbook? Rows("1:1").Select Selection.AutoFilter ActiveSheet.UsedRange.AutoFilter Field:=3, Criteria1:= _ "Livraison" ActiveSheet.UsedRange.AutoFilter Field:=11, Operator:= _ xlFilterValues, Criteria2:=Array(2, Standard, 2, StandardW) ActiveSheet.UsedRange.AutoFilter Field:=25, Criteria1:= _ "=Return to warehouse", Operator:=xlOr, Criteria2:="=" ActiveSheet.UsedRange.AutoFilter Field:=17, Criteria1:=Array( _ "Data received", "Data received - shipment not received", "Loaded", "Loading", _ "Optimized", "Received", "="), Operator:=xlFilterValues ActiveSheet.UsedRange.AutoFilter Field:=34, Criteria1:="=" ActiveSheet.UsedRange.AutoFilter Field:=2, Criteria1:= _ "INTLCM-CALG" i = 2 For i = 2 To lastrow If Sheet1.Cells(i, 11) = StandardW And Sheet1.Cells(i, 32) > Date1 Then Rows("i:i").Select Selection.EntireRow.Hidden = True End If Next i ActiveSheet.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 1).Select Range(Selection, Selection.End(xlDown)).Select Selection.Copy End Sub If use the advice in THIS POST you will shorten your code and probably fix the error. Your whole If inside the Loop can be replaced with: sheet1.Rows(i).Hidden = Sheet1.Cells(i, 11) = StandardW And Sheet1.Cells(i, 32) > Date1 @ScottCraner The OP's loop will keep any already hidden rows hidden. With your code they will be shown. @GSerg that is true. okay replace the two lines in the IF with Sheet1.Rows(i).Hidden = True @JoelBastien On which line do you get the error? It's good practice never to use Integer - Long is safer and there's no performance price to pay. What's Rows("i:i")? That's not a valid use of either the variable, or the row. I think you mean Rows(i & ":" & i).Select (or even just Rows(i).Select)? ...Also, it's best to avoid using .Select/.Activate The number of rows in a spreadsheet in modern Excel is enough to overflow an integer variable, which is one reason why the suggestion of @TimWilliams is so important. Your code probably has some other issues, but using Dim i As Long might fix the overflow problem. @GSerg Sorry should've mentioned. Here is where I get my error: For i = 2 To lastrow @BruceWayne , you're right It's meant to just be Rows(i).Select ... Thanks for pointing that out! @JoelBastien There can be 1048576 rows on a sheet. Integer is from -32768 to 32767.
common-pile/stackexchange_filtered
How to go through an array of url and parse it? I have an array of URL's and I want to go to every page to parse some information. I do: var numbers = ["1111", "2222", "3333"]; function parse(page){... } function set(page){ console.log(page); window.location = page; parse (page); } for (j=0,m = numbers.length; j<m; j++){ page="http://www.*****/*****/"+numbers[j]+"/*****/"; setInterval(set(page), 10000); } But it's not working because browser tries to download pages and at the end, only the last one will be displayed. Function "parse" does not parse pages. How to fix my code? setInterval will call your set function once every 10 seconds the way you have invoked it. The for loop will have ended before that time, and the page's value at that time will be: "http://www.*****/*****/3333/*****/"; So after 10 seconds you will only see that page displayed. Got it! Problem in for loop. There should be slowler than "set-parse". Is it possible to make a cycle slower? You can specify any time interval you like but it wouldn't be a stable solution because you can never predict how much time each iteration will take. A different solution is needed here Try use setTimeout combine with recursive call. const MAX=100; setPage(num){ parse() if(num<MAX) setTimeout(setPage(num+1), 10000); } Thank you for help! @ИльшатМурзурбеков, thank them by voting up their answer and marking it, or another, as the answer. It is due to Scopes and Closures in JS. The solution for the problem is to create IIFE(Immediately Invoked Function Expression) inside loop! for (var i=1; i<=5; i++) { page="http://www.*****/*****/"+numbers[j]+"/*****/"; (function(j){ setTimeout( set(page), 10000 ); })( i ); } If you have time, refer about Closures in JS! I'm just beginner.Thank you for help! When you use setInterval(), you just tells the browser to carry out set() function after 10 seconds, and because all the setInterval() are been called in a very short period of time in that for loop, they will carry out the task together as well, then set will be carried out thrice, first with "1111" then "2222" and "3333". It would seems like it only run the last one with "3333". I suggest you use setInterval() only once, while the page variable will be created with a counter. var counter=0 function count(){ page="http://www.*****/*****/"+numbers[counter]+"/*****/"; set(page); counter+=1; if(counter>=numbers.length){ counter=0; } } setInterval(count(), 10000); Is it normal, that chrome blocking my script "A parser-blocking, cross site script ...is invoked via document.write" Did you tried to use document.write in another script file? It has some security issues I guess. If it does not prevent your script from functioning, it's okay, but if it does, I guess you should put them in one file. It's interesting because I haven't "document.write" in my code. And Chrome does not allow to go to another page. I dont know where is problem now. Maybe in parse function. https://pastebin.com/Jd3WqSdN What do you mean when you write " you should put them in one file"? I put all my script into chrome console and wait for result What I meant is that you said the error was "...cross site script...", so I guessed that you used some script hosted elsewhere. Maybe you should download jquery and not using the cdn. It is wield though, because cdn does work on my site and many others.
common-pile/stackexchange_filtered
Create discrete colorbar I am trying to create a colormap from an image. This works fine using a continuous range but I'm trying to reduce the amount of colors by a discrete factor. I have tried to do this using 10 colors via the following code but all I get is red? import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np cim = plt.imread("https://i.stack.imgur.com/4q2Ev.png") cim = cim[cim.shape[0]//2, 8:740, :] cmap = mcolors.ListedColormap(cim) norm = mcolors.BoundaryNorm([0,1,2,3,4,5,6,7,8,9,10], cmap.N) X = np.random.rand(10,10) Y = np.random.rand(10,10) plt.contourf(X, Y, levels=100, cmap=cmap, norm = norm)# alpha = 0.8) plt.colorbar() Isn't the image data between 0 and 1? You will see a difference when you multiply data by 10. If you only want 10 colors in your colormap, you can create it with just those 10 colors: import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np cim = plt.imread("https://i.stack.imgur.com/4q2Ev.png") cim = cim[cim.shape[0]//2, 8:740, :] cim_10 = cim[cim.shape[0] // 9 * np.arange(10)] # array of 10 colors cmap = mcolors.ListedColormap(cim_10) print(cmap.N) # prints 10 X = np.random.rand(10,10) plt.contourf(X, cmap=cmap, levels=np.linspace(0, 1, 11)) plt.colorbar() plt.show()
common-pile/stackexchange_filtered
How to install NVIDIA GeForce 610M on Ubuntu 10.04 LTS root@wruslanAC-bismillah-rtai:~/Downloads/Linux-Drivers-ACER-4752G/xf86-video-intel-2.14.0# uname -a Linux wruslanAC-bismillah-rtai 2.6.32-122-rtai #rtai SMP Tue Jul 27 12:44:07 CDT 2010 i686 GNU/Linux root@wruslanAC-bismillah-rtai:~/Downloads/Linux-Drivers-ACER-4752G/xf86-video-intel-2.14.0# lspci 00:00.0 Host bridge: Intel Corporation Device 0104 (rev 09) 00:01.0 PCI bridge: Intel Corporation Sandy Bridge PCI Express Root Port (rev 09) 00:02.0 VGA compatible controller: Intel Corporation Device 0126 (rev 09) 00:16.0 Communication controller: Intel Corporation Cougar Point HECI Controller #1 (rev 04) ... ... root@wruslanAC-bismillah-rtai:~/Downloads/Linux-Drivers-ACER-4752G/xf86-video-intel-2.14.0# ./configure checking for XORG... no configure: error: Package requirements (xorg-server >= 1.6 xproto fontsproto ) were not met: No package 'xorg-server' found No package 'fontsproto' found .... .... root@wruslanAC-bismillah-rtai:~/Downloads/Linux-Drivers-ACER-4752G/xf86-video-intel-2.14.0# apt-get install xserver-xorg-video-intel Reading package lists... Done Building dependency tree Reading state information... Done xserver-xorg-video-intel is already the newest version. .... .... Thank you. WRY There has been a recent certified driver release, you may have to do a manual install: Linux x64 (AMD64/EM64T) Display Driver, Version: 304.51 Certified You may have to manually install, here is how I did it on an older legacy vid card, the code should be similar: Driver Installation Try installing nvidia-current and see if that fixes it. nvidia-current is the current version of the drivers as of Lucid (there's a newer version in precise if you want to upgrade, but that'll possibly break other things). The driver package in 10.04 is to old and does not support series 600 cards. In this particular case the Ubuntu X-Swat PPA might be actually of help since it provides current driver packages for 10.04.
common-pile/stackexchange_filtered
Confusion regarding mathematical notations in Greedy and Gumble attack paper The paper Greedy and Gumble attack defines the input space for the text clasifier in the following form, "We assume a model in the form of a conditional distribution, $p_m = (Y|X), X= x \in W^d$ where $W := ${$w_0,w_1,...w_m$} is a discrete space such as a dictionary of words or space of characters." This is the common way in which input to word based as well as character based CNNs are defined Now, in case of word based CNNs , I can think of the input to be having $d$ words each along the row, with each word ($w_i$) having an embedding of length $m$. Similarly , in case of character based CNNs, all I can think of is $d$ characters, each having embedding length $m$ (26?) . I am just wondering if my assumptions are correct and I would also want to clarify on the meaning of the symbol $:=$ while defining $W$. Does it simply mean that $W$ is a $m$ length vector? At least in many probability texts: $:=$ means “defined as” usually for introducing a new object/notation. So, in my case , $: = $ defines $W$ as a vector of length $m$ I suppose Yup, I'd say so too. Actually, at least in the texts I see this in (Probability with Martingales by D. Williams, for example), they explain the meaning and usage of $:=$ in the introduction, but a paper probably would assume familiarity. If you have any experience in computer programming, it is like the "assignment operator" (though the programming languages I'm familiar with use $=$ for assignment and $==$ for equality). Thanks for the clarification. :)
common-pile/stackexchange_filtered
Setting border-radius in a container whose transform-style: preserve-3d does not work I was reading a blog post as to CSS-3D. Somewhere it mentions the issue of setting the property transform-style: preserve-3d is not working as expected. He did not explain the reason, he just tried the other way to get around the issue. Could you explain why we can not set the property in question in the container? https://codepen.io/thebabydino/pen/ZppXbb/ The blog link I was reading: https://css-tricks.com/things-watch-working-css-3d/ This has nothing to do with either transform-style or 3D elements; the problem is that you're setting a border-radius on the parent of the element with the background, rather than the element itself. If you want to shrink a background, the target element (.face) needs a border-radius. Set the border-radius to face and it should work just fine. OR see the codepen $dim: 40vmin; body { overflow: hidden; margin: 0; height: 100vh; perspective: 20em; } div { position: absolute; width: $dim; height: $dim; } .face { border-radius: 50%; } .card { top: 50%; left: 50%; margin: -.5*$dim; border-radius: 50%; transform-style: preserve-3d; text-align: center; font: calc(1em + 10vmin)/#{$dim} trebuchet ms, verdana, arial, sans-serif; // shorthand doesn't work in Firefox :( // bug 1304014 font-size: calc(1em + 10vmin); line-height: $dim; font-family: trebuchet ms, verdana, arial, sans-serif; animation: rot 4s ease-in-out infinite; } @keyframes rot { 50% { transform: rotateY(.5turn); } 100% { transform: rotateY(1turn); } } .face { backface-visibility: hidden; background: #ee8c25; &:last-child { transform: rotateY(.5turn); background: #d14730; } } <div class='card'> <div class='face'>front</div> <div class='face'>back</div> </div>
common-pile/stackexchange_filtered
PostgreSQL Point in time recovery not working We have 2 PostgreSQL servers setup as master-slave. I want to test below scenario I took a base backup at master and then deleted a table and switched xlog file using command select pg_switch_xlog();. Then I stopped the master. Promoted slave as the master and deleted one more table and switched log file. Now I have restored this base backup and wal files of both servers on a new server and used recovery_target_time to test PITR. I am able to recover to a time when I haven't deleted any table or deleted 1 table from the old master. But I am not able to recover to a point in time when I deleted a table from the new master. Below is the log output for the same 2018-08-06 14:49:39.564 UTC [19772] LOG: starting point-in-time recovery to 2018-08-06 14:20:00+00 cp: cannot stat ‘/var/lib/pgsql/pg_log_archive/00000005.history’: No such file or directory 2018-08-06 14:49:39.579 UTC [19772] LOG: restored log file "000000050000000200000046" from archive 2018-08-06 14:49:39.630 UTC [19772] LOG: redo starts at 2/46000028 2018-08-06 14:49:39.635 UTC [19772] LOG: consistent recovery state reached at 2/460ABCE8 2018-08-06 14:49:39.636 UTC [19770] LOG: database system is ready to accept read only connections 2018-08-06 14:49:39.648 UTC [19772] LOG: restored log file "000000050000000200000047" from archive 2018-08-06 14:49:39.732 UTC [19772] LOG: restored log file "000000050000000200000048" from archive cp: cannot stat ‘/var/lib/pgsql/pg_log_archive/000000050000000200000049’: No such file or directory 2018-08-06 14:49:39.780 UTC [19772] LOG: redo done at 2/48003410 2018-08-06 14:49:39.780 UTC [19772] LOG: last completed transaction was at log time 2018-08-06 13:27:00.442816+00 2018-08-06 14:49:39.796 UTC [19772] LOG: restored log file "000000050000000200000048" from archive 2018-08-06 14:49:39.843 UTC [19772] LOG: restored log file "00000006.history" from archive cp: cannot stat ‘/var/lib/pgsql/pg_log_archive/00000007.history’: No such file or directory 2018-08-06 14:49:39.845 UTC [19772] LOG: selected new timeline ID: 7 cp: cannot stat ‘/var/lib/pgsql/pg_log_archive/00000005.history’: No such file or directory 2018-08-06 14:49:39.903 UTC [19772] LOG: archive recovery complete 2018-08-06 14:49:40.006 UTC [19772] LOG: MultiXact member wraparound protections are now enabled 2018-08-06 14:49:40.008 UTC [19770] LOG: database system is ready to accept connections 2018-08-06 14:49:40.009 UTC [19786] LOG: autovacuum launcher started Below is the content of the recovery.conf file: restore_command = 'cp /var/lib/pgsql/pg_log_archive/%f %p' recovery_target_time = '2018-08-06 14:20:00.0' recovery_target_inclusive = 'true' recovery_target_action = 'promote' What am I doing wrong here? Recovery does not proceed to timeline 6 because you didn't add recovery_target_timeline = 'latest' to recovery.conf. As the documentation says: The default is to recover along the same timeline that was current when the base backup was taken. As of now i am using restore_command,recovery_target_time, recovery_target_inclusive, recovery_target_action in recovery.conf. Now i am adding recovery_target_timeline. is it perfect now for the point in time recovery? I should say so. Could you please edit your question yourself to add the correct information?
common-pile/stackexchange_filtered
Power Automate HTTP action with internal server error failing to route the flow to the "Run after failed" action In Power Automate I have purposefully given a wrong password for the HTTP action, and I have configured a parallel branch which is configured to run if the HTTP action is failed/skipped/timed out. The retry policy has changed from "Default" to "None". In this configuration, I'm getting an internal server error, but the flow is not routing to the "Run after failed action".
common-pile/stackexchange_filtered
Fastest way to write data into the database My usecase is such.. I have a redshift cluster where i upload data into (Basically, i use pandas to just replace the data everyday).The frequency of the upload is every hour and the number of records are close to 35k.(They keep increasing everyday) Now, i wanted to know the quickest way to write the data into the cluster. Do i manually delete the existing data by using a delete query and then write data to redshift by using "dataframe.to_sql" ? Do i just let the "dataframe.to_sql" function do the job automatically by adding "if_exists = replace" option? Which is the quickest way to deal with data with huge number of records? Apparently sqlalchemy-redshift uses psycopg2 so if you search for similar questions regarding PostgreSQL you should find some examples that might be helpful. For example, at the very least the method="multi" option of pandas' to_sql method might help speed up the upload. As for deleting the data vs. dropping and re-creating the table via if_exists="replace", the former will likely be faster, especially if you can TRUNCATE the table instead of just deleting all the rows. Appreciate the response. Thanks a lot
common-pile/stackexchange_filtered
How to disable Spring autowiring for a certain bean? There are some class in jar (external library), that uses Spring internally. So library class has structure like a: @Component public class TestBean { @Autowired private TestDependency dependency; ... } And library provides API for constructing objects: public class Library { public static TestBean createBean() { ApplicationContext context = new AnnotationConfigApplicationContext(springConfigs); return context.getBean(TestBean); } } In my application, I have config: @Configuration public class TestConfig { @Bean public TestBean bean() { return Library.createBean(); } } It's throw en exception: Field dependency in TestBean required a bean of type TestDependency that could not be found.. But Spring should not trying to inject something, because bean is already configured. Can i disable Spring autowiring for a certain bean? How do you know bean is already configured? Since Library.createBean() is creating your object, why have you put @Autowired above TestDependency It's not me. It's a library source code. @randominstanceOfLivingThing, because Library.createBean use Spring internally. Might it be that TestDependency is not found in the component-scan classpath? IMO - problem is spring context created by TestConfig and Library, both are different. Also if you wanna load third party components into your system, best way is to configure it xml files instead of loading using component-scan. @asg, exactly!! Yep... a simple configuration seems to be still discussed https://github.com/spring-projects/spring-framework/issues/13043 Based on @Juan's answer, created a helper to wrap a bean not to be autowired: public static <T> FactoryBean<T> preventAutowire(T bean) { return new FactoryBean<T>() { public T getObject() throws Exception { return bean; } public Class<?> getObjectType() { return bean.getClass(); } public boolean isSingleton() { return true; } }; } ... @Bean static FactoryBean<MyBean> myBean() { return preventAutowire(new MyBean()); } The trick works. But note that the bean won't be wrapped by a proxy, i.e. to enable effect of @Validated or @Transactional This worked for me: import org.springframework.beans.factory.FactoryBean; ... @Configuration public class TestConfig { @Bean public FactoryBean<TestBean> bean() { TestBean bean = Library.createBean(); return new FactoryBean<TestBean>() { @Override public TestBean getObject() throws Exception { return bean; } @Override public Class<?> getObjectType() { return TestBean.class; } @Override public boolean isSingleton() { return true; } }; } } Not exactly but you can add required=false (@Autowired(required=false)) in your autowired annotation. But be careful that might get you NullPointer exception I can't. TestBean it's a class from a library source code. I am afraid for that you have to go by XML approach in that create beand for TestDependency and mark it autowire-candidate=false then it won't consider that for autowiring If I mark @Autowired(require = false) then will it always be null or will it try to autowire it and if it fails just continue? @jDub9:check asg's comment IMO - problem is spring context created by TestConfig and Library, both are different. Also if you wanna load third party components into your system, best way is to configure it xml files instead of loading using component-scan. u need to import in ur scan package xml file of ur library It seems like it's impossible to disable autowiring for a specific bean. So there is some workaround. We can make wrapper for a target bean and use it instead of original bean: public class TestBeanWrapper { private final TestBean bean; public TestBeanWrapper(TestBean bean) { this.bean = bean; } public TestBean bean() { return bean; } } @Configuration public class TestConfig { @Bean public TestBeanWrapper bean() { return new TestBeanWrapper(Library.createBean()); } } @RestController public class TestController { @Autowired private TestBeanWrapper bean; ... }
common-pile/stackexchange_filtered
Word for small chat about the speakers well being Is there a word or expression for a small chat that is about how people are? For having a bit of context, two characters, who meet up almost on a daily basis, ask each other how they are, before talking about more important subjects. I tried to search for a definite answer, but I haven't found anything suitable. As far as I know, small talk might be used, but that includes more subjects, like weather, work and what not. The other one could be stating that they simply had a chat, but that could be again about almost any subject. Catching up would be the most appropriate one I could think of, but that for me seems as if there should me way more time between the two talking to each other than just a few days. For me catching up has always been associated with long time no see type of conversations. The sentence I want the word to use in is: After a small chat about their well-being and James’s shopping list they made their way to the supermarket. I don’t think there’s one specific to well-being. You didn’t ask, but I doubt there’s one specific to shopping lists either. :) Thanks for your answer. You might be right. But just to clarify, I am not looking for a synonym for well being but for a word or expression for chatting about how the persons involved in the conversation are. They exchanged pleasantries I think the word you're looking for is pleasantries: [Merriam-Webster] 3 : a polite social remark // exchanged pleasantries There is also gossip, but it's something more intentional and focused than just chatting about the weather or traffic. So: After exchanging pleasantries about their well-being and James’s shopping list they made their way to the supermarket. For me, you have almost said it yourself: "small talk". This is conversation between people which is will never offend; "How are you?", "Did you find us OK?", "How was the traffic?". It often precedes a meeting or even something like a Doctor's appointment, or can be the entire conversation between people who are forced together, maybe in the Doctor's waiting room.
common-pile/stackexchange_filtered
Checking if reducing iterator points to a valid element I need to know if I can reduce the iterator and have a valid object. The below errors out because I reduce the iterator by 1 which doesn't exist. How can I know that so I don't get the error? ticks.push_front(Tick(Vec3(0, 0, 5), 0)); ticks.push_front(Tick(Vec3(0, 0, 8), 100)); ticks.push_front(Tick(Vec3(0, 0, 10), 200)); bool found = false; list<Tick, allocator<Tick>>::iterator iter; for (iter = ticks.begin(); iter != ticks.end(); ++iter) { Tick t = (*iter); if (214>= t.timestamp) { prior = t; if (--iter != ticks.end()) { next = (*--iter); found = true; break; } } } I'm trying to find the entries directly "above" and directly "below" the value 214 in the list. If only 1 exists then I don't care. I need above and below to exist. if (200 >= t.timestamp) Aaargh, my eyes! (I know, not a constructive comment...) ?? What did I do wrong? Why not t.timestamp <= 200? That's how most people write their conditions, IINM. I guess my brain works differently. To me the other way makes more sense. Since they mean the thing, why would "most" people write that. To each their own, they say :) @user441521 Also known as Yoda conditions. Like "If greater than 200 is the timestamp".. @jrok there's a growing movement to write all comparisons with constants by putting the constant first. The primary motive being that if you ALWAYS do it, you never have a problem with writing if(i = 0) since if(0 = i) will generate a compile-time error. Sometimes it makes sense on its own merits, Yoda conditions notwithstanding. Is there any reason why you're not using the simpler list<Tick>::iterator iter;? Sorry, this was from an example left over where I was using cpp linq and it required that. My bad. After your edits to the question, I think I can write a better answer than what I had before. First, write a comparison function for Ticks that uses their timestamps: bool CompareTicks(const Tick& l, const Tick& r) { return l.timestamp < r.timestamp; } Now use the function with std::upper_bound: // Get an iterator pointing to the first element in ticks that is > 214 // I'm assuming the second parameter to Tick's ctor is the timestamp auto itAbove = std::upper_bound(ticks.begin(), ticks.end(), Tick(Vec3(0, 0, 0), 214), CompareTicks); if(itAbove == ticks.end()) ; // there is nothing in ticks > 214. I don't know what you want to do in this case. This will give you the first element in ticks that is > 214. Next, you can use lower_bound to find the first element that is >= 214: // get an iterator pointing to the first element in ticks that is >= 214 // I'm assuming the second parameter to Tick's ctor is the timestamp auto itBelow = std::lower_bound(ticks.begin(), ticks.end(), Tick(Vec3(0, 0, 0), 214), CompareTicks); You have to do one extra step with itBelow now to get the first element before 214, taking care not to go past the beginning of the list: if(itBelow == ticks.begin()) ; // there is nothing in ticks < 214. I don't know what you want to do in this case. else --itBelow; Now, assuming you didn't hit any of the error cases, itAbove is pointing to the first element > 214, and itBelow is pointing to the last element < 214. This assumes your Ticks are in order by timestamp, which seems to be the case. Note also that this technique will work even if there are multiple 214s in the list. Finally, you said the list is short so it's not really worth worrying about time complexity, but this technique could get you logarithmic performance if you also replaced the list with a vector, as opposed to linear for iterative approaches. <= isn't valid for checking an iterator I guess. It gives me a compile error on that. Checking iter == before --iter didn't work. It still fell through. You're right; I missed that ticks was a list and not a vector; <= won't work for list (I'll edit). As for the third sentence, I'd have to see what you tried to evaluate why it didn't work. Further; I don't quite understand what you're trying to do in the loop. --iter can never == ticks.end() since the for loop terminates as soon as iter == ticks.end(). And do you really intend to decrement iter twice within the loop body? I didn't have the check at all at first and as long as the entries meet the criteria everything works fine. If the entries are as in my post then it blows up. So I was just trying something. If I don't try something with an error everyone on stackoverflow freaks out on me. I'm basically trying to find the 2 ticks that are between the number (200 in this case but that's just an example. it's variable in the real program) I think I get it now after your edits. Revised answer. Getting compile error: error C2893: Failed to specialize function template 'unknown-type std::less::operator ()(_Ty1 &&,_Ty2 &&) const' inside algorithm Apparently your Ticks aren't comparable. See my edit again. :) I had to switch < to > in the compare but then it worked. Now this is doing 2 iterations over the list right? This does work and I'll give credit because it's great, but I have to assume 1 iteration over the list could do the job more efficiently? It's doing 2 O(log(N)) processes instead of 1 O(N) process. So it's even better than iterating. :) This is great then! Thank you. In case you are wondering why I need to do this, I'm working on a multi-player game and the Entity Interpolation part of this site: https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking explains introducing render lag and doing interpolation to get smooth movement from remote clients on local client. So the 214 is the render time and the server is sending 10 ticks a second to each client of all remote clients. This helps me find the 2 ticks that I need to interpolate between. I did this with cpp linq but it was 2 queries and not very efficient. Ah. Given that this is performance critical code, you might actually do (fractionally) better using lower_bound to find itBelow, then scanning upwards from it until you get something > the target value (should require no more than 2 increments assuming there aren't multiple elements in the list with the same timestamp). "assuming there is only 1 214 in the list" - There is no 214 in the list so not sure what you mean with this. The value I send (214 in this case) will never be in the list. It's about finding the above/below the value I send it. This "214" value is actually the current time - 100 ms (lag) on every game update. So it's constantly changing and is never meant to actually be in the list, but timestamps on either side of it should be and if they aren't then I don't update that remote clients position. I'll check out reversing this though for speed. Thanks. Actually it's probably not a big deal. The list will only ever have 5 elements so I'm sure this is fast enough. I'm constantly pushing to the front new ticks and popping from the back the last old tick to maintain 5 total elements at all times. So going through 5 elements should be really fast right. @user441521, Is ticks always sorted? Even though you are constantly pushing to the front and popping from the back? The answer to your core question is simple. Don't increment if you are at the end. Don't decrement if you are at the start. Before incrementing, check. if ( iter == ticks.end() ) Before decrementig, check. if ( iter == ticks.begin() ) Your particular example Looking at what you are trying to accomplish, I suspect you meant to use: if (iter != ticks.begin()) instead of if (--iter != ticks.end()) Update It seems you are relying on the contents of your list being sorted by timestamp. After your comment, I think what you need is: if (214>= t.timestamp) { prior = t; if (++iter != ticks.end()) { next = *iter; if ( 214 <= next.timestep ) { found = true; break; } } } Update 2 I agree with the comment made by @crashmstr. Your logic can be: if (214 <= t.timestamp) { next = t; if ( iter != ticks.begin()) { prior = *--(iter); found = true; break; } } If I use that the entries I get back are 100 & 200. That's not right. I want the entry directly "below" my value (200 in this case) and the entry directly "above" my value (200). In my example (I changed it to 214 now to make it less confusing) there is no example above 214, so I don't want anything then. I need below and above entries to my value (214 in this case) @user441521 you say "above" and "below", do you really mean "before" and "after" with respect to the iteration? Or do you mean something else? Because this answer seems like it is correct from my understanding. Entries are always be added to this list and the last value is a timestamp in ms and it's always in order. So as I loop through the list I'm checking to find the 2 entries where the number I pass in is between. So if I had another entry of 300 in my example the "right" answer I want back is the 200 AND 300 entry. If there is no 300 entry then for my value of 214 I don't want anything. I've already went over the max timestamp of 200 or I don't need anything. @R Sahu That is returning the 200 and 100 entry. It's making it inside the if check which my expected result is that it wouldn't. @user441521 then I think your logic needs a reboot. Right now you check for 214 >= t.timestamp, but it sounds like you want t.timestamp >= 214 instead. This errors in the for loop after a couple times. I think because of the ++iter if check is increasing it when really we want to increase for the check but not for the loop. Regarding your second update. That works with the given entries to the list in my post. However if I make an entry where the timestamp is 300, then this doesn't work. The reason being 214 is <= 300 so it goes into that if check, but iter != ticks.begin() fails because 300 is the beginning. I think you can do what you want with std::adjacent_find from the standard library <algorithm>. By default std::adjacent_find looks for two consecutive identical elements but you can provide your own function to define the relationship you are interested in. Here's a simplified example: #include <algorithm> #include <iostream> #include <list> struct matcher { matcher(int value) : target(value) {} bool operator()(int lo, int hi) const { return (lo < target) && (target < hi); } int target; }; int main() { std::list<int> ticks = { 0, 100, 200, 300 }; auto it = std::adjacent_find(ticks.begin(), ticks.end(), matcher(214)); if (it != ticks.end()) { std::cout << *it << ' ' << *std::next(it) << '\n'; } else { std::cout << "not found\n"; } } This outputs 200 300, the two "surrounding" values it found.
common-pile/stackexchange_filtered
Objective-C: ViewWillAppear runs before body of buttonTouchUpInside I have a Storyboard iOS Application with 2 view controllers- The first Controller has a UIButton with an outlet to the next view controller and a buttonTouchUpInside method. At the moment, the second view controller's lifecycle begins before the body of buttonTouchUpInside runs - which is bad news because viewWillAppear relies on the body of buttonTouchUpInside being completed. How do I stop this from happening? Thanks in Advance I'm assuming by "outlet to the next view controller" you mean an action segue to display the next view controller, and yes, this is correct behavior in storyboards. If you want to perform an IBAction before performing the segue, you should define a manual segue between the two view controllers without referencing the button, give it an identifier in IB, and then in the IBAction method definition for your first view controller, use this code: [self performSegueWithIdentifier:@"segueIdentifierGoesHere" sender:self];
common-pile/stackexchange_filtered
SSRS sparkline with small difference in values I have created a sparkline in SSRS. Since the values are small i get a straight line graph How do i improve the sensitivity of the graph. the difference is like for every month 60.06 60.40 60.14 You need to look at the Sparkline Vertical Axis Properties. Testing with data like yours and a simple Tablix/Sparkline I get results similar to yours: Opening the Vertical Axis Properties I can see Always include zero is checked by default: Unchecking this option has a major effect on the sparkline: So this is one way of doing it. Other than that changing the Minimum and Maximum values here will also have an effect - you just need to play around and find the right combination for you. I unchecked the always include 0 , but did not find any difference. The graph is still a straight line. And also i tried changes the min and max to 50 to 70. and i could not see the graph. Do u know whow do i set the interval ? like vertical interval bar with intervels like 60.0, 60.1,60.2,60.3 ... I don't think you can set intervals on a sparkline since there aren't any actual grid lines or similar. If the options in the properties aren't helping then perhaps other data in the tablix is affecting that particular group? Wel did some work around and some how showed some difference... Thanks for the help
common-pile/stackexchange_filtered
SwiftUI doesn't update when variable is changed in appDelegate I am trying to have the app check for whether notification access is available, then display ContentView if it is, or NotificationView if it isn't. What I have does this great, when it runs it checks and shows the right view. But, the NotificationView asks the user to allow permissions with a button. I want it so once the permission is granted, then it switches to the other view, but I can't seem to figure out how. I have also tried to do it with a sheet, but same problem. Here is what I have: appApp.swift @main struct appApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate @State private var notificationStatus: String = "na" var body: some Scene { WindowGroup { if appDelegate.notificationStatus == true { NotificationView() } else { ContentView() } } } } appDelegate.swift class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate { @Published var notificationStatus: Bool = false func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let center = UNUserNotificationCenter.current() center.getNotificationSettings { settings in switch settings.authorizationStatus { case .notDetermined: self.notificationStatus = false case .denied: self.notificationStatus = false case .authorized: self.notificationStatus = true case .provisional: self.notificationStatus = true case .ephemeral: self.notificationStatus = false @unknown default: self.notificationStatus = false } } return true } Any help would be greatly appreciated, thanks everyone! Only a child view can observe the app delegate https://stackoverflow.com/questions/76568273/unable-to-pass-information-from-local-notification-in-appdelegate-to-a-view-in-s/76568301#76568301 This question is similar to: Unable to pass information from local notification in AppDelegate to a view in swiftui. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Conform your delegate to ObservableObject, e.g. class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate, ObservableObject { Then keep the @UIApplicationDelegateAdaptor in the App but in your View use: @EnvironmentObject private var appDelegate: MyAppDelegate Now body will be called when the @Published var notificationStatus is changed. For more info, see the docs https://developer.apple.com/documentation/swiftui/uiapplicationdelegateadaptor If your app delegate conforms to the ObservableObject protocol, as in the example above, then SwiftUI puts the delegate it creates into the Environment. You can access the delegate from any scene or view in your app using the EnvironmentObject property wrapper: @EnvironmentObject private var appDelegate: MyAppDelegate This enables you to use the dollar sign ($) prefix to get a binding to published properties that you declare in the delegate. For more information, see projectedValue. I saw that, but that is showing how to access it from the View, I am trying to access it from the App, and since AppDelegate is already defined there, I don't think I'm supposed to define it twice. Any suggestions? Just make a wrapper View
common-pile/stackexchange_filtered
How to connect from MySQL to Web Application I have been trying to setup a local instance for a web application. I am new to MySQL and I can't understand how to actually connect this database to the actual web application sitting in the /var/www folder in my computer. I have created a database in command line terminal: mysql> create database mydatabase -> ; Query OK, 1 row affected (0.00 sec) mysql> create user<EMAIL_ADDRESS>identified by 'hmypassword'; Query OK, 0 rows affected (0.00 sec) mysql> create user 'host'@'%' identified by 'mypassword'; Query OK, 0 rows affected (0.00 sec) mysql> grant all privileges on database.* to 'host'@'%'; Query OK, 0 rows affected (0.01 sec) mysql> flush privileges; Query OK, 0 rows affected (0.00 sec) mysql> exit Bye mysql -u host -h <IP_ADDRESS> -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 52 Server version: 5.5.37-0ubuntu<IP_ADDRESS> (Ubuntu) How do I actually connect this database to the website? I also don't understand how to make a schema for this databse. Whenever I try to refresh my web browser I get the following message: Could not access database! SQLSTATE[HY000] [2002] Connection refused Please update your question with details of how you are trying to connect to mysql. php ? code snipit? This is better suited for stackoverflow. The basic mechanism is: the browser asks the web server for a web page. This is in fact the address of a program or script, most often written in PHP. the web server executes the PHP program. the PHP program accesses the data base server using SQL statements. the data base server returns data to the program. the program puts the data into an HTML page. the web server sends the HTML page to the browser. So you still have some way to go. Please take a look at stackoverflow to find examples of the above.
common-pile/stackexchange_filtered
Prove $\cot(x) +\cot(\frac{\pi}{3}+x) + \cot(\frac{2\pi}{3}+x) = \frac{3-9\tan^2x}{3\tan x-\tan^3x}$ As the title says. I tried simplifying the LHS but got: $$\frac{\tan^2x+7\tan x- \sqrt{3}}{\tan^2x-\sqrt{3}}$$ What should I do next? probably you made mistake somewhere You can tell your simplification of the LHS must be incorrect by plugging in $x=0$: $\tan0=0$, so the expression you got reduces to $1$, but the expression you're aiming at is infinite at $x=0$. Yeah there's a mistake in my simplification. :) From this, $\displaystyle\tan3x=\frac{3\tan x-\tan^3x}{1-3\tan^2x}$ $\displaystyle\implies\cot3x=\frac{1-3\tan^2x}{3\tan x-\tan^3x}\ \ \ \ (1)$ Multiplying the numerator & the denominator by $\cot^3x,$ $\displaystyle\cot3x=\frac{\cot^3x-3\cot x}{3\cot^2x-1}\ \ \ \ (2)$ If $\displaystyle\cot3x=\cot3A\iff\tan3x=\tan3A\implies3x=n\pi+3A$ where $n$ is any integer $\displaystyle\implies x=\frac{n\pi}3+A$ where $n\equiv0,1,2\pmod3$ Usng $\displaystyle(2),\frac{\cot^3x-3\cot x}{3\cot^2x-1}=\cot3x=\cot3A$ $\displaystyle\iff\cot^3x-3\cot3A\cot^2x-3\cot x+\cot3A=0$ Using Vieta's formula, $\displaystyle\sum_{n=0}^2\cot\left(\frac{n\pi}3+A\right)=\frac{3\cot3A}1=3\cdot\frac{1-3\tan^2A}{3\tan A-\tan^3A}$ (using $(1)$) See also : http://math.stackexchange.com/questions/346368/sum-of-tangent-functions-where-arguments-are-in-specific-arithmetic-series and http://math.stackexchange.com/questions/218766/prove-the-trigonometric-identity-35
common-pile/stackexchange_filtered
Corrupt USB RAW filesystem showing wrong size I am trying to fix this USB stick for a friend who ripped it out of their computer incorrectly resulting in the filesystem being destroyed to the max, and the device showing a capacity which is clearly wrong. I brought up Testdisk to see if this would help me recover the partitions on the disk, but that just gave me this: And when i try to go into it and do a scan it comes back with nothing of use. Is there any way to recover this device or is this the result of a physical fault on the device which is beyond any repair? I am not an expert in data recovery, but in the few times I have tried, if TestDisk can't see the drive size correctly then there is something in the flash or the controller that is damaged and it cannot be recovered. You cannot fix hardware damage using software. Given that the controller reports a totally wrong size, the drive is physically damaged. Just throw it away. I was afraid that this was the case. Just wanted confirmation from people better qualified than myself. Thanks for providing it :)
common-pile/stackexchange_filtered
how to stop cp: overwrite './xxx' ? prompt How can I stop the cp command from prompting to overwrite. I want to overwrite all the files with out having to keep going back to the terminal. As these are large files and take some time to complete. I tried using the -f option. It still ask if I want to overwrite. -f, --force if an existing destination file cannot be opened, remove it and try again (redundant if the -n option is used) cp -f /media/somedir/somefiles* . cp: overwrite `./somefilesxxx'? y In addition to calling /bin/cp, you could do one of: \cp -f ... command cp -f ... However, I agree that you should not get accustomed to using an alias like cp -i or rm -i -- if you sit down at a different shell, you won't have the safety net you've become dependent on. A whereis cp will show where is the command. So you'll be able to call the real command instead of the alias. After seeing this solution. I could see that bashes alias feature was causing the problems. http://systembash.com/content/prompt-to-confirm-copy-even-with-cp-f/ which cp alias cp='cp -i' /bin/cp which cp | grep cp alias cp='cp -i' /bin/cp He recommends unalias cp I still want to keep the alias I just don't want it to apply to this instance. My solution is to use the binary with a full path, so that bashes alias function does not take over. That works quite well. /bin/cp -f /media/somedir/somefiles* . Unfortunately on Linux the copy "cp" command doesn’t have an option to automatically answer this question with a "y" or "n" answer. There’s more than one solution to this problem depending on what you want to do. One solution is to use the Unix "yes" command. This command will output a string repeatedly until killed. If we want to overwrite all of the files in the destination directory you can use the "yes" command to answer all questions with a "y". "y" is a default value so it doesn't have to be specified. yes | cp source/*.txt destination/. If we want to avoid overwriting any of the files in the destination directory you can use the "yes" command to answer all questions with a no "n". yes n | cp source/*.txt destination/. Use "man yes" for more information about the "yes" command.
common-pile/stackexchange_filtered
Create new tmux session from inside a tmux session I'm writing a shell script that creates / attaches or switches to a given session, depending on whether one is inside tmux and the session exists. I've got everything working great except for the case requiring the creation of a new tmux session from within a tmux session. When my script executes tmux new-session -s name, I get the following output: sessions should be nested with care, unset $TMUX to force I don't actually want to nest sessions, my goal is to create another separate session and switch to it from within a tmux session. Is this possible? A GREAT resource for users finding this question: https://leanpub.com/the-tao-of-tmux/read The quickest way (assuming you use ctrl-b as your command prefix) is: ctrl-b :new To create a new session, then ctrl-b s to interactively select and attach to the session. +1 for solution that doesn't care about "sessions should be nested with care, unset $TMUX to force" and then you could rename your session : ctrl-b $ And Ctrl-b :new -s <name> to give a name to the new session. @AinTohvri If your comment was an answer, I'd upvote it. If you want to attach (if the session exists) or create with the same command, you can use Ctrl-b :new -As <name> How to create the script This script will check if a session exists. If session does not exist create new session and attach to it. If session does exist nothing happens and we attach to that session. Feel free to replace `~/development' with project name. $ touch ~/development && chmod +x ~/development # ~/development tmux has-session -t development if [ $? != 0 ] then tmux new-session -s development fi tmux attach -t development New session from terminal Let's create two detached sessions, list them, attach to one and then from within tmux cycle through sessions. tmux new -s name -d works from inside tmux because we're creating a new detached session. Otherwise you'll get a nesting error. $ tmux new -s development -d $ tmux new -s foo -d $ tmux ls > development: 1 windows (created Wed Jan 13 11:31:38 2016) [204x54] > foo: 1 windows (created Wed Jan 13 11:31:38 2016) [204x54] $ tmux attach -t $ tmux ls > development: 1 windows (created Wed Jan 13 11:31:38 2016) [204x54] (attached) > foo: 1 windows (created Wed Jan 13 11:31:38 2016) [204x54] New session from within tmux We are now inside or better known as attached to our target session. If we try to create a new session while attached it will result in a nesting error. $ tmux new -s bar > sessions should be nested with care, unset $TMUX to force To solve this we create a new detached session. e.g., $ tmux new -s bar -d $ tmux ls > development: 1 windows (created Wed Jan 13 11:31:38 2016) [204x54] (attached) > foo: 1 windows (created Wed Jan 13 11:31:38 2016) [204x54] > bar: 1 windows (created Wed Jan 13 17:19:35 2016) [204x54] Cycle (switch) Sessions Prefix ( previous session Prefix ) next session note: Prefix is Ctrl-bby default. You can bind Prefix to Ctrl-a and in Mac OSX you can change Caps Lock to ctrl system preferences > keyboard > modifier keys Attach to a session using command mode while inside tmux Trying to attach to a session without detaching will result in an error. $ tmux attach -t development > sessions should be nested with care, unset $TMUX to force Instead use command mode Prefix : then type attach -t session_name and hit enter. Thanks for the very complete answer, this answered a few of my questions all at once! What might output no current client with such a setup on the default config on the very first attach to a new main Tmux session? For example, TMUX='' tmux new-session -ds 'main'; exec tmux attach -t 'main'; outside of Tmux and without main prior set. All the commands you can launch within your terminal, like tmux new -s sessionName can be launched from within tmux by pressing the trigger key (eg: ctrl-b) then : then the command without the starting tmux part. As a result, ctrl-b : followed by new -s sessionName will do exactly what you want and give a name to your session. It also switches automatically to the new session. You can try unset TMUX first, this works for me. this will nest tmux and isn't recommended TL;DR tmux switchc -t `tmux new -dP` How it works To create a new session and switch to it, from insde a tmux session and without using tmux commands, you need to do it in two steps. Create the session with new-session in a detatched way with -d, print out the name with -P. Capture this output. NEW_SESSION=`tmux new-session -dP` Use the output to switch the client (your terminal window) to different session with switch-client. Pass your new session as the target with -t. tmux switch-client -t $NEW_SESSION One-liner You can create a one-liner that does this: tmux switch-client -t `tmux new-session -dP` or in shorthand: tmux switchc -t `tmux new -dP` This a good variation to the accepted answer Awesome answer and mostly what I was looking for. I found that if binding to a key the tmux is not needed and just new-session will also bring you to the newly created session. In other words bind-key -N "New Client Session" C-a new-session will create the new session and then switch to that as well (as far as I see I don't have any other settings to automagically switch to the new session when created) at user2354696's advice I use following key bindings to create a new session or "clone" an existing session bind-key N run-shell 'TMUX= tmux new-session -d \; switch-client -n' bind-key C run-shell 'TMUX= tmux new-session -t $(tmux display-message -p #S) -s $(tmux display-message -p #S-clone) -d \; switch-client -n \; display-message "session #S cloned"' As mentioned by the comment here, use Ctrl-b :new -s <name> I created a zsh/zle function tmx: When invoked from the command line as just tmx or using a bound key (my case below F4) it invokes fzf to quickly switch to available tmux sessions with auto-completion and session preview on the right. (The function was inspired by https://waylonwalker.com/tmux-fzf-session-jump/, see also Quick jump to tmux session.) When invoked as tmux my-session it attaches to or creates a new session my-session. It works both within and outside an existing session. If invoked within a session it switches the client. function tmx { [ -n "$ZLE_STATE" ] && trap 'zle reset-prompt' EXIT local tmux item tmux="$(which tmux)" || return $? if [ -z "$1" ] ; then item="$($tmux list-sessions -F '#{session_name}' |\ fzf --header jump-to-session --preview "$tmux capture-pane -pt {}")" || return 2 else item="$1" fi ( # Restore the standard std* file descriptors for tmux. # https://unix.stackexchange.com/a/512979/22339 exec </dev/tty; exec <&1; if [ -z "$TMUX" ] ; then # Running insided tmux. $tmux new-session -As "$item" else # Attempt to create a new session in case there none with that name. $tmux new-session -ds "$item" 2>/dev/null || true $tmux switch-client -t "$item" fi ) } zle -N tmx bindkey '\eOS' tmx # Bind the function to F4.
common-pile/stackexchange_filtered
exporting scipy array for speech data to ascii text readable in adobe audition I read a 48khz, 16bit precision PCM speech data using wav read functionality of scipy.signal. Next, I perform these steps in order : decimation -> normalisation Decimation and normalisation is done using the following steps : yiir = scipy.signal.decimate(topRightChn, 3) timeSerDownSmpldSig = N.array(yiir) factor = 2**16 normtimeSerDownSmpldSig = normalise(timeSerDownSmpldSig, factor) My decimated(or downsampled) signal is supposed to be 16khz( Hence, the downsampling factor of 3 as above). Now, I want to view the normalised downsampled numpy array normtimeSerDownSmpldSig in Adobe Audition. What steps in Python and/or Adobe audition do I need to perform? How can I use the savetxt function of scipy to view the above array in Adobe Audition ? My yiir signal values look like following : Downsampled signal yiir First 10 values: [ -6.95990948e-05 -2.71091920e-02 -3. 76441923e-01 -5.65301893e-01 1.59163252e-01 -2.44745081e+00 -4.11047340e+00 -2.81722036e+00 -1.89322873e+00 -2.51526839e+00] Downsampled signal yiir: Last ten values: [-1.73357094 -3.41704894 -2.77903517 0.87867336 -2.00060527 -2.63675154 -5.93578443 -5.70939184 -3.68355598 -4.29757849] Array signal obtained from iir decimate of python: shape: (6400000,) Type: <class 'numpy.dtype'> dtype: float64 Rows : 6400000 min, max: -875.162306537<PHONE_NUMBER>84 Information for usage on Adobe audition ### at this link (page45) - http://www.newhopechurch.ca/docs/tech/AUDITION.pdf gives out the following : ASCII Text Data (.txt) Audio data can be read to or written from files in a standard text format, >with each sample separated by a carriage return, and channels separated by a tab character. An optional header can be placed >before the data. If there is no header text, then the data is assumed to be 16-bit signed decimal integers. The header is formatted as KEYWORD: value with the keywords being: SAMPLES, BITSPERSAMPLE, CHANNELS, SAMPLERATE, and NORMALIZED. >The values for NORMALIZED are either TRUE or FALSE. For example, SAMPLES: 1582 BITSPERSAMPLE: 16 CHANNELS: 2 SAMPLERATE: 22050 NORMALIZED: FALSE 164 -1372 492 -876 etc... Options Choose any of the following: •Include Format Header places a header before the data. •Normalized Data normalizes the data between -1.0 and 1.0. The title says "ascii text readable in adobe audition", but then you say "view the above as a wav file". Which format does Adobe Audition require, text or WAV? Based on a comment in an answer, it looks like the essence of the question is "How do I write a numpy array to the specific text file format that is used by Adobe Audtion". Is that correct? I want Adobe Audition to take the ASCII text file (containing numpy array of my downsampled signal values) as input. Then you'll need to specify the format of the text file that is required by Adobe Audtion, or give a link to the specification. As this is StackOverflow, you should probably also take a shot at writing some code in this format. Otherwise the question looks like one of those "give me teh codez" requests. @WarrenWeckesser Indeed, the essence of the question is what you wrote. numpy.savetxt does not create WAV files. You can use scipy.io.wavfile.write. For example, the following creates a WAV file containing a single channel (monophonic). The signal is 3 seconds of a 440 Hz sine wave sampled at 44100 samples per second. In [18]: from scipy.io import wavfile In [19]: fs = 44100 In [20]: T = 3.0 In [21]: t = np.linspace(0, 3, T*fs, endpoint=False) In [22]: y = np.sin(2*pi*440*t) In [23]: wavfile.write("sine440.wav", fs, y) Another alternative is wavio. That's right, I can use scipy.io.wavfile.write it to write wav files. But what I need is a way to write the scipy array in a ASCII text file with some header information and use this ascii text file in Adobe Audition. Then it would help if you added more information about the format required by Adobe Auditon to the quesiton. Included comments on how to use Adobe Audition to read the ASCII text information.
common-pile/stackexchange_filtered
Perpetual motion machines Out of pure curiosity, after seeing a few really awesome perpetual motion machine ideas on youtube, I decided to try it out in blender as an exercise. In addition, I thought, that would be cool to have a rigid body system driven by one of the perpetual motion ideas, instead of existing "motor" constraint or animated object. Of course, I understand that perpetual motion is impossible in real world, but, I believe, it can be achieved in computer simulation, by (cheating) tweaking some properties, friction or gravity for example. So, I am trying to recreate the examples from here https://youtu.be/jsxroTt9IhY?t=91, and from here https://youtu.be/1hYYdmjuDac?t=146 However, both simulation does'n work as expected and it seems, the system balances itself even, no matter how hard I'd try. Here are my test blends: Ball & Levelers Rolling Ball Wheel Is that possible to achieve that in blender simulation at all ? Edit: just found this example https://www.youtube.com/watch?v=1KeQc-vH46U Thanks, Michael please add some detail about what you tried and a specific thing not working... also use http://blend-exchange.giantcowfilms.com/ to upload your .blend files (free, permanent, integrated) then past the provided link editing your post. Maybe, probably, but for physical accuracy I would give it up with Blender. Check this, it's my favorite: https://www.youtube.com/watch?v=oyjE5L4-1lQ :) The last example you've posted was made in BGE, it's physics system was quite different as far as I know. So in my opinion - don't bother with it. It will be hard and frustrating as hell. Wow, the video is actually from 2012, and looks very nice! Can you add some pictures/gifs of what you have?
common-pile/stackexchange_filtered
OpenLayers, VectorSource (WFS) adds same features again I have some problems with OpenLayers and a WFS vector source. It is a clustered source and it works so to speak that it adds features as it should the first time. But when I pan the map it keeps adding the same features again and again. The WFS request seems to return what it's suposed but it is like it's just adding the same features again. The result is that if a clusterd point says that it contains 5 features, then I pan the map and the WFS correctly returns these previous 5 points and then another 2 that comes inside the extent, then the map shows 10 + 2. I would expect that it should show 5 + 2 since the 5 old features are the same as the last fetched. Any suggestion what I do wrong? this.userMapFeatureSource = new olVectorSource({ format: new olGeoJSON(), url: (extent) => { return this.geoserverURL + '/wfs?service=WFS&' + 'version=1.1.0&request=GetFeature&typename=cite:usermapsGeom&' + 'outputFormat=application/json&srsname=' + this.projstring + '&' + 'bbox=' + extent.join(',') + ',' + this.projstring; }, strategy: olBboxStrategy }); this.userMapFeatureClusterSource = new olCluster({ distance: 36, source: this.userMapFeatureSource }); this.userMapFeatureLayer = new olVectorLayer({ visible: false, source: this.userMapFeatureClusterSource, style: (feature) => { const size = feature.get('features').length; const style = new olStyle({ image: new olIcon({ src: '/assets/sysimg/btn_map.png', scale: 0.9 }), text: new olText({ font: '11px sans-serif', text: size + ' st', textAlign: 'center', fill: new olFill({ color: 'black' }), backgroundFill: new olFill({ color: '#efeee9' }), offsetX: 0, offsetY: 20 }) }); return style; } }); The features need an id to be used with bbox strategy, to prevent them being added repeatedly. Hi Yes I read something about that. But the data has a field called "id" with a unique number. But when I looked a bit closer on the result from Geoservers WFS there is a id field on the object as well. This seems to be automated generated. And if that chages for every request that would explain it.. So this might be a Geoserver question I guess.. This is the Id set by Geoserver.. "id":"usermapsGeom.fid-6ffb85cf_176438bd523_-5d89" The unique (never changing) Id from the database is in properties object I figured out what the problem was. The store in Geoserver for this layer was not a table but a view, and then the id was not recognized as a proper id. I had to create a primary key metadata table in PostGis that pointed out the id for the view, and that solved the problem.
common-pile/stackexchange_filtered
Python Buffer for large string - better or worse? I am using python to take a very large string (DNA sequences) and try to make a suffix tree out of it. My program gave a memory error after a long while of making nested objects, so I thought in order to increase performance, it might be useful to create buffers from the string instead of actually slicing the string. Both version are below, with their relevant issues described. First (non-buffer) version - After about a minute of processing a large string a MemoryError occurs for currNode.out[substring[0]] = self.Node(pos, substring[1:]) class SuffixTree(object): class Node(object): def __init__(self, position, suffix): self.position = position self.suffix = suffix self.out = {} def __init__(self, text): self.text = text self.max_repeat = 2 self.repeats = {} self.root = self.Node(None, '') L = len(self.text) for i in xrange(L): substring = self.text[-1*(i+1):] + "$" currNode = self.root self.branch(currNode, substring, L-i-1, 0) max_repeat = max(self.repeats.iterkeys(), key=len) print "Max repeat is", len(max_repeat), ":", max_repeat, "at locations:", self.repeats[max_repeat] def branch(self, currNode, substring, pos, repeat): if currNode.suffix != '': currNode.out[currNode.suffix[0]] = self.Node(currNode.position, currNode.suffix[1:]) currNode.suffix = '' currNode.position = None if substring[0] not in currNode.out: currNode.out[substring[0]] = self.Node(pos, substring[1:]) if repeat >= self.max_repeat: for node in currNode.out: self.repeats.setdefault(self.text[pos:pos+repeat], []).append(currNode.out[node].position) self.max_repeat = repeat else: newNode = currNode.out[substring[0]] self.branch(newNode, substring[1:], pos, repeat+1) **Second Version ** - Thinking that the constant saving of large string slices was probably the issue, I implemented all of the slices using buffers of strings instead. However, this version almost immediately gives a MemoryError for substring = buffer(self.text, i-1) + "$" class SuffixTree(object): class Node(object): def __init__(self, position, suffix): self.position = position self.suffix = suffix self.out = {} def __init__(self, text): self.text = text self.max_repeat = 2 self.repeats = {} self.root = self.Node(None, '') L = len(self.text) for i in xrange(L,0,-1): substring = buffer(self.text, i-1) + "$" #print substring currNode = self.root self.branch(currNode, substring, i-1, 0) max_repeat = max(self.repeats.iterkeys(), key=len) print "Max repeat is", len(max_repeat), ":", max_repeat, "at locations:", self.repeats[max_repeat] #print self.repeats def branch(self, currNode, substring, pos, repeat): if currNode.suffix != '': currNode.out[currNode.suffix[0]] = self.Node(currNode.position, buffer(currNode.suffix,1)) currNode.suffix = '' currNode.position = None if substring[0] not in currNode.out: currNode.out[substring[0]] = self.Node(pos, buffer(substring,1)) if repeat >= self.max_repeat: for node in currNode.out: self.repeats.setdefault(buffer(self.text,pos,repeat), []).append(currNode.out[node].position) self.max_repeat = repeat else: newNode = currNode.out[substring[0]] self.branch(newNode, buffer(substring,1), pos, repeat+1) Is my understanding of buffers mistaken in someway? I thought using them would help the memory issue my program was having, not make it worse. What kind of sequence files are you using and what size are they? Also what does your RAM look like? I'm inputing FASTA files, which have no compression or anything, I'm running on a laptop with 16gb of ram. What size is the FASTA file? Or if there are multiple, how many are there and what is their average size? It's small as FASTA files go, its only 4.5MB. I think that perhaps the way I coded my program is the issue. In essence it is making objects inside of objects inside of objects, to a very deep level. I believe that perhaps it runs out of memory at some point where it can no longer create another new "Node" object and gives the memory error. I am unsure of how to properly debug the memory issues so this is just supposition. Working with sequence data can become memory intensive, especially if you are working with fastq files that are in the tens of GB range or larger. At a certain point, you're just going to need to use a machine with more RAM. Because you did not provide the file size information, or information about your compute resource, it is impossible to tell if this is the case. Please provide that info when you get a chance. Regardless, it seems that you should be making use of some Bio python tools, which will make processing sequence data much more efficient. This is because much of Bio python makes use of C data structures. First of all, you should be representing sequences as Seqs, not strings. from Bio.Seq import Seq sequence = Seq('ACTG') Secondly, a suffix tree is a perfect job for a trie. Trie - Wikipedia from Bio import trie self.out = trie.trie() # You can work with this object just as you would with a dictionary. # self.out[key] = value Working with these biopython data structures should make things more memory efficient, and is just a good practice in general when handling sequence data in python. Also, I am not sure what you're end goal is, but you may want to look into the more efficient suffix array. Many de novo assemblers such as ABySS use this for assembly. My goal is less professional oriented and more learning oriented, so I am trying to create an implementation from my own skill set rather than using what comes with Bio python. I am more of a science person and less of a program person so I was attempting to put my "paper" knowledge on suffix trees to use in Python as an exercise. I would be happy to hear any suggestions about my suffix tree implementation however. I see. I have the same background (biology first, then computer science). I am confused however, as my suggestions are simply two alternate data structures, so in essence you will still have to develop and implement the algorithm itself, just while storing your data in a more efficient way. I would be curious to see how replacing your self.out = {} with self.out = trie.trie() would work, as if I understand the code, that is where you are saving your nested objects, and the trie does not create the suffix for you, but rather serves the same purpose as your dictionary but more memory efficient. Adding the '$' to your buffer is what kills it. This causes it to coerce itself into a string, which causes all the same copying as before. If you really need to append characters, you could try using a list of buffers instead of actually appending characters to a single buffer.
common-pile/stackexchange_filtered
C# Reflection get value from ICollection i'm struggling with a problem and I'm unable to find a solution. In a certain moment of my code, a SqlException is thrown. I have created a method using reflection to iterate through all the properties from any exception and perform some logic, but I'm having an issue with this one. One of its members call Errors, that inherits from SqlErrorCollection. (According to MSDN documentation, the class definition is [SerializableAttribute] [ListBindableAttribute(false)] public sealed class SqlErrorCollection : ICollection, The code I use to check if a property is a list doesn't work for this property: if (typeof(IEnumerable).IsAssignableFrom(prop.PropertyType) && typeof(ICollection).IsAssignableFrom(prop.PropertyType) && prop.PropertyType.IsGenericType) And when I will get it value using the code below property.GetValue(myObject, null); an TargetParameterCountException (Parameters count mismatch) is raised. Anyone know why? Why do you even need to use Reflection? What are you trying to achieve here? Explaining that will bring better answers rather than asking XY question. Which property is throwing the exception? My guess is that you're calling GetValue on an indexed property, and it's throwing that exception because you're passing null rather than an index parameter. SqlErrorCollection is non generic, it uses the non-generic version of ICollection. I'm using reflection to generate a xml string of the full exception. I already tried using XmlSerializer to achieve this, but according to other Stack Overflow questions, this isn't possible with the Exception class All exception classes are serialize. You can use BinarySerializer to serialize it. if you want. Or you could simply loop the SqlErrorCollection if that's what you're after. Sriram, this is exactly what I wanted first, loop the SqlErrorCollection, but I can't find a way to do this Due to the insight provided by pmcoltrane, the Error property is an indexed property. The article iterating through an indexed property (Reflection) helped to solve my problem. Thanks for the help Looping through the errors in SqlException is very easy. if that's what you're after, here you go. private string GenerateMessage(SqlException ex) { StringBuilder builder = new StringBuilder(); foreach (SqlError error in ex.Errors) { builder.Append(error.ToString()); } return builder.ToString(); } Oh thanks for the answer, but I'm looking for a way to do this in a generic way using reflection, like exception.GetType().GetProperty("Error").GetValue(myObject, null) @MarlonVidal What if Error property doesn't exist? Why are you complicating things? prop.PropertyType.IsGenericType check will return false, since SqlErrorsCollection is non-generic. As for second part of the problem - I was unable to reproduce this exception when getting property value. Following code executes without exceptions: // create inner sql error collection instance through reflection var sqlErrorCollCtor = typeof(SqlErrorCollection).GetConstructors( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.NonPublic).FirstOrDefault(); var errorCollection = (SqlErrorCollection)sqlErrorCollCtor.Invoke(null); // create sql exception instance through reflection var sqlExceptionCtor = typeof(SqlException).GetConstructors( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.NonPublic).FirstOrDefault(); var exception = sqlExceptionCtor.Invoke( new object[] { "Test", errorCollection, null, new Guid() }); // retrieve Errors property var prop = exception.GetType().GetProperty("Errors"); if (typeof(IEnumerable).IsAssignableFrom(prop.PropertyType) && typeof(ICollection).IsAssignableFrom(prop.PropertyType) ) // && prop.PropertyType.IsGenericType) { var val = prop.GetValue(exception, null); Console.WriteLine(val); } Could it be that you are retrieving value from another object, not SqlException?
common-pile/stackexchange_filtered
"man" can't find man page after installing Crunch Wordlist Generator on Fedora 25 [root@unknowna08cfd77f899 crunch-3.6]# ls charset.lst COPYING crunch crunch.1 crunch.c Makefile unicode_test.lst [root@unknowna08cfd77f899 crunch-3.6]# make make: Nothing to be done for 'all'. [root@unknowna08cfd77f899 crunch-3.6]# man crunch No manual entry for crunch Any suggestions would be great because I am stuck in my tutorial. Why is there no manual file? try to copy manually crunch.1 into /usr/share/man/man1/. ... Or read on-line http://manpages.ubuntu.com/manpages/xenial/man1/crunch.1.html ... I.e. almost every man page can be found with key word = man [app name] Isn't this missing a sudo make install? I don't think you've actually installed it quite yet. Just compiled. Thank you very much, can't believe I forgot to make install lol If you want to open locally built manual page that is not in the common path, you should use the ./ prefix, such as man ./crunch.1 Resolved in comment: Isn't this missing a sudo make install? I don't think you've actually installed it quite yet. Just compiled. – Benjamin W.
common-pile/stackexchange_filtered
Excel VBA store countifs for multiple or conditions I am using VBA Countifs to get the count of certain values according to the condition. Now I need either condition to count. The below code work for count "No Video" rows and Non "No video" rows. But I want to count "No Video" or "No Data" as single output and another is without those two. Set R1 = appExcel.Range(cmdAudit2.Text & ":" & cmdAudit2.Text) Set R2 = appExcel.Range(cmbChoice.Text & ":" & cmbChoice.Text) NoVideos = appExcel.Application.CountIfs(R1, AuditType, R2, "No video") Videos = appExcel.Application.CountIfs(R1, AuditType, R2, "<>No video") I found some examples which using multiple conditions "and" operator. But I want "or" condition. For the time being I am using the below code to make it work NoVideos = appExcel.Application.CountIfs(R1, AuditType, R2, "No video") NoAudited = appExcel.Application.CountIfs(R1, AuditType, R2, "Not audited") Videos = appExcel.Application.CountIfs(R1, AuditType, R2, "<>No video") Videos = Val(Videos) - Val(NoAudited) NoVideos = Val(NoVideos) + Val(NoAudited) Is there any good method which can be done in with single countifs. CountIfs doesn't allow the use of OR conditions like that. You could add or subtract the Countifs in one line of code and avoid the intermediate step. You could also use SumProduct, something like: = application.WorksheetFunction.SumProduct(((R2="No Video")*(R2="Not Audited"))+(R1 = AuditType)) The above is air-code, you'll need to make the SumProduct work in Excel and record it to get the correct syntax. For info on using SumProduct, see this OzGrid page Note that in the formula above multiplication creates an AND operation and addition creates and OR operation.
common-pile/stackexchange_filtered
Boot loop device as root file system I created an ext4-filesystem on a loop device with all necessary files to boot with, e.g.: /bin /boot /dev /lib /mnt /etc ... Now I want to boot from the loop device as an image (let's say filesystem.img) with this filesystem. Is it possible to make this loop device as the new root filesystem and to boot from it with the GRUB2 bootloader? I also read an article about initrd to perform this with the initial ram disk: https://developer.ibm.com/articles/l-initrd/ qemu should do the job. I use such command to emulate booting from another hard drive: sync ; echo 3 | sudo tee /proc/sys/vm/drop_caches ; sudo qemu-system-x86_64 -m 1024 -enable-kvm -hda /dev/sdc first two sections (sync and echo 3) usually are needed single time after you have edited the image file. -m 1024 - sets Ram limit. -enable-kvm - can be omited if causing problems. -hda /dev/sdc - this part you should change.. here is a better answer - Booting a raw disk image in QEMU Thanks for your answer! In my case, I want to boot directly from GRUB with that disk image. Do you know if this is possible? It seems like it is not possible with QEMU, am I right? Well, it is sure possible with GRUB load into GRUB2 and enter its command line mode (hit 'c') and investigate how it enumerated your disks in (hdN,N) fashion with ls command load into GRUB2 and edit any entry (hit 'e') , edit it into something like https://superuser.com/a/1300189/702372 according to your files location . Load it by hittin Ctrl-x to make a permanent entry, follow the answer from 2. Thank you once again. I got problems booting into my filesystem. I got in my main partition (hd0, msdos1), the following file is my filesystem: filesystem.img. My entry in /etc/grub.d/40_custom is: menuentry "test" { insmod linux set isofile="boot/filesystem.img" loopback loop (hd0,msdos1)/${isofile} linux (loop)/vmlinuz initrd (loop)/boot/initrd.img-4.15.0-187-generic }. But after that, when I boot from it, I get an error message attempt to read or write outside of disk 'loop'. Do you know a solution? I practiced it a bit. Probably I can tell you exact commands if you tell how you made that fs.img file.
common-pile/stackexchange_filtered
C# App.Config - Not getting values for courses collection I am attempting to read values from my config file into my program. I'm trying an example that I found online at http://www.bardev.com/2013/11/17/kickstart-c-custom-configuration/. I've set up the config and the classes the same way that I see it on the site. I can get the values for school name, address, city and state but I'm unable to get back the Settings.Courses values and also getting the following errors when running the code as is: Exception Unhandled 'System.TypeInitializationException' occurred in SchoolBlog.exe. Additional information: The type initializer for 'SchoolBlog.SchoolConfig' threw an exception. Inner Exception (key part of problem) ConfigurationErrorsException: Unrecognized element 'courses'. Config <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="school" type="SchoolBlog.SchoolConfig, SchoolBlog" /> </configSections> <school name="Manchester High"> <address street="123 Main Street" city="Mandeville" state="Manchester"/> <courses> <course title="Math"></course> <course title="English" instructor="Thompson"></course> </courses> </school> </configuration> Classes public class SchoolConfig : ConfigurationSection { private static SchoolConfig _schoolConfig = (SchoolConfig)ConfigurationManager.GetSection("school"); public static SchoolConfig Settings { get { return _schoolConfig; } } [ConfigurationProperty("name")] public string Name { get { return (string)base["name"]; } } [ConfigurationProperty("address")] public AddressElement Address { get { return (AddressElement)base["address"]; } } } public class AddressElement : ConfigurationElement { [ConfigurationProperty("street")] public string Street { get { return (string)base["street"]; } } [ConfigurationProperty("city")] public string City { get { return (string)base["city"]; } } [ConfigurationProperty("state")] public string State { get { return (string)base["state"]; } } } public class CourseElement : ConfigurationElement { [ConfigurationProperty("title", IsRequired = true)] public string Title { get { return (string)base["title"]; } } [ConfigurationProperty("instructor", IsRequired = false)] public string Instructor { get { return (string)base["instructor"]; } } [ConfigurationProperty("courses")] public CourseElementCollection Courses { get { return (CourseElementCollection)base["courses"]; } } } [ConfigurationCollection(typeof(CourseElement), AddItemName = "course", CollectionType = ConfigurationElementCollectionType.BasicMap)] public class CourseElementCollection : ConfigurationElementCollection { public ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } } protected override string ElementName { get { //return base.ElementName; return "course"; } } protected override ConfigurationElement CreateNewElement() { return new CourseElement(); } protected override object GetElementKey(ConfigurationElement element) { return (element as CourseElement).Title; } public CourseElement this[int index] { get { return (CourseElement)base.BaseGet(index); } set { if (base.BaseGet(index) != null) { base.BaseRemoveAt(index); } base.BaseAdd(index, value); } } public CourseElement this[string title] { get { return (CourseElement)base.BaseGet(title); } } } Main static void Main(string[] args) { //int coursesCount = SchoolConfig.Settings; string schoolName = SchoolConfig.Settings.Name; string schoolStreet = SchoolConfig.Settings.Address.Street; string schoolCity = SchoolConfig.Settings.Address.City; string schoolState = SchoolConfig.Settings.Address.State; Console.WriteLine("School Name: {0} ", schoolName); Console.WriteLine("School Address: {0} {1} {2} ", schoolStreet, schoolCity, schoolState); //Console.WriteLine("Course Count: {0} ", coursesCount); Console.WriteLine("\r\nDone"); Console.ReadLine(); } The CourseElement class inherits from ConfigurationElement. The CouseElement class is very similar to the other Element classes that we created earlier. Even though I will not go into detail about the CourseElement class, do note that the IsRequired property for each ConfigurationProperty attribute. One is set to true and the other is set to false. You don't have a courses element collection property in the SchoolConfig class. Its right there in the CourseElement class yes but where is it in the SchoolConfig class? SchoolConfig doesn't know about courses so how will it be able to load it? All you are loading at the moment is the Name property and address. you need to move [ConfigurationProperty("courses")] public CourseElementCollection Courses { get { return (CourseElementCollection)base["courses"]; } } into SchoolConfig I think. The class for SchoolConfig is missing a property for Courses. Update the class to the following and it should work. public class SchoolConfig : ConfigurationSection { public static SchoolConfig Settings { get; } = (SchoolConfig)ConfigurationManager.GetSection("school"); [ConfigurationProperty("name")] public string Name { get { return (string)base["name"]; } } [ConfigurationProperty("address")] public AddressElement Address { get { return (AddressElement)base["address"]; } } [ConfigurationProperty("courses")] public CourseElementCollection Courses { get { return base["courses"] as CourseElementCollection; } } }
common-pile/stackexchange_filtered
Select input - Angular 2 I would like to know the number of elements (in this case option) has my select <select class="form-control" required> <option *ngFor="let numberDoor of car.doors" type="text">{{numberDoor .number}}</option> </select> That is the select but I would like to check first if it has more than an element, or less (0 or 1) doors I guess the easiest way is using Jquery or Javascript You can check the length of the array <span>{{car.doors.length}}</span> Possible duplicate of jQuery count child elements Do you know if it is possible to do something like *ngIF="scenario.lIntConf.length>30" ? Try like this: <select class="form-control" required *ngIf='car.doors.length'> <option *ngFor="let numberDoor of car.doors" type="text">{{numberDoor.number}}</option> </select> If car.doors are empty, your select don't display. Just add '*ngIf="car.doors.length > 2". This will display the select when there are more than 2 elements and the doors array. @MarioLópez
common-pile/stackexchange_filtered
How to call asmx webservice for collection using BackboneJs I hope someone could put me through a code to learn to call asmx webservices from backbone collection. The example i have put here is extremely simple Collection window["Persons"] = Backbone.Collection.extend({ model: Person, url: "service.asmx/GetPeople" }); note: I do have a service.asmx file at the point Asmx End point [WebMethod] [ScriptMethod] public static List<Person> GetPeople() { List<Person> people = new List<Person>(10); for (int i = 0; i < 10; i++) { people.Add(new Person(i.ToString())); } return people; } The Model public class Person { public string Name { get; set; } public Person(string name) { Name = name; } } when i do the below chrome xhr inspector informs me of this error var family = new Persons();family.fetch(); Request format is unrecognized for URL unexpectedly ending in '/GetPeople' You will want to override the Backbone.sync() function to customize the persistence and retrieval of models from the server. You can take a look at the annotated source code of how the Backbone.sync() function is overwritten for a local storage alternative. so that means i will have to take care of routing if there are more than one Models, Collections on the page right. Yep, you will need to take care of the routing yourself
common-pile/stackexchange_filtered
How do I return all the desired dictionary values within an IF statement in python? (discord.py) I am trying to iterate through all the values in this JSON dictionary to retrieve whenever a user(s) has the desired date set as their birthday. However, it will only return the first value. This is the dictionary I am referencing: { "TARGETGUILD": { "USERID1": { "month": "09", "day": "10" }, "USERID2": { "month": "09", "day": "10" } }, "otherGUILD": { "USERID": { "month": "09", "day": "10" } } } Here is the code: @commands.command(name="today", pass_context=True) async def today(self, ctx): today = datetime.today() today_month = today.strftime("%m") today_day = today.strftime("%d") guild_av = ctx.guild.icon_url with open('commands/birthday/birthdays.json', 'r') as f: data = json.load(f) guild_data = data[str(ctx.guild.id)] birthday_dict = {"month": str(today_month), "day": str(today_day)} #length = len(guild_data) def find_birthday(): for user in guild_data: if guild_data[user] == birthday_dict: return ":tada: <@!" + str(user) + ">" + "\n" else: return "`None`" embed = discord.Embed(title=f":calendar_spiral: {today_month}/{today_day}", description="**Today's Birthdays:**" + "\n" + "\n" + str(find_birthday()), color=discord.Color.greyple()) embed.set_thumbnail(url=guild_av) await ctx.send(embed=embed) In this screenshot, you'll see it only will display the first user. The "other" guild ID in the JSON, for example, will obviously work properly as there's only one user with a birthday as seen in this screenshot. I've tried a couple of things, just to try and find out what my issue was. For instance, when I do: def find_birthday(): for user in guild_data: print(user) It DOES print each user. So, that's what leads me to believe the issue is within my if statement. Whenever it sees the user's birthday matches, it only will print the first user that matches. So, after looking through many threads... I just can't figure out how to make it list each person. I apologize if this is a simple fix and/or easy solution that I'm missing (typically it always is). I have been stuck on it for a bit now, though. I'm still learning python. I'd appreciate it if anyone could steer me in the right direction. QUESTION How do re-write this to allow it to return multiple values within an if statement? Thanks so much. You should consider using yield instead of return. You would then need to collect all the results from the generator before creating a string for the description parameter. The return statement exits the loop. It just returns from the function find_birthday() immediately to return its result to the caller.
common-pile/stackexchange_filtered
How to extend Eclipse's Java editor to recognize my own elements I want to add references to other elements inside javadoc. The javadoc should look similar to: /** * ... * @my.tag SomeElement */ I want to reuse the existing Java editor inside Eclipse. Of course I can type above javadoc already, however I'd like to add some features: Navigation: upon Ctrl-Click / F3 I want to navigate to the editor showing SomeElement Auto-completion: Ctrl-Space should complete the text / show valid alternatives Checking: I want to create a warning marker and underline the SomeElement if it cannot be found I already figured out that I can do the auto-completion by using the extension point org.eclipse.jdt.ui.javaCompletionProposalComputer, though this seems to be little more complex than I had hoped, so I might be on the wrong track here? For checking my elements I might be able to use org.eclipse.jdt.core.compilationParticipant, which can generate markers upon compilation which afaik happens with every save operation. But how can I can manage the navigation feature? Any pointers are welcome! Which version of Eclipse? The last time I checked, the Java editor was made up of Eclipse internal classes, which meant that the code and method signatures could change from Eclipse release to Eclipse release. @GilbertLeBlanc I use Eclipse Mars.2 (4.5.2), but generally I would prefer to use an API / extension points to achieve my goal. For navigation you can provide a Hyperlink Detector. You'll want to look at how the Java Editor and its existing detectors are declared in the org.eclipse.jdt.ui plug-in to determine the correct target ID. I have the HyperlinkDetector working now, however this only provides navigation for Ctrl-Click, not for F3. Any ideas how I can solve that? Is your detector not being called at all, or just not handing the call properly? When pressing the Ctrl+Moving the mouse then my detector is called immediately, even before clicking. However pressing F3 (aka "go to definition") does not call it at all, the status text in eclipse says "Current text selection cannot be opened in an editor". Your detector returns a hyperlink for what's being hovered over or not. Only when a returned hyperlink is activated should it actually open an editor, so are you returning one in the latter case? No. My detectHyperlinks() method is not triggered by pressing F3.
common-pile/stackexchange_filtered
Keyboard Few Keys Don't Work I use Lubuntu. Few keys of my keyboard stopped suddenly working. I have tried rebooting , reinstalling and nothing helped. Once I was able to to fix the problem with resetting the keyboard shortcuts. However , after the lid off hibernate\sleep. the problem came back. It never happened before Playing around with the Keyboard Tweaks and Keyboard Shortcuts Settings. IT AFFECTS BIOS AND LEGACY AND GRUB TOO. WHEN I HAVE FIXED THAT WITH RESETTING THE KEYBOARD SHORTCUTS IT HAS FIXED BIOS AND LEGACY AND GRUB TOO. I HAVE TRIED UPGRADING ALL OF MY DRIVERS. Funny and Strange things that happen: *) Another thing that occurs is when I press “number 2 key” or “number 1 key” they don’t work . but When I press escape+num 2+num 1 it prints out a special char. “<” xev: KeyPress event, serial 48, synthetic NO, window 0x5200001, root 0x2e9, subw 0x0, time 14467569, (539,-373), root:(1345,215), state 0x10, keycode 94 (keysym 0x3c, less), same_screen YES, XLookupString gives 1 bytes: (3c) "<" XmbLookupString gives 1 bytes: (3c) "<" XFilterEvent returns: False KeyRelease event, serial 48, synthetic NO, window 0x5200001, root 0x2e9, subw 0x0, time 14467699, (539,-373), root:(1345,215), state 0x10, keycode 94 (keysym 0x3c, less), same_screen YES, XLookupString gives 1 bytes: (3c) "<" XFilterEvent returns: False *) Funny thing is that when keyboard was working good. the caps lock key light was not going on when the Caps Lock was on. Now when I use Onboard and press Caps lock the light goes on but Caps Lock doesn’t work as a key. Can you please help me to solve the problem? Solutions that I have tried: *) I have tried Windows Troubleshooter. Found none. *) I have tried updating and Uninstall+Reinstalling the PS2 Keyboard Driver. Nothing has changed. *) I have tried contacting Chickony or Dell, None was succesful. Chickony support is unreachable . Dell community and support depend on Warranty and they don’t really care. *) I have updated the BIOS. non has changed. *) I have read about linux kernel and its modules. I have tried modifying some changes and changing to HK locale or others. Installing Chinese support programs. and other input control programs. None helped. *) I have of course removed and reconnected keyboard from connector. Nothing has changed. *) I have opened 2 keys individually to see if maybe some dust or other cause. Well there was a really small amount of dust but removing+cleaning didn’t help. *) I have tried different Operation Systems . No results. The only solution that once had worked is resetting the Keyboard Shortcuts via PureOS settings it worked like magic until suspend. Nowadays it is not helping. *) I have tried reinstalling PureOs. none is changed. *) I have tried removing and reinstalling CMOS battery. It has fixed the bipping on startup. not the keyboard… *) I am trying to reset the VRAM but I have no Idea how to do that. *) I have tried battery removing and pressing sleep button for 60secs or more. Your details are somewhat difficult to follow, you mention Lubuntu, but gave no release details (or install media which would tell us what kernel stack you're using which maybe useful for some releases), then you mention windows but its unclear if it worked there or not, then switched to Pure OS, which was then re-installed; so are you using Lubuntu now? If you have the same problem in windows, Pure OS & previously in Lubuntu, your issue is hardware related & not OS specific. My main use today is LUbuntu 24.04 I am not familiar with the command that provides all of the information that is required for you. I had Windows build in my pc When I have Bought it. Last year I have started Using Linux Mint - Everything was fine with Keyboard. This was my first Linux Distro. Later I wanted to try other Distros such as Ubuntu, Debian, SliTaz , trisquel , Arch, Fedora and PureOS... I have been configuring settings in PureOS when this problem occurred first. I think that it is related to the Layout. My keyboard model is: "built in" chickony mb-13N73HB-422 This is clearly a hardware and not an OS issue. How is it possible then that when I press ESC+2 it works but when I press only 2 it doesn't. How is it possible that resetting the Keyboard shortcuts fix this issue? Why is my Keyboard Looks like new? How is that few days after few more keys have stopped working and since than none are stopping to work. Seems quite similar to the bugs I had with my Asus Zenbook... What is your laptop brand and model please? https://askubuntu.com/questions/1526366/some-keys-refuse-to-work-after-suspend-or-reboot-then-work-ok-after-a-few-minut/1530620 Dell Inspiron 3542 ;\
common-pile/stackexchange_filtered
MVC 4 Web Api Controller does not have a default constructor? Here is the trace: <Error> <Message>An error has occurred.</Message> <ExceptionMessage> Type 'ProjectName.Web.Api.Controllers.ContinentsController' does not have a default constructor </ExceptionMessage> <ExceptionType>System.ArgumentException</ExceptionType> <StackTrace> at System.Linq.Expressions.Expression.New(Type type) at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) </StackTrace> </Error> I find this weird as public class UsersController : ApiController { ... } is working just fine. I have compared the 2 controllers, all the settings and structures are similar. I am using Ninject and i have my system setup similar to Jamie Kurtz Asp.Net Mvc 4 and the Web Api: Building a REST Service from Start to Finish. From the stack trace, is anyone able to spot the problem and how to solve it? Thanks! As Requested. ContinentsController [LoggingNHibernateSession] public class ContinentsController : ApiController { private readonly ISession _session; private readonly IContinentMapper _continentMapper; private readonly IHttpContinentFetcher _httpContinentFetcher; private readonly IDateTime _dateTime; public ContinentsController(ISession session, IContinentMapper continentMapper, IHttpContinentFetcher continentFetcher, IDateTime dateTime) { _session = session; _continentMapper = continentMapper; _httpContinentFetcher = continentFetcher; _dateTime = dateTime; } public IEnumerable<Continent> Get() { var continents = _session .Query<Data.Model.Continent>() .Select(_continentMapper.CreateContinent) .ToList(); return continents; } public Continent Get(long id) { var modelContinent = _httpContinentFetcher.GetContinent(id); var continent = _continentMapper.CreateContinent(modelContinent); return continent; } } UsersController: Works just fine. public class UsersController : ApiController { private readonly ISession _session; private readonly IUserManager _userManager; private readonly IUserMapper _userMapper; private readonly IHttpUserFetcher _userFetcher; public UsersController( IUserManager userManager, IUserMapper userMapper, IHttpUserFetcher userFetcher, ISession session) { _userManager = userManager; _userMapper = userMapper; _userFetcher = userFetcher; _session = session; } [Queryable] public IQueryable<Data.Model.User> Get() { return _session.Query<Data.Model.User>(); } [LoggingNHibernateSession] public User Get(Guid id) { var user = _userFetcher.GetUser(id); return _userMapper.CreateUser(user); } } I am using NinjectWebCommon.cs and in it, i have this and a few other default methods.: private static void RegisterServices(IKernel kernel) { var containerConfigurator = new NinjectConfigurator(); containerConfigurator.Configure(kernel); GlobalConfiguration.Configuration.MessageHandlers.Add(kernel.Get<BasicAuthenticationMessageHandler>()); } Then i have NinjectConfigurator.cs: public class NinjectConfigurator { ...... private void AddBindings(IKernel container) { ..... container.Bind<IDateTime>().To<DateTimeAdapter>(); container.Bind<IDatabaseValueParser>().To<DatabaseValueParser>(); //HttpFetchers container.Bind<IHttpUserFetcher>().To<HttpUserFetcher>(); container.Bind<IHttpContinentFetcher>().To<HttpContinentFetcher>(); //TypeMappers container.Bind<IUserManager>().To<UserManager>(); container.Bind<IMembershipInfoProvider>().To<MembershipAdapter>(); container.Bind<IUserMapper>().To<UserMapper>(); container.Bind<IContinentMapper>().To<ContinentMapper>(); ......... } ....... } Both NinjectWebCommon.cs and NinjectConfigurator.cs are located in the App_Start folder. container.Bind<ISession>().ToMethod(CreateSession); is NHibernate. It is within NinjectConfigurator.cs inside private void ConfigureNHibernate(IKernel container) { ... } The stacktrace is not enough to find out what is your problem, so please post the code of your ContinentsController! You have copied the code of the ContinentsController twice... but whatever. The problem is that one of the your contructor dependencies ISession session, IContinentMapper continentMapper, IHttpContinentFetcher continentFetcher, IDateTime dateTime is not registered in Ninject. Make sure that everything is registered or post your kernel bindings to lets us what is missing. And your UserController works fine because it has a completely different set of dependencies. @nemesv I added what you requested. One more thing you can check: make sure that also all the constructor paramters of the HttpContinentFetcher and ContinentMapper also have been registered in the contianer... @nemesv HttpContinentFetcher has ISession and ContinentMapper would take in child object's Mappers. ISession is already registered, and if i had a child of Continents i.e country, it would be registered. Did you set the Dependency Resolver on start up of your application? @FelipeOriani I have Dependency Resolver, and UserController works just fine. This error is a known error when you do not set the dependency resolver in your application. The Controller Factory could not find a parameterless constructor to create the controller and execute the action method (or verb method?). So, you have to create a dependency resolver class and set it on the initialization of your web app. It will resolve dependencies of your controllers. Using ninject, you could try something like this: using Ninject; using Ninject.Syntax; using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Web.Http.Dependencies; namespace MyApplication.App_Start { public class NinjectDependencyScope : IDependencyScope { private IResolutionRoot resolver; internal NinjectDependencyScope(IResolutionRoot resolver) { Contract.Assert(resolver != null); this.resolver = resolver; } public void Dispose() { IDisposable disposable = resolver as IDisposable; if (disposable != null) disposable.Dispose(); resolver = null; } public object GetService(Type serviceType) { if (resolver == null) throw new ObjectDisposedException("this", "This scope has already been disposed"); return resolver.TryGet(serviceType); } public IEnumerable GetServices(Type serviceType) { if (resolver == null) throw new ObjectDisposedException("this", "This scope has already been disposed"); return resolver.GetAll(serviceType); } } public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver { private IKernel kernel; public NinjectDependencyResolver(IKernel kernel) : base(kernel) { this.kernel = kernel; } public IDependencyScope BeginScope() { return new NinjectDependencyScope(kernel.BeginBlock()); } } } The NinjectDependencyResolver class takes a Ninject StandardKernel object as a constructor argument and this reference is used whenever a dependency scope is pipelined. To make this all work, the NinjectDependencyResolver class is assigned to the application's global configuration: private static IKernel CreateKernel() { var kernel = new StandardKernel(); kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); // register all your dependencies on the kernel container RegisterServices(kernel); // register the dependency resolver passing the kernel container GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel); return kernel; } On your Global.asax.cs file in the end of Application_Start event, call this CreateKernel method. I had to just add GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel); to my NinjectWebCommon, didn't have to call method in global.asax.cs. Thanks in the end of Application_Start event -> this is important! I am using Unity, not Ninject, but I was getting all kinds of exceptions as I was setting the Resolver too early. Moving it to the end of this handler fixed it. Thanks Felipe! You need to tell Ninject how to correctly resolve Web API dependencies. You can use Felipe Oriani's answer, but if you like there is a NuGet package called WebApiContrib.IoC.Ninject which will do this for you. In Visual Studio Go to: Tools > NuGet Package Manager > Manage NuGet Packages for Solution Install the WebApiContrib.IoC.Ninject package Edit: NinjectWebCommon.cs and update the CreateKernel() method to include: GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel); private static IKernel CreateKernel() { var kernel = new StandardKernel(); try { kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); RegisterServices(kernel); //Note: Add the line below: GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel); return kernel; } catch { kernel.Dispose(); throw; } } hey man! thanks, this works perfect in my webApi application. MVC 5. For me, it was just a matter of adding the Ninject.Web.WebApi.Webhost NuGet package. For my applications that use both MVC and WebApi2, I have the following packages for Ninject: Ninject Ninject.MVC5 Ninject.Web.Common Ninject.Web.Common.WebHost Ninject.Web.WebApi Ninject.Web.WebApi.WebHost Had to add the Ninject.Web.Common.WebHost and Ninject.Web.WebApi.WebHost packages after updating Ninject 3.2.x to 3.3.x I also ran into this identical error but from another cause using Ninject. I actually had the dependency resolver and configuration correct. In fact the app was working well until I tried to resolve another new dependency. I had the registration set for it, so I could not figure out what was missing. The issue was I accidentally resolved the Interface to the same Interface as opposed to resolving to the proper concrete type. So using an example from the OP I did the following which results in the identical error: container.Bind<IUserManager>().To<IUserManager>(); Notice resolving to IUserManager which was an oversight but it does lead to the identical error from the OP. Obviously the fix is to resolve to the proper concrete type. I had this problem, too, but it just turned out that one of my interfaces weren't actually implemented by any classes (I forgot to add it to the class declaration). The accepted answer is from 2014. Since tons of people had this issue, as of 2016 there's a recipe for it. This just adds to the accepted answer. The way I do it is by installing packages Ninject.MVC3 and WebApiContrib.IoC.Ninject. A file called NinjectWebCommon gets added to your App_Start folder. You can then use the built-in NinjectResolver. Just add this method: private static void AddWebApiSupport(StandardKernel kernel) { // Support WebAPI GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel); GlobalConfiguration.Configuration.Services.Add(typeof(IFilterProvider), new NinjectWebApiFilterProvider(kernel)); } and call it before calling RegisterServices. This is a common problem occurs mainly when you work with Ninject Dependency injection Container. Please follow the steps to resolve this problem. Again go for this and Install this- Now check the the App_start folder.You will find the following thing(NinjectWebcommon.cs). Now double click and check the following line in CreateKernel() method like this private static IKernel CreateKernel() { var kernel = new StandardKernel(); try { kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); RegisterServices(kernel); GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel); return kernel; } catch { kernel.Dispose(); throw; } } And then Register your dependincy like this private static void RegisterServices(IKernel kernel) { kernel.Bind<IProductDetails>().To<ProductDetails>().InRequestScope(); } I am sure this will make your solution work. private static void RegisterServices(IKernel kernel) { kernel.Bind<ICountingKsRepository>().To<CountingKsRepository>(); Make sure the To<> part is a concrete class not an interface, as that will create the same error also! In case any SimpleInjector users end up in here... For me, it was simply that I had forgotten to add SimpleInjectorInitializer.Initialize(); to my Application_Start() method. I typically create a SimpleInjectorInitializer class in the App_Start folder these days, within which I do the container.Verify() and GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); calls; after I've called my GetInitializeContainer() method that's doing all the type registrations, etc. It was happening with me when I did not mention the interface and class for dependency injection in the web.config file.
common-pile/stackexchange_filtered
PayPal IPN Nightmares I have setup an IPN listener. I throw this a test IPN from PayPal Developer - it says it's been sent successfully but then doesnt appear in ANY IPN history page... so I can't see if it's working or not. Anyone have any ideas what I am doing wrong? Simon Try setting up the IPN on a test sandbox seller account, and go through and make test payment with your sandbox buyer account. Then you should be able to log into the test sandbox seller account and see the IPN history and see if it is being sent out and what status code is being returned. Also, there are some troubleshooting tips posted here that may help to resolve the issue as well depending on what is specifically happening after further investigation.
common-pile/stackexchange_filtered
What are typical max speeds for pro downhill races? Looking videos like Red Bull Rampage or Mega Avalanche make me wonder about the speeds attained by those pro bikers. How fast they go in straight line sections? The differences are quite significant from race to race - each track is different. Also events such as Rampage are not too much about speed. The top speed may vary between 55-65km/h on tracks such as Mount Sainte Anne up to around 80km/h in Pietermaritzburg which is known for high speeds achieved. Of course all assuming good weather. Also these speeds are kept only for a few seconds (in the best case), the average speeds come around 30km/h mark course and weather dependent. These days we have Strava for this. Check for example (Strava account required to see details of individual rides): Mont ventoux descent. Galibier descent Alpe d'Huez descent You'll find some segments there, and quite often you also get tracks from pro cyclists. From looking at just a few KOMS I see that top speeds at about 110-120 km/h are not uncommon. You can find interviews with pro riders where they boast about speeds up to about 140-150 km/h. Above that seems highly unlikely because you're approaching terminal velocity and at those speed pedalling isn't going to help you. Note: Updated to show actual segments (no account needed), but to see maximum speeds, you do need an account. I avoid sites and apps that require creating an account before using it (Strava, MapMyRide). Information wants to be free. Are those speeds for road bikes or downhill? I would guess road bikes. Here's one for the downhill track at Fort William Please edit this answer so it makes sense to people who don't want to give their email address to some website just to find out how fast some bunch of guys ride their bikes. With specially designed aerodynamic bikes, suits and helmets, you can achieve much more than that (222km/h is the current record, I believe), but I wouldn't call that "riding" anymore. It's basically "free falling with your wheels gently touching an almost vertical wall of ice". @DavidRicherby I guess you'll have to take my word for the 110-120 km/h figure, you need to be logged in to view them it seems. @jillesdewit I'd like to see links to those pro interviews you speak of where they state they're going at 140-150kph... I have my doubts. Top road biker pro speeds are around 120kph and that's during races (on closed roads) and only on very particular descents that lend themselves to fast descending. Alp d'Huez is certainly not one of those descents with all its twists and turns. @chrisjleu here (in dutch) we have Belgian Philippe Gilbert claiming he has done 140 km/h (after he was clocked going 119) http://www.wielerflits.nl/nieuws/12188/snelheidsduivel-gilbert-rijdt-119-km-per-uur-met-fiets-.html In the econd paragraph he says (roughly): "fast? Not so much, if you really try you can easily reach 140 kph here, I've gone much faster before but I don't know how much. The movie below shows dutch rider Theo Bos doing 140. Both drafting behind a car though. I've seen tv interviews where they claim 150 but I can't find any on-line references.
common-pile/stackexchange_filtered
Different build rules for different CUDA versions? I'd like to specify in my CUDA code whether I'm compiling using CUDA build rule version 4.2 or CUDA build rule version 5. Is there any macro used for such purpose? Note: I know there is an option to specify whether current compilation process support certain architecture, e.g. __CUDA_ARCH__. I'm looking for a similar macro for CUDA build rule version. The macro used for determining the CUDA Toolkit version is CUDART_VERSION You can do conditional compilation of your code according to the CUDA Toolkit version like this: #if CUDART_VERSION == 5000 //Compilation is being done using CUDA Toolkit 5.0 #elif CUDART_VERSION == 4200 //Compilation is being done using CUDA Toolkit 4.2 . . . //And so on #else #endif
common-pile/stackexchange_filtered
Item address in array becomes too large and causes overflow Item address in array becomes too large and causes overflow struct payment { char id[17]; char date[10]; int cost; struct payment* next = NULL; }; int main() { payment* hash = (payment*) malloc(n * sizeof(payment)); // .... function(hash); } void function(payment hash[]) { long long j; // ... if (hash[j].id[0] == '-') // ... } (The array is of size 2087123) I have this function but because the number j gets too large (j = 1900000), so it returns overflow error. I tried this to solve it: if(((hash + j*sizeof(payment))->id)[0] == '-') But it does not give me the same values as the prior method before crashing. (which are the correct ones) Can someone help with this? (I have been searching a lot) You're accessing an element that does not exist. Check if j larger than array size before accessing the element. if (j < n) { if(hash[j].id[0] == '-') ... } } else { ... }
common-pile/stackexchange_filtered
What's ExtendedMessage on discord.js I'm on v12 and after a lot of time I decided to start coding again but I ran into a problem I can't quite fix. At start I wanted to add a function to the Message class like so Discord.Message.prototype.no = function(content){ this.channel.send(`:x: - ${content}`) }; But after a while I saw that some messages I sent did not have this function and threw me an error msg.no is not a function I used console.log to see what didn't have the function and it wasn't a Message, it was a ExtendedMessage class. My question is, what's ExtendedMessage ? I found nothing about it on the documentation and when searching for it on google, I only found things related to inline replies etc.. Discord don't have a class ExtendedMessage I tried deleting node_modules and reinstalling everything again but it didn't help. My dependecies : "dependencies": { "@blad3mak3r/reddit-memes": "^0.2.5", "color": "^4.0.1", "discord-buttons": "^4.0.0", "discord.bio": "^10.1.2", "discord.js": "^12.5.3", "easier-pokemon": "^1.0.7", "easy-json-database": "^1.5.0", "figlet": "^1.5.2", "genshin": "^1.2.4", "imgur-api.js": "^2.10.6", "mal-scraper": "^2.11.3", "moment": "^2.29.1", "nekos.life": "^2.0.7", "node": "^14.17.3", "node-osu": "^2.2.1", "node-spotify-api": "^1.1.1", "node.js": "^0.0.1-security", "tiktok-scraper": "^1.4.36", "twitch-api-v5": "^2.0.4", "user-instagram": "^3.0.0", "ytsearcher": "^1.2.4" } Are you using any other node modules? @MrMythical Yeah, want me to add my dependecies on the question ? Yes, that would helpful. I have a suspicion... In general, adding methods to objects by modifying their prototypes will make your code harder to maintain. A function sendNo(channel, content) { ... } would probably be better. The discord-buttons package uses ExtendedMessage to extend the Message class. You can see here. That's why in the console it shows up like that. Additionally, arrow functions don't have their own this. You need to use the function keyword to bind this. This worked for me Discord.Message.prototype.no = function(content) { this.channel.send(`:x: - ${content}`) } Omg so it was discord-buttons, tysm <3 @MalikLahlou No problem. Also a note, you should avoid saying "thank you" in the comments on Stack Overflow. That's what the upvote button and checkmark are for ;)
common-pile/stackexchange_filtered
How to customize seam 3 credentials? is there any way to customize seam 3 credentials object? I need to add one more attribute to credentials (captcha). I tryed the following code: @Named("credentials") @SessionScoped public class Credentials extends CredentialsImpl { private static final long serialVersionUID = -4377742708407292709L; private String captcha; public String getCaptcha() { return captcha; } public void setCaptcha(String captcha) { this.captcha = captcha; } } But it has a conflict with org.jboss.seam.security.CredentialsImpl @Named annotation. How can i override the credentials? Yould could try a CDI specialization. Ie : @Alternative @Specializes @SessionScoped public class Credentials extends CredentialsImpl { private static final long serialVersionUID = -4377742708407292709L; private String captcha; public String getCaptcha() { return captcha; } public void setCaptcha(String captcha) { this.captcha = captcha; } }
common-pile/stackexchange_filtered
how to scrape data from a website using node I am new in Node JS. from morning i am trying to scrape data from website https://www.pmkisan.gov.in/StateDist_Beneficiery.aspx [![enter image description here][1]][1] I want to store that date also in db table. Currently i am putting hard coded date. But how can i scrape that date? my code (async () => { await performDbActions(webData); })(); async function performDbActions(data) { let dataToBeInsert = {}; // console.log(data); for (const d of data) { if (Object.keys(d).length) { // console.log(d); let district = await db.sequelize.query("select * from abc where name=:districtName or other_names like :districtLike", { replacements: {districtName: d['name'], districtLike: '%' + d['name'] + '%'}, raw: true, type: db.sequelize.QueryTypes.SELECT }); delete d['sno']; delete d['name']; d['as_on'] = '2020-02-06'; } } } } According to the page's source code the date you're looking for is inside a <span> that has the id ContentPlaceHolder1_lbldate. So you can just use cheerio to get its text-content and pass the result to performDbActions as an additional parameter: //... const date = $('#ContentPlaceHolder1_lbldate').text(); //... await performDbActions(webData, date); // ... async function performDbActions(data, date) { // ... // it would be safer to use an external date-library like moment.js but here's a way to convert the date in plain js const dateParts =date.split('/'); const dateObj = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]); d['created_at'] = dateObj; } Note that the date is in format dd/mm/yyyy, so you may have to convert it to your desired format. it is in text format and in my table that column data type is date As mentioned in the answer, you need to make sure to convert it to a valid format/date. Check this for example: https://stackoverflow.com/questions/5619202/converting-a-string-to-a-date-in-javascript I saw this link already. But not able to solve my problem const date_temp = $('#ContentPlaceHolder1_lbldate').text(); console.log(date_temp); const date=new Date(date_temp); console.log(date); I have written this. but getting "Invalid Date" Yeah you did not carefully read the answers obviously :) I'll edit the answer and give you a solution ... Updated, please check. Let us continue this discussion in chat.
common-pile/stackexchange_filtered
How to Return and consume custom struct object from C++ COM component into C# application I have created a simple COM component in C++ and added a method like this interface IMathControl : IDispatch{ HRESULT AddTwoNumbers( [in] DWORD Number1, [in] DWORD Number2, [out] DWORD *pResult ); }; I have consumed above component in my C# application and it works fine. Now, I have a struct defined in C++ as this struct AttributeValueInfo { string attribute; string value; string description; }; My questions are: How I can define a method which should return the result of AttributeValueInfo type in my C++ COM component ? How I will consume that resultant struct AttributeValueInfo in my C# application ? I think i need to do marshaling but don't know where to start. Can someone point the steps or a simple code snippet for above scenario. Any help will be appreciated. According to this, interface is not a valid c++ keyword, so I fail to see how you used it in c++. In any case, if you need to use AttributeValueInfo as a return type in a C# application, why don't you just create a struct in your C# application called AttributeValueInfo with the same members? @Brian It's probably from an .idl file defining the COM interface. That is not possible. Only a C++ compiler can ever generate code to properly read the value of an std::string. With the additional restriction that it is the exact same version of the compiler with the exact same settings and using the exact same memory allocator. Interop capabilities for standard C++ classes compare unfavorably to those of a stone brick. C++ doesn't have anything similar to the kind of VM guarantees you get in C#, ensuring that basic rules like object layout and allocation is guaranteed for any code that runs in the process. You must use a string type that has interop guarantees. That's BSTR in COM, directly supported and assumed by the CLR. Using structs is pretty troublesome as well, their layout are heavily dependent on compiler settings. A declaration of the struct must appear in the type library you author, the CLR will use the IRecordInfo interface to safely access the struct members. Otherwise the kind of restriction that disappears when you realize that a struct is equivalent to a class with nothing but properties.
common-pile/stackexchange_filtered
Integration Awesomomium in Unity - RenderBuffer is an ambiguous reference between UnityEngine.RenderBuffer and AwesomiumMono.RenderBuffer I have to integrate Awesomium in Unity 3d. I have went over the steps defined in http://labs.awesomium.com/unity3d-integration-tutorial-part-1/ But when i have to drag the webTexture.cs over the player object its giving below error. Assets/WebTexture.cs(226,13): error CS0104: RenderBuffer' is an ambiguous reference betweenUnityEngine.RenderBuffer' and `AwesomiumMono.RenderBuffer' Kindly assist! Thanks, Vandana Done, I have fixed my own. In WebTexture.cs (which is provided by Awesomium) has ambiguity in Reference. Pass AwesomiumMono.RenderBuffer _rBuffer = webView.Render(); I have fixed my own In WebTexture.cs (Class file provided by Awesomium) has ambiguity in Reference. Instead of ** RenderBuffer _rBuffer = webView.Render();** Call AwesomiumMono.RenderBuffer _rBuffer = webView.Render(); It will fix and load you web container.
common-pile/stackexchange_filtered
How to convert number into currency field? I am trying to update currency field with number field in a Process builder. However i get an error data type mismatch. Is it possible to do type conversion here. Please let me know. You need to Use TEXT() function for this. It Converts a percent, number, date, date/time, or currency type field into text anywhere formulas are used. Also, converts picklist values to text in approval rules, approval step rules, workflow rules, escalation rules, assignment rules, auto-response rules, validation rules, formula fields, field updates, and custom buttons and links. e.g. Lets Say I am converting Amount Field(Type: Currency) into Number then I can create a formula like this: VALUE(TEXT(Amount)) The reason that I am using VALUE() here is because it converts my text string into Number.You can not directly convert your currency into Number. Try to add this formula in your process builder. Check the below link for more details: https://help.salesforce.com/articleView?id=customize_functions.htm&type=0 Let me know if it helps. Hi Patil, I need conversion from number to Currency. Thanks for the explanation though. Do u have multiple currencies enable in your org? Number to Currency conversion: Create a formula field with return type Currency and insert the number field within. Then update the Currency field with this formula field in the Process builder.
common-pile/stackexchange_filtered
Unfortunately Android WebService Has Stopped i am new to android programming and have developed this app that takes in parameter in Kg's and converts it to grams using a web service but while running on emulator the app says "Unfortunately Android WebService Has Stopped" and the main problem in logcat being shown "cannot find org.ksoap2.serialization.SoapObjectare" though i have included the "ksoap2-android-assembly-2.5.4-jar-with-dependencies" jar file ... please help This is my code: package com.sencide; private final String NAMESPACE = "http://www.webserviceX.NET/"; private final String URL = "http://www.webservicex.net/ConvertWeight.asmx"; private final String SOAP_ACTION = "http://www.webserviceX.NET/ConvertWeight"; private final String METHOD_NAME = "ConvertWeight"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); String weight = "3700"; String fromUnit = "Grams"; String toUnit = "Kilograms"; PropertyInfo weightProp =new PropertyInfo(); weightProp.setName("Weight"); weightProp.setValue(weight); weightProp.setType(double.class); request.addProperty(weightProp); PropertyInfo fromProp =new PropertyInfo(); fromProp.setName("FromUnit"); fromProp.setValue(fromUnit); fromProp.setType(String.class); request.addProperty(fromProp); PropertyInfo toProp =new PropertyInfo(); toProp.setName("ToUnit"); toProp.setValue(toUnit); toProp.setType(String.class); request.addProperty(toProp); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); try { androidHttpTransport.call(SOAP_ACTION, envelope); SoapPrimitive response = (SoapPrimitive)envelope.getResponse(); Log.i("myApp", response.toString()); TextView tv = new TextView(this); tv.setText(weight+" "+fromUnit+" equal "+response.toString()+ " "+toUnit); setContentView(tv); } catch (Exception e) { e.printStackTrace(); } } } Add the jar to the 'libs' folder and NOT lib folder and then add to the Build Path. i did the same and configured the path but still same problem Have you added the JAR to your Build Path? From your package explorer, right click the JAR file and select: Build Path > Add to Build Path Also, if you're just doing a simple conversion, why would you use a WebService? That could be done much quicker without connecting to the internet... Just my additional two cents I did the same and solved the problem checking checkbox on kosoap2 library in Java Build Path options, Order And Export tab. I did as follows: Add the jar to the 'libs' folder and then add to the Build Path. Check the checkbox on kosoap2 library in Java Build Path options, Order And Export tab. And the problem was solved.
common-pile/stackexchange_filtered
Medoo - Updating table row matching multiple field I am using Medoo. the update below works fine with single field match. I want to update data if match with clientId and businessCity. $database->update("clientInfo", array( "businessName" => $_POST['businessName'], "contactName" => $_POST['contactName'], "businessEmail" => $_POST['businessEmail'], "businessPhone" => $_POST['businessPhone'], "businessWebsite" => $_POST['businessWebsite'], "businessAddress" => $_POST['businessAddress'], "businessAddress2" => $_POST['businessAddress2'], "businessCity" => $_POST['businessCity'], "businessState" => $_POST['businessState'], "businessZip" => $_POST['businessZip'] ), array( "clientId" => $_POST['clientId'], "businessCity" => $_POST['businessCity'], )); I tried like this. but not working for me. are u using medoo OR cakephp ? bcoz it does not seem to be cakephp UPDATE Sorry i'm using medoo. Hi Why didn't go for cakePHP , Do u think medoo Is better ? :) haha echo $database->last_query(); use this function to check out the SQL query performed for debug. Read about the Relativity Condition from Medoo documentation: http://medoo.in/api/where Just add AND connector to each value. $database->update("clientInfo", array( "businessName" => $_POST['businessName'], "contactName" => $_POST['contactName'], "businessEmail" => $_POST['businessEmail'], "businessPhone" => $_POST['businessPhone'], "businessWebsite" => $_POST['businessWebsite'], "businessAddress" => $_POST['businessAddress'], "businessAddress2" => $_POST['businessAddress2'], "businessCity" => $_POST['businessCity'], "businessState" => $_POST['businessState'], "businessZip" => $_POST['businessZip'] ), array( 'AND' => array( "clientId" => $_POST['clientId'], "businessCity" => $_POST['businessCity'], ) )); Example: $datas = $db->update( "meta" , ["metalabel"=>$label[0][0]], ["AND"=>["metakey"=>"Collection", "metavalue"=>$_POST["metavalue"]] ] ); you must set an array with logic operator (AND or OR) and as the first value of this you must set another array...see my example above
common-pile/stackexchange_filtered
Bluetooth not getting paired I am trying to pair one android device with another through the bluetooth. But its not getting paired,not even getting any error. Can anybody tell me what i am doing wrong here? I have searched for the bluetooth devices and displayed that into the list. And now I am trying to pair the selected device name with my device. But its not getting paierd,its opening a dialog for taking the password and then it gets closed. Any help would be appreciated. Here is my code: @Override public void onItemClick(AdapterView<?> parent, View view,int position, long id) { Log.i("Log", "ListItem is clicked at :"+position); posn = position; String str = (String) listViewDetected.getItemAtPosition(position); Log.i("Log", "ListItem is :"+str); bluetoothDevice=arrayListBluetoothDevices.get(position); Intent intent = new Intent("android.bluetooth.device.action.PAIRING_REQUEST"); intent.putExtra("android.bluetooth.device.extra.DEVICE",bluetoothDevice); intent.putExtra("android.bluetooth.device.extra.PAIRING_VARIANT",0); startActivityForResult(intent, 1); } I have declared the permission in the manifest file. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH" /> help me to resolve this. pls refer http://stackoverflow.com/questions/4989902/how-to-programmatically-pair-a-bluetooth-device-on-android & http://stackoverflow.com/questions/5885438/bluetooth-pairing-without-user-confirmation this seems to happen always I have seen but not getting any idea about this. Can you tell me how to this to achieve pairing refer sample Bluetooth chat app available in android developers site As per my problem, i have posted right question. But why downvoted this? Can you suggest me?? I have gone through the Bluetooth Chat application. But in that its not connection to my device.Please friends please suggest me any site through which i can pair my device programatically. you cant actually pair your device programatically (as prior to 2.3.3 it was concidered a security flaw ) but from 2.0+ you can use unpaired rf socket to communicate. sry i dont feel sm1 can help you out in that any way try your luck please help me out guys. or else tell me any reference to do direct connection to the unpaired devices Here is an answer for you: You may experiencing some Bluetooth chip errors. For example you tried to pair once with that device, failed for some reason, and then the chip will always decline repairing - although it shouldn't. It happened to me lots of times working with different Bluetooth Android phones... What you can do: reset the Bluetooth chip. Resetting the Bluetooth chip does not mean resetting your phone! While Android may be reset, the chip continues its normal lifecycle happily, and the error will reappear after reboot. To make sure the Bluetooth chip is reset, take out the battery! On tablets, just empty the battery and restart. If that still doesn't work, do a factory reset! Bluetooth is a fragile technology, prone to bugs due to the ambiguity and vastness of its specs and the 'don't care' attitude of the chip manufacturers... nope, I am not facing any of this kind of issue.That issue is solved simply.Now i have asked a new question regarding printing int this thread. http://stackoverflow.com/q/12257164/1395259 If you know the solution then pleaselet me know.
common-pile/stackexchange_filtered
CSS - aplying border-radius to a gif I am trying to style the gif by giving it border-radius. However ther gif is smaller than the column itself so border-radius is aplied only to the right side of the gif. Could anyone help me out in applying it to the left side aswell? I dont want to change the background-size: contain!important; because then I will loose the proportions of the gif. PS. Snippet breakes the row and the gif is in another row but it doesn't matter in this example. .half-half-image-text { padding: 70px 0px; } .half-half-image-text h1 { color: #800000; } .half-half-image-text .content { height: 100%; display: flex; align-items: center; padding: 35px 0px; } .half-half-image-text .content p { font-size: 22px; } .half-half-image-text .img { min-height: 320px; height: 100%; border-radius: 10px; } <!-- begin snippet: js hide: false console: true babel: false --> <div class="half-half-image-text"> <div class="container" > <div class="row"> <div class="col-7 col-lg-7" style="padding-right:0"> <div class="content"> <p>At Fluid Automotive, our purpose is to make automotive parts easily accessible for everyone. Working with our partner brands, we aim to retail the highest quality parts, whilst maintaining a high level of customer satisfaction.</p> </div> </div> <div class="col-5 col-lg-5" style="padding-right:0"> <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Rotating_earth_%28large%29.gif/240px-Rotating_earth_%28large%29.gif" data-gallery="portfolioGallery" class="portfolio-lightbox"> <div class="img customzoom s2" style="background-size: contain!important;box-shadow: none; background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Rotating_earth_%28large%29.gif/240px-Rotating_earth_%28large%29.gif')no-repeat center right;background-size:cover;" alt="Plan rozwoju" title="Plan rozwoju"></div> </a> </div> </div> </div> </div> why are you using background image instead of img tag? Does this answer your question? Border-radius on background-image You could add this style to portfolio-lightbox : width: 240px; display: block; and change min-height:320px; to min-height:240px will solve your problem. Like below : half-half-image-text { padding: 70px 0px; } .half-half-image-text h1 { color: #800000; } .half-half-image-text .content { height: 100%; display: flex; align-items: center; padding: 35px 0px; } .half-half-image-text .content p { font-size: 22px; } .half-half-image-text .img { min-height: 240px; height: 100%; border-radius: 10px; } .portfolio-lightbox { width: 240px; display: block; } <div class="half-half-image-text"> <div class="container" > <div class="row"> <div class="col-7 col-lg-7" style="padding-right:0"> <div class="content"> <p>At Fluid Automotive, our purpose is to make automotive parts easily accessible for everyone. Working with our partner brands, we aim to retail the highest quality parts, whilst maintaining a high level of customer satisfaction.</p> </div> </div> <div class="col-5 col-lg-5" style="padding-right:0"> <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Rotating_earth_%28large%29.gif/240px-Rotating_earth_%28large%29.gif" data-gallery="portfolioGallery" class="portfolio-lightbox"> <div class="img customzoom s2" style="background-size: contain!important;box-shadow: none; background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Rotating_earth_%28large%29.gif/240px-Rotating_earth_%28large%29.gif')no-repeat center right;background-size:cover;" alt="Plan rozwoju" title="Plan rozwoju"></div> </a> </div> </div> </div> </div> Simply use an image tag. .imgradius { border-radius: 10px } <img class="imgradius" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Rotating_earth_%28large%29.gif/240px-Rotating_earth_%28large%29.gif"></img>
common-pile/stackexchange_filtered
How to wait for all completionHandler blocks to complete before proceeding? Have been using the Google Drive iOS SDK, and trying to build a list of folder contents, which includes the folder parent-folders & sub-folders. The Google Drive iOS SDK stuff is simple enough, but given the sample code below, how do I wait for all "queryForFilesGetWithFileId" completionHandler blocks to complete before proceeding? The reason is that addFolderChildren adds the sub-folders & then refreshes the view, which obviously needs to be done last. GTLQueryDrive *query = [GTLQueryDrive queryForParentsListWithFileId:folderId]; [self.driveService executeQuery:query completionHandler:^(GTLServiceTicket *ticket, GTLDriveParentList *parents, NSError *error) { if (error == nil) { for (GTLDriveParentReference *parent in parents) { if ([parent.isRoot intValue] == 1) { // add folder root -> "My Drive" } else { GTLQueryDrive *query = [GTLQueryDrive queryForFilesGetWithFileId:parent.identifier]; [self.driveService executeQuery:query completionHandler:^(GTLServiceTicket *ticket, GTLDriveFile *file, NSError *error) { if (error == nil) { // add folder parent -> file.title } else { [self handleFailed:error]; } }]; } } // add folder children // how do we wait here until all above queryForFilesGetWithFileId completionhandler blocks are done? [self addFolderChildren:folderId]; } else { [self handleFailed:error]; } }]; You can keep an index for parents count and decrease 1 at completion. Then you can update your ui when you reach to 0. Thanks @BoranA, nice workaround until I'm able to tame NSOperation/Queue, GCD etc. for an elegant solution. Ok then, this the more elegant one. Subclass NSOperation, create a property for your completion block. Create an operation queue and set maxconcurrency to 1 and add your operations to the queue. If you want to be sure about the fifo order you should set priorities or dependencies of the queue. you can use @protocol for this like @protocol MeuDelegate <NSObject> @optional -(void) meuEditingDone:(Meu*) meu; @end @interface EditMeu : MeuBasicViewController { id <MeuDelegate> delegate; } @property (retain) id delegate; @end and in the .m file do followings @synthesize delegate; call this method in your completion handler , so form there you can proceeds.
common-pile/stackexchange_filtered
Unit test to check if debug.assert statement is called in code I have some Assert statements to check some conditions for developers. So when developer is debugging if this condition fails then Assert should fail and warn developer. I want to write Unit test to see if this assert gets called in debug mode and ignored in Release mode. You'll need an observer or spy, but first, it would be nice to see the code to test. Testing to check if the C# compiler properly implements the [Conditional] attribute is not useful. It does.
common-pile/stackexchange_filtered
How to check threads timing? I wrote an application which reads all lines in text files and measure times. I`m wondering what will be the time of whole block. For example if I start 2 threads at the same time: for (int i = 0; i < 2; i++) { t[i] = new Threads(args[j], 2); j++; } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("TIME for block 1 of threads; " + (max(new long[]{t[0].getTime(),t[1].getTime()}))); Wait for them to stop processing the files and read operation times (by getTime). Is it good thinking for multithreading that in this case the time of block of threads, will be the maximum time got from thread? I think yes, because other threads will stop working by the time the thread with max time will stop. Or maybe should I think in another way? System.currentTimeMillis(); you can try this for total cost Yes, I used it in my thread. did you get whatever you were searching?? I think so, but still thinking if my output and the way I think is correct. Take a look at JDK-level cpu time reporting per-thread: ThreadMXBean/ If you want this for some benchmarking, take a look at JMH. It's dangerous to argue about execution order when having multiple threads! E.g. If you run your code on a single core CPU, the threads will not really run in parallel, but sequentially, so the total run time for both threads is the sum of each thread's run time, not the maximum of both. Fortunately, there is a very easy way to just measure this if you use an ExecutorService instead of directly using Threads (btw. this is always a good advice): // 1. init executor int numberOfThreads = 2; // or any other number int numberOfTasks = numberOfThreads; // is this true in your case? ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads); long startTime = System.currentTimeMillis(); // 2. execute tasks in parallel using executor for(int i = 0; i < numberOfTasks; i++) { executor.execute(new Task()); // Task is your implementation of Runnable } // 3. initiate shutdown and wait until all tasks are finished executor.shutdown(); executor.awaitTermination(1, TimeUnit.MINUTES); // we won't wait forever // 4. measure time long delta = System.currentTimeMillis() - startTime; Now, delta holds the total running time of your tasks. You can play around with numberOfThreads to see if more or less threads give different results. Important note: Reading from a file is not thread-safe in Java, so it is not allowed to share a Reader or InputStream between threads! That andswer touches what I wanted to know! Thanks You alot for this piece of contribution and useful note. Problem solved! As far as my concern You can Use System class's static methods. You can use it in starting of the block and end of the block and subtract the later one with earlier time. those are : System.currentTimeMillis(); // The current value of the system timer, in miliseconds. or System.nanoTime(); //The current value of the system timer, in nanoseconds. You can use Starting of block long startTime = System.currentTimeMillis(); End of block long endTime = System.currentTimeMillis()- startTime; By this you can calculate.
common-pile/stackexchange_filtered
Can I find out if anyone is within a boundary with a Intelligo Corpus Spell? For example, could I use a Intelligo Corpus spell with a range of personal, duration of instant, a target of boundary, and a Intelligo Corpus base level of 5 to know if someone is within my boundary and their location relative to me? The Lower Limits of Magic imply that you need an Arcane Connection with things you do not sense to affect them but this limit is more flexible with Intelligo spells. I would say: No. Not without Arcane connections to the targets. That spell is similiar to The Inexorable Search, which requires an Arcane Connection. I see the main problem in the fact, that you can't use Corpus with a target of boundary, Corpus needs to target a body (my interpretation) Would I think could be done: From Ars Magica Core Rulebook Page 113-114: MAGICAL SENSES Intellego spells can grant magical senses to a person. These spells allow the recipient to detect things that he could not normally sense, and they have different targets, corresponding to the kind of sense that the recipient gets. The range of the spell is the range to the recipient. Since you would get the senses yourself, Range Personal would be sufficient. Then you don't get a "radar map" in your mind, intellego gives you the information through your normal five senses: From Ars Magica Core Rulebook Page 114: Taste: The information comes through the sense of taste. This target is equivalent to Individual. Touch: The information comes through the sense of touch. This target is equivalent to Part. Smell: The information comes through the sense of smell. This target is equivalent to Group. Hearing: The information comes through the sense of hearing. This target is equivalent to Structure. Vision: The information comes through the sense of sight. This target is equivalent to Boundary, but, unlike Boundary, it does not require Ritual magic. That means , that you can't sense anything in the complete boundary, if you are not able to see, hear or smell anything in that boundary. But you could sense any Corpus Target in Hearing or Sight distance (how far that is must be decided by the GM). Hearing would have the advantage, you could sense targets behind you. But probably only a range of about 50-100 paces. But, how does Sense the Feet that Tread the Earth function? From Ars Magica Core Rulebook Page 154: Sense the Feet that Tread the Earth (Level 30) R: Touch, D: Conc, T: Part You touch the earth and feel what is moving along the ground within a mile of where you stand. You can tell the direction, distance, weight, number, and manner of movement of moving things. For instance, you might sense "a single 50-stone creature slithering toward us, a hundred rods in that direction." (Base 4, +1 Touch, +1 Conc, +1 Part, +3 size) That is nearly what you want, only as a terram spell. The Intellego Terram Guidelines states: Level 4: Learn one mundane property of an object. / See an object and its surroundings. Here they got around the problem, because you sense a property of the ground which you touch, so no Arcane Connection needed. But you can't exactly know what is moving. Maybe with a corpus requisite you can only sense corpus targets. I would say, the same is possible with Intellego Auram (you sense where there is a body which displaces the air, and since the air is around you, touch range is okay). Intellego Imaginem should also work, but Target: Boundary would be a ritual. But with corpus alone: I don't think it is possible. No, unfortunately the spell design you've suggested does not work. There are a few issues: 1) You cannot target somebody unseen without an AC, or without affecting all targets within a contained area (room/structure/boundary), and the caster must still touch the room/structure, etc to cast. The range cannot be personal. Using an enhanced perception spell with R: Personal also normally requires a link to a sense, such as T: Vision. So a R:Per and T: Boundary spell does not make sense. An InCo base 5 R:Touch, T: Boundary will work, as it will give the caster an idea of where inside the boundary the person is. A second issue is that all Boundary spells have to be rituals which are expensive in vis. 2) The Base 5 you mention is for understanding a lot of detail about a body, and does not grant any special exception to the normal limits of magic with regard to targeting a person or thing which is not directly perceived, or that you have an Arc to. It is an extension of the base 4 guideline which only gives very general information. e.g. Revealed Flaws of the Mortal Flesh directly demonstrates the base 5 guideline, and Physician's Eye demonstrates the base 4 (Ars p.130). Here are some sample spells which might work: Discern the Cardinal Path Intellego Corpus 15, R: Arc, D: Mom, T: Ind Caster gains knowledge of the current approximate distance and direction to the target with whom they have an arcane connection. (base 3, +4 Arc) Actually I'm not even sure if the 2nd and 3rd spell are valid, as they still seem to be breaking the law of Arcane Connection... I would also say 2nd and 3nd spell isn't working, but mainly because I would rule that a corpus spell needs a body or bodies as target, so a structure is not a valid target for a body spell. I've edited to delete them, however the fact that the spell uses Structure or Boundary isn't relevant for the Form - that's like trying to insist that "Gloom of Evening" (PeIg10, Ars p142) cannot target a room, except it does exactly that. The room is the "container" within which the magic is evoked. There are many T:Room spells that disprove your comment (e.g. Prying Eyes, Ear for Distant Voice, Vision of Haunt Spirits, Scent of Peaceful slumber) It would also be possible for a magus to complete this task with spontaneous magic using Opening the Intangible Tunnel (at ReVi4) then cast the spell above reduced back to R: Touch which makes a InCo4 spell (as Base 3, +1 Touch); both effects far easier to spont cast. I would say there is a difference: Gloom of evening targets the light in the room. A PeCo with target:room is also be possible, if you are in the room (or can sense the persons in the room) and see the targets ,so you can target the bodies. But with the Intellego Corpus, you don't have a valid target, because you don't know if there is one. And Prying Eyes is also different, because the Intellego Imaginem Guidelines say, that Level 1 means: Use on sense at a distance. So Target Room means you can use one sense in that room. That is a valid target. Intellego Corpus says you can get Information About a Body, but for that you need a (sensed) body or an Arcane Connection. You would need to Research a Breakthrough on the Lesser Limit of Arcane Connections for this to work. I don't have my books with me here, but I am pretty sure this is covered in Houses of Hermes: True Lineages under the Bonisagus section.
common-pile/stackexchange_filtered
Is it possible to see how many local notications are scheduled? Is there a way to see how many local notifications have been scheduled? For a long time I was under the impression that this would be possible (and I already found some 3rd party tools for that too), but I can't find any examples of how this could be done. You can see which local notifications your app has scheduled using UNUserNotificationCenter getPendingNotificationRequests(completionHandler:) There is an undocumented limit of 64 notifications that can be scheduled at once.
common-pile/stackexchange_filtered
How do I install swell-foop-3.11.1.tar.gz in Linux Mint Petra? How do I install swell-foop-3.11.1.tar.gz in Linux Mint Petra? I tried to install it with software manager but the game does not seem to work, so I downloaded swell-foop-3.11.1.tar.gz and extracted it, but I don't know how to install it. Do I use terminal? If so how? Why aren't you using a package manager? Does apt-get install swell-foop not work? I tried apt-get install swell-foopE: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied) E: Unable to lock the administration directory (/var/lib/dpkg/), are you root? I tried apt-get install swell-foop got message in terminal E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied) E: Unable to lock the administration directory (/var/lib/dpkg/), are you root? I am root it didnot ask for password I also clicked on autogen.sh a terminal quickly opened and closed but I cannot see a game anywhere there was no README or INSTALL Is it possible that you have /var on a read-only partition (a terrible idea, if that's the case!)? From your answer to my comment, it seems you're unaware that Swell Foop can be installed directly from the repos. Of course trying the installation as a regular user will fail. To install as root, follow these steps: [user@host]$ su Password: [root@host]# apt-get install swell-foop This of course assumes you have root access. If you haven't enabled the root account during installation, do this instead: [user@host]$ sudo apt-get install swell-foop [sudo] password for user: Note that in this second case, you should use your regular user password. I copied and pasted in terminal and got message [user@host]$ su [user@host]$: command not found Joseph R. thankyou for you comments and advice I am Dsylexic so have trouble reading and typing so I try to copy and paste please excuse my bad typing I will try and reinstall Petra tommorrow and post my question again thankyou for trying to help goodnight @markhewpac No worries. I don't see why you're going for a fresh install, though. Has something major happened to your installation? Also, you probably have already seen this, but I'll put it here just in case it can help you or someone else: opendyslexic.org. thankyou for the url Joseph R I just have downloaded it done a reinstall of mint Petra Mate 64 bit cut and pasted your commands but still asks if I am root? @markhewpac are you root? What do you get when you type id after entering your root password? Joseph R. thankyou for your assistance I am a Dsyslexic dickhead I was copying [user@host]$ with my copy function then pasting into Terminal Duh!!! swell-foop is now working when i tried Software manager game would not work using your commands in terminal correctly game has installed and working thank you Joseph R. @markhewpac Glad I could be of help. If this solved your problem, please consider marking the answer "Accepted" so that others know that the problem has been solved. How do I add solved to my post? @markhewpac You simply mark the answer that helped you accepted by clicking on the tick mark below the vote count on its left. @markhewpac Glad I could help :) First we need to determine what type of archive it is (since tar can hold any type of file). The three most common types of software distribution by tar file are source archives, installer archives, and package archives. Source archives contain the source code of the program, not the executable. Both of the other types contain the executable. these days it is more common for packages with executables to include the architecture in the file name (swell-foop-3.11.1-i386.tar.gz) but not always. So lets see if they tell us. we start by looking for a file called README or INSTALL. If you have them this is where to start. If not lets look fore a file called configure or makefile or any file ending in a .c. If you find any of these its a source archive, and will need compiled. so you want to ask that frequently asked question, "How do I compile swell foop?" which is a much bigger question than I am answering. Now if it has a file called something like installer.sh or similar it is probably an installer archive that has a script to put the files where they need to be. this should documented in the readme. If it has directories like usr lib bin etc usr/bin and so fourth It is probably intended to be extracted in your root directory like a slackware package.
common-pile/stackexchange_filtered
why does css position:fixed not work for the dialog tag? I'm starting to make a cookie banner. Simplifying my problem as much as possible, I pasted the following in the w3schools tryit editor: <dialog open style="position:fixed;right:0;"> <button>Decline</button>&nbsp; <button>Allow cookies</button> </dialog> expected result: it should go to the right of the viewport. Actual result: the dialog is centered in the viewport. When I edit the above to use div instead of dialog it works as expected: <div style="position:fixed;right:0;"> <button>Decline</button>&nbsp; <button>Allow cookies</button> </div> goes to the right of the viewport as it should do. How can I get this behaviour from the HTML5 dialog tag? Thanks for all the good work people are doing here. Inspect dialog: its browser-default styles - chrome gives its margin:auto so it's centered. Try margin:0 body { margin: 0; /* for testing */ min-height: 200vh; } dialog { position: fixed; right: 0; margin: unset; inset-inline-start: unset; } <dialog open> <button>Decline</button>&nbsp;<button>Allow cookies</button> </dialog> In fact, you can get away with right: 0;, because browser styles have inset-inline-end: 0;. But I am not 100% sure that all browsers have it. thank you imhvost. The user agent stylesheet does indeed set inset-inline-start:0; overruling that with auto or unset fixes the problem. When you set right: 0; on a <dialog>, it doesn't immediately work because the browser's default inset properties (inset-inline-start and inset-inline-end) take precedence over left and right properties. By default, <dialog> centers itself using inset values, which override your explicit right property. This means that even if you set right: 0;, the default inset-inline-start: auto; behaviour will prevent it from taking effect. To allow right: 0; to work as expected, you need to reset inset-inline-start.
common-pile/stackexchange_filtered
Proper army (Canadian Air Cadet) squadron formation (Note: I'm not in the army so feel free to correct me if my formation is wrong, but I will not be changing the question. I will change any terminology mistakes though, because I'm trying to avoid air-cadet-specific wording choices) (Note: this follows the standards for Canadian Air Cadets, not any actual army thing) Challenge Given some configurations for a squadron, output what it should look like. You will use 1 non-whitespace character to represent people. Configuration The configuration will consist of a mandatory non-empty list, a mandatory positive integer, and an optional positive integer. The list represents the number of people per "squad", the mandatory integer represents the maximum number of rows, and the optional integer represents the number of "squads" in the squadron; in other words, the length of the list. Each squad looks like this (without the commanders): X X X X X X X X X X X X X This would be a squad with 13 people in 3 rows. A squad must be strictly wider than it is tall, unless it's a single person, in which case it's 1 × 1. It must also be as tall as possible (within the restriction for the number of rows); that is, once it is one larger than a perfect square, it should form another row. An exception is that when there are 5 people, it should still be a single row.** The gap is always placed in the second column from the left, starting from the second row and moving downwards. For example, with 28 people and 5 rows maximum: X X X X X X X X X X X X X X X X X X X X X X X X X X X X Then, after the squad is formed, a commander is to be placed 2 rows above and below the squad, in the exact centre. For odd width squads: X X X X X X X X X X X X X X X X X And for even width squads: X X X X X X X X X X X X X X Hopefully you now understand how an individual squad is formed. Then, to form a squadron, each squad has 7 blank columns between it. For example, with a maximum row count of 3 and three squads of size 15, 16, and 17: X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X Then, in the final step, a commander is placed two rows above the row of front commanders, directly in the centre of the squadron, to the left if it has even width. In the example above, that would be the X at the very top. The final output may contain trailing whitespace on each line and an optional trailing newline. Here's a reference implementation: Try It Online! (Python 3) Input Input will be given in any flexible format with the 3 components listed above: list, int[, int]. Rules Standard loopholes apply Output must be in this exact format (of course, you may choose the character to use) Newline may be CR, LF, or CRLF Trailing whitespace is allowed Trailing newline is allowed **Except our squadron's Flag Party formed a 3x2 pseudorectangle :P Sandbox Post 'Murica Python 3, 308 314 309 305 269 bytes Input is the number rows in a squad and a list with a single integer for each squad, indicating the number of persons in the squad. Could probably be golfed quite a bit. Edit: +6 bytes, fixed a bug for squads with the same number of persons as rows Edit: -6 bytes thanks to @Mr.Xcoder Edit: -36 bytes by combining everything to one function def z(r,l,v=" ",z="X "):q=[z,v]+[(v*6).join(([z.center((w//r+(w%r>0))*2),v]+[r*[z],[z+[z,v*2][I*w%r and r>=w%r+I]+z*(w//r+(w%r>0)-2)for I in range(r)]][w>r]+[v,z.center((w//r+(w%r>0))*2)])[i]for w in l)for i in range(r+4)];return"\n".join(p.center(len(q[2]))for p in q) Try it online! 308 bytes Batch, 628 bytes @echo off call:s 1 %1 %4 call:s 2 %2 %4 call:s 3 %3 %4 set s=%s1%X%s1% %s2%X%s2% %s3%X echo %s1% %s2% %s3%X echo( echo %s% echo( for /l %%i in (1,1,%4)do call:r %%i echo( echo %s% exit/b :q set/ah=h%1,f=f%1 call set x=%%x%1%% if %2 gtr %f% set x=X %x:~3% if %2 gtr %h% set x=%x:X= % set r=%r%%x% exit/b :r set r= for %%j in (1 2 3)do call:q %%j %1 if not "%r: =%"=="" echo %r% exit/b :s set h=%3 if %2==5 set h=1 :t set/aw=~-%2/h+1 if %w% leq %h% set/ah-=1&goto t set x=X for /l %%i in (2,1,%w%)do call set x=%%x%% X set/ah%1=h,f%1=%2-h*~-w set x%1=%x% set s%1=%x:X=% Takes the three squad sizes and the height as parameters. Explanation: call:s 1 %1 %4 call:s 2 %2 %4 call:s 3 %3 %4 Calculate the dimensions of each squad. set s=%s1%X%s1% %s2%X%s2% %s3%X Calculate the squad commanders. The sN variables hold a number of spaces equal to half the width in characters of the squads rounded down, so adding this on both sides centres each commander. echo %s1% %s2% %s3%X echo( Calculate and output the position of the front commander. This is similar to the case of the individual commanders except for the additional spacing between the squads, which has to be rounded up to allow for the sN being rounded down. echo %s% echo( Output the first row of individual commanders. for /l %%i in (1,1,%4)do call:r %%i Output the squads. echo( echo %s% exit/b Finish by outputting the second row of per-squad commanders. :q set/ah=h%1,f=f%1 call set x=%%x%1%% Get the height, full width rows and full width cadet string for the squad. if %2 gtr %f% set x=X %x:~3% If this is not a full width row, remove the second cadet. if %2 gtr %h% set x=%x:X= % If all the rows have already been output, remove all the cadets. set r=%r%%x% exit/b Add any remaining cadets to the overall row. :r set r= for %%j in (1 2 3)do call:q %%j %1 if not "%r: =%"=="" echo %t% exit/b Given a row in %1, add each squad's cadets for that row and output the result. :s set h=%3 if %2==5 set h=1 :t set/aw=~-%2/h+1 if %w% leq %h% set/ah-=1&goto t Calculate the number of rows and columns for this squad. set x=X for /l %%i in (2,1,%w%)do call set x=%%x%% X Calculate the full width cadet string for this squad. set/ah%1=h,f%1=%2-h*~-w set x%1=%x% Calculate the number of full width rows and save all the results in per-squad variables. set s%1=%x:X=% Also calculate the half-width string for centring purposes.
common-pile/stackexchange_filtered
Missing file error (XMLStream.php) using XMPP I want to send message using XMPP and I have used this code: include 'XMPP.php'; #Use XMPPHP_Log::LEVEL_VERBOSE to get more logging for error reports #If this doesn't work, are you running 64-bit PHP with < 5.2.6? $conn = new XMPPHP_XMPP('hostname',5222, 'panelusername', 'panelpassword', 'xmpphp', 'gmail.com', $printlog=false, $loglevel=XMPPHP_Log::LEVEL_INFO); try { $conn->connect(); $conn->processUntil('session_start'); $conn->presence(); $conn->message('senderusername', 'This is a test message!'); $conn->disconnect(); } catch(XMPPHP_Exception $e) { die($e->getMessage()); } But it gives me this error: Warning: require_once(XMPPHP/XMLStream.php): failed to open stream: No such file or directory in /opt/lampp/htdocs/xmppmessage/examples/XMPP.php on line 30 Fatal error: require_once(): Failed opening required 'XMPPHP/XMLStream.php' (include_path='.:/opt/lampp/lib/php') in /opt/lampp/htdocs/xmppmessage/examples/XMPP.php on line 30 In the XMPP.php file on line 30, change it from: require_once 'XMPPHP/XMLStream.php'; to require_once 'XMLStream.php';
common-pile/stackexchange_filtered
Haskell function type generalization I am studying a Haskell course since I am total beginner. There is a task which I am not able to solve although I tried many times. The task is to determine the most general type of following function: f x _ False = x f _ x y = maybe 42 (g y) x providing we know that g :: a -> [a] -> b Can anyone help me? Thank you I tried to determine y :: Bool, g :: Bool -> [Bool] -> b(?) But I am not sure what should be "x" 'cause from the first row we could say that it can be maybe 42 (g y) x but there is another "x" in the expression. So maybe the type of the f is f :: [Bool] -> [Bool] -> Bool -> [Bool]? Ugh, this is such an idiotic exercise, I wish people giving Haskell lecture would stop giving these. Let us start with the most generic type possible: the function takes three parameters, and thus returns an item, so we assume first that f has type: f :: a -> b -> c -> d We see that the third parameter matches with False so that is a Bool, so c ~ Bool. The first clause also assigns the first parameter to x and returns x, so that means that the type a of the first parameter, and that of the return type d is the same, so a ~ d. We know that maybe has type maybe :: f -> (e -> f) -> Maybe e -> f, and 42 is the first parameter so has type f. An integer literal can have any Num type, so we know Num f. Since the return type of maybe 42 (g y) x is also f and we know that this is also a, we know that f ~ a, so we can "specialize" maybe in this case to maybe :: Num a => a -> (e -> a) -> Maybe e -> a. The third parameter in maybe 42 (g y) x is x, this is the second parameter in the f call (not to be confused with the first clause), so we know that b ~ Maybe e. We also see a call g y with g :: g -> [g] -> h. The type of g y should match that of the second parameter of the maybe call, so that means that e ~ [g] and a ~ h. y has type Bool in the g y call, so that means that g ~ Bool, and thus the g function has type g :: Bool -> [Bool] -> a. Now we thus have gathered the following types and equivalences: f :: a -> b -> c -> d maybe :: f -> (e -> f) -> Maybe e -> f g :: g -> [g] -> h a ~ d c ~ Bool Num f f ~ a b ~ Maybe e g ~ Bool e ~ [g] a ~ h g ~ Bool This thus means that f has type: f :: a -> b -> c -> d -> f :: a -> b -> c -> a -> f :: a -> b -> Bool -> a -> f :: Num f => f -> b -> Bool -> f -> f :: Num f => f -> Maybe e -> Bool -> f -> f :: Num f => f -> Maybe [g] -> Bool -> f -> f :: Num f => f -> Maybe [Bool] -> Bool -> f Hence the most generic type is f :: Num f => f -> Maybe [Bool] -> Bool -> f, or we can rename the parameters to f :: Num a => a -> Maybe [Bool] -> Bool -> a. We can let ghci do the work, for example with: ghci> import Data.Maybe ghci> :{ ghci| g :: a -> [a] -> b ghci| g = undefined ghci| :} ghci> :{ ghci| f x _ False = x ghci| f _ x y = maybe 42 (g y) x ghci| :} ghci> :t f f :: Num p => p -> Maybe [Bool] -> Bool -> p This thus means that ghci confirms this type. The first thing to realize is that, for any equation, any variables defined in that equation, are scoped only to that equation. In particular, this means that the x on the first line is not related at all to the x on the second line. These are two separate variables, they just happen to have the same name. Now, you have already correctly determined that y :: Bool and g :: Bool -> [Bool] -> b for some as of yet unknown b. And therefore, g y :: [Bool] -> b The next thing to observe is that, since maybe :: p -> (q -> p) -> Maybe q -> p, which means that q ~ [Bool] (coming from the type of g y) and p ~ Int (coming from the literal 42). And therefore, g :: Bool -> [Bool] -> Int and x :: Maybe [Bool] (since it's used as the third parameter of maybe). Finally, from the second equation, we can see that the function's return type is whatever maybe returns, which is Int. And therefore, that's also the type of the first parameter, because it's being returned in the first equation. Taking all of that together: f :: Int -> Maybe [Bool] -> Bool -> Int One final stroke: I actually lied a little. The literal 42 is not really Int. Such literal can be any type that has an instance of the Num class. To account for that, let's replace our Ints in the signature with a generic type and give that type a Num constraint: f :: Num a => a -> Maybe [Bool] -> Bool -> a
common-pile/stackexchange_filtered
Create Table As With Im writing sql query and i have issue which i cannot fix. I'm trying this: CREATE TABLE a AS WITH cteCandidates (Miejscowosc, Ulica, NrDomu, KodPocztowy) AS ( SELECT Miejscowosc, Ulica, NrDomu, KodPocztowy FROM Gimnazja INTERSECT SELECT Miejscowosc, Ulica, NrDomu, KodPocztowy FROM SzkolyPodstawowe ) Select e.Lp as 'Gimnazja', s.Lp as 'Szkoly Podstawowe' FROM Gimnazja AS e INNER JOIN cteCandidates AS c ON e.Miejscowosc = c.Miejscowosc AND e.Ulica = c.Ulica AND e.NrDomu = c.NrDomu AND e.KodPocztowy = c.KodPocztowy INNER JOIN SzkolyPodstawowe s ON s.Miejscowosc = e.Miejscowosc AND s.Ulica = e.Ulica AND s.NrDomu = e.NrDomu AND s.KodPocztowy = e.KodPocztowy Order By 'Gimnazja' And errors which i get: Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword 'AS'. Msg 319, Level 15, State 1, Line 3 Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon. And i don't know why. I think that my query is proper but clearly not, and i don't understand why. Is ths SQL Server, or Oracle? It feels like you're trying to apply an Oracle style syntax (create table as) to SQL Server, which won't work. Ofcourse. You're right. I use select into and it works. Perhaps you want: WITH cteCandidates (...) SELECT e.Lp as 'Gimnazja', s.Lp as 'Szkoly Podstawowe' INTO a -- < -- table created here FROM Gimnazja AS e INNER JOIN ...; Yes. My bad. It works. But now i wonder how can i add to this table new column like: ID, which will have numeric order of rows. It is possible? CREATE TABLE is used to define a table schema. The WITH keyword is used to define a CTE retrieval of data. These are two completely different operations. If you need a table within your SQL look at http://msdn.microsoft.com/en-us/library/ms174979.aspx to see the syntax for defining it. You then may populate it with INSERT but that's highly unlikely to be from a CTE ( see below) Usually with CTEs you don't need to insert the data into a table; in the statement immediately after it you can just use the data retrieved as the table has been temporarily defined and populated for you automatically. A CTE can be used to define a VIEW - see Create view based on hierarchy / used of CTE for an example Why do you need a table? Where are you calling this from? If the CTE returns what you need you can just do a simple select from the CTE after you've defined it. If you're looking for long-term storage of the cte results, do insert into table select from cteCandidates Are you trying to create a view? Then it'd work...
common-pile/stackexchange_filtered
BeamDagRunner dependency packaging issues I was attempting to run a TFX pipeline using BeamDagRunner where I was using Dataflow to both orchestrate pipeline and execute the tfx components. However I can't execute the components and my dataflow jobs fail saying setup.py not found. I believe what is happening is my component dataflow jobs are passed the beam pipeline arg --setup_file=/path/to/setup.py but that path doesn't exist on the orchestrator dataflow machine, only on my local. Is there a way to where I can pass that in to my component pipeline args properly? This works as expected when I orchestrate with a DirectRunner since the setup.py is found on the local path. Small snippet: from tfx.orchestration.beam.beam_dag_runner import BeamDagRunner from tfx.orchestration import pipeline BeamDagRunner( beam_orchestrator_args=[ '--setup_file=./setup.py', '--runner=DataflowRunner' ] ).run( pipeline.Pipeline( ... beam_pipeline_args=[ '--setup_file=./setup.py', '--runner=DataflowRunner' ] ) ) This snippet should run the orchestrator on Dataflow as well as execute the components using dataflow. However the components fail saying setup.py can't be found. Can you explain more about your architecture and share a snippet of your code? I can't conclude much only with the current description. Edited to add in a small snippet. Let me know if you need more details. Have you tried following the instructions of this Guide on multiple file dependencies: https://beam.apache.org/documentation/sdks/python-pipeline-dependencies/ Probably try out the existing example first. Where exactly are you running this code? Cloud Composer, Apache Beam?
common-pile/stackexchange_filtered
Can not pass form data by JS to Python Flask I need to send form input data to Python Flask without reloading page or submit button. I am using XMLHttpRequest Object for sending input data but I can not receive it from Python Flask. Html part: <form method="POST"> <div class="Enter"> <div class="MM">Management Module Name:<span style="margin-left: 66px;"></span> <input type="text" id="MM" class="input" name="MM" placeholder="MM name as seen in temip_enroll -d" required> </div> </form> JS part: var input = document.getElementById('MM') input.addEventListener('keyup',e => { var mm_name = e.target.value const request = new XMLHttpRequest() request.open('POST',"Enter",true) request.send(e.target) console.log(mm_name) }) Python code: @app.route('/Enter', methods = ['POST','GET']) def enter_case(): if request.method == 'POST': MM = request.form.get('MM') print(MM) this prints "None" I could get the JS variable by using below in python MM = request.data You send unformatted raw data to the server. For this reason you can request this via request.data on the server. If you want to submit the data as a form, you can use a FormData object. Then the query after receipt is possible via request.form. const input = document.getElementById('MM'); input.addEventListener('keyup', e => { const formData = new FormData(); formData.append('MM', e.target.value); const xhr = new XMLHttpRequest(); xhr.open('POST', '/enter', true); xhr.send(formData); });
common-pile/stackexchange_filtered
Get Activerecord list of associated objects from list of objects I'm fairly new to Rails, and so I apologise if this is a daft question. I've tried looking around the web for the answer, but I'm not totally sure on the terminology and so I'm finding it really difficult to get an answer. Basically, I have two models 'Group' and 'Category'. Groups has_one Categories, and Categories belongs_to Groups. What I'm trying to do, is get a list of Categories from a list of groups. Something like this: @groups = Group.find(:all) @categories = @groups.<< insert magic code to get the categories >> So I can do something like this in a view: <% @categories.each do |cat| %> <%= cat.title %> <% end %> The problem is that I can't for the chickens of me figure out the magic code bit, or even exactly what I need to be searching for to learn how to do it. Things I've tried: @categories = @groups.categories @categories = @groups.category @categories = @groups.category.find(:all, :select => 'title') @categories = Category.find(:all, @groups.categories) @categories = Category.find(:all, @groups.categories.find(:all, :select => 'title')) And various other takes on the above. I'd really appreciate a solution and/or a pointer to where I could learn this for myself! Thank you very much I understand! It's hard to know what to search for when you don't know what it's called. This is easily done with pure Ruby, with the map instance method of the Array class: categories = groups.map{|g| g.category} A shorthand approach to this is: categories = groups.map(&:category) The map array method calls the given block for each element, and rolls all the return values into an array. This should be much faster @categories = Category.where(id: @groups.pluck(:category_id)) I cannot think of some magic code to insert, but you can quite easily create the list without this magic code. @categories = [] @groups.each do |group| @categories << @group.category unless<EMAIL_ADDRESS>end @categories now contains a list of all categories (each only included once).
common-pile/stackexchange_filtered
Adding touchscreen driver via command line I've installed Android x86 on my windows tablet, and all works apart from the touchscreen. I've found out how to add support to it, but only by using the source, which I don't really know how to, and it would take out WiFi, Ethernet, USB, etc. I was wondering if it is possible to add the support via command line? I think its similar to Ubuntu's commands to install. Here is the link to the touchscreen patch. https://groups.google.com/forum/m/#!topic/android-x86/sqORX7AAICY I don't know how to install drivers on Ubuntu either, so if somebody could tell me how, I'd appreciate trying it.
common-pile/stackexchange_filtered
Prevent related record deletion, except when parent record is being deleted I have two custom objects, call them Parent and Child. Child has a Lookup to Parent, via Parent__c. It is not a Master:Detail relation. What pattern could I use to prevent deletion of a Child record by users, except in cases where the Parent record is being deleted? In other words, I would like to implement a cascade delete, but not allow users to delete Child records themselves. Should I simply accomplish this by revoking Delete permission on Child, and implement the cascade delete in a trigger on Parent? What is the best practice? I think you can achieve it in two ways including the one you mentioned. 1) As you suggested, remove delete permission on child. It will remove delete option on child. Then write trigger on parent, to delete child also, when parent is deleted. This would be the best approach. 2) Write trigger on both child and parent. child trigger will prevent deletion by record.addError(). Then in parent object trigger, you can delete child records also. Thank you. For option #2, what would I need to do in order to override the trigger on child? Would I want some custom field that I toggle in the Before Delete on Parent, so that the Child trigger could permit the deletion? Yeah. You will need to do that. Or there is an option while creating lookup "Clear value in lookup if parent is deleted". Select that. Then in child trigger, if the lookup value is empty, allow deletion.
common-pile/stackexchange_filtered
SQLite3 table not accepting INSERT INTO statements. The table is created, and so is the database, but nothing is passed into it <?php try { //open the database $db = new PDO('sqlite:music.db'); $db->exec("DELETE from Music;"); $db->exec("INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Whatd I Say', 'Ray Charles', '1956');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Smells Like Teen Spirit.', 'Nirvana', '1991');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Hey Jude', 'The Beatles', '1968');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Johnny B. Goode', 'Chuck Berry', '1958');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Good Vibrations', 'The Beach Boys', '1966');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Respect', 'Aretha Franklin', '1967');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Whats Going On', 'Marvin Gaye', '1971');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Imagine', 'John Lennon', '1971');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('(I Cant Get No) Satisfaction', 'Rolling Stones', '1965');" . "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ('Like A Rolling Stone', 'Bob Dylan', '1965');"); //now output the data to a simple html table... //example of specifier --> WHERE First=\'Josh\'; <-- print "<table border=1>"; print "<tr><td>Title</td><td>Author</td><td>Y.O.P.</td></tr>"; $result = $db->query('SELECT * FROM Music '); foreach($result as $row) { print "<td>".$row['Title']."</td>"; print "<td>".$row['Author']."</td>"; print "<td>".$row['ReleaseDate']."</td></tr>"; } print "</table>"; $db = NULL; } catch(PDOException $e) { print 'Exception : '.$e->getMessage(); } ?> I am not sure why nothing is being inserted into the table. The file 'music.db' exists in the right path. For the record, I can only use SQlite3, no SQL allowed. PHP is allowed, so is SQLite3. What specific error are you getting? Do you see the difference between these two lines? "INSERT INTO Music(Title, Author, Release Date) VALUES "INSERT INTO Music(Title, Author, ReleaseDate) VALUES ^ There you go. Take that space out of the column name, and you should be fine. This is the content of my music.db before running the code. sqlite> .dump PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE music (Title text, Author text, ReleaseDate text); COMMIT; The code you currently have posted in your question now runs successfully without modification here. Thank you for pointing out that error, I feel silly for not finding it myself. However, this did not fix the problem. Information is still not being added into the table itself. That's the only change I had to make for it to work here. I'll look at it again later today. Some implementations of SQLite3 restrict each execute command to only one query. Example, you cannot chain the INSERT like you have done, but must call $db->exec() for each insert. That shouldn't be an issue, as the '.' at the end of each line should combine the information, and I know this 'format' has worked before. I appreciate the feedback though.
common-pile/stackexchange_filtered
When golang does allocation for string to byte conversion var testString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" //var testString = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" func BenchmarkHashing900000000(b *testing.B){ var bufByte = bytes.Buffer{} for i := 0; i < b.N ; i++{ bufByte.WriteString(testString) Sum32(bufByte.Bytes()) bufByte.Reset() } } func BenchmarkHashingWithNew900000000(b *testing.B){ for i := 0; i < b.N ; i++{ bytStr := []byte(testString) Sum32(bytStr) } } test result: With testString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" BenchmarkHashing900000000-4 50000000 35.2 ns/op 0 B/op 0 allocs/op BenchmarkHashingWithNew900000000-4 50000000 30.9 ns/op 0 B/op 0 allocs/op With testString = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" BenchmarkHashing900000000-4 30000000 46.6 ns/op 0 B/op 0 allocs/op BenchmarkHashingWithNew900000000-4 20000000 73.0 ns/op 64 B/op 1 allocs/op Why there is allocation in case of BenchmarkHashingWithNew900000000 when string is long but no allocation when string is small. Sum32 : https://gowalker.org/github.com/spaolacci/murmur3 I am using go1.6 Your benchmarks are observing a curious optimisation by the Golang compiler (version 1.8). You can see the PR from Dmitry Dvyukov here https://go-review.googlesource.com/c/go/+/3120 Unfortunately that is from a long time ago, when the compiler was written in C, I am not sure where to find the optimisation in the current compiler. But I can confirm that it still exists, and Dmitry's PR description is accurate. If you want a clearer self contained set of benchmarks to demonstrate this I have a gist here. https://gist.github.com/fmstephe/f0eb393c4ec41940741376ab08cbdf7e If we look only at the second benchmark BenchmarkHashingWithNew900000000 we can see a clear spot where it 'should' allocate. bytStr := []byte(testString) This line must copy the contents of testString into a new []byte. However in this case the compiler can see that bytStr is never used again after Sum32 returns. Therefore it can be allocated on the stack. However, as strings can be arbitrarily large a limit is set to 32 bytes for a stack allocated string or []byte. It's worth being aware of this little trick, because it can be easy to trick yourself into believing some code does not allocate, if your benchmark strings are all short. When you write something into a byte.Buffer, it allocates memory as needed. When you call byte.Buffer.Reset, that memory is not freed but instead kept for later reuse. And your code does exactly that. It marks the buffer as empty and then fills it again. Actually, there is some allocation going on, but when iterating 50000000 times, it is negligible. But if you move the declaration for bufByte into the for loop, you will get some allocations. This is what i would expect. Except above bench mark shows for smaller string, there is no allocation in both the cases. But it behaves as expected for bigger string. You should have a look at the compiled code. go test -c and then go tool objdump -s 'BenchmarkHashing' main.test.exe. @VishalKumar You actually shouldn't see an allocation in either case for the bytes.Buffer version. Bytes.Buffer has a built-in 64-byte array in its structure for handling small data sets without (extra) allocation, and neither of those tests exceed 64 bytes per write operation. If you move the bufByte.Reset() outside the for loop, I have a feeling you'll see more equitable results. @Kaedys Question is not about why no allocation for bytes.Buffer. There will be single allocation outside loop. It is as expected in result. Question is why not allocation for other case when string is small. Thinking about it, I have a hunch you're seeing a compiler optimization, tbh. Try assigning the value in that bytStr slice to another global slice to prevent the compiler from optimizing it out. As long as you're assigning to a defined global slice variable (NOT appending to the global slice), there shouldn't be any extra allocation for that assignment, just the filling of a pointer and the setting of a pair of ints in the slice header. Example: https://play.golang.org/p/FchGznDWNC
common-pile/stackexchange_filtered
perfoming right join with django queryset I just need to apply right join with query set. vdata = (VisVisitData.objects. .select_related('vpvalue','vparameter') .filter(vpvalue__vparameter=9,) .values(name=F('vpvalue__parameter_value'), visit_day=F('visit__visit_day'), question=F('vparameter'), value_id=F('vpvalue')) .annotate(data=Count('vpvalue_id')) .order_by('visit__visit_day')) above code generate following join statement. FROM vis_visit_data INNER JOIN vis_visit_parameter_values ON (vis_visit_data.vpvalue_id = vis_visit_parameter_values.vpvalue_id) LEFT OUTER JOIN vis_visits ON (vis_visit_data.visit_id = vis_visits.visit_id) But I need to do right join instead of Inner Join with vis_visit_parameter_values and vis_visit_data table. below is the snapshot of sql in which I want to make changes. INNER JOIN vis_visit_parameter_values ON (vis_visit_data.vpvalue_id = vis_visit_parameter_values.vpvalue_id) Model classes (using these 3 models in query set class VisVisitParameterValues(models.Model): vpvalue_id = models.IntegerField(primary_key=True) vparameter = models.ForeignKey('VisVisitParameters', models.DO_NOTHING,related_name='values') parameter_value = models.TextField(blank=True, null=True) class VisVisits(models.Model): visit_id = models.IntegerField(primary_key=True,auto_created=True) app_local_id = models.IntegerField(blank=True, null=True) visit_day = models.IntegerField(blank=True, null=True,db_column='visit_no') class VisVisitData(models.Model): vdata_id = models.IntegerField(primary_key=True,auto_created=True) app_local_id = models.IntegerField(blank=True, null=True) visit = models.ForeignKey('VisVisits', models.DO_NOTHING, blank=True, null=True, related_name='data') vparameter = models.ForeignKey('VisVisitParameters', models.DO_NOTHING, blank=True, null=True,related_name='parameters') vpvalue = models.ForeignKey('VisVisitParameterValues', models.DO_NOTHING, blank=True, null=True,related_name='parameters_values') Not a proper answer but in the worst case you can always make a raw SQL query (https://docs.djangoproject.com/en/2.1/topics/db/sql/) Possible duplicate of Performing a right join in django @webbyfox please re-read my comment - I'm not advising to use raw SQL if there's a way to get the same result with ORM features, I just mentions that at worst_ (=> "if there's no other way") there's at least this option - which actually exists for the very reason that Django ORM has not be designed to be a complete SQL reimplementation but to make the most common 80% stuff dead simple. @webbyfox Have added the model class as well. and I already have gone through the link that you shared. That does not fix my issues. VisVisitParameters model is missing. Also your final goal is unclear. What do you want to do with what data? A right join cannot work in Django, where joins are implemented by adding fields (=right-hand side) to objects (=left-hand side). If the left-hand side is None, you have nowhere to attach the right-hand side objects. But right joins being mirrored left joins, you just need to swap left and right for your query. How this can be done in detail depends on what fields you need and what you would use them for. Have you tried using: .filter(Q(vpvalue__isnull=True) | Q(vpvalue__vparameter=9))
common-pile/stackexchange_filtered
Swift Cannot convert value of type to expected argument type override func viewDidLoad() { super.viewDidLoad() let ref = FIRDatabase.database().reference() ref.observe(.value, with: { snapshot in self.label1.text = (snapshot.value as AnyObject)["label"] as! String }, withCancel: { error in print(error.description) }) // Do any additional setup after loading the view, typically from a nib. } Line }, withCancel: { shows a compiler error: cannot convert value of type '(_) -> ()' to expected argument type '((Error) -> Void)' Try this override func viewDidLoad() { super.viewDidLoad() let ref = FIRDatabase.database().reference() ref.observe(.value, with: { snapshot in self.label1.text = (snapshot.value as AnyObject)["label"] as! String }, withCancel: { (error:Error) -> Void in print(error.description) }) // Do any additional setup after loading the view, typically from a nib. } This would be a really good answer if there was an explanation of why the OP was getting the error and how your code fixed the error.
common-pile/stackexchange_filtered
XMLHttpRequest and fetch Limiting file upload size to 100mb So I'm working on a simple project, it's a basic file upload system. Everything is working and running fine when I test the project locally, but whenever I run this program on my server, the file upload stops working at 100mb. It isn't speed, because at 99mb it uploaded in about 20 seconds. I only get 1 progress update when logging with the following function: xhr.upload.addEventListener("progress", (e) => { const progress = Math.floor(e.loaded/e.total*100) progressBar.style.width = progress + "%" progressBar.innerHTML = progress+"%" console.log(e.loaded/e.total*100) }, false) When with a 99mb file, I get them almost every second. Again, all of this works fine on localhost with no issues, it is just on my server. I am wondering if there is some sort of client or server issue preventing this? I want to allow larger files. Thanks! client code: <form id="uploadForm"> <div class="card" style="width: 50vw;"> <div class="input-group mb-3"> <button id="upload" disabled class="btn btn-success">Upload</button> <input type="file" name="file" id="file" class="form-control"> </div> <div class="progress"> <div class="progress-bar" id="progress" role="progressbar" style="width: 0%">0%</div> </div> </div> </form> <script> const fileInput = document.getElementById("file") const uploadButton = document.getElementById("upload") const progressBar = document.getElementById("progress") uploadButton.onclick = () => { uploadFile(fileInput.files[0]) } function uploadFile(file) { console.log(file) const xhr = new XMLHttpRequest() if (xhr.upload) { const formdata = new FormData() uploadButton.disabled = true xhr.upload.addEventListener("progress", (e) => { const progress = Math.floor(e.loaded/e.total*100) progressBar.style.width = progress + "%" progressBar.innerHTML = progress+"%" console.log(e.loaded/e.total*100) }, false) xhr.onreadystatechange = (e) => { if (xhr.readyState == 4) { const response = JSON.parse(xhr.response) window.location.pathname = response.path } } formdata.append("file", file) xhr.open("POST", "/upload", true) xhr.setRequestHeader("X-FILENAME", file.name) xhr.send(formdata) } } fileInput.onchange = event => { uploadButton.disabled = fileInput.value ? false : true } </script> server code: using express and express-fileupload on npm removed a lot of the unneeded stuff import express from "express" import fileUpload, { UploadedFile } from "express-fileupload" const app = express() app.use(fileUpload({ limits: { files: 1 } })) app.post("/upload", (req, res) => { const file = req.files.file as UploadedFile const key = crypto.randomBytes(8).toString("hex") fs.mkdirSync(path.join("./uploads", key)) file.mv(path.join("./uploads", key, file.name)) res.json({ file: file.name, path: `/uploads/${key}/${file.name}` }) }) You need to configure your server to accept file uploads grater than 100mb. With loaclhost its common that you dont need to explicitly specify but on dev/prod server this is necessay. Here is a link to the stackoverflow question that answers your actual problem. https://stackoverflow.com/questions/13374238/how-to-limit-upload-file-size-in-express-js This didn't really work, I think my issue is more client side than server side, I just included server code in case it was necessary. If you go to https://files.tkdkid1000.net and upload something above 99mb you will see only one progress message in the javascript console. 99mb and lower and everything works just fine, with consistent(ish) upload progress messages. I just managed to send a 270mb file on your server (the link you provided in your comment). and on 100% completion I am getting an error code 413 - Request Entity Too Large from cloudfare, I suppose thats the server where you have hosted your application. I presume this stackoveflow question's answer addresses your problem: https://stackoverflow.com/questions/19917401/error-request-entity-too-large Then again, its not frontend related!
common-pile/stackexchange_filtered
Standard Blowfish in C# My C++ program is using a standard blowfish. My C# program is using the Blowfish encryption algorithm from here. Both applications (TCP Clients) do the same thing: receive a packet, encrypt it and then send it back. If the server recognises the packet as normal - it sends another packet, otherwise it closes the socket. I followed all functions in C++ and C# and everything is the same except the encryption. In the C++ file I have only one encryption. However, in the C# Blowfish I have BlowfishCBC BlowfishCFB BlowfishECB BlowfishSimple I didn't know which one is the one in my C++ project, so I randomly picked BlowfishECB. But it doesn't work, the server (I don't have access to it) doesn't recognize the packet as encrypted. My question: Is there a standard Blowfish for C# or if this is the only one, how do I solve this problem? The C++ blowfish code can be seen here. Whatever you do don't use the one with the backdoor or Jack Bauer will get your encrypted data. :-) actually Chloe will, but yes! watch out for those BACKDOORS! No, there is not a standard blowfish for C#. It will use whichever you tell it to. (Edit: I think I misunderstood. If you want a standards compliant blowfish for C#, I would recommend Bouncy Castle Crypto. It is a port from Java and contains most documented RFC standards. Take a look at the unit tests for examples of how to use the classes. Whenever I used it last the documentation was lacking, but the unit tests are pretty good examples of how things fit together.) The question you want to ask is which flavour of Blowfish your C++ application is using. What library are you using in the C++ application to do your encryption? Once you know that, then you can make the correct choice in your C# application. I personally encounter CBC the most. "Simple" would probably be worth trying to. You will also have to deal with things like making sure your initialization vector matches up depending on which one you use. I don't think it's CBC or CFB, because in the loop in Encode it uses 8 bytes at a time, and doesn't seem to use any data from the previous iteration of the loop. I.e. a CBC or CFB would take data from the previous block that was encoded and use it in the next block. What's the problem then? I used ECB and the server cannot recognize it. Maybe it's the "Simple" mode, never heard of that it. One or the other may be non-standard. Something maybe somebody cooked up that follows the general algorithm of blowfish, but doesn't include all the little pieces of meta-data that most standards define. This will be standards compliant on the C# side: http://www.mobilefish.com/developer/bouncycastle/bouncycastle.html I tried them all,aarnols. None of them worked. As for the encryption from bauncycastle.com - http://pastebin.com/m7cab286b Where's the Encode/Encrypt function?! I've answered this on your other thread: http://stackoverflow.com/questions/694454/how-to-use-blowfish-in-c-as-an-external-dll-in-c
common-pile/stackexchange_filtered
How to tell if item was selected or menu dismissed from comboBoxWillDismiss in NSComboBox? I have a dialog where changing the value in an NSComboBox triggers changes to other parts of the dialog. We apply the changes in controlTextDidEndEditing and comboBoxWillDismiss, but it turns out that if the user used the keyboard to select an item but then presses escape to cancel the selection, indexOfSelectedItem returns that item, even though the text doesn't get updated to that selection. How can we tell whether the user selected an item or dismissed the menu without selecting an item? Have you tried the action method instead of controlTextDidEndEditing and comboBoxWillDismiss? @Willeke: the action only triggers when pressing enter inside the textbox (not in the menu, nor when clicking in the menu) The action should be triggered when the user selects a menu item. @Willeke thanks, I see that that works in a test app. Now to figure out why it's not working in my real app. If you make an answer I'll accept it.
common-pile/stackexchange_filtered
Does every manifold with boundary admit a flat metric? There are several obstructions for a closed manifold $M$ admit a flat metric. for example Cartan-Hadamard Theorem implies the universal cover of $M$ must be $\mathbb R^n$. So if the manifold $M$ is allowed to have nonempty boundary and we do not put any restrictions on the boundary(say we do not ask it to be convex). Then can we say something? You should explain what you mean by a flat metric is there is nonempty boundary. Whatever definition you have in mind, it should imply the existence of a flat metric on the interior of your manifold. You should also assume that the manifold is connected. For connected oriented manifolds of dimension $n\le 3$ there are no obstructions since every such manifold admits an immersion in $R^n$. However, starting with dimension $n\ge 4$ there are obstructions. The simplest one is the following. Suppose that your manifold $M$ is also simply-connected. Then the existence of a flat metric on the interior of $M$ implies that $M$ admits an (isometric) immersion in $R^n$. This, in turn, implies that $M$ is parallelizable. (Actually, an open $n$-manifold is parallelizable if and only if it admits an immersion in $R^n$.) Now, take your favorite simply-connected non-parallelizable $n$-manifold with nonempty boundary, for instance, let $M$ be the complement to an open ball in $CP^2$. (It is not parallelizable because $CP^2$ is not a spin-manifold.) The interior of this manifold will not have a flat metric.
common-pile/stackexchange_filtered
Java upload file (image specifically) from a JApplet to MS MVC page I am going mad trying to find an example of file upload code in Java that will enable me to submit (POST) images to a URL from a JApplet in the same manner that an html form would post a multipart form. I have found loads of examples referencing servlets, jsp, apache but this is no good to me as my applet is being displayed in a Microsoft MVC 2 .Net project on IIS 7 Surely there has to be a simple way to do this - I am using jnlp/webstart and have no issues accessing the files I want to upload I just can't seem to find a simple sample to get me underway. Any feedback/tutes greatly appreciated, I am happy to be pointed in the right direction in regards to the appropriate Java classes/methods - this will at least give me a starting point. Cheers Rob Actually it got the better of me and starting googling again but this time for Java Submit Form rather than Java File Upload and I found this great class that I have just confirmed works correctly with great abstraction of the painful intricacies of this process. http://www.devx.com/Java/Article/17679/1954 Short Pointer: Use URL, URLConnection, setDoOutput(), and getOutputStream().
common-pile/stackexchange_filtered
How to make firefox run search in new tab rather than window from command line? Basically i want firefox.exe --new-tab --search apples ,but it's not how it works, it opens new window. There seems to be no 'native' way of doing that. However, how about firefox.exe --new-tab https://www.google.com/search?q=apples? You could replace google with your favorite search engine of course. e.g, https://duckduckgo.com/?q=test.
common-pile/stackexchange_filtered
Weird string appears in Sublime text filenames Today when I started my work with Sublime Text I just discovered that a weird string appears in my filenames that is added dynamically by Sublime. It doesn't matter if it's a newly created project or saved file. (I have a paid license, however I don't think it's about that) This is how it looks like: What causes this and is it something I should worried about or not? It's unclear from your question, but if you're concerned about the text in () in the title, that's the name of the folder/project that's open in the window and isn't part of the file name. Also you tagged the question as sublimetext3 but the image shows Sublime Text 2. I'm assuming that you're opening files on a remote (S)FTP server with FileZilla 3. As pointed out in the comment, the name in brackets is the folder/project name. In this case the folder is a temporary folder created by FileZilla, hence the fz3- prefix.
common-pile/stackexchange_filtered
Name conflicts in Vaadin WidgetSet I am working on integrating third party javascript libraries into a Vaadin WidgetSet for a Liferay portal. I am using Vaadin version 6.7.3 and Liferay 6.1. There are, so far, two independent projects and each generates a differente jar file. The inherits element is the same in both the cliend-side module descriptors: <inherits name="com.vaadin.portal.gwt.PortalDefaultWidgetSet" /> When I use the Vaadin Liferay Control Panel to recompile my WidgetSet, I see that the results of the compilation are dumped into tomcat-folder/webapps/ROOT/html/VAADIN/widgetsets/com.vaadin.portal.gwt.PortalDefaultWidgetSet, which is expected. Each Widget defines their own javascript and stylesheets in their client-side module descriptors like so: Widget 1 <script src="script_1.js"></script> <stylesheet src="styles_1.css"></stylesheet> Widget 2 <script src="script_2.js"></script> <stylesheet src="styles_2.css"></stylesheet> Since each javascript file and stylesheet is named differently, I see that the folder tomcat-folder/webapps/ROOT/html/VAADIN/widgetsets/com.vaadin.portal.gwt.PortalDefaultWidgetSet does contain script_1.js, script_2.js, styles_1.css and styles_2.css. The problem is that there are name clashes. Both widgets define styles and functions in their stylesheets/javascript files, but some names are the same, which leads to unexpected behaviour. Using firebug, I have confirmed that both stylesheets and both javascript files are loaded when using either one of the widgets. I have also checked that if I undeploy one of the widgets and recompile the widget set, it works perfectly. Since those javascripts and stylesheets are actually third party provided and have been obfuscated for my reading pleasure, it would be a bit tedious to go through all names to resolve conflicts. I have tried to force the gwt compiler to rename the widgetset by passing properties in the client-side module descriptor, like so: <set-property name="widgetset" value="custom.widgetset.FooBarWidgetSet"/> And also like so: <set-configuration-property name="widgetset" value="custom.widgetset.FooBarWidgetSet"/> I was expecting that for each widget, a different folder under tomcat-folder/webapps/ROOT/html/VAADIN/widgetsets for each widget would be created, but it didn't work. To be honest, I am not sure if this is even possible, since the Vaadin Liferay Control Panel has a field stating Active WidgetSet (see this related image) My question is: how is it possible to resolve name conflicts across different stylesheets/javascript files?
common-pile/stackexchange_filtered
BDD - how to deal with specification of cross cutting features? In BDD, how would you deal with the specification of cross cutting features? Consider for example an application that allows working on a document. There are features like editing text or adding images to the document. Now there's an additional feature "Changelog" that should provide the ability to investigate any change that has been done to a document before. Now here's my dilemma: Either the "Changelog" gets it's own spec but than it's kind of a never-ending feature. Whenever a new feature for editing the document is added I also need to add something to the "Changelog" feature. Or the "Changelog" is specified in all other features' specs by always sketching out which kind of entry should appear in the changelog after a certain operation. In this case I need to foresee the changelog feature when defining other features, and features that have already been defined and possibly implemented need refinement for the changelog feature. Any practical advice how to solve this dilemma? I handle things like this by adding an extra assert step on any scenario that is relevant. Given some set up When I use a feature Then something happens And it is reflected in the changelog as a 'something happened' entry The reason I would do it this way, rather than having a separate spec is that it sounds like the two actions are part of the same feature. It wouldn't make sense to me to split them out into separate scenarios. Any existing scenarios that would be broken by a change will be using the same step definition so will be updated when you make this test pass. The downside of doing it this way is that the relevant tests that you would want to run when making changes to the changelog functionality are distributed through your test suite. I would remedy this by tagging a relevant subset of the tests with @changelog and creating a test run to run only these tests.
common-pile/stackexchange_filtered
How can I write only certain lines of a file in Perl? I am looking for a way to read an input file and print only select lines to an output file in Perl. The lines I want to print to the output file all begin with xxxx.xxxx.xxxx, where x is an alphanumeric character (the periods are periods, not wildcards). The lines do not all have the same ending, if that makes a difference. I'm thinking something like the following (the condition of the if statement is all that is really missing as far as I can tell). open(IN, "<$csvfile"); my @LINES = <IN>; close(IN); open(OUT, ">$csvnewfile"); print OUT @LINES if ([line starts with xxxx.xxxx.xxxx]); close(OUT); Thanks in advance! Here is a better way to loop through your lines. It avoids loading your whole input file into memory at once: use strict; use warnings; open my $fhi, '<', $csvfile or die "Can not open file $csvfile: $!"; open my $fho, '>', $csvnewfile or die "Can not open file $csvnewfile: $!"; while (<$fhi>) { print $fho $_ if m/^ \w{4} \. \w{4} \. \w{4} /x; } close $fho; close $fhi; Keep in mind that the \w character class also includes underscores. To avoid underscores: print $fho $_ if m/^ [a-z\d]{4} \. [a-z\d]{4} \. [a-z\d]{4} /xi; Style tips: use lexical filehandles check the result of open also a good idea to check the result of close on a handle opened for writing See below: #! /usr/bin/perl use warnings; use strict; die "Usage: $0 old new\n" unless @ARGV == 2; my($csvfile,$csvnewfile) = @ARGV; open my $in, "<", $csvfile or die "$0: open $csvfile: $!"; open my $out, ">", $csvnewfile or die "$0: open $csvnewfile: $!"; while (<$in>) { print $out $_ if /^\w{4}\.\w{4}\.\w{4}/; } close $out or warn "$0: close $csvnewfile: $!"; using grep grep "^\w\{4\}\.\w\{4\}\.\w\{4\}\b" file That's on the command line, not in perl BTW. It's what grep is for. If you don't have a modern grep you may need egrep or an older regexp like ^[0-9a-zA-Z.]{14} or whatever. yes, on the command line. I assume the grep tag is the *nix grep, not Perl's own. if ($_ =~ m/^\w{4}\.\w{4}\.\w{4}/i) I think. My perl's a bit rusty. From perlfaq5's answer to How do I change, delete, or insert a line in a file, or append to the beginning of a file? The basic idea of inserting, changing, or deleting a line from a text file involves reading and printing the file to the point you want to make the change, making the change, then reading and printing the rest of the file. Perl doesn't provide random access to lines (especially since the record input separator, $/, is mutable), although modules such as Tie::File can fake it. A Perl program to do these tasks takes the basic form of opening a file, printing its lines, then closing the file: open my $in, '<', $file or die "Can't read old file: $!"; open my $out, '>', "$file.new" or die "Can't write new file: $!"; while( <$in> ) { print $out $_; } close $out; Within that basic form, add the parts that you need to insert, change, or delete lines. To prepend lines to the beginning, print those lines before you enter the loop that prints the existing lines. open my $in, '<', $file or die "Can't read old file: $!"; open my $out, '>', "$file.new" or die "Can't write new file: $!"; print $out "# Add this line to the top\n"; # <--- HERE'S THE MAGIC while( <$in> ) { print $out $_; } close $out; To change existing lines, insert the code to modify the lines inside the while loop. In this case, the code finds all lowercased versions of "perl" and uppercases them. The happens for every line, so be sure that you're supposed to do that on every line! open my $in, '<', $file or die "Can't read old file: $!"; open my $out, '>', "$file.new" or die "Can't write new file: $!"; print $out "# Add this line to the top\n"; while( <$in> ) { s/\b(perl)\b/Perl/g; print $out $_; } close $out; To change only a particular line, the input line number, $., is useful. First read and print the lines up to the one you want to change. Next, read the single line you want to change, change it, and print it. After that, read the rest of the lines and print those: while( <$in> ) # print the lines before the change { print $out $_; last if $. == 4; # line number before change } my $line = <$in>; $line =~ s/\b(perl)\b/Perl/g; print $out $line; while( <$in> ) # print the rest of the lines { print $out $_; } To skip lines, use the looping controls. The next in this example skips comment lines, and the last stops all processing once it encounters either END or DATA. while( <$in> ) { next if /^\s+#/; # skip comment lines last if /^__(END|DATA)__$/; # stop at end of code marker print $out $_; } Do the same sort of thing to delete a particular line by using next to skip the lines you don't want to show up in the output. This example skips every fifth line: while( <$in> ) { next unless $. % 5; print $out $_; } If, for some odd reason, you really want to see the whole file at once rather than processing line-by-line, you can slurp it in (as long as you can fit the whole thing in memory!): open my $in, '<', $file or die "Can't read old file: $!" open my $out, '>', "$file.new" or die "Can't write new file: $!"; my @lines = do { local $/; <$in> }; # slurp! # do your magic here print $out @lines; Modules such as File::Slurp and Tie::File can help with that too. If you can, however, avoid reading the entire file at once. Perl won't give that memory back to the operating system until the process finishes. You can also use Perl one-liners to modify a file in-place. The following changes all 'Fred' to 'Barney' in inFile.txt, overwriting the file with the new contents. With the -p switch, Perl wraps a while loop around the code you specify with -e, and -i turns on in-place editing. The current line is in $. With -p, Perl automatically prints the value of $ at the end of the loop. See perlrun for more details. perl -pi -e 's/Fred/Barney/' inFile.txt To make a backup of inFile.txt, give -i a file extension to add: perl -pi.bak -e 's/Fred/Barney/' inFile.txt To change only the fifth line, you can add a test checking $., the input line number, then only perform the operation when the test passes: perl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt To add lines before a certain line, you can add a line (or lines!) before Perl prints $_: perl -pi -e 'print "Put before third line\n" if $. == 3' inFile.txt You can even add a line to the beginning of a file, since the current line prints at the end of the loop: perl -pi -e 'print "Put before first line\n" if $. == 1' inFile.txt To insert a line after one already in the file, use the -n switch. It's just like -p except that it doesn't print $_ at the end of the loop, so you have to do that yourself. In this case, print $_ first, then print the line that you want to add. perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt To delete lines, only print the ones that you want. perl -ni -e 'print unless /d/' inFile.txt ... or ... perl -pi -e 'next unless /d/' inFile.txt If you don't mind leaving it as a command line 1 liner: perl -ne "print if /^.{4}[.].{4}[.].{4}/" csvfile.csv > csvnewfile.csv perl -ne 'print if /^\w{4}\.\w{4}\.\w{4}\b/' file > newfile.csv
common-pile/stackexchange_filtered
Swift NSMutableDictionary removeobject I have a NSMutableDictionary I initiated like this var data = NSMutableDictionary() later I am trying to remove the value because I want to move every value up one key. This is the code I am doing let buttonRow = sender.tag let setCount = buttonRow + 1 var keyedPath: String = NSString(format: "Set%d", setCount) as String let value: AnyObject? = data.valueForKey(keyedPath) var goodSetsCount: String = NSString(format: "Set%d", goodSets.count) as String goodSets.setValue(value, forKey: goodSetsCount) //data.setValue("Hello", forKey: keyedPath) //data.removeObjectForKey(keyedPath) On both of the lines that are commented out I get this error *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object' If you can help me find the bug or a way to remove objects and move them up the dictionary it would be greatly appreciated. You're trying to remove objects from a different dictionary that isn't mutable (an NSDictionary). Find it and initialize it as mutable. Use mutableCopy when you are setting data Why don't you just use an array? @Paulw11 I am not using and array because its a dictionary and then all the values are another dictionary @rebello95 This is the line of code I used to initialize it data = NSJSONSerialization.JSONObjectWithData(returnData, options: nil, error: &jsonError) as! NSMutableDictionary By default, NSJSONSerialization.JSONObjectWithData returns immutable containers. You need to specify the option NSJSONReadingOptions.MutableContainers in order to retrieve a mutable containers. In fact, in Swift 1.2 your assignment data = NSJSONSerialization.JSONObjectWithData(returnData, options: nil, error: &jsonError) as! NSMutableDictionary should throw a run time exception because you are using a forced downcast to NSMutableDictionary that will fail, although I am not sure if this is enforced with Cocoa classes. If you change the line to data = NSJSONSerialization.JSONObjectWithData(returnData, options: .MutableContainers, error: &jsonError) as! NSMutableDictionary your code should work. As indicated by @Pauwlw11 you are trying to modify immutable dictionary object. Apart from that your code could be clear if you use with Swift constructs rather than just plainly translating it from Objective-C. var data = NSJSONSerialization.JSONObjectWithData(returnData, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as NSMutableDictionary In button click handler: let setCount = 1 var keyedPath = "Set\(setCount)" let value = data[keyedPath] var goodSetsCount = "Set\(setCount)" data[keyedPath] = "Hello" data.removeObjectForKey(keyedPath)
common-pile/stackexchange_filtered
Is 'jdbcType' necessary in a MyBatis resultMap? When we use Mybatis , in <select> ...</select> statment I know we need set jdbcType beacuse the IN variable maybe null, but when I see the document of Mybatis, I found jdbcType in <result>...</result> under ResultMap. the document of the jdbcTpe in <result>...</result> was: ... The JDBC type is only required for nullable columns upon insert, update or delete. This is a JDBC requirement, not a MyBatis one. So even if you were coding JDBC directly, you'd need to specify this type – but only for nullable values. the bold word say only required for nullable columns upon insert, update or delete. BUT,the element of result is used in select neither insert, update or delete. so ,is it necessary use jdbcType in <result>...</result> ? Most of the time, no. Why? Read on. If you want to use a null as a JDBC parameter value you need to specify the jdbcType. That's a restriction of the JDBC specification you can't avoid. Therefore, if there's even a remote possibility a JDBC parameter could have a null value, then yes, specify it. This does not apply to parameters preprocessed by MyBatis inside MyBatis tags, like the ones you use in the "test" attribute of the < if > tag. Those ones are not JDBC parameters. Now, for the columns you read. These are the ones you are interested on. The thing is most of the time you don't need them. MyBatis will pick the right JDBC type for you. Well... this has been the case for me 99.999% of the time. What about the other 0.001%? For some exotic column types -- that you rarely use -- MyBatis may pick the wrong JDBC type for you. The designers of MyBatis thought about this case, and give you the chance of overriding it. I think I remember an XML type database column that MyBatis was unsuccessfully trying to read as a VARCHAR, but I don't remember which database. Bottom line, don't use it when reading columns, unless MyBatis reads exotic data type columns (XML, UUID, POINT, etc.) the wrong way.
common-pile/stackexchange_filtered