INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Compressing by counting repetitive elements (Haskell)
I'm looking for a straight-forward combination of standard higher-order functions to compress a list by counting repetitive elements. For example the result for
`"abbccccb"`
would be :
[(1, 'a'), (2, 'b'), (4, 'c'), (1, 'b')]
another example, the result for
(sort "abrakadabra")
would be:
[(5, 'a'), (2, 'b'), (1, 'd'), (1, 'k'), (2, 'r')] | I wrote a code that only makes use of elementary functions.
f :: Eq a => [a] -> [(Int, a)]
f [] = []
f (x:xs) = (1 + length (takeWhile (==x) xs), x) : f (dropWhile (==x) xs)
I hope this will help!. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "haskell, compression, run length encoding"
} |
Checking for an object, based on a string, using Twig
Is there a way—using Twig—to check if a variable is set based on a string of the same name?
In this example below, `editLink.object` is a string with the value of "entryAlias". I want to check to see if a variable, `entryAlias`, has been set and to see if it's an entry.
{% if "#{editLink.object}" is same as(editLink.object) %}
it workes
{% else %}
not so much
{% endif %}
I've looked into `same as` and `is`, but I think the problem I'm having is converting the string to an object. Also, I'm pretty sure this can just be done using PHP, but I'd like to see if it can be done within Craft's Twig so this can be cached as part of a template. | I don't think `same as` is what you're looking for in this case. Try the Twig `attribute` function instead...
If you're dealing with the global scope, it would be something like this:
{{ attribute(_context, 'myVariable') is defined ? 'Variable exists' : 'Variable does not exist' }}
You can always use `_context` to reference your current scope.
If you're testing to see if an object/array **contains** a property, it's practically identical:
{{ attribute(myObject, 'myProperty') is defined ? 'Property exists' : 'Property does not exist' }}
Building off of that...
* `attribute(x, y) is defined` will return a boolean, whether or not it exists.
* `{% set value = attribute(x, y) %}` will return the value (assuming it exists). | stackexchange-craftcms | {
"answer_score": 2,
"question_score": 2,
"tags": "templating, entry"
} |
Restrict Remote Desktop access to specific users to specific servers in a domain environment?
I have a domain controller and I want to allow certain user accounts Remote Desktop access to certain servers in the same domain.
There are many servers that can be accessed via the Remote Desktop Protocol, but I'd like to restrict these users to connecting only to the servers I allow, not all of them.
For example, I have user "Billy" and I want him to be able to RDP to servers "1" and "2" but not to server "3".
Please explain a good approach to this problem. | > **Restricted remote-desktop connection in domain enviroment for domain-user**
## **Solution**
> To deny a user or a group logon via RDP, explicitly set the " ** _Deny logon through Remote Desktop Services_** " privilege.
>
> To do this access a group policy editor (either local to the server or from a OU) and set this privilege:
>
> 1. **Start** | **Run** | **Gpedit.msc** if editing the local policy or chose the appropriate policy and edit it.
>
> 2. **Computer Configuration** | **Windows Settings** | **Security Settings** | **Local Policies** | **User Rights Assignment**.
>
> 3. Find and double click " **Deny logon through Remote Desktop Services** "
>
> 4. Add the user and / or the group that you would like to dny access.
>
> 5. Click **Ok**.
>
> 6. Either run **gpupdate /force /target:computer** or wait for the next policy refresh for this setting to take effect.
>
>
Source | stackexchange-superuser | {
"answer_score": 11,
"question_score": 12,
"tags": "windows, remote desktop, domain"
} |
Is it possible to install zoo-project in Ubuntu 18.04?
I want to install zoo-project in Ubuntu 18.04 (bionic), but it seems there aren't any programs to do that, for example I have a problem with zoo-kernel install because there is not "ibmozjs185-dev" for bionic. Which version of Ubuntu (14, 16 or 18) is suitable for installing zoo-project? | nickan
You could use the ppa from the OSGeoLive project. They have a libmozjs and zoo-project for 18.04.
PPA is at <
Their github formula is at < | stackexchange-gis | {
"answer_score": 2,
"question_score": 1,
"tags": "installation, ubuntu, zoo project"
} |
Is a clearance needed to depart a helipad in class B airspace?
I have noticed statements like the following on sectionals:
. That means, engineers at google modified linux code to run on android phones or tablets. I would like to become those engineers someday. Where should I start? Should I start looking at embedded linux? | Actually google did more writing an app platform / virtual machine system to run on top of linux than they did modifying linux. They basically just used it as a base to build off of, they hardly had to touch it.
As for your question, just start doing things. Get yourself some linux distros, install them on your computers or in VM's, learn your way around them, then start poking at custom platforms like embeded once you already know the ropes. Find some devices to hack, code up some projects of your own, then find some open source projects to lend a hand with. Along the way you'll figure out how to answer your own question. | stackexchange-unix | {
"answer_score": 5,
"question_score": 2,
"tags": "linux, embedded, android"
} |
Neo4j/Cypher matching first n nodes in the traversal branch
I have graph: `(:Sector)<-[:BELONGS_TO]-(:Company)-[:PRODUCE]->(:Product)`.
I'm looking for the query below.
Start with `(:Sector)`. Then match first 50 companies in that sector and for each company match first 10 products.
First limit is simple. But what about limiting products.
Is it possible with cypher?
**UPDATE**
As @cybersam suggested below query will return valid results
MATCH (s:Sector)<-[:BELONGS_TO]-(c:Company)
WITH c
LIMIT 50
MATCH (c)-[:PRODUCE]->(p:Product)
WITH c, (COLLECT(p))[0..10] AS products
RETURN c, products
However this solution doesn't scale as it still traverses all products per company. Slice applied after each company products collected. As number of products grows query performance will degrade. | Each returned row of this query will contain: a sector, one of its companies (at most 50 per sector), and a collection of up to 10 products for that company:
MATCH (s:Sector)<-[:BELONGS_TO]-(c:Company)
WITH s, (COLLECT(c))[0..50] AS companies
UNWIND companies AS company
MATCH (company)-[:PRODUCE]->(p:Product)
WITH s, company, (COLLECT(p))[0..10] AS products; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "neo4j, cypher, graph databases, nosql"
} |
Como firmar un .pkg con un certificado de apple?
He creado un instalador `.pkg` con la herramienta Packages, pero al distribuirlo en las demas mac no deja instalarlo porque solo permite appstore y desarrolladores identificados, ya tengo mi certificado, mas no se como firmarlo, como puedo hacerlo? | Desde la terminal con la herramienta de linea de comandos `productsign` de Apple que viene con `XCODE`, puedes usarlo de la siguiente manera:
`productsign --sign com.tu.id.cert tuRutaAl.pkg tuProductoFinal.pgk`
Puedes ver tambien la documentacion de productsign de Apple Developer aqui | stackexchange-es_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "macos, pkg"
} |
Problems changing incoming string to integer
I have a rest api that that is getting a string sent to it. The problem is that I need to use this string (which will always be a number) for an id, which needs to be an integer. I am trying to accomplish this by turning the string into an integer when it is received. This is what I have been trying to do, but I get the error message listed bellow when I try:
def create
respond_with @classroom = Classroom.create(classroom_params)
if @classroom.save
#do stuff
else
#do other stuff
end
end
def classroom_params
params.require(:classroom).permit(:period.to_i, :teacher.to_i, :subject.to_i)
end
Here is the error:
NoMethodError (undefined method `to_i' for :period:Symbol):
app/controllers/api/v1/classroom_controller.rb:42:in `classroom_params'
app/controllers/api/v1/classroom_controller.rb:24:in `create' | Try this. `permit` method requires a list of symbols to allow. You can only do `classroom_params.map(&:to_i)` since you want all the parameters as integer. If there is anything in `classroom_params` that you want as string, you will have to convert the ones that you want as integers explicitly.
def create
attributes = classroom_params
@classroom = Classroom.create(:teacher_id => attributes[:teacher].to_i,
:student_id => attributes[:student].to_i,
:subject_id => attributes[:subject].to_i)
respond_with
if @classroom.save
#do stuff
else
#do other stuff
end
end
def classroom_params
params.require(:classroom).permit(:period, :teacher, :subject)
end | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "ruby on rails, api, rest, integer"
} |
Random() заполнение не с нуля java
Собственно кто знает как это сделать? Думалось сделать Random(20) * 20; но это бешеное число, так что мне нужен другой выход. | Не понятно, что конкретно вам надо, но видимо как всегда одно и то же. И тут, и в гугле миллион один ответ по теме, и всё равно его упорно задают
Random rnd = new Random(System.currentTimeMillis());
int number = rnd.nextInt(to - from) + from;
позволяет получать числа в интервале [from; to) | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "java, случайные числа"
} |
Android Project imported in android studio giving exception
I imported an eclipse project in android studio. On running the app, its giving the below error. As suggested in some links, I run the command 'gradlew.bat clear' and after that restarted my android studio, but it didn't worked.
Please help me out
Error:Execution failed for task ':app:dexDebug'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_45\bin\java.exe'' finished with non-zero exit value 2 | Look if you have duplicates in gradle settings like this:
compile 'com.google.android.gms:play-services:+'
compile files('libs/google-play-services.jar')
that could also cause this issue. Remove one of lines if you have this. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "android, eclipse, android studio"
} |
if grep value greater than 1000 then
I want to grep "priority=" in a file where the value of "priority=" is greater than 1000.
I tried something like this:
if grep -q "priority=[ >1000 ]" file; then
echo "[!] Unnatural priority"
fi
e.g. `<intent-filter android:priority="2147483647">` | You could use this Perl one-liner:
perl -lne 'print "[!] Unnatural priority" if /priority="(\d+)"/ && $1 > 1000'
Capture the digits in priority="X" and print the warning if the value is greater than 1000.
You can also do this in native bash if you want:
while read -r line; do
if [[ $line =~ priority=\"([[:digit:]]+)\" ]] && (( BASH_REMATCH[1] > 1000 )); then
echo "[!] Unnatural priority"
fi
done < file | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "bash, shell"
} |
Get the class of all form elements using jQuery for form validation
I am working on form validation, and the submit button is disabled by default. If all of the inputs have the class 'valid' I want to enable the submit button.
I have tried this code but it does not work.
$('input').each(function() {
$(this).on('input', function() {
if($(this).hasClass('valid') {
// All the classes are valid.
alert('Form is valid.');
}
});
});
Also, if there are multiple forms on the page, how can I assure that the jQuery is only looking inside that form for the valid class. One form with all valid classes should not enable the submit buttons on all forms.
Here is a JSFiddle of the problem. | EDIT : I updated your jsfiddle, and added checks on every `keyup` event on your fields. The function ignores the submit button of course.
* * *
Old answer :
you can try this code :
function checkForm() {
var valid = true;
$('input','#myForm').each(function() {
if(!$(this).hasClass('valid') {
valid = false;
}
});
return valid;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery, html, forms, validation"
} |
doxilion document converter alternative
> **Possible Duplicate:**
> Converting .doc files to .pdf
Do you know of any alternative to doxilion document converter. because when I try to convert .doc files into .pdf. The images is removed and the output .pdf file will only contain text.
Please not the online converter. Because I have slow internet. | A couple of free alternatives, which set themselves up as printers, rather than converters are:
* PDFCreator <
* PDF995 <
I have used both myself, and found them very good. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 0,
"tags": "pdf, conversion"
} |
Why does my regular expression work in PHP but not JavaScript?
I have a regex created by myself that I am currently running in PHP. Although when I merge it over to JavaScript, it refuses to work. I have also tried it in Python and it works perfectly fine.
Regex:
@[[]]()[)]
Testing in PHP, and working
Testing in JavaScript, and not working | JavaScript doesn't automatically escape your `]`.
This will help you get a visual idea:
## PCRE:
!PCRE
## JS:
!JS
## Python:
!Python
So to fix this, you need to escape the brackets
@[[\]]()[)]
// ^ ^
The best way to write this regex is to minimize the use of character classes:
@\[(.[^\]]+)\]()\)
That's why it's good practice to escape this stuff instead of relying on quirks of the flavor.
I generated these images through regex101. | stackexchange-stackoverflow | {
"answer_score": 30,
"question_score": 14,
"tags": "javascript, regex"
} |
:hover not working
:hover is not working when applied to my styles:
<
<nav>
<div class="container">
<div class="row-fluid center">
<div id="navcontainerimg" class="span12 center">
<img src="img/hs-header.png"/>
</div>
<div id="navcontainernav" class="span12 center">
<span class="topleft">Our Story</span>
<span class="topright">Awesome Support!</span>
<span class="bottomleft">Read the Blog!</span>
<span class="bottomright">Join Now</span>
</div>
</div>
</div>
The classes can be styled without the :hover, but when added it does nothing. If I click the :hover style display in chrome it will show it there, but not functional. | This is because you've set a negative `z-index` for the container so Chrome essentially won't recognise the hover events.
Change it to:
#navcontainernav
{
width: 720px;
margin-left: 40px;
height: 170px;
top: -233px;
border-radius: 8px;
position: relative;
z-index: 1;
}
Or any other positive value. | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 3,
"tags": "html, css, styles, hover"
} |
Responsive JavaScript table to load 20k records in 2 or 3 seconds
I am looking for a responsive JavaScript table which loads and handles atleast 20k records within 2 or 3 seconds and have many options:
* CSV
* Copy to clipboard
* Export Excel, PDF, text, PNG, Word, JSON
* Visible columns
It must be open source.
Here is the ones I have found:
* Swimlane \- It's not active as of now. No updates for a long time.
* Angular UI Grid \- Uses ng:repeat which slows down the rendering.
* Slick Grid \- It's not active as of now. No updates for a long time.
* Datatables | Datatables should able support large record, even server side. If you need help to transfer data over the wire faster, you might need streaming API, or some ajax method like comet.
jqGrid or other jQuery library should also do fine
If the loading over the wire is what you intended to ask, maybe change the title or ask another question.
Loading 20,000 should be the extremely maximum that should implement. I guess around 5k to 10k data loading in one time, could work for some task, and loading another batch while user browsing half of them. Test your scenario on bottom-line browser, or even mobile browser for the maximum row your want to achieve | stackexchange-softwarerecs | {
"answer_score": 0,
"question_score": 5,
"tags": "open source, javascript, html, table, responsive design"
} |
using postgres server-side cursor for caching
To speed page generation for pages based on large postgres collections, we cache query results in memcache. However, for immutable collections that are very large, or that are rarely accessed, I'm wondering if saving server side cursors in postgres would be a viable alternate caching strategy.
The idea is that after having served a page in the middle of a collection "next" and "prev" links are much more likely to be used than a random query somewhere else in the collection. Could I have a cursor "WITH HOLD" in the neighborhood to avoid the (seemingly unavoidable) large startup costs of the query?
I wonder about resource consumption on the server. If the collection is immutable, saving the cursor shouldn't need very many resources, but I wonder how optimized postgres is in this respect. Any links to further documentation would be appreciated. | You're going to run into a lot of issues.
* You 'd have to ensure the same user gets the same sql connection
* You have to create a cleanup strategy
* The cursors will be holding up vacuum operations.
* You have to convince the connection pool to not clear the cursors
* Probably other issues I have not mentioned.
In short: don't do it. How about precalculating the next/previous page in background, and storing it in memcached? | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 8,
"tags": "postgresql"
} |
R - Read data from HTML table
I'm trying to execute an example from book "Practical Data Science Cookbook" the code as following :
year <- 2013
#Acquire offense data
url <- paste(" group=Offense&cat=Total&conference=NFL&year=season_",
year,"&sort=530&old_category=Total&old_group=Offense")
offense <- readHTMLTable(url, encoding = "UTF-8", colClasses="character")[[7]]
and getting error :
Error in UseMethod("xmlNamespaceDefinitions") :
no applicable method for 'xmlNamespaceDefinitions' applied to an object of class "NULL"
Please help | To solve the problem need to configure http proxy . On Windows desktop edit R-Studio shortcut , add after R-Studio name proxy definitions
http_proxy=
source: Proxy settings for R | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "r, web scraping"
} |
fatal error in stack
I use codeblocks to compile my code in C language.but I faced fatal error. my code is:
#include<stdio.h>
#include<stack.h>
the fatal erroe is:
stack.h:No such a file or directory
What is my problem? | #include <filename.h>
is for standard/system headers that come with the language/compiler/operating system, for example:
#include <stdio.h>
includes a well-defined header file that is part of the C standard library for IO routines.
The C standard does _not_ define a `stack.h` header file, so the file you are trying to include must be from another source.
If there is a file called `stack.h` in your project, then you need to use
#include "stack.h"
Beyond these two cases, we can't help you - `stack.h` sounds very much specific to your project/setup. If you know what directory it is in, you can try adding that directory as an include path to your IDE. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c, stack, codeblocks"
} |
how to get the nearest Int floored from a sqrt of an Int?
I need the largest int at or below the sqrt of n.
I am getting _Cannot use mutating member on immutable value: 'sqrt' returns immutable value_
func isPrime (n:Int) -> Bool {
if n < 2 { return false }
generatePrimes(to: sqrt(Double(n)).round(.towardZero))
The same problem with `.squareRoot`
How can I generate to:Int here? | If you want to call generatePrimes with a Double
generatePrimes(to: floor(sqrt(Double(n)))
or if you want to call it with an Int
generatePrimes(to: Int(floor(sqrt(Double(n)))) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "swift"
} |
Linq method equivalent for "Into"
I do have an LINQ query:
var groupedResult = from address in Address.GetAddresses()
group new { City = address.City, HasManyInhabitants = address.Inhabitants > 20 }
by address.City into addressWithInfo
select addressWithInfo;
That works fine. But I'm looking for the method base approach for this query. At the moment I use
var groupedResult = Address.GetAddresses()
.Select(a => new { City = a.City, HasManyInhabitants = a.Inhabitants > 20 })
.GroupBy(a => a.City)
.Select(a => a);
It works, but it doesn't seem to be right because the decompiled code (with ILSpy) looks not similar.
Regards, Torsten | You just want this:
var groupedResult =
Address
.GetAddresses()
.GroupBy(
address => address.City,
address => new
{
City = address.City,
HasManyInhabitants = address.Inhabitants > 20
}); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, linq"
} |
Firebase Cors issue for remote js files
So basically there is a host app which is gets remote microfrontend files from another firebase url.
So remote app is hosted on firebase such as `www.firebas-ipsum.web.app`.
When host application tries to get file `www.firebas-ipsum.web.app/remoteEntry.js` as expected we received CORS error.
How can we enable CORS for fetching any files? I tried solution in CORS issue but it is for requests, not for files. | Found solution by adding headers to `firebase.json.`
{
"hosting": {
"public": "dist",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
],
"headers": [
{
"source": "**/**",
"headers": [
{
"key": "Access-Control-Allow-Origin",
"value": "*"
}
]
}
]
}
}
For more information Offical Docs | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "firebase hosting"
} |
ansible loop over list with multiple items
I have a definition of an array in an ansible playbook, which looks like:
x_php_versions:
- php71
- php72
- php73
And I would like to make a loop for all of them, so my task looks like this:
- name: Install PHP packages
yum:
name: '{{ item }}'
state: 'present'
loop:
- '{{ x_php_versions }}'
- '{{ x_php_versions }}-bcmath'
- '{{ x_php_versions }}-bz2'
This should install php71 php71-bcmath php71-bz2 php72 php72-bcmath ... and so on. But this kind of loop does not work. Am I made a typo or my loop is completly wrong for this scenario? If I try the loop without '' then it also gave me an error. | you can use the filter `product` to combine all possibilities
- name: Install PHP packages
yum:
name: '{{ item.0 }}{{ item.1 }}'
state: 'present'
loop: "{{ x_php_versions | product(['', '-bcmath', '-bz2']) | list }}" | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "ansible, yaml"
} |
Disadvantages of using TLB (and tlbimp.exe) with C#
We're integrating a communications company's software into our own for doing things like answering calls, transfering calls, matching numbers with clients etc.
They have given us the API documentation, which includes a TLB file. We've used the tlbimp tool to create an assembly which we now want to use in our implementation.
Some of the classes created by tlbimp have been given internal constructors, rendering them uninstantiable. I think it should be ok in this instance as another class should return an instance of these classes.
This made me think though: are there any other pitfalls I should be aware of when using tlbimp.exe, and TLB's as a whole? Would it be better to create the DllImport/ComImport/PInvoke code by hand? | In general if you have a TLB I would at least start my work by consuming the assembly produced by tlbimp.
The tool itself is widely used and produces correct code based on the definitions provided in the TLB. I have seen some circumstances where the resulting code was incorrect but it almost always came back to either a very complex marshalling situation with arrays or a place where the TLB author had simply added the wrong COM annotations.
If you do find any issues down the road then you should consider beginning to hand code the fixes. But I certainly wouldn't start that way. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, pinvoke, com interop, tlbimp, typelib"
} |
Getting all column values that match even though value is slighty different
I have 2 tables, table A and Table B each with 4 columns. Table A has a column `model` value = 'civic' and table B has column `modelname` value of 'civic sedan'.
I want to select all the rows in table A where table A.model = B.modelname even though table B.modelname is a little different but still contains 'civic' in this example.
select A.model as modelname, B.jpgname
from A, B
where A.year = B.year
and A.year = '2016'
and A.make = B.make
and A.make = 'honda'
and A.model LIKE B.modelname
group by model
That code gets all the other honda models except for example, the 'civic sedan' in table B.
I am probably missing something really simple. Thanks for any help! | Use `concat` , like this:
select A.model as modelname, B.jpgname
from A, B
where A.year = B.year
and A.year = '2016'
and A.make = B.make
and A.make = 'honda'
and B.modelname LIKE concat('%',A.model,'%')
group by model | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": 0,
"tags": "mysql"
} |
Does there exist a $\Bbb{Q}$-algebra homorphism from $\Bbb{R}\to\Bbb{R}$ which is not onto.
We know that $\Bbb{Q}\hookrightarrow \Bbb{R}$, by a $\Bbb{Q}$-algebra homomorphism from $\Bbb{R}\to\Bbb{R}$ we mean a ring homomorphism from $\Bbb{R}\to\Bbb{R}$ which is the identity on $\Bbb{Q}$.
I first thought in this way- We know that $[\Bbb{R}:\Bbb{Q}]=\infty$, and the set $\\{1,\sqrt{2}\\}$ can be extended to a basis $B$ of $\Bbb{R}$ over $\Bbb{Q}$. Then I define $f:\Bbb{R}\to\Bbb{R}$ such that $f(1)=\sqrt{2}$, $f(\sqrt{2})=1$ and $f(x)=x\ \forall x\in B\setminus \\{1,\sqrt{2}\\}$. Now extend $f$ linearly. But this way $f$ will be a group homomorphism but may not preserve the product (i.e. may not be a ring homomorphism). Even this $f$ is onto as well.
Can anyone suggest a way out? Thanks for your help in advance. | No. In fact, the only $\mathbb Q$-algebra homomorphism $\mathbb R \to \mathbb R$ is the identity map. Proof: Suppose $f$ is such a homomorphism. If $x > 0$, then $x = y^2$ for some $y \neq 0$, so $f(x) = f(y^2) = f(y)^2 > 0$. Therefore $f$ sends all positives to positives. It follows that $f$ preserves the ordering on $\mathbb R$. But $f$ must act as the identity on all rationals, and this forces it to act as the identity everywhere. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "abstract algebra, ring theory"
} |
How to replace &ndash with Objective-C
I'm getting JSON back from an API, and when the article text returns, alot of times there will be a dash. But the dash comes thru as `&ndash` instead how the actual `-`...
How do I convert the `&ndash` to just the actual `-`?
Thanks for the help! | NSString *myString = @"Here is &ndash some text";
myString = [myString stringByReplacingOccurrencesOfString:@"&ndash" withString:@"-"]; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 5,
"tags": "objective c, json, api"
} |
About sequences in the unit bal converging to zero
Let $c_0$ be all sequences in $\mathbb{C}$ that converge to zero. Prove that for every $x \in B_{c_0} := \\{x \in c_0 : ||x||_\infty = 1\\}$, there exist $x_1, x_2 \in B_{c_0},x = \frac{1}{2}(x_1 + x_2)$, while $x_1 \neq x_2$.
I have already: for every $x_1, x_2$ as given we have $||\frac{1}{2}(x_1 + x_2)||_\infty = 1$ and $\frac{1}{2}(x_1 + x_2)$ converges to zero, because $c_0$ is closed in $\ell^\infty$. I think that for every $x$ there is a $y$ with $y = e^{i\pi a}x$, a rotation of the sequence. Is that true? If so I think I can construct a sequence $z$ with for all $i\geq1$: $|z_i| = |x_i|$ and Arg$(z_i)$ is the angle of rotation between $x$ and $y$. Then $\frac{1}{2}(y + z) = x$. Is that right? | _Hint :_ since $x$ goes to zero, one of its terms has absolute value stricly less than $1$ and is therefore the mean average of two different numbers with absolute value less than or equal to 1. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "sequences and series, functional analysis"
} |
Extract rows based on last value of row R
I'm very new to R, so just bear with me.
I have a dataframe df:
ID,NUM,REV,HRY
1221838,2556200,17396.979,L
9677461,5562000,0.000,L
9636801,5562215,0.000,L
9713221,5562222,25739.479,L
i want to extract those rows, whose NUM value ends with 0. Similarly for 1,2,..9.
In this case output for those records whose NUM value ends with 0 will be `df_out`,
ID,NUM,REV,HRY
1221838,2556200,17396.979,L
9677461,5562000,0.000,L
Is there any way to do this in R? Thanks in advance. | We can use `substring` to get the last digit to be used as logical condition in `subset`
subset(df1, substring(NUM, nchar(NUM))==0)
# ID NUM REV HRY
#1 1221838 2556200 17396.98 L
#2 9677461 5562000 0.00 L
* * *
Based on @lmo's comments and the update in the OP's post, we can create multiple datasets in a `list` with `split`
lst <- split(df1, substring(df1$NUM, nchar(df1$NUM))) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "r, dataframe"
} |
.replace() in a DataFrame does not replace
I am trying to remove `;` from a column in a DataFrame, but when I use the `.replace(';', ' ')` method it does not replace the semicolumn, here is how i am doing it:
for i in excel_file['dateTime']:
i.replace(';', ' ')
This is how my `'dateTime'` column looks like:
11-06-18;
18-06-18;
18-09-18;
14-06-18;
20-06-18;
13-06-18;
21-06-18;
19-06-18;
19-06-18;
20-06-18;
11-06-18;
22-06-18; | Don't use `for` loops. Instead:
excel_file['dateTime'] = excel_file['dateTime'].str.replace(';', ' ')
Implicit in this answer is the fact that `str.replace()` returns a new string, rather than modifying the original in-place. That was the functional defect in your original code. But doing it without a `for` loop will be many times faster.
Ref: < | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": -1,
"tags": "python, pandas"
} |
How to use SPLIT and CROSS APPLY functions in BigQuery
I'm struggling with the split and cross apply functions in BigQuery. However it didn't work. If anyone can help that will help me a lot in my project. Thanks! I want the output looks like this:
!The output I want | Try UNNEST:
select deptid, deptname, value
from mytable, unnest(split(deptlocation)) as value | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "split, google bigquery, cross apply"
} |
get object of a list via get in R
I have list which has some objects and I want to get the object in a loop. I use now this code but I don't know why it didn't answer!!
test1 <- list(a=c(1,2,3,4),b=rnorm(100))
test1$a
[1] 1 2 3 4
but when I want to load it via get in a loop I could't. for example
get("test1$a")
Error in get("test1$a") : object 'test1$a' not found
So, How can I load this objects of a list via a command like this? | You have to use
get("test1")$a
since the object's name is `test1`, not `test1$a`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "r"
} |
What's the right way to check if collection.find success in Meteor?
The Meteor document said 'find returns a cursor', and can use 'fetch' to return all matching documents, but I didn't find a complete reference of this 'cursor' object.
I want to use this 'cursor' object to check if find sucessfully got some result or got nothing.
Following is what I am doing now:
if (Tags.find({name: tag["tag"]}).fetch().length === 0) {
// Not found, add default documents
}
Not sure if this is right way(best practice) to do this? | The idiom is to use .findOne:
if (!Tags.findOne(...)) {
// nothing found, add default documents
}
This is more efficient than `fetch()` because it only queries the database for one document.
You can also use `<cursor>.count`, but beware that in Mongo, count operations are expensive. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "meteor"
} |
How to calculate the number of trades in the market?
Is there any way to calculate the **number of trades** in an options contract, if the following data is available-
1. Volume
2. Open Interest
3. Change in open interest
4. Underlying Price
5. Implied Volatility
6. Total Buy orders
7. Total Sell orders
8. Last Traded price
9. Average Price
Please provide the formula if it is possible. | No, it is not possible, because:
* There is no distinction in volume and open interest between the effect of many small trades and the effect of a few large trades for the same total number of contracts.
* There is not a one-to-one correspondence between orders and trades. | stackexchange-money | {
"answer_score": 1,
"question_score": 0,
"tags": "options, trading"
} |
Block Scoping in python - is it similar to javascript hoisting when inside a function?
I am currently trying to understand this piece of code in python
def foo(a):
if a==12:
var = "Same"
else:
var = "different"
I read and understand the fact that python does not support block based scoping. So everything created inside a function (whether inside a loop or conditional statements) is openly available to other members of a function.I also read the scoping rules here . At this point would it be same to assume that these inner scoped variables are hoisted inside a functions just like they are hoisted in javascript ? | You got it. Any name assigned inside a function that isn't explicitly declared with `global` (with Py3 adding `nonlocal` to indicate it's not in local scope, but to look in wrapping scopes rather than jumping straight to global scope) is a local variable from the beginning of the function (it has space reserved in an array of locals), but reading it prior to assignment raises `UnboundLocalError`. | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 15,
"tags": "javascript, python"
} |
Retrieving type of Opencv Mat_<T> at compile time
I need to access the element type T of an opencv matrix Mat_<\T> at compile time; Is there any way to do it? I am trying to achieve the following:
template <typename T>
void foo(const T& mat) {
// T::type* ptr = (T::type*)mat.data;
}
foo(Mat_<float>::ones(5,5));
The following declaration is not an option:
template <typename T>
void foo(const Mat_<T>& mat); | It looks like there is a typedef called value_type that does what you want.
template <typename T>
void foo(const T& mat) {
T::value_type* ptr = ...;
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, opencv"
} |
C++ Decompressing a file, then compressing the decompressed data does not give the same file as a result
I'm using ZLib along with header files from < to handle gzip files.
I have been trying for days now. I have a file say "abc," and as I decompress it, I compress it back and save the compressed result in another file "xyz." Now, theoretically, data of "abc" should be equal to "xyz," but that's not the case. As I compare, both the files are different. I'm using fstream to read/write files with binary flags. I've tried different compression levels as well, but failed. I also checked the decompressed data and it stands accurate. My only trouble is compressing it back, which yields different results from original. | There is no reason to expect nor any need to be able to reconstruct the same compressed data. What is guaranteed for lossless compression is that x -> compress -> decompress -> y will result in y being exactly the same as x. There is no guarantee for p -> decompress -> compress -> q that q is the same as p, or similar to p, or even the same length as p.
The difference can vary due to different compression software, a different version of the same compression software, or different compression settings for the same version.
The zlib and gzip compressors, while written by the same person, will generally produce different compressed data regardless of the settings you select. They have different approaches internally for when they decide to emit a deflate block. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "c++, compression, zlib"
} |
Hibernate query with subquery in WHERE clause and multiple joins
I have been trying to get Hibernate to generate me a query with a subquery in its where clause. I've used this answer as a base to help me going, but this question mentioned only one table.
However, this is what I would need (in SQL):
SELECT [...]
FROM a
LEFT OUTER JOIN b on a.idb = b.idb
LEFT OUTER JOIN c on b.idc = c.idc
[...]
LEFT OUTER JOIN k out on j.idk = k.idk
WHERE k.date = (SELECT max(date) from k in where in.idk = out.idk) OR k.date is null
As I am not very used to using Hibernate, I'm having trouble specifying these inner joins while navigating in the inner constraints. I was able to re-create the initial criteria as in the linked answer, but I can't seem to join the criteria and the rootCriteria. | If the entities are properly joined with `@ManyToOne` annotations, simply joining the criteria to the previous table will be enough to propagate the criteria to the whole query.
The following code seems to work properly to add the WHERE clause I'm looking for.
DetachedCriteria kSubquery = DetachedCriteria.forClass(TableJPE.class,"j2");
kSubQuery = kSubQuery.createAlias("k","k2");
kSubQuery.setProjection(Projections.max("k2.date"));
kSubQuery = kSubQuery.add(Restrictions.eqProperty("j.id", "j2.id"));
rootCriteria.add(Restrictions.disjunction()
.add(Subqueries.propertyEq("k.date",kSubQuery))
.add(Restrictions.isNull("k.date"))); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, hibernate, join, subquery, where clause"
} |
gnu parallel: output each job to a different file
I am trying to process so text files with `awk` using the `parallel` command as a shell script, but haven't been able to get it to output each job to a different file
If i try:
seq 10 | parallel awk \''{ if ( $5 > 0.4 ) print $2}'\' file{}.txt > file{}.out
It outputs to the file `file{}.out` instead of `file1.out`, `file2.out`, etc.
The tutorial and man pages also suggest that I could use `--files`, but it just prints to `stdout`:
seq 10 | parallel awk \''{ if ( $5 > 0.4 ) print $2}'\' file{}.txt --files file{}.out | It turns out I needed to quote out the redirect, because it was being processed outside of `parallel`:
seq 10 | parallel awk \''{...}'\' file{}.txt ">" file{}.out | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 12,
"tags": "bash, gnu parallel"
} |
Como remover uma View de um layout xml?
por exemplo... quero que ao inflar um layout com uma determinada classe, ela remova as views desnecessárias e utilize apenas as necessárias... Existe um método para remover views? | Consigo enxergar duas maneiras de fazer isso. A primeira é que você pode esconder a view que deseja através do método `suaView.setVisibility(View.GONE)`. Ela vai continuar lá, mas não estará visível. A segunda é que todo layout (LinearLayout, RelativeLayout e etc) herda de ViewGroup, e essa classe tem o método `[removeView(suaView)][1]`. | stackexchange-pt_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, android, android studio, view"
} |
Shell Scripting: how to use part of the file path as the file name?
I have a group of directories, each containing exactly 1 jpeg image, like so-
/psds/folder1/image.jpg
/psds/someotherfolder/picture.jpg
/psds/yetanotherfolder/thumbnail.jpg
What is the appropriate way to rename the jpegs to the name of their containing folder? What I want is:
/psds/folder1/folder1.jpg
/psds/someotherfolder/someotherfolder.jpg
/psds/yetanotherfolder/yetanotherfolder.jpg | Run the below commands inside `/psds` directory.
for f in ./*; do
if [ -d "$f" ] ; then
cd "$f"
mv *.jpg "$f.jpg"
cd ..
fi
done
If you have 3 folders inside `/psds` directory like below,
/psds/folder1/image1.jpg
/psds/folder2/image2.jpg
/psds/folder3/image3.jpg
After you run the above command, the files would be renamed as,
/psds/folder1/folder1.jpg
/psds/folder2/folder2.jpg
/psds/folder3/folder3.jpg | stackexchange-unix | {
"answer_score": 1,
"question_score": 2,
"tags": "shell script, files, rename, filenames"
} |
Seeing Blank page After refresh in nested routes in React Router
Here is my main router page in `App.js`:
<Provider store={store}>
<Router>
<Switch>
<Route exact path = "/" component= {FormPage}></Route>
<Route path = "/dashboard" component= {Dashboard}></Route>
</Switch>
</Router>
</Provider>
And in Dashboard Page:
<Router>
<Switch>
<Route path = "/register" component= {Registration}></Route>
<Route path = "/home" component= {Home}></Route>
</Switch>
</Router>
After refresh in register or home page, nothing renders. But the route in `App.js` file working fine. | <Router>
<Switch>
<Route path = "/dashboard/register" component= {Registration}>
</Route>
<Route path = "/dashboard/home" component= {Home}></Route>
</Switch>
</Router> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "reactjs, react router"
} |
How can I create a wp plugin with this code
I came across a post - from code tutsplus for a plugin which requires one to create it from the cpanel file directory but I need a plugin instead in zip file. Will all the codes be in the index.php And help for this? You can check the codes here Thanks in advance. | Just create the same files as in the tutorial, but on your computer, then zip them. That's all a plugin zip is. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development"
} |
What is my Atom's architecture doing?
The short answer is that it's a dual core 64 bit processor at least in my case with a 330. But the Atom's architecture has traits of x64 and x86. So, what is it? | The Atom 330 operates as x86-64 thus making it fully backwards compatible with 32 bit code. | stackexchange-superuser | {
"answer_score": 0,
"question_score": 0,
"tags": "intel atom, architecture"
} |
Radio input return incomplete string
I've got radio buttons in MVC Razor like this
<td style="min-width:110px" align="center"><label for="naraName">@listOfNames[i]</label></td>
<td style="min-width:110px" align="center"><input type="radio" name="naraName" value=@listOfNames[i] /></td>
which in HTML look like this:  consist of multiple Web User Controls(.ascx)
I would like to have an error handling machanism in such a way that if there is any exception in one of the user control, asp .net should show some friendly error message on a control. All other control should render as expected.
Is there any way this can be done without putting place holder on each control which you show/hide in case of exception? | You could do something like this.
An abstract base class with an abstract OnLoad() that each UserControl has to implement. You can use this same model for any event that you want to have shared error handling.
public abstract class BaseUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
OnLoad();
}
catch (Exception)
{
//Custom error handling here
}
}
protected abstract void OnLoad();
}
public class MyUserControl: BaseUserControl
{
protected override void OnLoad()
{
//My normal load event handling here
}
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "c#, asp.net, .net, iis"
} |
Understanding 'ccdc' algorithm in Google Earth Engine
I want to know how the 'ccdc' algorithm, which is deployed on GEE, detects changes.
Does the algorithm use the method on the left, the method on the right, or some other method?
 | It's somewhere in between, since it's derived from the V12.30 MATLAB implementation, and you can manually specify the number of observations required to detect a change (it defaults to 6). There is no angle adjustment. | stackexchange-gis | {
"answer_score": 2,
"question_score": 0,
"tags": "google earth engine, time series, change detection"
} |
Polynomial Regression didn't give proper hypothesis
PFB code, here X is the number of levels of positions (i.e. level 1,level 2 ..) and y is the salary range. Polynomial regression isn't giving best fit line, also how can I figure out for X = 20. Kindly suggest :)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
X = [[ 1],[ 2],[ 3],[ 4],[ 5],[ 6],[ 7],[ 8],[ 9],[10]]
y = [45000,50000,60000,80000,110000,150000,200000,300000,500000,1000000]
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 2)
X_poly = poly_reg.fit_transform(X)
linearReg_2 = LinearRegression()
linearReg_2.fit(X_poly,y)
# plot polynomial linear regression
plt.scatter(X,y, color = "red")
plt.plot(X,linearReg_2.predict(X_poly), color = "blue")
plt.show() | You can try increasing the degree to 3 or 4 for a more proper match.
poly_reg = PolynomialFeatures(degree = 3)

`
Something like this:
X_new = [[20]]
# Observe that I used transform() and not fit_transform()
X_new_poly = poly_reg.transform(X_new)
y_new = linearReg_2.predict(X_new_poly) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "machine learning, scikit learn, artificial intelligence, regression"
} |
Multiple Show/Hide with changing text
I have a multiple show/hide divs with changing texts _from **Expand** to **Reduce_**. If there is more than one dropdown, text doesn't changing. There is my **JSFiddle**, you can test it, by delete one section. Any solutions for that? :)
This is my JQuery
$(".section .section-title").click(function(){
$(this).closest(".section").find('.dropdown-content').slideToggle(100);
$(this).find('.expand').toggleClass('expanded');
if ($.trim($(".expand").text()) === 'Expand') {
$(".expand").text('Reduce');
} else {
$(".expand").text('Expand');
}
}); | You must find text with class `.expand` in `this`,which represents the `section` clicked.
Use this:
$(".section .section-title").click(function(){
$(this).closest(".section").find('.dropdown-content').slideToggle(100);
$(this).find('.expand').toggleClass('expanded');
if ($.trim($(this).find(".expand").text()) === 'Expand') {
$(this).find(".expand").text('Reduce');
} else {
$(this).find(".expand").text('Expand');
}
});
Here is jsfiddle | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "javascript, jquery, html, css, events"
} |
how to reuse a svg element and resize
I have a rectangle
`<rect id="greenRect" fill="lightgreen" height="20" width="20"/>`
Now I want to reuse the rect, but make it bigger
`<use href="#greenRect" y="150" height="50" width="50"/>`
The size (height/width) don't seem to get overwritten from the original `<rect>` element.
How would I achieve such a thing? | **Solution 1:** Wrap the rect in a `<symbol>` with a `viewBox` attribute.
<symbol id="greenRect" viewBox="0 0 20 20">
<rect fill="lightgreen" height="20" width="20"/>
</symbol>
<!-- symbols are not rendered, so if you want to see your original,
you have to also use it -->
<use href="#greenRect" height="20" width="20"/>
<use href="#greenRect" y="150" height="50" width="50"/>
**Solution 2:** scale and translate your rectangle
<rect id="greenRect" fill="lightgreen" height="20" width="20"/>
<!-- transformation are applied right-to-left -->
<use href="#greenRect" transform="translate(0 150) scale(2.5)"/> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "svg"
} |
How does the iOS Reachability class work, and why the IP Address 169.254.0.0?
How does the iOS Reachability class work, and what's so special about the IP Address 169.254.0.0?
I'm trying to figure out whether Wi-Fi is on, independent of whether it is connected to an actual Wi-Fi network or not.
I haven't found a satisfactory answer for this question on SO, and even the answers that try to answer this don't work for me. | When you fail to get an IP address from DHCP, it will automatically assign you a random address in the 169.254.x.x range. So if you have an IP address like this, it means you're connected to a network, and set to use DHCP to get an address, but it is unable to obtain an IP address from DHCP.
There doesn't appear to be any way to simply detect if wifi is enabled and not connected to a network, so I think you're out of luck there. The best you can do is detect if you're connected to a wifi network, but often if you're out and about, you won't be connected to a wifi network even though it is enabled. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "ios, networking, network programming, reachability"
} |
Running Octave in macOS Terminal
I installed Octave (6.4.0) using Homebrew. When I type "`octave`" in the Terminal, it shows in the title of Terminal window that it is "`octave-gui`" but no GUI shows up.  is above enclosing parentheses.
\begin{equation*}
\left[\frac{{\left(\vec{A} - \displaystyle\frac{b}{c} \vec{D} \right)}^2}{E^2} \right]^{1/2}
\end{equation*}
}{E^2}
\end{tabular}\right]^{1/2}
\end{equation}
\end{document}
**Addendum:** More simple code is, if instead of `tabular` the environment `array` is used:
\begin{equation}
\left[\begin{array}{@{} c @{}
}
\dfrac{\left(\vec{A} - \dfrac{b}{c}\vec{D}\right)}{E^2}
\end{array}\right]^{1/2}
\end{equation}
Result is the same ase before. | stackexchange-tex | {
"answer_score": 4,
"question_score": 5,
"tags": "equations, parenthesis"
} |
Comparing string with an input string :: python
I am trying to compare an input string but when ever i enter barack as an input, the compiler directly goes to the else condition ignoring the the if condition and giving me the output "Wrong answer"
def main():
First_name = raw_input(" enter the first name of President Obama : ") #input
if First_name == ['b', 'a', 'r','a', 'c', 'k'] :
print "Correct answer"
else :
print "Wrong answer"
Exit_key = input('Press any key to end') | Is there a reason you are doing it like that? Try:
if First_name == "Barack" : | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python, python 2.7"
} |
Replace space with new line
How can I replace spaces with new lines on an input like:
`/path/to/file /path/to/file2 /path/to/file3 /path/to/file4 /path/to/file5` etc...
To obtain the following:
/path/to/file
/path/to/file2
/path/to/file3
/path/to/file4
/path/to/file5
### Note
I'm posting this question to help other users, it was not easy to find a useful answer on UNIX SE until I started to type this question. After that I found the following:
### Related question
How can I find and replace with a new line? | **Use the`tr` command**
echo "/path/to/file /path/to/file2 /path/to/file3 /path/to/file4 /path/to/file5" \
| tr " " "\n"
Found on < | stackexchange-unix | {
"answer_score": 224,
"question_score": 142,
"tags": "text processing, string"
} |
What is the formal/polite way to begin and end an email in Chinese?
In English, formal emails, e.g. emails to a professor, often start with "Hi", "Hello", "Dear" followed by the receiver's name (and title, if applicable). The ending is usually "Best", "Regards", "Sincerely" followed by the writer's name. Does Chinese have similar constructs? Or does it have more/less strict rules? | The traditional Chinese letter is very complex.It has many honorifics that vary greatly for different receivers.
But today,most people's traditional education is insufficient to write these letter.
For email,people tend to write simply and practicably
**Habitual formation**
!enter image description here
example:
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna a...
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna a...
Jacob
2015.04.10
example 2:
| stackexchange-chinese | {
"answer_score": 12,
"question_score": 16,
"tags": "word choice, politeness, formal"
} |
How to handle <a href> inside a button in wordpress
I am using wordpress for this project. How can I handle the `<a>` tag which is getting displayed inside a button?
Here is how I am using it
<button class="red-btn btn-effect reply" type="button">
<?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
</button>
and its output is shown as
<button class="red-btn btn-effect reply">
<a rel="nofollow" class="comment-reply-link" href=" onclick="return addComment.moveForm( "comment-3", "3", "respond", "18" )" aria-label="Reply to umair">Reply</a> </button>
Html5 does not support `<a>` tags inside a button. How to handle this? | That is because a button is not a link.
Remove the button and your output should actually be something like this instead:
<a rel="nofollow" class="red-btn btn-effect reply comment-reply-link" href="
/dynamoLogic/security-vulnerabilities-in-php/?replytocom=3#respond"
onclick="return addComment.moveForm( "comment-3", "3",
"respond", "18" )" aria-label="Reply to
umair">Reply</a>
Add in the neccessary classes for the link, you may need to make adjustments to the CSS for the a element. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "wordpress"
} |
Best way to query a Table in MySql
# Mode Model
Auto A1
Auto B1
Manual A1
Auto A1
Manual A1
Manual A1
Manual B1
Manual B1
Auto A1
I want the results like below.
# Mode Model-A1 Model-B1
Auto 3 1
Manual 3 2
What will be the efficient way/query to get the above results? | There are different ways to get the expected output. You can try like this as well:
SELECT
mm.Mode
, SUM((CASE WHEN mm.model = 'A1' THEN 1 ELSE 0 END)) AS "Model-A1"
, SUM((CASE WHEN mm.model = 'B1' THEN 1 ELSE 0 END)) AS "Model-B1"
FROM mode_model as mm
GROUP BY mm.mode; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "mysql"
} |
Swift send data to viewcontroller in different storyboard
i'm trying to send an Object to a Viewcontroller in a different storyboard.
Todo so i tried this but its always nil:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let link = list[indexPath.row].link
self.object.cat = link
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "SelectContacts")
self.present(controller, animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destVC = segue.destination as! SelectContactsViewController
destVC.object = object
} | You need
let controller = self.storyboard!.instantiateViewController(withIdentifier: "SelectContacts") as! SelectContactsViewController
controller.object = link
self.present(controller, animated: true, completion: nil)
* * *
`prepareForSegue` is triggered when you use `performSegue`
* * *
Every vc contains storyboard property which references main storyboard so no need for
let storyboard = UIStoryboard(name: "Main", bundle: nil) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "swift, uicollectionview"
} |
Prove the Identity $\cot x - \frac{1}{2} \sec x \csc x = \cot 2x$
Prove the identity $$\cot x - \frac{1}{2} \sec x \csc x = \cot 2x$$ Thanks in advance. | $cotx - \dfrac{secx\cdot cscx}{2} = \dfrac{cosx}{sinx} - \dfrac{1}{2cosxsinx} = \dfrac{2cos^2x - 1}{2sinxcosx} = \dfrac{cos2x}{sin2x} = cot2x$ | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "algebra precalculus"
} |
Will expanding my Synology Hybrid RAID delete the data on the initial disk?
As the title states, I currently have my Synology NAS with a single 4TB drive in it. I now wish to expand this with another 4TB drive. If I expand the volume (it's currently setup as SHR) will the initial disk be erased? I know it says "existing data will be erased" when you select the new drive, but I'm not sure if it means only on the new drive or both the new and the existing drive. | No the existing data will not be erased when you add a disk to the SHR array. The message is simply saying the new drive being added will be formatted.
Your data and applications will actually remain available _during_ the expansion process; there is no need at all to even stop using the NAS whilst SHR Vertical Expansion is taking place.
That said - before any type of RAID manipulation (of any flavor) you should backup first.
Finally it is probably worth pointing out that if you are using two equally sized disks there is no point at all using SHR over RAID1 - indeed you should use RAID1 as SHR will incur an overhead in both read and write speeds compared with RAID1.
The real advantage of SHR comes when using odd sized disks. | stackexchange-serverfault | {
"answer_score": 4,
"question_score": 2,
"tags": "raid, software raid, network attached storage, synology"
} |
Redirect specific host from HTTPS to HTTP
I need to redirect all https//panel.mysite.com to < (HTTPS to HTTP) without affect any other redirections in my .htaccess. How do i proceed?
Thanks a lot. | Put this code in your `DOCUMENT_ROOT/.htaccess` file:
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^panel\.mysite\.com$ [NC]
RewriteRule ^ [L,NC,R=301] | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "regex, apache, .htaccess, mod rewrite, redirect"
} |
Passing an embed variable in a parameter of a tag
I don't think that the parse order would make this code below work
{exp:channel:entries
entry_id="{embed='common/.get-entry-id-based-on-some-complex-logic'}"
}
Is there a way to make embed tag be parsed first before the `{exp:channel:entries}` is parsed?
If not, what are alternative ways to this(Snippets can't be used if in this case if I am not mistaken)? | Why not do it the other way around, where the template being loaded is what actually contains the complex logic? Then you can embed the rest of the template, passing the `entry_id` via an embed parameter.
Alternately, write a simple plugin which performs your logic and returns the `entry_id`, then put your Channel Entries tag inside of that plugin tag pair (related example here). | stackexchange-expressionengine | {
"answer_score": 3,
"question_score": 0,
"tags": "embeds"
} |
Why is my terminal saying "permission denied" when I try to clone?
Anything I try to clone from github, but my terminal blocks me with the message "Permission denied (publickey). fatal: Could not read from remote repository". What do I need to do to clone to my desktop files? | The comments to your question are likely correct - you are missing a public key.
I suggest navigating to the github www page for the repository that you want to clone, and change from `SSH` to `HTTPS` and use that clone url instead. It should be in the following form:
You can also just try the new URL without the need to navigate the github www UI by using the format described above, rather than the ssh form ( `[email protected]:{username}/{project}.git` ) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "git, github"
} |
Facebook Socialite Error 404: Page not found
I am setting up `Facebooking socialite` on my existing website and encountered an **404 error when I click "Login With Facebook " button**. The error is:
> Sorry, the page you are looking for could not be found.
I don't know whether the error is from the routing or it is from something else.
The designate url for the button is: < | You need to setup routes for socialite to use to connect to Facebook. Please see the official documentation:
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "laravel socialite"
} |
Incrementing Makefile Variable When Executing Rule
My dilemma is the following: I need to create a symbolic link to a different serial port for each of the items in the Makefile variable 'LINKS'. I have the following code.
LINK_PATH = ~/some/path/
LINKS = $(LINK_PATH)/SomeLinkName $(LINK_PATH)/AnotherLinkName $(LINK_PATH)/TheseLinkNamesUnchangeable
COUNT = 0
install: $(LINKS)
#Do other stuff
$(LINKS): $(LINK_PATH)
ln -s /dev/ttyS$(COUNT) $@
$(LINK_PATH):
mkdir -p $@
I know that, as it is now, it will just create a bunch of links pointing to /dev/ttyS0. But I need them to be different, preferably sequential. Any ideas? Thanks. | if all of the serial ports are defined ahead of time, you can enumerate them and store that list in another variable then use that variable as a target dependency:
LINKS=/path/to/bar /path/to/baz /path/to/woz
COUNTS=$(shell v=`echo $(LINKS) | wc -w`; echo `seq 0 $$(expr $$v - 1)`)
install: $(COUNTS)
$(COUNTS):
@echo ln -s /dev/ttyS$@ $(shell v=($(LINKS)); echo $${v[$@]})
then, when run:
[user@host: ~]$ make install
ln -s /dev/ttyS0 /path/to/bar
ln -s /dev/ttyS1 /path/to/baz
ln -s /dev/ttyS2 /path/to/woz | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "makefile"
} |
Substring to remove everything before first period and after second
So I have a filename that looks like this:
myFile.12345.txt
If I wanted to end up with just the "12345" how would I go about removing that from the filename if the 12345 could be anywhere between 1 and 5 numbers in length? | If you are sure that there would be 2 periods `.` for sure
String fileName = string.split("\\.")[1] | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 0,
"tags": "java, substring"
} |
sudo: command not found
I'm new to this. I'm trying to install apache2 on an Ubuntu 15.04 server. Running as root.
But when giving the command:
$ sudo apt-get install apache2
-bash: sudo: command not found
Can anyone point me in the right direction? Thanks in advance.
EDIT:
root@dev:~# whoami
root
root@dev:~# apt-cache policy sudo
N: Unable to locate package sudo
root@dev:~# apt-get install sudo
Reading package lists... Done
Building dependency tree... Done
E: Unable to locate package sudo
root@dev:~# apt-cache policy sudo
N: Unable to locate package sudo
root@dev:~# sudo apt-get install apache2
-bash: sudo: command not found
root@dev:~# apt-get install apache2
Reading package lists... Done
Building dependency tree... Done
E: Unable to locate package apache2
**EDIT** :
Ran; apt-get update and then tried again. Worked! | As you are root you shouldn't need `sudo` to run the command. Try running the commands without `sudo` as in `apt-get install apache2` for example.
Source: experience | stackexchange-askubuntu | {
"answer_score": 2,
"question_score": 3,
"tags": "apache2, sudo"
} |
css/html: padding in % doesn't make sense
Consider the following html
<div id="parent">
<div id="child"/>
</div>
I've given the parent a height of 100px. The child has a height of 100% and a padding of "10% 0". In CSS:
* {
box-sizing: border-box;
}
#parent {
height: 100px ;
}
#child {
height: 100%;
padding: 10% 0;
}
Or checkout this jsfiddle. Anyway, from the above I would expect the child div to have a top/bottom border of 10px (10% of 100px). But it is 31.5px. Can someone explain why this happens and how I can achieve what I want ?
Thanks a lot! | Percentage is width based: If you do this you will get the desired result. Also `<div>` is not self closing.
* {
box-sizing: border-box;
}
#parent {
height: 100px;
width : 100px;
background-color: green;
}
#child {
height: 100%;
padding: 10% 0%;
background-color: blue;
}
See related question: How to set the margin or padding as percentage of height of parent container? | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "html, css"
} |
VB.net has process finished running
I have this code which prints files in vb.net:
' Create object, passing in text
Dim psi As New ProcessStartInfo
psi.UseShellExecute = True
psi.Verb = "print"
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.FileName = fi.FullName
Process.Start(psi)
i want to be able to run more code once the printing process has completed, how can i see if it has completed? | I think you most likely want to wait for the process to finish. Try this:
Dim p = Process.Start("calc.exe")
p.WaitForExit()
If you really don't want to wait but just check for completion try this:
If p.HasExited() Then
' do something
End If | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "vb.net"
} |
Send a file directly to a printer
Within the command window (cmd) I can do a
Copy myfile.ps com1*
If I run this in Powershell I receive an error message similar to:
English:
> The Path D:\directory\com1 cannot be processed as the destination represents a reserved device name.
German:
> Der Pfad ... kann nicht verarbeitet werden, da das Ziel für einen reservierten Gerätenamen steht.
Is there still a way to send a file directly to a printer? | There's the `Out-Printer` cmdlet that is used for printing. It looks like the printer needs to be installed in Windows, so direct print into serial port might not work. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "powershell"
} |
django/celery data import fails to check for existing data
I have running celery with django. I import a stream of objects into my database by using tasks. each task imports one object. concurrency is 2. within the stream objects can be duplicated, but should not be inside my database.
code i'm running:
if qs.exists() and qs.count() == 1:
return qs.get()
elif qs.exists():
logger.exception('Multiple venues for same place')
raise ValueError('Multiple venues for same place')
else:
obj = self.create(**defaults)
problem is that if objects inside the stream are duplicate and very close to each other, the app still imports the same objects twice.
I assume that the db checks are not working properly with this concurrency setup. what architecture du you recommend to resolve this issue? | You have to use locking _architecture_ , so will block the the two tasks from executing the object fetching part at the same time, you can use python-redis-lock to do that. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "django, database, concurrency, celery"
} |
PHP Mysql DISTINCT Column Where current date
Just Wanted us to DISTINCT a Column and same time short into Current Date
Table contains ref,joined then now need to short by joined date = Current date
Joined = 2019-12-21 15:10:53;
$sql = "SELECT DISTINCT ref FROM users where joined = Current date ";
how write this query help us | you can use `NOW()`
$sql = "SELECT DISTINCT ref FROM users where joined = NOW() ";
also you can use `group by`
$sql = "SELECT ref FROM users where joined = NOW() group by ref "; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql"
} |
Flex DataGrid autoscroll on dataProvider change
My Flex datagrid automatically **scrolls to the top** when I update the dataProvider (ArrayCollection). I **do not want this to happen, but I still want _all_ of the objects to update**. I am developing a semi-real time dashboard for a customer's management system, that will update often. If it scrolls to the top every time it updates, it will be very difficult and frustrating to use.
I've attempted to use the following techniques to prevent this, none have worked.
dataProvider = updatedDataProvider;
dataProvider.updateItem(dataProvider);
dataProvider.source = updatedDataProvider.source;
dataProvider.updateItem(dataProvider);
I've attempted to dispatch a mouse event to hold the vertical scrollbar in place, I've attempted to lock the vertical scrollbar position value in place (saving and reassigning)...
And many others, those are just the first few that popped into my head. Anyone have any ideas? | Already been answered in How do I maintain selection in a DataGrid when the data changes? , check it.
Building on top of that answer, if the index changes between data providers, ie, if a row is inserted above, you may want to do a getItemIndex on the new provider. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "apache flex, actionscript 3, flex3"
} |
How can I unbind (C-M-x) globally?
I was trying to bind `(C-M-x)` to `er/expand-region` but I checked the key combination with `(C-h k)` and noticed that it was binded to `eval-defun`. So I tried to unbind it with any of the following commands:
(global-set-key (kbd "C-M-x") nil)
(global-unset-key (kbd "C-M-x"))
But even using any of those won't unbind the key and `(C-M-x)` still will be running `eval-defun`
This is the result after running both commands:
 | stackexchange-emacs | {
"answer_score": 8,
"question_score": 1,
"tags": "key bindings"
} |
Change in pressure due to dissociation of gas
Let's say I have a container with fixed volume, containing Hydrogen Gas at some predefined temperature. Now I pass an electric spark in the whole container such that this reaction takes place
$$H_2 \rightarrow 2H$$
Now actually the number of moles of Hydrogen(atoms) remain constant, the volume is also constant, would there be an increase in pressure assuming the whole situation to be ideal. I just want to know the contribution in increment due to dissociation and not due to increase in temperature of the gas due to the electric spark. Will the pressure increase, decrease or remain constant? | We use the ideal gas law:
$$PV=nRT$$
Here, $n$ is not the number of moles of hydrogen, but rather the number of moles of gas _particles_ , whatever those may be. Before the spark, there are $n$ moles of hydrogen molecules. After the spark, each molecule dissociates into two hydrogen atoms, making $2n$ moles of hydrogen atoms. So, all else being constant, pressure in the chamber should double.
Of course, this is assuming that you can actually keep the gas dissociated into neutral atoms for long enough to reach steady-state conditions. In practice, this is difficult for any case except very dilute gases, as collisions between the neutral hydrogen atoms favor recombination into $H_2$. | stackexchange-physics | {
"answer_score": 0,
"question_score": 1,
"tags": "thermodynamics, pressure, ideal gas"
} |
like's not appearing on facebook, button is working
so the button works and remembers the likes. I say it works because looking at the ajax requests there is not error, it's all succesful.
but the like with the link or image is never shown on facebook, I've checked my wall/timeline... nothing...
<iframe src=' scrolling='no' frameborder='0' style='border:none; overflow:hidden; height:22px;' allowTransparency='true'></iframe>
that's the code I use... it's supposed to work... anybody know why it could fail?
thanks! | How do you mean? Did you post after the like? Or just do a like?
I just did a pure like of a techcrunch article and didn't see it appear on my wall or timeline. Where does it say in Facebook documentation that you are to see it on the wall/timeline? | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "facebook, facebook like"
} |
Polite terms for excrement
There are many vulgar terms for excrement, but what are the non-vulgar, polite ones (used in medical settings, or with children, or among adults in polite conversation)? | All of these terms are quite "polite":
* **Excremento**
* **Heces** (the singular is hez, but it's used in plural for this meaning)
* **Deposición** (very formal, used by the medical profession)
* **Deyección** (very formal, so much that some people wouldn't know its meaning; used by the medical profession)
* **Defecación** (very formal, used in medical environments)
* **Materia fecal** (very formal, used in clinical tests)
* **Caca** (not so polite as the others, but probably the term used with children)
* **Popó** (more childish even than caca, term used with children) | stackexchange-spanish | {
"answer_score": 14,
"question_score": 6,
"tags": "traducción, selección de palabras, cortesía, vocabulario"
} |
Any other way to Reverse String Without using array?
int main()
{
clrscr();
char c[80],d[80];
cout<<"Enter a string = ";
cin.get(a,80);
strcpy(c,a);
strrev(a);
if(strcmp(c,a)==0)
cout<<"String = "<<c<< "is palindrome.";
else
cout<<c<<" is not palindrome";
getch();
return 0;
}
so there is any other way to accomplish this task in easy way without using array or in other way? | #include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string s;
getline(std::cin, s);
if (std::equal(s.begin(), s.end(), s.rbegin()))
std::cout << s << " is a palindrome\n";
else
std::cout << s << " is not a palindrome\n";
}
No arrays, no pointers. | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 6,
"tags": "c++, algorithm"
} |
How can I read WKT from the shapefile .prj?
I am building a system which lets users upload shapefiles. It then converts those shapefiles to PostGIS using `shp2pgsql`. This command requires the SRS ID in form of an EPSG code.
So I need a ruby gem that can read the shapefile's `*.prj` file (which contains the projection/spatial reference system encoded as WKT) and return a corresponding SRS ID. | I'm not sure how Ruby bindings work to GDAL, but OSR (part of GDAL) can extract either the projection WKT (text) or the SRID (integer).
See this gis.SE answer for a solution with Python/GDAL/OSR.
**Update:** It turns out the Ruby bindings work nicely as expected. To get you going, try this code:
require 'gdal/osr'
prj_fname = 'myfile.prj'
prj = File.open( prj_fname )
# Import the WKT from the PRJ file
srs = Gdal::Osr::SpatialReference.new()
srs.import_from_wkt( prj.read )
# Various exports
puts srs.export_to_wkt
srs.auto_identify_epsg
puts srs.get_authority_name(nil)
puts srs.get_authority_code(nil)
If you need some other aspect of the projection, explore the available public methods:
srs.public_methods.sort | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "ruby, rubygems, postgis, shapefile, map projections"
} |
Bytes to String, without decoding
I'm new to python3 and i need to get incoming bytes from a socket and store it as a string.
print(input_bytes)
b'data:\x00,\xff'
I don't need to decode the data
byte_input_to_string = input_bytes
print(byte_input_to_string)
b'data:\x00,\xff'
file = open('byte_data.txt','w')
file.write(byte_input_to_string)
file.close()
What i need is to store data as a string, i don't need to decode it. I just want the same data but as a string, so i can parse it, etc. | file.write(str(byte_input_to_string)) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "python 3.x"
} |
Controlar el cerrar la ventana o cambiar de componente
Tengo un formulario, el cual tiene un botón de guardar cambios, si el formulario es correcto el botón se pone activo, si el formulario no es correcto el botón se pone disabled, quiero que si el botón está activo y el usuario quiere navegar a otro componente o cerrar la pestaña del navegador le alerte ede guardar los cambios
<button class="btn btn-block btn-sm btn-success" [disabled]="f.invalid">Guardar cambios</button>
Alguna idea? He visto que con Javascript se puede controlar el cerrado de la pestaña, pero nada de los componentes | vale, estás trabajando con Angular entonces debes usar FormsModule y a su vez en tu formulario usar NgForm. Lo que deberás hacer es validar el formulario algo así:
<button class="btn btn-block btn-sm btn-success" [disabled]="f.invalid" (click)="TuFuncion( NombreDelFormulario )">Guardar cambios</button>
En el ts:
TuFuncion( NombreDelFormulario: NgForm ){
if( NombreDelFormulario.invalid ){
console.error( "Algún mensaje de llenar campos" );
}else{
if (confirm("¿Realmente deseas salir?")) {
// Aquí aplicar el router navigate a donde quiere ir.
}
}
} | stackexchange-es_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "angular"
} |
How to split an string array element by whitespace, and forming two new arrays?
I searched for **"How to split a String"** related questions, they all seem to be something like `String.split("")`, and you end up having a `String` array with each part being its element. But I didn't mean that, my question is:
I have an array of String called columnNameType:
columnNameType = {TeamName string, City string, Sport string, Year int}
each element in this array contains columnName and its corresponding type, for instance: TeamName string: the columnName is TeamName, its type is string.
But I want to get two new arrays respectively containing columnNname and columnType:
types = {string, string, string, int}
names = {TeamName, City, Sport, Year}
How can I do this? | As you mentioned the split-function can handle this.
String[] types = new String[columnNameType.length];
String[] names = new String[columnNameType.length];
for(int i = 0 ; i< columnNameType.length; ++i){
names[i] = columnNameType[i].split(" ")[0];
types[i] = columnNameType[i].split(" ")[1];
}
iterate your array and split every element on its own. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -5,
"tags": "java, arrays, string, split"
} |
Проблема с pip, no module 'pip'
Проблема такая, нужно было установить pyinstaller через pip, оно не устанавливалось, нашел в интернете ответ такой, что надо откатить pip на раннюю версию, сделал по команде котору привел человек в итоге теперь пишет мне no module named 'pip' как быть? Как вернуть pip?
вот данный ответ, который я нашел:
Откати версию PIP до 18.1
pip install pip==18.1
Пробуй установить pyinstaller еще раз
pip install pyinstaller
Обнови версию PIP до последней
python -m pip install –upgrade pip | Я сталкивался с похожей ошибкой и решил ее жестко и грубо: удалил python и установил снова | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python"
} |
Why controller does not working using laravel 5?
I'm trying to make a test controller, i read its documentation and following the instruction during developer controller and view. But it does not working.
## Controller
project/app/http/controllers/TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class TestController extends Controller {
/**
* Show the profile for the given user.
*
* @param int $id
* @return Response
*/
public function index()
{
return view('test');
}
}
?>
## Route
Route::get('test', 'TestController@index');
## View
project/resources/views/test.blade.php
simple html
I'm testing this controller using ` but it does not work. Can any one guide me where i'm wrong. | Use this in your view `<a src="{{ route('test') }}">test</a>` | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "php, laravel, laravel 5"
} |
How to use 彼 and 彼女?
The first time I saw these two terms, they were used in a love context, to mean "boyfriend/girlfriend". Later, I came to know that you can also use these to refer to "that guy/girl".
So, what I wanted to know is:
1) Nowadays, what are these commonly used for?
2) Does the meaning depend enterily on context? If so, isn't there a chance to be misunderstood?
3) Does Japanese have a specific term to convey just one of these meanings? For instance, something just for girlfriend? | **(1)** The words are still used commonly as you describe, i.e. = he/him/boyfriend and = she/her/girlfriend
**(2)** Semantic context is definitely the easiest way to differentiate. Yes, there might be times when the words could be ambiguous or be construed in unintended ways, but that is probably true of some words in most languages. In any case, the speaker will usually make it clear from the context which meaning is intended.
**(3)** is a term specifically meaning "boyfriend" and is a term specifically meaning "girlfriend". | stackexchange-japanese | {
"answer_score": 5,
"question_score": 1,
"tags": "meaning, word choice, pronouns, ambiguity"
} |
How to get absolute position of point inside CALayer
how can I obtain the absolute position of a CGPoint inside a CALayer. I need this for exact pixel drawing
Edit: Absolute to the screen | Hit test the superlayers recursively, until you arrive at the root layer:
CGPoint originalPoint = // wherever from you obtain your original point
CALayer *layer = self;
CGPoint point = originalPoint;
while (layer.superlayer)
{
point = [layer convertPoint:point toLayer:layer.superlayer];
layer = layer.superlayer;
}
// here `point' will contain the exact position | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "iphone, objective c, calayer, quartz graphics"
} |
How do I get a file length?
I am trying to get the length (in bytes) of a file, but every time I test different files, the result is invariably 4065123.0.
This is the relevant portion of my code:
File file = new File(path + filename);
if(!file.exists()) {
System.out.println("File does not exist");
} else {
double bytes = file.length();
}
How do I correctly get the length of a file? | Try:
File file =new File("myfile_in_test.java");
if(file.exists()){
final double bytes = file.length();
final double kilobytes = (bytes / 1024);
System.out.println("bytes : " + bytes);
System.out.println("kilobytes : " + kilobytes);
}else{
System.out.println("File does not exists!");
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, file"
} |
Interesting Combinatorial Identities; e.g. $\sum_{k=0}^n {n\choose k}^2 = {2n\choose n}$
I came across the following combinatorial identity:
$$\sum_{k=0}^n {n\choose k}^2 = {2n\choose n}$$
Here's the kind of proof which caught my interest:
$\sum_k {n \choose k}^2 = \sum_k {n \choose k}{n \choose n - k}$, and this represents the number of ways we might choose a committee of $n$ people out of a group of $2n$ people. On the other hand, ${2n \choose n}$ represents the same thing. So the result follows.
Now, I'm looking for some nice combinatorial identities which are, in spirit, similar to such an identity.
Thank you. | There is a book called "Proofs that Really Count: The Art of Combinatorial Proof" by Arthur T. Benjamin and Jennifer J. Quinn, which might be of interest to you. | stackexchange-math | {
"answer_score": 3,
"question_score": 3,
"tags": "combinatorics"
} |
vim arrow keys inserting strange character in iterm2
vim escape & arrow keys are inserting strange character (the letter q in my case) but works perfectly if launched in a tmux session or with terminal.app
Someone having the same problem? | Setting the Report Terminal Type to ansi or linux in my profile solved my problem.
When the terminal type of your sessions is set to one of those "xterm" types, iTerm handles the arrow keys, the home key, and the end key in a special way. | stackexchange-apple | {
"answer_score": 6,
"question_score": 5,
"tags": "iterm"
} |
How to execute a method of a nested component
I have the component with form and I have the nested component with input['file']. Nested component have a method 'removeFile'. How can I execute this method when submit form?
// form
<form>
<input type="text">
<file-input></file-input>
</form>
// component "file-input"
<script>
export default {
methods: {
removeFile() {
// ***
}
}
};
</script>
<template>
<div>
<label>
<div>
<span @click="removeFile"></span>
</div>
<input type="file">
</label>
</div>
</template> | In most cases you want to avoid doing this if possible. Data should flow down and events should be emitted up.
That being said you can access by adding a ref to the child. In child you add a
<Child ref='foo'></>
Then in your parent you access the component vie 'this.$refs.foo' which will have all the normal method and data stuff on the child.
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "vue.js, vuejs2"
} |
What is an object of the verb 'De' for the use of 'Ce dont'?
The object of a preposition would be like this:
_Avec quoi écris-tu ?_
(What do you write with?)
With _quoi_ being the object of the preposition _avec_ (with); however when you use the preposition _de_ you must use _Ce Dont_ instead of _quoi_.
In this example:
C'est ce dont je me souviens.
(That's what I remember)
You never see the preposition _de_ , anywhere in the clause. How is it an object of a preposition, which is not even present in the sentence? Whereas in the first example you see the preposition _avec_ in the sentence.
Please explain! | _Dont_ means _de qui_ (for people), _duquel_ / _de laquelle_ / _desquels_ / _desquelles_ (for identified things) or _de quoi_ (for unidentified things). Depending on the context, you may have the choice of what to use, or one may be mandatory. The two most important aspects of those rules is that:
* when asking a question, it is never _dont_ (thus, _de quoi te souviens-tu?_ , not ~~_Dont te souviens-tu?_~~ )
* after _ce_ , it is always _dont_ (thus, _c'est ce dont je me souviens_ , not ~~_C'est de quoi je me souviens_~~ )
See this question for more details. | stackexchange-french | {
"answer_score": 5,
"question_score": 2,
"tags": "prépositions"
} |
how to get rid of these weird artifacts in my fluid sim?
 not replacing certain characters
def replace_at_index(string, index):
print (string.replace(string[index], "-", 1))
That's my current code for replacing a character with a given index.
* string "House" with Index 4 produces "Hous-"
* string "Housee" with Index 5 produces "Hous-e"
* string "Houseed" with Index 6 produces "Housee-"
* string "Houseed" with Index 5 produces "Hous-ed"
Not sure why it's doing this. The result I'm wanting is for it to replace the given Index, which in the case of "Housee" Index 5 would be "House-" | Look at the function doc-string: `string.replace(old, new, count)` so it replaces `count` as many occurences that it can find.
You cannot change a string. Each string is newly created, it is immutable. What you want is:
def replace_at_index(string, index):
string = string[:index] + "-" + string[index+1:]
return string | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "python"
} |
Suppose that $I$ is an ideal of $R$ which is maximal with respect to the property that it is proper and not prime.
> Let $R$ be a commutative ring with $1$. Suppose that $I$ is an ideal of $R$ which is maximal with respect to the property that it is proper and not prime. Deduce that $I$ is contained in at most two other proper ideals of $R$.
I don't have idea. Help me.
Thanks in advanced. | Let $I$ be such an ideal, and let $P$ be a minimal prime ideal over $I$. Then in $R/P$, every proper ideal is prime. Hence for any nonzero $a \in R/P$, $(a^2)$ is prime, so it contains $a$, so there is some $b$ such that $a^2b = a$; that is, $a(ab-1)=0$ and since $R/P$ is an integral domain, it follows that $ab=1$ and $a$ has an inverse. So that means that $R/P$ is a field; hence $P$ is maximal.
Now consider $R/I$. The nonzero proper ideals of $R/I$ correspond exactly to the proper ideals of $R$ strictly containing $I$, and they are all maximal. Use the result of your previous question to deduce that there are most two maximal ideals in $R/I$, and hence at most two proper ideals of $R$ strictly containing $I$. | stackexchange-math | {
"answer_score": 1,
"question_score": 3,
"tags": "abstract algebra, ring theory, ideals"
} |
Concatenate two datetimes into a string date range
I have a pandas dataframe.
Data = pd.DataFrame([[datetime.datetime(2014,1,1),datetime.datetime(2014,1,3)]],columns=['date1','date2')
That dataframe has two datetime columns date1 and date2.
I want to create a new column that contains a string in the format below:
'1/1/2014 - 1/3/2014'
Right now I have this setup to create the new column, **but it keeps the trailing hms** :
Data['range'] = Data.apply(lambda x:'%s - %s' % (x['date1'],x['date2']),axis=1)
Finding it hard to strip just the date out since I am working with two columns rather than two values. Any pointers? | > > Finding it hard to strip just the date out since I am working with two columns rather than two values
Well, since you're already using `apply`, you're dealing with two values (not columns), so you can call the `date` method on each:
Data.apply(
lambda x: '%s - %s' % ( xdate1.date() , x.date2.date() ),
axis=1)
The `x` passed to your lambda function is a single row of your dataframe, so accessing `x.date1` (or `x['date1']`) gives a single value of type `Timestamp`. It's easy to extract just the date from that. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "python, string, datetime, pandas, concatenation"
} |
How do I link to a pdf using CodeIgniter?
this is such a simple task, yet I can't seem to get it to load a pdf.
I have a simple link on my view that links to a pdf stored in a downloads folder.
Is there something I'm missing about doing this in CodeIgniter?
<div class="node_title_grant">
<a href="<?php echo base_url();?>index.php/downloads/grant.pdf" target="_blank">
Grant
</a>
</div>
then I have grant.pdf stored in a downloads folder in my application folder.
thanks in advance | Simply do the normal path ...
href="<?php echo base_url(); ?>application/downloads/grant.pdf"
Or:
href="/application/downloads/grant.pdf"
Edit:
I believe .htaccess was the problem. Moving the downloads folder from inside applications to the root directory solved the issue. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "codeigniter, hyperlink, download"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.