INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Python Tesseract with OpenCV and PIL not detecting characters I'm attempting to image recognize the text from a league of legends lobby so I can data mine. I guess it's not recognizing the font, as the output of the program is: Doel seen aay Source code: import numpy as nm import pytesseract import cv2 from PIL import ImageGrab, Image def imToString(): # Path of tesseract executable pytesseract.pytesseract.tesseract_cmd ='C:\\Program Files\\Tesseract-OCR\\Tesseract.exe' while(True): cap = ImageGrab.grab(bbox =(242, 884, 561, 990)) cap.save('test.png') tesstr = pytesseract.image_to_string( cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY), lang ='eng',config='--psm 7') print(tesstr) imToString() The image I'm using to test
It seems you need some preprocessing to image. Try this one. import numpy as np import cv2 img = cv2.imread('wXQMF.png', 0) print(img.max(), img.min()) ret, thr1 = cv2.threshold(img, 10, 255, cv2.THRESH_BINARY_INV) kernel_size_row = 3 kernel_size_col = 3 kernel = np.ones((3, 3), np.uint8) erosion_image = cv2.erode(thr1, kernel, iterations=1) #// make erosion image cv2.imwrite('a.png',thr1)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, python 3.x, opencv, python imaging library, python tesseract" }
Including multiple .txt files into httpd.conf using regex? I want to be able to include multiple virtualhost files into httpd.conf. I know that it's possible to include one using something like: `include virtualhost-1.txt` However, I want to be able to import all virtualhost files within a certain directory, without needing to hardcode the include statements. Is there an appropriate command/syntax for this? I know the directory and have a suitable regular expression: ^.+-[0-9]+\.txt
The syntax of the Include directive is the following: Include file-path|directory-path|wildcard You can do for example: Include /usr/local/apache2/conf/vhosts/dom1-*.conf to include all configuration starting with `dom1-` from the directory `/usr/local/apache2/conf/vhosts/`. Note that you can use wildcards but you cannnot use a full regex.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "regex, apache, include, httpd.conf" }
Empty file called 'sudo' in home directory I have encountered empty file just called 'sudo' in home directory. The file size is 0 bytes. Is it safe to just delete this file?
Yes, that's not a system file. It was probably created by mistake. Check its owner and creation date, that'll tell you more about it. You can safely delete it. At worst, you can recreate it via the command `touch ~/sudo`. Config files and other system files usually start with a dot (`.`). These are the so-called dotfiles, and you should not touch them unless you know what you're doing.
stackexchange-unix
{ "answer_score": 5, "question_score": 3, "tags": "sudo, opensuse" }
How to mock method with any arguments? I write following row in my test: when(Product.fromNode(any(Node.class), any(Locale.class),anyString())).thenReturn(productMock); I see following error message: > you cannot use argument matchers outside of verification or stubbing It is impposible because I can't use `any` at this case. But I don't know what concrete argument will be passed to the method but I know that I should handle it same. What can you advice for me ?
Problem was that I used `PowerMockito.mockStatic` but I used RunWith annotation different than: @RunWith(PowerMockRunner.class)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, unit testing, mocking, mockito, powermock" }
GTK+3 + Python: "Loading..." dialog I have a function in my main application that looks like this: def foo(stuff): a_line_that_takes_a_while(stuff) return result I'm trying to add a dialog to show before a_line_that_takes_a_while and destroy it right after that line was executed. I've tried: def foo(stuff): dialog = Gtk.MessageDialog(...) dialog.show_all() a_line_that_takes_a_while(stuff) dialog.destroy() return result But surprisingly, the dialog shows up just when a_line_that_takes_a_while was already executed. Of course I can't use dialog.run() because that'd block my application's main loop. Any ideas?
All that your calls to GTK are really doing is queuing up actions that happen during the main loop. A dialog is somewhat of a special case where when you call dialog.run() to blocks permitting certain updates. Your foo function instructs GTK to create a dialog then destroy it, before it even got started trying to do the work. Threads should do the job. The biggest gotcha here is that GTK is NOT thread safe. Therefore be careful if you decide to use native python threading. Also, if you are doing disk operations consider GFile's asynchronous callbacks. They might save you a little bit of wheel re-inventing.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, gtk" }
the derivative for F-norm of a matrix From the matrix cookbook, I got: $\frac{\partial}{\partial X} ||X||_F^2 = \frac{\partial}{\partial X} Tr(XX^H) = 2X$ Now I want to compute $\frac{\partial}{\partial X} ||X-Y||_F^2 = \frac{\partial}{\partial X} Tr\left((X-Y)(X-Y)^H\right)$, but I am stuck here, any idea?
For convenience, define a new variable $$\eqalign{ W &= X-Y \cr }$$ Write the function in terms of this new variable and the Frobenius (:) Inner Product and find its differential $$\eqalign{ f &= W:W \cr df &= 2W:dW \cr &= 2W:dX\cr }$$Since $df=\big(\frac{\partial f}{\partial X}:dX\big),\,$ we can identify $$\eqalign{ \frac{\partial f}{\partial X} &= 2\,W \cr &= 2\,(X-Y) \cr }$$ Note that setting $Y=0,\,$ recovers the Cookbook result.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "matrix calculus" }
Proper way to submit a password i'm using VueJS and sending in my username and password HTTPS to my backend endpoint.... trouble is I can see the password in the Chrome Inspector which seems not that safe? Am I handling things wrong? thanks
If you are sending it with HTTPS you are doing it right. All communications between your authentication service and the client are encrypted. An attacker is normally someone sitting between your browser and the service, not someone who can inspect your HTTP request like you did in your Chrome developer tools. If you still don't feel comfortable about this, launch any login page of the well-known applications, for example, github.com and do Inspect, you will see password transferred without encryption.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "forms, vue.js, post, passwords" }
Command line like Angular Cli I'would like to create something like Angular Cli with some commands we can create a beaultful scaffold and with others parameters like ng new ng g c ... we can create other components, modules ... etc How Can I search a way to create this or Study the steps to create this?
You probably want to look at the Schematics feature of the Angular CLI. You can find information about it in this discussion, in this blog post and in this blog post.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "node.js, command, angular cli" }
IPhone: Why are Bulk Inserts in Core Data so slow? So I'm making an iphone app that just has a thousand entries that I'm reading from an xml file into core data. But inserting these records takes like 10 seconds on the device. It's pretty ridiculous. The schema is very simple, just one table. I.e., no relationships or anything. To see what I mean, you can just go to: 1\. File -> New Project -> Navigation Based Application (make sure 'use Core Data' is checked) 2\. Now inside RootViewController.m go to the 'viewDidLoad' and at the very end of this method add: for (int n = 0; n < 1000; n++) [self insertNewObject]; And just run the app. Even in simulator it takes 5 seconds and on devices it's twice as slow. Any ideas??
Argh... I found the reason. I shouldn't save the context after each insert. My bad.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "iphone, objective c, ipad, core data" }
How to access right-clicked file in Eclipse RCP using commands? I implemented an entry in the context menu of my Eclipse RCP application. The function should export the right-clicked file in another format. I already implemented the transformation-function. What I need, is the path and name of the right-clicked file. This is what I have: @Override public Object execute(ExecutionEvent event) throws ExecutionException { Shell shell = new Shell(); DirectoryDialog dialog = new DirectoryDialog(shell); String saveToPath = dialog.open(); String filePath = // ... how to access the clicked file? exportOtherFormat(filePath, saveToPath); return null; } So basically I would like to know, how I can access the right-clicked file, specially the path and name.
Get the current selection in your handler and adapt it to an `IFile` with: ISelection sel = HandlerUtil.getCurrentSelection(event); if (sel instanceof IStructuredSelection) { Object selObj = ((IStructuredSelection)sel).getFirstObject(); IFile file = (IFile)Platform.getAdapterManager().getAdapter(selObj, IFile.class); // TODO your code }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, path, eclipse plugin, eclipse rcp, filepath" }
Django - get the query by date using postgresql "to_date" I need to get raw objects using Django .objects.raw functions like : SELECT * FROM TEST_APP_DOCUMENT WHERE DATE BETWEEN to_date('0000-02-07','YYYY-MM-DD') AND to_date('2027-02-15', 'YYYY-MM-DD') in pgAdmin select return good result, but when i put it to django there is an error: File "C:\Users\User\Desktop\test_task\test_app\views.py", line 110 queryset = Document.objects.raw('SELECT * FROM TEST_APP_DOCUMENT WHERE DATE BETWEEN to_date('0000 - 02 - 07','YYYY - MM - DD') AND to_date('2027 - 02 - 15', 'YYYY - MM - DD')') ^ SyntaxError: invalid syntax what is the syntax problem?
You're passing a string literal with single parenthesis (`'`) while having them inside the string itself. You must escape them or use `"`: queryset = Document.objects.raw("SELECT * FROM TEST_APP_DOCUMENT WHERE DATE BETWEEN to_date('0000 - 02 - 07','YYYY - MM - DD') AND to_date('2027 - 02 - 15', 'YYYY - MM - DD')") * * * You can escape with backslash, as you'd expect. For example, `'foo\'bar'` will yield `foo'bar`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, django, postgresql, to date" }
convertir imagen base64 a file en angular 9 Estoy usando < para recortar imagenes subidas desde angular a mi api en node, el problema es que las transforma a base64 y aunque esta todo bien, no puedo subirlas asi al servidor asi que estoy tratando de convertirlas a tipo File let nuevo = new FormData(); let split = this.croppedImage.split(",")[1]; let blob = new Blob([atob(split)], { type: "image/png" }); let file = new File([blob], "imageFileName.png"); nuevo.append("tipo", "perfil"); nuevo.append("user", this.id.toString()); nuevo.append("image", file); this.dataService.nuevaImage(nuevo).subscribe( res => console.log(res), err => console.log(err) ) hasta el momento de usar el split esta todo ok, pero al transformarla a File y enviarla a la api se ve negro y en local dice que el formato no es compatible. PD: La api no arroja error
pude solucionarla con < es un poco engorroso el tema del decodificado pero esto me sirvio
stackexchange-es_stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "nodejs, angular" }
What is the name of this terminology? Let $G$ be the group generated by a set $X=\\{x_1,\cdots,x_n\\}$. Then each element can be (not necessarily uniquely) written as a product of the form $x_{j_1}^{e_1}\cdots x_{j_k}^{e_k}$, where each $x_{j_i}\in X$ and $e_i=\pm1$, $i=1,\cdots,k$. Among all possible such expressions, let $k$ be the number of terms in the "shortest" one. For example, if $G=\mathbb{Z}/7\mathbb{Z}*\mathbb{Z}/4\mathbb{Z}=\\{x,y\mid x^7=y^4=1\\}$, then the "$k$" for the element $x^5y^{-3}x^{-1}=x^{-1}x^{-1}yx^{-1}$ is $4$. I am wondering if there is any standard terminology of the "$k$" defined above. Is it called the "weight" of an element?
The most common name is the _length_ of the group element, which is defined to be the minimum length of words that define the element. Of course it depends on the choice of finite generating set, but changing $X$ will decrease or increase the length by at most a constant factor.
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "abstract algebra, group theory, terminology" }
What are the best option for a pager when building on Rails? I am building an education app and I want a pager that uses the buttons "previous" and "next" to go back and forth on the lessons I created. Many Google results show me to use the kaminari gem but kaminiari seems to be more on the pagination(like pages 1, 2, 3...) side rather than the pager that I am looking for. What gem or tool would be the best in my situation?
You can copy kaminari's views into your app/views and edit _paginator partial. For example, change this: == paginator.render do nav.pagination = first_page_tag unless current_page.first? - each_page do |page| - if page.left_outer? || page.right_outer? || page.inside_window? == page_tag page - elsif !page.was_truncated? == gap_tag = last_page_tag unless current_page.last? to that: == paginator.render do nav.pagination = prev_page_tag unless current_page.first? = next_page_tag unless current_page.last?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -5, "tags": "ruby on rails, ruby, rubygems" }
yii2 : how to keep the url same in kartik grid view? I am using kartik grid view to display my data in yii 2 with pjax enabled. Every time, I search a data in the grid view, the search is done using ajax but the url keeps changing. Is there a way to keep the url unchanged? Please help me with the solution. Here is my code: <?php use kartik\grid\GridView;?> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'pjax'=>true, 'pjaxSettings'=>[ 'neverTimeout'=>true, ], 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'hotel_id', 'name', 'address', 'phone_no', 'contact_person', // 'email_address:email', // 'website', ['class' => 'yii\grid\ActionColumn'], ], ]); ?>
You can disable pushState feature like this: 'pjax' => true, 'pjaxSettings' => [ 'options' => [ 'enablePushState' => false, ], ],
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 6, "tags": "php, yii2" }
I/O prioritization in Java I'd like to use of the Vista+ feature of I/O prioritization. Is there a platform independent way of setting I/O priority on an operation in Java (e.g. a library, in Java 7) or should I revert to a sleeping-filter or JNx solution? Do other platforms have a similar feature?
This is the kind of thing that is difficult for Java to support because it depends heavily on the capabilities of the underlying operating system. Java tries very hard to offer APIs that work the same across multiple platform. (It doesn't always succeed, but that's a different topic.) In this case, a Java API would need to be implementable across multiple versions of Windows, multiple versions of Linux, Solaris, and various other third party platforms. Coming up with a platform independent model of IO prioritization that can be mapped to the functionality of the range of OS platforms would be hard. For a now, I suggest that you look for a platform specific solution that goes outside of Java to make the necessary tuning adjustments; e.g. use Process et al to run an external command, or do the work in a wrapper script before starting your JVM.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "java, io" }
Seek n number of bits into a file (C++) I have a file which contains data which is not byte aligned and I want to seek (e.g. 3 bits) into the file and then start reading chars into a buffer. Is there an "easy" way to do this? I want to avoid bit-shifting each char in the buffer if possible.
Unless you're using a very interesting platform, your file contains bytes. And you read it one byte at a time. So there is no way to do it without bit shifting. The simplest way to **hide** the bit shifting I could think of, is to make an input iterator that stores the previously read byte and does the shift "behind the scenes".
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "c++, binaryfiles" }
Update Vendors in Sylius - Imagine Bundle Error (Symfony2) I am trying to install Sylius - Open Source E-Commerce based on Symfony2 from this link The composer can successfully pull the project files from github but while updating vendors i get this error [UnexpectedValueException] 'C:\wamp\www\sylius\vendor/liip/imagine-bundle/Liip/ImagineBundle/3e0aa0b8b 218dab8fc7a752ff6d3a41e.4' is not a zip archive. I have zip and git installed on my system. Please help with your solutions and suggestions. Thanks in advance.
Ok..so i did this I cleared the cache from the project folder and ran the command: php composer.phar update And now all seems to be working fine without any error. All vendors successfully updated and downloaded the remaining ones. Hope this helps someone
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 5, "tags": "symfony, e commerce, composer php, sylius" }
iPhone 6+ does not have navigation bar back button item I have developed an app in Xcode 5 before the new versions of iOS and iPhone 6/6+. It was working well in Xcode 5 with its simulators (iPhone retina 4 inches, etc.) but now that I have updated to Xcode 6 and I run my app in new simulators, it works great in the iPhone 4s, 5, 5s, and 6 simulators but not in the iPhone 6+ simulator. I have a table view in my first view controller. If you tap on a cell the push segue brings you to an another view controller. There are two problems: 1. In every view controller, the top of the object (e.g. table view or a UIImage) is not shown and the scene is deficient. 2. when we go to the second view controller there is no back button item on the top in order to return to the home view controller. How can I fix this? What is the problem?
I believe there is a bug in the iPhone 6+ simulator - I have also observed a similar behavior, but only on the simulator. Running the app on a real iPhone 6+ works as expected - the navigation bar is there as are all the buttons.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "objective c, iphone, xcode" }
How do I remove a "missing" MP3 file from my iPhone? I have an MP3 file located on my iPhone that I want to delete but am unable to find in the Music app. The track only appears when I connect my iPhone to my Mac and go to (Devices > iPhone > Music) in iTunes. There, it shows a list of all of my voice memos and songs in my music library. I have already deleted all of the songs from my music library using (Settings > General > Usage > Music...) on my iPhone, but it did not delete the file in question. I know absolutely for certain that it is not a voice memo. There is now a circle with an exclamation mark next to the file in iTunes, but secondary clicking on it does not offer a remove or delete option. Does anyone have any suggestions on removing the file?
I managed to successfully remove the listing by downloading the iOS file explorer iFunbox and poking around inside of the iPhone's raw filesystem. The process I took was rather unscientific, but after deleting many of the files and directories located in directories such as Downloads, MediaAnalysis, and Music and iTunes-related folders, the bad listing disappeared. My suspicion is that the file was appearing because of a bad SQL entry, and that deleting all of the .sqlite files fixed the problem.
stackexchange-apple
{ "answer_score": 0, "question_score": 3, "tags": "iphone, itunes, music" }
Get unique value using STRING_AGG in SQL Server 2017 The following query: SELECT T1.REPORTED_NAME, STRING_AGG(CAST(T1.ENTRY AS NVARCHAR(MAX)),',') AS Average_Str FROM Table1 T1 INNER JOIN Table2 T2 ON T1.ID = T2.ProdID WHERE T1.ENTRY like '%[A-Za-z]%' GROUP BY T1.REPORTED_NAME ORDER BY T1.REPORTED_NAME Returns: REPORTED_NAME Average_Str Report_1 Failed,Failed,Failed,Failed,Failed, Report_2 Passed,Passed,Passed I would like my final output to have only unique value as below REPORTED_NAME Average_Str Report_1 Failed Report_2 Passed Thank you in advance for your help
You can go for first getting unique values and then applying string aggregate like below: ;WITH CTE_UniqueValues ( SELECT Reported_Name, Entry, MAX(ID) AS ID FROM Table1 GROUP BY Reported_Name, Entry ) SELECT T1.REPORTED_NAME, STRING_AGG(CAST(T1.ENTRY AS NVARCHAR(MAX)),',') AS Average_Str FROM CTE_UniqueValues T1 INNER JOIN Table2 T2 ON T1.ID = T2.ProdID WHERE T1.ENTRY like '%[A-Za-z]%' GROUP BY T1.REPORTED_NAME ORDER BY T1.REPORTED_NAME
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, sql server" }
How to read in long list of parameters into GDB/DDD I have written this C++ program which has a fairly lengthy list of parameters which I supply at the BASH command line. However for debugging with GDB, it is a pain to type `run param1 param2 ....` at the GDB command prompt for debugging my executable. So is there a way to store this lengthy list into a text file and tell GDB to look at this text file for the parameters for supplying the arguments to my **a.out**.
> So is there a way to store this lengthy list into a text file and tell GDB to look at this text file for the parameters for supplying the arguments to my a.out Put this into the text file: set args foo bar baz ... and then (gdb) source commands.txt Alternatively: gdb --args ./a.out foo bar baz ... (gdb) run
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "linux, bash, unix, gdb" }
Can I use is null instead of isInitialized in Kotlin? The following Code A is from the project play-billing-samples. Can I use is null instead of `isInitialized` in Kotlin? just like Code B **Code A** lateinit private var localCacheBillingClient: LocalBillingDb val inappSkuDetailsListLiveData: LiveData<List<AugmentedSkuDetails>> by lazy { if (::localCacheBillingClient.isInitialized == false) { localCacheBillingClient = LocalBillingDb.getInstance(application) } ... } **Code B** lateinit private var localCacheBillingClient: LocalBillingDb val inappSkuDetailsListLiveData: LiveData<List<AugmentedSkuDetails>> by lazy { if (localCacheBillingClient == null) { localCacheBillingClient = LocalBillingDb.getInstance(application) } ... }
Yes, you can, but you'd have to change the type of the variable to `LocalBillingDb?` and get rid of the `lateinit` modifier: private var localCacheBillingClient: LocalBillingDb? = null val inappSkuDetailsListLiveData: LiveData<List<AugmentedSkuDetails>> by lazy { if (localCacheBillingClient == null) { localCacheBillingClient = LocalBillingDb.getInstance(application) } ... }
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "kotlin" }
Objective C:Object Deallocated while key value observers were still registered with it I am hitting the below error after I added 2 additional fields to my core data model. CarPark_CarPark_ was deallocated while key value observers were still registered with it. Observation info was leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger. Here's the current observation info: <NSKeyValueObservationInfo 0x1b6510> ( <NSKeyValueObservance 0x19b210: Observer: 0x1a8cf0, Key path: coordinate, Options: <New: NO, Old: NO, Prior: YES> Context: 0x0, Property: 0x1b7e00> ) I am a little lost on what to do next. Any guidance on this will be greatly greatly appreciated! Please let me know what other information is required.
To set the breakpoint open the breakpoints tab in Xcode 4 (Breakpoints window in Xcode 3) and add a new symbolic Breakpoint for the symbol "NSKVODeallocateBreak" Use the debugger console to print the observer at the adress given in the observation info Observer: 0x19af20 po 0x19af20 This should give some valuable information about the observer. Override addObserver:forKeyPath:options:context: in your custom CarPark class and set a breakpoint to see the exact location of the observing being established.
stackexchange-stackoverflow
{ "answer_score": 28, "question_score": 17, "tags": "objective c, ios, core data, key value observing" }
How to create table in Hive with specific column values from another table I am new to Hive and have some problems. I try to find a answer here and other sites but with no luck... I also tried many different querys that come to my mind, also without success. I have my source table and i want to create new table like this. Were: * **id** would be number of distinct counties as auto increment numbers and primary key * **counties** as distinct names of counties (from source table)
You could follow this approach. A CTAS(Create Table As Select) with your example this CTAS could work CREATE TABLE t_county ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE AS WITH t AS( SELECT DISTINCT county, ROW_NUMBER() OVER() AS id FROM counties) SELECT id, county FROM t; You cannot have primary key or foreign keys on Hive as you have primary key on RBDMSs like Oracle or MySql because Hive is schema on read instead of schema on write like Oracle so you cannot implement constraints of any kind on Hive.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 4, "tags": "hadoop, hive, hql" }
What's this length-tunned shape in this circuit? Here is an image of an LNB circuit: ![image]( Probably you heard something about length-tunned traces that they use in high-frequencies PCBs. There is something similar to the length-tunned traces in the PCB(blue circle) but it's not length-tunned trace because they are cutted-out. What could be they?
It is a special transmission line filter topology, called "hairpin filter" because the line sections look like hair pins. It is most likely used as a band-pass filter of some sort in this circuit. More on these filters can be found on the wikipedia page for distributed element filters: < The following document shows a few examples for hairpin band-pass filters: <
stackexchange-electronics
{ "answer_score": 5, "question_score": 1, "tags": "pcb design, high frequency" }
Get the first given symbol from the word counting from the back I'm a beginner in VBA and need some help with my school assignment. Function CountfromBack(tekst As String, sümbol As String) As Integer CountfromBack = 0 lengthie = Len(tekst) For i = 1 To lengthie s = Mid((tekst), i, 1) If s = sümbol Then CountfromBack = i Exit For End If Next i CountfromBack = (lengthie - CountfromBack + 1) End Function Here is what the function currently does. for the text in B9 and the symbol "e" it gives me the answer 6, but it should be 1, considering I'm looking for the first given symbol reading from the back. Also, if the symbol isn't in the cell, how should I return 0? ![
Iterate from the last letter to the first: Function CountfromBack(tekst As String, sümbol As String) As Integer Dim lengthie as Long, i as Long, s as String CountfromBack = 0 lengthie = Len(tekst) For i = lengthie To 1 Step -1 s = Mid((tekst), i, 1) If s = sümbol Then CountfromBack = lengthie - i + 1 Exit Function End If Next i End Function ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "vba, excel" }
The default route is not added by rmnet interface when the WiFi interfaces are UP I'm developing a router, that uses a sim-card for the WAN connection. When the rmnet interface is up and WiFi interfaces are down, the default route is created successfully: root@OpenWrt:/# route Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface default 10.59.127.70 0.0.0.0 UG 0 0 0 rmnet_data0 But **when the WiFi interfaces are up as well, the default route is absent in the routing table**. Of course, I can add it manually and 'ping' the network, but it is not a solution. I can't even imagine where the problem can be. I will be very grateful for any ideas and advice. Thank you in advance.
I found out the problem. It is in WiFi configuration. I have WPS enabled by default on every WiFi interface. That affects in some way the rmnet interfaces (or routing tables). However, if WPS is disabled by default the default route is created successfully. I will continue investigation.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "routes, wifi, router, openwrt, cellular network" }
Calculating the limit of a sequence? In one of the exercises I got, I was required in order to proceed to calculate the limit: $\lim_{n\to \infty} (\frac 1 {e^n} (1+ \frac 1 n)^{n^2})$ I checked in the solution sheet to see if the answer will give me a clue, and the answer is supposed to be $\frac 1 {\sqrt e}$ but I still can't see how I get there... Can anyone please give me a clue? :)
$\frac 1 {e^x} (1+ \frac 1 x)^{x^2}=\left(\frac{\left(1+\frac{1}{x}\right)^x}{e}\right)^x=e^{x\left(ln\left(1+\frac{1}{x}\right)^x-lne\right)}=e^{\frac{ln\left(1+\frac{1}{x}\right)^x-1}{\frac{1}{x}}}$ Now apply L'Hôpital's rule twice on the exponent and you will get the result.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "calculus, sequences and series, limits" }
How to open a new screen at the time of accepting the alert? My first screen has the alert message when I accept the alert I have to show the next screen and pass some values to that screen to show that values.I am very new to android. new AlertDialog.Builder(this) .setTitle("File accept!") .setMessage("Do you Want to open "+name+" file !!") .setPositiveButton("Open", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dlg,int acc) { //here i need to open a new screen } }) .setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dlg, int sumthin) { // do nothing – it will close on its own } }) .show(); } \--Thanks in advance
You want to create an Intent with the constructor that takes a context and a Class object. In this Intent you have to specify the class that handles the new screen. This class has to extend Activity. To get the file name to the new screen use intent.putExtra to attach a data bundle to that intent. In your new activity you can use getIntent.getExtras() to retrieve the data attached to the Intent.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "android" }
How did Brother Kwame's words almost make that 'whole pig' (white cops) nightmare worthwhile? In _BlacKkKlansman_ (2018), both eating, Patrice speaks to Ron Stallworth: > Patrice: When we dropped Brother Kwame off at the airport, he told me that the Black Power movement needed strong sisters like me to lead the fight against capitalist oppression and the politicians and pigs who perpetuate it. **His words almost made that whole pig nightmare worthwhile**. How did Brother Kwame's words almost make that 'whole pig' (white cops) nightmare worthwhile?
It means that Brother Kwame's words were so inspiring that it almost made it worthwhile going against the cops (the white pig nightmare mentioned). Obviously people generally don't _want_ to fight cops for no good reason, so his words were almost a good enough reason to fight.
stackexchange-movies
{ "answer_score": 2, "question_score": -1, "tags": "plot explanation, dialogue, blackkklansman" }
Is it possible in PHP for an array to reference itself within its array elements? I'm wondering if the elements of array can 'know' where they are inside of an array and reference that: Something like... $foo = array( 'This is position ' . $this->position, 'This is position ' . $this->position, 'This is position ' . $this->position, ), foreach($foo as $item) { echo $item . '\n'; } //Results: // This is position 0 // This is position 1 // This is position 2
They can't "reference themselves" per se, and certainly not via a `$this->position` as array elements are not necessarily objects. However, you should be tracking their position as a side-effect of iterating through the array: // Sequential numeric keys: for ($i = 0; $i < count($array); ++$i) { ... } // Non-numeric or non-sequential keys: foreach (array_keys($array) as $key) { ... } foreach ($array as $key => $value) { ... } // Slow and memory-intensive way (don't do this) foreach ($array as $item) { $position = array_search($item, $array); }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "php, arrays" }
Dart IO process.run('pbcopy', []) - How to use? I am a beginner and I have a problem. I would like to use dart:io process with the command "pbcopy". I tried this but it seems that it doesn't work : import 'dart:io'; main() { Process.run('echo', ['hello', '|', 'pbcopy']); }
`echo` is an internal command from your shell and `|` is also a shell-only feature, not a command parameter. If you're on Linux or Mac, you can try Process.run('bash', ['-c', 'echo hello | pbcopy']);
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "dart" }
Intersection of is the kernel of a homomorphism/representation. Let $\phi: G → GL_d(\mathbb{C})$ be a homomorphism. And let the kernel be $N = {\\{g\in G: \phi(g) = I}\\}$, and $N $ is a normal subgroup of $G$. Show that for the coset representation , $N = \cap_ig_iHg_i^{-1}$, where the $g_i$ are the transversal. Proof: Suppose $N$ is the kernel of $\phi$. Then $N = gNg^{-1}$ for all $g\in G$. And let $H$ be a subgroup of $G$. Then $\cap_ig_iHg_i^{-1} = g_1Hg^{-1}\cap g_2Hg_2^{-1}.....\cap g_kHg_k^{-1}$. So recall $gg_iH = g_iH$. Can someone please help?
Let $G$ be a group, and $H$ a subgroup. Then $G$ acts on $G/H = \\{gH|g\in G\\}$ by left translation. You seek the kernel of this action (your question uses the language of linear representations, but this is overkill, since the kernel of an action is the same as the kernel of its associated linear representation). Now let $a\in G$ be in this kernel, meaning that $agH = gH$ for all $g\in G$ (or just for $g$ running over a set of representatives, if you will). Then $g^{-1}agH=H$, so $g^{-1}ag \in H$, which is equivalent to $a\in gHg^{-1}$. So indeed $a\in \bigcap gHg^{-1}$. The converse is even easier (and you can actually reason directly through equivalences, though I wouldn't advise to do so if you're uneasy with the material).
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "abstract algebra, normal subgroups, group homomorphism" }
PHP Youtube API v3 Missing Description in Playlist Items I'm not getting the description form my uploaded videos when i query them via Youtube Data API v3 using OAuth 2.0 and the sample code provided here < Could this be a bug? None of my videos are private and the only thing that is missing from the response is the video's description! I'm using the PHP library and the "part" parameter is snippet (don't know if this helps). Thanks in advance.
I believe this is intended, since video descriptions are not displayed when viewing playlists on YouTube. If you wish to include the description of your uploaded videos, consider using YouTube API v3 Search: list instead. An ellipsis-truncated description will be provided for your videos under _snippet/description_. Again, this behaviour is similar to searching on YouTube, where descriptions are cut off. If a full description is required, you'll need to use Videos: list. Alternatively, use version 2 of the API: **youtube_username** /uploads?max-results=50&start-index=1.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "youtube, google api, youtube api" }
RMSE vs. Correlation Coefficient I am testing my model by 2 different experiments: 1. No test set: I just use cross-validation on the training set. 2. I take a subset of the dataset and use it as a test set (I use the same subset in the training data as well). Now what happens is that I get a high correlation coefficient on the first experiment and higher RMSE. But I get lower correlation coefficient on the second one but lower RMSE. I am not sure how should I evaluate these results. Can I say that a. I get a lower correlation coefficient on the second experiment because I am using a smaller dataset? b. RMSE was smaller in the second case because our model was able to explain a smaller subset of the dataset better? Am I on the right track?
In terms of a. the correlation is automatically standardised for sample size. No correlation is even explained as being bigger or larger because of a certain sample size. In terms of b. what RMSE you are referring to is a little ambiguous. But the fraction of explained variance is the square of the correlation, so that explanation sounds at least muddled: RMSE is a measure of unexplained variation, which is a failure, rather than a success.
stackexchange-stats
{ "answer_score": 1, "question_score": 1, "tags": "machine learning, computational statistics" }
How to modify array elements? I have `labels` which is an array. I want to replace `Catch & Bowled` to `Caught & Bowled` similarly `run` to `Run Out`. What I tried was loop through array and replace that particular string. Code: let labels = Object.keys(wickets); <--- wickets array of objects of type let console.log(labels); for(var i=0;i<labels.length;i++){ if(labels[i] === 'catch & bowled'){ labels[i] = 'Caught & Bowled'; }else if(labels[i] === 'run'){ labels[i] = 'Run Out' } } When I again `console.log(labels)` they are not modified why so ? Screenshot: ![enter image description here](
It is because comparison of string is js is case sensitive, Try the following if(labels[i].toLowerCase() === "catch & bowled".toLowerCase()) If you want to check for equality of values of string than it is always better to convert both the string characters to same case. Like in this example both the strings are converted to a string of lowercase characters.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -1, "tags": "javascript, ecmascript 6" }
Redshift limitation on LIKE operator in CASE statement I am running into an issue where if I have more than 15 `LIKE` operators within a case statement, I get an error `java.lang.StackOverflowError`. Here is an example of what I am doing against a table with 60 million rows: SELECT CASE WHEN field LIKE '%value%' THEN 'result' WHEN field LIKE '%value2%' THEN 'result2' .... 14 more of those END I haven't seen this limitation documented anywhere. Any ideas how to get around this?
This turned out to be a driver issue. I was initially using 1.2.16.1027 and upgraded to 1.2.20.1043 and I am no longer receiving the error.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "amazon redshift" }
1004 Method 'Range' of object '_Worksheet' failed The following assignment statement is in the code for a commandbutton on a form: Range("AvailabilityDataModified").Value = "No" AvailabilityDataModified is a single-celled named range on a sheet called "Controls". This statement executes properly with no error. I also have three occurrences of the following statement (virtually identical to the one above) that reside in a sheet's code for multiple event handlers: Range("AvailabilityDataModified").Value = "Yes" My problem is the 3 occurrences of the 2nd instance of code generate the 1004 Method 'Range' of object '_Worksheet' failed error while the first does not. This might be a problem with scope; however, I don't believe you need any additional reference info when assigning a value to a named range. I'm at a loss at this point.
Use Worksheets("Controls").Range("AvailabilityDataModified").Value = "Yes" instead. Inside a worksheet object Range refers to SheetName.Range, not to the workbook-scoped Excel.Application.Range object. This causes the range "AvailabilityDataModified" to be restricted to the sheet of the worksheet object. Because no cells of "AvailabilityDataModified" are in the sheet the Range returns a error.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "vba, excel" }
How to get multiple resultset in knex? I am using SQL server and I have one procedure which returning two result set. Following is the result set. { records : [ {name : "abc", age: 26}, {name : "def", age: 22}, {name : "ghi", age: 29} ], totalCount : 10 } I am using Knex in node.js for Databese Operation. I am able to get **records** (which is first result set of my SP result) but can not able to get **totalCount**. below is my code for executing stored procedure. const getUserList= async ({arg1, arg2, knexInstance}) => { const results = await knexInstance.raw( `exec dbo.getUsers @arg1=?, @arg1=?, [ arg1, arg2 ] ); I already go through with this but it did not work for me.
There is no way to get multiple result sets in knex. As explained in the knex issue that you linked, you have to use mssql or tedious driver directly to be able to do it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "node.js, knex.js" }
Download Manager for Mac OS X? IS there a download manager for Mac OS X that allows me to interrupt and resume large downloads? (I'm trying to download the Apple Developer Tools update, but a 3+ GB file size seldom plays nicely with my internet connection. **EDIT:** I prefer a free solution if possible. **EDIT2:** I need it to be able to download from the Apple Developer site, which requires authentication. The downloads there are huge - my bandwidth isn't. Using Folx and authentication, I successfully downloaded ... drumroll please ... an intermediate HTML file.
I highly recommended using iGetter it was much better than other one. * iGetter But also you can use: * Download Accelerator Plus (DAP) * Folx (free) but can pay money and upgrade it to pro * Speed Download (paid one) : nice one with a lot of features. * Leech (paid one) : clean UI. * Folx (free one) : download & torrents manager. Besides, if you use Terminal and can install packages, I recommend AXEL. I myself use this one. After installation is complete you can use the command below to do what you want. axel -n 100 -s 5242880 "your download link" The -n 100 show the number of your connection to the server and the -s 5242880 use for limiting the speed,-s 5242880 in above example will try to keep the average speed around 5242880 (5120 Kilobyte per/sec).
stackexchange-superuser
{ "answer_score": 12, "question_score": 14, "tags": "macos, download manager, download" }
preg_match_all -> string: var a = 100 I'm trying parse string: var a = 100 var b = 150 var c = test I was trying create regex: preg_match_all('/var( )*=( )*([^\s]+)/', $code, $get_zmienne); preg_match_all('/var(\s)*=(\s)*([^\s]+)/', $code, $get_zmienne); and this is wrong.
Have a try with: preg_match_all('/var\s*(\w+)=\s*(\S+)/', $code, $get_zmienne); This will match: `var`: litteral `var` `\s*`: 0 or more white spaces `=`: litteral `=` `(\w+)`: group1 that contains one or more word characters ie:`[a-zA-Z0-9_]` `\S+`: one or more non space character.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -4, "tags": "php, regex" }
What user interface element would I use to take and crop a photo on the iPhone? I'd like to be able to take a photo from the iPhone's camera, select a polygon within that photo, crop the photo to match, and then fit the resulting image to the screen. What user interface element would you suggest for me to start doing this? I'm a Java programmer and just getting started with the iPhone, so I'm not sure what to use.
You should start by looking at sample code from Apple for UIImagePickerController to start getting the image. When you are comfortable with that you can start thinking about how to crop the image.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "iphone, cocoa touch, ios4" }
How can I skip Helm/IDO when I want to open Dired? When I call Dired with `M-x` `Dired`, I got the IDO window with the file structure and when I press Enter, he goes to Dired. When I disable IDO in Emacs, and I do `M-x` `Dired` again, I got the `Helm-dired-mode`. When I confirm the current directory path, the Dired open anyways. Is there a way to skip IDO/Helm directly when I want to open Dired?
Thanks for all the answers. After inspecting it further, I found the option `dired-jump` which does the same as `dired` but without the IDO/Helm. The docstring tells the following Jump to Dired buffer corresponding to current buffer. If in a file, Dired the current directory and move to file's line. If in Dired already, pop up a level and goto old directory's line. In case the proper Dired file line cannot be found, refresh the dired buffer and try again. When OTHER-WINDOW is non-nil, jump to Dired buffer in other window. Interactively with prefix argument, read FILE-NAME and move to its line in dired. Thanks for the help anyway! :)
stackexchange-emacs
{ "answer_score": 4, "question_score": 3, "tags": "helm, dired, ido" }
simple question concerning NSString adding multiple strings I have a fairly simple question concerning NSString however it doesn't seem to do what I want. this is what i have ` NSString *title = [NSString stringWithformat: character.name, @"is the character"]; ` This is a line in my parser takes the charactername and inserts in into a plist , however it doesn't insert the @"is the character" is there something I'm doing wrong?
Your code is wrong. It should be : NSString *title = [NSString stringWithformat:@"%@ is the character", character.name]; assuming that character.name is another `NSString`. Read the Formatting String Objects paragraph of the String Programming Guide for Cocoa to learn everything about formatting strings.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "objective c, nsstring" }
Does all processes that consume energy from outside result in negative entropy change? In any spontaneous process entropy increases.In biological systems disordered elements are converted into highly ordered tissues etc(-ve entropy change) which make up living organisms. But, it requires energy from the sun(ultimately). So,does that mean all processes that consume energy from outside result in negative entropy change? Endothermic reactions consume energy in the form of heat from outside so, is all endothermic reactions causing the entropy to decrease?
**Entropy increases in a spontaneous evolution of an isolated system… other than that, there is no general law on the evolution of entropy.** * * * > does that mean all processes that consume energy from outside result in negative entropy change? No. When you heat a solid, it increases its entropy. > endothermic reactions causing the entropy to decrease? Endothermic reactions which cause entropy to decrease have both ∆H positive and ∆S negative, so they will have a positive ∆G, i.e. their are not thermodynamically favorable.
stackexchange-chemistry
{ "answer_score": 3, "question_score": 1, "tags": "thermodynamics, entropy" }
distance calculation between two ports with PostgreSQL and Postgis I'm using PostgreSQL with PostGis and have shapes of all countries loaded. How can I calculate the shortes sea route between two ports (without intersecting a country shape) is there a 'standard solution'?
you could use graph theory so long as you have a set of sea-lane type way-points defined. these would be points along the ship travel lanes with maybe nautical miles between each one indicated. then use a min path algorithm to find the best travel lane. of course inreal life this problem has many more variables than just distance i would think.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "postgresql, postgis" }
Script to activate and enter details in System Dialog I am trying to write a script which can enter details in the system dialog. But i am not able to access it. Is there a way to access this? I tried getting the list of all the system dialogs and alerts but still I am not able to catch this. tell application "System Events" to ¬ get name of every application process ¬ whose role description of window 1 is "system dialog" system dialog
I am not sure following is what you asked for, but try yourself: tell application "System Events" to tell process "SecurityAgent" return name of every window end tell
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "macos, applescript" }
How to come up with an interval for this Big Oh Problem? This is from Discrete Mathematics and its Applications !enter image description here I'am trying to use the interval method like what was shown in this example !enter image description here Here is my work so far: I noticed that when $x > 5$, $2^x > 17$, so when $x > 5$, $2^x + 17 \leq 2^x + 2^x \leq 2*2^x$. This shows that $2^x + 17$ is $O(2^x)$, because there exist constants $C = 2$ and $x_0 = 5$ such that when $x > 5$, $2^x + 17 < 2 * 2^x$. The next step was to show that $O(2^x)$ is in $O(3^x)$. To do this, I took a function $2^x$ that is in $O(2^x)$, and first observed that when $x > 1$, $2^x \leq 3^x$, so $2^x$ is in $O(3^x)$ because there exist constants $C = 3$ and $x_0 = 1$ such that when $x > 1$, $2^x < 3^x$. Did i do everything to show that $2^x + 17$ is $O(3^x)$? Is there a more efficient way to do this, to go straight to $O(3^x)$ and not $O(2^x)$ to $O(3^x)$ like I did ?
For all $x>1$ we get $$17+2^x \le 2^5+2^x \le 2^5\cdot 2^{x} \le 2^5 \cdot 3^{x}=O(3^x).$$ The notation of big O is useful for sufficiently large values of $x$, to give an idea of the order of magnitude of some function.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "computer science, computational complexity" }
Updating my application across thousands of nodes. What are the standard tools/procedures? Are there any standard practice/procedures/tools to perform a software update (OTA) of my c++ application across thousands of battery powered IoT nodes. I don't want to reinvent something, and wondering if a proven/standard tool or solution already exits. Ideally something that would be power fail-safe. Edit: I would like to make a custom smart-speaker (Alexa or Google Home) type devices, powered by battery, using RPi Zero W
The professional OTA updaters include: Mender, rauc, swupdate These are power fail safe, as they do an "A/B" update. Two images: A and B, where A is the current running image stays flashed, until the new B image is confirmed to be flashed in the OTA partition. The following presentation gives a good overview of differences between pushing debugging images, ci images, and production images: <
stackexchange-raspberrypi
{ "answer_score": 1, "question_score": 1, "tags": "apt, update, rsync" }
Javascript IF statement not returning as expected I'm trying to write a simple javascript code to generate a random door (either door1 or door2, and if door1 is generated, the phrase 'you win' appears. Right now, despite if door1 or door2 is generated, the output is still 'you lose'. What am I doing wrong? let doors = ["door1", "door2"] function selectDoor() { const randomDoor = doors[Math.round(Math.random())] console.log(randomDoor) } if(selectDoor() === "door1") { console.log('you win') } else { console.log('you lose') }
You're not returning `randomDoor` from `selectDoor`. function selectDoor(){ const randomDoor = doors[Math.round(Math.random())] console.log(randomDoor) return randomDoor } Returning nothing is equivalent to returning `undefined` which is a falsy value, effectively a `false` when used with comparison operators.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery" }
Получить имена доступных сетевых папок Есть сервер с несколькими расшаренными папками, например \\MyServer\Directory1 \\MyServer\Directory2 ... \\MyServer\DirectoryN как можно получить список всех этих папок если \\MyServer не доступна?
Попробуйте через WMI: GetObject("winmgmts:\\MyServer\root\CIMV2").ExecQuery("SELEC‌​T Path, Name, Caption FROM Win32_Share Where Type = 0")
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, .net" }
linux tar command -t option to show max-depth=1 may be a tar.gz file has content many filefolder,the filefolder may have a lot of file and filefolder,I want to show the tar.gz file only the first depth.How to write this command. for example ,I want to show this tar.gz file ![enter image description here]( It's only to show auth,help,xa,install.txt,license.txt.release.xt,sqljdbc.jar,sqljdbcr.jar How to write this command?
Since `tar t` itself does not have an option to limit the depth to which the tarball contents are listed, you need to take the full listing and reduce it to what you want. Since this means `tar` will list the full archive in any case, _it will not be faster than a full listing_. tar tzf <tarball> | sed "s@/.*@@" | sort -u Note that, for all well-behaved tarballs, this will only give _one_ entry, of the same name as the tarball. Real-world example: $ tar tjf gcc-5.2.0.tar.bz2 | sed "s@/.*@@" | sort -u gcc-5.2.0 Tarballs that splatter the extraction directory with files and subfolders are commonly called tarbombs.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "linux, shell, tar" }
Is the "omniscient-omnipotent-omnipresent" definition of God consistent? God is commonly defined as an omniscient (infinite knowledge), omnipotent (unlimited power), omnipresent (present everywhere) entity. Is there any logical inconsistency in this definition? I have seen several paradoxes like below > Does God know what he's going to do tomorrow? If so, could he do something else?" If God knows what will happen, and does something else, he's not omniscient. If he knows and can't change it, he's not omnipotent. > > "Can 'an omnipotent being' create a stone so heavy that it cannot lift it?" _Do they mean that the defintion of God ( as commonly held) is logically inconsistent?_
Your example can be more simply stated by not involving the future: > Can god create something that is so heavy that he can not move it? The answer of course is "Yes". But then, you say, he would not be omnipotent as he can not move it. But that's wrong. He can. Because he is omnipotent. Hence: > An omnipotent being is able to move that which he is unable to move. If you want to call this consistent or not is up to you. It is inconsistent as seen from a logical framework. But it is consistent with the standpoint that an omnipotent being by definition can do _anything_ , **including breaking the laws of logic**. God is generally claimed to have created everything, including logic, so he is not susceptible to them, or any form of reason. That also per definition makes God unknowable, unreachable and unscientific. He can not even be discussed in any form of meaningful way with human words, rendering your question and my answer equally meaningless.
stackexchange-philosophy
{ "answer_score": 86, "question_score": 62, "tags": "logic, epistemology, theology" }
2-way Graph Partitioning problem We have a graph $G=(V,E)$ and we need to divide this graph into two clusters $A$ and $B$. Some pairs of vertices $u$, $v$ should not be in the same cluster, and we define an edge $(u,v) \in E$. The total cost of a solution is the total number of edges with endpoints both in the _same_ cluster. My goal is to find an algorithm that returns the optimal solution that _minimizes_ this total cost. The solution does _not_ have to be balanced in the sense that the clusters should be of the same size. I was wondering what the general name for this problem is and what a proper algorithm is that can solve this efficiently. By a colleague I was pointed into the direction of using a (nice) _tree decomposition_.
You're looking for a **maximum cut** in the graph - maximizing the number of edges between the partitions minimizes the number within them. Unfortunately, Max Cut is **NP** -hard on general graphs and also hard to approximate. There's a polynomial-time algorithm on planar graphs, if that's of any use to you.
stackexchange-cs
{ "answer_score": 2, "question_score": 0, "tags": "algorithms, graphs, terminology, partition problem" }
Static variable memory destruction A static variable is defined in a function.Can v destroy its memory outside that function?
If you're talking about C, then no you can't "destroy its memory" - all your static variables are going to be around for as long as your program is running.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "memory, variables, scope, static variables" }
What is the value of $a+b$ Satisfies these two equations. Let $a,b\in \mathbb R$ Such that : $$\cases{a^3-3a^2+5a-17=0 \\\ b^3-3b^2+5b+11=0}$$ Find the value of $a+b$ I’ve tried to add the two equation and factoring $a+b$ but it didn’t help me. I think that letting $f(x)=x^3-3x^2+5x-17$ And $g(x)=b^3-3x^2+5x+11$ Could help . **claim :** $a+b=2$
Let $a=c+1, b=d+1$ Then the equations becomes $$c^3+2c-14=0$$ $$d^3+2d+14=0$$ Add them up, $$c^3+d^3+2c+2d=0\iff (c+d)(c^2-cd+d^2)+2(c+d)=0\\\\(c+d)(c^2-cd+d^2+2)=0$$ Since $c^2-cd+d^2+2$ clearly $>0$ we know $c+d=0$ so $a+b=2$
stackexchange-math
{ "answer_score": 5, "question_score": -1, "tags": "algebra precalculus, contest math" }
Showing that complement of $\mathbb{Q}^2$ in $\mathbb{R}^2$ is connected > The complement of $\mathbb{Q}^2$ in $\mathbb{R}^2$ is connected. I have to solve this problem. At first, I tried to solve as following: For any 2 disjoint neighborhoods of $\mathbb{R}^2$ \ $\mathbb{Q}^2$, whose union is $\mathbb{R}^2$ \ $\mathbb{Q}^2$, one of them must be empty. But I couldn't deduce the last goal. How can this problem be solved?
Take any two point $A,B$ from $\mathbb{R}^2\setminus\mathbb{Q}^2$, join them by a straight line, draw perpendicular bisector of $AB$,Now You start chosing points on the Perpendicular bisector of $AB$ and join to $A$ and $B$ by straightline. How many points you can chose to join $A$ and $B$ like this way? Do you see your set is path connected?
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "general topology" }
add child screen to parent screen with rmq In the on_load method of HomeScreen class i want to do something like rmq.append(LoginScreen, :login_form). LoginScreen inherits from PM::FormScreen. ![enter image description here]( Since I am not implementing initWithFrame in LoginScreen the app crashes. This has been done in < but with motion kit. How can I achieve the same with rmq?
You're going to need to create an instance of the screen and then add its view. def on_load @login_screen = LoginScreen.new addChildViewController @login_screen rmq.append(UIImageView, :logo) rmq.append(@login_screen.view, :login_form) end The `addChildViewController` ensures that lifecycle events are properly called on `LoginScreen`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ruby, rubymotion, rubymotion promotion" }
Create RelNode for SELECT 1 Which API should I use in `org.apache.calcite.tools.RelBuilder` to produce `RelNode` representing query `SELECT 1` in BigQuery?
RelNode r = builder.values(new String[] {"c"}, 1).build();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "apache calcite" }
STRING_AGG with Union All I want to do STRING_AGG with union all. here are my tables. SELECT C1 = P1 FROM elt.Api UNION ALL SELECT C1 = E1 FROM elt.Api2 for one table STRING_AGG is working fine. SELECT STRING_AGG(CONVERT(NVARCHAR(max), ISNULL(P1,'N/A')), ',') AS C1 FROM elt.Api how should I do same with UNION ALL? Do I have to write the cursor for this ?
Try Something like this SELECT STRING_AGG(CONVERT(NVARCHAR(max), ISNULL(c1,'N/A')), ',') AS C1 FROM (SELECT C1 = P1 FROM elt.Api UNION ALL SELECT C1 = E1 FROM elt.Api2 ) A
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, tsql" }
Вырезать короткие слова и исключением Мне нужно вырезать короткие слова (до 2х символов), но оставить цифры. Делаю так: `/\b([а-я]{0,2})\b/u` \+ preg_replace. Как мне эту регулярку задать исключения? Типа кг, см и т.п.
Используйте негативный просмотр вперед например: /\b(?!кг|см)([а-яё]{0,2})\b/ui Тест < P.S. Группу захвата можно убрать <
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, регулярные выражения" }
Where does the IBM OmniFind Yahoo! search engine cache Domain-IP resolutions? We are using Omnifind on Windows 2008 Server for site search, and after one website has migrated to another server - same domain, another IP (DNS update has been more than 24 hours ago, Omnifind server knows new IP) -, Omnifind keeps searching the old IP, meaning it has cached the name resolution somewhere. But where? Omnifind uses Apache Lucene technology, so maybe someone has an idea about that one which might serve as a hint? Restarting the service or the server doesn't change that behaviour.
No answer, and we haven't found out. However, a workaround is to block access to the "old" IP, the apparently Omnifind will do another DNS check and find the new IP while keeping the index (we didn't do this in the first place because we were afraid that Omnifind might decide to delete the index).
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "lucene" }
Scala nested for loop over Streams I've written the following Scala code to compute a distance matrix: def dist(fasta: Stream[FastaRecord], f: (FastaRecord, FastaRecord) => Int) = { val inF = fasta.par for (i <- inF; j <- inF) yield (f(i, j)) } This code works great in the sense that I get excellent parallelism. Unfortunately, I'm doing twice as much work as I need to as f(i, j) is the same as f(j, i). What I want to do is start j at i+1 in the stream. I can do this with indices: for (i <- 0 until inF.length - 1; j <- i+1 until inF.length) yield(f(inF(i), inF(j))) However, asking for inF.length I've heard is not good on a Stream and this doesn't give me the parallelism. I think there should be a way to do this iteration, however, I haven't come up with anything yet. thanks! jim
I think using `zipWithIndex` might get you what you're looking for: def dist(fasta: Stream[FastaRecord], f: (FastaRecord, FastaRecord) => Int) = { val inF = fasta.zipWithIndex.par for ((x, i) <- inF; (y, j) <- inF; if i <= j) yield f(x, y) } By filtering `i <= j` you can eliminate the repeated (mirrored) cases. However, I do get a warning when I compile this: warning: `withFilter' method does not yet exist on scala.collection.parallel.immutable.ParSeq[(FastaRecord, Int)], using `filter' method instead I don't think that would really be an issue, but I also don't know how to supress the error...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "scala, parallel processing, iteration" }
To edit or not to edit? I wonder this when I read questions a lot on SO. Is it common convention when you see a new user make a question with bad formatting (not using proper code casing on SO or not using latex math formatting on mathematics) to edit their question for them so the formatting is nice and pretty, or to post a comment and ask them to format their question? Does it deserve a down vote for a poorly formatted question?
There are many tools at your disposal to help improve the site. Most of them involve positive reinforcement. Editing a question not only helps you receive rep for suggested edits, but it also drastically improves the quality of the content on the site, the quality of the answers, and the results of the question. Editing the question may result in something that helps other people for years to come. A downvote is negative: it costs the question asker rep. Chances are, it's not going to help improve the question. My suggestion is to use downvotes as a last resort or when there is no fix. If a question can be fixed, and you know how to fix it, then you should do so. Tools: * Downvotes * Edit * Flags * Comments - Leave a tip for how to improve the question, or ask for clarification. Keep in mind that not every brand new user understands that he/she can format code on this site. As they gain more rep, they'll learn more about how the system works.
stackexchange-meta
{ "answer_score": 9, "question_score": 15, "tags": "discussion, markdown, etiquette" }
Linking VS and Git. Getting error message ![enter image description here]( I try and do a Commit I get this error message. An error occurred. Detailed message: Could not open 'C:/Users/Nate/AppData/Local/Comms/UnistoreDB/store.vol': The process cannot access the file because it is being used by another process. I don't understand because the local repository I set up is C:\Users\Nate\Desktop\GitRepo\NewRepo Also after I get the error message the button is grayed out. Everything works fine on my school computer but not on my computer. I am using version 2015. Thank you
My guess is Visual studio is trying to get your email address in order to initialise your git config, but, frankly, who knows, it's a black box. Try closing all Email applications, or, create your git repository directly using the git command line.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, git" }
Selectively hiding series in a C# chart Lets say I have a chart with 2 series on it. Then for each series, I have a checkbox to say whether I want to see them or not. Assume that I originally plot both, and afterwards, wanted to hide either of them. What is the best way to do this? I know I could just `Clear()` it and then `AddXY()` them back in, but is there a faster way to do it? My attempted ideas: 1\. Set a visibility property to true/false depending on checkbox. There is No visibility Property 2\. Copy Points Collection to a variable, clear, and put back in. `Series[].Points` is read-only 3\. Copy Series to a variable, clear the points, and put back in. Apparently it stores the Series as a reference when I try this, and I cannot find a copy command. So I am apparently going about this the wrong way. How would you dynamically allow chart to have different series hidden?
To hide a series in MSChart, use the `Enabled` property this way : msChart.Series["Series"].Enabled = false; and to show it again : msChart.Series["Series"].Enabled = true; So you dont need to remove points and re-add them.
stackexchange-stackoverflow
{ "answer_score": 27, "question_score": 11, "tags": "c#, charts, customization, mschart" }
Float sum with javascript > **Possible Duplicate:** > Is JavaScript's Math broken? I'm calculating the sum of several float values using javascript and... I've noticed a strange thing never seen before. Executing this code: parseFloat('2.3') + parseFloat('2.4') I obtain **4.699999999999999** So... what sould I do to obtain a correct value? (supposed that this is incorrect...)
Once you read what _What Every Computer Scientist Should Know About Floating-Point Arithmetic_ you could use the `.toFixed()` function: var result = parseFloat('2.3') + parseFloat('2.4'); alert(result.toFixed(2));​
stackexchange-stackoverflow
{ "answer_score": 185, "question_score": 96, "tags": "javascript, math, floating point" }
screen -r and screen -list only show last screen My problem is pretty much as the title describes it. I am running `ssh` session and on my server I screen for multitasking. My issue here is that I have at least 4 screens open and detached, but `screen -r` connects only the the last screen I have visited. `screen -list` also only lists the last screen, as if there is only one screen open. However, once I am in one of the screens, I can freely switch between them with `Ctrl+A` and `N` and all of them are there. What am I doing wrong? Thanks.
`screen -ls` shows the sessions, and there are `windows` (also called "screens") inside the session that can be scrolled by `CTRL-A N` or listed by `CTRL-A w` or `CRTL-A "`
stackexchange-serverfault
{ "answer_score": 2, "question_score": 0, "tags": "linux, terminal, gnu screen" }
calling a javascript function inside a .js file which resides in a iframe i have a default.aspx page which contains a iframe, whose source is set to a default.htm page. The default.htm in turn has a link to a script file(). Is it possible to access the functions in the script file in my default.aspx page ?if so how ??
Assuming that default.htm is on the same domain as default.aspx, you can use the following javascript to call functions in default.htm: var myIframe = document.getElementById("iframe_id").contentWindow; myIframe.func1(); myIframe.func2(); myIframe.func3();
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, iframe" }
problem with error handling when I use readlink I'm having an issue when I run following command. I tried both way but didn't get desired output. `if{[catch {file readlink $ver}]}` then it gives output as "if{1} unknown command". `if{[catch [file readlink $ver]]}` then it gives error, it does not catch error. I want it to catch error & run body part of `if` block.
Correct syntax for the `catch` block: if { [catch {file readlink $ver} errmsg] } { puts $errmsg # will print the actual error } else { continue the body part!!! }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "tcl" }
session.get_expiry_age() never decreases I set `SESSION_COOKIE_AGE` to some value in my `settings.py` and I want to retrieve the time that is left before a session dies by using `session.get_expiry_age()` from a view. However, it seems the returned value is never changing between different calls (at different times): it stays at `SESSION_COOKIE_AGE`, meaning the session will never end(?) Is it a normal behaviour? I would like to notify the user whenever the session is about expire and I don't really see how to do it.
Yes, this is the intended behaviour. See this ticket: < You can use `get_expiry_date()` instead and calculate it from there.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "python, python 3.x, django, django sessions, django cookies" }
Creamer returns I use Nestle Coffee-mate creamer. I have noticed when I fix my thermos to go, the creamer has no problem dissolving when I first fix them, but let's say after 5 hours when the coffee has gotten cold, the creamer clumps back up. Why does this happen?
I substituted your question in a quick google search for "solution chilled why do powders reappear" - and after reading a couple of the posts, I found this one/Recrystallization) to be the most succinct answer. In short, as the coffee is hot it allows for rapid dissolving of the creamer due to high levels of excess energy (which we perceive as heat). However, as it cools the energy levels to keep the creamer dissolved are no longer there and it begins to "clump back up". Have a read and good luck - cooking is just tasty chemistry.
stackexchange-cooking
{ "answer_score": 2, "question_score": 0, "tags": "coffee" }
why my react js button click event not working I'm learning React.js and confused on the below code: btnClick(){ return ( <div> <button onClick={alert("button clicked!")} >Click me</button> </div> ) } render(){ return( <div> {this.btnClick()} </div> ) } the alert only get prompted after refreshing every time but not when clicking. Why?
You should write: <button onClick={() => alert("button clicked!")} >Click me</button> And {this.btnClick} or {() => this.btnClick()}
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "reactjs" }
Spring Security: allow user only to access their own administration page In my web app users are able to change their user details. The URL for this page is: springproject/usermanagement/edituserinfo/4 where "4" is the user id. My security-context looks like: <security:http auto-config="true" use-expressions="true"> <security:intercept-url pattern="/usermanagement" access="isAuthenticated()" /> <security:intercept-url pattern="/usermanagement/new" access="hasRole('ROLE_ADMIN')" /> <security:intercept-url pattern="/usermanagement/edit/*" access="hasRole('ROLE_ADMIN')" /> <security:intercept-url pattern="/usermanagement/edituserinfo/*" access="isAuthenticated()" /> </security:http> How can I restrict the user only to access their own "edituserinfo" page? E.g. user with user id 1 can only access: "springproject/usermanagement/edituserinfo/1 " and not "springproject/usermanagement/edituserinfo/4 "
Use a `PathVariable` on the URL, like `@RequestMapping("/usermanagement/edituserinfo/{userid}")` and in your code validate the logged-in user's Spring Security context principle (via `SecurityContextHolder.getContext().getAuthentication().getPrincipal()`) against the `userid` path variable. If they don't match, bounce the user out, log a `SecurityException`, and send an email to the admins.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 9, "tags": "spring mvc, spring security" }
Do all browsers ignore blank lines in html In html, if you use a new line character to create blank lines, Chrome will ignore them when it renders the page, although if you look at the actual html rendered, they are still in the source. If I recall, years ago, browsers didn't always do this. Some actually rendered the new line as more spacing. I can't test this in all the various browsers whether this is still the case. Does anyone know if all modern browsers ignore the new lines?
By Default Browsers doesn't show carriage returns in the rendered page. If you have an element with carriage return and want to preserve them so the rendered page also show them you have to add the following style to your element: style="white-space: pre-line" Example: <div style="white-space: pre-line"> Hello How are you this text will be shown with carriage returns You see it </div> If you want also to preserve the "tabs" => \t, you should use: style="white-space: pre-wrap" <div style="white-space: pre-wrap"> Hello How are you this text will also shown spaces before when rendered nice </div> Fiddle Example: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html" }
Proxy server - Who queries DNS server? Let us suppose that on my machine it is configured a proxy server. Let now suppose that I want to visit www.sitename.com, what happens? In particular, I send an `HTTP GET www.sitename.com` request to the proxy server and it queries his own dns or, on the contrary, I query my dns and then I send an `HTTP GET IPfromDNS` to the proxy server?
With a HTTP proxy you send the URL to the proxy and the DNS lookup is done by the proxy. With a SOCKS4 proxy the client need to do the DNS lookup itself since this kind of proxy can only forward to IP addresses. SOCKS5 instead allows you again to forward by name so that the DNS lookup is done by the proxy.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "tcp, dns, proxy server" }
Change Spring form tag path value I need to convert "lastModified" to millisecond.Normally it is Date() format.But i must send it as a millisecond.How I can change path variable from jsp or my controller ? Or you can suggest other way. ![enter image description here]( ![enter image description here]( ![enter image description here]( ![enter image description here](
You can add a transient long field and use it like below inside your Organization entity class. public class Organization { -------------- -------------- @Transient private long lastModifiedMili; public long getLastModifiedMili() { return lastModified.getTime(); } public void setLastModifiedMili(long lastModifiedMili) { this.lastModifiedMili = lastModifiedMili; this.lastModified = new Date(lastModifiedMili); } public Organization(Long id, String name, String address, long lastModifiedMili) { this.id = id; this.name=name; this.address = address; this.lastModifiedMili = lastModifiedMili; this.lastModified = new Date(lastModifiedMili); } } And inside your form use this: <form:hidden path="lastModifiedMili" />
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "spring, spring mvc, spring form" }
crystal sort for last 12 months I am trying a create a crystal report for the monthly rate for twelve month showing in chart. For this task, I have a `dc_date(mm/dd/yyyy)` as variable, which I changed in to a `mmyyyy` format. But when I see the group of month it starts always from `01_XXXX` which is not necessarily true. For example, for the report running this `month(072013)` first month should be `062013` and last month should be `072012`. Is there a way to achieve this?
Have you tried to change the format to YYYYMM Hope this will help.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c, crystal reports" }
Вертикальный пэйджинг Всем привет, горизонтальную постраничную прокрутку удалось реализовать с помощью `ViewPager`, подскажите, пожалуйста, есть ли подобный класс для вертикальной прокрутки, можно ли адаптировать `ViewPager` и как? Большое спасибо за потраченное время!
Гуглить за вас нужно? Например это
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "android, java" }
Do spells continue to use hand(s) on following rounds of combat? If I use a spell in combat (eg: Shriveling) on one turn of combat, and it succeeds, on a subsequent round of combat, does the spell still use up any "hands" for combat? OR After casting a spell, on a subsequent round of combat, is that hand(s) free to use other weapons/spells?
From the rulebook, page 16: _A spell or weapon that gives you a bonus (even one that says it lasts until the end of combat) only continues to give you the bonus while you devote the required number of hands to it. You can choose to switch weapons/spells in later combat rounds, but as soon as you “release” a spell or weapon, it stops working for you. Similarly, spells that are refreshed (such as at the beginning of each combat round in the final battle) cease to work and must be re-cast._
stackexchange-boardgames
{ "answer_score": 2, "question_score": 0, "tags": "arkham horror" }
Android Development: Webview progress Bar Take a look at: < ive done that a got it to work but the progress does not change when clicking on a link in the webbrowser. So the progressbar is showed when the app starts and load the home URL but when i click a link or search in google the bar is not showed. why? Thank-you!
webview.setWebViewClient(new WebViewClient() { ProgressDialog MyDialog; public void onReceivedError(WebView view, int errorCode,String description,String failingUrl) { Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show(); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { activity.setProgress(progress * 1000); view.loadUrl(url); return true; } });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "android" }
Select from arrays in a way similar to IN I have this table and data: CREATE TABLE sal_emp ( name text, pay_by_quarter integer[] ); INSERT INTO sal_emp VALUES ('Bil' , '{1, 2, 3, 4}'), ('Bill2', '{5, 6, 7, 8}'); I can run query: select name from sal_emp where pay_by_quarter @> ARRAY[1,4]; And got "Bil". Is there a way to run a query like: select name from sal_emp where pay_by_quarter @> ARRAY[1,4,5] and get "Bil", "Bill2"?
You can use overlap (&&) operator which means "have elements in common". SELECT name FROM sal_emp WHERE pay_by_quarter && ARRAY[1,4,5] Documentation link is here: Array Operators
stackexchange-dba
{ "answer_score": 2, "question_score": 1, "tags": "postgresql, array" }
what is the meaning of "High D"? Whtat is the meaning of "High d"? If people say " So, I am a High D and...." what is the meaning of "High D"? I guess this is negative meaning.. Thank you in advance.
It seems to be jargon related to a certain personality classification system, the "DiSC profile"; it means "high dominance". Someone who is "High D" is described as a "person [who] places emphasis on accomplishing results, the bottom line, confidence." See <
stackexchange-english
{ "answer_score": 6, "question_score": 4, "tags": "meaning" }
Assigning the value of String variable to another String variable I have a check box and according to its status value of the code variable should change. Because I'm using it to next activity. I have code as shown below, String code; String itemCode; String MayoItemCode; mayoBaseCB.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mayoBaseCB.isChecked()) { code = (MayoItemCode); } else { code.equals(itemCode); } } }); `itemcode` and `MayotItemCode` has values and I want to assign it to the variable code according to the status of the checkbox. I have tried these 2 ways (equaling) but it didn't work for me. Can anyone help me to solve this?
You are invoking `code.equals`, which checks for `String` content equality and returns `boolean` (you are not using the outcome of the invocation). Not sure I understand the question but you might want to assign instead, with the `=` idiom. I.e. } else { code = itemCode; } **Edit** On second thought, since you are using an anonimized idiom, you need your fields outside your anonymous `View.OnClickListener` to be `final`. Yet again, assignment would not compile as illustrated in your example, with `final` fields. What you may want to use is a mutable `CharSequence` (i.e. a `StringBuilder`), and manipulate it through method invocation. Sounds fishy though, but there's not enough information (and scope) to help you further.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "java, android, string" }
vb.net reflection vs. late binding? What should be more proper or what is recommended to use in VB.NET from either reflection vs. late binding: 'Type can be various objects that have a common property for sure.' Dim type = sender.GetType() Dim prop = type.GetProperty("Text", 20) Dim value = property.GetValue(sender, Nothing) versus: Dim value = sender.Text
Under the covers they are both doing the same thing (relatively speaking). VB.NET's late-binding feature is done via assembly metadata queries at runtime which is exactly what reflection is all about. One of the benefits to your first approach is that you have an opportunity to handle errors in a more finely-grained manner.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "vb.net, reflection, late binding" }
Assigning a variable using readline function in R? Although this should be very simple, I am having an issue with readline function to assign variables. fun <- function(x){ x <- readline(prompt="Please choose your color 'red, blue, yellow' ") if (x=="red") { x<-1} else if (x=="blue") { x<-2} else if (x=="yellow") { x<-3} else {print("Please choose the color provided above")} return(x) } To me, this simple code should definitely work. Although it seems like working properly, the code is not assigning the new variable (1, 2, or 3) into x. When I run the code, it does return the new value of x, but the new x value is not stored. Could you help me if there is any error in my code? Much thanks in advance.
You haven’t shown how you’re using the function but I’m guessing that you’re trying to call it something like this: foo(x) But what you _should_ be doing is call it like this: x = foo() (And `x` doesn’t need to exist beforehand: you’re not overwriting an existing variable, you’re creating a new one.) In fact, the _argument_ `x` to the function is unnecessary (you’re not using it). Furthermore, your function can be simplified quite substantially: fun = function() { x = readline(prompt="Please choose your color 'red, blue, yellow' ") switch(x, red = 1, blue = 2, yellow = 3, stop('Please choose a color provided above')) }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r, function, readline" }
Issues on getting event from Calendar I was using this code to get event from calendar. But I got **error** like this: request time failed: java.net.SocketException: Address family not supported by protocol When debugging I noticed that code crash on this line: Cursor eventCursor = contentResolver .query(builder.build(), new String[] { "title", "begin", "end", "allDay" }, "Calendars._id=" + 1, null, "startDay ASC, startMinute ASC"); System.out.println("eventCursor count=" + eventCursor.getCount()); any idea will be helpful. Thanks.
The error occurred for the OS version. May be you are using SDK-7. try this code instead, Uri.Builder builder; if (android.os.Build.VERSION.SDK_INT <= 7) { // the old way builder = Uri.parse("content://calendar/instances/when").buildUpon(); } else { // the new way builder = Uri .parse("content://com.android.calendar/instances/when").buildUpon(); } This should work fine.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "android, calendar" }
LINQ where clause using Generic IQueryable source I'm trying to make a method that will filter through an IQueryable datasource with a generic type. I want to have a search method that I could reuse for each of the tables that I will be creating. Preferably I would like to be able to pass a field type as well into this so that I can narrow the search, but also wouldn't care if it just looked into every field. So far I have this: public static IQueryable<T> Search<T>(IQueryable<T> dataSource, string searchFor) { foreach(var variable in dataSource) { dataSource = dataSource.Where(var.Contains(searchFor)); } } i don't know if this really possible, but it would save me a ton of coding since I will have to implement a new search method for each new table that I would be viewing.
You don't need `for` loop here and have mistake in this line: dataSource = dataSource.Where(var.Contains(searchFor)); You can define interface in this way: public interface IMyInterface { bool Contains(string searchFor); } and now you can write your function in the following way: public static IQueryable<T> Search<T>(IQueryable<T> dataSource, string searchFor) where T:IMyInterface { return dataSource.Where(x=>x.Contains(searchFor)); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, linq, generics" }
How can I use the SVN? I am newbie to SVN, I have read Link but when I get to my java application code, and try to do svn add it says not enough arguments provided. what should I do? My application is Java I am using svn on Windows
do you have a repository set up? if you don't have a repository that could be the other argument it's looking for
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "java, svn" }
Global thread local object for Rails request Some Python frameworks such as Flask, Pyramid and Pylons provide a `g` object, a thread-local global object that persists for the request. It's very useful, as it can contain the current user as initialized in a `before_request` hook, etc. Since RoR does not provide such an object, what is the equivalent "Ruby-esque" way to do the same thing? before_request hook initializes some variables on g -> routing controller accesses variables initialized in before_request
With Ruby on Rails, you should use an instance variable (instance varialbes start with an `@`, for example `@user`) which is available in the controller and in the view, and only for the current request.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ruby on rails, ruby" }
sql error in query When executing this I get an error: SELECT A.company_id, B.property_code, ISNULL(C.value, B.default_value) as [value] FROM T_COMPANY A, T_PROPERTY_DEFINITION B LEFT JOIN [T_PROPERTY_VALUE] C ON B.property_id=C.property_id AND A.company_id=C.company_id Msg 4104, Level 16, State 1, Line 7 The multi-part identifier "A.company_id" could not be bound. Why is that?
Your join clause: T_PROPERTY_DEFINITION B LEFT JOIN [T_PROPERTY_VALUE] C ON B.property_id=C.property_id AND A.company_id=C.company_id doesn't contain a table `A` so you can't refer to it in the 'ON' condition. `A` is in a separate syntactic block.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, sql server" }
Print a 256-color test pattern in the terminal How do I print a 256-colour test pattern in my terminal? I want to check that my terminal correctly supports 256 colours.
## 256-colour test pattern To get the below image, use: curl -s | bash ![256-colour test pattern]( The gist `bash`/`zsh` code is `shellcheck` clean, and also supports "Look Ma, no subprocesses!". * * * Alternatively, for a `bash` quicky: for i in {0..255} ; do printf "\x1b48;5;%sm%3d\e[0m " "$i" "$i" if (( i == 15 )) || (( i > 15 )) && (( (i-15) % 6 == 0 )); then printf "\n"; fi done For total overkill, the granddaddy of the lot is `terminal-colors`, a [572-line script with multiple output formats. You can also print a true color (24-bit) test pattern.
stackexchange-askubuntu
{ "answer_score": 149, "question_score": 99, "tags": "command line, colors" }
Именование аргуметов Action public event Action<string, int, int> Changed; Если у `Action` два и более аргументов одного типа, в большинстве случаев это не понятное уродство. Остаётся либо писать `<summary> T2: old value, T3: new value </summary>`, либо заворачивать в `struct`. При генерации метода под это событие выходит: private void OnChange (string arg1, int arg2, int arg3) { throw new NotImplementedException(); } А случаем нет каких нибудь опций указать имена аргументам `Action`?
Например, можно отказаться от предопределённого `Action<>`, воспользоваться кастомным делегатом: public delegate void ChangedEvent(string name, int oldValue, int newValue); public class C { public event ChangedEvent Changed; } При создании обработчика Студия предложит нужные имена: ![как-то так](
stackexchange-ru_stackoverflow
{ "answer_score": 9, "question_score": 6, "tags": "c#" }
Case statement using different columns in Talend I have a case statement as below Case when col1 like '%other%' then 'No' else col5 end as col5 Here like in SQL I need to implement the case statement with different columns and the wild card check of the word 'other' all in talend how can this be done?
If the columns are not dynamically created, you can add a case in _tMap_ for example. So, for a new boolean column you could create the expression: row1.mycolumn1.toLowerCase().contains("other") ? new Boolean.true : new Boolean.false; The boolean field would hold the check value then. **EDIT** Since a new boolean column is not wanted here, your specific requirement would look like this: row1.product_code.toLowerCase().contains("other") ? "No data" : row1.product_code;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "talend" }
Writing a 2-D array to Excel Is there a good way to write a 2-D array to a table in DataNitro? I'm working on a basic sudoku solver in Excel and would rather use python than VisualBasic.
Yes, you can use the table cell property - we just added this in our last update. For example: x = [[6, 7, '', 2, 3, '', '', '', ''], ... ['', '', '', '', 6, 8, '', 3, 2]] # the sudoku puzzle, written out row boy row Cell("A1").table = x Source: I'm one of the DataNitro developers.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "excel, datanitro" }
Select distinct one field other first non empty or null I have table | Id | val | | --- | ---- | | 1 | null | | 1 | qwe1 | | 1 | qwe2 | | 2 | null | | 2 | qwe4 | | 3 | qwe5 | | 4 | qew6 | | 4 | qwe7 | | 5 | null | | 5 | null | is there any easy way to select distinct 'id' values with first non null 'val' values. if not exist then null. for example result should be | Id | val | | --- | ---- | | 1 | qwe1 | | 2 | qwe4 | | 3 | qwe5 | | 4 | qew6 | | 5 | null |
In your case a simple `GROUP BY` should be the solution: SELECT Id ,MIN(val) FROM dbo.mytable GROUP BY Id Whenever using a `GROUP BY`, you have to use an aggregate function on all columns, which are not listed in the `GROUP BY`. If an Id has a value (val) other than `NULL`, this value will be returned. If there are just `NULLs` for the Id, `NULL` will be returned. As far as i unterstood (regarding your comment), this is exactly what you're going to approach. If you always want to have _"the first"_ value <> `NULL`, you'll need another sort criteria (like a timestamp column) and might be able to solve it with a `WINDOW-function`.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "sql, sql server, distinct" }
mod_rewrite specific urls only mod_rewrite is my worst enemy and cant for the life of me figure out whats going wrong, so scrapped any htaccess content i had in hope you clever fools can help a dumb fool! we only want 3 links re-written so it only effects these. index.php?portfolio=print into portfolio/print and index.php?portfolio=branding into portfolio/branding and index.php?portfolio=illustration] into portfolio/illustration however i dont want it to effect links such as index.php?portfolio=photography. so ideally i guess 3 lines with 3 rules that re-write only those links, the base dir is /new/. hope ya guys can help :) thanks again! Owen
RewriteRule ^portfolio/(print|branding|illustration)$ index.php?portfolio=$1 [L] This will match what you describe using one rule with **_2 assumptions_** \- no trailing slash or query string parameters. Comment back if you expect either in the URLs. You can add another section very easily by appending it to the capture.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "apache, mod rewrite, navigation, url rewriting" }
Get DOM element of watch event in Angular.JS I have two select boxes on my web page, and when an state is chosen from the first one I use Angular to load in the options for the second. When the page first loads, the second select box has one item, `Select state...` and after the first item is changed, I want it to change to just `Select...`. Is it possible to access the DOM element through Angular to make this change, or must I use a full-on jQuery selector as I do in this example: $scope.$watch('state', function() { $http.get('institutions?state=' + $scope.state).success(function(institutions) { $scope.institutionOptions = institutions; // Would like to avoid this jQuery selector if possible... $('[name=institution_id] option:first').html('Select...'); }); }, true);
I think you should stick to data binding as much as possible. Bind to `$scope.message`: js: $scope.message = "initial message" html: <select ng-model="selected" ng-options="c.o for c in options"> <option value="">{{message}}</option> </select> when you receive your data, just change the `message`: $scope.message = "select..."; $scope.options = [{o:"option1"},{o:"option2"}, {o:"option3"} ] see this plunker: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, jquery, angularjs" }
Error Handling method call on a null-valued expression I am getting the following non-terminating error in PowerShell. I want to catch this and write-host a generic statement, rather than see the error. Here is the output: > You cannot call a method on a null-valued expression. At C:\PowerShell Scripts\windowsUpdates.ps1:17 char:2 \+ $a = $key.GetValue("LastSuccessTime") \+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \+ CategoryInfo : InvalidOperation: (:) [], ParentContainsErrorRec ordException \+ FullyQualifiedErrorId : InvokeMethodOnNull My catch statement is currently not "catching" this. Any help is appreciated.
I figured this out. I simply added `if($variable -eq $null){write-host "message";}`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "powershell, error handling, try catch" }