qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
44,743,969
I have a text file containing information on restaurants, what is required to is,to insert this information to several dictionaries.The attributes are name, rating, price range, cuisine type Here's the content of txt ``` Georgie Porgie 87% $$$ Canadian,Pub Food Queen St. Cafe 82% $ Malaysian,Thai ``` So far I've read the file and grabbed the contents to a list. ``` content = []; with open(file) as f: content = f.readlines(); content = [x.strip() for x in content]; ``` Need to insert into three dictionaries names\_rating,price\_names,cuisine\_names how would I go about it?
2017/06/25
[ "https://Stackoverflow.com/questions/44743969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5014749/" ]
You seem to have pasted a script into your terminal. It's not going to work unless you invoke `python` first
First check, whether python is on you system: ``` edwards-iMac:~$ which -a python /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python /usr/bin/python ``` To enter live interpreter do this on your commandline: ``` python ``` Now you are in the shell (Live Interpreter). Then you can enter the following line by line: ``` from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor import time import atexit mh = Adafruit_MotorHAT(addr=0x60) def turnOffMotors(): mh.getMotor(1).run(Adafruit_MotorHAT.RELEASE) mh.getMotor(2).run(Adafruit_MotorHAT.RELEASE) mh.getMotor(3).run(Adafruit_MotorHAT.RELEASE) mh.getMotor(4).run(Adafruit_MotorHAT.RELEASE) atexit.register(turnOffMotors) ``` More here: <http://pythoncentral.io/execute-python-script-file-shell/>
5,871,437
I've written some tests using Capybara, but I'm not using selenium and neither any other JS drivers. But my doubt is if I can test a destroy method this way? Since I need to confirm a JS confirmation and the data-method = "delete" can't be visited... I would like to do something very Capybara's way like: visit '/people/123', :data-method => 'delete' Do you guys know if is there some way to do that? Thanks in advance, Andre
2011/05/03
[ "https://Stackoverflow.com/questions/5871437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/268673/" ]
"In general", both queries can produce different execution plans depending on data distribution. However, assuming that your second query is in fact this: ``` SELECT y.* FROM mytable y LEFT JOIN mytable y2 ON y2.person = y.person AND y2.year > y.year WHERE y2.year IS NULL ``` , the `LEFT JOIN` version will most probably be faster, since it will be optimized either to a `HASH ANTI JOIN` or a `HASH JOIN` with filter, depending on whether you have an index on `mytable (person, year)` or not and some other conditions. The subquery version is not optimizeable to an anti join. You may most probably find these queries more efficient: ``` SELECT * FROM mytable y WHERE (y.person , y.year) IN ( SELECT person, MAX(year) FROM mytable GROUP BY person ) ``` or ``` SELECT * FROM ( SELECT y.*, DENSE_RANK() OVER (PARTITION BY person ORDER BY year DESC) dr FROM mytable y ) WHERE dr = 1 ``` , with the first one being more efficient in case of many persons and few years per person, and the second one being the more efficient in the opposite case. You can replace `DENSE_RANK` with `ROW_NUMBER` which will allow you to get rid of duplicates on `person, MAX(year)` should you ever want to.
They don't look relationally equivalent - the first is doing a correlated subquery on person that's absent in the second. ``` select * from mytable y where y.year = (select max(yi.year) from mytable yi where yi.person = y.person) ``` Could be rewritten as: ``` select [list of columns] from (select [list of columns including year], max(year) over (partition by person) as max_year from mytable) where year = max_year ``` To avoid the self-join.
2,049,355
I have an Application that need to evaluate Excel Logical Formulas and I use Excel DLL to do this, but DLL isn't it very efficient. .NET Framework (C#) has any Class that can make this Job? An sample I Provide this ``` =IF(AND(10>=-5;10<0);(-3,8*10+335);IF(AND(10>=0;10<5);(1,4*10+335);IF(AND(10>=5;10<14,4);(-1,2766*10+348,38);IF(AND(10>=14,4;10<25);(-1,5094*10+351,74);IF(AND(10>=25;10<=45);(-1,4*10+349);0))))) ``` And get this ``` 335,614 ``` Thanks
2010/01/12
[ "https://Stackoverflow.com/questions/2049355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/237766/" ]
I am using [ActiveXls](http://www.activexls.com) and it's doing a great job. It's not a free component so you have to pay for it. I don't know if there are any good and free components out there, but I prefer to have support in case I need it :)
I used bcParser.NET is a mathematical expression parser library for the .NET platform. this utility from bestcode organisation and easy to use to calculate all type of formula. refer to this <http://www.bestcode.com/html/math_parser_for_dot_net.html>
1,460,724
I want to print a pixel on the screen using C language. When I write code and compile it shows > > graphics.h:No such file or directory > > > I found that gcc doesn't have the "graphics.h" header file. How can I add graphics.h to the gcc compiler?
2019/07/17
[ "https://superuser.com/questions/1460724", "https://superuser.com", "https://superuser.com/users/1063659/" ]
OpenSSL does not support PPK files. Only PuTTY tools do. You can use PuTTYgen to convert PPK to PEM. And then you should be able to convert PEM to PKCS12.
As @"Martin Prikryl" already mentioned, OpenSSL does not support PPK files and you need to install `putty-tools`. After that you execute `puttygen YOUR_PRIVATE.ppk -O private-openssh -o your_private_id` for your private key and `puttygen YOUR_PUBLIC.ppk -O public-openssh -o your_public_id` for your public key.
423,109
I am using `.pdf_tex` files to insert and label figures in LaTeX: ``` \begin{figure} \centering \graphicspath{{Graphics/FiltersCa/}} \input{Graphics/FiltersCa/COMB_filter_activeZ2b.pdf_tex } \caption{... } \label{fig:FiltersCa} \end{figure} ``` Is it possible to export each figure as a separate PDF-file?
2018/03/25
[ "https://tex.stackexchange.com/questions/423109", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/159089/" ]
The endfloat package will export all the figures (LaTeX source) to a `.fff` file. ``` \documentclass{article} \usepackage{endfloat} \usepackage{graphicx} \makeatletter \efloat@openpost{fff} \efloat@iwrite{fff}{\string\textwidth=\the\textwidth}% pass \textwidth to fff file \makeatother \begin{document} \begin{figure} \centering \includegraphics{example-image} \caption{Test caption} \end{figure} \end{document} ``` Standalone can create a PDF file containing one figure/page. Labels and counter values will be lost. ``` \documentclass[multi=figure]{standalone} \usepackage{graphicx} \makeatletter \renewenvironment{figure}% {\def\@captype{figure}% \minipage{\textwidth}}% {\endminipage} \makeatother \let\efloatseparator=\empty \begin{document} \input{test5.fff} \end{document} ``` [![demo](https://i.stack.imgur.com/ofMs5.png)](https://i.stack.imgur.com/ofMs5.png) --- This version loses the caption. ``` \documentclass[multi=figure]{standalone} \usepackage{graphicx} \renewenvironment{figure}{\ignorespaces}{\unskip} \renewcommand{\caption}[2][]{\ignorespaces} \let\efloatseparator=\empty \begin{document} \input{test5.fff}% previously created fff file \end{document} ```
Quick update with my current work-around (figure-by-figure): * I open the original `PDF`-output with `Inkscape` (I recommend Poppler/Cairo import). You can select the page containing a specific figure. * Create an rectangle (`F4`) that outlines the region of the page, you would like to export (Figure with or without caption). * Press `Shift` and click on the imported `PDF`-page and the rectangle. * Right mouse click on the rectangle and choose `Set Clip` * Press `Shift`+`Ctrl`+`D`, click on `Resize page to content...` in the `Custom size` section and click `Resize page to rawing or selection` * In the `File`-menu, you can safe it as a `PNG` or `PDF` file. For `PDF` I would suggest to `Convert text to path` in order to maintain the original `LaTeX` font. Best wishes, Markus
2,066
We found that water with salt, sugar, or baking soda dissolved in it cools faster than pure water. Water has a very high specific heat; how do these solutes lower it? We heated a beaker (300ml) of water to 90° C and let it cool, checking the temperature every 5 minutes. We repeated the experiment adding a tablespoon of salt. At each 5 minute interval, the temperature was higher for pure water than for salt water. Same result with baking soda and sugar.
2010/12/19
[ "https://physics.stackexchange.com/questions/2066", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/889/" ]
If your description of the experiment is accurate then the result you got is unexpected. It is true that specific heat capacity of salt solution (per *mass* unit) is lower than of pure water, you can estimate it as $$C\_{p} = wC\_{p}^{salt}+(1-w)C\_p^{H\_2O}$$ where *w* is the mass fraction of salt. However, as you describe it, you didn't keep the mass constant but increased it by adding some salt to a fixed volume of water so your total heat capacity should be the sum of the heat capacity of water (which is the same for all samples) and that of salt, sugar or baking soda. Since *w* in your experiment was around 0.04, the effect you were measuring was quite small and could easily be smaller then the experimental error. This error consists of the accuracy of measuring volume of water, of measuring temperature, of timing. The easiest way to reduce these errors is to repeat each experiment several times in random order and see if the results are consistent. **Update**: I found [a plot](http://www.genchem.com/SABrochure/Fig0205.html) of specific heat of soda solutions and I calculated heat capacity for two cases: a) 300 ml of pure water and b) 300 ml of water + 12.5 g of soda = 312.5 g of 4% soda solution. The heat capacity of pure water sample would be 1254 J/K and that of water with soda 1276 J/K - as I expected, it is higher but the difference is less than 2%.
I think that the reason why water has a very high specific heat capacity is due to the presence of hydrogen bonding between each individual water molecule (polarity). These hydrogen bonds are capable of storing energy from heating, and so when water is heated, some heat energy becomes the bond energy and is stored, therefore much more energy is needed to heat up a specific volume of water by a degree and vice versa. When solutes are present, hydrogen bonds break as the permanent dipole - permanent dipole interactions change to ion-dipole interactions where, as mentioned above, solute ions/ polar substances surround each water molecule. This causes each water molecule to lose its attractive forces with each other due to the net loss of hydrogen bonds with each water molecule. Finally, as such, the reduced number of hydrogen bonds mean that less energy can be stored in them, reducing the specific heat capacity of water. P.S this is just a conjecture
54,008
I'm about to write the company guidelines about what must never appear in logs (trace of an application). In fact, some developers try to include as many information as possible in trace, **making it risky to store those logs, and extremely dangerous to submit them**, especially when the customer doesn't know this information is stored, because she never cared about this and never read documentation and/or warning messages. For example, when dealing with files, some developers are tempted to trace **the names of the files**. For example before appending file name to a directory, if we trace everything on error, it will be easy to notice for example that the appended name is too long, and that the bug in the code was to forget to check for the length of the concatenated string. It is helpful, but **this is sensitive data, and must never appear in logs**. In the same way: * **Passwords**, * IP addresses and network information (MAC address, host name, etc.)¹, * Database accesses, * Direct input from user and stored **business data** must never appear in trace. So what other types of information must be banished from the logs? Are there any guidelines already written which I can use? --- ¹ Obviously, I'm not talking about things as IIS or Apache logs. What I'm talking about is the sort of information which is collected with the only intent to debug the application itself, not to trace the activity of untrusted entities. --- **Edit:** Thank you for your answers and your comments. Since my question is not too precise, I'll try to answer the questions asked in the comments: * What I'm doing with the logs? The logs of the application may be stored in memory, which means either in plain on hard disk on localhost, in a database, again in plain, or in Windows Events. In every case, the concern is that those sources may not be safe enough. For example, when a customer runs an application and this application stores logs in plain text file in temp directory, anybody who has a physical access to the PC can read those logs. The logs of the application may also be sent through internet. For example, if a customer has an issue with an application, we can ask her to run this application in full-trace mode and to send us the log file. Also, some application may sent automatically the crash report to us (and even if there are warnings about sensitive data, in most cases customers don't read them). * Am I talking about specific fields? No. I'm working on general business applications only, so the only sensitive data is business data. There is nothing related to health or other fields covered by specific regulations. But thank you to talk about that, I probably should take a look about those fields for some clues about what I can include in guidelines. * Isn't it easier to encrypt the data? No. It would make every application much more difficult, especially if we want to use C# diagnostics and `TraceSource`. It would also require to manage authorizations, which is not the easiest think to do. Finally, if we are talking about the logs submitted to us from a customer, we must be able to read the logs, but without having access to sensitive data. So technically, it's easier to never include sensitive information in logs at all and to never care about how and where those logs are stored.
2011/03/02
[ "https://softwareengineering.stackexchange.com/questions/54008", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/6605/" ]
Personally-identifiable health information covered by the Health Insurance Portability and Accountability Act of 1996 (HIPAA). [This article](http://www.twc.state.tx.us/news/efte/hipaa_basics.html) lists the following examples: * Health care claims or health care encounter information, such as documentation of doctor's visits and notes made by physicians and other provider staff; * Health care payment and remittance advice; * Coordination of health care benefits; * Health care claim status; * Enrollment and disenrollment in a health plan; * Eligibility for a health plan; * Health plan premium payments; * Referral certifications and authorization; * First report of injury; * Health claims attachments.
Off the top of my head.... Credit card information should not be in logs. SSN (or SIN) data should not be in logs. ...of course there are exceptions, if you should happen to work for some central data store for a credit card company or a government agency that manages SIN data, then you might *have* to log it, because it's the main meat of what you're processing/managing.
33,163
I have no idea what this thing is, and it appears to be a kitchen tool, but for what? I put up a YouTube video of it, and would love to see if anybody knows exactly what it would be used for, because we have no idea: <http://youtu.be/do5_D8Sjhk8> It would appear to be some kind of corer, or to cut shapes out of some fruit, but I can't find anything similar to it online. ![Mystery Kitchen Tool](https://i.stack.imgur.com/KMKno.jpg) The video linked to above does a better job of showing it from multiple angles.
2013/04/01
[ "https://cooking.stackexchange.com/questions/33163", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/6170/" ]
It looks like one I bought a few years ago, it was suppose to cut corn off the cob. You put it around the small end of the corn and rotate in a downward motion. I didn't like the results and went back to using a knife.
This looks like a butter looper/curler. They are used to create a nice presentation of butter for the bread course. <http://en.wikipedia.org/wiki/Butter_curler>
27,872,959
I am getting an issue where android studio is saying ``` Installation failed since the device has an application with the same package but a different signature. . . .. ``` This is correct, as I recently signed an APK and uploaded to the beta area of my play developer console. And now I am trying to debug it locally and by default I believe that all Android projects are signed by the debug keystore hence the signatures would be different. What is the best way to deal with this? Would it be possible to sign my debug version with my release key, and is there a potential danger here? How would I force the signing of my debug version with my release keystore without losing the ability to debug, etc.? Or should I just keep uninstalling and reinstalling the different versions - that seems the worst possible workaround. :-)
2015/01/10
[ "https://Stackoverflow.com/questions/27872959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457172/" ]
You can sign your apps with your release key while keeping the debugging option - you just have to add your release key into Android Studio (or specify it on the command line if you are signing your apps there). In Android Studio, right click on your app in the project browser and open module settings. Select your app's module and click on 'Signing' to make sure your release keystore is listed. Then under 'Build Types', make sure that the debug target and the release target share the same signing config, and that the debug target has debuggable set to true. They should now share the same key. More information on app signing can be found in the Developer docs [here](http://developer.android.com/tools/publishing/app-signing.html). I haven't heard of a downside to using the same key for debugging and for release, provided the private key is kept secure (read: not under version control).
changing the app id in gradle files did it for me ``` defaultConfig { applicationId 'com.example.app' } ```
116,615
Every once in a while, our server will do something stupid. Maybe a log file got too big and ate up all the disk space, or a process has hung. In either case, the result is our website is down. And in e-commerce, downtime = lost sales. All of the issues I can easily fix in 15 minutes or less. But the issues never occur when it's convenient. It's always 4am, or when you're on vacation, etc. Our company is small and can't afford another IT person/server admin/etc. What we would like to do is find a company that provides 24/7 emergency server support on a contract basis. A non-technical employee can call them up and say "the site is down", and they'll log into your server and troubleshoot the problem within 15 minutes or so. We don't need installation or removal of software, routine upgrades, or configuration. Just someone who's always available to fix problems quickly in an emergency when I'm not available. Does such a service exist? Where might we find it? Clarification: We're using a VPS provider that maintains the hardware and network infrastructure for us. But the don't provide os or software level support. Were looking for a company that can fix software or OS issues remotely via ssh, on a contract basis.
2010/02/25
[ "https://serverfault.com/questions/116615", "https://serverfault.com", "https://serverfault.com/users/15623/" ]
Yes, it's called "Managed Hosting". For what it's worth, we use Rackspace.
Have you considered outsourcing your IT infrastructure that specializes in management? There are several Infrastructure as a Service (IaaS) hosting companies that provide 24x7x365 server management and support. I personally recommend NetDepot (www.netdepot.com) and have used them for over 3 years. They have on-site technical support engineers and provide network and uptime, hardware replacement, and other SLA's that you simply can't get with a consulting company. Overall, your company will reduce IT costs and overhead by outsourcing your server infrastructure and having it managed by a team of engineers who are available and on-site 24x7x365. NetDepot also provides phone support so you can always call them no matter what time of day or night. Their data center is PCI compliant and recently became SAS 70 type II certified.
11,687,146
I've got the following code which makes a connection to a db > runs a stored proc > and then moves on. I believe it is easy to get db programming wrong so it is important to be *defensive*: is the following defensive? (or can it be improved?) ``` public int RunStoredProc() { SqlConnection conn = null; SqlCommand dataCommand = null; SqlParameter param = null; int myOutputValue; try { conn = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString); conn.Open(); dataCommand = conn.CreateCommand(); dataCommand.CommandType = CommandType.StoredProcedure; dataCommand.CommandText = "pr_blahblah"; dataCommand.CommandTimeout = 200; //seconds param = new SqlParameter(); param = dataCommand.Parameters.Add("@NumRowsReturned", SqlDbType.Int); param.Direction = ParameterDirection.Output; dataCommand.ExecuteNonQuery(); myOutputValue = (int)param.Value; return myOutputValue; } catch (SqlException ex) { MessageBox.Show("Error:" + ex.Number.ToString(), "Error StoredProcedure"); return 0; } finally { if (conn != null) { conn.Close(); conn.Dispose(); } } } ``` **CODE NOW LOOKS LIKE THE FOLLOWING** I've tried to use all the help offered by everyone and the above code has now been amended to the following which I hope is now sufficiently *defensive*: ``` public SqlConnection CreateConnection() { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString); return conn; } public int RunStoredProc() { using (var conn = CreateConnection()) using (var dataCommand = conn.CreateCommand()) { conn.Open(); dataCommand.CommandType = CommandType.StoredProcedure; dataCommand.CommandText = "pr_BankingChargebacks"; dataCommand.CommandTimeout = 200; //5 minutes SqlParameter param = new SqlParameter(); param = dataCommand.Parameters.Add("@NumRowsReturned", SqlDbType.Int); param.Direction = ParameterDirection.Output; dataCommand.ExecuteNonQuery(); int myOutputValue = (int)param.Value; return myOutputValue; } } ```
2012/07/27
[ "https://Stackoverflow.com/questions/11687146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1179880/" ]
Try using, well, the `using` construct for such things. ``` using(var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString) { } ``` Once you do that, I think you will be at the right level of "defense". Similarly try to do the same for anything that has to be disposed ( like the command)
If `MessageBox.Show("Error:" + ex.Number.ToString(), "Error StoredProcedure");` is how you're going to handle an exception then you're not logging or even retrieving the actual exception details.
27,237,162
I am writing a database using mysql and I am trying to show multiple columns using subquery but it gives me an error "ERROR 1241 (21000): Operand should contain 1 column(s)". the code for the query looks like this: ``` SELECT P_SSN, Name, Blood_Type FROM PATIENT WHERE P_SSN IN (SELECT P_SSN, ID FROM BLOOD_POUCH WHERE Blood_Type LIKE 'A'); ``` Or in a join ``` SELECT P_SSN, Name, Blood_Type, ID FROM PATIENT, BLOOD_POUCH WHERE PATIENT.P_SSN = BLOOD_POUCH.P_SSN AND Blood_type LIKE 'A'; ``` My tables are: PATIENT - P\_SSN, Name, Blood\_Type, ..... // P\_SSN PK BLOOD\_POUCH - ID, Blood\_Type,...., P\_SSN // ID PK, P\_SSN FK Any ideas on how to display ID as well? If I leave only P\_SSN it works, but I'd like the BLOOD\_POUCH table to show some information as well.
2014/12/01
[ "https://Stackoverflow.com/questions/27237162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2898592/" ]
You can use `EXISTS` to check: ``` IF EXISTS (SELECT * FROM [table]) BEGIN DELETE FROM [table] ---Or for fast delete use: TRUNCATE TABLE [table] END ELSE BEGIN PRINT 'nothing in table' END ```
``` IF (SELECT COUNT(*) FROM greek_organizations) > 0 BEGIN DELETE FROM greek_organizations END ```
59,893,070
I am trying to build an image using singularity. in one step I have to run a R script to do so, in the recipe file I need to install R and I did using the following command: ``` apt-get install -y systemd systemd-sysv gdebi-core procps libssl1.1 ed wget curl libqt5webkit5 libqt5core5a libxml2-dev r-cran-xml wget libssl-dev curl libcurl4-openssl-dev libnetcdf-dev netcdf-bin libcairo2-dev libxt-dev default-jre texlive-latex-base libhdf5-dev r-base r-base-dev curl https://download1.rstudio.org/rstudio-xenial-1.1.463-amd64.deb > /rstudio-1.1.463-amd64.deb apt-get -y install /rstudio-1.1.463-amd64.deb wget -O /rstudio-server-stretch-1.1.463-amd64.deb \ https://download2.rstudio.org/rstudio-server-stretch-1.1.463-amd64.deb gdebi -n /rstudio-server-stretch-1.1.463-amd64.deb ``` and I run the recipe file using this command: ``` sudo singularity build nanos.sif Singularity.recipe ``` but after running it, at some point it asks me that which time zones I am located at and here is the message: ``` Please select the geographic area in which you live. Subsequent configuration questions will narrow this down by presenting a list of cities, representing the time zones in which they are located. 1. Africa 6. Asia 11. System V timezones 2. America 7. Atlantic Ocean 12. US 3. Antarctica 8. Europe 13. None of the above 4. Australia 9. Indian Ocean 5. Arctic Ocean 10. Pacific Ocean Geographic area: ``` I chose one of them using name and numbers but building did not proceed. do you know how I can fix this problem?
2020/01/24
[ "https://Stackoverflow.com/questions/59893070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10657934/" ]
There is a problem with `new`: your code depends on the concrete class. Thus changing/evolving the code is a more difficult task. A factory is much more manageable because (1) the user code is not dependant on the concrete type (2) the code that choose the concrete type is in a single place. Then the final code is much more secure/evolvable, etc. `getInstance()` is not a good name for a factory, it is more the name of a singleton method. "get" is not intended to create something, just to get something already existant. `createInstance` or `create` is much more explicit for factories (many of them, even in Java are called such - examine `createImage` and alike). But alas, for reasons explicited by @slaw in comments, you need to be more precise to help the user choose between argument semantic, thus things like `createFromYears`, `createFromMinutes`, etc. That may be slightly verbose, then `of` seems to be a good compromise. Finally it is more easy (IMHO) to use `of*()` than `createImage()` with a lot of parameters to explain what arguments are...
There a design pattern called `Fluent interface`, which allows "chaining" of methods, see [Wikipedia](https://en.wikipedia.org/wiki/Fluent_interface#Java). It's supposed to very readable, imitating natural speech ("get x of y with z"). It's not especially *chaining* in your example (given it consists of only one method call), but it makes sense to use the same paradigm everywhere.
77,298
I'm running sqlcmd from a batch file and I was wondering how to make it return an ERRORLEVEL other than 0 when something goes wrong with the backup.
2014/09/22
[ "https://dba.stackexchange.com/questions/77298", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/135/" ]
You should use the option -b in sqlcmd. -b Specifies that sqlcmd exits and returns a DOS ERRORLEVEL value when an error occurs. The value that is returned to the DOS ERRORLEVEL variable is 1 when the SQL Server error message has a severity level greater than 10; otherwise, the value returned is 0 <http://msdn.microsoft.com/en-us/library/ms162773.aspx>
I solved this with this command ``` sqlcmd -V1 -m0 -r1 -S dbHost -U dbUser -P dbPass -Q "SELECT 1 FROM xxxxxxxxx" 1>nul ```
39,119,817
Im trying Laravel 5 and cant get Session working. Im inside a `Controller` and this is what ive done on an fresh setup and fresh controller: ``` \Request::session()->put('test', 'x'); var_dump(\Request::session()->get('test')); ``` This works as long as session is being written, and once you comment the first line there session value is gone on the next request. Similarly, ive tried this `Session::` instead of `Request::session()` and still same result.
2016/08/24
[ "https://Stackoverflow.com/questions/39119817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1093486/" ]
Ok ive found the solution myself thanks to 2 posts: [Laravel 5 - session doesn't work](https://stackoverflow.com/questions/29346743/laravel-5-session-doesnt-work?rq=1) [Session not working in middleware Laravel 5](https://stackoverflow.com/questions/29797952/session-not-working-in-middleware-laravel-5?rq=1) --- 1. After all the `OMG` buzz around Laravel being so so so simple lets dance in the rain!! the simplest thing in PHP such as `$_SESSION` now requires `\Request::session()` for which you need to `user Request`. then you need 2 different methods to save and get values from it instead of $\_SESSION['x'] directly!! 2. Laravel (genius super alien tech) saves session at `TerminableMiddleware` instead of on spot, but DOESNOT mentions it on <https://laravel.com/docs/5.2/session>. So you will need to explicitly call `Session::save()`!! So there you go, 5 lines to do 1 line work of $\_SESSION!
if you are using 5.2, make sure your controller is governed by the 'web' middleware group either via the route ``` $route->group([ 'middleware' => ['web'] .... ``` or by instantiating it in your controllers construct method; ``` $this->middleware('web'); ```
13,355,107
I've overridden the CredentialsAuthProvider like so: ``` public override bool TryAuthenticate(IServiceBase authService, string userName, string password) { //TODO: Auth the user and return if valid login return true; } public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo) { base.OnAuthenticated(authService, session, tokens, authInfo); //User has been authenticated //Find the user's role form the DB if (roleA) //GOTO mypage1 if (roleB) //GOTO mypage2 } ``` I perform a simple post to ~/auth/Credentials and while the authentication works and the OnAuthenticated method is called, how do I actually redirect the user to the appropriate page based on a role or something similar? I tired to do the following in the OnAuthenticated method but it did not have the desired effect: > > authService.("/views/customers"); > > > **Update using Starter Template (see comment below):** ``` public class CustomCredentialsAuthProvider : CredentialsAuthProvider { public override bool TryAuthenticate(IServiceBase authService, string userName, string password) { return true; } public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo) { session.ReferrerUrl = "http://www.msn.com"; base.OnAuthenticated(authService, session, tokens, authInfo); } } ``` And the form to POST: ``` <form method="POST" action="/auth/credentials"> <input name="UserName"/> <input name="Password" type="password"/> <input type="submit"/> </form> ```
2012/11/13
[ "https://Stackoverflow.com/questions/13355107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/403605/" ]
The different places where you can set the Url to redirect to during [ServiceStack Authentication](https://github.com/ServiceStack/ServiceStack/wiki/Authentication-and-authorization), in order of precedence are: 1. The **Continue** QueryString, FormData or Request DTO variable when making the request to `/auth` 2. The `Session.ReferrerUrl` Url 3. The HTTP **Referer** HTTP Header 4. The **CallbackUrl** in the AuthConfig of the current AuthProvider used Given these order of preferences, if the request didn't have a **Continue** parameter, it should use the `session.ReferrerUrl`, so you could do: ``` if (roleA) session.ReferrerUrl = "http://myPage1Url"; if (roleB) session.ReferrerUrl = "http://myPage2Url"; ```
mythz, Good call on making this OSS. :) You are correct regarding the order of precedence: 1. The Continue QueryString, FormData or Request DTO variable when making the request to /auth 2. The Session.ReferrerUrl Url The HTTP 3. Referer HTTP Header 4. The CallbackUrl in the AuthConfig of the current AuthProvider used So in my example, I didn't have the Continue QueryString, Form Data or Request DTO variable, and I didn't have the CallbackUrl, and certainly not the Session.ReferrerUrl because this is the first post of the Session. From `AuthService.cs`: ``` var referrerUrl = request.Continue ?? session.ReferrerUrl ?? this.RequestContext.GetHeader("Referer") ?? oAuthConfig.CallbackUrl; ``` By default referrerUrl will have the Referer header value from the request. And that is what is going to be assigned to the Location header further down the `Post` method of the `AuthService.cs`: ``` if (!(response is IHttpResult)) { return new HttpResult(response) { Location = referrerUrl }; } ``` Once authenticated, and the `session.ReferrerUrl` is set here the response will be sent to the client with the Location property above set to the original referrer, not the value below: ``` public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo) { session.ReferrerUrl = "http://www.msn.com"; } ``` It's only on the second POST of the same session will the client navigate to www.msn.com (in this example) because the session has already been populated. I think this: ``` var referrerUrl = request.Continue ?? session.ReferrerUrl ?? this.RequestContext.GetHeader("Referer") ?? oAuthConfig.CallbackUrl; ``` Needs to be determined after the call to auth.
18,229,279
I am facing problem in sending mail to my inbox (gmail account) but everytime it goes to spam folder. Here is the code snippet ``` //$ticketDetail is array which contain required information to send. sendOwnershipEmail('dineshnagarscriet@gmail.com', $ticketDetail); function sendOwnershipEmail($email, $ticketDetail) { $param = new stdClass(); $param->content = "<div> <div><b>".$ticketDetail[0]['ticket_number']."</b></div><br/> <div><img src='".$ticketDetail[0]['image_path']."'/></div><br/> <div>Ticket with ticket number ".$ticketDetail[0]['ticket_number']." has been requested for tranfer from <div/> <div>".$ticketDetail[0]['oldDepartment']." to ".$ticketDetail[0]['newDepartment']." Department <div/> </div>"; $param->sendTo = $email; $param->subject = "Request for Department transfer"; sendMailFunction($param); } function sendMailFunction($param) { $to = $param->sendTo; $subject = $param->subject; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: successive.testing@gmail.com' . "\r\n"; $message = "<html><head>" . "<meta http-equiv='Content-Language' content='en-us'>" . "<meta http-equiv='Content-Type' content='text/html; charset=windows-1252'>" . "</head><body>" .$param->content. "<br><br></body></html>"; mail($to, $subject, $message, $headers); } ``` And I have tried a lot like setting headers as Reply-To, Return-Path etc but every time it goes to spam. Can you please figure out whats the problem?
2013/08/14
[ "https://Stackoverflow.com/questions/18229279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2555207/" ]
### Try changing your headers to this: ``` $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n"; $headers .= "From: successive.testing@gmail.com" . "\r\n" . "Reply-To: successive.testing@gmail.com" . "\r\n" . "X-Mailer: PHP/" . phpversion(); ``` **For a few reasons.** * One of which is the need of a `Reply-To` and, * The use of apostrophes instead of double-quotes. Those two things in my experience with forms, is usually what triggers a message ending up in the Spam box. You could also try changing the `$from` to: ``` $from = "successive.testing@gmail.com"; ``` --- --- EDIT: ----- See these links I found on the subject <https://stackoverflow.com/a/9988544/1415724> and <https://stackoverflow.com/a/16717647/1415724> and <https://stackoverflow.com/a/9899837/1415724> <https://stackoverflow.com/a/5944155/1415724> and <https://stackoverflow.com/a/6532320/1415724> * Try using the SMTP server of your ISP. Using this apparently worked for many: `X-MSMail-Priority: High` <http://www.webhostingtalk.com/showthread.php?t=931932> *"My host helped me to enable DomainKeys and SPF Records on my domain and now when I send a test message to my Hotmail address it doesn't end up in Junk. It was actually really easy to enable these settings in cPanel under Email Authentication. I can't believe I never saw that before. It only works with sending through SMTP using phpmailer by the way. Any other way it still is marked as spam."* PHPmailer sending mail to spam in hotmail. how to fix <http://pastebin.com/QdQUrfax>
If you are sending this through your own mail server you might need to add a "Sender" header which will contain an email address of from your own domain. Gmail will probably be spamming the email because the FROM address is a gmail address but has not been sent from their own server.
25,831,334
This is my script ``` #include <stdio.h> #define PI 3.14; int main(void){ double hasil, input; printf("Enter a positive number : "); scanf("%lf",&input); hasil = PI * input; printf("\nThe result is : %lf",hasil); getchar(); return 0; } ``` I get error \* must be a pointer? What's it? I mean '\*' sign is to multiply number....
2014/09/14
[ "https://Stackoverflow.com/questions/25831334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3658777/" ]
Remove `;` from your `#define`, it should be `#define PI 3.14`
change the line to, ``` hasil = input * PI; ```
47,883,066
I am trying to use the **mat-paginator** for a table where I want to show data retrieved via an HTTP call, but the problem I have is that I cannot set the **length** of the paginator to the total number of the results I get from the API. In this example, the length is hardcoded in the component, but it shoudn't be a problem (I tried also to set it on the view as [length]="100" and it doesn't work). Here is the HTML: ``` <mat-table #table1="matSort" [dataSource]="dataSource1" matSort> <ng-container matColumnDef="id"> <mat-header-cell *matHeaderCellDef> <mat-checkbox name="all" class="" [checked]="isAllChecked()" (change)="checkAll($event)" *ngIf="bulkView"></mat-checkbox> </mat-header-cell> <mat-cell *matCellDef="let element"> <mat-checkbox class="" [checked]="isAllRowsSelected" [(ngModel)]="element.state" *ngIf="bulkView"></mat-checkbox> </mat-cell> </ng-container> <ng-container matColumnDef="firstName"> <mat-header-cell *matHeaderCellDef mat-sort-header="CompanyAgent"> First name </mat-header-cell> <mat-cell *matCellDef="let element"> <img class="personal-data-table__img" src="/assets/app/media/img/users/100_3.jpg" alt="user" width="50" /> {{element.firstName}} </mat-cell> </ng-container> <ng-container matColumnDef="lastName"> <mat-header-cell *matHeaderCellDef mat-sort-header="CompanyEmail"> Last name </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.lastName}} </mat-cell> </ng-container> <ng-container matColumnDef="city"> <mat-header-cell *matHeaderCellDef mat-sort-header="Website"> City </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.city}} </mat-cell> </ng-container> <ng-container matColumnDef="actions"> <mat-header-cell *matHeaderCellDef>Actions</mat-header-cell> <mat-cell *matCellDef="let element"> <span class="btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill"> <i class="la la-ellipsis-h"></i> </span> <span class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" (click)="editPersonalDataItem(element.RecordID)"> <i class="la la-edit"></i> </span> <span class="btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill"> <i class="la la-trash"></i> </span> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table> <mat-paginator #paginator1 [length]="pag1.pageLength" [pageSize]="pag1.pageSize" [pageSizeOptions]="pag1.pageSizeOptions" [pageIndex]="pag1.pageIndex" (page)="onPaginateChange1($event)"> </mat-paginator> ``` and the component: ``` pag1 = { pageSize: 10, pageSizeOptions: [5, 10, 20], pageIndex: 0, pageLength: 100 }; @ViewChild('paginator1') paginator1: MatPaginator; this.route.data.subscribe(data => { this.personalData = data.users.data.persons; this.dataSource1 = new MatTableDataSource(this.personalData); this.dataSource1.paginator = this.paginator1; console.log('this.paginator1: ', this.paginator1); }); ``` When I console.log this.paginator1, I can see the \_length set to 100, but when I open the object, I see the value which is displayed in the browser (10). [![enter image description here](https://i.stack.imgur.com/o4jzo.png)](https://i.stack.imgur.com/o4jzo.png) The data is displaying fine in the browser, the only problem I have is that the paginator always shows 1-10 of 10 and I want it to show 1-10 of x, where x is the value I get from the API for the total number of items. Please advise. Thanks!
2017/12/19
[ "https://Stackoverflow.com/questions/47883066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5142554/" ]
Answer found here <https://github.com/angular/components/issues/10526> Just remove `this.tableDataSource.paginator = this.paginator;` and definition of paginator from ts.
I advise you to take a look at [the internationalization of the paginator](https://material.angular.io/components/paginator/overview#internationalization). I will save you the research time, here is how you do it : ```js import { MatPaginatorIntl } from '@angular/material'; export class MatPaginatorI18n extends MatPaginatorIntl { itemsPerPageLabel = 'Lines per page'; nextPageLabel = 'Next page'; previousPageLabel = 'Previous page'; getRangeLabel = (page: number, pageSize: number, totalResults: number) => { if (!totalResults) { return 'No result'; } totalResults = Math.max(totalResults, 0); const startIndex = page * pageSize; // If the start index exceeds the list length, do not try and fix the end index to the end. const endIndex = startIndex < totalResults ? Math.min(startIndex + pageSize, totalResults) : startIndex + pageSize; return `${startIndex + 1} - ${endIndex} sur ${totalResults}` ; } } ``` In your module, remember to import you custom provider : ``` providers: [ { provide: MatPaginatorIntl, useClass: MatPaginatorI18n } ] ```
101,485
Normally in principal component analysis (PCA) the first few PCs are used and the low variance PCs are dropped, as they do not explain much of the variation in the data. However, are there examples where the low variation PCs are useful (i.e. have use in the context of the data, have an intuitive explanation, etc.) and should not be thrown away?
2014/06/07
[ "https://stats.stackexchange.com/questions/101485", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/46897/" ]
Here's a cool excerpt from [Jolliffe (1982)](http://automatica.dei.unipd.it/public/Schenato/PSC/2010_2011/gruppo4-Building_termo_identification/IdentificazioneTermodinamica20072008/Biblio/Articoli/PCR%20vecchio%2082.pdf) that I didn't include in my previous answer to the very similar question, "[Low variance components in PCA, are they really just noise? Is there any way to test for it?](https://stats.stackexchange.com/q/87198/32036)" I find it pretty intuitive. > > $\quad$Suppose that it is required to predict the height of the cloud-base, $H$, an important problem at airports. Various climatic variables are measured including surface temperature $T\_s$, and surface dewpoint, $T\_d$. Here, $T\_d$ is the temperature at which the surface air would be saturated with water vapour, and the difference $T\_s-T\_d$, is a measure of surface humidity. Now $T\_s,T\_d$ are generally positively correlated, so a principal component analysis of the climatic variables will have a high-variance component which is highly correlated with $T\_s+T\_d$,and a low-variance component which is similarly correlated with $T\_s-T\_d$. But $H$ is related to humidity and hence to $T\_s-T\_d$, i.e. to a low-variance rather than a high-variance component, so a strategy which rejects low-variance components will give poor predictions for $H$. > > $\quad$The discussion of this example is necessarily vague because of the unknown effects of any other climatic variables which are also measured and included in the analysis. However, it shows a physically plausible case where a dependent variable will be related to a low-variance component, confirming the three empirical examples from the literature. > > $\quad$Furthermore, the cloud-base example has been tested on data from Cardiff (Wales) Airport for the period 1966–73 with one extra climatic variable, sea-surface temperature, also included. > Results were essentially as predicted above. The last principal component was approximately > $T\_s-T\_d$, and **it accounted for only 0·4 per cent of the total variation. However, in a principal component regression it was easily the most important predictor for $H$**. [Emphasis added] > > > The three examples from literature referred to in the last sentence of the second paragraph were the three I mentioned in [my answer to the linked question](https://stats.stackexchange.com/a/87231/32036). --- **Reference** Jolliffe, I. T. (1982). Note on the use of principal components in regression. *Applied Statistics, 31*(3), 300–303. Retrieved from <http://automatica.dei.unipd.it/public/Schenato/PSC/2010_2011/gruppo4-Building_termo_identification/IdentificazioneTermodinamica20072008/Biblio/Articoli/PCR%20vecchio%2082.pdf>.
In [this talk](https://youtu.be/E4lg3aJFXpY?t=8m46s) ([slides](https://www.slideshare.net/databricks/needle-in-the-haystackuser-behavior-anomaly-detection-for-information-security-with-ping-yan-and-wei-deng/7)) the presenters discuss their use of PCA to discriminate between high variability and low variability features. They actually prefer the low variability features for anomaly detection, since a significant shift in a low variability dimension is a strong indicator of anomalous behavior. The motivating example they provide is as follows: > > Assume a user always logs in from a Mac. The "operating system" dimension of their activity would be very low variance. But if we saw a login event from that same user where the "operating system" was Windows, that would be very interesting, and something we'd like to catch. > > >
58,998,323
Im trying to use olingo with Flutter on Android. I set up my channel and I can call the library but I keep getting this message: ``` E/AndroidRuntime(28391): FATAL EXCEPTION: main E/AndroidRuntime(28391): Process: com.example.odata, PID: 28391 E/AndroidRuntime(28391): org.apache.olingo.client.api.http.HttpClientException: android.os.NetworkOnMainThreadException E/AndroidRuntime(28391): at org.apache.olingo.client.core.communication.request.AbstractODataRequest.doExecute(AbstractODataRequest.java:312) ``` So it looks like it is running on the main thread - which is a no go as this would block. I tried the looper to ask Java to run on the UI Thread: ``` public void onMethodCall(MethodCall call, Result result) { // Note: this method is invoked on the main thread. Log.i("test", "using " + call.method); String serviceUrl = "http://services.odata.org/OData/OData.svc/"; new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (call.method.equals("getMetaData")) { String metadata; final Edm edm = ODataClientFactory.getClient().getRetrieveRequestFactory().getMetadataRequest(serviceUrl).execute().getBody(); metadata = edm.toString(); if (metadata != "") { result.success(metadata); } else { result.error("UNAVAILABLE", "Metadata cannot read.", null); } } else { result.notImplemented(); } } }); ``` But Im still getting the same error. So how exactly can I deal with external JAR Library which are doing blocking operations ? To my understanding an external call is a Future anyway so it will not block my Flutter thread anyway - but Android Java does not think so ... This is my method call in flutter ``` Future<void> _getMetaData() async { String metadata; try { final String result = await platform.invokeMethod('getMetaData'); metadata = result; } on PlatformException catch (e) { metadata = e.message; } setState(() { _metadata = metadata; }); } ```
2019/11/22
[ "https://Stackoverflow.com/questions/58998323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12417320/" ]
Thanks for the answer, this is the solution for anyone that may be interested: ``` public void onMethodCall(MethodCall call, Result result) { if (call.method.equals("getMetaData")) { class MetadataLoader extends AsyncTask<String , Integer, String> { @Override protected String doInBackground(String... urls) { // call your Java library method here, including blocking methods return your_return_value; } protected void onPostExecute(String _result) { // your_return_value is now passed in _result result.success(_result); } } new MetadataLoader().execute(); // Start the Async } ``` On the flutter side, ``` Future<void> _getMetaData() async { String metadata; try { final String result = await platform.invokeMethod('getMetaData'); // do something with the result // the Flutter thread will stop at the await and resume when the Java // will call result.success } } ```
You will need to create a new Java thread or `Worker`. (Note that the "main" thread and the "UI" thread are the same thing - so by posting to the main looper you've ended up in the same place - trying to do network i/o on the main thread.) Yes, the Flutter engine is running in different threads, but you still need to leave the main native thread unblocked as it is responsible for detecting user input, etc. Also note that when your blocking activity completes - on its non-main thread - it will likely want to deliver the response to Dart. To do this it will need to use part of your code above - to post the results back to the main thread, which can then invoke method channel operations. You'll probably want to use your method channel bi-directionally. From flutter to native to request an operation (returning, say, a sequence number), and from native to flutter to deliver the results (quoting the sequence number so that the result can be tied back to the request).
20,237,905
There is such a method which read a file and do something: ``` public void readFileAndDoSomething(File file) { InputStream inputStream = new FileInputStream(file); // a lot of complex code which reads the inputStream // and we don't know if the inputStream is closed or not } ``` Now I want to test the method to make sure if any input stream that uses the file is closed or not finally. My test code: ``` public void test() { File testFile = new File("my_test_file"); readFileAndDoSomething(testFile); // is it possible to just check the file to make sure // if it is still used by some unclosed input streams? } ``` Please see my comment in the `test` method, is it possible?
2013/11/27
[ "https://Stackoverflow.com/questions/20237905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342235/" ]
Try to use all uppercase `DATE`, like this: ``` <Property Name="BuildDate" Value="$(env.DATE)" /> ``` **UPDATE**: My initial guess was not correct - environment variables are case-insensitive when referenced this way. It seems like it depends on the type of the environment variable. There are standard environment variables, like `%TEMP%`, `%windir%`, etc. Those are "static", meaning the value is not calculated each time you reference it. There are dynamic environment variables, which are calculated each time they are referenced. These include `%DATE%`, `%TIME%`, etc. It seems that WiX preprocessor can't work with dynamic variables. You can verify this: put `$(env.windir)` and it will work, put `$(env.time)` - and it won't. More info about environment variables can be found [here](http://ss64.com/nt/syntax-variables.html). I have not verified whether there's a wish in WiX bug database to support this. Feel free to do it yourself. So, back to your question. You can work around this limitation in the following way: * Create preprocessor extension * Reference the value from that extension instead of addressing environment variable direcly The sample how to create preprocessor extension can be found [here](http://wixtoolset.org/documentation/manual/v3/wixdev/extensions/extension_development_preprocessor.html). Here's a sample of the code which does the job: ```c# public class DateExtension : PreprocessorExtension { public override string[] Prefixes { get { return new[] { "date" }; } } public override string GetVariableValue(string prefix, string name) { string result = null; switch (prefix) { case "date": switch (name) { case "Now": result = DateTime.Now.ToShortDateString(); break; } break; } return result; } } ``` And in your WiX code you can use it in the following way: ``` <Property Id="BuildDate" Value="$(date.Now)" /> ``` Don't forget to: * pass preprocessor extension DLL to the WiX setup project (`-ext path/to/PreprocessorExtension.dll`) * add `[assembly: AssemblyDefaultWixExtension(typeof(PreprocessorWixExtension))]` to the preprocessor extension project Here is the result I observe in the MSI package: ![resulting MSI package](https://i.stack.imgur.com/bzGwC.png)
To set property value from another property use the following syntax: ``` <SetProperty Id="BuildDate" Value="[Date]" After="InstallInitialize" /> ```
10,038,755
I would like to contribute to PlayFramework 2.0. Building from the command line is really not the best way to work on this overcomplex language called Scala. It really needs an IDE to ease comprehension. ( btw see <http://zeroturnaround.com/blog/scala-sink-or-swim-part-2/> for more details on this topic) What is the preferred IDE to work on the framework sources, and how to import the code ? In other words, how do play developers work ? What is their setup ? Thank you
2012/04/06
[ "https://Stackoverflow.com/questions/10038755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258689/" ]
it is not all that difficult: ### get the source ``` git clone https://github.com/playframework/Play20.git ``` ### add IDEA plugin *to `framework/project/plugins.sbt`*: ``` resolvers += "sbt-idea-repo" at "http://mpeltonen.github.com/maven/" addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.0.0") ``` ### generate IDE friendliness ``` [...Play20/framework]$ sbt gen-idea ```
Today Idea, Eclipse and Ensime - all supports importing sbt project. So, it's up to you which one to choose. Looking through commits on [Play20/.gitignore](https://github.com/playframework/Play20/commits/master/.gitignore), [Ignore IntelliJ IDEA projects](https://github.com/playframework/Play20/commit/c13d666d919d23e23e90aff9a89a8e5e70ac1b31) commit tells that some of developers are using Idea, [Finalized integration with sbteclipse, using sbteclipse 2.0.0-M3.](https://github.com/playframework/Play20/commit/49163e48957f5670545da15bd859c9e7ad2a7243) commit tells there is Eclipse support out of the box. I'd add that I am using Ensime with Play for a long time. It just works as well as with other sbt projects. ### Ensime support *plugins.sbt*: ``` resolvers += ScalaToolsSnapshots addSbtPlugin("org.ensime" % "ensime-sbt-cmd" % "latest.milestone") ``` from sbt console ``` $ ensime generate ```
16,945,308
I want to remove the last revision (or last n revisions) from a repository. How to do it? Is it possible to remove the svn revision files from `project/db/revs/` and from `project/db/revprops/` ?
2013/06/05
[ "https://Stackoverflow.com/questions/16945308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003575/" ]
I just tried to do exactly what you suggested in your question and it worked! First, you remove the last revision from `db/revprops` and `db/revs`. Then you also have to decrement the numbers in `db/current` and `db/txn-current` If any other developer already had checked out the last revision then they must check out again fresh. Having checked out an older revision seems to be ok. There will be no unforseen sideeffects because I made a diff with before and after and the databases were identical (after commit & removing the last rev). But I think it is very clear that you can only remove revisions at the end of the chain. Removing a revision from in the middle can screw up the deltas between the revisions. **You dont need to be an expert in svn database structure to do such simple things, as bahrep suggested in the comments**
Generally, removing a revision involves creating a new copy of the repository with the particular revision removed. If it's a small check-in, I'd say get the previous version, move those files to the side, get latest, then copy the previous files on top and check back in.
426,981
We need to prove that $$\dfrac{\sin\theta - \cos\theta + 1}{\sin\theta + \cos\theta - 1} = \frac 1{\sec\theta - \tan\theta}$$ I have tried and it gets confusing.
2013/06/22
[ "https://math.stackexchange.com/questions/426981", "https://math.stackexchange.com", "https://math.stackexchange.com/users/83528/" ]
$$\frac{\sin\theta -\cos\theta +1}{\sin\theta +\cos\theta -1}= \frac{1}{\sec\theta - \tan\theta}$$ By taking $$\mbox{L.H.S ( Left hand side )} = \frac{\sin\theta -\cos\theta +1}{\sin\theta +\cos\theta -1} = \frac{2\sin\frac{\theta}{2}\cos\frac{\theta}{2}+2\sin^2\frac{\theta}{2}}{2\sin\frac{\theta}{2}\cos\frac{\theta}{2}-2\sin^2\frac{\theta}{2}}$$ [By applying $1-\cos\theta = 2\sin^2\frac{\theta}{2}$] Which after simplification gives : $$\frac{\sin\frac{\theta}{2}+ \cos\frac{\theta}{2}}{\cos\frac{\theta}{2}-\sin\frac{\theta}{2}}$$ Now taking R.H.S we get : $$ \begin{align} \frac{1}{\sec\theta - \tan\theta} &= \frac{\cos\theta}{1-\sin\theta}\\ &= \frac{\cos^2\theta - \sin^2\theta}{\cos^2\frac{\theta}{2}+\sin^2\frac{\theta}{2}-2\sin\frac{\theta}{2}\cos\frac{\theta}{2}} \\ &= \frac{(\cos^2\frac{\theta}{2}-\sin^\frac{\theta}{2})}{(\cos\frac{\theta}{2}-\sin\frac{\theta}{2})^2} \\ &= \frac{\sin\frac{\theta}{2}+ \cos\frac{\theta}{2}}{\cos\frac{\theta}{2}-\sin\frac{\theta}{2}}\\ &= \mbox{L.H.S ( Left hand side )}\end{align},$$ where the second equality comes from applying $\cos\theta = \cos^2\frac{\theta}{2}-\sin^2\frac{\theta}{2}$ and $\sin\theta = 2\sin\frac{\theta}{2}\cos\frac{\theta}{2}$.
multiply numerator and denominator by $(1-\sin\theta)$. $$\dfrac {\sin\theta-\cos\theta+1}{\sin\theta+\cos\theta-1}\times \dfrac{1-\sin\theta}{1-\sin\theta}$$ $$\dfrac {\sin\theta-\sin^2\theta-\cos\theta+\sin\theta\cdot\cos\theta+1-\sin\theta}{(\sin\theta+\cos\theta-1)(1-\sin\theta)}$$ $$\dfrac {1-\sin^2\theta-\cos\theta+\sin\theta\cdot\cos\theta}{(\sin\theta+\cos\theta-1)(1-\sin\theta)}$$ $$\dfrac {\cos^2\theta-\cos\theta+\sin\theta\cdot\cos\theta}{(\sin\theta+\cos\theta-1)(1-\sin\theta)}$$ $$\dfrac {\cos\theta(\cos\theta+\sin\theta-1)}{(\sin\theta+\cos\theta-1)(1-\sin\theta)}$$ $$\dfrac {\cos\theta}{1-\sin\theta}$$ $$\dfrac {1}{\dfrac{1-\sin\theta}{\cos\theta}}$$ $$\dfrac {1}{\dfrac{1}{\cos\theta}-\dfrac{\sin\theta}{{\cos\theta}}}$$ $$\dfrac {1}{\sec\theta-\tan\theta}$$
27,306,371
I've been through the various `reshape` questions but don't believe this iteration has been asked before. I am dealing with a data frame of 81K rows and 4188 variables. Variables 161:4188 are the measurements present as different variables. The `idvar` is in column 1. I want to repeat columns 1:160 and create new records for columns 169:4188. The final data frame will be of the dimension 162 columns and 326,268,000 rows (81K \* 4028 variables converted as unique records). Here is what I tried: `reshapeddf <- reshape(c, idvar = "PID", varying = c(dput(names(c[161:4188]))), v.names = "viewership", timevar = "network.show", times = c(dput(names(c[161:4188]))), direction = "long")` The operation didn't complete. I waited almost 10 minutes. Is this the right way? I am on a Windows 7, 8GB RAM, i5 3.20ghz PC. What is the most efficient way to complete this transpose in R? Both of the answers by BondedDust and Nick are clever but I run into memory issues. Is there a way any of the three approaches in this thread- `reshape`, `tidyr` or the `do.call` be implemented using `ff`? In Example Data below, columns 1:4 are the ones I want to repeat and columns 5:9 are the ones to create new records for. ``` structure(list(PID = c(1003401L, 1004801L, 1007601L, 1008601L, 1008602L, 1011901L), HHID = c(10034L, 10048L, 10076L, 10086L, 10086L, 10119L), HH.START.DATE = structure(c(1378440000, 1362974400, 1399521600, 1352869200, 1352869200, 1404964800), class = c("POSIXct", "POSIXt"), tzone = ""), VISITOR.CODE = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("0", "L"), class = "factor"), WEIGHTED.MINUTES.VIEWED..ABC...20.20.FRI = c(0, 0, 305892, 0, 101453, 0), WEIGHTED.MINUTES.VIEWED..ABC...BLACK.ISH = c(0, 0, 0, 0, 127281, 0), WEIGHTED.MINUTES.VIEWED..ABC...CASTLE = c(0, 27805, 0, 0, 0, 0), WEIGHTED.MINUTES.VIEWED..ABC...CMA.AWARDS = c(0, 679148, 0, 0, 278460, 498972), WEIGHTED.MINUTES.VIEWED..ABC...COUNTDOWN.TO.CMA.AWARDS = c(0, 316448, 0, 0, 0, 0)), .Names = c("PID", "HHID", "HH.START.DATE", "VISITOR.CODE", "WEIGHTED.MINUTES.VIEWED..ABC...20.20.FRI", "WEIGHTED.MINUTES.VIEWED..ABC...BLACK.ISH", "WEIGHTED.MINUTES.VIEWED..ABC...CASTLE", "WEIGHTED.MINUTES.VIEWED..ABC...CMA.AWARDS", "WEIGHTED.MINUTES.VIEWED..ABC...COUNTDOWN.TO.CMA.AWARDS"), row.names = c(NA, 6L), class = "data.frame") ```
2014/12/04
[ "https://Stackoverflow.com/questions/27306371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3328804/" ]
Might be as easy as something like this: ``` dat2 <- cbind(dat[1:4], stack( dat[5:length(dat)] ) ```
I think this should work: ``` library(tidyr) newdf <- gather(yourdf, program, minutes, -PID:-VISITOR.CODE) ```
153,776
I am inside of... ``` public class bgchange : IMapServerDropDownBoxAction { void IServerAction.ServerAction(ToolbarItemInfo info) { Some code... ``` and after "some code" I want to trigger ``` [WebMethod] public static void DoSome() { } ``` Which triggers some javascript. Is this possible? Ok, switch methods here. I was able to call dosome(); which fired but did not trigger the javascript. I have tried to use the registerstartupscript method but don't fully understand how to implement it. Here's what I tried: ``` public class bgchange : IMapServerDropDownBoxAction { void IServerAction.ServerAction(ToolbarItemInfo info) { ...my C# code to perform on dropdown selection... //now I want to trigger some javascript... // Define the name and type of the client scripts on the page. String csname1 = "PopupScript"; Type cstype = this.GetType(); // Get a ClientScriptManager reference from the Page class. ClientScriptManager cs = Page.ClientScript; // Check to see if the startup script is already registered. if (!cs.IsStartupScriptRegistered(cstype, csname1)) { String cstext1 = "alert('Hello World');"; cs.RegisterStartupScript(cstype, csname1, cstext1, true); } } ``` } I got the registerstartupscript code from an msdn example. Clearly I am not implementing it correctly. Currently vs says "An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.ClientScript.get' refering to the piece of code "Page.Clientscript;" Thanks.
2008/09/30
[ "https://Stackoverflow.com/questions/153776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5234/" ]
You cannot call methods within a browser directly from the server. You can, however, add javascript functions to the response that will execute methods within the browser. Within the ServerAction method, do the following ``` string script = "<script language='javascript'>\n"; script += "javascriptFunctionHere();\n"; script += "</script>"; Page.RegisterStartupScript("ForceClientToCallServerMethod", script); ``` [More info here](http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerstartupscript.aspx)
hmmm... the question changed dramatically since my original answer. Now I think the answer is no. But I might be wrong.
11,307,649
Regrettably there is no way to specify a timeout when using a regular expression on a String in Java. So if you have no strict control over what patterns get applied to which input, you might end up having threads that consume a lot of CPU while endlessly trying to match (not so well designed) patterns to (malicious?) input. I'm aware of the reasons why Thread#stop() is deprecated (see <http://download.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html>). They are centered around objects that might get damaged in case of ThreadDeath exceptions, and which then pollute your running JVM environment and can lead to subtle errors. My question to anyone who has deeper insight than me into the workings of the JVM is this: **If the thread that needs to be stopped does not hold any (obvious) monitors on or references to objects that are used by the rest of the program, can it then be acceptable to use Thread#stop() nevertheless?** I created a rather defensive solution to be able to process regular expression matching with a timeout. I would be glad for any comment or remark, especially on problems that this approach can cause despite my efforts to avoid them. Thanks! ``` import java.util.concurrent.Callable; public class SafeRegularExpressionMatcher { // demonstrates behavior for regular expression running into catastrophic backtracking for given input public static void main(String[] args) { SafeRegularExpressionMatcher matcher = new SafeRegularExpressionMatcher( "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "(x+x+)+y", 2000); System.out.println(matcher.matches()); } final String stringToMatch; final String regularExpression; final int timeoutMillis; public SafeRegularExpressionMatcher(String stringToMatch, String regularExpression, int timeoutMillis) { this.stringToMatch = stringToMatch; this.regularExpression = regularExpression; this.timeoutMillis = timeoutMillis; } public Boolean matches() { CallableThread<Boolean> thread = createSafeRegularExpressionMatchingThread(); Boolean result = tryToGetResultFromThreadWithTimeout(thread); return result; } private CallableThread<Boolean> createSafeRegularExpressionMatchingThread() { final String stringToMatchForUseInThread = new String(stringToMatch); final String regularExpressionForUseInThread = new String(regularExpression); Callable<Boolean> callable = createRegularExpressionMatchingCallable(stringToMatchForUseInThread, regularExpressionForUseInThread); CallableThread<Boolean> thread = new CallableThread<Boolean>(callable); return thread; } private Callable<Boolean> createRegularExpressionMatchingCallable(final String stringToMatchForUseInThread, final String regularExpressionForUseInThread) { Callable<Boolean> callable = new Callable<Boolean>() { public Boolean call() throws Exception { return Boolean.valueOf(stringToMatchForUseInThread.matches(regularExpressionForUseInThread)); } }; return callable; } private Boolean tryToGetResultFromThreadWithTimeout(CallableThread<Boolean> thread) { startThreadAndApplyTimeout(thread); Boolean result = processThreadResult(thread); return result; } private void startThreadAndApplyTimeout(CallableThread<Boolean> thread) { thread.start(); try { thread.join(timeoutMillis); } catch (InterruptedException e) { throwRuntimeException("Interrupt", e); } } private Boolean processThreadResult(CallableThread<Boolean> thread) { Boolean result = null; if (thread.isAlive()) { killThread(thread); // do not use anything from the thread anymore, objects may be damaged! throwRuntimeException("Timeout", null); } else { Exception exceptionOccurredInThread = thread.getException(); if (exceptionOccurredInThread != null) { throwRuntimeException("Exception", exceptionOccurredInThread); } else { result = thread.getResult(); } } return result; } private void throwRuntimeException(String situation, Exception e) { throw new RuntimeException(situation + " occured while applying pattern /" + regularExpression + "/ to input '" + stringToMatch + " after " + timeoutMillis + "ms!", e); } /** * This method uses {@link Thread#stop()} to kill a thread that is running wild. Although it is acknowledged that * {@link Thread#stop()} is inherently unsafe, the assumption is that the thread to kill does not hold any monitors on or * even references to objects referenced by the rest of the JVM, so it is acceptable to do this. * * After calling this method nothing from the thread should be used anymore! * * @param thread Thread to stop */ @SuppressWarnings("deprecation") private static void killThread(CallableThread<Boolean> thread) { thread.stop(); } private static class CallableThread<V> extends Thread { private final Callable<V> callable; private V result = null; private Exception exception = null; public CallableThread(Callable<V> callable) { this.callable = callable; } @Override public void run() { try { V result = compute(); setResult(result); } catch (Exception e) { exception = e; } catch (ThreadDeath e) { cleanup(); } } private V compute() throws Exception { return callable.call(); } private synchronized void cleanup() { result = null; } private synchronized void setResult(V result) { this.result = result; } public synchronized V getResult() { return result; } public synchronized Exception getException() { return exception; } } } ``` EDIT: Thanks to dawce who pointed me to [this solution](https://stackoverflow.com/questions/910740/cancelling-a-long-running-regex-match/11348374#11348374) I have been able to solve my original problem without the need for additional threads. I have posted the code there. Thanks to all who have responded.
2012/07/03
[ "https://Stackoverflow.com/questions/11307649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1498022/" ]
You can use Thread.stop() if you determine its the only solution available to you. You may need to shutdown and restart your applicaton to ensure its in a good state. Note: a Thread can capture and ignore `ThreadDeath` so stop isn't guarenteed to stop all threads. An alternative way to stop a thread is to run it in a different process. This can be killed as required. This can still leave resources in an incosistent state (like lock files) but it is less likely and easier to control. The best solution of course is to fix the code so it doesn't do this in the first place and respects Thread.interrupt() instead.
If you specifically design your thread code to not hold locks etc., (yes, and this includes the non-explicit locks. eg. a malloc lock that may be used when changing string sizes), then stop the thread, yes. Polling an 'interrupted' flag is fine, except that it means polling an 'interrupted' flag, ie. overhead during the 99.9999% of the time it is not actually set. This can be an issue with high-performance, tight loops. If the check can be kept out of an innermost loop and still be checked reasonably frequently, then that is indeed the best way to go. If the flag cannot be checked often, (eg. because of a tight loop in inaccessible library code), you could set the thread priority to the lowest possible and forget it until it does eventually die. Another bodge that is occasionally possible is to destroy the data upon which the thread is working in such a way that the library code does exit normally, causes an exception to be raised and so control bubbles out of the opaque library code or causes an 'OnError' handler to be called. If the lib. is operating on a string, splatting the string with nulls is sure to do something. Any exception will do - if you can arrange for an AV/segfault in the thread, then fine, as long as you get control back.
65,541,515
The main question is how to remove the "Label" namespace in the graphic if I have a count plot of three dataset files? I am using the Seaborn module. ``` #Importing the libraries import pandas as pd import numpy as np import seaborn as sb #Reading the files train_filename = 'train.csv' test_filename = 'test.csv' valid_filename = 'valid.csv' train_news = pd.read_csv(train_filename) test_news = pd.read_csv(test_filename) valid_news = pd.read_csv(valid_filename) #Data observation def data_obs(): print("Training dataset size:") print(train_news.shape) print(train_news) print("Testing dataset size:") print(test_news.shape) print(test_news) print("Validation dataset size:") print(valid_news.shape) print(valid_news) print(data_obs()) ``` Here is the result what I got from data [enter image description here](https://i.stack.imgur.com/nLQeI.png) [![enter image description here](https://i.stack.imgur.com/US44H.png)](https://i.stack.imgur.com/US44H.png) Also, I am using the LIAR dataset and it has the following features: [enter image description here](https://i.stack.imgur.com/026ld.png)
2021/01/02
[ "https://Stackoverflow.com/questions/65541515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12963012/" ]
Create a new column `X4` that is the composition you want. ``` d={ 'id' :[1,2,3,4,5], 'X1':[25,12,3,7,1], 'X2':[3,45,3,1,6], 'X3':[6,23,9,3,2] } df=pd.DataFrame(d, columns=['id','X1','X2','X3']) df = df.assign(X4=lambda dfa: "X1:" + dfa["X1"].astype("string") + ",X2:" + dfa['X2'].astype("string") + ",X3:" + dfa['X3'].astype("string") ) ``` output ------ ``` id X1 X2 X3 X4 1 25 3 6 X1:25,X2:3,X3:6 2 12 45 23 X1:12,X2:45,X3:23 3 3 3 9 X1:3,X2:3,X3:9 4 7 1 3 X1:7,X2:1,X3:3 5 1 6 2 X1:1,X2:6,X3:2 ```
A different general approach: ``` def get_other_cols_vals(df1): vals = [] for i_enm, col in enumerate(df1.columns): vals.append(f"{col}:{df1.iloc[0, i_enm]}") return ",".join(vals) df['X4'] = df.groupby(df.index)[df.columns.drop('id').values].apply(get_other_cols_vals) ``` [![enter image description here](https://i.stack.imgur.com/Df80t.png)](https://i.stack.imgur.com/Df80t.png)
2,833,805
What does address operator mean. say in the method below. what should be passed in the method as parameter value of integer or the address of an integer variable. ``` void func1(int&)// method declaration void func1(int& inNumber)//method definition { //some code } ```
2010/05/14
[ "https://Stackoverflow.com/questions/2833805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/276989/" ]
There is no address-of operator in your code - the ampersand is being used to declare a reference. Which C++ text book are you using that does not cover this?
its called as reference in c++ <http://en.wikipedia.org/wiki/Reference_(C%2B%2B)>
32,211,504
**Relevant code:** ``` add_action( 'wp_ajax_proj_update', 'proj_update' ); function proj_update ( ) { $id = $_POST['id']; $compname = $_POST['compname']; $projname = $_POST['projname']; $imageurl = $_POST['imageurl']; $sumsmall = $_POST['sumsmall']; $sumfull = $_POST['sumfull']; $results = $_POST['results']; $caseid = (!isset($_POST['caseid']) || strcmp($_POST['caseid'],'none')) ? $_POST['caseid'] : "NULL"; // weirdness required to get the value of our <select name="caseid"> element converted to something we can insert to database $hide = array_key_exists('hide',$_POST) !== false ? 1 : 0; // weirdness required to get the value of <input type="checkbox" name="hide"> converted to something we can insert to database $thisAction = $_POST['thisAction']; global $wpdb; $message = ""; switch ($thisAction) { case 'add': { /* Note: Have to break up prepare statement because https://core.trac.wordpress.org/ticket/12819 */ $addQuery = $wpdb->prepare("INSERT INTO projs (compname,projname,imageurl,sumsmall,sumfull,results,caseid,hide) VALUES (%s,%s,%s,%s,%s,%s,%d," . $caseid . ",%d)", array($compname, $projname,$imageurl,$sumsmall,$sumfull,$results,$hide)); $message .= $wpdb->query($addQuery) ? 'Successfully added project to the database.' : 'Error occurred when trying to add project to database: ' . $wpdb->last_error; break; } ``` For some reason, `$wpdb->last_error` is turning out to be `Query was empty`, and I can't figure out why. I've looked at other S.O. posts on this topic and they say that an undefined object is being used as the query, but here I'm using `$addQuery` as the query and I don't see any reason why it is not defined. Any ideas?
2015/08/25
[ "https://Stackoverflow.com/questions/32211504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This is because of the lack of permission to the user aseema in hdfs. Follow the steps below. Login as hduser and perform the following operations (from the logs, it seems hduser is a superuser) ``` hadoop fs -mkdir -p /user/hive/warehouse hadoop fs -mkdir /tmp hadoop fs -chmod -R 777 /user/hive hadoop fs -chmod 777 /tmp ``` After this, try executing the create database statement from aseema user.
If you are running from Local Mode then you should run this command from hdfs user: ``` su hdfs ``` Then change the permission like below if you want: ``` hdfs dfs -chown -R <username_of_new_owner> /user ```
35,348
My understanding is that Venus, Earth, Mars, and Jupiter are all losing mass due to their gravity, temperature, and the solar wind. But what about Mercury, Saturn, Uranus, and Neptune? Mercury has a magnetic field and so typically would repeal the worst of the solar wind and no atmosphere to lose, only an exosphere. Though the Poynting-Robertson effect should be pulling in more dust to Mercury. I do not know the calculations to determine if Saturn, Uranus, and Neptune are losing mass though.
2020/02/28
[ "https://astronomy.stackexchange.com/questions/35348", "https://astronomy.stackexchange.com", "https://astronomy.stackexchange.com/users/17272/" ]
I'm not sure how the balance between mass loss and gain works out... Yes, atmospheric escape is probably happening to some extent on all the planets, with rates that depend on escape velocity, magnetic field, atmospheric/exospheric composition, temperature, and other effects we are still learning about. But the planets are also gaining mass by capturing dust, meteorites, and the occasional larger object that can cause cratering on solid bodies, or atmospheric debris clouds in giant planets like Jupiter.
Anything that's working, spending energy is losing mass, Einstein Mass-energy equivalence of SR along with radiant energy(electromagnetic and gravitational radiation) would be effecting all the planets, but at a different rate for each one. <https://en.m.wikipedia.org/wiki/Radiant_energy> And. <https://en.m.wikipedia.org/wiki/Mass_in_special_relativity> These should help I think
17,653,112
I have a popup on my website for some registration. When this popup opens on a phone, it is to high for the browser view port, and some of the content comes outside it. ![illustration of the problem](https://i.stack.imgur.com/wahr6.png) When I try to scroll down, it scroll the background. If I lock the background with `overflow-y: hidden`, nothing scrolls at all. The popup scrolls with the window, locked at the same place. I would like to not lock the position to the top of the page, and have it always appear in the top of the view port, but it should be possible to scroll to see all its contents. Does anyone know how to fix this?
2013/07/15
[ "https://Stackoverflow.com/questions/17653112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1211119/" ]
You can use `media` types to write CSS rules for mobile devices, tablets, etc. for example if you want the ability of scroll in you modal content you can do something like: ``` @media (max-width: 767px) { .modal-content { overflow-y: scroll; } } ```
This will display a vertical scrollbar if the container exceeds the viewport height: ``` .some-modal { maxHeight: 100vh; overflowY: 'auto'; overscrollBehavior: 'contain'; /* <-- nice to have but not required */ } ```
27,659,211
I need to insert a variable inside a jQuery selector like this example, how can I fix my problem? ``` var index = 5; $(".tables li:nth-child('+index+')").addClass('vr_active'); ```
2014/12/26
[ "https://Stackoverflow.com/questions/27659211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2678346/" ]
The issue is in the quotes ... ``` var index = 5; $(".tables li:nth-child("+index+")").addClass('vr_active'); ``` This way, the index variable is part of a concatenation of: * ".tables li:nth-child(" ... a string * index ... a variable * ")" ... a string. Functioning **[jsFiddle](http://jsfiddle.net/rfornal/pv91Lesh/)**
**A jQuery selector is just a string.** So your problem is actually "How to insert a variable into a string" and this can be done in a myriad of ways, for example: ``` ".tables li:nth-child(" + index + ")" ``` ``` var selector = ".tables li:nth-child(${index})"; selector = selector.replace("${index}", index); ``` ``` etc. ```
1,226,730
I am working on a continuous integration system for both .Net and VB6 applications using Subversion, CruiseControl, NAnt and Ivy. The .Net side of things isn't too much of a problem, but I need a little guidance with the VB6 side of things, more from the 'DLL-hell' side of things! My current set-up is getting all dependent files for my VB6 system, as expected and builds the various projects within ok. BUT... it's using DLLs that are already registered on my PC, and not those within my Lib folder, which is where I am resolving my dependencies from Ivy. I can get around this problem by registering the downloaded DLLs after Ivy has resolved them, which means that the project file can be pointed at the local Lib folder; but I want my NAnt script to do this automatically, and then automatically un-register them after the build process has completed, so that the next project in-turn can do the same thing. What I think I need help with, is the ability to have Ivy give me a list of the project's dependencies... For example, if I am building Project X, which depends on projects A, B and C, then if I could issue a command to Ivy that would give back a list such as A, B, C then I can pass these to another Target process to register/unregister them in turn... Does this make sense? Is this possible and am I looking at this in the right way? Or is there a better way? My apologies is I have gone right around the houses to explain this...!!
2009/08/04
[ "https://Stackoverflow.com/questions/1226730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/114805/" ]
We keep project references in separate REF files next to our VBP files and we are using custom tool to "fix" VBPs during compile. Our build process is greatly inspired by [this page (The Way We Work)](http://users.skynet.be/wvdd2/Compiling/The_Way_we_Work/the_way_we_work.html) and our REF files are direct rip-off of the structure he is describing. From The Way We Work you can follow a link to [L.J. Johnson's Take Control of Your Build Cycle](http://mvps.org/st-software/Code/BuildCycle.zip) for a utility that does the same "fix" without external files. Basicly the fix has to use tlbinfo to extract LIBID from the executable (OCX/DLL) and completely replace the guid of the reference in the VBP file. Once this not so complicated procedure is used, it doesn't matter if you are using binary or project compatibility for your projects. Also, if doing full builds none of the previous OCX/DLL has to be registered.
I have found the answer to this myself; Instead of using Ivy to try to generate a list of dependencies for me on-demand, I thought I'd use the file-system to give me that same list, as Ivy has done it's job in resolving the dependencies for me, resulting in a 'lib' folder full of .dll files... All I have done, is get a list of the .dll files within that lib folder, store them in a property (variable) and then cycle back through that same property registering/unregistering as need be. Simple really..!
566,065
In my biological study, **I have around 14000 independent samples**, and I study the evolution of a response variable over time. I have three groups to study. Thus, I have two factors: factor "Group" (with three levels: CTRL, VC1, VC2) and a factor "Time" (with three levels: T0, T1, T2): I have a total of 3\*3 = 9 conditions. **Thus, for each condition, I have around 1600 independent samples**... Which is huge for statistical testing. I conducted a [two-way ANOVA](https://en.wikipedia.org/wiki/Two-way_analysis_of_variance), but **not surprisingly every comparisons (main effects and post hoc tests) are statistically significant due to a very big sample size**. Basically, it finds significant p-values when they're not really significant (false positives) ... ``` > model <- lm(Variable ~ Group*Time, data) Sum Sq Df F value Pr(>F) Group 705 2 61.597 < 2.2e-16 *** Time 6495 2 567.686 < 2.2e-16 *** Group:Time 713 4 31.152 < 2.2e-16 *** > cohens_f_squared(Anova(model,type=2)) Parameter | Cohen's f2 (partial) | 95% CI ----------------------------------------------------- Group | 9.56e-03 | [0.01, Inf] Time | 0.09 | [0.08, Inf] Group:Time | 9.67e-03 | [0.01, Inf] ``` How can I reduce the sample size to reduce the false positive rate? Is there a way for sampling my data?
2022/02/28
[ "https://stats.stackexchange.com/questions/566065", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/203934/" ]
If you want to specify an amount that is "too small to be interesting", *and* you want a metric that will give you a metric similar to a p-value, you could do an [equivalence test](https://en.wikipedia.org/wiki/Equivalence_test), i.e. you could do a test of whether $|\beta|<0.1$ (if that is your threshold of "interesting"). [This answer](https://stats.stackexchange.com/questions/245543/anova-for-equivalence-testing) points out that you can do a post-hoc equivalence test for a linear model/ANOVA using the emmeans package (see the vignette [here](https://cran.r-project.org/web/packages/emmeans/vignettes/confidence-intervals.html#equiv)). But I do agree with other answers that showing effect sizes + CIs can be more useful than single numbers that measure the strength of evidence against a particular dichotomous hypothesis (e.g. $H\_0$: $|\beta|<0.1$).
You have an impression that your p-values are exaggerated. This might occur in several situations. * It can be that the data points are not entirely independent. (you say they are independent and it might be a good assumption, but if you are measuring small differences, then a small amount of dependence might become important). For instance, you are sampling many individuals but you have only little variation in other larger units that play a role in noise. Say you are sampling chickens on farms and you only test the chickens on a few farms. The variation is due to the differences in the chickens (which you use to compute the p-value) but also due to differences between farms or other units (which are not taken into account). * It can be that you are looking at a process that has variability in time. For instance, not every time point will be the same. And you are wrongly interpreting it as if the time has some causal influence or whether there is some trend with time. If you measure only three different time points then you might observe some correlation with time, but this can be just a little bump and on a longer time scale the outcome that you measure fluctuates from year to year. Below is an example figure where data is randomly generated. For each time point and each group time point combination, a random mean is drawn from a random distribution. [![example](https://i.stack.imgur.com/8AKqH.png)](https://i.stack.imgur.com/8AKqH.png) Say you measure a hundred times in time points 17, 18, 19. If there is a significant difference and there was a decreasing trend then this doesn't mean that the parameter is a decreasing function of time. It means that those three temperatures in the three time points were different Because your small amount of data points (you have 14000 points but only 3 different times) you should not interpret the significant coefficient for time as an indication for a time trend. It means that the three time points were different (and this could have been random variation between time points instead of the outcome being some deterministic function of time). In order to determine whether there is a significant trend in time you need more time points. So yes, you can reduce the sample an interpret your sample to be only 3 points (in time) instead of 14000. And you should do it this way if you want to interpret the result (significance) as a significant time trend. The 3 different years are significantly different but the coefficient of a linear time trend is not significant if you only have 3 time points.
38,737,955
``` import nltk import random from nltk.corpus import movie_reviews documents=[(list(movie_reviews.words(fileid)),category) for category in movie_reviews.categories() for fileid in movie_reviews.fileids(category)] random.shuffle(documents) #print(documents[1]) all_words=[] for w in movie_reviews.words(): all_words.append(w.lower()) all_words=nltk.FreqDist(all_words) word_features = list(all_words.keys())[:3000] def find_features(document): words = set(document) features=[] for w in word_features: features[w]= (w in words) return features print((find_features(movie_reviews.words('neg/cv000_29416.txt')))) featuresets = [(find_features(rev), category) for (rev,category) in documents] ``` --- After run, I am getting the error ``` features[w]= (w in words) TypeError: list indices must be integers, not str ``` Please help me to solve it...
2016/08/03
[ "https://Stackoverflow.com/questions/38737955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5842544/" ]
Only change that needs to be made is that `features` must be initialized to a `dict` (`{}`) rather than a `list` (`[]`) and then you could populate it's contents. The `TypeError` was because `word_features` is a list of *strings* which you were trying to index using a list and lists can't have string indices. ``` features={} for w in word_features: features[w] = (w in words) ``` Here, the elements present in `word_features` constitute the `keys` of dictionary, `features` holding boolean values, `True` based on whether the same element appears in `words` (which holds unique items due to calling of `set()`) and `False` for the vice-versa situation.
You have tried to index a list `features` with a string and it is not possible with python. **List indices can only be integers**. What you need is a `dictionary`. Try using a `defaultdict` meaning that even if a key is not found in the dictionary, instead of a `KeyError` being thrown, a new entry is created ``` from collections import defaultdict features = defaultdict() for w in word_features: features[w] = [w in words] ```
2,116
I am a newbie to Python and have started object-oriented programming recently. I have implemented a "Rock Paper Scissors" application in OOP. I would like for you to evaluate my code, and tell me where can I improve my code and how I can better organize the functionality. ``` import random class RockPaperScissors(object): def setUserOption(self,val): self.__option = val def getValueFromList(self,option): l = ['rock','scissors','paper'] return l[option] def __getRandomValue(self,max): val = random.randint(1,max) return self.getValueFromList(val-1) def __getResult(self,t): self.__d = {('rock','scissors'):'rock breaks scissors - User has won',('rock','paper'):'rock is captured by paper - User has won',('scissors','paper'):'Scissors cut paper - User has won', ('scissors','rock'):'rock breaks scissors - Computer won',('paper','rock'):'rock is captured by paper - Computer won',('paper','scissors'):'Scissors cut paper - Computer won'} return self.__d[t] def __computeResult(self,computerOption): if computerOption == self.__option: return 'The user and computer choose the same option' else: return self.__getResult((self.__option,computerOption)) def printResult(self): computerOption = self.__getRandomValue(3) print 'User choice: ',self.__option print 'Computer choice: ',computerOption print self.__computeResult(computerOption) if __name__ == "__main__": print 'Welcome to rock paper scissors' print '1. Rock, 2. Paper, 3. Scissor' val = int(raw_input('Enter your choice Number: ')) if val >=1 and val <= 3: obj = RockPaperScissors() obj.setUserOption(obj.getValueFromList(val-1)) obj.printResult() else: raise ValueError('You are supposed to enter the choice given in the menu') ```
2011/04/26
[ "https://codereview.stackexchange.com/questions/2116", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/3873/" ]
Your random function: ``` def __getRandomValue(self,max): val = random.randint(1,max) return self.getValueFromList(val-1) ``` 1. You only ever call this function with max = 3, since thats the only sensible argument just assume that and don't make the caller pass it 2. You pick a random value between 1 and max, and then subtract one. Better to pick a value between 0 and max-1 (random.randrange make that easy) 3. If you make the l list a class attribute, as Chris suggests, then you can use random.choice to select the option.
It would be more pythonic to use properties (or public fields if you don't need any special getter/setter logic) instead of getter/setter methods.
2,432,596
I'm trying to execute a copy of the Perl interpreter using Java's Runtime.exec(). However, it returned error code `9`. After running the file a few times, the `perl` interpreter mysteriously started to return code 253 with no changes in my command at all. What does code `253` / code `9` mean? A Google search for `perl` interpreter's exit codes turned up nothing. Where can I find a list of exit codes for the Perl interpreter?
2010/03/12
[ "https://Stackoverflow.com/questions/2432596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69783/" ]
The perl interpreter actually *does* return exit codes of its own if the script doesn't run. Most syntax errors lead to exit code 9: Unknown function / disallowed bareword: ``` perl -e 'use strict; print scalar(localtime); schei;' ``` $? = 9 division by zero: ``` perl -e 'use strict; print scalar(localtime); my $s = 1/0;' ``` $? = 9 syntax error: ``` perl -e 'use strict; print scalar(localtime); my $ff; $ff(5;' ``` $? = 9 using die: ``` perl -e 'use strict; print scalar(localtime); die "twaeng!"' ``` $? = 9 an unknown module was the only one situation I found perl to exit differently: ``` perl -e 'use strict; use doof; print scalar(localtime);' ``` $? = 2 BTW I'm still searching for a comprehensive list of the perl interpreter's exit codes myself. Anyone got an idea where to look, aside from the perl interpreters sources?
Perl itself doesn't have any defined exit codes; unless the perl interpreter crashes in a really horrific way, the exit code is determined by the program that `perl` is running, not by `perl` itself.
76,558
First of all, I'm not sure about the title of this question, so please correct me if there is any title more sensible than mine. The problem is the following: I have a function f that checks if a variable as a value. For that, I need to pass the argument "by reference" that is I set HoldAll to f. ``` f[var_] := ValueQ[var]; SetAttributes[f, HoldAll]; f[x] (* False *) x = 10; f[x] (* True *) ``` It works, as long as I call f passing the name of variable. But, if I want to call f on a list of variables, and I use something like a Map, it doesn't work ``` Map[f, {x, y, z}] (* {False, False, False} *) ``` Note that x has a value and the result should be {True, False, False}. Even more clear: ``` {x, y, z} = {1, 2, 3}; Map[f, {x, y, z}] (* {False, False, False} *) ``` The problem is that Map evaluates x and pass the value of x to f, so ValueQ[1](https://mathematica.stackexchange.com/users/125/kguler) gives false. How to get the Map to give the right sequence {True, True, True}. It could be a very stupid solution but today I'm not able to get it. Of course, the actual code is a little bit more complex, I tried to simplify it so to provide a clear example. Thanks for any help. **EDIT** Thanks to kguler, using Unevaluated works for the example I provided above, but not always for my real case. As for the other answer, that using Listable, it works as well but even that is not suitable for my real code because actually my f does many other things and cannot be easily applied to a list (moreover it has many other arguments, not just the variable). I'll try to add here a more realistic example of what I have. Considering this variation: ``` f[vars : {(_) ..}] := Map[ValueQ, vars]; SetAttributes[f, HoldAllComplete]; f[{x}] (* {False} *) x = 10; f[{x}] (* {False} *) f[{Unevaluated@x, Unevaluated@y}] (* {True, False} *) ``` but if I have many variables and I don't know the names, for instance if I have all names of variables in another variable, like the following variables = {x, y, z, q, w, e, r, t} How to call f using Unevaluated? The only solution I can think of is to apply manually the Unevaluated to all variables. Is there another way? **EDIT II** Somehow solutions provided by Mr.Wizard, Kuba and Algohi work fine in my case, but are not so easy as to add Unevaluated in the Map inside the f function, as suggested by [kugler](https://mathematica.stackexchange.com/users/125/kguler).
2015/03/05
[ "https://mathematica.stackexchange.com/questions/76558", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/8565/" ]
The two standard approaches to this problem, [`Unevaluated`](http://reference.wolfram.com/language/ref/Unevaluated.html) and [`Listable`](http://reference.wolfram.com/language/ref/Listable.html), have already been posted. If you need a different kind of evaluation control please consider my original method:[(1)](https://mathematica.stackexchange.com/a/19900/121),[(2)](https://mathematica.stackexchange.com/a/24558/121),[(3)](https://mathematica.stackexchange.com/a/31711/121),[(4)](https://mathematica.stackexchange.com/a/46925/121) Load `step` [How do I evaluate only one step of an expression?](https://mathematica.stackexchange.com/questions/334/how-do-i-evaluate-only-one-step-of-an-expression/1447#1447) then: ``` SetAttributes[f2, HoldAll] f2[s_Symbol] := step[s] /. {_[x_List] :> f2 /@ Unevaluated[x], _ :> ValueQ[s]} ``` Now: ``` x = 1; q := {x, y, z}; f2[q] ``` > > > ``` > {True, False, False} > > ``` > >
you can change the attribute of Map: ``` Clear[f] f[var_] := ValueQ[var] SetAttributes[f, HoldAll] SetAttributes[Map, HoldAll] {x, y, z} = {1, 2, 3}; Map[f, {x, y, z, k}] (*{True, True, True, False}*) ```
6,106,695
I have a Wix solution to install an application. When attempting to uninstall the application from control panel while it is running, a popup is appearing to close the application before continue. The issues is the message showing in that popup which is suppose to be an uninstall message instead of install message. The message is "**The following application is running which is need to be close before continuing the install**" can we customize this default popup and change our message?
2011/05/24
[ "https://Stackoverflow.com/questions/6106695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/724789/" ]
Take a look at the [Identifying app installations](http://android-developers.blogspot.com/2011/03/identifying-app-installations.html) article. You can't rely on `ANDROID_ID`. The best solution is to generate a custom id with: ``` String id = UUID.randomUUID().toString(); ```
If you want to create one with the same format as real `ANDROID_ID`s, you can use the same method they use [here](https://github.com/CyanogenMod/android_frameworks_base/blob/81ed751a1dcf1e7c722db2cdded38bef4308a1c5/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java#L216): ``` private static String generateAndroidId() { String generated = null; try { final SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed( (System.nanoTime() + new SecureRandom().nextLong()).getBytes() ); generated = Long.toHexString(random.nextLong()); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "Unexpected exception", e); } return generated; } ``` Outputs: `9e7859438099538e`
29,918,351
I was asked a question > > You are given a list of characters, a score associated with each character and a dictionary of valid words ( say normal English dictionary ). you have to form a word out of the character list such that the score is maximum and the word is valid. > > > I could think of a solution involving a trie made out of dictionary and backtracking with available characters, but could not formulate properly. Does anyone know the correct approach or come up with one?
2015/04/28
[ "https://Stackoverflow.com/questions/29918351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3966664/" ]
If the number of dictionary entries is relatively small (up to a few million) you can use brute force: For each word, create a 32 bit mask. Preprocess the data: Set one bit if the letter a/b/c/.../z is used. For the six most common English characters etaoin set another bit if the letter is used twice. Create a similar bitmap for the letters that you have. Then scan the dictionary for words where all bits that are needed for the word are set in the bitmap for the available letters. You have reduced the problem to words where you have all needed characters once, and the six most common characters twice if the are needed twice. You'll still have to check if a word can be formed in case you have a word like "bubble" and the first test only tells you that you have letters b,u,l,e but not necessarily 3 b's. By also sorting the list of words by point values before doing the check, the first hit is the best one. This has another advantage: You can count the points that you have, and don't bother checking words with more points. For example, bubble has 12 points. If you have only 11 points, then there is no need to check this word at all (have a small table with the indexes of the first word with any given number of points). To improve anagrams: In the table, only store different bitmasks with equal number of points (so we would have entries for bubble and blue because they have different point values, but not for team and mate). Then store all the possible words, possibly more than one, for each bit mask and check them all. This should reduce the number of bit masks to check.
Can we assume that the dictionary is fixed and the score are fixed and that only the letters available will change (as in scrabble) ? Otherwise, I think there is no better than looking up each word of the dictionnary as previously suggested. So let's assume that we are in this setting. Pick an order < that respects the costs of letters. For instance Q > Z > J > X > K > .. > A >E >I .. > U. Replace your dictionary D with a dictionary D' made of the anagrams of the words of D with letters ordered by the previous order (so the word buzz is mapped to zzbu, for instance), and also removing duplicates and words of length > 8 if you have at most 8 letters in your game. Then construct a trie with the words of D' where the children nodes are ordered by the value of their letters (so the first child of the root would be Q, the second Z, .., the last child one U). On each node of the trie, also store the maximal value of a word going through this node. Given a set of available characters, you can explore the trie in a depth first manner, going from left to right, and keeping in memory the current best value found. Only explore branches whose node's value is larger than you current best value. This way, you will explore only a few branches after the first ones (for instance, if you have a Z in your game, exploring any branch that start with a one point letter as A is discarded, because it will score at most 8x1 which is less than the value of Z). I bet that you will explore only a very few branches each time.
16,702,672
IMO, this query should return `A=1,B=2,` ``` SELECT regexp_substr('A=1,B=2,C=3,', '.*B=.*?,') as A_and_B FROM dual ``` But it returns the whole string, `A=1,B=2,C=3,`, instead. Why? --- **Update 1:** Oracle 10.2+ is required to use Perl-style metacharacters in regular expressions. **Update 2:** A more clear form of my question (to avoid questions about Oracle version and availability of Perl-style regex extension): ***On the same system***, why does a non-greedy quantifier sometimes work as expected and sometimes not? This works correctly: ``` regexp_substr('A=1,B=2,C=3,', 'B=.*?,') ``` This doesn't work: ``` regexp_substr('A=1,B=2,C=3,', '.*B=.*?,') ``` [Fiddle](http://www.sqlfiddle.com/#!4/d41d8/11449) **Update 3:** Yes, it seems to be a bug. **What is the Oracle support reaction on this issue?** Is the bug already known? Does it have an ID?
2013/05/22
[ "https://Stackoverflow.com/questions/16702672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1847592/" ]
It's a BUG! =========== You are right that in Perl, `'A=1,B=2,C=3,' =~ /.*B=.*?,/; print $&` prints `A=1,B=2,` What you have stumbled upon is a bug that still exists in Oracle Database 11g R2. If the exact same regular expression atom (including the quantifier but excluding the greediness modifier) appears twice in a regular expression, both occurrences will have the greediness indicated by the first appearance regardless of the greediness specified by the second one. That this is a bug is clearly demonstrated by these results (here, "the exact same regular expression atom" is `[^B]*`): ``` SQL> SELECT regexp_substr('A=1,B=2,C=3,', '[^B]*B=[^Bx]*?,') as good FROM dual; GOOD -------- A=1,B=2, SQL> SELECT regexp_substr('A=1,B=2,C=3,', '[^B]*B=[^B]*?,') as bad FROM dual; BAD ----------- A=1,B=2,C=3, ``` The only difference between the two regular expressions is that the "good" one excludes 'x' as a possible match in the second matching list. Since 'x' does not appear in the target string, excluding it should make no difference, but as you can see, removing the 'x' makes a big difference. That has to be a bug. Here are some more examples from Oracle 11.2: ([SQL Fiddle with even more examples](http://www.sqlfiddle.com/#!4/d41d8/11498)) ``` SELECT regexp_substr('A=1,B=2,C=3,', '.*B=.*?,') FROM dual; => A=1,B=2,C=3, SELECT regexp_substr('A=1,B=2,C=3,', '.*B=.*,') FROM dual; => A=1,B=2,C=3, SELECT regexp_substr('A=1,B=2,C=3,', '.*?B=.*?,') FROM dual; => A=1,B=2, SELECT regexp_substr('A=1,B=2,C=3,', '.*?B=.*,') FROM dual; => A=1,B=2, -- Changing second operator from * to + SELECT regexp_substr('A=1,B=2,C=3,', '.*B=.+?,') FROM dual; => A=1,B=2, SELECT regexp_substr('A=1,B=2,C=3,', '.*B=.+,') FROM dual; => A=1,B=2,C=3, SELECT regexp_substr('A=1,B=2,C=3,', '.+B=.+,') FROM dual; => A=1,B=2,C=3, SELECT regexp_substr('A=1,B=2,C=3,', '.+?B=.+,') FROM dual; => A=1,B=2, ``` The pattern is consistent: the greediness of the first occurrence is used for the second occurrence whether it should be or not.
Because you're selecting too much: ``` SELECT regexp_substr( 'A=1,B=2,C=3,', '.*?B=.*?,' ) as A_and_B, -- Now works as expected regexp_substr( 'A=1,B=2,C=3,', 'B=.*?,' ) as B_only -- works just fine FROM dual ``` SQL Fiddle: <http://www.sqlfiddle.com/#!4/d41d8/11450>
6,822,970
I meet a headache problem. there are too many Quotation marks in my code make me headache. I tried both of these method, but all the way are make links broken. I cheked it in `chrome`, In `elements`, I find the source code like what I add after `print($link);`. How to solve the problem? Thanks. ``` $str = 'I\'m very "shock"!'; $link=<<<EOT <a Onclick="javascript('$str')" href="#">$str</a>' EOT; print($link); // <a onclick="javascript('I'm very " shock"!')"="" href="#">I'm very "shock"!</a> ``` OR ``` $str = 'I\'m very "shock"!'; $link = '<a Onclick="javascript(\''.$str.'\')" href="#">'.$str.'</a>'; print($link); //<a onclick="javascript('I'm very " shock"!')"="" href="#">I'm very "shock"!</a> ```
2011/07/25
[ "https://Stackoverflow.com/questions/6822970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/783396/" ]
There is an alternate form of Throwable.printStackTrace() that takes a print stream as an argument. <http://download.oracle.com/javase/6/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)> E.g. ``` catch(Exception e) { e.printStackTrace(System.out); } ``` This will print the stack trace to std out instead of std error.
If you are interested in a more compact stack trace with more information (package detail) that looks like: ``` java.net.SocketTimeoutException:Receive timed out at j.n.PlainDatagramSocketImpl.receive0(Native Method)[na:1.8.0_151] at j.n.AbstractPlainDatagramSocketImpl.receive(AbstractPlainDatagramSocketImpl.java:143)[^] at j.n.DatagramSocket.receive(DatagramSocket.java:812)[^] at o.s.n.SntpClient.requestTime(SntpClient.java:213)[classes/] at o.s.n.SntpClient$1.call(^:145)[^] at ^.call(^:134)[^] at o.s.f.SyncRetryExecutor.call(SyncRetryExecutor.java:124)[^] at o.s.f.RetryPolicy.call(RetryPolicy.java:105)[^] at o.s.f.SyncRetryExecutor.call(SyncRetryExecutor.java:59)[^] at o.s.n.SntpClient.requestTimeHA(SntpClient.java:134)[^] at ^.requestTimeHA(^:122)[^] at o.s.n.SntpClientTest.test2h(SntpClientTest.java:89)[test-classes/] at s.r.NativeMethodAccessorImpl.invoke0(Native Method)[na:1.8.0_151] ``` you can try to use [Throwables.writeTo](https://github.com/zolyfarkas/spf4j/blob/master/spf4j-core/src/main/java/org/spf4j/base/Throwables.java#L536) from the [spf4j](http://www.spf4j.org) lib.
38,563,317
I'm trying to make a search fragment similar to the one in the Play Store: [![Google Play Store](https://i.stack.imgur.com/AG5KD.png)](https://i.stack.imgur.com/AG5KD.png) My `AppBarLayout` has a `CardView` in it, and the background is set to transparent: ``` <android.support.design.widget.CoordinatorLayout android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/transparent" android:theme="@style/ThemeOverlay.AppCompat.ActionBar" app:elevation="0dp"> <!-- CardView --> </android.support.design.widget.AppBarLayout> <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <!-- Main content --> </android.support.v4.widget.NestedScrollView> </android.support.design.widget.CoordinatorLayout> ``` But as you can see, there is a solid background behind the `CardView` so that the content behind it is hidden: [![Hidden content](https://i.stack.imgur.com/IfXVA.png)](https://i.stack.imgur.com/IfXVA.png) How can I make the `AppBarLayout`'s background transparent so that the content behind is visible?
2016/07/25
[ "https://Stackoverflow.com/questions/38563317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490484/" ]
The same problem happened to me and at this point it has nothing to do with the transparency of the `AppBarLayout`. But the `AppBarLayout` pushes the content of your `NestedScrollView` below itself when fading in. You can solve this by 1. moving your `NestedScrollView` up and behind the `AppBarLayout` and 2. adding a space element to your `NestedScrollView` with the size of the AppBar **Step 1** can be easily achieved by adding this to your `onCreate()` ``` mNestedScroll.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { mNestedScroll.getViewTreeObserver().removeOnGlobalLayoutListener(this); final int appBarHeight = mAppBar.getHeight(); mNestedScroll.setTranslationY(-appBarHeight); mNestedScroll.getLayoutParams().height = mNestedScroll.getHeight() + appBarHeight; } }); ``` For **Step 2** you need to add an empty view with the height of the appBar as a spacer to your `NestedScrollView`. Note: I used a `RecyclerView` instead of a `NestedScrollView` in my approach, so I had to add an empty ViewHolder with the appBarHeight to my RecyclerView. So this snippet is not tested, but it should do the trick for you: ``` <View android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"/> ```
Try putting the CardView into a FrameLayout with `match_parent` dimensions, so that the CardView has the space around it. I'm not 100% confident that it will work, but it's worth trying.
8,661,559
I have this code: ``` import java.util.Scanner; public class Example { public static void main(String[] args) { Scanner input = new Scanner(System.in); String answer = input.nextLine(); if(answer == "yes"){ System.out.println("Yea I programmed this right!"); }else{ System.out.println("Awww :("); } } } ``` But when I run it and type *yes*, it should be saying **"Yea I programmed this right!"** but it says "**Awww :(**"
2011/12/28
[ "https://Stackoverflow.com/questions/8661559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/924378/" ]
``` if(answer == "yes"){ ``` should be ``` if("yes".equals(answer)){ ``` (`==` is not correct for `String` equality, and we handle the case where `answer` is null)
import java.util.Scanner; public class Example { public static void main(String[] args) { ``` Scanner input = new Scanner(System.in); String answer = input.nextLine(); /*Edit your next line as mine,u'll get the correct ans...*/ if("yes".equals(answer)){ System.out.println("Yea I programmed this right!"); }else{ System.out.println("Awww :("); } ``` } }
19,499,096
I have a bunch of subfolders and I want to put them in the drawable folder so that I can support all screens is there another way I can do it because I read that you cant put subfolder but I want to support all screens
2013/10/21
[ "https://Stackoverflow.com/questions/19499096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975060/" ]
You don't need subfolders in the drawable folder but different drawable-folders. Such as: drawable-hdpi drawable-xhdpi drawable-mdpi and have a look at the documentation in @Raghunandan's comment!
No sub-folders is required at all for supporting in all screen sizes. Just put your data's (images, icons etc.) on the default drawable folders [drwable-hdpi,drwable-ldpi,drwable-mdpi.. ].And don't forget to keep required sizes of the images,icons for different screens. For more details please follow this [link](http://developer.android.com/guide/practices/screens_support.html).
27,385,506
Can someone help me confirm the default port when using ftplib.FTP\_TLS? We have opened port 990 and 21 but my script fails to connect. ``` import ftplib session = ftplib.FTP_TLS('xxx.ftp.com','user','password') file = open('Bkup.tar.gz','rb') session.storbinary('STOR Bkup.tar.gz', file) file.close() session.quit() ``` Thank You!
2014/12/09
[ "https://Stackoverflow.com/questions/27385506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2565554/" ]
Please don't modify the port directly. If you get a closer look at `FTP_TLS` super `__init__` you can clearly see that if it's called with a host param `connect` gets automatically called with just the host as param so the port defaults to `FTP_PORT` which is 21. A better approach would be to call `FTP_TLS` without any params and then manually call the `connect` method where you can specify host as well as port. ``` from ftplib import FTP_TLS client = FTP_TLS() client.connect(host="ftp.example.com", port=12121) ```
Oddly, the [FTP\_TLS](https://docs.python.org/3/library/ftplib.html#ftplib.FTP_TLS) object has no direct port parameter on the constructor like the [FTP](https://docs.python.org/3/library/ftplib.html#ftp-objects) object does. you can set the port prior to calling the constructor and that works. ``` ftplib.FTP_TLS.port=1234 ftplib.FTP_TLS( 'ftphost.domain.tld', 'user', 'password' ) ```
1,073,488
I have an Excel workbook which is used to produce quotations for customers. It automatically generates a unique quotation number based on the salesperson's name, the name of the company receiving the quotation, the date, and the issue number (if two separate quotations are being made by the same salesperson, for the same company, on the same day, the first will have the issue number 01, the second will have the issue number 02, etc.) Filled with dummy information, a typical quotation number will look like this: > > JS-ABC-05052016-01 > > > The 'JS' is the initials of the salesperson (John Smith.) The 'ABC' is the first three characters of the company name (ABCompany.) The '05052016' is today's date, and '01' is the issue number. This is all information entered by the salesperson. The formula used in the cell which generates and displays the quotation number is: ``` =UPPER(LEFT(P4,1)&LEFT(P5,1)&"-"&LEFT(D11,3)&"-"&LEFT(K6,2)&MID(K6,4,2)&MID(K6,7,4)&"-"&D5) ``` The above formula is taking pieces of information that are entered in cells, and compiling them to generate the quotation number. There is an issue, however, when the first three characters of the company name contains a blank space, or a special character. For example, a company name of 'A. B. Company' would generate the following quotation number: > > JS-A. -05052016-01 > > > Another example is that a company name of 'A&B Company' would generate the following quotation number: > > JS-A&B-05052016-01 > > > Further along in the quotation process, the workbook will be renamed to contain the quotation number. This can cause issues where the quotation number contains a special character such as a period (for example, it can mess up the file type.) Is there a way to make Excel ignore any characters (including spaces) in the company name that aren't letters or numbers? For example, making a company named 'A. & B. Company' generate the quotation number: > > JS-ABC-05052016-01 > > >
2016/05/05
[ "https://superuser.com/questions/1073488", "https://superuser.com", "https://superuser.com/users/565490/" ]
Resetting the Bash Subsystem is pretty easy. To uninstall it fully, use the following command: ``` lxrun /uninstall /full ``` To reinstall it, use this command: ``` lxrun /install ``` This will re-download it from the Windows Store - it is not that large and you will get a completely fresh copy. If you really screw up, re-downloading might be the only way to go.
Starting with the Windows 10 Fall Creators Update, you must use `wslconfig` (instead of `lxrun`) to manage the WSL distributions. You can [read the documentation from Microsoft](https://docs.microsoft.com/es-es/windows/wsl/wsl-config#managing-multiple-linux-distributions). Note that you can install multiple linux distributions in your WSL. To list the distributions you have, you can use: ``` wslconfig /list /all ``` To remove a distribution, you must unregister it. The WSL will keep the installer but it will remove all the programs and user data. ``` wslconfig /unregister <DistributionName> ```
7,511,216
In my app i have 3 activities. From 1st activity it goes to 2nd and from 2nd it goes to 3rd. From 3rd it is coming to 1st again. and if I press back key from the 1st then it should go to home screen (App will stop). If I press back key of 1st its goes to 2nd activity again and if I press 2nd's back key, then it goes to the 1st . Then if I press back key of 1st then app stops. What I want , when I am in 3rd activity and press the back button then it should go to 1st and simultaneously finish the 2nd activity. How can I do that?
2011/09/22
[ "https://Stackoverflow.com/questions/7511216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1147007/" ]
When you start your third activity you should call in your 2nd acitivity like this: `startActivityForResult(intent, 0)` When you finish your 3rd activity, you should include: ``` setResult(RESULT_OK); finish(); ``` It sends a signal from the 3rd activity to the 2nd. In the 2nd put: ``` protected void onActivityResult(int requestCode, int resultCode, Intent data) { finish(); } ``` It receives this signal and finishes the 2nd activity.
Using this way: In your first activity, declare one Activity object like this, ``` public static Activity fa; onCreate() { fa = this; } ``` now use that object in another Activity to finish first-activity like this, ``` onCreate() { FirstActivity.fa.finish(); } ``` More information : [Finish an activity from another activity](https://stackoverflow.com/questions/10379134/finish-an-activity-from-another-activity)
37,523
On rare occasions, you are in a situation where a simple *Thank You* seems like you're undermining the other person's help. You know, instances where you are too grateful to express your feelings of gratitude. When this happens face to face (or even over the phone) your body language/voice carry that feeling and the other person understands the full gravity of your expression. However, many a time, all you have is online/email interface for expression. And words are all you can use. So my question(s) is(are): 1. Is there a *superlative* form of *Thank You* which one can make use of in such cases? 2. Will you advice using the same during face-to-face(or voice)? 3. Which is the highest degree of gratitude you have seen/expressed? 4. Is there any chance that the other person might think you are exaggerating? (If you are wondering about the last question : see my comment (3rd one) below [this SO answer](https://stackoverflow.com/questions/5329664/is-this-correct-object-oriented-programing-in-php/5333415#5333415). Its not that there are no good books/authoritative articles/sources on theory of Object Oriented Programming. I have read few, if not many, of them. And I *do* feel strongly about the answer the user has given. But at the same time, I don't want to *overdo* it)
2011/08/10
[ "https://english.stackexchange.com/questions/37523", "https://english.stackexchange.com", "https://english.stackexchange.com/users/11714/" ]
You could use "Many thanks". This would sound weird in person, though. Also, emphasizing with another sentence would work: "Thank you. I genuinely appreciate it."
To literally use a superlative (in the grammatical more/most big/bigger/biggest sense), you could say: > > **I am most grateful.** > > > From the acknowledgements of R. W. G. Hunt's *Measuring Color:* (2011) > > I am most grateful to Dr M. R. Pointer of Kodak Limited for kindly making many helpful comments on the text... > > > From the acknowledgements of Jak Mallmann Showell's *Hitler's Navy:* (2009) > > I am most grateful to everybody who has helped and many have not only provided additional information, but also become good friends. > > > For dramatic hyperbole that is only at home in fantasy stories where an individual averts the doom of a people: > > **We are eternally grateful.** > > > From Glazer et al's *Having Your Baby Through Egg Donation:* (2011) > > If only I am able to have a baby, I will be eternally grateful > > >
39,083
Suppose a bond has annual coupon of \$1 and face value of \$100 and matures in two years. If recovery rate is $50\%$ and the bond defaults before the first coupon payment. How should we receive the recovery? Is it \$50 at year 2 or \$0.5 at year 1 and \$100.5 at year 2?
2018/03/30
[ "https://quant.stackexchange.com/questions/39083", "https://quant.stackexchange.com", "https://quant.stackexchange.com/users/33550/" ]
There are at least two ways of doing it: 1) Resampling them to their median frequency. 2) Build one ML model for each data type, then combine the 4 different forecasts into a single meta-ML model. (Courtesy: MARCOS LO´PEZ DE PRADO)
Consider investigating the MIDAS approach of incorporating signals with different frequencies. The classical apporach is to create a signal based on each source and tune it to your trading/rebalancing frequency. Convert this signal to an alpha based on Grinold and Khan, then add the alphas together.
72,247
In the finale to Doctor Who's 8th series, *Death in Heaven*, > > where did the newly created Cybermen's armour come from? I mean, they rose from their graves already fully suited up. Not to mention the fuel to drive their thrusters! > > > I was hoping this would be mentioned, at least in passing, but everybody totally ignored it, as if it was normal. Unless I'm missing some clue? (Oh, and if anyone can improve on the title, while still keeping it informative and non-spoilerish, I'd be delighted!)
2014/11/09
[ "https://scifi.stackexchange.com/questions/72247", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/4495/" ]
The Doctor stated (at 18:20 for those of you with access to IPlayer) that the rain was actually 'cyber-pollen'. > > It wasn't rain, man-scout, it was pollen. Cyber-pollen. > Every tiny particle of a cyberman contains the plans to make another cyberman > > > Combine that with the dimensionally trancendental technology of a time lord (a la Missy) and an interesting new fluid capable of hiding non biological matter ("Dark Water"), and you have rain capable of full cyber conversion of the dead.
I had noticed that the 'water' was flowing uphill so the contact in the morgue would be related to that same gravity defeating nanotechnology, the increase in mass however and the sourcing of metals from the environment rather stretches credibility.
12,709,811
Hello I would like to slightly modify the below script so that it outputs the response to a div rather than a alert see bold section. Any help appreciated! ``` function processResponse() { if (gateway.readyState == 4 && gateway.status == 200) { alert("Done loading!\n\nThe response from the PHP script was: "+gateway.responseText); } } ```
2012/10/03
[ "https://Stackoverflow.com/questions/12709811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1717236/" ]
if the div has an id try something like this: ``` document.getElementById("divId").innerHTML = gateway.responseText; ```
``` function processResponse() { if (gateway.readyState == 4 && gateway.status == 200) { document.getElementById("yourDiv").innerHTML = "php script was : " + gateway.responseText; } } ``` or if using jquery ``` function processResponse() { if (gateway.readyState == 4 && gateway.status == 200) { $("#youdivid").html("php script was : " + gateway.responseText); } } ```
48,386,263
how do I pivot a results query? currently it looks like this ``` Hours | Volume 8 | 1000 9 | 1012 10 | 1045 11 | 1598 12 | 1145 13 | 1147 ``` into this ``` 8 |9 |10 |11 |12 |13 1000|1012|1045|1598|1145|1147 ``` I tried the following but its not working ``` Select #TEMP.volume, pvt.volume, #TEMP.volume pvt.volume FROM #TEMP PIVOT (volume FOR [DialHour] IN ( "8", "9", "10", "11","12","13","14","15","16","17","18","19")) AS pvt ```
2018/01/22
[ "https://Stackoverflow.com/questions/48386263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7345871/" ]
This assumes you are working with **SQL Server** , then it is always better to use dynamic **PIVOT** approach ``` declare @col nvarchar(max), @query nvarchar(max) select @col = stuff( (select ','+quotename(Hours) from #tm for xml path('')), 1,1, '') set @query = N'select * from ( select * from #tm )a PIVOT ( MAX(Volume) for Hours in ('+@col+') )pvt' EXECUTE sp_executesql @query ``` **Result :** ``` 8 9 10 11 12 13 1000 1012 1045 1598 1145 1147 ```
It is always good to use pivot query in addition to an ID column , to simplify u can get result set this way ``` WITH cte AS ( SELECT * FROM #TEMP PIVOT(max(volume) FOR [DialHour] IN ( "8" ,"9" ,"10" ,"11" ,"12" ,"13" ,"14" ,"15" ,"16" ,"17" ,"18" ,"19" )) AS pvt ) SELECT 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19... FROM cte ```
86,066
Is explaining consciousness in the realm of physics? **Detailed question:** We know that consciousness exists. Or rather, I know that I have it. The rest of you may not be conscious, but I know that I am, so it exists. Since it's the job of physics to explain everything in the universe (even indirectly), I feel that sooner or later, we have to tackle how consciousness arises. With other phenomena, yes. Physics *does* answer them. We see a straightforward link between the fundamental laws of physics and the phenomena in question. Examples: Economics → human psychology → evolutionary biology → biology → chemistry → physics Climate science → thermodynamics/weather/geology, etc. -> physics Fluid mechanics → collected movements of particles → physics So with all other phenomena, we see the links between them and physics. The links may be too numerous to compute, but there's nothing mysterious about these links. We can easily observe and measure these links, no problemo. With consciousness however, there appear to be no links to explain how subjective experience can possibly arise from the interaction of particles. It seems to be the only phenomena in nature for which we have zero inkling of how it arises. I feel that this is a challenge that physics should not ignore. But there are some physicists who feel it's not in the domain of physics to explain how consciousness arises. What do you think? Is consciousness in the domain of physics, or is it outside? Some say that the physics only deals with experiments reproducible by others. This would imply that a single person by themselves could never, ever be scientific, which I think is inaccurate. It converts physics into a social science field.
2021/09/21
[ "https://philosophy.stackexchange.com/questions/86066", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/56069/" ]
In seeking to describe the 'truths of nature', natural philosophy that focused on *physika*, 'the natural things', came to mean explicitly not animals (biology) or minds (philosophy). But physics has been on a journey of unification, which is better thought of as having arrived at the power of the 'languages' of energy and information, as discussed here: [Is the idea that "Everything is energy" even coherent?](https://philosophy.stackexchange.com/questions/85899/is-the-idea-that-everything-is-energy-even-coherent/85950#85950) David Deutsch made the case in The Fabric Of Reality that we need [four strands](https://en.m.wikipedia.org/wiki/The_Fabric_of_Reality#The_four_strands), styles of approach, to account for the universe at large. With his [Constructor Theory](https://en.wikipedia.org/wiki/Constructor_theory) he is aiming to provide an integrated picture for the four strands, a shared language, which could then specifically integrate information theory with wider physics. [Conway's Game Of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life), which is Turing complete and can simulate universal Turing constructors, gives an intuitive example of a very simple picture out of which information and things reminiscent of life can be constructed, illustrating the process. Consciousness as presented in the Hard Problem, as qualia, is dangerously close to metaphysics. If no one else can really 'get' something about your experience, it is not part of the shared domain, expressible in these universal languages of energy and information, that build up a picture of complex behaviours from simple things. It is unverifiable. Qualia as usually defined, just isn't part of physics. It may be real, though physicalists don't generally think so, but as something intrinsically personal it doesn't relate to this wider picture. It's kind of funny to ask if physics should explain consciousness, when we call it a biological phenomenon, and have neuroscience and other specialisms focusing on our brains, synthetic ones and so on. But chemistry has been completely 'folded in' to physics, integrated with the picture of fundamental building blocks and the energy-information mode of prediction. We have no reason to think biology won't follow, though it's a lot more complicated a lot has already. But still biology won't be physics, neither will consciousness - but we expect they will be integrated with this physics picture in the same way chemistry has. Should physics be focused on explaining consciousness? It's been estimated that with very small VonNeuman replicator probes humans could colonise our galaxy using technology we understand now and currently achievable speeds, in less than 10,000 years. So the impact of life will become very important in shaping the future evolution of the cosmos at the large scale, even without life elsewhere. At the small scale, quantum biology proved essential to understanding how chlorophyll works, and OrchOR theory proposes a role for quantum behaviour in neurons. So, while explaining consciousness is not an explicit goal of physics, the journey of unification seems to point towards inevitably requiring understanding consciousness, or at least the fundamental mechanisms, and widest impacts. Popper would certainly not accept that science is only about the reproducible. He regarded the idea science is based on induction as a myth, and focused on experiments as *testing models*. Treating a specific persons illness, would not be science by the former model, as their unique predicament can't be replicated. But it could be by the latter model.
If physics wants to explain consciousness, then it would ultimately need to discover possible measurable properties. In my mind, this comes down to finding those attributes of consciousness that may or may not happen to be exactly (or at least approximately) identical for every individual. Unfortunately, we currently have no faith in such a discovery, because we consider consciousness a metaphysical construct, which is even contrary to science.
37,815,601
I have the following entities that i want my web service to pass as jsons ``` @Entity(name = "tests") public class Test { @Id @GeneratedValue private int id; @Column(name = "test_name") private String name; @JoinColumn(name = "test_id") @OneToMany(cascade = CascadeType.REMOVE) private List<Question> questions; } @Entity(name = "questions") public class Question { @Id @GeneratedValue private int id; @Column private String question; @Column(name = "is_multi_select") private boolean isMultiSelect; @JoinColumn(name = "question_id") @OneToMany(cascade = CascadeType.REMOVE) private List<Answer> answers; } ``` The problem is i want the question list not to be included in my json, but i just can't make jackson ignore them. I tried to annotated the question list with `@JsonIgnore`, but no result. How do i do this? P.S. Forgot to mention that the serialization is done via jersey, and here's the method that actually returns my test list ``` @GET @Produces(MediaType.APPLICATION_JSON) @Path("/tests") public Response getLanguageList() { List<Test> tests = TestDao.getTests(); return Response.status(200).entity(tests).build(); } ```
2016/06/14
[ "https://Stackoverflow.com/questions/37815601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3852459/" ]
``` @JsonInclude(JsonInclude.Include.NON_EMPTY) ``` NON\_EMPTY makes include only non null fields and not empty collection type fields.
You have to configure your mapper to ignore empty arrays: ``` ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false); ``` To ignore a specific property, the `com.fasterxml.jackson.annotation.JsonIgnore` annotation should do: ``` @JsonIgnore @JoinColumn(name = "test_id") @OneToMany(cascade = CascadeType.REMOVE) private List<Question> questions; ``` **EDIT:** You may need to enable Jackson with this in your `web.xml`: ``` <init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param> ``` or configuring though code: ``` ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(clientConfig); ``` Reference: <https://jersey.java.net/documentation/1.19.1/json.html>
20,175,626
I need a program, that checks input number with latest input, and if it's true - show how many numbers were inputed (with latest 2 same); Example: Input: 3 5 24 4 3 5 3 5 3 5 5 Output: 11 ``` #include <iostream> using namespace std; int main() { int nr, am, last; cin >> nr; last = nr; am = 1; while (nr != last){ cin >> nr; last = nr; am = am + 1; } cout << am; return 0; } ``` I will rewrite code later to work with files, I just need to make it work first. Also, I don't want to get finished code, I want to know my misstakes, and or I'm going on right way. Thanks.
2013/11/24
[ "https://Stackoverflow.com/questions/20175626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3027389/" ]
In the while guard last != nr is never true, because you read from cin first and then update last. This two statements should be switched, also initialize last with (for example) -1, so the while loop is entered the first time. initialize last: ``` last = -1; ``` in your while: ``` last = nr; cin >> nr; ```
You never enter your while loop, because you're assigning `nr` to `last` just before your test: ``` last = nr; // ... while (nr != last){ // ... } ``` `while` condition is evaluated **before** entering the loop.
162
So far on writers.SE we've had a few questions asking for examples of published works that show how to do something well. For example * [Examples for books that don't use (traditional) chapters](https://writers.stackexchange.com/questions/976/examples-for-books-that-dont-use-traditional-chapters) * [Story for children without a happy ending](https://writers.stackexchange.com/questions/287/story-for-children-without-a-happy-ending) * [What books should I read before writing a non-humanoid point of view story?](https://writers.stackexchange.com/questions/499/what-books-should-i-read-before-writing-a-non-humanoid-point-of-view-story) Should we create a tag that unifies these questions? I believe that they do provide value to the site, although unless they ask for "...and why do your examples work" or other additional detail they *certainly* fall into the category of lists of X and therefore are prime candidates for CW if we choose to allow it. If you do think we should have a single tag that covers such questions, what would it be? `published-examples`?
2010/12/21
[ "https://writers.meta.stackexchange.com/questions/162", "https://writers.meta.stackexchange.com", "https://writers.meta.stackexchange.com/users/20/" ]
This might be a bit of an odd one, but how about something with [Writing Excuses](http://www.writingexcuses.com/)? It's probably the most popular writing podcast out there, so if we can get a plug on it we'll get a lot of coverage. Even better would be if we could get the hosts to contribute to the site.
The following is a *Community Wiki* answer for the purposes of drafting a common e-mail or letter that we can use when contacting others. It is there to be edited as well as used, so please go ahead and modify it. When you are contacting people, if you already have a relationship with someone you may want to eschew the form letter. This can be a place to start talking about ourselves to others, though. --- Dear /Name/, I have been a fan of your {blog|podcast|zine} for some time now. As a {writer|editor|agent|employee at /organization/} I am constantly seeking information about the writing world. I've recently discovered a new site for questions and answers about writing and writing careers. This site seeks to be a place for experts to ask and answer questions about all genres of writing and many aspects of the writing discipline. Some of the questions since the site's inception that show its potential include: * [Help me find the unnecessary words](https://writers.stackexchange.com/questions/665/something-different-help-me-find-the-unnecessary-words) * [What are some ways to get to know your characters?](https://writers.stackexchange.com/questions/582/what-are-some-ways-to-get-to-know-your-characters) * [Should DOIs ever be preferred to ISBNs?](https://writers.stackexchange.com/questions/944/should-dois-ever-be-preferred-to-isbns) We are looking for more experts to participate in this site, and I thought of you. Would you be willing to visit <http://writers.stackexchange.com> and check it out? If you like it, we'd also love if you encourage others you know in the business and art of writing to take a look. Sincerely, /Your Name/
211,722
I want to delete an array of elements from another one, `DeleteCases` seems to be an option, but the problem is that it deletes an element more than once if available, I do not want this. I want to delete any element as many times as available in second list. For example `DeleteCases[{1, 1, 2, 3}, Alternatives@@{1, 2}]` gives `{3}`, which means it deleted `1` twice from the first array. I want the output to be `{1, 3}`. Is there any function other than `DeleteCases` which can do this?
2019/12/20
[ "https://mathematica.stackexchange.com/questions/211722", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/49535/" ]
You can use the [`ResourceFunction`](http://reference.wolfram.com/language/ref/ResourceFunction) [MultisetComplement](https://resources.wolframcloud.com/FunctionRepository/resources/MultisetComplement) to do this: ``` ResourceFunction["MultisetComplement"][{1, 1, 2, 3}, {1, 2}] ``` > > {1, 3} > > >
Another approach is to use explicit iterators in `Condition`: ``` Module[{n=1,k=1}, Replace[{1, 1, 2, 3, 2}, {1 :> Nothing/; n++ == 1, 2 :> Nothing/; k++ == 1},{1}]] ``` > > > ``` > {1, 3, 2} > > ``` > >
59,119,158
*Hello,* I'm trying to make an algorithm with pulp to resolve a JOB SEQUENCING problem. I know that it is not the best way to use a MIP solver to resolve JOB SEQUENCING, however it's just for training. But my code it's not good and doesn't produce the good solution(full 0). So if someone helpful can have a look. Thank you ! ``` import numpy import pulp import time # Work must me achieve before : deadline=[2,4,3,7,10] # Score of each work : score = [10,30,20,50,20] # Time to do the work : time=[2,2,2,5,3] # Just works index : works = [0,1,2,3,4] tMax = max(deadline) nItem = len(deadline) # Create (item, time) variables s = [(i,j) for i in range(0,nItem) for j in range(0,tMax)] prob = pulp.LpProblem("Job_Sequencing_Problem", pulp.LpMaximize) wk = pulp.LpVariable.dicts("Works", s,lowBound=0, upBound=1, cat=pulp.LpInteger) # We want to maximize the score prob+=pulp.lpSum([wk[(i,j)]*score[i] for i in range (0,nItem) for j in range(0,tMax)]) # Respect deadline constraints for i in range (0,nItem): for j in range(0,tMax): # j represent time(or step) where we are # If we are at t=3 and the object takes 2 sec to compile # but the deadline is t=4 it's not good if j>(deadline[i]-time[i]): prob+=pulp.lpSum(wk[(i,j)])==0 for i in range(0,nItem): # Works can only be done once prob+=pulp.lpSum([wk[(i,j)] for j in range(0,tMax)]) <=1 # We must add time to achieve work constraint for j in range(0,tMax): # If the sum of time to achive work of before jobs, are greater than the current time who we # are, it's not good, so we add this constraint timeToFinishPreviousWork = 0 for x in range(0,tMax-1): for y in range(0,nItem): timeToFinishPreviousWork += wk[(y,x)]*time[y] # wk[(i,j)]*(j+1) = current t prob+=pulp.lpSum(wk[(i,j)]*(j+1)) >= timeToFinishPreviousWork prob.solve() for i in range(0,nItem): for j in range(0,tMax): print("%s = %f" % (wk[(i,j)], pulp.value(wk[(i,j)]))) ```
2019/11/30
[ "https://Stackoverflow.com/questions/59119158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12283022/" ]
Try with the default `.htaccess` and check. ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ```
I solve the above issue by updating xyz.com.conf file with below codes: ``` <Directory /var/www/html/wordpress> Require all granted RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [L] </Directory> <VirtualHost *:80> ServerAdmin admin@xyz.com ServerName xyz.com ServerAlias www.xyz.com DocumentRoot /var/www/html/wordpress ErrorLog ${APACHE_LOG_DIR}/xyz.com_error.log CustomLog ${APACHE_LOG_DIR}/xyz.com_access.log combined <Directory /var/www/html/wordpress> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory> </VirtualHost> ```
52,773,056
I have a Problem with my code.I want to get all Cells and to put These in an Array but it didnt work. Runtime Error 13. Range -> Array ``` For z = 0 To 3 Worksheets(Tabellen(z)).Select AnzahlZellen = Application.WorksheetFunction.CountA(Range("A:A")) For n = 1 To AnzahlZellen 'Worksheets(Tabellen(z)).Select' Range("A" & n).Select InhaltsArray(n) = Range("A" & n).Value ```
2018/10/12
[ "https://Stackoverflow.com/questions/52773056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10489030/" ]
In this case you could build a one-dimensioal array like that ``` Dim vDat as variant Dim rg as range Set rg = Range("A1:A" & AnzahlZellen) vDat = WorksheetFunction.Transpose((rg)) ``` In this way you can easily read from a range of cells to an array. You can also write from an array to a range of cells. Usually you get a 2D-array but as you only have one column you can convert it by Transpose into a 1D-array. As you did not show the declaration of InhaltsArray I guess the [run time error 13](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/type-mismatch-error-13) is caused by some content of the range which does not fit the data type of InhaltsArray As an additional comment to your code: Most of the time you do not need [select](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba)
It looks like you are trying to store 4 worksheets' column A values into a single 1-D array, ``` dim i as long, n as long, z as long, tmp as variant for z=lbound(Tabellen) to ubound(Tabellen) with Worksheets(Tabellen(z)) if z=lbound(Tabellen) then InhaltsArray = application.transpose(.range(.cells(1, "A"), .cells(.rows.count, "A").end(xlup)).value2 else tmp = .range(.cells(1, "A"), .cells(.rows.count, "A").end(xlup)).value2 i = ubound(InhaltsArray) redim preserve InhaltsArray(lbound(InhaltsArray) to (i + ubound(tmp, 1))) for n = lbound(tmp, 1) to ubound(tmp, 1) InhaltsArray(i + n) = tmp(n, 1) next n end if end with next z ```
33,323,412
I am am trying to configure a magento store . I have a couple of ghost products that appear on the Front end. These Ghost products have no name, no image , and aren't found under my back-end product list. However their add to button is active and works and also has a wishlist URL in the form of. ``` example.com/wishlist/index/add/product/4/form_key/p3jZL1nym3j4XeNl/ ``` I think I got myself into this mess after trying to duplicate a few products. How do I trace and get rid of these ghost products. Im using absolute template.
2015/10/24
[ "https://Stackoverflow.com/questions/33323412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5361888/" ]
Indeed, consider the Muenchian Grouping especially as keys are needed to align figures for group summing. ``` <xsl:key name="taxgrp" match="bus:VoPaidTax" use="concat(bus:TaxCode, bus:TaxRate)" /> <xsl:template match="bus:TaxList"> <bus:TaxList> <xsl:for-each select="bus:VoPaidTax[generate-id() = generate-id(key('taxgrp', concat(bus:TaxCode, bus:TaxRate))[1])]"> <bus:VoPaidTax> <bus:TaxAmount> <xsl:value-of select="sum(key('taxgrp', concat(bus:TaxCode, bus:TaxRate))/bus:TaxAmount)"/> </bus:TaxAmount> <xsl:copy-of select="*[not(local-name()='bus:TaxAmount')]"/> </bus:VoPaidTax> </xsl:for-each> </bus:TaxList> </xsl:template> ``` Output ``` <bus:TaxList> <bus:VoPaidTax> <bus:TaxAmount>10.9</bus:TaxAmount> <bus:TaxCode>10</bus:TaxCode> <bus:TaxRate>0.05</bus:TaxRate> <bus:TaxType>VAT</bus:TaxType> </bus:VoPaidTax> <bus:VoPaidTax> <bus:TaxAmount>15.26</bus:TaxAmount> <bus:TaxCode>12</bus:TaxCode> <bus:TaxRate>0.07</bus:TaxRate> <bus:TaxType>VAT</bus:TaxType> </bus:VoPaidTax> </bus:TaxList> ```
``` <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()" /> </xsl:copy> </xsl:template> <xsl:key name="taxgrp" match="bus:VoPaidTax" use="concat(generate-id(..),bus:TaxCode, bus:TaxRate)" /> <xsl:template match="bus:BsAddOrderPaymentRequestPayload/bus:Request/bus:TotalPaidAmount/bus:TaxList"> <bus:TaxList> <xsl:for-each select="bus:VoPaidTax[generate-id() = generate-id(key('taxgrp', concat(generate-id(..),bus:TaxCode, bus:TaxRate))[1])]"> <bus:VoPaidTax> <bus:TaxAmount> <xsl:value-of select="sum(key('taxgrp', concat(generate-id(..),bus:TaxCode, bus:TaxRate))/bus:TaxAmount)"/> </bus:TaxAmount> <xsl:copy-of select="*[not(self::bus:TaxAmount)]"/> </bus:VoPaidTax> </xsl:for-each> </bus:TaxList> </xsl:template> </xsl:stylesheet> ``` Added generate-id(..) to each key to keep the grouping in a particular node and not the whole document.
2,084,979
By using the formula : $$ \cos(A)+\cos(B)+\cos(C) = 1 + 4 \sin\left(\frac{A}{2}\right)\sin\left(\frac{B}{2}\right) \sin\left(\frac{C}{2}\right) $$ I've managed to simplify it to : $$ 2\sin\left(\frac{A}{2}\right)\sin\left(\frac{B}{2}\right)=\sin\left(\frac{C}{2}\right)$$ But I have no idea how to proceed.
2017/01/05
[ "https://math.stackexchange.com/questions/2084979", "https://math.stackexchange.com", "https://math.stackexchange.com/users/397349/" ]
using $$\cos(\alpha)=\frac{b^2+c^2-a^2}{2bc}$$ and so on and plugging these equations in your equation and factorizing we get $$-1/2\,{\frac { \left( c+a-b \right) \left( -c+a-b \right) \left( -2 \,c+a+b \right) }{bca}} =0$$ can you proceed?
From : $$ \cos(A)+\cos(B)+2\cos(C)=2 \\ \implies \cos(A)+\cos(B)=2-2\cos(C) \\ \implies \cos(A)+\cos(B)=2[1-\cos(C)] \\ \\\implies \cos(A)+\cos(B)=4\sin^2\left(\frac{C}{2}\right) $$ Using Prosthaphaeresis Formulas : $$ \cos A+\cos B=2\cos\dfrac{A+B}2\cos\dfrac{A-B}2 $$ And substituting this formula in the first equation, we have : $$ 2\cos\dfrac{A+B}2\cos\dfrac{A-B}2=4\sin^2\left(\frac{C}{2}\right) $$ Since $A+B+C=\pi$ $$ \frac{A+B}{2}=\frac{\pi}{2}-\frac{C}{2} $$ Taking cosines on both sides : $$ \cos\left(\frac{A+B}{2}\right)=\cos\left(\frac{\pi}{2}-\frac{C}{2}\right)=\sin\left(\frac{C}{2}\right) $$ Using this : $$ 2\cos\dfrac{A+B}2\cos\dfrac{A-B}2=4\cos^2\left(\frac{A+B}{2}\right) \\ \implies \cos\dfrac{A-B}2=2 \cos\dfrac{A+B}2 $$ Multiplying both sides by $2\sin\dfrac{A+B}2$ : $$ 2\sin\dfrac{A+B}2\cos\dfrac{A-B}2=4\sin\dfrac{A+B}2\cos\dfrac{A+B}2 $$ Using Another Prosthaphaeresis Formula : $$ \sin A+\sin B=2\sin\dfrac{A+B}2\cos\dfrac{A-B}2 $$ Applying the reverse in the obtained equation, we get : $$ \sin A+\sin B=2\sin\dfrac{A+B}2\cos\dfrac{A-B}2=4\sin\dfrac{A+B}2\cos\dfrac{A+B}2 $$ Using the sine double angle formula $2\sin(\alpha)\cos(\alpha)=\sin(2\alpha)$ : $$ \sin A+\sin B=2\sin(A+B)=2\sin C \\ \implies \sin A + \sin B = 2\sin C $$ Using the sine rule : $$ a + b = 2c $$ Hence, the sides of the triangle are in A.P.
278,758
a person is always lying about where he is going to be or what he is going to be doing. So, when he tells me something, I don't believe him anymore. What is a word that describes me?
2015/10/08
[ "https://english.stackexchange.com/questions/278758", "https://english.stackexchange.com", "https://english.stackexchange.com/users/141855/" ]
**skeptical.** From the freedictionary.com skep·ti·cal also scep·ti·cal (skĕp′tĭ-kəl) adj. 1. Marked by or given to doubt; questioning: skeptical of political promises. 2. Relating to or characteristic of skeptics or skepticism. skep′ti·cal·ly adv.
There are a number of possibilities. **Dismissive** describes your reaction to his statements. **Incredulous** "unwilling or unable to believe something" is a good start, but the lack of belief could be caused by any number of reasons. **Profoundly mistrusting** would describe your mental state, although it is two words rather than one. **Disillusioned** does not precisely state that you do not believe the person, but it is pretty well implied.
267,045
I started out with a generic interface called ILogin. The interfaces requires that you implement two properties: UserID and Password. I have many login-type classes that implement this interface. As my project grew and grew, I found that many classes repeated the UserID and Password code. Now I decide that I need a base Login class. Is it proper to create an abstract base Login class that implements the ILogin interface and have all of my concrete classes just inherit from the abstract class and override when necessary? Originally I was thinking there would be no problem with this. Then I started think that ILogin was probably unneeded because it'll likely only ever be implemented by my abstract class. Is there a benefit to keeping both the abstract class and the interface around? Thanks!
2008/11/05
[ "https://Stackoverflow.com/questions/267045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132931/" ]
If your abstract class is the *only* class that will ever implement the interface, then you can always just check for instances of the abstract class, you don't need the interface. But if you want to be future-compatible with new classes not yet written which will not extend the abstract class but could use the interface, then keep using the interface now.
Assuming you are asking specifically when the interface and the abstract class have identical signatures ... ... (If the members of the Interface are different in any way from the members of the abstract class then of course the answer is yes, there may be a need for both) ... but assuming the members are identical, then the only reason I can think of to need both is if you're coding in a system that does not allow multiple implementation inheritance there are two classes in your system that need to be polymorphically similar, but must inherit from different base classes...
28,391,733
This concerns "a software algorithm" from <https://stackoverflow.com/help/on-topic>, in this case the quicksort sorting algorithm This is a practice coding question(non competition) from <https://www.hackerrank.com/challenges/quicksort1> Basically you're supposed to take in a list, say ``` 4 5 3 7 2 ``` and partition around the first element, in this case 4. The expected output is ``` 3 2 4 5 7 ``` However the output I am getting is ``` 2 3 4 7 5 ``` Here is my code for doing the partitioning(based off the learning friendly version from <https://courses.cs.washington.edu/courses/cse373/13wi/lectures/02-27/20-sorting3-merge-quick.pdf> slide 16) ``` static void partition(int[] ar) { int toPartitionAround = ar[0]; swap(ar, 0, ar.length - 1); int index = partition(ar, 0, ar.length - 2, toPartitionAround); swap(ar, index, ar.length - 1); printArray(ar); } static int partition(int[] ar, int left, int right, int toAround) { while(left <= right) { while(ar[left] < toAround) { left ++; } while(ar[right] > toAround) { right --; } if(left <= right) { swap(ar, left, right); left ++; right --; } } return left; } static void swap(int[] arrayNums, int index1, int index2) { int temp = arrayNums[index1]; arrayNums[index1] = arrayNums[index2]; arrayNums[index2] = temp; } ``` Is there a modification I can make to this to match the expected output? Am I technically still getting a possible correct output because my output does follow the property elements to the left of the pivot are less than the pivot and elements to the right of the pivot are greater than the pivot? What I do is assign the pivot, move it to the back of the array and then partition the rest of the array around the pivot (from index of 0 to length - 2). With this input, one swap happened when going through the array(3 and the 5). Then when I get index from the result of the partition, I swap the pivot with that result, meaning I swap 4 and 5. Do I follow a similar process to get the expected output? I can't see what to replace.
2015/02/08
[ "https://Stackoverflow.com/questions/28391733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3761297/" ]
WIthin a batch file, the metavariable (loop-control variable) requires the `%` to be doubled, so replace each `%f` with `%%f` when you mean `the loop-control variable`"f"`
Your code seems fine. The issue is, that when you run it inside a batch file, you need to put an extra % mark. In the batch try: ``` for /f "tokens=*" %%f in ('dir /b *.DAT') do "c:\Program Files\7-Zip\7z.exe" a "%%f.7z" "%%f" ```
20,951
Every automatic transmission car I've driven (not sure if all do this) allow you to shift from Reverse to Neutral and from Neutral to Drive (and therefore Reverse all the way to Drive) without pressing the brake or hitting the little shift lock on the gear selector. However, it doesn't let you go the opposite direction from Drive to Reverse, or Reverse to Park, etc. According to [this question](https://mechanics.stackexchange.com/questions/4048/switching-from-reverse-to-drive-always-stop-completely) if you don't stop completely before shifting its possible to damage your transmission. Some cars apparently mitigate this damage but it still seems strange to even allow the opportunity. So why would car designers give you the feature to shift from reverse to drive without hitting the brake of it can cause damage? Even if it didn't cause damage why would they not allow you to shift in the reverse order without braking? Please note I'm not asking **how** this is done, I'm asking **why** it is like this.
2015/09/08
[ "https://mechanics.stackexchange.com/questions/20951", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/12124/" ]
I don't have reference for this, but believe the reason for the positive lockout going from drive to reverse is so you don't *accidentally* shift from drive to reverse while at speed. Can you imagine going 60 mph down the road and dropping it from drive into reverse? You can expect catastrophic consequences for your transmission if you were to do this. If there weren't a positive lock to bring it out of drive going to reverse, how easy would it be for you to accidentally move the shift lever (considering a floor shift lever) from drive if it wasn't in place. Also consider driving down the road at that speed and punching it up into reverse. You would not only be putting your own life in danger, you'd be putting everyone around in you danger with the very real possibility of a wreck in the process. My *belief* is that **you can go from reverse to drive without stopping is for convenience sake**. It *is* very likely you can damage the transmission by not stopping the vehicle between reverse to drive shifting (we used to call this a neutral drop in days of yore). The difference here is the speed at which you are moving when going in reverse is not that great. You most likely are not going to *accidentally* move the shift lever down from reverse into drive. I'm not saying it won't happen, but even if you did, the damage would not be as instantaneous as it would be going in the opposite direction. There is also a lot less possibility of a wreck at those speeds, so that is a consideration as well.
The answer is simpler then you might think. You are allowed to pull the gear shifter into neutral regardless of where it is pulled from to disengage the transmission. This is for safety, to be able to stop a runaway car regardless of if it's in drive or reverse. The ability to pull the car into drive from neutral comes form the occasional need to limp a car along when it's having engine troubles. The engine can only be started in in park or neutral. When your in neutral you can still be rolling along and trying to start and engine. When the engine starts then the shifter can be smoothly pulled into gear.
96,479
I would like to be able to add the symbol "lambda-bar" (see below) into an equation. How can I do this? ![enter image description here](https://i.stack.imgur.com/OPmAc.png)
2013/02/02
[ "https://tex.stackexchange.com/questions/96479", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/17670/" ]
As far as I know (confirmed by the Comprehensive list of LaTeX symbols), the only package that provides `\lambdabar` is `txfonts` (and the derived `newtxmath`). Of course changing all document fonts to get that symbol is out of the question (and the lambda is quite different from other fonts, so it's also impossible to import only it). One can build the symbol similarly to `\hbar`: ``` \documentclass{article} \newcommand{\lambdabar}{{\mkern0.75mu\mathchar '26\mkern -9.75mu\lambda}} \begin{document} $|\lambdabar|$ $|\lambda|$ \end{document} ``` This exploits the fact that the bar character used is exactly 9mu wide. In the standard definition of `\hbar` there is just `\mkern-9mu`, but we need to push the bar slightly to the right. (The second line is just to compare the results.) ![enter image description here](https://i.stack.imgur.com/vKCJT.png) --- A different implementation, where the bar is lower. ``` \documentclass{article} \makeatletter \newcommand{\lambdabar}{{\mathchoice {\smash@bar\textfont\displaystyle{0.25}{1.2}\lambda} {\smash@bar\textfont\textstyle{0.25}{1.2}\lambda} {\smash@bar\scriptfont\scriptstyle{0.25}{1.2}\lambda} {\smash@bar\scriptscriptfont\scriptscriptstyle{0.25}{1.2}\lambda} }} \newcommand{\smash@bar}[4]{% \smash{\rlap{\raisebox{-#3\fontdimen5#10}{$\m@th#2\mkern#4mu\mathchar'26$}}}% } \makeatother \begin{document} $|\lambdabar|_{\lambdabar_\lambdabar}$ $|\lambda|_{\lambda_\lambda}$ \end{document} ``` I've left the four parameters to `\smash@bar` so that one can fine tune them for different fonts. The variable parameters are the third (amount of shifting down as a fraction of 1ex in the correct font size) and the fourth (amount of shifting right of the bar, in mu units). ![enter image description here](https://i.stack.imgur.com/LWptE.png)
The answers posted earlier helped me conceptually to develop a solution for the Jupyter/Mathjax environment. I thought I should post that solution for the folks who would like a solution specific to that environment. Run this first in any cell before invoking lambdabar: ``` $$\newcommand\lambdabar{ \raise1.5pt{\moveright4.0pt\unicode{0x0335}}\moveleft1pt\lambda }$$ ``` Then you may use \lambdabar, sample use in markdown with mathjax: > > From Krane pg 422 we have also particles of momentum $p$ >interacting with > > > impact parameter $b$. The semiclassical relative angular >momentum is then > > > $$ \mathcal{l} \hbar = pb > $$ > or > $$ b = \mathcal{l} \frac{\hbar}{p} = \mathcal{l} \frac{\lambda}>{2\pi}= > \mathcal{l}\; \lambdabar > $$ > > > [![image of the above in browser](https://i.stack.imgur.com/7Vn1b.jpg)](https://i.stack.imgur.com/7Vn1b.jpg) Click on the image to see a larger version (didn't realize it would be so small here). That should be reduced Plank constant divided by momentum in the fraction above, but the subject here is really the bar lambda symbol so will leave image as is (but I did correct the LaTex code above). My system environment running the code is: ``` Software Version Python 3.6.3 64bit [MSC v.1900 64 bit (AMD64)] IPython 6.1.0 OS Windows 8.1 6.3.9600 SP0 numpy 1.13.3 scipy 0.19.1 ipython 6.1.0 JupyterLab v0.27.0 Wed Dec 12 15:41:29 2018 Mountain Standard Time ```
252,692
In Unix, using a simple command like sed, is there a way to print the last character of a file?
2011/03/03
[ "https://superuser.com/questions/252692", "https://superuser.com", "https://superuser.com/users/-1/" ]
tail is the right tool, not sed. ``` tail -c 1 filename ```
Use: `cat test | sed -e "s/^.*\(.\)$/\1/"` where test is the name of your file.
4,668,760
What is the shortest way, preferably inline-able, to convert an int to a string? Answers using stl and boost will be welcomed.
2011/01/12
[ "https://Stackoverflow.com/questions/4668760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/166067/" ]
`boost::lexical_cast<std::string>(yourint)` from `boost/lexical_cast.hpp` Work's for everything with std::ostream support, but is not as fast as, for example, `itoa` It even appears to be faster than stringstream or scanf: * <http://www.boost.org/doc/libs/1_53_0/doc/html/boost_lexical_cast/performance.html>
You might include the implementation of itoa in your project. Here's itoa modified to work with std::string: <http://www.strudel.org.uk/itoa/>
68,679,375
I am using Couchbase 3.2 SDK, to query couchbase server. Like below ``` QueryResult result = cluster.query( "SELECT *, Meta().id FROM bucketName USE KEYS ?", queryOptions().parameters(JsonArray.from("pk")).readonly(true)); ``` The response is like ``` [{"id":"pk","bucketName":"<binary (21 b)>"}] ``` My Document is a byte[], How can I get byte[] from the query response. **I have tried** 1. parsing to custom object by doing ``` result.rowsAs(CustomClass.class) ``` 2. Also tried ``` for (JsonObject row : result.rowsAsObject()) { resposne.put((String) row.get("id"), ((String)row.get("ratingsAndReviewCollection")).getBytes("UTF-8")); } ``` but both of them does not return the same doc that i had put. [This](https://forums.couchbase.com/t/how-to-convert-n1ql-query-results-to-binarydocuments/12088) thread talks about this but does not give clear solution to this.
2021/08/06
[ "https://Stackoverflow.com/questions/68679375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3892213/" ]
``` GetResult s = cluster.bucket("bucketName").defaultCollection().get("pk"); byte[] doc = s.contentAs(byte[].class); ```
It is not possible with N1QL, hence the solution in the referenced thread and the solution I provided to the specific question asked. To pair arguments with results, get creative with reactor. The following is with spring-data-couchbase, where findById() returns Airport. Using the SDK replace findById() with get() which returns a GetResult. ``` Flux<Pair<String, Mono<Airport>>> pairFlux = Flux.fromIterable(list).map((airport) -> Pair.of(airport.getId(), airportRepository.findById(airport.getId()))); List<Pair<String, Mono<Airport>>> airportPairs = pairFlux.collectList().block(); for (Pair<String, Mono<Airport>> airportPair : airportPairs) { System.out.println("id: " + airportPair.getFirst() + " airport: " + airportPair.getSecond().block()); } ```
2,949,956
Where did I go wrong? (preferably a logical explanation instead of "this isn't how you use (insert name) rule) \begin{align\*} &\lim\_{x\to 0}\frac{ 1 -\cos x }{x²}\\ =&\lim\_{x\to 0}\frac{ 1 -\cos x }{(x-0)\cdot(x-0)}\\ =&\lim\_{x\to 0}\frac{\sin x }{x-0}\\ =&\lim\_{x\to 0}\cos x\\ =&1. \end{align\*}
2018/10/10
[ "https://math.stackexchange.com/questions/2949956", "https://math.stackexchange.com", "https://math.stackexchange.com/users/602618/" ]
The second equality doesn't hold. If you are using L'Hopital's rule, you should do\begin{align}\lim\_{x\to0}\frac{1-\cos x}{x^2}&=\lim\_{x\to0}\frac{\sin x}{2x}\\&=\frac12\lim\_{x\to0}\frac{\sin x}x\\&=\frac12.\end{align} --- Another possibility is:\begin{align}\lim\_{x\to0}\frac{1-\cos x}{x^2}&=\lim\_{x\to0}\frac{2\sin^2\left(\frac x2\right)}{x^2}\\&=\frac12\lim\_{x\to0}\frac{\sin^2\left(\frac x2\right)}{\left(\frac x2\right)^2}\\&=\frac12\left(\lim\_{x\to0}\frac{\sin\left(\frac x2\right)}{\frac x2}\right)^2\\&=\frac12.\end{align}
You have an indeterminate form. Using L'Hopital's Rule, take the derivative of numerator and denominator, transforming your limit to: \begin{align}\lim\_{x\to0}\dfrac{1-\cos{x}}{x^2}=\lim\_{x\to0}\dfrac{\sin{x}}{2x}\end{align} This is another indeterminate form. Another iteration of L'Hopital's Rule implies: \begin{align}\lim\_{x\to0}\dfrac{\sin{x}}{2x} = \lim\_{x\to0}\dfrac{\cos{x}}{2}\end{align} Upon substitution of $x=0$, \begin{align}\lim\_{x\rightarrow0}\dfrac{\cos{x}}{2}=\dfrac{1}{2}\end{align}
2,001,842
I cant seem to find a direct method for implementing filtering of text input into a list of items in a WPF combobox. By setting IsTextSearchEnabled to true, the comboBox dropdown will jump to whatever the first matching item is. What I need is for the list to be filtered to whatever matches the text string (e.g. If I focus on my combobox and type 'abc', I'd like to see all the items in the ItemsSource collection that start with (or contain preferably) 'abc' as the members of the dropdown list). I doubt that it makes a difference but my display item is templated to a property of a complex type : ``` <ComboBox x:Name="DiagnosisComboBox" Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="3" ItemsSource="{Binding Path = ApacheDxList, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" IsTextSearchEnabled="True" ItemTemplate="{StaticResource DxDescriptionTemplate}" SelectedValue="{Binding Path = SelectedEncounterDetails.Diagnosis, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> ``` Thanks.
2010/01/04
[ "https://Stackoverflow.com/questions/2001842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107933/" ]
I just did this a few days ago using a modified version of the code from this site: [Credit where credit is due](http://dotbay.blogspot.ca/2009/04/building-filtered-combobox-for-wpf.html) My full code listed below: ``` using System.Collections; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; namespace MyControls { public class FilteredComboBox : ComboBox { private string oldFilter = string.Empty; private string currentFilter = string.Empty; protected TextBox EditableTextBox => GetTemplateChild("PART_EditableTextBox") as TextBox; protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue) { if (newValue != null) { var view = CollectionViewSource.GetDefaultView(newValue); view.Filter += FilterItem; } if (oldValue != null) { var view = CollectionViewSource.GetDefaultView(oldValue); if (view != null) view.Filter -= FilterItem; } base.OnItemsSourceChanged(oldValue, newValue); } protected override void OnPreviewKeyDown(KeyEventArgs e) { switch (e.Key) { case Key.Tab: case Key.Enter: IsDropDownOpen = false; break; case Key.Escape: IsDropDownOpen = false; SelectedIndex = -1; Text = currentFilter; break; default: if (e.Key == Key.Down) IsDropDownOpen = true; base.OnPreviewKeyDown(e); break; } // Cache text oldFilter = Text; } protected override void OnKeyUp(KeyEventArgs e) { switch (e.Key) { case Key.Up: case Key.Down: break; case Key.Tab: case Key.Enter: ClearFilter(); break; default: if (Text != oldFilter) { RefreshFilter(); IsDropDownOpen = true; EditableTextBox.SelectionStart = int.MaxValue; } base.OnKeyUp(e); currentFilter = Text; break; } } protected override void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEventArgs e) { ClearFilter(); var temp = SelectedIndex; SelectedIndex = -1; Text = string.Empty; SelectedIndex = temp; base.OnPreviewLostKeyboardFocus(e); } private void RefreshFilter() { if (ItemsSource == null) return; var view = CollectionViewSource.GetDefaultView(ItemsSource); view.Refresh(); } private void ClearFilter() { currentFilter = string.Empty; RefreshFilter(); } private bool FilterItem(object value) { if (value == null) return false; if (Text.Length == 0) return true; return value.ToString().ToLower().Contains(Text.ToLower()); } } } ``` And the WPF should be something like so: ``` <MyControls:FilteredComboBox ItemsSource="{Binding MyItemsSource}" SelectedItem="{Binding MySelectedItem}" DisplayMemberPath="Name" IsEditable="True" IsTextSearchEnabled="False" StaysOpenOnEdit="True"> <MyControls:FilteredComboBox.ItemsPanel> <ItemsPanelTemplate> <VirtualizingStackPanel VirtualizationMode="Recycling" /> </ItemsPanelTemplate> </MyControls:FilteredComboBox.ItemsPanel> </MyControls:FilteredComboBox> ``` A few things to note here. You will notice the FilterItem implementation does a ToString() on the object. This means the property of your object you want to display should be returned in your object.ToString() implementation. (or be a string already) In other words something like so: ``` public class Customer { public string Name { get; set; } public string Address { get; set; } public string PhoneNumber { get; set; } public override string ToString() { return Name; } } ``` If this does not work for your needs I suppose you could get the value of DisplayMemberPath and use reflection to get the property to use it, but that would be slower so I wouldn't recommend doing that unless necessary. Also this implementation does NOT stop the user from typing whatever they like in the TextBox portion of the ComboBox. If they type something stupid there the SelectedItem will revert to NULL, so be prepared to handle that in your code. Also if you have many items I would highly recommend using the VirtualizingStackPanel like my example above as it makes quite a difference in loading time
Kelly's answer is great. However, there is a small bug that if you select an item in the list (highlighting the input text) then press BackSpace, the input text will revert to the selected item and the SelectedItem property of the ComboBox is still the item you selected previously. Below is the code to fix the bug and add the ability to automatically select the item when the input text matches it. ``` using System.Collections; using System.Diagnostics; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; namespace MyControls { public class FilteredComboBox : ComboBox { private string oldFilter = string.Empty; private string currentFilter = string.Empty; protected TextBox EditableTextBox => GetTemplateChild("PART_EditableTextBox") as TextBox; protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue) { if (newValue != null) { var view = CollectionViewSource.GetDefaultView(newValue); view.Filter += FilterItem; } if (oldValue != null) { var view = CollectionViewSource.GetDefaultView(oldValue); if (view != null) view.Filter -= FilterItem; } base.OnItemsSourceChanged(oldValue, newValue); } protected override void OnPreviewKeyDown(KeyEventArgs e) { switch (e.Key) { case Key.Tab: case Key.Enter: IsDropDownOpen = false; break; case Key.Escape: IsDropDownOpen = false; SelectedIndex = -1; Text = currentFilter; break; default: if (e.Key == Key.Down) IsDropDownOpen = true; base.OnPreviewKeyDown(e); break; } // Cache text oldFilter = Text; } protected override void OnKeyUp(KeyEventArgs e) { switch (e.Key) { case Key.Up: case Key.Down: break; case Key.Tab: case Key.Enter: ClearFilter(); break; default: if (Text != oldFilter) { var temp = Text; RefreshFilter(); //RefreshFilter will change Text property Text = temp; if (SelectedIndex != -1 && Text != Items[SelectedIndex].ToString()) { SelectedIndex = -1; //Clear selection. This line will also clear Text property Text = temp; } IsDropDownOpen = true; EditableTextBox.SelectionStart = int.MaxValue; } //automatically select the item when the input text matches it for (int i = 0; i < Items.Count; i++) { if (Text == Items[i].ToString()) SelectedIndex = i; } base.OnKeyUp(e); currentFilter = Text; break; } } protected override void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEventArgs e) { ClearFilter(); var temp = SelectedIndex; SelectedIndex = -1; Text = string.Empty; SelectedIndex = temp; base.OnPreviewLostKeyboardFocus(e); } private void RefreshFilter() { if (ItemsSource == null) return; var view = CollectionViewSource.GetDefaultView(ItemsSource); view.Refresh(); } private void ClearFilter() { currentFilter = string.Empty; RefreshFilter(); } private bool FilterItem(object value) { if (value == null) return false; if (Text.Length == 0) return true; return value.ToString().ToLower().Contains(Text.ToLower()); } } } ```
16,811,173
I'm trying to write a bash script, which will do the following: 1. reads the content from the first file (as a first argument) 2. reads the content from the second file (as a second argument) 3. finds the line in the second file with the given pattern (as a third argument) 4. inserts text from the first file to the second file after the line of the pattern. 5. prints final file on the screen. For example: first\_file.txt: ``` 111111 1111 11 1 ``` second\_file.txt: ``` 122221 2222 22 2 ``` pattern: ``` 2222 ``` output: ``` 122221 111111 1111 11 1 2222 111111 1111 11 1 22 2 ``` What should I use to realize this functionality on BASH? I wrote the code, but it doesn't work properly (why?): ``` #!/bin/bash first_filename="$1" second_filename="$2" pattern="$3" while read -r line do if [[ $line=˜$pattern ]]; then while read -r line2 do echo $line2 done < $second_filename fi echo $line done < $first_filename ```
2013/05/29
[ "https://Stackoverflow.com/questions/16811173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2431907/" ]
You need spaces around the `=~` operator. Compare: ``` [[ foo=~bar ]] [[ foo =~ bar ]] ``` This is because the first expression essentially evaluates as "Is this string empty?" Also, the **OP code uses [small tilde](http://www.fileformat.info/info/unicode/char/02dc/index.htm) rather than [tilde](http://www.fileformat.info/info/unicode/char/007e/index.htm)**. Even so, you can easily get rid of the inner loop. Just replace the whole `while read -r line2` bit with `cat -- "$second_filename"`. Your last `echo $line` is only correct if the file does *not* end in a newline character (standard with \*nix tools). Instead, you should use `while read -r line || [[ $line ~= '' ]]`. This works with or without newline at the end. Also, [Use More Quotes™](http://mywiki.wooledge.org/BashGuide/Practices).
I use sed like this and it worked as a charm ***sed -i -e '/pattern/r filetoinsert' filetobeinserted*** What it does is insert the 'filetoinsert' into 'filetobeinserted' after the line with the specified pattern Take care to choose a unique pattern, not sure how it will work with a duplicate patterns, I assume it will do it just of the first one
266
While there are many open databases available, is there a database or the project that would contain the information of such databases? In other words, is there an open meta-database of open databases?
2013/05/12
[ "https://opendata.stackexchange.com/questions/266", "https://opendata.stackexchange.com", "https://opendata.stackexchange.com/users/139/" ]
### The short answer **[DataPortals.org](http://dataportals.org/)** (previously DataCatalogs.org) provides a comprehensive list of open data portals from around the world. Their (meta-)data is in the public domain and available for download as [CSV](https://raw.githubusercontent.com/okfn/dataportals.org/master/data/portals.csv) and [JSON](http://dataportals.org/api/data.json). ### The longer answer Data that is somehow related is usually grouped in ***datasets*** or ***databases***, contained in files (e.g. CSV or spreadsheets) or some kind of database management system, which might be accessible via an API. In the context of Open Data, ***data portals***, ***data catalogs***, or ***data hubs*** make it easier to find these datasets or databases. A great example of such a data portal is **[the Datahub](https://datahub.io/)**, which currently lists [more than 4,500 open datasets](https://datahub.io/dataset?isopen=true). However, there are already hundreds of data portals. A few prominent examples are the official data portals of the US ([data.gov](https://www.data.gov/)), the UK ([data.gov.uk](https://data.gov.uk/)), or the European Union ([open-data.europa.eu](https://open-data.europa.eu/)). This is where DataPortal.org comes in: It is a data portal of data portals. To sum it up: ``` DataPortals.org --> Specific Data Portal --> Specific Data Set --> Open Data ```
Google offers a couple more structured ways to search just on data sets beyond the main Google search function mentioned above: 1) A Googler on Twitter [has suggested](https://twitter.com/danbri/status/391192805873172480) "try[ing] Google custom search (@googlecse) on pages that mention a <http://schema.org/Dataset> - <http://datasets.schema-labs.appspot.com/>" This search tool allows you to search for data sets that have been tagged using the [Schema.org tag for data sets](http://schema.org/Dataset). 2) Google Fusion tables [allows the public to search for tables](https://support.google.com/fusiontables/answer/2573812?hl=en) that are either uploaded into Fusion tables or tables that Google has found on the web that could be uploaded into Fusion tables. In their words, "Web pages sometimes display high-quality structured data in a table. Many of these tables appear in Google Tables search results, dramatically expanding your ability to locate structured data. Once you find a good table, you may decide to import it to Fusion Tables."
5,506,061
I have a custom control that has a property that is an ObservableCollection of another custom control. I can't seem to get the DependencyProperty change event to fire in design time. I have tried to use CoerceValueCallback this doesn't fire either. can anyone give me some direction. Every thing else is working just fine in runtime i just can't get this to fire so i can update the control in designtime. Many thanks in advance. ``` Public Shared ReadOnly ArcsProperty As DependencyProperty = DependencyProperty.Register("Arcs", GetType(ObservableCollection(Of OPCWPF.OPCWPFArcControl)), GetType(OPCWPFPie), New PropertyMetadata(New ObservableCollection(Of OPCWPF.OPCWPFArcControl), New PropertyChangedCallback(AddressOf ArcsPropertyChanged), New CoerceValueCallback(AddressOf CoerceArcs))) ' Arc Quantity <Description("Collection of Arcs"), _ Category("Common Properties")> _ Public Property Arcs() As ObservableCollection(Of OPCWPF.OPCWPFArcControl) Get Return DirectCast(Me.GetValue(ArcsProperty), ObservableCollection(Of OPCWPF.OPCWPFArcControl)) End Get Set(ByVal value As ObservableCollection(Of OPCWPF.OPCWPFArcControl)) Me.SetValue(ArcsProperty, value) End Set End Property ```
2011/03/31
[ "https://Stackoverflow.com/questions/5506061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/686500/" ]
You may want to create a `VIEW` so you can use it for many other queries: ``` CREATE VIEW CallRecordsAgents AS ( SELECT HistoryID , CallID , Date , Data , LEFT( Agent+' ', CHARINDEX(' ', Agent+' ') - 1) AS Agent1 , RTRIM(LTRIM( SUBSTRING( Agent+' ', CHARINDEX(' ', Agent+' '), LEN(Agent+' ')))) AS Agent2 FROM CallRecords ) ``` After that, the question: "***How many transfers did Bob receive?***", would be solved by: ``` SELECT COUNT(*) AS Transfers FROM CallRecordsAgents WHERE Agent2 = "Bob" ``` And "***How many transfers did every agent receive?***", would be: ``` SELECT Agent2 , COUNT(*) AS TransfersReceived FROM CallRecordsAgents GROUP BY Agent2 ``` --- The Agent2 extraction can be simplified (i think) with: ``` , RTRIM( SUBSTRING( Agent, LEN(Agent1)+2, LEN(Agent) ) ) AS Agent2 ```
I would get a count of records grouped by agent2. something like: ``` SELECT agent2, COUNT(*) FROM yourTable GROUP BY agent2 ```
125,842
We have installed *Cygwin* on a *Windows Server 2008 Standard* server and it working pretty well. Unfortunately we still have a *big problem*. We want to connect using a public key through SSH which doesn't work. It always falls back to using password login. We have appended our public key to `~/.ssh/authorized_keys` on the server and we have our private and public key in `~/.ssh/id_dsa` respective `~/.ssh/id_dsa.pub` on the client. When debugging the SSH login session we see that the key is offered by the server apparently rejects it by some **unknown** reason. --- The SSH output when connecting from an Ubuntu 9.10 desktop with debug information enabled: ``` $ ssh -v 192.168.10.11 OpenSSH_5.1p1 Debian-6ubuntu2, OpenSSL 0.9.8g 19 Oct 2007 debug1: Reading configuration data /home/myuseraccount/.ssh/config debug1: Reading configuration data /etc/ssh/ssh_config debug1: Applying options for debug1: Connecting to 192.168.10.11 [192.168.10.11] port 22. debug1: Connection established. debug1: identity file /home/myuseraccount/.ssh/identity type -1 debug1: identity file /home/myuseraccount/.ssh/id_rsa type -1 debug1: identity file /home/myuseraccount/.ssh/id_dsa type 2 debug1: Checking blacklist file /usr/share/ssh/blacklist.DSA-1024 debug1: Checking blacklist file /etc/ssh/blacklist.DSA-1024 debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3 debug1: match: OpenSSH_5.3 pat OpenSSH debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_5.1p1 Debian-6ubuntu2 debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: server->client aes128-cbc hmac-md5 none debug1: kex: client->server aes128-cbc hmac-md5 none debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP debug1: SSH2_MSG_KEX_DH_GEX_INIT sent debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY debug1: Host '192.168.10.11' is known and matches the RSA host key. debug1: Found key in /home/myuseraccount/.ssh/known_hosts:12 debug1: ssh_rsa_verify: signature correct debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: SSH2_MSG_SERVICE_REQUEST sent debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey,password,keyboard-interactive debug1: Next authentication method: publickey debug1: Offering public key: /home/myuseraccount/.ssh/id_dsa debug1: Authentications that can continue: publickey,password,keyboard-interactive debug1: Trying private key: /home/myuseraccount/.ssh/identity debug1: Trying private key: /home/myuseraccount/.ssh/id_rsa debug1: Next authentication method: keyboard-interactive debug1: Authentications that can continue: publickey,password,keyboard-interactive debug1: Next authentication method: password myuseraccount@192.168.10.11's password: ``` The version of Cygwin: ``` $ uname -a CYGWIN_NT-6.0 servername 1.7.1(0.218/5/3) 2009-12-07 11:48 i686 Cygwin ``` The installed packages: ``` $ cygcheck -c Cygwin Package Information Package Version Status _update-info-dir 00871-1 OK alternatives 1.3.30c-10 OK arj 3.10.22-1 OK aspell 0.60.5-1 OK aspell-en 6.0.0-1 OK aspell-sv 0.50.2-2 OK autossh 1.4b-1 OK base-cygwin 2.1-1 OK base-files 3.9-3 OK base-passwd 3.1-1 OK bash 3.2.49-23 OK bash-completion 1.1-2 OK bc 1.06-2 OK bzip2 1.0.5-10 OK cabextract 1.1-1 OK compface 1.5.2-1 OK coreutils 7.0-2 OK cron 4.1-59 OK crypt 1.1-1 OK csih 0.9.1-1 OK curl 7.19.6-1 OK cvs 1.12.13-10 OK cvsutils 0.2.5-1 OK cygrunsrv 1.34-1 OK cygutils 1.4.2-1 OK cygwin 1.7.1-1 OK cygwin-doc 1.5-1 OK cygwin-x-doc 1.1.0-1 OK dash 0.5.5.1-2 OK diffutils 2.8.7-2 OK doxygen 1.6.1-2 OK e2fsprogs 1.35-3 OK editrights 1.01-2 OK emacs 23.1-10 OK emacs-X11 23.1-10 OK file 5.04-1 OK findutils 4.5.5-1 OK flip 1.19-1 OK font-adobe-dpi75 1.0.1-1 OK font-alias 1.0.2-1 OK font-encodings 1.0.3-1 OK font-misc-misc 1.1.0-1 OK fontconfig 2.8.0-1 OK gamin 0.1.10-10 OK gawk 3.1.7-1 OK gettext 0.17-11 OK gnome-icon-theme 2.28.0-1 OK grep 2.5.4-2 OK groff 1.19.2-2 OK gvim 7.2.264-1 OK gzip 1.3.12-2 OK hicolor-icon-theme 0.11-1 OK inetutils 1.5-6 OK ipc-utils 1.0-1 OK keychain 2.6.8-1 OK less 429-1 OK libaspell15 0.60.5-1 OK libatk1.0_0 1.28.0-1 OK libaudio2 1.9.2-1 OK libbz2_1 1.0.5-10 OK libcairo2 1.8.8-1 OK libcurl4 7.19.6-1 OK libdb4.2 4.2.52.5-2 OK libdb4.5 4.5.20.2-2 OK libexpat1 2.0.1-1 OK libfam0 0.1.10-10 OK libfontconfig1 2.8.0-1 OK libfontenc1 1.0.5-1 OK libfreetype6 2.3.12-1 OK libgcc1 4.3.4-3 OK libgdbm4 1.8.3-20 OK libgdk_pixbuf2.0_0 2.18.6-1 OK libgif4 4.1.6-10 OK libGL1 7.6.1-1 OK libglib2.0_0 2.22.4-2 OK libglitz1 0.5.6-10 OK libgmp3 4.3.1-3 OK libgtk2.0_0 2.18.6-1 OK libICE6 1.0.6-1 OK libiconv2 1.13.1-1 OK libidn11 1.16-1 OK libintl3 0.14.5-1 OK libintl8 0.17-11 OK libjasper1 1.900.1-1 OK libjbig2 2.0-11 OK libjpeg62 6b-21 OK libjpeg7 7-10 OK liblzma1 4.999.9beta-10 OK libncurses10 5.7-18 OK libncurses8 5.5-10 OK libncurses9 5.7-16 OK libopenldap2_3_0 2.3.43-1 OK libpango1.0_0 1.26.2-1 OK libpcre0 8.00-1 OK libpixman1_0 0.16.6-1 OK libpng12 1.2.35-10 OK libpopt0 1.6.4-4 OK libpq5 8.2.11-1 OK libreadline6 5.2.14-12 OK libreadline7 6.0.3-2 OK libsasl2 2.1.19-3 OK libSM6 1.1.1-1 OK libssh2_1 1.2.2-1 OK libssp0 4.3.4-3 OK libstdc++6 4.3.4-3 OK libtiff5 3.9.2-1 OK libwrap0 7.6-20 OK libX11_6 1.3.3-1 OK libXau6 1.0.5-1 OK libXaw3d7 1.5D-8 OK libXaw7 1.0.7-1 OK libxcb-render-util0 0.3.6-1 OK libxcb-render0 1.5-1 OK libxcb1 1.5-1 OK libXcomposite1 0.4.1-1 OK libXcursor1 1.1.10-1 OK libXdamage1 1.1.2-1 OK libXdmcp6 1.0.3-1 OK libXext6 1.1.1-1 OK libXfixes3 4.0.4-1 OK libXft2 2.1.14-1 OK libXi6 1.3-1 OK libXinerama1 1.1-1 OK libxkbfile1 1.0.6-1 OK libxml2 2.7.6-1 OK libXmu6 1.0.5-1 OK libXmuu1 1.0.5-1 OK libXpm4 3.5.8-1 OK libXrandr2 1.3.0-10 OK libXrender1 0.9.5-1 OK libXt6 1.0.7-1 OK links 1.00pre20-1 OK login 1.10-10 OK luit 1.0.5-1 OK lynx 2.8.5-4 OK man 1.6e-1 OK minires 1.02-1 OK mkfontdir 1.0.5-1 OK mkfontscale 1.0.7-1 OK openssh 5.4p1-1 OK openssl 0.9.8m-1 OK patch 2.5.8-9 OK patchutils 0.3.1-1 OK perl 5.10.1-3 OK rebase 3.0.1-1 OK run 1.1.12-11 OK screen 4.0.3-5 OK sed 4.1.5-2 OK shared-mime-info 0.70-1 OK tar 1.22.90-1 OK terminfo 5.7_20091114-13 OK terminfo0 5.5_20061104-11 OK texinfo 4.13-3 OK tidy 041206-1 OK time 1.7-2 OK tzcode 2009k-1 OK unzip 6.0-10 OK util-linux 2.14.1-1 OK vim 7.2.264-2 OK wget 1.11.4-4 OK which 2.20-2 OK wput 0.6.1-2 OK xauth 1.0.4-1 OK xclipboard 1.1.0-1 OK xcursor-themes 1.0.2-1 OK xemacs 21.4.22-1 OK xemacs-emacs-common 21.4.22-1 OK xemacs-sumo 2007-04-27-1 OK xemacs-tags 21.4.22-1 OK xeyes 1.1.0-1 OK xinit 1.2.1-1 OK xinput 1.5.0-1 OK xkbcomp 1.1.1-1 OK xkeyboard-config 1.8-1 OK xkill 1.0.2-1 OK xmodmap 1.0.4-1 OK xorg-docs 1.5-1 OK xorg-server 1.7.6-2 OK xrdb 1.0.6-1 OK xset 1.1.0-1 OK xterm 255-1 OK xz 4.999.9beta-10 OK zip 3.0-11 OK zlib 1.2.3-10 OK zlib-devel 1.2.3-10 OK zlib0 1.2.3-10 OK ``` The ssh deamon configuration file: ``` $ cat /etc/sshd_config # $OpenBSD: sshd_config,v 1.80 2008/07/02 02:24:18 djm Exp $ # This is the sshd server system-wide configuration file. See # sshd_config(5) for more information. # This sshd was compiled with PATH=/bin:/usr/sbin:/sbin:/usr/bin # The strategy used for options in the default sshd_config shipped with # OpenSSH is to specify options with their default value where # possible, but leave them commented. Uncommented options change a # default value. Port 22 #AddressFamily any #ListenAddress 0.0.0.0 #ListenAddress :: # Disable legacy (protocol version 1) support in the server for new # installations. In future the default will change to require explicit # activation of protocol 1 Protocol 2 # HostKey for protocol version 1 #HostKey /etc/ssh_host_key # HostKeys for protocol version 2 #HostKey /etc/ssh_host_rsa_key #HostKey /etc/ssh_host_dsa_key # Lifetime and size of ephemeral version 1 server key #KeyRegenerationInterval 1h #ServerKeyBits 1024 # Logging # obsoletes QuietMode and FascistLogging #SyslogFacility AUTH #LogLevel INFO # Authentication: #LoginGraceTime 2m #PermitRootLogin yes StrictModes no #MaxAuthTries 6 #MaxSessions 10 RSAAuthentication yes PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys # For this to work you will also need host keys in /etc/ssh_known_hosts #RhostsRSAAuthentication no # similar for protocol version 2 #HostbasedAuthentication no # Change to yes if you don't trust ~/.ssh/known_hosts for # RhostsRSAAuthentication and HostbasedAuthentication #IgnoreUserKnownHosts no # Don't read the user's ~/.rhosts and ~/.shosts files #IgnoreRhosts yes # To disable tunneled clear text passwords, change to no here! #PasswordAuthentication yes #PermitEmptyPasswords no # Change to no to disable s/key passwords #ChallengeResponseAuthentication yes # Kerberos options #KerberosAuthentication no #KerberosOrLocalPasswd yes #KerberosTicketCleanup yes #KerberosGetAFSToken no # GSSAPI options #GSSAPIAuthentication no #GSSAPICleanupCredentials yes # Set this to 'yes' to enable PAM authentication, account processing, # and session processing. If this is enabled, PAM authentication will # be allowed through the ChallengeResponseAuthentication and # PasswordAuthentication. Depending on your PAM configuration, # PAM authentication via ChallengeResponseAuthentication may bypass # the setting of "PermitRootLogin without-password". # If you just want the PAM account and session checks to run without # PAM authentication, then enable this but set PasswordAuthentication # and ChallengeResponseAuthentication to 'no'. #UsePAM no AllowAgentForwarding yes AllowTcpForwarding yes GatewayPorts yes X11Forwarding yes X11DisplayOffset 10 X11UseLocalhost no #PrintMotd yes #PrintLastLog yes TCPKeepAlive yes #UseLogin no UsePrivilegeSeparation yes #PermitUserEnvironment no #Compression delayed #ClientAliveInterval 0 #ClientAliveCountMax 3 #UseDNS yes #PidFile /var/run/sshd.pid #MaxStartups 10 #PermitTunnel no #ChrootDirectory none # no default banner path #Banner none # override default of no subsystems Subsystem sftp /usr/sbin/sftp-server # Example of overriding settings on a per-user basis #Match User anoncvs #X11Forwarding yes #AllowTcpForwarding yes #ForceCommand cvs server ``` I hope this information is enough to solve the problem. In case any more is needed please comment and I'll add it. Thank you for reading!
2010/03/24
[ "https://serverfault.com/questions/125842", "https://serverfault.com", "https://serverfault.com/users/32224/" ]
I have three accounts on one machine (Mac OSX) and I setup all of their .ssh/authorized\_keys files to contain the id\_rsa.pub of the other two. But I could not "ssh" into one of these accounts from either of the other two, yet they could "ssh" to each other. The answer came from a blog entitled `Debugging SSH public key authentication problems`. My "bad" account had group and public "write" permissions on its home directory. All I had to do was ``` chmod 755 /Users/yourname ``` where yourname is the bad account, and you are logged into that account, or using "sudo" (root) privileges. Check it out. It worked for me.
For search purpose: For me it only works, when the private key is named id\_rsa. In your verbose message u see, that this is the pattern he looks per default. otherwise you have to name it "ssh -i .ssh/keyname user@server"
13,018,312
I have the following JSON object array in javascript : ``` [{ "AuthorName" : "Abc", "BookName" : "book-1" }] [{ "AuthorName" : "Abc", "BookName" : "book-2" }] [{ "AuthorName" : "Abc", "BookName" : "book-3" }] [{ "AuthorName" : "Abc", "BookName" : "book-4" }] ``` Now I want to create a single JSON object from the above JSON objects array. The newly created single JSON object contains 2 properties: `AuthorName` and `BooKName` array. I am trying to achieve something like this: ``` { "AuthorName" : "Abc", "Book" : ['book-1', 'book-2', 'book-3', 'book-4'] } ``` Now my question is, how can I achive this efficiently and with writing minimum code in javascript?
2012/10/22
[ "https://Stackoverflow.com/questions/13018312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1459031/" ]
``` var obj = {}; for(var i=0; i<myArray.length; i++) { if(obj[myArray[i].AuthorName] == null) obj[myArray[i].AuthorName] = []; obj[myArray[i].AuthorName].push(myArray[i].BookName) } ```
Hopefully, this will help: ``` var bookSort = function (bookarray) { var i, book, authorArray = [], il = bookarray.length, j, jl, authorInArray; for (i = 0; i < il; i++) { authorInArray= false; jl = authorArray.length; book = bookArray[i]; for (j = 0; j < jl; j++) { if (book.AuthorName = authorArray[j].AuthorName) { authorInArray= true; authorArray[j].BookName.push(book.BookName); break; } } if (!authorInArray) { authorArray.push({AuthorName: book.AuthorName, BookName: [book.BookName]}); } } return authorArray; }; ```
13,231,730
Hi I'm a `c++` beginner and this is one of my assignments and I'm a bit stuck. This isn't my entire code it's just a snippet of what I need help with. What I'm trying to do is have one function dedicated to exporting everything with that function into a `text` file which is called results.txt. So the line "does this work" should show up when I open the file, but when I run the file I get errors like > > "Error C2065: 'out' : undeclared identifier" > > > "Error C2275: 'std::ofstream' : illegal use of this type as an expression" > > > "IntelliSense: type name is not allowed" > > > "IntelliSense: identifier "out" is undefined" > > > ``` #include <iostream> #include <string> #include <fstream> using namespace std; //prototypes void output(ofstream& out); int main() { output(ofstream& out); ifstream in; in.open("inven.txt"); ofstream out; out.open("results.txt"); return 0; } void output(ofstream& out) { out << "does this work?" << endl; } ``` Right now it's really late and I'm just blanking out on what I'm doing wrong.
2012/11/05
[ "https://Stackoverflow.com/questions/13231730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1800033/" ]
First of all, this is fine: ``` void output(ofstream& out) { out << "does this work?" << endl; } ``` However, this is not: ``` int main() { output(ofstream& out); // what is out? ifstream in; in.open("inven.txt"); ofstream out; out.open("results.txt"); return 0; } ``` This is the first error you get: "Error C2065: 'out' : undeclared identifier", because the compiler doesn't know about out yet. In the second fragment you want to *call* output with a specific `ostream&`. Instead of calling a function, you're giving a function declaration, which isn't allowed in this context. You have to call it with the given `ostream&`: ``` int main() { ifstream in; in.open("inven.txt"); ofstream out; out.open("results.txt"); output(out); // note the missing ostream& return 0; } ``` In this case you *call* `output` with `out` as parameter.
Since you described yourself as a begginer, I'll answer accordingly and hopefully in a educational manner. Here is what is happening: Think of `fstream`, `ofstream` and `ifstream` as smart variable types (even if you know what classes are, think like that for the sake of **logical clarity**). Like any other variable, you have to **declare it** before you use. After it is declared, that variable can **hold a compatible value**. The `fstream` variable types is for **holding files**. All variations of it hold the same thing, just what they do that is different. You use the variable to **open a file**, **use it** in your program, then **close**. Hope this helps
29,208,566
I have following project strucure: `projectA build/ projectB build/ build` I would like to ignore everything which is under build folder. I used following in the .hgignore file: ``` syntax: glob build/** ``` It ignores build folder under projectA and projectB, but it doesn't ignore build folder in the root. How can I accomplish the build folder in the root to also be ignored? Best regards, mismas
2015/03/23
[ "https://Stackoverflow.com/questions/29208566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/640022/" ]
The glob syntax in Mercurial does not operate from the root folder, as you've found it'll match the path wherever in the tree it occurs. To match relative to the root you'll need to use the regexp syntax, so try: ``` syntax: regexp ^build/ ``` or ``` syntax: regexp ^build$ ``` And you can have both regexp and glob syntax in your hgignore file, you just lay it out as follows: ``` syntax: glob *.pyc syntax: regexp ^static/ syntax: glob *~ ``` Originally from [here](https://stackoverflow.com/questions/10673783/is-it-possible-to-use-rooted-glob-patterns-in-hgignore)
This is how my file looks like in the end: ``` ProjectA/dist .*\.log .*\.class build/ ^\.gradle/ ^\.settings ``` I needed to restart Eclipse in order for this to work. @Nanhydrin thanks for your help :)
67,989,382
I need to check if there are some duplicates value in one column of a dataframe using Pandas and, if there is any duplicate, delete the entire row. I need to check just the first column. Example: ``` object type apple fruit ball toy banana fruit xbox videogame banana fruit apple fruit ``` What i need is: ``` object type apple fruit ball toy banana fruit xbox videogame ``` I can delete the 'object' duplicates with the following code, but I can't delete the entire row that contains the duplicate as the second column won't be deleted. ``` df = pd.read_csv(directory, header=None,) objects= df[0] for object in df[0]: ```
2021/06/15
[ "https://Stackoverflow.com/questions/67989382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13421326/" ]
Pipe the object through the `keys` filter, and slice it if you really want the first 2 of more-than-2: ``` % jq 'keys[:2]' tmp.json [ "BI_Arch", "Data_Engineers" ] ```
You can use just `jq '[keys]'` Here's an online tool <https://jqplay.org/s/csowtIQRaZ>
14,501,920
Is there any other way to shorten this condition? ``` if (oper.equals("add") || oper.equals("Add") || oper.equals("addition") || oper.equals("Addition") || oper.equals("+")) ``` I was just wondering if there's something I can do to 'shortcut' this. The user will type a string when prompted what kind of operation is to be performed in my simple calculator program. Our professor said our program should accept whether the user enters "add", or "Add", you know, in lowercase letters or not... Or is the only way I should do it?
2013/01/24
[ "https://Stackoverflow.com/questions/14501920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1882428/" ]
You can use [`String#equalsIgnoreCase(String)`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase%28java.lang.String%29) for 1st four strings: - ``` if (oper.equalsIgnoreCase("add") || oper.equalsIgnoreCase("addition") || oper.equals("+")) ``` If number of strings increases, you would be better off with a `List`, and use its `contains` method. But just for these inputs, you can follow this approach only. --- Another way to approach this is to use [`String#matches(String)`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#matches%28java.lang.String%29) method, which takes a regex: - ``` if (oper.matches("add|addition|[+]") ``` But, you don't really need a regex for this. Specially, this method can become ugly for greater inputs. But, it's just a way for this case. So, you can choose either of them. 1st one is more clear to watch on first go. --- Alternatively, you can also use [`enum`](http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html) to store `operators`, and pass it's instance everywhere, rather than a `string`. It would be more easy to work with. The enum would look like this: ``` public enum Operator { ADD, SUB, MUL, DIV; } ``` You can enhance it to your appropriate need. Note that, since you are getting user input, you would first need to identify the appropriate enum instance based on it, and from there-on you can work on that enum instance, rather than String.
In addition to @Rohit's answer, I would like to add this. In case of comparison of strings, if `oper is null` a `NullPointerException` could be thrown. SO its always better to write ``` "addition".equalsIgnoreCase(oper) ``` instead of ``` oper.equalsIgnoreCase("addition") ```
52,941,249
I am new to JavaScript, so could someone explain this (in my opinion) strange behaviour (code below)? The second console.log prints 5 to the console, despite the fact that loop defines that `a` should be less than 5. Additionally, the second console.log is outside the loop. I understand that assigning value to the "let" instead of "var" generates different results, but I am curious why JavaScript behaves that way. Does JavaScript somehow "export" that 5 outside the loop? I am a little bit confused. ```js for (var a = 0; a < 5; a++) { console.log("Number inside is " + a); }; // Prints: "Number inside is 0...1...2...3...4" console.log("Number outside is " + a); // Prints: "Number outside is 5 ```
2018/10/23
[ "https://Stackoverflow.com/questions/52941249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9920306/" ]
`a++` increments variable `a` by 1 after its execution. `console.log` inside loop is executed till value of `a` remains less than 5. However, after the last loop iteration when the value of `a` becomes 4 and it's printed by the inside `console.log`, `a++` increments its value to 5 and then the for-loop condition `a<5` fails and the loop breaks. Afterwards, the compiler executes `console.log` outside the for-loop where the value of `a` is already 5. The key point is, the for-loop breaks only when the value of `a` turns 5. But as soon as it breaks, `console.log` inside the loop won't be executed and the compiler would execute line of code next to the for-loop. Furthermore, you've declared the variable `a` outside the loop and its scope exists even the loop is finished. I hope it clarifies the confusion.
The scope of a variable declared with `var` is its current execution context, which is either the enclosing function or, for variables declared outside any function, `global`. Here the variable `a` is declared `globally`, and redeclaring the variable makes it `original value changed`, So when running inside for loop a is firstly initialised with 0 thus replacing 10, and when the loop terminates at a is equal to 5, because 5<5, which is false. Thus consoling the value 5 to the outer for loop. So the conclusion is `var` scope is functional which is responsible for the changes. <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var>
14,410,431
In the below code once I hit check\_access as 0 how do I preserve the value and hit the if condition below ($check\_root && $check\_access) . Break will only terminate the inner loop. But the other loops will continue as per me. ``` } else { set check_access 0 break } } } if {$check_root && $check_access} { set result 1 } else { set result 0 } ```
2013/01/19
[ "https://Stackoverflow.com/questions/14410431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1813181/" ]
One of the times that I have run into this issue is when doing a `git commit` after a `git add`. So, the following sequence will produce the rebase error you mention: ``` git add <file with conflict> git commit -m "<some message>" git rebase --continue ``` While, the sequence below runs without any errors, and continues the rebase: ``` git add <file with conflict> git rebase --continue ``` It might be possible that `git add -A` with the "All" option is creating a similar situation. (Please note, I am very inexperienced in git, so this answer may not be correct.) To be safe, the `git rebase --skip` seems to also work well in this situation.
After a rebase with lots of conflicts (long `git status`) I couldn't figure out what it was that I was supposed to stage. I use Git integrated with PhpStorm and it didn't show any unstaged files. `git add .` didn't solve it but [this comment](https://stackoverflow.com/questions/12759390/cannot-continue-git-rebase#comment17240698_12759390) recommended calling `git diff-files --ignore-submodules`. That showed three files I had to specifically git add and that did the trick.
11,174,858
Manually built: ``` [btnRun addTarget:self action:@selector(RunApp:) forControlEvents:UIControlEventTouchUpOutside]; ``` --- Programmatically built: something of the following like ?? ``` - (void) setRunButton:(UIButton*)objectName mySelector:(NSString*)funcName myControlEvent:(NSString*) controlEvent { [objectName addTarget:self action:@selector(funcName) forControlEvents:controlEvent]; } ```
2012/06/24
[ "https://Stackoverflow.com/questions/11174858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/767829/" ]
I think you'd need something like the following: ``` - (void)setRunButton:(UIButton *)objectName mySelector:(NSString *)action myControlEvent:(UIControlEvents)controlEvent { [objectName addTarget:self action:NSSelectorFromString(action) forControlEvents:controlEvent]; } ``` It is unusual to pass a selector as an `NSString` but you can use `NSSelectorFromString()` to convert the string name of the selector into a selector. Control events parameters are not strings they are an enumeration so I have changed the `myControlEvent` parameter to have the `UIControlEvents` type. It would be more usual to pass the selector to the method using `@selector(action)`. However, `@selector` is handled at compile time so the parameter isn't actually an `NSString`. In this case the method would look like: ``` - (void)setRunButton:(UIButton *)objectName mySelector:(SEL)action myControlEvent:(UIControlEvents)controlEvent { [objectName addTarget:self action:action forControlEvents:controlEvent]; } ```
Pass the entire selector as a parameter ``` - (void) setRunButton:(UIButton*)objectName mySelector:(SEL)action myControlEvent:(NSString*) controlEvent { [objectName addTarget:self action:action forControlEvents:controlEvent]; } ```
47,451,579
I've found some code examples that explain how I can apply a class item if conditions are met. In my .ts file I have the following: ``` private readNews : boolean = false; ``` [..] ``` ngOnInit() { localStorage.setItem('readNews', 'Read'); if (localStorage.getItem('readNews') != null || '') { this.readNews = true; } } ``` In my HTML I have the following inline CSS: ``` <i class="fal fa-cogs fa-5x"></i> ``` However, what I want it to be is the following: If `this.readNews === true` ``` <i class="fal fa-cogs fa-5x blink"></i> ``` So it needs to add 'blink' in the CSS when the news is read (which is saved in localStorage).
2017/11/23
[ "https://Stackoverflow.com/questions/47451579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8718995/" ]
``` <i [class.blink]="readNews"></i> ``` Based on cheat sheet on <https://angular.io/guide/cheatsheet>
In HTML: ``` <i *ngIf="readNews" class="fal fa-cogs fa-5x"></i> <i *ngIf="!readNews" class="fal fa-cogs fa-5x blink"></i> ``` And in typescript i would refactor as this to improve readability: ``` ngOnInit() { localStorage.setItem('readNews', 'Read'); this.readNews = (localStorage.getItem('readNews') != null || ''); ``` }
16,194,456
I must be missing something. After downloading AntlrWorks2 I found the executable bin/antlrworks2.exe and bin/antlrworks264.exe. Aren't these supposed to be the standalone version of the tool? Neither works for me; after a NetBeans splash screen, the first times around I got an error message on missing packages; after a couple of times I chose to go on regardless, but now (still after the initial spash screen) there is simply nothing happening at all. I can't find any tutorial or manual detailing how to run AntlrWorks stand-alone, so any help is much appreciated.
2013/04/24
[ "https://Stackoverflow.com/questions/16194456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1871216/" ]
This is due to a bug in the NetBeans platform. I filed a report but it hasn't received a reply yet: [Cannot launch platform application after moving installation folder](https://netbeans.org/bugzilla/show_bug.cgi?id=227219) Here is a workaround that does not delete any preferences you have customized: > > I found that deleting just the `var` folder under the user's generated > `.antlrworks2` settings folder resolves the issue... > > >
Still an issue as of date of this post. Deleting the `.antlrworks2` folder from \users\username\AppData\Roaming does work - you can find this folder by putting `%APPDATA%` into your file explorer address bar (exactly as shown) - that will go to the app data folder for your current user login session. Delete the `.antlrworks2` folder and then re-run the app.
34,249,518
I am new to mule ESB. I have a requirement to set HTTP headers where the values should be fetched from MySQLDB. I am able to fetch values from DB. DB returned multiple column values with one row. I can able to set one column value in flow variable(flowVars) and that can be set in HTTP headers. But if i have to set multiple column variables in each HTTP headers will leads me to write multiple set variable command. How can I avoid to write multiple set variable command ? (Is there any mule expresion to set multiple variable by single command ?) Is there any other simple way to achieve this ? ``` <flow name="mule_eeFlow"> <http:listener config-ref="HTTP_Input_eba_Listener_Configuration" path="/XXX/additem" doc:name="HTTP"/> <db:select config-ref="MySQL_Configuration" doc:name="Database"> <db:template-query-ref name="Template_Query"/> </db:select> <set-variable variableName="LEVEL" value="#[message.payload[0].'X-API-COMPATIBILITY-LEVEL']" doc:name="Variable"/> <set-variable variableName="DEVNAME" value="#[message.payload[0].'X-API-DEV-NAME']" doc:name="Variable"/> <set-variable variableName="APPNAME" value="#[message.payload[0].'X-API-APP-NAME']" doc:name="Variable"/> <set-variable variableName="CERTNAME" value="#[message.payload[0].'X-API-CERT-NAME']" doc:name="Variable"/> <set-variable variableName="SITEID" value="#[message.payload[0].'X-API-SITEID']" doc:name="Variable"/> <set-variable variableName="CALLNAME" value="#[message.payload[0].'X-API-CALL-NAME']" doc:name="Variable"/> <custom-transformer class="AddingHTTPHeader" doc:name="Java"/> </flow> ``` My Java code look like ``` @Override public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException { // TODO Auto-generated method stub message.setOutboundProperty("X-API-COMPATIBILITY-LEVEL", message.getInvocationProperty("LEVEL")); message.setOutboundProperty("X-API-DEV-NAME", message.getInvocationProperty("DEVNAME")); message.setOutboundProperty("X-API-APP-NAME", message.getInvocationProperty("APPNAME")); message.setOutboundProperty("X-API-CERT-NAME", message.getInvocationProperty("CERTNAME")); message.setOutboundProperty("X-API-SITEID", message.getInvocationProperty("SITEID")); message.setOutboundProperty("X-API-CALL-NAME", message.getInvocationProperty("CALLNAME")); return null; } ```
2015/12/13
[ "https://Stackoverflow.com/questions/34249518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4594924/" ]
I am taking the same course from Coursera as you are. Instead of going for the above solutions, do you mind trying this one. I feel this one is within the scope of what we had learnt till the above mentioned problem. It absolutely worked for me. ``` import urllib import re from bs4 import * url = 'http://python-data.dr-chuck.net/comments_216543.html' html = urllib.urlopen(url).read() soup = BeautifulSoup(html,"html.parser") sum=0 # Retrieve all of the anchor tags tags = soup('span') for tag in tags: # Look at the parts of a tag y=str(tag) x= re.findall("[0-9]+",y) for i in x: i=int(i) sum=sum+i print sum ```
``` from urllib.request import urlopen from bs4 import BeautifulSoup import ssl import re lst = list() sum = 0 ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter - ') html = urlopen(url, context=ctx).read() soup = BeautifulSoup(html, "html.parser") tags = soup('span') for tag in tags: strtag = str(tag) lst = re.findall('[0-9+]+',strtag) sum = sum + int(lst[0]) print(sum) ```
7,366
This is probably a very basic question. But I am getting conflicting results from Google regarding the types of Talaq or divorce in Islam. Could someone explain how many types of Talaq are there in Islam and how are they initiated? **EDIT** I am specially bewildered by the following article. The article states that there are three types of Talaq, while the rest of the stuff- including Wikipedia- says that there are two. [Types of Divorce](http://myummah.co.za/site/2008/04/29/types-of-divorce/)
2013/02/13
[ "https://islam.stackexchange.com/questions/7366", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/558/" ]
I only know of two types. You can give single talaq or triple talaq. The triple Talaq ends the marriage permentantly and you cannot marry the same woman again until she marries again, consummates the marriage and the marriage ends. In single Talaq you can get back together;if you have intercourse, the talaq is then annulled. Single talaq should be given. Inshallah someone will provide more comprehensive information on this.
The types of Divorce ( Talaq ) are Four in other View. 1) Talaq ( in which by a husband pronounciation ) = In this type of Divorce, it is spell out by A husband to his wife, declaring a Seperation to that particular Social Contract. Once a word of Divorce in this Term is commenced, there's no amendment in which to wipe it as a mistake, even in a Bed of Sick or Intoxicated, either to pronounce a Divorce beyond 3 terms. According to Maliki School of Thought " Such type of Divorce can not be Reconcilled if a person became Intoxicant Voluntarally, and when ever beyond 3 terms, it will be reduced to 1 term of Divorce. According to Hanafi " Such type of Divorce can be reconcilled when a person even Voluntarally became Intoxicant, after He gain the conscious to ask him if He mean such Divorce. 2) khul'i ( Men are your cloth and you are their cloth ) = Therefore, it is not only A Men that has such right of Divorce at his own will, even Women can be title to Divorce in this type. When ever a woman is no longer interested in being with her Husband, she has the right to complain before the Arbitrators, Such Divorce can be Valid if the Woman can take back the Dowry she recieved by the Man. Such Case Happened During prophet Muhammad's life time. 3) Tafriq ( An allegation in ponder ) = In a nut Shell, when there is an allegation in between a Husband and wife the Divorce may Be consider. For Example, if a husband Reject a pregnant of His wife, claiming that it is not by him, therefore, the Arbitrators are in title to Seperate them, and no Marriage to be Conducted between them again. 4) ( cant remember the Arabic title ) Islam Issue = in this type, it is when a Husband or Wife cannot focus on Islam. I.e If a husband or wife can not pray, fasting, zakat etc in respect of Five pillars of Islam. One can Complain to the Arbitrators, when Husband or wife set at default to do so, then the Marriage can be Seperated.
25,477
My plane departs from Geneva Airport (Geneva International terminal M) at 19:55. I'll be in Zürich and a bit short on time. If I take the train that arrives at "Genève-Aéroport" at 18:51, will I have enough time to find the terminal and check in? I've never been to this airport before.
2014/03/27
[ "https://travel.stackexchange.com/questions/25477", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/12593/" ]
The train station is at the airport. You have to take up two (or three) escalators from the platform and then walk for [approximately 50 meters to arrive at the check-in](http://gva.ch/en/desktopdefault.aspx/tabid-60/). There is only one terminal, so it will take you 5-10 minutes at most to go from the platform to check-in. It is a rather small airport and you should be able to find it without problems. This being said, the [airport says](http://gva.ch/en/desktopdefault.aspx/tabid-43/) that you have to check-in 40 minutes before the flight leaves and be at the gate 30 minutes before departure. I am not sure how much that is enforced. I'd be wary especially if you are flying Easyjet, as their gates tend to be very far away. Also note that there can be quite long queues at security. I would say you can definitely make it to the check-in in time, what comes after will depend on how busy the airport is and will require that you don't have any problems at immigration or security.
It's really in the airport (which is itself not very big but not so efficient for its size). Arriving: Out of the baggage claim, take left, walk 50-100m tops, you are already in the station (the actual tracks run underneath the airport). In the other direction you need to take some escalators, find the right check-in desk and then take some other escalators to reach the security check but it's not very long either. You will walk more between the security screening and your gate.
1,132,708
I am a student and I want to know if this proof is correct. **Proof.** If $\sqrt5$ is a natural number, it should be even or odd. If it would be even, we could express it as $2k$ for some integer $k$. If it would be odd, we could express it as $2j+1$ for some integer $j$. But those integers do not exist what is a contradiction. Then, $\sqrt5$ is not a natural number. Q.E.D. Using Joofan's idea, I have a second proof. Please give me your opinion! **Proof.** If $\sqrt5$ is a natural number, then there exists a natural number $n^2=5$, but $2^2<5<3^2$, and there is no natural number between $2$ and $3$. Therefore, we can conclude that there does not exist a natural number $n^2=5$, and that is a contradiction. Q.E.D.
2015/02/04
[ "https://math.stackexchange.com/questions/1132708", "https://math.stackexchange.com", "https://math.stackexchange.com/users/195513/" ]
Let's assume, to the contrary, that $\sqrt{5}$ is a natural number, $n \in \mathbb{N}.$ Then, since $f(x)=\sqrt{x}$ is an increasing function, we know that $\sqrt{4}<\sqrt{5}<\sqrt{9}.$ Thus, $$\sqrt{4}<n<\sqrt{9}\implies 2<n < 3 $$ Producing a contradiction. So, it must be the case that $n \notin \mathbb{N}$.
You can prove that 5 is not rational. Suppose, without lost of generality that there exists natural numbers $p, q$ such that: $$\sqrt5 =p/q$$ $$5q^2 = p^2$$ Then, $p$ has to be multiple of 5, so $p=5 k$. Therefore: $$q^2=5k^2$$ So $p, q$ cannot be relatively prime. $\sqrt 5$ cannot be expressed as a ratio of integers, so it is irrational.
432,143
The medians of a triangle intersect in a trisection point of each.
2013/06/29
[ "https://math.stackexchange.com/questions/432143", "https://math.stackexchange.com", "https://math.stackexchange.com/users/76961/" ]
I can propose the following evidence. Let $ABC$ be an arbitrary triangle of a Cartesian plane. Let its vertices $A$, $B$, and $C$ have the coordinates $(x\_1,y\_1)$, $(x\_2,y\_2)$ and $(x\_3, y\_3)$ respectively. Then the midpoints $A\_1$, $B\_1$, and $C\_1$ of the sides $BC$, $CA$, and $AB$ respectively have the coordinates $(\frac{x\_2+x\_3}2, \frac{y\_1+y\_3}2)$, $(\frac{x\_1+x\_3}2, \frac{y\_1+y\_3}2)$ and $(\frac{x\_1+x\_2}2, \frac{y\_1+y\_2}2)$ respectively. Shifting, if necessary, the zero $O$ of the Cartesian plane, without loss of generality, we may assume that $x\_1+x\_2+x\_3=y\_1+y\_2+y\_3=0$. Then all the determinants $\left|\begin{matrix} x\_1 & y\_1 \\ \frac{x\_2+x\_3}2 & \frac{y\_2+y\_3}2\\ \end{matrix} \right|,$ $\left|\begin{matrix} x\_2 & y\_2 \\ \frac{x\_1+x\_3}2 & \frac{y\_1+y\_3}2\\ \end{matrix} \right|$, and $\left|\begin{matrix} x\_3 & y\_3 \\ \frac{x\_1+x\_2}2 & \frac{y\_1+y\_2}2\\ \end{matrix} \right|$ are equal to zero. Therefore all the triangles $AOA\_1$, $BOB\_1$, and $COC\_1$ have zero area. Therefore $O$ is the intersection point of the medians of the triangle $ABC$. Moreover, ${\bf AO}=(-x\_1,-y\_1) =2(\frac{x\_2+x\_3}2, \frac{y\_1+y\_3}2)=2{\bf OA\_1}$. Similarly, ${\bf BO}=2{\bf OB\_1}$ and ${\bf CO}=2{\bf OC\_1}$. Thus $O$ is the trisection point of each of the segments $AA\_1$, $BB\_1$, and $CC\_1$.
The medians of an equilateral triangle must trisect by symmetry. Any other triangular shape can be found by performing a linear transformation on the vertices of the equilateral triangle, and such transformations preserve the medians along with their trisection point.
371
I'm curious about natural language querying. Stanford has what looks to be a strong set of [software for processing natural language](http://nlp.stanford.edu/software/index.shtml). I've also seen the [Apache OpenNLP library](http://opennlp.apache.org/documentation/1.5.3/manual/opennlp.html), and the [General Architecture for Text Engineering](http://gate.ac.uk/science.html). There are an incredible amount of uses for natural language processing and that makes the documentation of these projects difficult to quickly absorb. Can you simplify things for me a bit and at a high level outline the tasks necessary for performing a basic translation of simple questions into SQL? The first rectangle on my flow chart is a bit of a mystery. ![enter image description here](https://i.stack.imgur.com/wJPx9.png) For example, I might want to know: ``` How many books were sold last month? ``` And I'd want that translated into ``` Select count(*) from sales where item_type='book' and sales_date >= '5/1/2014' and sales_date <= '5/31/2014' ```
2014/06/14
[ "https://datascience.stackexchange.com/questions/371", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/434/" ]
Natural language querying poses very many intricacies which can be very difficult to generalize. From a high level, I would start with trying to think of things in terms of nouns and verbs. So for the sentence: How many books were sold last month? You would start by breaking the sentence down with a parser which will return a tree format similar to this: ![enter image description here](https://i.stack.imgur.com/ogoiY.png) You can see that there is a subject books, a compound verbal phrase indicating the past action of sell, and then a noun phrase where you have the time focus of a month. We can further break down the subject for modifiers: "how many" for books, and "last" for month. Once you have broken the sentence down you need to map those elements to sql language e.g.: how many => count, books => book, sold => sales, month => sales\_date (interval), and so on. Finally, once you have the elements of the language you just need to come up with a set of rules for how different entities interact with each other, which leaves you with: Select count(\*) from sales where item\_type='book' and sales\_date >= '5/1/2014' and sales\_date <= '5/31/2014' This is at a high level how I would begin, while almost every step I have mentioned is non-trivial and really the rabbit hole can be endless, this should give you many of the dots to connect.
Check [ln2sql is an NLP tool to query a database in natural language.](https://github.com/FerreroJeremy/ln2sql) [Daniel Moisset - Querying Your Database in Natural Language](https://www.youtube.com/watch?v=6RrDBKUlO4Q) In general very hard [NLU and Natural Language Interfaces to Databases](https://medium.com/ontologik/nlu-and-natural-language-interfaces-to-databases-d04c3f032949)
31
When I am documenting records, do I use the name of a city or country as it is called today or as it was in the year an ancestor was there? Related to: [When documenting place names, should I write them in my language or in their native language?](https://genealogy.stackexchange.com/questions/64/when-documenting-place-names-should-i-write-them-in-my-language-or-in-their-nat)
2012/10/09
[ "https://genealogy.stackexchange.com/questions/31", "https://genealogy.stackexchange.com", "https://genealogy.stackexchange.com/users/41/" ]
The problem with using "current" names as the only name, is that "current" changes over time. Is the Crimea part of the Ukraine or of Russia. If you attempt to use "current" you're dooming yourself to a never ending job of updating locations. I prefer an approach, supported by the tool I use, [Genbox](http://www.genbox.com/), that uses the name at the time of the event which links to a database location where all the names are indicated. ``` born L'vov, (...) Russia Bar Mitzva Lemberg, (...) Austria Married L'vov, (...) Soviet Union Died L'viv, (...) Ukraine ``` [Where the (...) indicate the equivalent of town/city, township, county, province based on the location on the date in question] I have the option to add the current name also, which makes the events look like ``` born L'vov, (...) Russia (Lately, L'viv, (...) Ukraine) Bar Mitzva Lemberg, (...) Austria (Lately, L'viv, (...) Ukraine) Married L'vov, (...) USSR (Lately, L'viv, (...) Ukraine) Died L'viv, (...) Ukraine ``` This allows the information to be correct and not require an update with Russia conquers the Ukraine.
Personally I use today's name but also place a note with the old name.
11,462
Is there a suitable tape for permanently joining pieces of cardboard or paper together, that can then have paint (or other finish) applied to it just as it could to the paper/card itself? I’ve been making some polyhedra out of cardboard—nothing fancy, just corrugated stuff cut from boxes, joined together with some painter’s tape that I had handy. This was originally in the nature of a prototype, before I draw up something to be printed on paper or card, complete with tabs for gluing. The intended context is a school classroom. I’d like to make, or let students make, something reasonably sturdy that will last a few months, sitting around. (If I can make something more durable that will last me a few *years*, so much the better, but that’s a lesser consideration.) But the more time I spent on this prototype, assembling the pieces with tape, the more I liked being able to use tape instead of glue. It covers the joins, and it’s easier to apply to the final joint than trying to press down a tab that’s on the *inside* of the object! The trouble with painter’s/masking tape is that it’s meant to be peeled off, and so it doesn’t stick very securely. Already some of the edges on the earliest pieces are peeling up. But the more permanent tapes I have (or know of) have a plastic surface. I’d like the finished object to take paint, or pencil, or whatever—so students can decorate their work freely, and I can add some visual appeal (or mathematical info) to mine. And I’d like to avoid having to wrap it in a paper coat first! I want the tape to essentially give the same surface as paper or card. My own searching hasn’t turned anything up. I did learn that masking tapes come in different adhesive strengths, so maybe just picking a stronger tape would serve?
2023/01/26
[ "https://crafts.stackexchange.com/questions/11462", "https://crafts.stackexchange.com", "https://crafts.stackexchange.com/users/16324/" ]
Drywall tape is cheap and pretty permanent. It is designed to have drywall mud applied over it, but paint sticks to it as well.
If you want your "art" to last a long time, I would exclude any ribbon product with glue on one side from the factory. First you should find a good glue for paper, which will not die in a few months / years. Then make your own "ribbon" of paper - cut long stretches of paper from something. You might even find for purchase such ribbons - without the glue. Then apply the glue, apply a ribbon of mesh of fiberglass (used in constructions and home repairs), then the paper ribbon. Make sure that the fiberglass mesh is fully "immersed" (covered) with glue, before adding the paper ribbon. Paint as needed when it is cured. If the glue is paintable when cured, you might not even need to use a paper ribbon. Just glue the fiberglass mesh on one side of the carton box, let it cure, glue it to the other side, let it cure. at the end, if needed apply another level of glue (it will also minimize the height of the bumps created by the fiberglass). Paint as desired. If you look for additional artistic effect, use some fabric instead of fiberglass. Hemp sack comes first to mind. Either cut it as ribbons, or use it to cover large areas. Apply it as I described before. he surface of your art will now have the texture of the fabric (hemp sack or something else), and the color of your choice. You might even use different fabrics on different areas / edges, for more artistic flexibility. --- The thing you were doing at the beginning with those tabs was actually one of the better things you could to - quality wise.
27,285,775
I have a huge problem with printing the specific word backwards. I'm trying to find words with '\*' at the beggining and print them backwards, the rest should be printed normally. ***For example:*** **Input**: `aaa1 ab0 1kk *ddd *lel 2cccc2 c1` **Output** `aaa1 ab0 1kk ddd* lel* 2cccc2 c1` All I have is finding the words, finding the ones with '*' and printing normally the words without '*'. Please help me and thank you in advance for your attention to this matter... Have to write it in C language and here's my code ``` int main() { char *x = "aaa1 ab0 1kk *ddd *lel 2cccc2 c1"; char bufor[100]; asm volatile ( ".intel_syntax noprefix;" "mov eax, %0;" "push eax;" "mov eax, %1;" "push eax;" "call zadanie1;" "jmp wyjscie;" "zadanie1:" // // FUNCTION START // "pushad;" "mov esi, [esp+40];" "mov edx, [esp+36];" "push edx;" "xor ecx, ecx;" // MAIN LOOP - WORDS SEARCHING "zad_loop:" "mov edx, [esp];" "lodsb;" "test al, al;" "jz zad_loop_end;" "cmp al, 0x20;" "jz zad_loop_end;" "mov [edx+ecx], al;" "inc ecx;" "jmp zad_loop;" // MAIN LOOP END "zad_loop_end:" "mov [edx+ecx], ch;" "push eax;" "push ecx;" "test ecx, ecx;" "jz not_print;" // IS THE FIRST CHAR '*' "lea eax, [edx];" "mov al, [eax];" "cmp al, '*';" "jz backwards;" "test al, al;" "jz not_print;" // PRINTING THE WORD WITHOUT '*' "mov edx, [esp];" "mov ecx, [esp+8];" "mov ebx, 1;" "push eax;" "mov eax, 4;" "int 0x80;" "push 0x20;" "call print_char;" "pop eax;" // PRINTING THE WORD WITH '*' - BACKWARDS "backwards:" // SKIP PRINTING "not_print:" "pop ecx;" "pop eax;" "xor ecx, ecx;" "test al, al;" "jnz zad_loop;" // FUNCTION END "pop edx;" "push 0x0A;" "call print_char;" "popad;" "ret 8;" // CHAR OUTPUT "print_char:" "pushad;" "mov edx, 1;" "lea ecx, [esp+36];" "mov ebx, 1;" "mov eax, 4;" "int 0x80;" "popad;" "ret 4;" "wyjscie:" ".att_syntax prefix;" : : "r" (x), "r" (bufor) : "eax" ); return 0; } ```
2014/12/04
[ "https://Stackoverflow.com/questions/27285775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4322758/" ]
We can generalize the solution of 3x14159265 and Seth Tisue thanks to 2 small type classes: ```scala import play.api.libs.json.Json.JsValueWrapper import play.api.libs.json._ import simulacrum._ object MapFormat { @typeclass trait ToString[A] { def toStringValue(v: A): String } @typeclass trait FromString[A] { def fromString(v: String): A } implicit final def mapReads[K: FromString, V: Reads]: Reads[Map[K, V]] = new Reads[Map[K, V]] { def reads(js: JsValue): JsResult[Map[K, V]] = JsSuccess(js.as[Map[String, V]].map { case (k, v) => FromString[K].fromString(k) -> v }) } implicit final def mapWrites[K: ToString, V: Writes]: Writes[Map[K, V]] = new Writes[Map[K, V]] { def writes(map: Map[K, V]): JsValue = Json.obj(map.map { case (s, o) => val ret: (String, JsValueWrapper) = ToString[K].toStringValue(s) -> o ret }.toSeq: _*) } implicit final def mapFormat[K: ToString: FromString, V: Format]: Format[Map[K, V]] = Format(mapReads, mapWrites) } ``` Note that I use Simulacrum (<https://github.com/mpilquist/simulacrum>) to define my type classes. Here is an example of how to use it: ```scala final case class UserId(value: String) extends AnyVal object UserId { import MapFormat._ implicit final val userToString: ToString[UserId] = new ToString[UserId] { def toStringValue(v: UserId): String = v.value } implicit final val userFromString: FromString[UserId] = new FromString[UserId] { def fromString(v: String): UserId = UserId(v) } } object MyApp extends App { import MapFormat._ val myMap: Map[UserId, Something] = Map(...) Json.toJson(myMap) } ``` if IntelliJ says that your `import MapFormat._` is never used, you can and this: `implicitly[Format[Map[UserId, Something]]]` just below the import. It'll fix the pb. ;)
<https://gist.github.com/fancellu/0bea53f1a1dda712e179892785572ce3> Here is a way to persist a Map[NotString,...]
3,992,027
can you give me any advice how to caluclate $\int\_{0}^{1/2} \frac{e^x - 1}{x} \,dx$ ? I need to use series. I tried to split it as $$ \int\_{0}^{1/2} \frac{e^x}{x} \,dx - \int\_{0}^{1/2} \frac{1}{x} \,dx$$ and then I can use a series for the first equation but I get another $\int\_{0}^{1/2} \frac{1}{x} \,dx$. Can I somehow evaluate these integrals or I need to use a completely different approach. Thanks!
2021/01/19
[ "https://math.stackexchange.com/questions/3992027", "https://math.stackexchange.com", "https://math.stackexchange.com/users/876268/" ]
You cannot split the integral into two unless at least one of them is convergent. By the series definition of the exponential function, for $x\ne 0$ $$ \frac{e^x-1}{x}=\frac1x(x+\frac{x^2}{2!}+\frac{x^3}{3!}+\cdots ) =1+\frac{x}{2!}+\frac{x^2}{3!}+\cdots $$ Now define the function $f:[0,1/2]\to\mathbb{R}$ with $f(x)=\frac{e^x-1}{x}$ if $x\ne 0$ and $f(0)=1$. Then the function $f$ is continuous on $[0,1]$. So you can write $$ f(x)=1+\frac{x}{2!}+\frac{x^2}{3!}+\cdots $$ and $$ \int\_0^{1/2} \frac{e^x-1}{x}\,dx=\int\_0^{1/2}f(x)dx= \int\_0^{1/2}(1+\frac{x}{2!}+\frac{x^2}{3!}+\cdots)\,dx $$ Now do [integration term by term](https://www.dpmms.cam.ac.uk/%7Eagk22/uniform.pdf).
$\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,} \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace} \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack} \newcommand{\dd}{\mathrm{d}} \newcommand{\ds}[1]{\displaystyle{#1}} \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,} \newcommand{\ic}{\mathrm{i}} \newcommand{\mc}[1]{\mathcal{#1}} \newcommand{\mrm}[1]{\mathrm{#1}} \newcommand{\on}[1]{\operatorname{#1}} \newcommand{\pars}[1]{\left(\,{#1}\,\right)} \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,} \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}} \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$ $\ds{\bbox[5px,#ffd]{}}$ --- \begin{align} &\bbox[5px,#ffd]{\int\_{0}^{1/2}{\expo{x} - 1 \over x}\,\dd x} \,\,\,\stackrel{x\ \mapsto\ -x}{=}\,\,\, -\int\_{-1/2}^{0}{\expo{-x} - 1 \over x}\,\dd x \\[5mm] = & \lim\_{\Lambda \to \infty} \bracks{-\int\_{-1/2}^{\Lambda}{\expo{-x} - 1 \over x}\,\dd x + \int\_{0}^{\Lambda}{\expo{-x} - 1 \over x}\,\dd x} \\[5mm] = &\ \lim\_{\Lambda \to \infty} \left[-{\rm P.V.}\int\_{-1/2}^{\Lambda} {\expo{-x} \over x}\,\dd x\right. \\[2mm] &\ \phantom{\lim\_{\Lambda \to \infty}\,\,\,} + \int\_{-1/2}^{\Lambda}{\dd x \over x} + \ln\pars{\Lambda}\pars{\expo{-\Lambda} - 1} \\[2mm] &\ \left.\phantom{\lim\_{\Lambda \to \infty}\,\,\,}+ \int\_{0}^{\Lambda}\ln\pars{x}\expo{-x}\dd x\right] \\[5mm] = &\ \bbx{\on{E\_{i}}\pars{1 \over 2} + \ln\pars{2} - \gamma} \approx 0.5702 \\ & \end{align} * $\ds{\on{E\_{i}}}$: *Exponential Integral Function*. $\ds{\on{E\_{i}}\pars{z} \equiv -{\rm P.V.}\int\_{-z}^{\infty}{\expo{-x} \over x}\dd x}$. * $\ds{\gamma}$: *Euler-Mascheroni Constant* which is equal to $\ds{\phantom{\gamma:}-\int\_{0}^{\infty}\ln\pars{x}\expo{-x}\dd x}$.
29,417,783
I converted this [.ttf](http://www.dafont.com/minecraftia.font) to webfont (used in css) in many online converters but the result always has some weird space at the bottom. It's like a `line-height` and `valign` glitch. Here is an example how the links looks ![s](https://i.stack.imgur.com/wABN5.png) Also [on Ubuntu](http://static.md/e92a65e2496a5f72105bb7b939736015.png) (Linux) and [on other OS it looks different](http://www.browserstack.com/screenshots/b0545b7e05cedf3f1e0ffa56cbf4cf63809cfedb) (see the top header text "RO EN RU" vertical alignemnt). Do you have any idea why this happens and how to fix it?
2015/04/02
[ "https://Stackoverflow.com/questions/29417783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1794248/" ]
I created this little extension in **Swift 5** to convert from `UIImage` to `CKAsset`: ``` extension UIImage { func toCKAsset(name: String? = nil) -> CKAsset? { guard let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return nil } guard let imageFilePath = NSURL(fileURLWithPath: documentDirectory) .appendingPathComponent(name ?? "asset#\(UUID.init().uuidString)") else { return nil } do { try self.pngData()?.write(to: imageFilePath) return CKAsset(fileURL: imageFilePath) } catch { print("Error converting UIImage to CKAsset!") } return nil } } ``` You can then use it as you have it in your question: ``` if let asset = ImageToSave.toCKAsset() { newRecord.setObject(asset, forKey: "Image") CKContainer.defaultContainer().publicCloudDatabase.saveRecord(newRecord, completionHandler: { record, error in if error != nil { println("\(error)") } else { // saved successfully! } }) } ```
You'll want to pick the Asset value type in the dashboard for this value. `newRecord.setValue(ImageToSave, forKey: "Image")` UIImage is not an allowed type on `CKRecord`. Your best option is to write this image out to a file, then create a `CKAsset` and set that on the record.
67,243,475
I am working on a project in Node.JS Express. I had several pages all of which are running fine but only one page (till now) is giving error in loading up. When I ran that page a error pops up, that is : ```html SyntaxError: Unexpected token catch in E:\nodeapp\views\adm.ejs while compiling ejs If the above error is not helpful, you may want to try EJS-Lint: https://github.com/RyanZim/EJS-Lint Or, if you meant to create an async function, pass async: true as an option. at new Function (<anonymous>) at Template.compile (E:\Submit\Fresh\nodeapp\node_modules\ejs\lib\ejs.js:633:12) at Object.compile (E:\Submit\Fresh\nodeapp\node_modules\ejs\lib\ejs.js:392:16) at handleCache (E:\Submit\Fresh\nodeapp\node_modules\ejs\lib\ejs.js:215:18) at tryHandleCache (E:\Submit\Fresh\nodeapp\node_modules\ejs\lib\ejs.js:254:16) at View.exports.renderFile [as engine] (E:\Submit\Fresh\nodeapp\node_modules\ejs\lib\ejs.js:485:10) at View.render (E:\Submit\Fresh\nodeapp\node_modules\express\lib\view.js:135:8) at tryRender (E:\Submit\Fresh\nodeapp\node_modules\express\lib\application.js:640:10) at Function.render (E:\Submit\Fresh\nodeapp\node_modules\express\lib\application.js:592:3) at ServerResponse.render (E:\Submit\Fresh\nodeapp\node_modules\express\lib\response.js:1008:7) ``` My adm.ejs file is : ```html <%- include('../views/header') %> <div class="container"> <div class="row"> <div class="col-md-12"> <hr> <button type="button" class="btn btn-warning" id="table_view_btn"> Voters / Candidates</button> <button type="button" class="btn btn-danger float-right" onclick="javascript:window.location = '/admin/logout';"> Logout</button> <hr> <div id="voter_table"> <table class="table table-hover table-bordered table-striped"> <h4>Voters</h4> <small>Click on the row item to verify the identity of Voter.</small> <thead> <tr> <th scope="col">#</th> <th scope="col">Name</th> <th scope="col">Aadhaar</th> <th scope="col">Constituency</th> <th scope="col">Voted?</th> <th scope="col">Verified?</th> </tr> </thead> <tbody> <!--<% for(var i=0 ; i < voters.length; i++) { %> --> <tr onclick="window.location='/admin/verifyvoter/';" style="cursor: pointer;"> <th scope="row"> 1 </th> <td> Janit </td> <td> ABC123 </td> <td> COR </td> <td> True </td> <td> True </td> </tr> </tbody> </table> </div> <div id="candidate_table" style="display:none;"> <!-- <div> <h3>Add Candidate</h3> <form method="post" action="/addcandidate" class="form-inline"> <div class="form-group"> <input type="text" class="form-control" id="cand_name" name="cand_name" placeholder="Enter Name"> </div> <div class="form-group"> <select class="custom-select form-control" id="cand_constituency" name="cand_constituency"> <option selected>Constituency</option> <option value="Jabalpur">Jabalpur</option> <option value="Delhi">Delhi</option> </select> </div> <div class="form-group"> <button type="submit" class="btn btn-primary form-control">Add Candidate</button> </div> </form> </div> <hr> --> <table class="table table-hover table-bordered table-striped"> <h4>Candidates</h4> <thead> <tr> <th scope="col">#</th> <th scope="col">Name</th> <th scope="col">Constituency</th> </tr> </thead> <tbody> <!--<% for(var i=0 ; i < candidates.length; i++) { %>--> <tr> <th scope="row"> 2 </th> <td> Souvik </td> <td> Jabalpur </td> </tr> </tbody> </table> </div> </div> </div> </div> </body> </html> ``` I tried searching on the internet regarding this error but everyone showed that there is a problem in the include syntax which is correct for me. Also my router file for this page has nothing else other than a get request which renders this page to the client. Where's the problem then ? Thanks
2021/04/24
[ "https://Stackoverflow.com/questions/67243475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11642391/" ]
That's really simple. The answer is: it's the padding. as you might know by now, padding is some pixels that get added to an element after its normal dimensions and before the border. For example: [![padding and no padding example](https://i.stack.imgur.com/bPqYw.png)](https://i.stack.imgur.com/bPqYw.png) So when you set width to 100% the padding overflows your page. You need to set your width to `100% - (padding * 2)`. Padding is \*2 because there is one in the left and one in the right. This can be acheived with the `calc()` function of CSS. ``` .yournavbar{ /*Style here*/ padding: 8px; /*Set this to anything*/ width: calc(100% - calc(8px * 2)); /*You have to set 8 px to your padding*/ } ``` Example image: [![Width 100% and minus padding example](https://i.stack.imgur.com/vACin.png)](https://i.stack.imgur.com/vACin.png) Did this solve your error? Do you want more information (for margin and border)? Comment me.
Its looks like your padding is pushing your content way after the 100% size. Try using `box-sizing: border-box;` and check out this documentation: <https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing>