INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Delete the "Settings" Tab in Navigation drawer
I'm developing an app with a Navigation Drawer. But in the top right corner there is always the menue with the tab "Settings". How can I remove that menue as well in the drawer as in the normal view?
|
First of all delete the `main.xml` file under the directory
> "project name"\app\src\main\res\menu
and it should look like this image.
Then, remove a block of code that is in relation to that of the `main.xml` file. It should be located under the MainActivity or the activity where you are seeing the "Settings". Refer to this image.
You can also delete the string resource under `strings.xml` file which is named "action_settings" by default.
That is all and your project is clear from what you want to get rid off.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "android, menu, navigation, drawer"
}
|
Remove Wordpress Cache Definitely
I have a WordPress install without any cache plugin (I had W3 Cache and Wp Super Cache installed but now they were removed) and the site still be caching. When I enter I see old news and when I manually refresh the browser it updates.
Any idea? What is happening?
|
The problem was caused by APC Cache. <
I disable it and now everything it's ok.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "wordpress, caching"
}
|
Ruby on rails- How can I insert a variable into a string in array?
I want to make a repetition using: for.
For example,
<li class="<%= is_active?([y17s_index_path,y17s_gun_path]) %>"><a href='<%= y17s_index_path%>'>2017</a></li>
<li class="<%= is_active?([y16s_index_path,y16s_gun_path]) %>"><a href='<%= y16s_index_path%>'>2016</a></li>
<li class="<%= is_active?([y15s_index_path,y15s_gun_path]) %>"><a href='<%= y15s_index_path%>'>2015</a></li>
<li class="<%= is_active?([y14s_index_path,y14s_gun_path]) %>"><a href='<%= y14s_index_path%>'>2014</a></li>
.
.
.
How can I write repetitive statement in this case? I tried #{} but It does not work.
I want to change only 17,16,15... these numbers.
|
You can use some light meta-programming with the `send`-method with an each-call:
<% [1..17].each do |i| %>
<li class="<%= is_active?([send("y#{i}s_index_path"), send("y#{i}s_gun_path")]) %>"><a href='<%= send("y#{i}s_index_path") %>'>20<%= "%02d" % i %></a></li>
<% end %>
Should output 2001 to 2017, with same methods as before. You can see the documentation on `send` method here: <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ruby on rails"
}
|
Fetch next date from based on a date parameter
I have a requirement to fetch back the next date based on a date I already know. I am using the following query but this returns all dates and all nextdates for the entire recordset. I can understand that I am asking for dates greater than my search date, but if I use `WHERE = '2010-01-01 04:30:00.000'` then I get no results. How can I fetch only the next date?
The query is (using SQL Server 2012 Express):
SELECT [DateTime], [Item], LEAD([DateTime]) OVER (ORDER BY [DateTime]) NextDate
FROM cteList
WHERE [DateTime] > '2010-01-01 04:30:00.000'
ORDER BY [DateTime];
|
As others have stated you can limit your existing query `TOP 1`
SELECT TOP 1 [DateTime], [Item], LEAD([DateTime]) OVER (ORDER BY [DateTime]) NextDate
FROM cteList
WHERE [DateTime] > '2010-01-01 04:30:00.000'
ORDER BY [DateTime];
For you to use `WHERE [DateTime] =` you would have to have the exact datetime to the corresponding row in your table.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql server"
}
|
Can I add sub folders to a SQL Server Management Studio Project?
What is the best way to keep large projects organized with SSMS?
I want to do something like:
ProjectRoot
SchemaObjects
Tables
Constraints
Indexes
Keys
Functions
Views
Stored Procedures
Scripts
DataGeneration
And so on, but I cannot find a nice way to do this... Any suggestions?
|
I don't think there's anyway way to do this in SMSS, at least not in 2005. Maybe a third party tool will give you this; there's a list of replacements for 2000 Enterprise Manager here; not the most current, but probably a good starting point.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "sql server 2005"
}
|
using cardview on top of recycler view crashes system
Why does using large images using cardview crash the android system? I used 1280 X 600 images for cardview, but launching the app after install crashes the system presents a `out of memory error` from the logcat.
I had atleast 400MB of RAM while launching the app(viewed using simple system monitor), but yet the app crashes. Is the cardview designed to work with only small images? What if we _have_ to use larger images for larger dpi devices? The cardview was used with a recycler view and the OS which it was tested on was KitKat.
|
You may have 400 MB RAM but all the RAM will not be directly provided to your application so application will crash...if you want to use different dpi images for different devices then you can add that to drawable, drawable-mdpi, drawable-xhdpi,drawable-xxhdpi etc. folder so that system can select them automatically....if you are loading from a url...then you can use third party libraries like Picasso, Glide etc to load the image efficiently
Also, in your question you are saying that you are adding card view in recycler view...which means more than one 1280x600 images will be loaded which will take a lot of memory and make your app to crash.
For your question "Is the cardview designed to work with only small images?" No, cardview is not related to your out of memory... its the image size and Memory provided for you...card view can work with any size of image.
Adding Adding android:largeHeap="true" to your menifest can help you to some extent
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, android recyclerview, android cardview"
}
|
key map to call function in a plugin
I have a visual map:
vmap 1 :call ExecuteSelection()<CR>
The `ExecuteSelection` function is defined in the plugin vim-shell-executor.
However, when I try to press the `1` key in visual mode, I receive the error:
E117: Unknown function: ExecuteSelection
**Question:** how can I fix this?
|
If you look at the plugin's source, that's the name of the _command_ ; the underlying function is named differently:
command! -range ExecuteSelection call ExecuteWithShellProgram("selection")
So, I'd recommend to use the (public) command in your mapping.
vnoremap 1 :ExecuteSelection<CR>
(You should use `:noremap`; it makes the mapping immune to remapping and recursion.)
PS: Are you sure you want to map to `1`? That prevents you from supplying a _count_ ; e.g. you won't be able to shift the selection by 10 any more (`10>`)!
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "vim"
}
|
How to configure firewall for ftp?
I have got ftp working for isolate users on a windows web server running iis 7.0
I am using coffecup as ftp client to connect.
when i turn off the firewall on the server the ftp works fine. I can connect to server.
As soon as i turn on firewall i get error:
There was a problem connecting to your host or proxy. Please check your server settings and try again. If you are sure you have entered the correct information, please contact your network administrator or the server administrator. [7] Additional information: couldn't connect to host.
On firewall i have port 20 and 21 open. What else am i missing? thanks
|
You're missing passive mode operation of FTP. In passive mode you're connecting to servers port that is negotiated over port 21.
`netsh advfirewall firewall add rule name=”FTP Service” action=allow service=ftpsvc protocol=TCP dir=in`
`netsh advfirewall set global StatefulFTP disable`
More info here: <
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iis, ftp, firewall, windows server, windows firewall"
}
|
While moving the cursor across a vim process open in a tmux session, every now and then, why does it leave a trail of ghost characters - ^[OB, ^[OA?
These disappear if I do a page-up and page-down. Why does this happen and how do I rectify it?
I recently fiddled around with my vimrc. Could that be the cause?
UPDATE: I figured out the cause. I had added to functions that automatically updated the cwd name and the current git branch in my vim statusline. This caused vim to be laggy and everytime it lagged on a up/down/left/right key hit, it printed out the ghost characters ^[OA, etc. It's possible that stuff got complicated because I was using vim in tmux, but I saw the ghost characters outside tmux also. So, probably not. I've turned off those two functions in my .vimrc and my vim statusline is presently less awesome than it used to be :( Wish there's a way out.
|
`^[OB` and `^[OA` are how your terminal represent `<down>` and `<up>`.
I've seen these (and their friends `^[OC` and `^[OD`) appear in the "command line" or omni-completion menus and during usage of a couple of plugins in vim in tmux.
My solution was to map them to the directional keys:
map ^[OA <up>
map ^[OB <down>
map ^[OC <right>
map ^[OD <left>
In case you don't know, you must not type `^[` as two characters, you must do `<C-v><Esc>`.
That is, while in `--INSERT--` mode press the **Control** key and the **V** key together then hit the **Escape** key. Doing so will input the correct **single** character that looks like `^[`.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 8,
"tags": "vim, tmux"
}
|
How do sites like codewars, that run user submitted code, protect themselves from malicious users?
I am working on a little project for me and my buddies that works like some of these sites like leetcode and codewars. These sites have code editors that you can actually run your code. I want a user to be able to input a function that solves an algorithm and unit test it to see whose code was the most efficient.
**How do sites like this make sure that someone doesn't run a bunch of code that can perform something malicious?**
I think I am having trouble finding answers to this since I don't really know how someone could use that to create problems for a site like CodeWars.
**What are best practices for a web code editor to protect my site from anyone with nefarious intentions (other than cross site scripting)? What are some methods people could exploit a feature like this?**
|
Presumably, the user's code is executed in an isolated environment (i.e. virtual machine). If so, the code executed will not be able to escape the VM (unless they are able to find vulnerabilities in the VM implementation). The host machines will have the ability to limit resources available to users' programs.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, node.js, security, express"
}
|
Jenkins Pipeline - upload artifacts to s3 with build parameters
I'm building multiple branches, and I have created a build parameter (String parameter) for branch. So my artifacts should get upload to specific branch based on the parameter I pass:
s3Upload(file:'target/test-ear-1.0.ear', bucket:'test/$BRANCH', path:'').
But `$BRANCH` or `${BRANCH}` is not working. Its copying to the path like this `test/$BRANCH`. I'm expecting it should upload to `test/dev`.
Does anyone have hints on this ?
|
Try specifying it within double quotes.
bucket: "test/${BRANCH}"
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jenkins, amazon s3, jenkins pipeline"
}
|
Simple flatbed scanner - but it must work in Windows 7 Prof x64 ?
Any recommendations on a pretty basic flatbed scanner for light-duty text and graphics scanning? I don't need any fancy features like sheet feeder or anything like that - I just need to scan an occasional text document or picture.
A scan-to-PDF function would be nice.
An **absolute MUST** is compatibility with Windows 7 Professional in **64-bit edition** \- no VM or Virtual XP mess - the scanner **MUST** have working Windows 7-x64 drivers.
|
Check this link to see what other scanners are Windows 7 64 bit compatible
Here's an example: Canon Canoscan LiDe 100
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 0,
"tags": "windows 7, 64 bit, scanner"
}
|
How to add libreoffice 5.0 links to dash
I have removed libreoffice 4.2 from my ubuntu 14.04 machine by using:
sudo apt-get purge libreoffice*
And then I have installed libreoffice 5.0 extracting files from the downloaded package, and using the following command in the DEB folder
sudo dpkg -i *.deb
I can open openoffice 5.0 aplications using the terminal, but they do not appear in the unity dash.Even worst, the applications are not set as default to open office documents.
How can I fix this?
|
I did it by uninstall all 4.4 packages via synaptic. After logout and login again short-cuts to 5.0 where in dash
|
stackexchange-askubuntu
|
{
"answer_score": 2,
"question_score": 0,
"tags": "14.04, package management, libreoffice, unity dash"
}
|
How can the Address condition in a Match conditional block in sshd_config be negated?
I would like to force users into a specific command when they log in from outside my LAN via SSH to my LAN. My idea was, to use `ForceCommand` in a `Match` conditional block, that matches all addresses except for the ones in my LAN.
I have tried the following, according to `man 5 sshd_config`:
* `Match Address !192.168.1.0/24` allowed users from anywhere to execute any command.
* `Match Address !192.168.*` allowed users from anywhere to execute any command.
* `Match !Address 192.168.*` prevented execution of any command by means of `sshd` refusing to start.
Negating a pattern using `!` is described in `man 5 ssh_config` (Section "Patterns"). How can this be applied to addresses?
|
According to this ServerFault answer, for some unknown reason, you need to add a wildcard match in order to do this. CIDR notation does however seem to work. For example:
Match Address *,!192.168.1.0/24
ForceCommand /bin/false
This works for me with OpenSSH 5.9p1.
|
stackexchange-serverfault
|
{
"answer_score": 14,
"question_score": 8,
"tags": "ssh, cygwin sshd"
}
|
What do the icons on the Historia Crux represent?
Under each location, there are these little symbols that look kind of like stylized flames. They seem to be lighting up as I proceed through the areas but I can't figure out any 1:1 relation for them, and the manual and Datalog are useless here. What are these actually for?
|
They correspond to the number of gates in the area:
* **White gates** are still locked, requiring an artefact you haven't found yet, or an artefact you've found but haven't brought to the gate yet.
* **Orange gates** are unlocked and usable.
Because you need to unlock gates as part of the main storyline, you'll undoubtedly have orange gate icons for most of the locations by default. The other ones unlock optional paths and are usually unlocked with wild artefacts found in optional parts of the area.
|
stackexchange-gaming
|
{
"answer_score": 4,
"question_score": 2,
"tags": "final fantasy 13 2"
}
|
Is there an Ambiance theme available for Windows?
I tend to run Windows apps with VirtualBox in seamless mode (so that virtualized Windows applications windows and Windows taskbar appear alongside host OS windows instead of a separate virtual machine screen). To make the experience even more "seamless" I'd like Windows theming (especially windows' title bars and a taskbar) to look exactly as Ubuntu windows look. So it seems that I need a Windows clone of Ubuntu Ambiance theme. Is there one?
I'm ok to have Windows minimize/maximize buttons on the right, as I've switched Ubuntu to the same classic mode.
I am interested in both Windows XP _and Windows 7_ themes.
|
Yes, you can download it here. This theme is for Windows XP and while it has a few bugs, outlined in the download link, it should be an improvement on what you have now.
, make it open a specific webpage, execute some javascript on the DOM and pass information to the **outside** (the outside might be the application that made firefox start).
What do you think would be the best way to achieve this? I thought of creating a firefox plugin that opens a tcp socket, listening to connections that trigger the execution of javascript code on the DOM. The result is then passed either to a local **webserver via http** or to the other end of the **socket connection**.
Would it also be possible to **start a webserver within the firefox plugin** instead? I think this would be easier than having a socket connection opened all the time (if not, this would be fine though).
|
Just for those who stumble across this question, I solved the problem by now.
The process is as follows:
1. A web server (in my case written in node.js) opens the browser via a shell command.
2. When the browser has initiated the plugin, it starts a socket server and sends an http request to the web server telling it to be ready to receive commands.
3. The web server sends the command "get-dom" with the web site as parameter to back to the browser (via socket).
4. The browser executes a content script on the website via a page-worker, creates a DOM object and sends it via http request back to the web server.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, sockets, firefox, plugins, tcp"
}
|
bypass the yes prompt in apt-get install, but only authorized packages
How do I call `apt-get install -y --force-yes` if I want to install the package no matter what, except unauthorized packages.
So I want apt-get to work in non interactive mode and only with signed packages.
|
If I understand your question correctly, you use one of the options `-y`or `--yes`, or `--assume-yes`
From the man page <
> -y, --yes, --assume-yes Automatic yes to prompts; assume "yes" as answer to all prompts and run non-interactively. If an undesirable situation, such as changing a held package, **trying to install a unauthenticated package** or removing an essential package occurs then apt-get will abort. Configuration Item: APT::Get::Assume-Yes.
I suppose it may depend on what you mean by "unauthorized packages"
I would use extreme caution with any of the force options with apt-get, forcing things is a good way to break apt, or your install, or both.
|
stackexchange-askubuntu
|
{
"answer_score": 5,
"question_score": 1,
"tags": "apt, debian, signature"
}
|
Dollar sign in URL breaks link
I've seen a number of reports of special characters breaking links, some of which seem to get fixes, others seem to be tagged "status-by-design". I didn't see any indicating that the $ sign wasn't working so I thought I'd report it. I tried to link to:
> <
But the link does not appear as a link either in the editor or in the completed question. I _fixed_ it by using TinyURL to proxy the link and pasting in the TinyURL.
|
See if you can safely remove the dollar sign (`$`)
> <
The dollar sign is a special character (and apparently hasn't been taken in with the automatic SO linkifier).
If you wanted (or could be bothered) you can also encode to its hex equivalent (`%24`):
> <
|
stackexchange-meta
|
{
"answer_score": 16,
"question_score": 10,
"tags": "bug, status bydesign, hyperlinks"
}
|
Can I safely add an analogue clock in series with an LED light?
I have a voltage regulator outputting 5v to an LED grow light that draws 1A. Can I increase the output to 6.5v, and add an analogue quarts clock in series, intended to run off a 1.5v battery?
My concern is that the current draw from the clock is not constant, and this will create a drop in the LED light that could damage it.
From reading online, the clock draws 0.1mA constantly and and then draws 5mA for 0.02 seconds per second when the solenoid fires.
|
No. Either the clock burns out from the higher current draw or the leds won't turn on from a reduced voltage drop. As the current of the clock will vary greatly between the motor moving, the motor not moving, or the motor moving a load, the leds will not see a steady draw if any.
If you really need to do this, put a 1.5V regulator in parallel with the led light. Even an non-low drop out (LDO) linear regulator will work. The parallel draw will not affect the other side and you get both powered by a single source.
Hell, a few silicone diodes in series would be enough. 5 diodes in series would be just about 3.5V give or take a few tenth of a volt and give you 1.5V. But again since the motor which is the highest draw in a mechanical clock, will vary, an actual linear regulator would be better. Lm317 would fit nicely.
|
stackexchange-electronics
|
{
"answer_score": 0,
"question_score": 1,
"tags": "circuit design, quartz"
}
|
splunk query based on log stdout
I cannot think of how to query a splunk. I have log "Waiting for changelog lock.." and now I need to select all occurrences if in 10 minutes time period, starting from after this is printed, there is no log saying "Successfully acquired change log lock". This does not work, as it checks if same log contains it: `index="[there goes my index]" | spath log | search NOT log="*Successfully acquired change log lock*" AND log='Waiting for changelog lock..' earliest=-10m@m latest=now`
|
You're right in that the current query expects one field to contain two different values, which will never work. Instead, use `OR` and then pick off the most recent event. If it's "Successfully..." then all is well; otherwise, it's a problem.
index="[there goes my index]" earliest=-10m@m latest=now
| spath log
| search NOT log="*Successfully acquired change log lock*" OR log='Waiting for changelog lock..'
| dedup log
| where log="Waiting for changelog lock"
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "select, logging, splunk"
}
|
How to perform a dry-run using rsync over ssh?
I got these errors while trying to perform a dry-run with option `-n` over ssh on a remote server:
# rsync --progress --delete -avhHen ssh /etc/yum [email protected]:/etc
rsync: Failed to exec n: No such file or directory (2)
rsync error: error in IPC code (code 14) at pipe.c(85) [sender=3.1.0]
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: error in IPC code (code 14) at io.c(226) [sender=3.1.0]
How do I perform a dry-run for the above command using rsync over ssh?
|
rsync: Failed to exec n: No such file or directory (2)
Pretty much explains it there...
the `-e` option (long version: --rsh=) says to execute the **FOLLOWING** command as the shell on the destination machine.
You told it: `-e n`. Look at the order of the options you supplied. (`-avhHen`)
Reverse the order, `ne` so that your redundant use of `-e ssh` will work as you desire.
|
stackexchange-unix
|
{
"answer_score": 5,
"question_score": 2,
"tags": "ssh, rsync"
}
|
syntax error when using ifstream
It's been a long time since I've done any C++. What's wrong with this code?
#include <iostream>
#include <fstream>
using namespace std;
main()
{
ifstream& ifs("foo.txt");
}
Gives:
$ g++ foo.cc
foo.cc: In function ‘int main()’:
foo.cc:7:25: error: invalid initialization of non-const reference of type ‘std::ifstream& {aka std::basic_ifstream<char>&}’ from an rvalue of type ‘const char*’
ifstream& ifs("foo.txt");
|
Passing values by reference isn't done in the variable declaration, but instead in the parameter list of the function using the ifstream object. For example, your function main might look like this:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream ifs("foo.txt");
myFunction(ifs);
}
and your called function should look like this:
void myFunction(std::ifstream& in_stream)
{
// ...
}
If you need the C++11 reference type (which I doubt, but maybe), try this:
ifstream ifs("foo.txt.");
std::ref<std::ifstream> ifs_ref(ifs);
That works in a lot of cases where doing a regular by-ref wouldn't.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c++"
}
|
Do you need to call mysqli_stmt::close before you call mysqli::close?
I'm not exactly sure why mysqli_stmt::close is needed. Is it enough to just call mysqli::close?
Is it needed only when you want to execut multiple prepared statements? Or is it also needed if you execute just one?
|
It all depends on the nature of your script.
If it's a regular web-page, that runs for a fraction of second, neither stmt::close nor mysqli::close is ever needed - PHP will close all the resources automatically.
While in a long-running PHP script it's good to close particular statements when you don't need them anymore, as every statement allocates some resources on the server that otherwise can be used by other connections.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "php, mysqli, prepared statement"
}
|
UnhandledPromiseRejectionWarning: ReferenceError: message is not defined
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("messageUpdate", async (oldMessage, newMessage) => {
var logchannel = client.channels.cache.get("736913251274719273");
let logembed = new Discord.MessageEmbed()
.setAuthor(message.author.tag, message.author.avatarURL)
.setThumbnail(message.author.avatarURL)
.setColor("RED")
.setDescription(":wastebasket: Message Deleted")
.addField("Message", message.content, true)
.setTimestamp()
logchannel.send(logembed)
})
client.login('token');
|
Your error is saying exactly what is your problem.
message.author.tag
`message` variable is used in several places of the function, but you didn't define the variable.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -3,
"tags": "node.js, discord, discord.js, message"
}
|
SemanticUI modals is always closable, regardless of configuration
I am using Semantic UI and I am pretty happy using it. I am facing a small issue. I am trying to implement a `Modal`, a full screen one. I do not want that modal to be closable (ie. click on dimmer closes modal). So as per the documentation I implemented following to show a non closable modal.
$("body").find(".processing-loader")
.modal("setting", "closable", false).modal("show");
But the modal closes when clicked anywhere on dimmer.
|
I am not sure which part of the documentation led you to the `.modal("setting", "closable", false)` syntax, but this is what SemanticUI expects from you:
element.modal(settings).modal(behavior, arguments...);
so here we go:
$("body").find(".processing-loader").modal({closable: true}).modal('show')
Use a single plain object with your configuration as a parameter and it will work just fine :) Also make sure you use the newest version of the library.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 5,
"tags": "semantic ui"
}
|
What am I doing wrong? Gram Schmidt process..
Let there be the inner product of all polynomials of degree smaller or equal to 2: $\langle f,g\rangle=\int_0^1f(x)g(x)xdx$. Find orthonormal basis.
So I really tried this for an hour and it pretty much became annoying, as I can't tell what's my mistake. Let $E=\\{1,x,x^2\\}$ be the standard basis.
$u_1=1$
$u_2=x-\langle x,1\rangle1=x-\int_0^1x\cdot1\cdot x dx=x-\int_0^1x^2dx=x-\frac{1}{3}$
There is also $u_3$ but let's say I can find it successfully. Lets find the normal of $u_1$ and $u_2$:
$\|u_1\|=\sqrt{\int_0^11\cdot1 \cdot x dx}=\sqrt{\int_0^1x dx}=\sqrt{\frac{1}{2}} \rightarrow \hat u_1=\sqrt2$
$\|u_2\|=\sqrt{\int_0^1(x-\frac{1}{3})^2\cdot x dx}=\sqrt{\frac{1}{12}} \rightarrow \hat u_2=\sqrt{12}(x-\frac{1}{3})$
But $\langle u_1,u_2\rangle=\int_0^1\sqrt2 \cdot \sqrt{12}(x-\frac{1}{3})\cdot x dx \neq 0$.
What's my mistake?
Thanks in advance!
|
I think your mistake is when you put
$$ u_2 = x - \langle x , 1 \rangle \cdot 1 \ . $$
You indeed have that the second vector is something like
$$ u_2 = v_2 + \lambda v_1 \ , $$
where $v_1, v_2$ are the first vectors of your original basis. Now you want to replace them by $u_1, u_2$ being orthogonal. So you set $u_1 = v_1$ and impose
$$ 0 = \langle u_1, u_2\rangle = \langle v_1, v_2 + \lambda v_1\rangle = \langle v_1, v_2\rangle + \lambda \langle v_1, v_1\rangle \ . $$
Which entails that you must take
$$ \lambda = - \frac{\langle v_1, v_2 \rangle}{\langle v_1, v_1 \rangle} \ . $$
That is,
$$ u_2 = x - \frac{\langle 1, x \rangle}{\langle 1, 1 \rangle} \cdot 1 \ . $$
would be better.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 4,
"tags": "linear algebra, polynomials, definite integrals, inner products, orthonormal"
}
|
Can you index fields in elasticsearch that cant be searched?
Are you able to index text fields that cannot be searched on when the user trys to perform any kind of search/match query?
|
Yes you can, just exclude them from `_all` if you do general purpose query by setting `include_in_all` to false: <
As all query run on the `_all` field by default; this should do the trick.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "elasticsearch"
}
|
Markdown for Blogger
Is it possible to have Markdown integration for Blogger? How can I do it if possible? Is there some sort of plugin or JavaScript trick that I can use to modify my template to make it support Markdown?
|
You could use StackEdit (I'm the developer). It's a web-based Markdown editor and it allows you to publish your document (Markdown or converted HTML) on different sites. Amongst others, you can post to Blogger.
|
stackexchange-webapps
|
{
"answer_score": 38,
"question_score": 28,
"tags": "blogger, markdown"
}
|
Tabular paragraph vertical alignment
How to make this kind of tabbed paragraph: 3 columns 2cm 10cm 2cm, the last column is right aligned and it's content starts on the last line of the paragraph of the second column.
10. Some text or description here
can has more than one line 300
This is what I have so far:
\documentclass[10pt,a4paper]{report}
\begin{document}
\begin{tabular}{p{2cm}p{10cm}p{2cm}}
10. &
Some text or description here can has more than one line &
\raggedleft{300} \\
\end{tabular}
\end{document}
I dont know how to vertically align last column
|
It's probably easiest to make the final part part of the main paragraph so it naturally aligns with the last row. Exactly how to do that depends a bit on whether it needs to be multiple line or not, but for example
!enter image description here
\documentclass[10pt,a4paper]{report}
\setlength\textwidth{16cm}
\begin{document}
\begin{tabular}{p{2cm}p{10cm}p{2cm}}
10. &
Some text or description here can has more than one line
Some text or description here can has more than one line
\hfill 300\hspace{-2cm}\mbox{}\\
\end{tabular}
\end{document}
|
stackexchange-tex
|
{
"answer_score": 6,
"question_score": 7,
"tags": "tables, vertical alignment"
}
|
c# Selenium EdgeOptions not working for Chromium Edge
I have chromium edge version 80.0.361.69. For this, I am using Selenium.WebDriver -Version 4.0.0-alpha05. The testing software runs well but on startup, it goes to data;. I tried to get this to start at a different url using AddArguments and StartPage but neither of these have worked. Is there a way to get this to start at a different url?
|
I just updated to latest Selenium.WebDriver -Version 4.0.0-alpha07, seems like all the chrome options works for chromium edge now. Hope that helps!!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, selenium, selenium webdriver, selenium chromedriver"
}
|
How can I see the post data when I call a webapi?
Is it possible to view or debug the post sent to a webapi?
`var parameters = new List<KeyValuePair<string, string>>(); parameters.Add(new KeyValuePair<string, string>("currency", "BTC")); httpContent content = new FormUrlEncodedContent(parameters); HttpResponseMessage response = await client.PostAsync("/public/currency",content);`
I want to know what is sent, cannot figure how? Do I have to use fiddler?
This is what I try to view ----->
POST /path/script.cgi HTTP/1.0 From: [email protected] User-Agent: HTTPTool/1.0 Content-Type: application/x-www-form-urlencoded Content-Length: 32
home=Cosby&favorite+flavor=flies
Thanks
|
Fiddler is the best way to actually look at the actual HTTP Request and Responses. I use it every day for stuff like this. You can also use the built in dev tools in which ever browser you are using. If you are not familiar with the browser dev tools, I would suggest learning them. They are super handy. Check out chrome's documentation here. --<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "asp.net web api"
}
|
Adding multiple columns AFTER a specific column in MySQL
I need to add multiple columns to a table but position the columns **after** a column called `lastname`.
I have tried this:
ALTER TABLE `users` ADD COLUMN
(
`count` smallint(6) NOT NULL,
`log` varchar(12) NOT NULL,
`status` int(10) unsigned NOT NULL
)
AFTER `lastname`;
I get this error:
> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AFTER `lastname`' at line 7
How can I use AFTER in a query like this?
|
Try this
ALTER TABLE users
ADD COLUMN `count` SMALLINT(6) NOT NULL AFTER `lastname`,
ADD COLUMN `log` VARCHAR(12) NOT NULL AFTER `count`,
ADD COLUMN `status` INT(10) UNSIGNED NOT NULL AFTER `log`;
check the syntax
|
stackexchange-stackoverflow
|
{
"answer_score": 904,
"question_score": 470,
"tags": "mysql, ddl, alter table"
}
|
kernel panic not syncing: vfs :unable to mount root fs on unknown block(31,1)
I am trying to boot linux from flash on an powerpc board. In u-boot I set bootargs with:
setenv bootargs root=/dev/mtdblock1 rootfstype=ext2 rw console=ttyS0,115200 ramdisk_image=\${rd_size}
I also tried **_rootfstype=ext3_** and **_jfs2_** ; and **_root=/dev/mtdblockn_** (n from 0 to 6) and **_root=/dev/ram_** without rootfstype
The rd_size is another environment variable set to 12000.
Then each time I entered bootm with appropriate arguments, but each time I faced the error mentioned in title.
|
I used the setenv command that ltib prints at the end of building images and the error vanished. It seems that you should instruct system of size of your disk with that command.
setenv ramdisksize=90000,...
|
stackexchange-unix
|
{
"answer_score": 0,
"question_score": 0,
"tags": "boot, embedded, kernel panic, u boot"
}
|
write a text file in Python, line by line
I need to write a text file, line by line. This code is printing a text line by line, but only the last line is stored in the result.txt file.
import re
import fileinput
for line in fileinput.input("test.txt"):
new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
print new_str
open('result.txt', 'w').write(new_str)
|
1. I don't know why you need the fileinput module, `open` can handle this case as well.
2. Your for-loop goes through all lines and _overrides_ `new_str` with the new line. The last line has no next line, so it won't be overridden, so it's the only line that will get saved.
import re
test_f = open('test.txt')
result_f = open('result.txt', 'a')
for line in test_f:
new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
result_f.write(new_str)
# also, this too, please:
test_f.close()
result_f.close()
3. You should use the `with` statement to automatically close your files even when your code crashes.
import re
with open('test.txt') as test_f, open('result.txt', 'w') as result_f:
for line in test_f:
new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
result_f.write(new_str)
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "python, python 2.7"
}
|
Ruby consume array part by part
Let's say I've array with n elements. I want to take first ten elements and do something with them and then next ten and so on until array is done.
What's the right Ruby way to do it? (With c-language background I could write some for-loop and inside the loop count to ten, do stuff and set my bookkeeping variable to zero and continue main array handling..)
|
#!/usr/bin/ruby1.8
a = (1..10).to_a
a.each_slice(3) do |slice|
p slice # => [1, 2, 3]
# => [4, 5, 6]
# => [7, 8, 9]
# => [10]
end
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 3,
"tags": "ruby, arrays"
}
|
ABNewPersonViewController parentGroup issue
I'm trying to add a contact to custom created Group but contact every time is being added to the default contact list.
this is how I'm showing the controller
-(void) showNewPersonContact
{
ABRecordRef groupId=
ABAddressBookGetGroupWithRecordID(ABAddressBookCreate(), recordId);
ABNewPersonViewController *picker = [[ABNewPersonViewController alloc] init];
picker.newPersonViewDelegate = self;
picker.parentGroup=groupId;
UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:picker];
[self presentModalViewController:navigation animated:YES];
}
recordId field I'm getting from another method which returns correct recordId.How is possible to create a contact in custom group by using ABNewPersonViewController?
|
solved!
ABRecordRef groupId=
ABAddressBookGetGroupWithRecordID(ABAddressBookCreate(), recordId);
instead of `ABAddressBookCreate()` should be `picker.addressBook`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, abaddressbook"
}
|
Hazelcast semaphore via its REST API
I was wondering if it is possible (and if so how) to acquire/release an Hazelcast semaphore, more specifically a mutex, **using REST**. I found some documentation on how to use maps, queues, amongst other Hazelcast features with REST (e.g. here), but I failed to find it for concurrency features like semaphores.
Thank you for your help
|
Yes, REST client is pretty minimal and it doesn't have support for ISemaphore. See here to see it's capabilities.
If REST is the only way, you can contribute the code for an ISemaphore endpoint, or use a Java Client and expose it through a REST API on your side.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "hazelcast"
}
|
continiouty of maping from set back into itself.
Let $f: [a,b] \to [a,b]$ be continuous. Show that the equation $f(x) = x$ has at least one solution in $[a,b]$. Firstly im going to assume $x \in [a,b]$ thus a is the min and b is that max or vice versa assume the first. thus x >a and $x <b$ so we can divide the interval up into $(A=[a,x) ) \cup (B=[x,b])$ then i am going to assume that f maps the interval back onto itself but doesn't not include $f(x)=x$. thus $f(A) \cap f_{closure}(B) = \phi $ and $f(B) \cap f_{closure}(A) = \phi $ thus f is not connected so clearly $f(x)=x$
im fairly certain im supposed to use the intermediate value theorem but i don't remember it. this work?
|
If there are two points $x,y$ s.t. $f(x)\geq x$ and $f(y)\leq y$, then the intermediate value theorem will give a solution. Therefore, assume that $f(x)>x$ for all $x\in (a,b)$. Now think about what happens when $x\mapsto b$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "calculus, real analysis"
}
|
Is this a sound line of reasoning to conclude that $\sqrt[n]{n!} \sim \frac{n}{e}$?
In the paper _Decomposable Searching Problems I. Static-to-Dynamic Transformations_ by Bentley and Saxe, the authors state without proof that
$$\sqrt[n]{n!} \sim {\frac{n}{e}}\text.$$
I have a line of reasoning below that I _think_ correctly proves this, but I'm a bit shaky about whether I can apply tilde approximations this way. Is this reasoning correct?
Using Stirling's approximation, we know that
$$n! \sim \left(\frac{n}{e}\right)^n \sqrt{2\pi n}\text.$$
Taking $n$th roots then gives
$$\sqrt[n]{n!} \sim \left( \frac{n}{e} \right) \sqrt[2n]{2 \pi n} \sim \frac{n}{e}\text.$$
The step I'm uncomfortable about is whether I can take $n$th roots of both sides of the tilde expression. This feels like it "ought" to work, but I've been surprised by tilde expressions in the past and wouldn't want to bet the farm on it. :-)
|
Suppose that $a_n\sim b_n$ as $n\to +\infty$. This means, by definition, that, in particular, $$ \frac{1}{2}<\frac{a_n}{b_n}<\frac{3}{2} $$ for all sufficiently large $n$. Taking $n$th roots and using the squeeze theorem shows that $\sqrt[n]\frac{a_n}{b_n}=\frac{\sqrt[n]{a_n}}{\sqrt[n]{b_n}} \to 1$, i.e., $\sqrt[n]{a_n} \sim \sqrt[n]{b_n}$ as $n\to +\infty$.
You can apply this observation with $a_n=n!$ and $b_n=\left( {\frac{n}{e}} \right)^n \sqrt {2\pi n}$.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 4,
"tags": "discrete mathematics, asymptotics, roots, factorial"
}
|
How to use Levene's test on a data frame in R
Say I have a data frame with two columns, height (in inches) and sex (Male or Female) and I want to run levene's test to see if the variance is the same for Male and Female height. How would I do this?
I've read a few other questions here but none of them seem to address running a test from a data frame.
|
It's actually very easy. Assuming your data is in `data` and the columns are `height` and `sex`:
# load leveneTest function
library(car)
# run the levene test centered around the mean
leveneTest(data$height, data$sex, center=mean)
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 1,
"tags": "r"
}
|
How to customize whether a request follow the 302 by one okhttpclient
Currently, we only have one okhttpclient in our app, by some of our request need to intercept the original reponse and some want to follow the redirect.
we can identify the request whether it needs to redirect, but a okhttp client only has a global param to control this, how can we customize for each request?
|
You could use a network Interceptor to remove the server response’s `Location` header. If you need that data you can put it into another header like `Rewritten-Location`. Either way if the location header is absent the response will not be redirected.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "android, okhttp"
}
|
How to resolve one to many relationship in core data in iOS 4.0
I'm now developing an app on iPhone OS with core data, but when I add core data code into app, Xcode throw an error that "to-many relationship entity.relationship option requires iOS 5.0 or later"
How to deal with this problem? or is there another way to replace core data with low cost.
Some info: Base SDK :iOS 5.0 Deployment Target : iOS 4.0
Thanks
|
It's not complaining about the relationship, it's complaining about an option you've set for the relationship. Most likely, this is because you have selected the _Ordered_ option for the relationship, which is only supported in iOS 5 and above.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 4,
"tags": "ios, core data, ios4, one to many"
}
|
Fetch version number from GitHub repository
I'm having trouble fetching the current version number of my application from a text file in the repository on my GitHub account.
def version_check(self):
# Fetch version number from GitHub repo
get_version = urlopen('
#get_version.read().decode("utf-8") (No terminal output)
print(get_version.read())
print(get_version.headers['content-type'])
#if get_version.read() == version_number:
# return True
#else:
# return False
I get this terminal output:
b'1.6\n'
text/plain; charset=utf-8
How do I format the output? I believe they are bytes literals but I'm stumped on finding the solution.
|
That is a "bytes" type value. You need to call the decode function on it to turn it into a string.
myBytesVal = myBytesVal.decode('utf-8')
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, python 3.x"
}
|
Change a tag font size in relation to it's current font size
Not sure if this is actually possible to do. Is it possible to increase/decrease a specific HTML tag (h1,p,...) based on their current size; Only using CSS and HTML? **I know the JavaScript way.**
The percentage of smaller/larger will be determined by the user. it might be for instance 97%. Then it should be 97% of the font-size of the element.
Example:
CSS:
`h1 { font-size: 2rem }`
HTML:
`<h1 style="font-size: (20% larger)"></h1>`
|
From your example, CSS `var()`) and calc() could help
h1 {
--font-size: 2rem;/* set a var for your font-size. --font-size is a valid name for a CSS var() */
/* use that var() */
font-size: var(--font-size);
}
<h1 style="font-size: calc( var(--font-size) * 1.2 )">Enlarge 20%</h1>
<h1 style="font-size: 2.64rem">2.2rem x 1.2 = 2.64rem </h1>
<h1 style="font-size: var(--font-size);">2rem</h1>
<h1 style="font-size:2rem;">2rem</h1>
<h1>from the sheet</h1>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "html, css"
}
|
Github stars not showing correctly in packagist
I have recently created an open source project in github.
<
And then, I have uploaded this package to <
After that, I have made auto updating by adding web hook. Main problem is star counts are not showing correctly in packagist.
There are 10 stars in the github project but only one star is shown in packagist ? Did I missed something to setup or it's issue in packagist ?
|
If you have _just_ published < check if the issue persists in time.
The "Stars" link might have its value cached in the packagist.org page, and maybe in a few hours it will be updated.
Or it was cached at the time of publication (Jan. 4th), and would be updated only if you were to upload a new version today.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, github, composer php, packagist, git webhooks"
}
|
Can't connect to google play service
I had an android application working fine in all average smartphones, but only one client is using a custom phone from Huawei, he received this error `Can't connect to google play service`, and also `Google Maps` not working, so my question there's any way **programmatically** to send a request to download the missed google play service ?
|
You can't install Google Play Services like a normal application, since it isn't a normal application. It's actually at least 3.
It needs to be a system app (ie in `/system/priv-app/`) to work, and relies on certain other frameworks that can't simply be installed.
If this user is rooted, tell them to flash Google Play Services from something like OpenGApps or MicroG. Otherwise, if you need people without Google Services to use your app, you need to find another maps API that isn't from Google.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "android, google maps, google play services"
}
|
asp.net include pagination in dynamically generated table
I have existing client code wherein sql data reader is being used to pull records from a database and in code behind, table content is being generated as string and then assigned to a asp:literal element on the page.
Dim myreader As SqlDataReader = selectcmd.ExecuteReader
If myreader.HasRows Then
str = str & "" // str is string
While myreader.Read()
If Not IsDBNull(myreader("column1")) Then
str = str & "<tr><td align=left><font color=white>" & myreader("column1") & "</font></td></tr>"
End If
End While
// in the end string is assigned to Text attribute of asp:literal element
The client wants that pagination should be used, and that only 10 rows should be visible at a time and rest should be viewed via paging.
Can anyone suggest how this can be achieved.
Thanks.
|
Most of the time doing this sort of HTML concatenation on the server side is a very bad idea.
For your scenario, you could possibly use a SQLDataSource to feed the data to a gridview and just enable support for paging & sorting. You wouldn't have to write a single line of code to make it work, besides declaring your data source on the markup.
There's an excellent tutorial here.
If that doesn't cut it for you, you'll have to implement paging yourself by asking the database to return exactly the number of rows you want based on the current page number. In general, you'll need to use `ROW_NUMBER()` and `TOP` to page the results on the database side.
Here's an example on how to do paging on the database side.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "asp.net, paging"
}
|
Calculating Day, Month, Year
How do I calculate Day, Month, Year exactly?
Means..
From 2th Jan 1990 to 9th May 2009 is..
xxx Days, xxx Months, xxx Years.
Any idea how to do that?
I tried Timespan and Tick().. Both failed to do so..
|
You cannot do it through direct calculation (i.e. there's no "TotalMonths" or "TotalYears" property of `TimeSpan`, simply because those numbers do not make sense with arbitrary intervals of time).
Instead, you can just count the number in a loop, like so:
var dt1 = new DateTime(1990, 1, 2);
var dt2 = new DateTime(2009, 5, 9);
int years = 0;
while (dt1.AddYears(1) < dt2)
{
years ++;
dt1 = dt1.AddYears(1);
}
int months = 0;
while (dt1.AddMonths(1) < dt2)
{
months ++;
dt1 = dt1.AddMonths(1);
}
int days = (int) Math.Floor(dt2.Subtract(dt1).TotalDays);
I haven't tested this, so there might be off-by-one errors or whatever, but that's the basic idea.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "c#"
}
|
Output without new line
how can I output text to the console without new line at the end? for example:
print 'temp1'
print 'temp2'
output:
temp1
temp2
And I need:
temp1temp2
|
~~Add a comma after the last argument:
print 'temp1',
print 'temp2'
Alternatively, ~~Call `sys.stdout.write`:
import sys
sys.stdout.write("Some output")
|
stackexchange-stackoverflow
|
{
"answer_score": 37,
"question_score": 26,
"tags": "python, newline"
}
|
i need to extract this json format content using php and need to store into db
I need to extract these below content using php. Then need to store as seprate fields. Every fields need to split.
[data: {
date: 2015-08-12
}{
day: Wed,
{
TableName: title1,
{
Timing: 2-6,
Function_name: test
},
{
Timing: 4-8,
Function_name: demo
}
},
{
TableName: variable,
{
Timing: 3-8,
Function_name: dest
}
},
{
TableName: dfdf,
{
Timing: 3-7,
Function_name: gdfgdfg
}
}
}]
Thanks advance.
|
You can use json_encode function as you are passing json string and it will give you normal php array. And i don't think your posted json string is correct try validating it over here.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "php, arrays, json"
}
|
how to select those rows where x > y
Does anyone know how to select those rows where x > y, where x and y both are table columns.
$query = mysql_query("SELECT * FROM table WHERE x > '???' ");
|
To get all rows where the column `x` value is greater than that in column `y` it is this simple.
SELECT * /*BTW - Don't use *. List desired columns explicitly*/
FROM table
WHERE x > y;
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "php, sql, select, row"
}
|
Autocomplete google maps JS error
I have been trying to get the autocomplete to work with class name although since I have done that I cannot add the event listener anymore ? Anyone has got a solution to that ?
This is my code
function InitiliazeGoogleSearch() {
var input = document.getElementsByClassName('js-autocomplete');
for (i = 0; i < input.length; i++) {
autocomplete = new google.maps.places.Autocomplete(input[i]);
}
google.maps.event.addListener(autocomplete, 'place_changed', function () {
if(!$('.js-main-filter_wrapper').css('display','block')) {
$('.js-main-filter_wrapper').slideToggle();
}
});
}
|
In your loop you are re-assigning the `autocomplete` variable, but you are only attaching the listener to the last one, since it's outside the loop. To have a listener for each, you need it in the loop.
function InitiliazeGoogleSearch() {
var input = document.getElementsByClassName('js-autocomplete');
for (var i = 0; i < input.length; i++) {
autocomplete = new google.maps.places.Autocomplete(input[i]);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
if (!$('.js-main-filter_wrapper').css('display', 'block')) {
$('.js-main-filter_wrapper').slideToggle();
}
});
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -1,
"tags": "javascript, jquery, google maps"
}
|
Find shared libraries that ldd won't list?
I have a script that would run through and pull in needed shared libraries (and another that will report unused libraries), using `ldd` however certain things like the `libnss_*` items part of the `glibc` don't show up. How can I find those type of dependencies?
Thanks
|
In short: you can't.
Loading a library can be done at program initialization with hard-coded library names, and that's what ldd detects.
However, any program can also at runtime load symbols from any library, and the name of that library can be computed at run-time as well; the most obvious use case for that is plugin systems!
You hence can't know that without running the program in exactly the use case that makes it load that library (e.g., if you have say an image editor, that could decide to load a library for loading jpeg files no earlier than you actually trying to open a jpeg file).
Since knowing all libraries loaded at run time is an impossible problem, package scripts, like the .spec files needed to build rpm packages for redhat/fedora, need packagers to manually specify those dependencies that cannot be auto-detected.
|
stackexchange-unix
|
{
"answer_score": 2,
"question_score": -1,
"tags": "linux, dependencies, shared library"
}
|
How to convert UTF→CP1251 and finally to URL-encoded %CA%F3%EF%E8%F2%FC+%EA%E2%E0%F0%F2%E8%F0%F3
I have a phrase in Russian " _Купить квартиру_ ". I need to convert it to
%CA%F3%EF%E8%F2%FC+%EA%E2%E0%F0%F2%E8%F0%F3
Encoding looks like ANSI
Notice, if I **Uri.EscapeDataString(** " _Купить квартиру_ " **)** , I get
%D0%9A%D1%83%D0%BF%D0%B8%D1%82%D1%8C%20%D0%BA%D0%B2%D0%B0%D1%80%D1%82%D0%B8%D1%80%D1%83
But these strings are not equal.
Is there some correct way to convert?
|
`Uri.EscapeDataString` follows the URL spec RFC 3986, which says to use UTF-8 character encoding.
You'll need to write your own function in custom M, like this:
let
To1251URL = (input as text) as text => let
ToBytes = Binary.ToList(Text.ToBinary(input, 1251)),
ToText = Text.Combine(List.Transform(ToBytes, (b) => "%" & Number.ToText(b, "X"))),
FixSpace = Text.Replace(ToText, "%20", "+")
in
FixSpace,
Applied = To1251URL("Купить квартиру")
in
Applied
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "powerbi, powerquery"
}
|
LINQ Entity Framework Select A Record
I have a trying to select a record. In db, i have two records for Month 1 and 4.
I need to get values for both month 1 and 4, but all i get is value for month 1 both times in iteration (Month 1 and Month 4).
EX: In dB Month 1 Value is : 55 and Month 4 value is 22, but i get value 55 for both Months 1 and 4, while iteration in code.
for (var month = 1; month <= 12; month++)
{
var itemMonth = month;
var itemAuditReport = proxy.itemAuditReports.SingleOrDefault(i => i.SKU == itemSku && i.Month == itemMonth && i.Year==itemYear);
//
}
if (itemAuditReport == null)
{
// Do Something
}
Am i missing something ?
|
Yes, the keys in the Entity Framework model wasn't set properly, Sku was set as a primary key with title. in the model, hence bringing the same result set.
I changed the keys to be applied on Sku, Month and Year, and it worked great !!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, entity framework, c# 4.0, for loop"
}
|
Will this ceiling fan box replacement work in old work hole?
I have had a hanging light fixture in the middle of the living room which I now want to replace with a ceiling fan+light. Nothing huge and fancy... but a hunter nonetheless.
The old pan box was, old (complete with knob & tube which I will not be re-using):
:
?
With the oak board in the ceiling how it is, I don't really have room to use one of those hefty giant metal-bar contraptions.
|
Pictured is a random one dollar 4" octagon box.
That is acceptable for a lamp, but won't do at all for a ceiling fan box.
Since you're rewiring _anyway_ , you'd be better off to spend _a latté_ worth of cost to put a ceiling fan box here and use /3 cable from the switch. That way the next occupant has a choice about putting a ceiling fan here. Obviously the last occupant thought it was worthwhile.
|
stackexchange-diy
|
{
"answer_score": 2,
"question_score": 1,
"tags": "ceiling fan, junction box"
}
|
dev_appserver.py doesn't load appengine_config.py
I have an App Engine app running locally using `dev_appserver.py`. In the app directory I have the standard `appengine_config.py` that is supposed to execute on every request made to the app. In the past it used to execute the module, but suddenly it stopped doing it.
In another app runs on the same machine it works fine.
I checked with Process Monitor to see if the file is loaded from another location, but it's not (I can see the other app's file being loaded).
Any ideas why `appengine_config.py` is not executed?
|
I had the same problem before. Solved by changing the loading method in `app.yaml` to wsgi, for example, from:
> script: my_app/main.py
To:
> script: my_app.main.application
Let me know if it works for you.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 5,
"tags": "python, google app engine"
}
|
Creating good indexes for table
I'm working with a MariaDB (MySQL) table which contains information about some map points (latitude and longitude) and a quantity.
I'm making a lot of querys that retrieve some of this points and I want to optimize the query **using indexes**. I don't know how to do it well.
My queries are like this:
SELECT p.id, p.lat, p.lon, p.quantity
FROM Points p
WHERE ((p.lat BETWEEN -10.0 AND 50.5) AND
(p.lon BETWEEN -30.1 AND 20.2) AND
(100 <= p.quantity AND 2000 >= p.quantity))
ORDER BY p.name DESC;
So, the columns involved in the queries are: `lat`, `lon` and `quantity`.
Could anyone help me?
|
What you want here is a _spatial index_. You will need to alter the schema of your table (by turning `lat` and `lon` into a single `POINT` or `GEOMETRY` value) to support this, and use specific functions to query that value. Once you've done this, you can create a spatial index using `CREATE SPATIAL INDEX`; this index will allow you to perform a variety of highly optimized queries against the value.
There's more information on using spatial types in MySQL in the "Spatial Data Types" section of the MySQL manual.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "mysql, optimization, indexing, mariadb, database indexes"
}
|
Abstract class member variable
I have an abstract class, `CAbstract`, and want to have a member of this type in another class, `CClass`. If I make it a pointer, I will have to take care of the deleting myself, and do would like to avoid this.
* If I make it a reference, will it get deleted automatically when the `CClass` gets deleted?
* Can I make it a `shared_ptr`? Can `shared_ptr` manage abstract classes and pointing to derived classes?
|
References don't automatically deallocate anything; `shared_ptr` does. As long as you follow the rules of C++, it should handle inheritance situations gracefully. More specifically, since `shared_ptr`'s destructor calls `delete` by default when the reference count drops to zero, you need to implement the (`virtual`) destructor properly to make `shared_ptr` work.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c++"
}
|
Problem when linking c++ program with lpsolve api
I'm facing some issues when linking my c++ program, here is what I do : `g++ tp.cpp -llpsolve55 -lcolamd -ldl -o MyExe` and the command-line return me this :
`/usr/bin/ld: cannot find -llpsolve` `collect2: error: ld returned 1 exit status`
But I've already installed lpsolve, it appear in Synapatic as installed and I even installed it via the terminal
|
If `/usr/lib/lp_solve` is not in the normal search path for libraries, you can add that path to your executeable when linking. Also note that libraries should typically come last:
g++ -o MyExe tp.cpp -L /usr/lib/lp_solve -Wl,-rpath,/usr/lib/lp_solve -llpsolve55 -lcolamd
The `-L` argument adds the directory to the list of directories to look for libraries in when doing the linking.
`-Wl` tells the compiler to pass on what follows to the linker.
The linkers `-rpath,<path>` argument tells it to add `<path>` to `MyExe` so it can find the library when you later run the program.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c++, linker, g++, linear programming, lpsolve"
}
|
Add attribute to RadioButtonList input for JQuery Validation
How can I add `required` to one of the input fields which I believe is needed to enable `JQuery Valiadation` on a radio button group.
I can add `required` to the `RadioButtonList` control by doing the following
`rbSeverity.Attributes.Add("required","");`
But how can this attribute be added to one of the inputs that is generated from the `<asp:ListItem>` control?
<asp:RadioButtonList ID="rbSeverity" RepeatDirection="Horizontal" RepeatLayout="Flow"
runat="server" >
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
</asp:RadioButtonList>
|
You can do this using jQuery:
$(function () {
$('#<%= rbSeverity.ClientID %> input').attr('required', '');
});
The above code will insert all the `required` attribute to all the input inside the radio button list.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, jquery, asp.net, jquery validate"
}
|
How to get index of spsecific values in list - python
If I have a list:
A = [1,1,1,0,0,1,0]
How can I return the index of any occurence of the number 1?
With this example, how to return the following:
[0, 1, 2, 5]
This is because the number 1 appears specifically in these parts of the list
|
You can use a simple list comprehension:
A = [1,1,1,0,0,1,0]
i = [i for i,v in enumerate(A) if v==1]
[0, 1, 2, 5]
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, arrays, list, indexing"
}
|
How to make HTML5 Builder to use my own copy of Android SDK
I am using Embarcadero's HTML5Builder for Android mobile apps development. If I install `android-setup.exe`, I may deploy the HTML5Builder project to android virtual device without problem.
Next, I uninstall `android-setup.exe` and set `path` variable to add my own copy of Android SDK path. I then repeat the above steps to deploy the HTML5Builder project to android virtual device. The IDE prompt me "Android SDK not installed".
Is that possible to make H5B to use my own version of Android SDK?
|
To make Embarcadero HTML5Builder works with manual installation of `Android SDK Tools`, follow these steps:
1. Set an environment variable `Path=%Path%;[android sdk tools]\sdk\platform-tools`
2. For Windows x86, create a registry key in `HKLM\Software\Android SDK Tools\Path = [android-sdk-path]\sdk`
3. For Windows x64, create a registry key in `HKLM\Software\Wow6432Node\Android SDK Tools\Path = [android-sdk-path]\sdk`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "android, android sdk tools, html5builder"
}
|
Rails 4 - in_time_zone unexpected behavior
I am using Rails 4 trying to work with the in_time_zone helper, and can't understand the weird behavior.
When converting my timestamp to UTC in localhost (or from the console), everything works as expected:
"2016-12-05 10:00 pm".to_time.in_time_zone("UTC)
=> 2016-12-06 05:00:00 UTC # this is the correct utc time
However, on my production site, it returns an incorrect time.
"2016-12-05 10:00 pm".to_time.in_time_zone("UTC)
=> 2016-12-05 22:00:00 UTC # this is incorrect
Not sure how this is possible.. UTC should be UTC regardless. Any help understanding why this is happening would be awesome.
|
You need to tell the software what time zone you're converting _from_ , not just _to_. Since you don't, it assumes that it should convert from the system time to UTC. As it happens, it appears that the system clock on your production server is _already_ in UTC, so it doesn't change the time at all.
Since you seem to be in UTC-7, I'm guessing you're on the west coast of the United States, so you might use code like this:
ActiveSupport::TimeZone['America/Los_Angeles'].parse("2016-12-05 10:00 pm").utc
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "ruby on rails, ruby, ruby on rails 4, timezone, utc"
}
|
access iphone user settings from javascript
is there a way to access an app's iphone user default settings from javascript?
|
You could create a JS function to call from the Objective-C side that copies settings over, but there's no way for the JS layer to directly access the settings in your app.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, iphone, ios4"
}
|
Edit Html Attribute Without ID
Hello so I have this code
<div class="ic-app-header__logomark-container">
<a href=" class="ic-app-header__logomark __web-inspector-hide-shortcut__">
<span class="screenreader-only">Dashboard</span>
</a>
</div>
And I want to modify the href to be javascript:void(0) how can I do this with only class and name would I have to use
`.ic-app-header__logomark` or something?
Also I am injecting code into external site with electron and can only access css and javascript in one js file.
|
You can use `document.getElementsByClassName("ic-app-header__logomark-container")` or `document.querySelector(".ic-app-header__logomark-container")`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, html, dom, electron, inject"
}
|
cocos2d customize switch
i need to create a switch over cocos2d scene. i can create a uiswitch and add it to scene but i really interested in cocos2d switch if there is any....
can anyone give me any idea??
|
If you compile and run the cocs2d test applications included with cocos2d there are several tests that use controls like a switch or a slider. Then you can look at the test files and see how they implemented.
Best way I have been learning cocos2d is by reviewing the test apps.
Also check out these posts for several other useful resources: Need 2D iPhone graphics designed
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "cocos2d iphone"
}
|
How to re.sub european street adress to remove letters/digits
I'm working with a df where streets must be transformed into the following:
Streets:
A. Jakšto g. 2
Stumbrų g. 26A
M. K. Paco g. 19
Birželio 23-iosios g. 15
Grigiškių m. Kovo 11-osios g. 43
Laisvės pr. 87
Would need to be transformed to:
A. Jakšto g.
Stumbrų g.
M. K. Paco g.
Birželio 23-iosios g.
Grigiškių m. Kovo 11-osios g.
Laisvės pr
.
Yes, I know this isn't a place where someone could do the work for me - everything is Google'able, but I'm feeling really stuck here, even while reading the documentations ^^
|
Looks like you need to remove the last string in your text.
**Demo:**
s = """A. Jakšto g. 2
Stumbrų g. 26A
M. K. Paco g. 19
Birželio 23-iosios g. 15
Grigiškių m. Kovo 11-osios g. 43
Laisvės pr. 87"""
print("\n".join(" ".join(i.split()[:-1]) for i in s.splitlines()))
**Output:**
A. Jakšto g.
Stumbrų g.
M. K. Paco g.
Birželio 23-iosios g.
Grigiškių m. Kovo 11-osios g.
Laisvės pr.
Or using Regex.
**Ex:**
import re
s = """A. Jakšto g. 2A
Stumbrų g. 26A
M. K. Paco g. 19
Birželio 23-iosios g. 15
Grigiškių m. Kovo 11-osios g. 43
Laisvės pr. 87"""
print(re.sub(r"(\d+[A-Za-z]?)$", "", s, flags=re.M))
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, string"
}
|
Visual Studio 2003 GUI in japanese
I have an application developed in C++ in Visual Studio 2003 (Windows Forms application). My requirement is such that some of the text of the GUI of the application has to be in Japanese and some other in English. I am copping the Japanese text from the Google language tool and pasting in the main menu bar text in the form. Doing this is giving me small squares instead of actual Japanese text. However, when I am pasting thise text in a Word file, the characters are printing correctly.
How do I resolve this issue of multi-language GUI in Visual Studio 2003 (Windows Forms application)?
|
You need to use a font on your form that supports Far Eastern glyphs, such as a Shift JIS font. Check what font Word uses for the pasted text, and see if you can set your form and controls to use that same font.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "unicode, internationalization, windows forms designer, visual studio 2003"
}
|
Play Slick database error - table definition class
I have problem with creating a table definition class with Play Slick. Here is my class:
package database;
class EmployeeTableDef(tag: Tag) extends TableEmployee {
def id = columnLong
def name = columnString
def resume = columnString
def additionalInformation = columnString
override def * =
(id, name, resume, additionalInformation) <>(User.tupled, User.unapply)
}
It's simple and I did it according to the tutorial(< However I'm getting strange error: Compilation error. `{' expected but`(' found. EmployeeTableDef.java:3
and it displays that there is a problem with (tag:Tag) part. I would be grateful for your help!
Btw I am using slick 2.0.0
|
You have the wrong file extension. It's `EmployeeTableDef.scala`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "scala, playframework, playframework 2.0, slick"
}
|
Trouble understanding this Kaf HaHaim
My friend asked recently asked me an interesting Hakira in Halacha. Is it better to eat Pat Shahrit Hamosi or Pat Shahrit Mezonot and go to the Mikve (because of a lack of time)?
I started looking through some Mefarshim on the S"A where it discusses Pat Shahrit and was looking for some who allow eating Mezonot (not a Keviat Seuda). So I came across this Kaf HaHaim 155:24 which I can't really understand. I think it discusses the question, but I don't really understand what he is saying. If anyone can help me with this it would be greatly appreciated.
|
> דמדברי הש״ס משמע דבסתם פת מיירי כל שמסיר הרעבון
this translates to "from the words of the Gemara it is understood that when it says Pas, Pas = anything that takes away hunger"
Based on this eating crackers or cereal would suffice for Pas Shacharis.
Rabbi Monsour brings in the name of HaRav Bentzion Abba Shaul that one fulfills this obligation also with other baked grain products, such as a cake or a danish.
Halachically Speaking Vol 4 Issue 2 says
> However, many say one is not required to eat actual bread, and any food one eats in the morning is sufficient, as long as it is filling (Eishel Avraham Butchatch 155). Some say one should be careful to have a food that is Mezonos (Pri Megadim M.Z. 1, Kaf Ha’chaim 23, Ohr L’tzyion 2:10:6, Rivevos Ephraim 3:590:21, 35).
|
stackexchange-judaism
|
{
"answer_score": 3,
"question_score": 5,
"tags": "books generally, time, bread, mezonot beracha"
}
|
os.chdir returns No such file or directory: 'None'
How come that these lines of code creates a folder, but returns an error output?
key_ = "Test"
new_folder = os.makedirs(str(key_)+str(datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M')))
os.chdir(str(new_folder))
)
FileNotFoundError: [Errno 2] No such file or directory: 'None'
|
This seems to be the solution:
file_path = os.path.realpath(__file__)
output_files = file_path.replace('billede_indsamling.py',str(output_dir))
os.chdir(output_files)
new_folder = str(key_)+str(datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d'))
#os.mkdir(new_folder)
path = os.path.join(output_files, new_folder)
if not os.path.exists(path):
os.makedirs(path)
print("Directory '%s' created successfully" %new_folder)
elif os.path.exists(path):
os.chdir(path)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, string, directory, chdir"
}
|
How to generate UI at runtime in asp.net mvc
i am new in mvc. i want to generate a UI dynamically like
initially a table will be displayed with four columns and 5 rows. in first & second columns there will be dropdown with predefine values and in last column there will be textbox. there will be a button called add more and when user will click on that button then a postback will occur and a new row will be added to that existing column. user can remove any column just clicking on another button which will be in fourth column.
it is very easy to do it in webform with gridview but i have no idea how can i do it in mvc. i do not want to use any js library or grid rather i want to do it with html table which i will generate dynamically. please help me with concept & sample code snippet if possible. thanks
|
I cant see here something really connected with mvc.
The case is that you would like to have an interactive UI, that basically is the job of Javascript.
If we are talking about grids, it can be next plugins/frameworks:
* Kendo UI (not free for commercial use) - <
* <
* A lot of good plugings are here: Choosing a jQuery datagrid plugin?
So basically this is the same (like) Grid View from asp.net.
If you wanna have something exactly like GridView - I think there is no native implementation (from Visual Studio) for this (maybe i'm wrong, but 4 year experience say to me that i'm right :) ).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "asp.net mvc"
}
|
How to stop Unity3D Monodevelop from copying reference dlls into target directory
I have a monodevelop sln with a sub project that builds out a dll into the Assets/myplugin/ target directory.
I can not get it to stop copying the reference dlls. i.e. UnityEngine, UnityEditor.
I don't have this problem with VisualStudio on the PC. But on the Mac its driving me crazy.
How do I configure MonoDevelop to not copy reference dlls with dll i'm creating.
|
Found the answer for Visual Studio and hence MonoDevelop.
In Visual Studio on the Reference file you can right click to view the properties and select "Local Copy" = false.
Same in MonoDevelop and VisualStudio(mac).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "unity3d, monodevelop"
}
|
Umbraco Admin UI not showing Tree Nodes thumbnail
When installing an Umbraco site, I changed my umbraco admin url from '/umbraco/' to '/myadminurl/', even before I went through the install process.
Just like it's documented, I changed in the web.config the keys 'umbracoReservedPaths' and 'umbracoPath' to match my new admin url.
Installed and everything is working fine, except for one thing: All the nodes in the trees in all sections aren't showing any thumbnails. There used to be a win folder thumb before each tree node, but now it's just empty, except for the 'packages' node in the developer section, and for the recycle bin thumb.
Am I missing anything else I should had changed?
Thanks!
|
Lee Kelleher answered my question in the Umbraco forum here.
The answer is that it looks like the image reference for the tree icons are hard-coded to use the "/umbraco" path.
2 options:
1. Manually create the path to the image? The CSS is specifically looking for... /umbraco/images/umbraco/sprites.png
2. Change the reference in the CSS, (rule for ".tree.tree-umbraco li a") ... /umbraco_client/Tree/Themes/umbraco/style.css
Cheers!
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "asp.net, umbraco"
}
|
How to place a android webview in the real world using google tango?
Android webview can be used as a UI element in Android, how do I render the whole webview at a specific place using Google Tango? Currently, one can place 3D objects, sprites.
|
It is possible but not with normal Android UI out of the box
If you build your tango application using unity you can use for example this < to render the web view as part of the 3d space
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "unity3d, android webview, google project tango"
}
|
delete elements less than a given element in C++ set
I have a set in C++. I want to delete all the elements from the set which are less than a specified value. E.g.
std::set setElem;
setElem.insert(1);
setElem.insert(45);
setElem.insert(47);
//setElem contains {1,45,47}
//delete all elements less than 46 such that the set now becomes: {47}
I know we can iterate over the set and delete the elements by verifying whether they are less than 46 or not. Is there some other more efficient way in C++ to do the same.
gcc version which I am using is: gcc (Ubuntu/Linaro 4.6.4-6ubuntu2) 4.6.4
|
You can use `lower_bound()` and `erase()`
#include <set>
#include <iostream>
using namespace std;
int main()
{
set<int>setElem;
setElem.insert(1);
setElem.insert(45);
setElem.insert(46);
setElem.insert(47);
setElem.insert(50);
setElem.insert(51);
set<int>:: iterator it;
it=setElem.lower_bound(46);
//Erasing
setElem.erase(setElem.begin(),it);
//Printing
for(set<int>::iterator it1=setElem.begin(); it1!=setElem.end(); ++it1)
cout<< *it1 << "\n";
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -2,
"tags": "c++"
}
|
filter records by year
Need to filter Articles by year using created_at field.
I got the links for years in articles like this:
**Article helper:**
def artcles_by_years
Article.uniq.pluck("EXTRACT(YEAR FROM created_at)")
end
**index.html.erb**
<% for art in artcles_by_years do %>
<%= link_to art %>
<% end %>
it displays: `2009 2010 2011 2012`, sure, non-working links.
Question:
How would I build working links and query in controller to filter Articles by year, like pressing 2009 and return all articles created in 2009. Thank you.
|
You can add a scope to your model
scope :year, lambda{|year|
where(" EXTRACT(YEAR FROM created_at) = ? ", year ) if year.present?
}
And use the scope in your controller:
@articles = Article.year(params[:year])
Display link as:
<%= link_to art, articles_path( :year => atr) %>
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "ruby on rails, ruby on rails 3.2"
}
|
Find general equation for the following sequence
Given the following sequence: $$a_1 = 1, a_{n+1}=2*a_{n} + 1$$
what is the general equation for $a_n$? I couldn't find it because the sequence is not in the form of $a_{n+1} = a_n * c$ neither is it in the form of $a_{n+1} = a_n + c$, but more like a combination of the two.
|
$$ \begin{align} a_{n+1} &= 2a_{n} + 1 = 2(2a_{n-1}+1) + 1 \\\ &= 4a_{n-1} + 2 + 1 = 4(2a_{n-2} + 1) + 2 + 1 \\\ &= 8a_{n-2} + 4 + 2 + 1 = ... \\\ &= 2^na_1 + \sum\limits_{k=0}^{n-1} 2^k \end{align} $$ Using the formula for the geometric series and using the fact that $a_1 = 1$, we are able to obtain: $$ \begin{align} a_{n+1} = 2^na_1 + \sum\limits_{k=0}^{n-1} 2^k = 2^na_1 + 2^n-1 = 2^{n+1}-1 \end{align} $$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sequences and series"
}
|
How many odd coefficients will there be when expanding $(x^2+x+1)^{33}$
> How many odd coefficients will there be when expanding $(x^2+x+1)^{33}$
This question seems hard to me because of the $x^2$. I tested it out on wolfram alpha and I got $6$ odd coefficients (coefficients of $x^0 \text{, } x^1 \text{, }x^2 \text{, } x^{64} \text{, } x^{65} \text{, } x^{66}$). I tried to use logic to see the different ways of getting $x^n$ but I am unable to keep track as we can go all the way to $x^{66}$. Is there any simple and algebraic way to prove it. Thank you anyways.
|
If you know about the Frobenius Automorphism, you can work modulo 2 and write $(x^2+x+1)^{33}=(x^2+x+1)^{2^5}×(x^2+x+1)=(x^{2^6}+x^{2^5}+1)(x^2+x+1)$ and from here we see there is enough space between $1$, $2^5$ and $2^6$ so that the answer is $3×3=9$. I think you forgot some coefficients in the middle of the expression around the coefficient of $x^{32}$.
(I initially posted a comment but this is an answer after all.)
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 3,
"tags": "algebra precalculus"
}
|
Retrieve data from Account Server
I'm trying to make a game launcher in C++ and I was wondering if I could get some guidance on how to carry out this task. Basically I've created an API which outputs the account data in JSON format.
i.e `{"success":true,"errorCode":0,"reason":"You're now logged in!"}`
http_fetch("
How am I able to retrieve the data?
Sorry if you don't understand. English isn't my first language :)
-brownzilla
|
Look for a library that allows you to parse Json. Some examples:
* Picojson
* Rapidjson
Both are quite easy to use and allow you to turn json into a model that can later be used to map to your own model. Alternatively you could write your own Json parser though that would be a bit of work (reinventing the wheel perhaps).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c++, json"
}
|
Get my AD groups info from SharePoint Online App JS
How can I to get my AD groups info (Id, Name), from an app js on SharePoint Online?
Thanks.
|
You cannot do LDAP lookups with JS. However, with the Graph API, you can do CRUD operations on Azure AD Groups. JavaScript examples are included in the article.
Active Directory groups may be synchronized with Azure AD, depending on how Azure AD Connect was configured.
|
stackexchange-sharepoint
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sharepoint online, javascript, office 365, rest, azure ad"
}
|
How can I generate QR code in UWP application?
I have tried to install QrCode.net nugget package for an UWP application, but it writes the error for me:
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
are not not exists.
Does anyone know any nugget package for UWP application that helps me to create and show a QR code that generated from a string? (UWP/C#)
|
> Does anyone know any nugget package for UWP application that helps me to create and show a QR code that generated from a string? (UWP/C#)
Since you are developing an UWP app, you can use the `Zxing.Net.Mobile` package. After installed this package, to generate a barcode, you can refer to the following example:
<Image x:Name="qrcodeImg" Stretch="None" />
code behind:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var write = new BarcodeWriter();
write.Format = ZXing.BarcodeFormat.QR_CODE;
var wb = write.Write("BarCode Content");
this.qrcodeImg.Source = wb;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "c#, uwp"
}
|
A riddle about one of my favorite things :)
My source is borne upon the wing of valkyries of gold,
They work their magic summer long then winter through the cold,
Once the black and golds are done I'm plucked with careful hand,
And left to swim among the shrooms until it's time to stand,
And in that time my power grows as was the hand's intent,
Til even mighty fall like fools when my power is spent,
Though fewer know me by the days, some think I'm in the past,
My history is far from gone, it stretches wide and vast.
**What am I?**
|
Is it
> Mead
"My source is borne upon the wing of valkyries of gold,
They work their magic summer long then winter through the cold,"
> Bees make honey
"Once the black and golds are done I'm plucked with careful hand,"
> Honey collected by beekeepers
"And left to swim among the shrooms until it's time to stand,
And in that time my power grows as was the hand's intent,"
> The honey is left to ferment into mead
"Til even mighty fall like fools when my power is spent,"
> Mead gets people drunk
"Though fewer know me by the days, some think I'm in the past,
My history is far from gone, it stretches wide and vast."
> Mead was more popular historically than in the modern age
|
stackexchange-puzzling
|
{
"answer_score": 3,
"question_score": 3,
"tags": "riddle"
}
|
Prevent toFixed from rounding off very small decimal numbers
I have very small value, 0.09986684420772304, and I want to show it upto three decimals. toFixed rounds it off.
(0.09986684420772304).toFixed(3) ==> 0.100
I even tried
(Math.round(0.09986684420772304 * 100)/100).toFixed(3) => 0.100
What I need is
(0.09986684420772304).toFixed(3) ==> 0.0998
Please someone suggest me a solution
|
`(0.09986684420772304).toPrecision(3)`
or `Math.floor(0.09986684420772304 * 10000) / 10000`
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, tofixed"
}
|
get-service using powershell does not return
If I send this two-liner to Powershell
$sName = "ALG"
$service = Get-Service -computername db-name -Name $sName
I will get back information about that service on that computer. If I change the name to "db-nameXXX" (bogus name) I will get an error that the service is not found. However, I have a server that stops accepting remote-desktop sessions (I also can't connect with MS SQL Manaagement studio) and sending these commands to that machine (when in an error condition) just hangs... The script runs but never returns. I would like to have a 'time out' functionality so that at a certain point, I can output a message saying the machine is not responding. Right now, the script is not letting me do anything. I tried a start/process/end block, but as long as get-service does not come back with an error, I can't get anywhere.
|
Try something like this:
$sb = [scriptblock]::create("Get-Service -computername db-name -Name $sName")
$job = Start-Job -ScriptBlock $sb | Wait-Job -Timeout 10
if($job -eq $null) {
#timed out
}
else {
$service = Receive-Job $job
}
This will submit `Get-Service` as a job and wait for the job to finish. By setting a timeout on the job, if it fails to complete the return will be null. Do whatever error handling you need to if the value is null, or receive the job and drop the result in your `$service` variable if it completed. This will return a `Deserialized.System.ServiceProcess.ServiceController` object. Adjust `-Timeout` on `Wait-Job` to fit your needs.
|
stackexchange-serverfault
|
{
"answer_score": 6,
"question_score": 1,
"tags": "powershell"
}
|
SQL Server Remove Last Word
I have variables in a column named Tier. Please see below some examples;
Tier
Tier 1 (Unspecified)
Tier 7 (Anti-client)
Tier 3 (Priority)
I would like the variables to be transformed like the below;
Tier
Tier 1
Tier 7
Tier 3
Would you know how to efficiently remove all the strings in brackets at the end of the variables?
Thanks
Chris
|
Is this what you need?
create table #table1
(id int
,Tier varchar(100)
)
insert into #table1 VALUES
(1, 'Tier 1 (Unspecified)'),
(2, 'Tier 7 (Anti-client)'),
(3, 'Tier 3 (Priority)')
select id,
substring(tier, 1, charindex('(', tier) - 1) as Tier
from #table1
You can use `substring(tier, 1, charindex('(', tier) - 2) as Tier` if you are sure that there's a space before the bracket
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "sql server"
}
|
Javascript test string for lower case in any language
Hi I need test javascript string for any lower latters i have build next code:
var LOWER = /[a-z]/;
var lower = LOWER.test('mystring');
but If string contain any special chars from other languages this code not working. and is is logical my test is just for English latter. How to write test for any language ?
|
You can do this:
function isLowerCase(s){
return s==s.toLowerCase()
}
isLowerCase('mystring');
`toLowerCase` respects the unicode standard.
Some examples:
`isLowerCase('ä')==true`
`isLowerCase('Ä')==false`
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 2,
"tags": "javascript"
}
|
How to display tab bar in different activity in android
I have a tab bar in my application. In this I have three tabs. It will call three activities. In activities I have the list view. If I click the list view, it will call different activities other than tab activities. Can anybody tell me how to display the tab bar for other activities and give an example?
Thanks in advance
|
First, do the tutorial. Then, if you are still having problems, ask more specific questions.
Good Luck
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android"
}
|
geodesics, covering map and its lift
Followings are given problems.
* * *
Let $f:(M,g)\rightarrow (N,h)$ a covering map that is a local isometry, and let $p\in M$. If $\gamma:[0,1] \rightarrow N$ is a geodesic such that $\gamma(0)=f(p(0))$, then we can lift $\gamma$ to a geodesic $\tilde{\gamma}$:[0,1]→M a geodesic with $\tilde{\gamma}(0)=p(0)$
of course one can see that $\gamma(t)=f(p(t))$, so that $\tilde{\gamma}(t) = p(t)$ for $t \in[0,1]$
* * *
I want to prove this statement. How we can prove this?
|
A possible proof is as follows. The fact that $f$ is a covering map means that $f$ is a topological covering map (and thus a local homeomorphism), and also a local diffeomorphism and a local isometry. The theory of (topological) coverings tells us that $\gamma$ can be lifted to a continuous map $\widetilde\gamma:[0,1]\rightarrow M$, i.e. we have $f\circ \widetilde\gamma = \gamma$. Now, the fact that $f$ is a local diffeomorphism tells us that $\widetilde\gamma$ is smooth, since $\gamma$ is smooth and being smooth is a local property. Finally, the fact that $f$ is a local isometry tells us that $\widetilde\gamma$ is geodesic, since $\gamma$ is geodesic and being geodesic also is a local property.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "differential geometry, riemannian geometry"
}
|
Custom font-variation-axis being set results in Chrome not displaying font
I have a variable ttf font that I've created with one axis, optical sizing or opsz, using Glyphs 2.6.1. In Firefox 65, going to use this axis works as expected, text becomes thicker when the axis is bumped.
In Chrome 72 and Safari 12.0.3, using the axis results in the glyph not being displayed at all.
|
As of Build 1220, the patch notes of Glyphs included a note about about always including a `cvar` table.
With this addition, the font renders and respects my font variation axis in Webkit.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "css, google chrome, fonts, webkit"
}
|
click li, go to next li
Can't find a simple solution to this, I know it's easy and I've tried a few things but I can't quite get it to work. I'm currently working with a sidescrolling site and I want every time you click an image (contained in an li) it scrolls to the next li. I have jQuery plugin localscroll so it smoothly goes from one to the next, and that's working. I need to now write a code that triggers jQuery to utilize the localscroll function and go to the next li. Right now I have this, but I know it's not right:
$(document).ready(function () {
$('.wrapper ul li').click(function() {
$(this).next(li).localScroll();
});
});
|
Accoding to the ScrollTo examples, you need to do this:
$(container).scrollTo(element);
e.g.
$(document).ready(function () {
$('.wrapper ul li').click(function() {
$(window).scrollTo($(this).next('li'));
});
});
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "javascript, jquery, list"
}
|
PHP Calculating future date by adding days to a variable date
I was looking at this post, and it is close to what I need: PHP - How to count 60 days from the add date
However, in that post, the calculation is performed by adding 60 days to the current date. What I need to do is calculate the date based on a variable date ( _and not the current date_ ).
Something like this:
$my_date = $some_row_from_a_database;
$date_plus_10_days = ???;
Anyone know how to do that?
Thanks
|
You can put something before the "+10 days" part:
strtotime("2010-01-01 +10 days");
|
stackexchange-stackoverflow
|
{
"answer_score": 31,
"question_score": 10,
"tags": "php, math, date"
}
|
Корзина товаров drag n drop
Всем привет! Необходимо реализовать метод для события drop. Есть примерно такая структура:
<div class="droparea"></div>
<div class="cart__lits">
<div class="cart__item">
<p>Some content</p>
</div>
</div>
Начинаю работать с JS, мне всего лишь нужно когда элемент cart__item находится над droparea срабатывал уже написанный метод, допустим addToCart(). И когда задействую события:
document.addEventListener(`dragover`, (evt) => {
addToCart()
})
Но срабатывает этот метод по 100500 раз... Что мне делать. Уточню что карточка товара наполнена стандартным контентом, типо картинки тайтла цены, мне нужно что бы само событие срабатывало именно на главном родителе карточки. А итог падал в дроп ареа, просто вызывая определенный метод один раз, так же как мы нажимаем на кнопку. Есть идеи, а то у меня уже мыслей нет почему такая вроде простая тема не работает...
|
Событие "dragover" срабатывает каждые 100 миллисекунд, когда вы держите элемент cart_item над корзиной. В связи с этим метод срабатывает 100500 раз.
Для того, чтобы метод вызывался один раз - используйте событие "drop" вместе с "dragover".
document.addEventListener('dragover', function(event) {
event.preventDefault();
});
document.addEventListener('drop', function(event) {
event.preventDefault();
addToCart();
});
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, html5"
}
|
Installing build-essential fails in Docker
Basically I have:
FROM ubuntu:18.04
RUN apt update
RUN apt install -y software-properties-common ca-certificates wget curl ssh
RUN apt install -y build-essential
Which ends up in:
...
Get:48 bionic/main amd64 libalgorithm-merge-perl all 0.08-3 [12.0 kB]
Get:49 bionic/main amd64 libfile-fcntllock-perl amd64 0.22-3build2 [33.2 kB]
Get:50 bionic/main amd64 manpages-dev all 4.15-1 [2217 kB]
Fetched 44.2 MB in 3s (15.0 MB/s)
E: Failed to fetch 404 Not Found [IP: 91.189.88.149 80]
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?
The command '/bin/sh -c apt install -y build-essential' returned a non-zero code: 100
Are there some broken packages now?
|
Solved this by giving `--no-cache` to Docker.
|
stackexchange-askubuntu
|
{
"answer_score": 8,
"question_score": 8,
"tags": "docker, 18.04"
}
|
iOS (Swift), Realm migration add a new property to store another realm object
I ran into a strange error while trying to update the migration scheme for an existing Realm model.
Specifically, I try to update the model by adding a property which stores another realm object.
However, it doesn't matter how I try (even by trying to delete the former object and replace it with the new one), realm crashes with the following error "The `RMOHomebook.general` property must be marked as being optional"
Is there any way of doing this? Why do I need to mark the property as optional since it will never be optional.
Many thanks in advance!
|
Is `RMOHomebook.general` property `Object` subclass type? RealmSwift doesn't support making optional `Object` type properties. It is the current limitation of Realm underlying storage engine.
> to-one relationships must be optional
<
See also Realm object definitions cheatsheet. <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "ios, swift2, realm"
}
|
how to set htm with span tags in jquery
This piece of code is working fine:
$("#myp").html("Hello <b>world!</b>");
i.e. it displays in myp world in bold
but adding span style color like this:
$("#myp").html("<span style="color: #F00;">Hello </span><b>world!</b>");
is not working anymore, it does not display anything in the web page
what am I doing wrong?
|
You have to escape the quotes inside your string:
$("#myp").html("<span style=\"color: #F00;\">Hello </span><b>world!</b>");
Or use a different string delimiter:
$("#myp").html('<span style="color: #F00;">Hello </span><b>world!</b>');
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "jquery, methods, html"
}
|
Passing whether a checkbox is checked, via jQuery, to PHP
I have an AJAX call in my jQuery/PHP app. It needs to send some data to a PHP script to process (I have this part working fine).
My jQuery variable:
var form_data = {
urltitle: '<?php echo $urltitle; ?>',
subscribe: $('#subscribe').val(),
comment: $('#commentbox').val()
};
This works fine, the PHP script reads the values of all the variables - except for the 'subscribe' variable. Subscribe is a checkbox, like so:
<input type="checkbox" name="subscribe" checked="checked" value="subscribe" id="subscribe"/>
**How can I pass the 'value' of the checkbox to my PHP script?** I have a non-AJAX version of this script too, which is almost identical, except on the PHP side I use:
if (isset($_POST['subscribe'])) { /* do something */ }
And that works fine...
Thanks!
Jack
|
When you say value do you mean subscribe or do you just want to know if the checkbox has been checked or not.
If you just want to know if it has been checked then you can do `$('#subscribe:checked').val()` and if it is null then you know it is not checked and if it is not then you should have the value in your case subscribe.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, jquery, ajax"
}
|
What is the official name of the "open apps" view that is navigated to by hitting the square system button?
On Android, there are three buttons along the bottom system bar. When I hit the square one, a UI displaying all the currently "open" apps.
What is the official name of this view?
|
It's called Recents Screen:
> The Recents screen (also referred to as the Overview screen, recent task list, or recent apps) is a system-level UI that lists recently accessed activities and tasks.
|
stackexchange-android
|
{
"answer_score": 8,
"question_score": 5,
"tags": "system, user interface"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.