source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0013672743.txt"
] | Q:
EventSource / Server-Sent Events through Nginx
On server-side using Sinatra with a stream block.
get '/stream', :provides => 'text/event-stream' do
stream :keep_open do |out|
connections << out
out.callback { connections.delete(out) }
end
end
On client side:
var es = new EventSource('/stream');
es.onmessage = function(e) { $('#chat').append(e.data + "\n") };
When i using app directly, via http://localhost:9292/, everything works perfect. The connection is persistent and all messages are passed to all clients.
However when it goes through Nginx, http://chat.dev, the connection are dropped and a reconnection fires every second or so.
Nginx setup looks ok to me:
upstream chat_dev_upstream {
server 127.0.0.1:9292;
}
server {
listen 80;
server_name chat.dev;
location / {
proxy_pass http://chat_dev_upstream;
proxy_buffering off;
proxy_cache off;
proxy_set_header Host $host;
}
}
Tried keepalive 1024 in upstream section as well as proxy_set_header Connection keep-alive;in location.
Nothing helps :(
No persistent connections and messages not passed to any clients.
A:
Your Nginx config is correct, you just miss few lines.
Here is a "magic trio" making EventSource working through Nginx:
proxy_set_header Connection '';
proxy_http_version 1.1;
chunked_transfer_encoding off;
Place them into location section and it should work.
You may also need to add
proxy_buffering off;
proxy_cache off;
That's not an official way of doing it.
I ended up with this by "trial and errors" + "googling" :)
A:
Another option is to include in your response a 'X-Accel-Buffering' header with value 'no'. Nginx treats it specially,
see http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering
A:
Don't write this from scratch yourself. Nginx is a wonderful evented server and has modules that will handle SSE for you without any performance degradation of your upstream server.
Check out https://github.com/wandenberg/nginx-push-stream-module
The way it works is the subscriber (browser using SSE) connects to Nginx, and the connection stops there. The publisher (your server behind Nginx) will send a POST to Nginx at a corresponding route and in that moment Nginx will immediately forward to the waiting EventSource listener in the browser.
This method is much more scalable than having your ruby webserver handle these "long-polling" SSE connections.
|
[
"joomla.stackexchange",
"0000013712.txt"
] | Q:
Two reversed conditions in one onAfterDispatch() plugin function
In my system plugin, I use the following condition
class PlgSystemMyPlugin extends JPlugin
{
public function onAfterDispatch()
{
$uri = JFactory::getURI();
$current_url = $uri->toString();
if(strpos($current_url,'?mykey') === false) {
return true;
}
// some event that is being executed when url HAS ?mykey
}
}
It works perfectly. But I need one more event that will be executed under reversed condition i.e. when url has no ?mykey
I try
class PlgSystemMyPlugin extends JPlugin
{
public function onAfterDispatch()
{
$uri = JFactory::getURI();
$current_url = $uri->toString();
if(strpos($current_url,'?mykey') === false) {
return true;
}
// some event that is being executed when url HAS ?mykey
if(strpos($current_url,'?mykey') !== false) {
return true;
}
// some event that is being executed when url HAS NO ?mykey
}
}
but it doesn't work and it looks like an incorrect statement
A:
Seeing as the URL can either have or not have ?mykey, surely you can use an else condition can't you?
Like so:
if(strpos($current_url,'?mykey') !== false)
{
// URL has ?mykey
// Do some fancy code here
// You've finished what you need to do, so stop anything else
return true;
}
else
{
// URL doesn't have ?mykey
// Do some fancy code here
// You've finished what you need to do, so stop anything else
return true;
}
|
[
"math.stackexchange",
"0001909044.txt"
] | Q:
Showing upper semicontinuity of a function
Let $F$ be holomorphic in the strip $S := \{ z \in \mathbb{C} : 0 < \mathrm{Re} z < 1\}$ and continuous on its closure $\overline{S}$. Further define
$\displaystyle h(z) := \frac{1}{\pi i} \log \left( i \frac{1 + z}{1 - z}\right)$
for $\vert z \vert \leqslant 1$ and $z \neq \pm 1$ ($\log$ denotes the branch of the logarithm, where $\log 1 = 0$). Why exactly is $\log \vert F \circ h\vert$ upper semicontinuous for $\vert z \vert \leqslant 1$ and $z \neq \pm 1$?
A:
It is, because we can choose a continuous branch of the logarithm and since the composition of a upper semicontinuous function with a continuous function is upper semicontinuous, we are done.
|
[
"stackoverflow",
"0025474863.txt"
] | Q:
C: Convert array to RGB image
In C, I have a 1D array of unsigned chars (ie, between 0 to 255) of length 3*DIM*DIM which represents a DIM*DIM pixel image, where the first 3 pixels are the RGB levels of the first pixel, the second 3 pixels are the RGB levels of the second pixel, etc. I would like to save it as a PNG image. What is the easiest, most lightweight method of doing this conversion?
Obviously OpenGL can read and display images of this form (GLUT_RGB), but DIM is larger than the dimensions of my monitor screen, so simply displaying the image and taking a screenshot is not an option.
At the moment, I have been doing the conversion by simply saving the array to a CSV file, loading it in Mathematica, and then exporting it as a PNG, but this is very slow (~8 minutes for a single 7000*7000 pixel image).
A:
There are many excellent third party libraries you can use to convert an array of pixel-data to a picture.
libPNG is a long standing standard library for png images.
LodePNG also seems like a good candidate.
Finally, ImageMagick is a great library that supports many different image formats.
All these support C, and are relatively easy to use.
|
[
"stackoverflow",
"0050289374.txt"
] | Q:
New Google Maps Platform - How do I set my own usage limits?
In their notifications about the new billing system for the Google Maps APIs, Google very clearly state that you "can set usage limits to protect against unexpected increases". However, I haven't found any documentation regarding how to set these usage limits against an API key. Does anyone know how to do this?
To clarify, I would like to set my own daily usage limits against my API key to prevent it ever going over the free threshold for the static maps API.
A:
I understand Google means that you can set your custom daily quota for each individual API in order to stay within free 200$, not a global per API key/project/Billing account daily quota. As far as I know there is no such thing as limit per daily usage in $ per Billing account yet.
There are alerts that you can establish in your Billing account and receive notifications if your usage is close to the defined budget. Have a look at the following document that explain how to set alerts:
https://cloud.google.com/billing/docs/how-to/budgets?hl=en
If your project uses only Static Maps API, it is easy to set daily quota to stay within 200$ per month. The price sheet says that you can have up to 100 000 free requests per month. That means 100 000 / 31 = 3225 free requests per day. You can go to Quota section of Static Maps API in your project
https://console.developers.google.com/google/maps-apis/apis/static-maps-backend.googleapis.com/quotas?project=YOUR_PROJECT_ID&duration=PT1H
and change your daily quota as shown in my screenshots
edit number requests per day
and you are set.
I hope this helps!
|
[
"math.stackexchange",
"0001085984.txt"
] | Q:
Newton's method convergence criteria
To use Newton's method on interval $[a,b]$ we need to guarantee that
$f(a)f(b)<0$ on the interval which is true for $[0,1]$.
$f'(x)$ and $f''(x)$ are continuous on the interval $[a,b]$ (which they are)
$f'(x) \neq 0$ on $[a,b]$ and $f''(x)$ does not change signs on $[a,b]$
Then if $f(x_{0})f''(x_{0})>0$ the method will converge.
I have the following exercise in my textbook and I don't understand a part of the solution:
Using Newton's method and starting approximation $x_{0} = 1$ find the root of the equation $$f(x)=e^{x}-\sin(x)-1.5$$
Given solution:
$$f'(x) = e^{x}-\cos(x)$$
$$f''(x) = e^{x}+\sin(x)$$
$f'(x)$ and $f''(x)$ are both positive on the given interval, we can therefore use it.
We verify that $f(0)f''(0)>0$ and then start the algorithm itself.
My questions for this part of the solution:
How can I determine what are the function values for a function like $f'(x)$ or $f''(x)$? Is it possible to graph them by hand?
$f'(x)=0$ for $x=0$ which seems to be in contradiction with the convergence criteria. Is the solution right?
Thanks.
A:
I don't understand what you mean by your first question. If you know the explicit form, simply compute it. Otherwise, note that $e^x > 1$ for $x > 0$ and observe that $\cos x$ is bounded above by $1$. Therefore, $f'(x)$ must be positive over the positive reals. The same argument holds for $f''(x)$.
For your second question, since $f(0) = -0.5$, and $f(x)$ is continuous, we know that there is a neighborhood around $0$ where $f$ does not have a root. So consider an interval $[\epsilon, 1]$. That elides the problem in your first derivative criterion.
|
[
"stackoverflow",
"0046209488.txt"
] | Q:
Python for loops and if statements
I am trying to write a function which uses a for loop to iterate through a list of integers and return True if there are two 2's next to each other on the list, and False otherwise. For example, when I call it with print(has22([1, 2, 2])), it should return True . I am new to Python so here is what I have so far, I am unsure of what to put after and to specify that I want it to check the next iteration to see if it is a 2 as well. Any help is appreciated.
def has22(nums):
"""Checks a list for two 2's"""
for num in nums:
if num == 2 and
return(True)
else: return(False)
A:
You can use built in any() to check for two consecutive twos as the following:
def has22(nums):
return True if any(nums[i] == 2 and nums[i+1] == 2 for i in range(len(nums)-1) else False
Alternatively, you can modify your for loop to the following:
def has22(nums):
for i in range(len(nums)-1):
if nums[i] == 2 and nums[i+1] == 2:
return True
return False
|
[
"stackoverflow",
"0037024610.txt"
] | Q:
How to implement navigation drawer with viewpager(having 3 tabs) in a single activity using material design?
I am new to android.I am trying to implement navigation drawer with viewpager and here the viewpager contains tablayout with three tabs in a single activity. I dont know how to do this. Do provide me proper solutions and also give some knowledge of how to do this.
A:
You can follow this tutorial for your requirement this will produced like given image.
As you mentioned you are beginner to android then i suggest you follow complete tutorial.
Here is the Link
|
[
"stackoverflow",
"0003027033.txt"
] | Q:
How much storage space does the following take up?
int 72
It's a question in our discussion in a C# class. I said 2 bytes, others said it uses 32 bits or 4 bytes due to the integer type. Which is correct?
A:
You need to be a lot more specific. Are you wondering about:
the size of a variable in memory holding that value
the size of the MSIL to load that value into the IL stack so it can be used in an expression
the size of the MSIL to declare a local variable capable of holding the value
the size of the MSIL to declare a member variable capable of holding the value
the size of the machine language produced from the MSIL by the runtime
the size of the metadata and debug information associated with it
something else?
There are a lot of different "costs" associated with the appearance of an integer literal such as (int)72 appearing in a program. If it's part of a larger expression, simplification may occur at compile time such that the marginal runtime cost of the literal is nothing at all (except for the debugger to display the longer snippet of source code).
|
[
"superuser",
"0000170644.txt"
] | Q:
How to give out the internet from PC(win xp) via wireless-router(dlink dir320)?
I have a dlink dir320 router(dd-wrt firmware) and a PC(winxp) that have the internet connection via usb modem. How to install it to give the internet on a few wi-fi devises?
A:
Make sure you have a working network card and that internet connection sharing is enabled on your windows xp machine. Then connect your xp machine's network card to the WAN port on your wireless router. You should set up the network card on the windows machine to use a static internal IP (something in the 192.168.x.x or 10.x.x.x range) and set up the router to also have a static IP that is different from the xp machine but on the same subnet.
|
[
"stackoverflow",
"0051597778.txt"
] | Q:
Uncaught SyntaxError: Unexpected token for while adding data to pieChart dynamically
i have imbrecated json objects, i am struggling with this error when i try to loop inside PieData to fill pieChart this is my code
var PieData = [
for(b in quizs[i].quests[j].reps){
//quizs[i].quests[j]["quizId"]
/* if(quizs[i].quests[j].reps[b]["stat"]==null){
var l = 1;
}
else{
var l =quizs[i].quests[j].reps[b]["stat"]
}*/
{
{%set h = 'hex'%}
value : 2,
startAngle: 240,
color : '{{h}}',
label : quizs[i].quests[j].reps[b]["rep"]
}, }
];
when i if i try to change to static for => for (var r = 0; r < 2; r++) {
i always get the same error, any help is appreciatred
A:
You can't use for in array declaration.
var PieData = [];
for (var b in quizs[i].quests[j].reps) {
PieData.push({
value: 2,
startAngle: 240,
color: "{{h}}",
label: quizs[i].quests[j].reps[b]["rep"]
});
}
Array#map will looks cleaner here
var PieData = quizs[i].quests[j].reps.map(i => ({
value: 2,
startAngle: 240,
color: "{{h}}",
label: i.rep
}));
|
[
"stackoverflow",
"0050708180.txt"
] | Q:
Click listener inside OnBindViewHolder
I have the following code for the recyclerview adapter for an android app that I'm working on right now:
@Override
public void onBindViewHolder(final FeedViewHolder contactViewHolder, final int i) {
final FeedInfo ci = feedInfoList.get(i);
//Set the text of the feed with your data
contactViewHolder.feedText.setText(ci.getFeed());
contactViewHolder.surNameText.setText(ci.getSurName());
contactViewHolder.nameText.setText(ci.getFirstName());
contactViewHolder.feedDate.setText(ci.getDate());
contactViewHolder.numberOfGoingText.setText(ci.getNumber_of_going());
contactViewHolder.numberOfInterestedText.setText(ci.getNumber_of_interested());
//seteaza fotografia de profil in postare
new ProfilePictureDownloadImage(contactViewHolder.profilePicture).execute(ci.getProfileImageURL());
ImageButton interestedButton = contactViewHolder.interestedButton;
interestedButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = i;
FeedInfo fi = feedInfoList.get(position);
int displayedNumberOfInterested = Integer.parseInt(ci.getNumber_of_interested()) + 1;
contactViewHolder.numberOfInterestedText.setText(Integer.toString(displayedNumberOfInterested));
System.out.println("emilutzy interested from within" + fi.getPostID());
contactViewHolder.surNameText.setText("kk");
}
});
}
The problem is the click listener. In theory the button I press should increment the number right next to it. However, since I have to declare onBindViewHolder's arguments as final, only the first click works, the rest of the clicks do not change the value of the number. I am new to Android, so could you please help me find a better solution?
A:
There's a nice method called getAdapterPosition() that you can use in your RecyclerView's ViewHolder.
Instead of setting the click listener in onBindViewHolder, set it in the constructor of your ViewHolder like so:
public class FeedViewHolder extends RecyclerView.ViewHolder {
private TextView feedText;
private TextView surNameText;
private Button interestedButton;
// ... the rest of your viewholder elements
public FeedViewHolder(View itemView) {
super(itemView);
feedtext = itemView.findViewById(R.id.feedtext);
// ... find your other views
interestedButton.setOnClickListener(new View.OnClickListener() {
final FeedInfo fi = feedInfoList.get(getAdapterPosition());
int numInterested = Integer.parseInt(ci.getNumber_of_interested()) + 1;
// setting the views here might work,
// but you will find that they reset themselves
// after you scroll up and down (views get recycled).
// find a way to update feedInfoList,
// I like to use EventBus to send an event to the
// host activity/fragment like so:
EventBus.getDefault().post(
new UpdateFeedInfoListEvent(getAdapterPosition(), numInterested));
// in your host activity/fragment,
// update the list and call
// notifyDatasetChanged/notifyDataUpdated()
//on this RecyclerView adapter accordingly
});
}
}
Don't set your position in onBindViewHolder to final (Android Studio will warn you why).
|
[
"stackoverflow",
"0016161742.txt"
] | Q:
How to print white text with black background image
I am trying to print white text with black background image, but it is working only when we enable "Print Background (Colors & Image). Is there any way to enable this through jquery or other work around to fix this problem. Here is my sample code.
<script type="text/javascript">
$(function () {
var print = $('.printButton');
print.bind('mousedown', function () {
$('.FirstName').attr("style", "background: transparent !important;color:#FFEFD5;-webkit-print-color-adjust: exact;");
window.print();
});
});
</script>
<div >
<div >
<asp:Image runat="server" ID="imgIO" ImageUrl="/css/Images/Img-Black.jpg" />
</div>
<div class="FirstName">Hello</div>
</div>
<div>
<div class="printButton">
<asp:Button runat="server" ID="Button2" />
</div>
</div>
.FirstName {
color: #eee;
font-size: 11px;
font-weight: bold;
position: absolute;
top: 15px;
left: 72px;
}
.printButton {
margin: 0 -3px 0 0;
float: right;
font-family: Arial;
direction: ltr;
}
I verified this link Can I force text to print as white? already, but I am unable to find the solution.
Can anyone help me to sort this issue.
Many Thanks
Anna
A:
A workaround: Generate an image on the fly. Image generation is quite simple in the server and relatively cheap too. Think captcha but with your colors, fonts, chosen text etc etc.
Should not be too big of a challenge to generate even from dynamic text. Animations will be harder, but possibly doable and if you are printing it anyway, derp!
|
[
"tex.stackexchange",
"0000314386.txt"
] | Q:
Clickable cross-references to deduction labels
I'm using the package proof for drawing deductions. The package supports labels. However, I'd like to have clickable cross-references to them. Is this possible? Note that I want the label to be a custom text, not a number. The package doesn't seem to have inbuilt support for cross-references (neither clickable nor non-clickable). Neither does the seemingly more comprehensive bussproof. Below's an example of intended use:
\documentclass{llncs} %or {article}
\usepackage{proof} %\infer
\begin{document}
\[
\infer[\mbox{mylabel}]{a : A}{a ~\mbox{exists}}
\]
As %\intendedrefto{mylabel} shows, ...
\end{document}
A:
You can set the reference text yourself, since \label uses the current definition of \@currentlabel:
\documentclass{article}
\usepackage{proof}
\makeatletter
\newcommand{\labelthis}[2]{%
\def\@currentlabel{#2}\label{#1}#2%
}
\makeatother
\begin{document}
\[
\infer[\mbox{\labelthis{ml}{mylabel}}]{a : A}{a ~\mbox{exists}}
\]
As \ref{ml} shows, ...
\end{document}
If you are also using amsmath, you need to use \ltx@label instead of \label
\makeatletter
\newcommand{\labelthis}[2]{%
\def\@currentlabel{#2}\ltx@label{#1}#2%
}
\makeatother
|
[
"stackoverflow",
"0052680922.txt"
] | Q:
How to upload files with php the right way?
So I have been working on this school project for about a week now and then came across an instance where I had to implement a user registration form where it is supposed to submit the user info as well as the user profile image whose path is to be stored in the DB as well. The drawback is I can't seem to get the upload script working. I have watched tens of tutorials and read like 15 solutions to similar problems from this very platform but still to no avail. I have also made sure that the php.ini file has the file_upload setting turned on.
HERE IS MY HTML FORM
<form style="padding: 1em;" class="ui form small inverted raised segment" action="signup.php" method="POST" enctype="multipart/form-data">
<h4 class="ui dividing header">Background Information</h4>
<div class="field">
<div class="three fields">
<div class="field">
<input type="text" name="fname" placeholder="Firstname" required>
</div>
<div class="field">
<input type="text" name="mname" placeholder="Other name">
</div>
<div class="field">
<input type="text" name="lname" placeholder="Lastname" required>
</div>
</div>
</div>
<div class="field">
<div class="two fields">
<div class="field">
<select name="gender">
<option value="">Select Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
</div>
<div class="field">
<input type="date" name="dob" required>
</div>
</div>
</div>
<div class="ui dividing header">Contact Information</div>
<div class="field">
<div class="two fields">
<div class="field">
<input type="tel" name="phone" placeholder="Mobile phone number" required>
</div>
<div class="field">
<input type="email" name="email" placeholder="Email address" required/>
</div>
</div>
</div>
<div class="field">
<div class="three fields">
<div class="field">
<input type="text" name="area" placeholder="Area/Village" required>
</div>
<div class="field">
<input type="text" name="trad_auth" placeholder="T/A or STA">
</div>
<div class="field">
<select id="district" name="kasungu">
<option value="Kasungu">Kasungu</option>
</select>
</div>
</div>
<div class="ui dividing header">Work Details</div>
<div class="field">
<div class="two field">
<div class="field">
<select id="department" name="department">
<option value="">Select Department</option>
</select>
</div>
</div>
</div>
<div class="ui dividing header">Acc Authentication Details</div>
<div class="field">
<input type="text" name="activation-code" placeholder="Enter admin authentication code (XXX-XXXX-XXXX)" required/>
</div>
<div class="field">
<div class="two fields">
<div class="field">
<input type="password" name="pass1" placeholder="Create Password" required/>
</div>
<div class="field">
<input type="password" name="pass2" placeholder="Confirm Password" required/>
</div>
</div>
</div>
<div class="ui dividing header">Upload Image</div>
<div class="field">
<div class="two fields">
<div class="field">
<input type="file" style="display: none;" id="pic" name="image"/>
<a type="button" id="upload" class="ui button fluid negative mini"><i class="icon camera"></i></a>
</div>
</div>
</div>
<div class="three fields">
<div class="field"></div>
<div class="field">
<button type="submit" name="submit" class="ui fluid mini positive button">
Signup <i class="icon user"></i>
</button>
</div>
<div class="field"></div>
</div>
<div>
<?php
if(!empty($errorMsg)){
echo $errorMsg;
}
?>
</div>
</div>
</form>
HERE IS MY PHP FUNCTION WHICH RECEIVES THE FILE['image'] A PARAMETER.
<?php
function uploadFile($file){
$newName;
if(isset($file)){
$file_name = $file['name'];
$file_tmp_loc = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$ext = strtolower(end(explode('.', $file_name)));
$allowed = array('jpg','jpeg','png','gif');
if(in_array($allowed, $allowed)){
if($file_error == 0){
if($file_size > 3000000){
$file_name_new = uniqid('',true).".".$ext;
$destination = '../images/users/';
$destination = $destination.$file_name_new;
if(move_uploaded_file($file_tmp_loc, $destination)){
$newName = $destination;
}else{
echo "<h1>Failed to move uploaded file</h1>";
}
}
}else{
echo "file upload failed. ".$file['error'];
}
}else{
echo "Type not allowed!"; }
}
}
return $newName;
?>
In my other PHP script, I am calling the function like this:
<?php
$fileName = uploadFile($_FILE['image']);
?>
an then stores the returned new name as its reference in the MySQL DB
A:
You have to use the $_FILES when you receiving file and in first array mean $_FILES['the file name which you have mentioned in Input files by Name like name='abc' '] and second array is all about file name, size, error,location. you can also see this by using print_r($_FILES['image']);
<input type="file" style="display: none;" id="pic" name="image"/>
$file_name = $_FILES['image']['name'];
$file_tmp_loc = $_FILES['image']['tmp_name'];
$file_size = $_FILES['image']['size'];
$file_error = $_FILES['image']['error'];
So correct it!
Cheer you!
|
[
"stackoverflow",
"0030187242.txt"
] | Q:
"Mobile first" or last from a breakpoint perspective?
"Mobile first" is recommended, I know.
However, I understand this to be because of the progressive enhancement principle.
But when I build a simple site, where I am just scaling/re-arranging items to fit better and have better legibility on smaller devices, can I not just as well start with the desktop design and work my way down to mobile?
A:
It's near impossible to design something perfectly for every possible screen. The basic "breakpoint" as you put it has always been to determine what the client needs, and what they expect. Presently, most clients need a site that meets some basic mobile requirements or at least has a few mobile-friendly pages, even if deeper content is still in a desktop format. There is no one fixed answer for this. However, you should probably be conceptualizing how your design will work in both formats and trying to minimize the amount of rewriting you'll need to do from one to the other, by keeping the layouts as fluid as possible.
|
[
"unix.stackexchange",
"0000155286.txt"
] | Q:
Keychain SSH Key Manager prevents SFTP login on CentOS
I installed keychain and added this to my .bashrc in CentOs to help manage my SSH Keys:
/usr/bin/keychain --clear $HOME/.ssh/id_rsa
source $HOME/.keychain/$HOSTNAME-sh
So on SSH login I am prompted to enter the key's password which will endure until reboot or session termination.
While this is enabled any SFTP login attempts are then halted at authentication. How can I leave keychain support enabled while disregarding for SFTP logins? Is this possible? I don't want to have to enable/disable when I need to do things.
A:
It looks like your login shell is bash, and your SSH server is configured to invoke your login shell to run the SFTP server.
You can set up sshd to run the SFTP server directly by putting a line like the following in /etc/sshd_config:
Subsystem sftp /usr/lib/openssh/sftp-server
or
Subsystem sftp internal-sftp
You can also fix the problem by changing your .bashrc. This has the side benefit of also fixing problems with other non-interactive uses of ssh, such as scp, rsync, etc. There is a design bug in bash: it loads .bashrc for interactive non-login shells, and for non-interactive remote login shells, even though the two situations have absolutely nothing in common. Add a guard at the top of your .bashrc to ignore the rest of the file in a non-interactive setting:
[[ $- = *i* ]] || return
|
[
"stackoverflow",
"0041441074.txt"
] | Q:
TFS 'Powershell on Target Machines' task for machines in different AD domain
We want to utilize TFS release management for our deployments. We have several environments (dev, qa, staging, prod). Each of them in separate AD forest. Build machine also resides in separate forest. No trust between them.
I set up target machines to accept CredSSP authentications for PS remoting. I was able to enter PS session on target machine from build machine. But no luck from TFS task 'Powershell on Target Machines'.
Here how my tasks looks in TFS:
TFS PS on Target Machines task
In logs:
2016-12-30T15:04:11.0279893Z System.Management.Automation.Remoting.PSRemotingTransportException: Connecting to remote server app.dev.local failed with the following error message : WinRM cannot process the request. The following error with errorcode 0x80090322 occurred while using Negotiate authentication: An unknown security error occurred.
Is there any way to make TFS run PS on target machines that resides outside of build machine AD domain?
AD trust doesn't look like an option. And without proper PS remoting it doesn't look like release management can provide much value for us.
A:
TL;DR;
No, you have two options.
Setup one way trust between your primary domain ans all of your sub domains so that your production domain credentials can be used on all of your sub domains.
use shadow accounts to allow cross domain authentication. These are local accounts with the same username and password across machines that allows auth. This is the official MSFT work around for non trust domain auth.
The long answer
Other than that, since you are well off the supported happy path, you would need to implement your own custom tasks that facilitated the cross domain authentication that you want. Should be a fairly simple task to implement your own tasks in PowerShell.
https://www.visualstudio.com/en-us/docs/integrate/extensions/develop/add-build-task
The reality is that there are only a few limited senarios that you need a "test AD" environment and it is never correct to have domains for Dev, QA, or Staging. AD is not designed that way and I have never seen it work for the benefit of the organisation or the development efforts. It is a product of over paranoid sysadmins and it is a lost cause.
The only reason to have a permanent additional domain is for your sysadmins to test their domain changes and configurations.
For software development projects that actively change AD, or require specific setups for testing, you would dynamically create your test domain along with the test machines required. That is how you create valid and repeatable tests against a Domain.
|
[
"stackoverflow",
"0029560413.txt"
] | Q:
Redirection of a url using parameter
I am trying to one URL with parameter to another url which doesn't have parameter.
I have written below things in apache conf file:
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/abc/others_jp$
RewriteCond %{QUERY_STRING} ^utm_source=facebook_jp&utm_medium=social&utm_campaign=2014_Facebook_contents&utm_term=other_facebook&utm_content=bridal$
RewriteRule ^(.*)$ http://www.others.com/campaign/link-to-love-2015 [R=302,L]
When i tried, it shows like
http://www.others.com/campaign/link-to-love-2015?utm_source=facebook_jp&utm_medium=social&utm_campaign=2014_Facebook_contents&utm_term=other_facebook&utm_content=bridal
Here I don't want to include the query string in redirected URL.
A:
Just add a ? to the rewrite, that will truncate the query string:
RewriteRule ^(.*)$ http://www.others.com/campaign/link-to-love-2015? [R=302,L]
|
[
"dba.stackexchange",
"0000018769.txt"
] | Q:
Schema qualification necessary for query plan reuse?
While reading this article about Plan Caching in SQL server, I came across a tidbit I was unaware of:
... for reuse it is necessary that the objects that the batch references do not require name resolutions. For example, Sales.SalesOrderDetail does not require name resolution, whereas SalesOrderDetail does because there could be tables named SalesOrderDetail in multiple schemas. In general, two-part object names (that is, schema.object) provide more opportunities for plan reuse.
I'm looking for some clarification about how important it is to use two-part object names, since "In general, two-part object names provide more opportunities for plan reuse.", yet it starts by saying it's necessary.
More specifically, most of the stored procedures I deal with are in the dbo schema and reference only dbo objects, without specifying the dbo prefix. Are these prevented from reusing cached query plans, even with everything using the default schema?
A:
For a plan to be reused all of the attributes in sys.dm_exec_plan_attributes where is_cache_key=1 must be the same. A list of these is below.
acceptable_cursor_options
compat_level
date_first
date_format
dbid
dbid_execute
is_replication_specific
language_id
merge_action_type
objectid
optional_clr_trigger_dbid
optional_clr_trigger_objid
optional_spid
required_cursor_options
set_options
status
user_id
The one affected by using two part names is user_id
If you try the following under the credentials of a user with default schema dbo
DBCC FREEPROCCACHE;
CREATE TABLE dbo.FooBar(X int);
EXEC('SELECT * FROM FooBar');
EXEC('SELECT * FROM FooBar');
EXEC('SELECT * FROM dbo.FooBar');
EXEC('SELECT * FROM dbo.FooBar');
And then execute the following query
SELECT usecounts,
text,
value AS [user_id]
FROM sys.dm_exec_cached_plans
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
CROSS APPLY sys.dm_exec_plan_attributes(plan_handle) AS epa
WHERE text LIKE 'SELECT * FROM %FooBar' and attribute='user_id'
You will see the following results
usecounts text user_id
----------- ----------------------------------- -------
2 SELECT * FROM dbo.FooBar -2
2 SELECT * FROM FooBar 1
This shows that both plans got re-used when the identical statement got run for the second time. The docs for sys.dm_exec_plan_attributes explain for the user_id
Value of -2 indicates that the batch submitted does not depend on
implicit name resolution and can be shared among different users. This
is the preferred method. Any other value represents the user ID of the
user submitting the query in the database.
This appears to be incorrect! It seems from my testing that the value it actually uses for the user_id in the second case is the schema_id of the default schema for the executing user rather than an identifier for that specific user. Running the four EXEC statements again under a different login with default schema "dbo" gives.
usecounts text user_id
----------- ----------------------------------- -------
4 SELECT * FROM dbo.FooBar -2
4 SELECT * FROM FooBar 1
Showing the plans for both versions of the query were able to be re-used between users. Finally running the four EXEC statements again under a third login with default schema "guest" gives.
usecounts text user_id
----------- ----------------------------------- -------
6 SELECT * FROM dbo.FooBar -2
4 SELECT * FROM FooBar 1
2 SELECT * FROM FooBar 2
Showing that the plan for the dbo qualified query was successfully shared between the users with different default schemas but the non schema qualified query needed a new plan compiled.
If you don't see this sharing happening ensure that all logins you are testing have the same set_options,language_id, date_first,date_format as these are among the cache keys listed at the beginning and any differences in those will prevent the plans being reused between sessions.
|
[
"gamedev.stackexchange",
"0000022071.txt"
] | Q:
What are the requirements for a sound file in android?
I am creating a game in Android and eventually I am going to outsource the sound effects. I have a few place holder sounds for testing and I have noticed a problem. I have an OGG sound file which plays correctly through the emulator/headphones but when I put it on my phone it doesn't play. Putting my ear right up to the speaker I can hear a faint crackle.
So what are the requirements for a mobile sound file? Frequency, format, etc.
A:
Are you using android.media.SoundPool or another library?
Core Media Supported formats: http://developer.android.com/guide/appendix/media-formats.html
Peter Drescher on implementing sound in Android games via FMOD:
http://broadcast.oreilly.com/2011/06/fmod-for-android.html
http://www.twittering.com/
He also did a presentation at the most recent AES convention in NY where he showed the equivalent implementation of FMOD vs Android for the Vector Pinball game, I don't know if he put his slides online though, can't find them anywhere.
Ogg vorbis should work fine though. Make sure you start with one encoded and formatted as a basic stereo or mono 44.1kHz Ogg Vorbis file.
|
[
"stackoverflow",
"0045415793.txt"
] | Q:
Ajax is passing the data in the URL and doesn't work
i'm trying to pass some data with ajax but isn't working.
I do it before and it works i think it's something about cache.
I have this view:
@extends('cms.public.layouts.default')
@section('content')
<div class="col-md-10">
<h3 style="letter-spacing:40px;text-align:center;color:f15d5e;">PROYECTOS</h3>
</div>
<div id="listall"> <!-- DIV TO LIST ALL THE PROJECTS START HERE -->
<div class="col-md-2" style="padding:20px;">
<button type="button" id="buttoncreate" class="btn btn-danger">Crear Proyecto</button>
</div>
<table class="table">
<thead style="color:white">
<tr>
<th>Id</th>
<th>Slug</th>
<th>Order</th>
<th>Public</th>
<th>Fecha creación</th>
<th>Fecha ultima actualización</th>
<th><span class="glyphicon glyphicon-cog"></span></th>
</tr>
</thead>
<tbody style="color:white">
@foreach ($projects as $key => $project)
<tr>
<th>{{$project->id}}</th>
<td>{{$project->slug}}</td>
<td>{{$project->order}}</td>
<td>{{$project->public}}</td>
<td>{{ date('M j, Y', strtotime($project->created_at))}}</td>
<td>{{ date('M j, Y', strtotime($project->updated_at))}}</td>
<td><a href="{{ route('admin.projects.show', $project->id)}}" class="btn btn-info btn-sm">View</a> <a href="{{ route('admin.project.edit', $project->id)}}" class="btn btn-success btn-sm">Edit</a>
@endforeach
</tr>
</tbody>
</table>
<br><br>
</div> <!-- DIV TO LIST ALL THE PROJECTS END HERE -->
<div id="form1" style="display:none;" class="col-md-8"> <!-- DIV TO SHOW THE CREATE PROJECT FORM 1 START HERE-->
<div>
<h3>Crear nuevo proyecto</h3>
</div>
<div id="formcreateproject">
<form enctype="multipart/form-data" id="myForm" name="myForm">
<input type="hidden" name="_token" value="{{ Session::token() }}">
<div class="form-group">
<label name="title">Slug:</label>
<input type="text" id="slug" name="slug" placeholder="ejemplo-de-slug" class="form-control form-control-sm">
<label name="order">Order:</label>
<input type="number" id="order" name="order" class="form-control form-control-sm">
<label name="public">Public:</label>
<input type="number" id="public" name="public" class="form-control form-control-sm">
<label name="body">Header</label>
<input type="file" name="pathheader" id="pathheader" class="form-control-file" aria-describedby="fileHelp"><br>
<label name="body">Home</label>
<input type="file" name="pathhome" id="pathhome" class="form-control-file" aria-describedby="fileHelp"><br>
<input type="submit" value="Crear Proyecto" id="createprojectsubmit" class="btn btn-danger btn-md">
<br><br><br>
</div>
</form>
</div>
</div> <!-- DIV TO SHOW THE CREATE PROJECT FORM 1 END HERE-->
<div id="form2" style="display:none;" class="col-md-6">
<div class="col-md-">
<h3>Crear nueva traduccion</h3>
<form enctype="multipart/form-data" id="myFormTraduccion" name="myFormTraduccion"><!--FIRST FORM TO TRANSLATE -->
<input type="hidden" name="_token" value="{{ Session::token() }}">
<div class="form-group">
<label name="Language">Language:</label>
<input type="text" id="locale" name="locale" value="en" disabled class="form-control form-control-sm">
<label name="Project">Project id:</label>
<input type="number" id="project" name="project" class="form-control form-control-sm">
<label name="Title">Title:</label>
<input type="text" id="title" name="title" class="form-control form-control-sm">
<label name="Caption">Caption:</label>
<input type="text" id="caption" name="caption" class="form-control form-control-sm"><br>
<input type="submit" value="Crear Traduccion" id="createtranslatesubmit" class="btn btn-danger btn-md">
<br><br><br>
</div>
</form> <!-- FIRST FORM TO TRANSLATE END HERE -->
<form enctype="multipart/form-data" id="myFormTraduccion2" name="myFormTraduccion2"> <!--SECOND FORM TO TRANSLATE -->
<input type="hidden" name="_token" value="{{ Session::token() }}">
<div class="form-group">
<label name="title">Language:</label>
<input type="text" id="locale" name="locale" value="es" disabled class="form-control form-control-sm">
<label name="order">Project id:</label>
<input type="number" id="project" name="project" class="form-control form-control-sm">
<label name="public">Title:</label>
<input type="text" id="title" name="title" class="form-control form-control-sm">
<label name="caption">Caption:</label>
<input type="text" id="caption" name="caption" class="form-control form-control-sm"><br>
<input type="submit" value="Crear Traduccion" id="createtranslatesubmit2" class="btn btn-danger btn-md">
<br><br><br>
</div>
</form> <!--SECOND FORM TO TRANSLATE END HERE -->
</div>
</div>
@stop
Div with id="form" works.
When i try to create the translate don't give me any error, but don't work correctly. As you can see the submit button have id createtranslatesubmit and the id of the form is myFormTradducion.
Here i put the ajax code:
//Javascript view /projects/menu.blade.php
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$("#buttoncreate").click(function(){
$("#listall").hide();
$("#form1").fadeIn(1000);
});
$("#createprojectsubmit").click(function(){
$("#myForm").submit();
});
$("#myForm").submit(function(e){
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url:'/admin/projects/postUpload',
type:'POST',
data: formData,
success: function(){
$("#form1").fadeOut(1000);
$("#form2").fadeIn(1000);
$("#form3").fadeIn(1000);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
$("#createtranslatesubmit").click(function(){
$("#myFormTraduccion").submit();
});
$("myFormTraduccion").submit(function(e){
e.preventDefault();
$.ajax({
url:'/admin/projects/postUploadTranslation',
type:'post',
data:$('#myFormTraduccion').serializeArray(),
success: function(){
$("#form2").fadeOut(1000);
}
});
});
});
Routes are this:
//Proyectos
Route::get('project/listall', ['uses' => 'AdminController@listAll', 'as' => 'admin.projects.listall']);
Route::get('project/create', ['uses' => 'AdminController@createProject', 'as' => 'admin.projects.formupload']);
Route::post('projects/postUpload', ['uses' => 'AdminController@storeProject', 'as' => 'admin.projects.store']);
**Route::post('projects/postUploadTranslation', ['uses' => 'Web\ProjectsTranslationController@storeTranslation', 'as' => 'admin.projectstranslation.store']);**
Route::get('project/{id}/edit', ['uses' => 'AdminController@editProject', 'as' => 'admin.project.edit']);
Route::put('projects/{id}', ['uses' => 'AdminController@updateProject', 'as' => 'admin.project.update']);
Route::delete('project/{id}', ['uses' => 'AdminController@destroyProject', 'as' => 'admin.projects.destroy']);
Route::get('project/{id}/delete', ['uses' => 'AdminController@delete', 'as' => 'admin.projects.delete']);
Route::get('project/{id}', ['uses' => 'AdminController@showProject', 'as' => 'admin.projects.show']);
Controller is in a folder called Web, controller looks like here:
use App\Models\ProjectTranslation;
class ProjectsTranslationController extends Controller
{
public function storeTranslation(Request $request)
{
$projecttranslation = new ProjectTranslation();
$projecttranslation->locale = $request->input("locale");
$projecttranslation->project_id = $request->input("project");
$projecttranslation->title = $request->input("title");
$projecttranslation->caption = $request->input("caption");
$projecttranslation->save();
}
}
So when i click on submit with id createtranslatesubmit url change and looks like this:
http://test.loc/admin/projects?_token=ymzuWLO6I0nl7z5CQEriftjP1swWmH&project=40&title=1&caption=1
Know what's wrong?
If need more info, please ask it.
Thanks a lot
A:
I think you forgot #
$("myFormTraduccion").submit(function(e){
e.preventDefault();
$.ajax({
url:'/admin/projects/postUploadTranslation',
type:'post',
data:$('#myFormTraduccion').serializeArray(),
success: function(){
$("#form2").fadeOut(1000);
}
});
});
Updated code:
$("#myFormTraduccion").submit(function(e){
e.preventDefault();
$.ajax({
url:'/admin/projects/postUploadTranslation',
type:'post',
data:$('#myFormTraduccion').serializeArray(),
success: function(){
$("#form2").fadeOut(1000);
}
});
});
|
[
"stackoverflow",
"0022374579.txt"
] | Q:
Android - Error: com.facebook.FacebookException: Failed to get app name
I am using share dialog of facebook in order to share a link from my app to facebook. But I keep getting error com.facebook.FacebookException: Failed to get app name.
I already made my app status live and available to public.
Any help is appreciated.
A:
I faced the same issue, this is how I solved it for me.
The solution was to add .setApplicationName("name of app")
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(activity)
.setLink("https://www.google.com")
.setApplicationName("name of app")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
A:
You may check your developer roles or disable the Sandbox Mode.
|
[
"bicycles.stackexchange",
"0000032165.txt"
] | Q:
How do I know what is wrong with my brakes?
My brakes are not powerful anymore, it takes a few meters when fully pulling my brakes for my bike to come to a stop. Which means that the brakes'pads are touching the wheels but not enough.
So, my question is: how do I know if I need to change the brake pads or give more tension to the cable?
A:
How thick are the pads? Are these rim brakes or disk brakes? For rim brakes, the block (rubber) will get worn away over time so you should adjust the cable occasionally, but well before the block is so thin that the shoe (the metal backing) starts to scrape on the rim.
For disk brakes it's essentially the same but the pad is thinner and made of harder material. The manufacturers usually give a number how thin the pad can become, something like 0.7 mm.
|
[
"stackoverflow",
"0034811611.txt"
] | Q:
eval function not working in ajax post
So I am using ajax to post a serialised form to a php script and then on success alert the returned data.
My code works fine on my local environment, but uploaded, the eval() function mucks everything up.
here is my code:
function post_that_shit(formIdToSerialize, postUrl) {
var serializedData = $("#"+formIdToSerialize).serialize();
var post_url = postUrl+".php";
//alert(serializedData + "\n" + post_url);
$.ajax({
url: post_url,
type: "POST",
data: serializedData,
success: function(data){
data = eval('('+data+')' );
console.log(data.msg);
if(data.reload == 'yes'){
window.location.reload();
}
if(data.relocate != 'no'){
window.location.href = data.relocate;
//alert(data.relocate);
}
if(data.msg != 'no'){
$(".message").html(data.msg);
//alert(data.msg);
}
//alert('relocate: '+data.relocate);
}
});
}
So it is pretty simple.
The php echo out a json encoded array like so:
echo json_encode(array('msg' => $errors, 'relocate' => 'no'));
And depending on what is echoed, the msg is displayed or the user relocated.
Why do I get the error of SyntaxError: Unexpected token ')' when I use the code online?
Locally it works just fine :(
Thanx for your help
Chris
A:
You don't need to use eval(). Just set the dataType option to 'json' and the data will be internally parsed to an object by jQuery
$.ajax({
url: post_url,
type: "POST",
dataType:'json',
data: serializedData,
success: function(data){
console.log(typeof data); // returns "object"
In addition setting the proper content type header for application/json at server also helps
A:
First of all, eval is evil. Don't use it... never ever! It's like a bomb ready to detonate.
Secondly, parsing json can be done natively in Javascript. No need for eval.
You can use JSON.parse and it will return you an object parsed by the string containing the json text.
eval is used to evaluate code, in other words, it is executing javascript not json. When eval returns an object, it is simply a side effect of JSON being a subset of JavaScript. In other words, any string formatted as json can be evaluated to JavaScript. But JavaScript cannot be formatted to JSON. There is no representation of Date, Function and many more complex objects. That said, when using eval, you're actually executing JavaScript and that is the big problem here. It could execute potentially dangerous code while parsing JSON simply requires parsing data into a data structure and nothing more.
Here more about JSON: https://fr.wikipedia.org/wiki/JavaScript_Object_Notation
So it would allow anyone to add somewhat some javascript that would then get executed by your use of eval. It could allow someone to execute code on the browser of other users. It could be used to steal passwords for example or steal any kind of private information that wouldn't be accessible otherwise.
jQuery on the other hand allow you to parse json natively by using the dataType attribute as 'json'. Like this:
$.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedData,
success: function(data){
console.log(data.msg);
Or using JSON.parse
$.ajax({
url: post_url,
type: "POST",
data: serializedData,
success: function(data){
data = JSON.parse(data)
console.log(data.msg);
Also as charlie pointed out, parsing by ourselves JSON means that we have to wrap it in a try catch, because parsing might fail if the json isn't valid.
But using jQuery gives us a way to handle that easily.
You could rewrite your code such as this:
var req = $.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedDate
});
req.done(function (data) {
// Success
});
req.fail(function () {
// Error something went wrong
});
The advantage of using the promise form is that you can chain calls to have clean async code instead of the callback hell and infinite function nesting.
|
[
"stackoverflow",
"0037929165.txt"
] | Q:
Rust and C linking problems with minimal program and no_std
I'm trying to build a minimal program in C that calls Rust functions, preferably compiled with #![no_std], in Windows, using GCC 6.1.0 and rustc 1.11.0-nightly (bb4a79b08 2016-06-15) x86_64-pc-windows-gnu. Here's what I tried first:
main.c
#include <stdio.h>
int sum(int, int);
int main()
{
printf("Sum is %d.\n", sum(2, 3));
return 0;
}
sum.rs
#![no_std]
#![feature(libc)]
extern crate libc;
#[no_mangle]
pub extern "C" fn sum(x: libc::c_int, y: libc::c_int) -> libc::c_int
{
x + y
}
Then I tried running:
rustc --crate-type=staticlib --emit=obj sum.rs
But got:
error: language item required, but not found: `panic_fmt`
error: language item required, but not found: `eh_personality`
error: language item required, but not found: `eh_unwind_resume`
error: aborting due to 3 previous errors
OK, so some of those errors are related to panic unwinding. I found out about a Rust compiler setting to remove unwinding support, -C panic=abort. Using that, the errors about eh_personality and eh_unwind_resume disappeared, but Rust still required the panic_fmt function. So I found its signature at the Rust docs, then I added that to the file:
sum.rs
#![no_std]
#![feature(lang_items, libc)]
extern crate libc;
#[lang = "panic_fmt"]
pub fn panic_fmt(_fmt: core::fmt::Arguments, _file_line: &(&'static str, u32)) -> !
{ loop { } }
#[no_mangle]
pub extern "C" fn sum(x: libc::c_int, y: libc::c_int) -> libc::c_int
{
x + y
}
Then, I tried building the whole program again:
rustc --crate-type=staticlib --emit=obj -C panic=abort sum.rs
gcc -c main.c
gcc sum.o main.o -o program.exe
But got:
sum.o:(.text+0x3e): undefined reference to `core::panicking::panic::h907815f47e914305'
collect2.exe: error: ld returned 1 exit status
The panic function reference is probably from a overflow check in the addition at sum(). That's all fine and desirable. According to this page, I need to define my own panic function to work with libcore. But I can't find instructions on how to do so: the function for which I am supposed to provide a definition is called panic_impl in the docs, however the linker is complaining about panic::h907815f47e914305, whatever that's supposed to be.
Using objdump, I was able to find the missing function's name, and hacked that into C:
main.c
#include <stdio.h>
#include <stdlib.h>
int sum(int, int);
void _ZN4core9panicking5panic17h907815f47e914305E()
{
printf("Panic!\n");
abort();
}
int main()
{
printf("Sum is %d.\n", sum(2, 3));
return 0;
}
Now, the whole program compiles and links successfully, and even works correctly.
If I then try using arrays in Rust, another kind of panic function (for bounds checks) is generated, so I need to provide a definition for that too. Whenever I try something more complex in Rust, new errors arise. And, by the way, panic_fmt seems to never be called, even when a panic does happen.
Anyways, this all seems very unreliable, and contradicts every information I could find via Google on the matter. There's this, but I tried to follow the instructions to no avail.
It seems such a simple and fundamental thing, but I can't get it to work the right way. Perhaps it's a Rust nightly bug? But I need libc and lang_items. How can I generate a Rust object file/static library without unwinding or panic support? It should probably just execute an illegal processor instruction when it wants to panic, or call a panic function I can safely define in C.
A:
You shouldn't use --emit=obj; just rustc --crate-type=staticlib -C panic=abort sum.rs should do the right thing. (This fixes the _ZN4core9panicking5panic17h907815f47e914305E link error.)
To fix another link error, you need to write panic_fmt correctly (note the use of extern):
#[lang="panic_fmt"]
extern fn panic_fmt(_: ::core::fmt::Arguments, _: &'static str, _: u32) -> ! {
loop {}
}
With those changes, everything appears to work the way it's supposed to.
You need panic_fmt so you can decide what to do when a panic happens: if you use #![no_std], rustc assumes there is no standard library/libc/kernel, so it can't just call abort() or expect an illegal instruction to do anything useful. It's something which should be exposed in stable Rust somehow, but I don't know if anyone is working on stabilizing it.
You don't need to use #![feature(libc)] to get libc; you should use the version posted on crates.io instead (or you can declare the functions you need by hand).
A:
So, the solution, from the accepted answer, was:
main.c
#include <stdio.h>
#include <stdlib.h>
int sum(int, int);
void panic(const char* filename_unterminated, int filename_size, int line_num)
{
printf("Panic! At line %d, file ", line_num);
for (int i = 0; i < filename_size; i++)
printf("%c", filename_unterminated[i]);
abort();
}
int main()
{
// Sum as u8 will overflow to test panicking.
printf("Sum is %d.\n", sum(0xff, 3));
return 0;
}
sum.rs
#![no_std]
#![feature(lang_items, libc)]
extern crate libc;
extern "C"
{
fn panic(
filename_unterminated: *const libc::c_char,
filename_size: libc::c_int,
line_num: libc::c_int) -> !;
}
#[lang="panic_fmt"]
extern fn panic_fmt(_: ::core::fmt::Arguments, filename: &'static str, line_num: u32) -> !
{
unsafe { panic(filename.as_ptr() as _, filename.len() as _, line_num as _); }
}
#[no_mangle]
pub extern "C" fn sum(x: libc::c_int, y: libc::c_int) -> libc::c_int
{
// Convert to u8 to test overflow panicking.
((x as u8) + (y as u8)) as _
}
And compiling with:
rustc --crate-type=staticlib -C panic=abort sum.rs
gcc -c main.c
gcc main.o -L . -l sum -o program.exe
Now everything works, and I have a panic handler in C that shows where the error occurred!
|
[
"sitecore.stackexchange",
"0000004044.txt"
] | Q:
How to get hostname on publish end event
I am trying to get "http://hostname" in below way.
string.Concat(Request.Url.Scheme, Uri.SchemeDelimiter, Request.Url.Host)
this should work in normal cases, but i am doing this on publish:end event, where request is null.
The context site is publisher and could not find Request property in EventArgs whats the best way to get Request properties in this case?
A:
The problem with Sitecore.Context.Site:
Sitecore performs publishing on the publisher site, and as you noted, the publish:end is an event and is called without a request, so there isn't even a URL to work from.
Based on the above, hypothetically, if we assume that Sitecore is going to resolve a site (we don't know which yet) to put in the Sitecore.Context then the website (or custom site) that you're looking for isn't even a candidate.
Working towards getting the site:
Every item in Sitecore is site-specific, in that it's path should only ever live within a single site. The publish:end event just so happens to have a handy little Publisher object as a parameter, that holds the RootItem that was published. You can access this item and the Site it belongs to by doing the following in your event handler:
...
var scArgs = args as Sitecore.Events.SitecoreEventArgs;
if (scArgs == null)
{
return;
}
var publisher = scArgs.Parameters[0] as Publisher;
if (publisher == null)
{
return;
}
var rootItem = publisher.Options.RootItem;
var site = Sitecore.Configuration.Factory.GetSiteInfoList()
.FirstOrDefault(site => rootItem.Paths.FullPath.StartsWith(site.RootPath));
...
But wait! What about multi-site publishes?
What if you published more than one site? Now you will match the first one, when you should probably return both or return null. On the flip side, what if you published the full solution and have only one site, or else you published the full solution and now you want to get all sites that you published? The above will give you null in these cases, but maybe that's not what you want.
Getting the site with multi-site publishing support:
In order to support multi-site and situations where you may have published the full solution, update the above to the following:
...
var scArgs = args as Sitecore.Events.SitecoreEventArgs;
if (scArgs == null)
{
return;
}
var publisher = scArgs.Parameters[0] as Publisher;
if (publisher == null)
{
return;
}
var rootItem = publisher.Options.RootItem;
var publishedSites = Sitecore.Configuration.Factory.GetSiteInfoList()
.Where(site => rootItem.Paths.FullPath.StartsWith(site.RootPath));
...
We aren't done yet, however. You still don't have the URL of the site.
Solution: Getting the URL of the published site(s)
The site-definition nodes have the nifty little optional attributes targetHostName and scheme. Assuming that you have specified a value for those attributes, you can then retrieve the URLs of the sites of the sites you published by updating the above to the following:
...
var scArgs = args as Sitecore.Events.SitecoreEventArgs;
if (scArgs == null)
{
return;
}
var publisher = scArgs.Parameters[0] as Publisher;
if (publisher == null)
{
return;
}
var rootItem = publisher.Options.RootItem;
var publishedSites = Sitecore.Configuration.Factory.GetSiteInfoList()
.Where(site => rootItem.Paths.FullPath.StartsWith(site.RootPath));
var publishedHosts = publishedSites
.Select(site => site.Properties["scheme"] + @":\\" + site.Properties["targetHostName"]);
...
A:
Using the Sitecore.Configuration.Factory.GetSite() method you can retrieve a Sitecore.Sites.SiteContext object that has properties defined that correspond to your site.
var siteContext = Sitecore.Configuration.Factory.GetSite("sitename");
Then from the siteContext item you can access the HostName or TargetHostName values depending on what you need.
|
[
"outdoors.stackexchange",
"0000012957.txt"
] | Q:
Baby-friendly trek near Innsbruck
My family is going to Innsbruck in August, and we want to do a 3-4 day mountain hut trek. This will be our first trek with our son, who will be 16 months old. I can see many, many huts and trails in the area, but I'm having a hard time ascertaining which ones are easier. For example, we don't want via ferrata, nor very steep climbs. Basically, we just want an easy trek - I'm sure that practically anywhere in the area will be lovely, we don't need somewhere famous.
I don't mind arriving in Innsbruck and then consulting with locals, but I'm worried that things will be crazy in August, and if I don't reserve places in huts, they will fill up. Is this true?
Anyone have a route or area they'd like to suggest?
A:
Why not try the Wilder Kaiser, it's not in Innsbruck, only some 55mins drive, but it's pretty dame awesome and very kid friendly! More than 400km of walking paths make the Wilder Kaiser mountains an absolute gem for hiking holidays. Trails include accurate directions and approximate walk times.
Hiking from hut to hut
There is a remarkably diverse paradise just waiting to be discovered when hiking in the Wilder Kaiser region. The variety of tours is huge and the combination of mild climate, fresh mountain air and steady physical activity has a wonderfully revitalising effect on the body. Why not prolong the experience and enjoy some traditional Austrian hospitality along the way with a 3 days' hut-to-hut hike. This tour takes you to the prettiest spots on the south side of the range where, thanks to the moderate altitude, the tour can be enjoyed from as early as June until mid October.
Source: http://www.austria.info/uk/things-to-do/walking-and-hiking/hiking-wilder-kaiser
|
[
"stackoverflow",
"0007687061.txt"
] | Q:
Interfacing Google Doc Api's with Ruby on Rails
I'm trying to interface with the Google Docs APIs, namely the Google Documents List Data API v3.0.
Are there any open-source Ruby libraries that can do the interfacing? Google has a Python api released for v3.0; I'm looking for something similar.
(I'm trying to develop a webapp that converts from PowerPoint to a Google doc.)
A:
Have you tried the gdata gem? I'm not sure it helps, but it has a number of clients for working with Google Data APIs, namely the DocList...
|
[
"tex.stackexchange",
"0000084073.txt"
] | Q:
Space between bars, height and width of the plot
I'm using pgfplots to generate bar plots from data files. Here's MWE:
\documentclass{article}
\usepackage[ngerman]{babel}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xbar,
% enlarge y limits=0.2,
xlabel={Häufigkeit},
symbolic y coords={sehr viel mehr,deutlich mehr,Verzehr ist gleich geblieben,etwas
weniger O+G,deutlich weniger O+G,keine Bewertung möglich},
ytick=data,
nodes near coords, nodes near coords align={horizontal},
]
\addplot table[col sep=tab,header=false] {data1.dat};
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[
xbar,
% enlarge y limits=auto,
xlabel={Häufigkeit},
symbolic y coords={Äpfel,Melonen,Erdbeeren,Bananen,Trauben,Nektarinen,Aprikosen,Clementinen,Pfirsiche,Birnen,Kiwi,Pflaumen,individuell völlig verschieden,eigentlich alle Sorten,Orangen,Kirschen,Himbeeren,Ananas,Mirabellen},
ytick=data,
nodes near coords, nodes near coords align={horizontal},
]
\addplot table[col sep=tab,header=false] {data2.dat};
\end{axis}
\end{tikzpicture}
\end{document}
data1.dat:
11 sehr viel mehr
55 deutlich mehr
4 Verzehr ist gleich geblieben
0 etwas weniger O+G
0 deutlich weniger O+G
0 keine Bewertung möglich
data2.dat:
56 Äpfel
20 Melonen
12 Erdbeeren
45 Bananen
18 Trauben
12 Nektarinen
8 Aprikosen
4 Clementinen
10 Pfirsiche
19 Birnen
16 Kiwi
7 Pflaumen
1 individuell völlig verschieden
1 eigentlich alle Sorten
7 Orangen
3 Kirschen
1 Himbeeren
1 Ananas
1 Mirabellen
Here are the plots:
There are some problems I can not solve:
I wonder why each plot has the same height and width even if more space is needed.
How do I add space between bars in the second plot? Since I have many plots I'd like to have a global option that automatically adapts the space between bars.
Thanks in advance!
Christoph
Edit: Here's plot that shows further problems with spacing (same pgfplots settings as in MWE except that I added “yticklabel style={text width=3cm,align=right}”, and different data, of course.)
A:
By default, plots always take up the same amount of space (240pt by 207pt). If you want the plots to adjust their height depending on the number of bars, you can define the length of a unit in the y direction, by setting y=0.5cm, for instance. If you then define the bar width to be 0.4cm, there will be no overlap between the bars. Since PGFPlots version 1.7 (I think), you can also define the extra space at the top and bottom in absolute lengths (before that, you could only specify it in data units).
\documentclass{article}
\usepackage[ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xbar,
y=-0.5cm,
bar width=0.3cm,
enlarge y limits={abs=0.45cm},
xlabel={Häufigkeit},
symbolic y coords={sehr viel mehr,deutlich mehr,Verzehr ist gleich geblieben,etwas
weniger O+G,deutlich weniger O+G,keine Bewertung möglich},
ytick=data,
nodes near coords, nodes near coords align={horizontal},
]
\addplot table[col sep=comma,header=false] {
11,sehr viel mehr
55,deutlich mehr
4,Verzehr ist gleich geblieben
0,etwas weniger O+G
0,deutlich weniger O+G
0,keine Bewertung möglich
};
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[
xbar,
y=-0.5cm,
bar width=0.3cm,
enlarge y limits={abs=0.45cm},
% enlarge y limits=auto,
xlabel={Häufigkeit},
symbolic y coords={Äpfel,Melonen,Erdbeeren,Bananen,Trauben,Nektarinen,Aprikosen,Clementinen,Pfirsiche,Birnen,Kiwi,Pflaumen,individuell völlig verschieden,eigentlich alle Sorten,Orangen,Kirschen,Himbeeren,Ananas,Mirabellen},
ytick=data,
nodes near coords, nodes near coords align={horizontal},
]
\addplot table[col sep=comma,header=false] {
56,Äpfel
20, Melonen
12, Erdbeeren
45, Bananen
18, Trauben
12, Nektarinen
8, Aprikosen
4, Clementinen
10, Pfirsiche
19, Birnen
16, Kiwi
7, Pflaumen
1, individuell völlig verschieden
1, eigentlich alle Sorten
7, Orangen
3, Kirschen
1, Himbeeren
1, Ananas
1, Mirabellen
};
\end{axis}
\end{tikzpicture}
\end{document}
|
[
"stackoverflow",
"0049767974.txt"
] | Q:
Auto-Linking framework not found
I have forked a framework called BTNavigationDropdownMenu (swift project for ios). all worked fine till I tried to add a dependency to the latest version in the branch I created. the problem is the same whether I add the other framework (DYBadge) through a podfile or through Carthage.
Auto-Linking framework not found DYBadge.
It seems to have a problem with a UIView extension that is part of DYBadge.
DYBadge works fine in my main app I'm working on (I also need it in the app target).
errors below. thanks for any hints into the right direction.
ld: warning: Auto-Linking framework not found DYBadge Undefined
symbols for architecture x86_64: "(extension in
DYBadge):__ObjC.UIView.getBadge() -> DYBadge.DYBadge?", referenced
from:
Demo.BTNavigationDropdownMenu.updateBadge(text: Swift.String, at: Swift.Int) -> () in BTNavigationDropdownMenu.o ld: symbol(s) not
found for architecture x86_64 clang: error: linker command failed with
exit code 1 (use -v to see invocation)
A:
Xcode is not able to find your frameworks because the FRAMEWORK_SEARCH_PATHS is probably not set or is wrong (happened to me because I moved the Info.plist file).
You can fix this by going into your target and adapt the Build Settings. Simply search in there for FRAMEWORK_SEARCH_PATHS and add the correct one, which is usually $(PROJECT_DIR)/Carthage/Build/iOS (for iOS projects). $(inherited) should also be in there as the first entry.
This is the post of @user3122959 answer in the comments, which helped me and others to fix this problem and was requested to put in as the answer to this question.
A:
I had this problem accessing 3rd party frameworks from my tests. Here's how I fixed it.
In Xcode goto: Your Unit-Test target > Build Phases > Link Binary With Libraries
In Finder goto: Carthage > Build > yourframework.Framework
Drag the framework in to your build phases then clean (cmd - shift - K).
|
[
"stackoverflow",
"0058687035.txt"
] | Q:
How to detect user idle in UWP?
I want to know how to detect user idle in UWP. I mean not the case user idle for the app, but for the whole system/OS: no keyboard input, no mouse operation, no touch even when no focus on the app or app is minimized.
I find some other post about it. Like this: How to check if user is idle on UWP?
And it uses below method:
Window.Current.CoreWindow.PointerMoved += onCoreWindowPointerMoved;
I tested and found that if my mouse moves outside of the app window, then onCoreWindowPointerMoved() will not be executed. It means this method can not detect user idle on the whole system.
A:
How to detect user idle in UWP?
For security reason, we could not implement this in UWP platform, But we could implement this in legacy win32 app, and use FullTrustProcessLauncher to run the win32 app to detect the system idle. then use AppService pass the status to UWP app. For more please refer this tutorial
|
[
"emacs.stackexchange",
"0000033719.txt"
] | Q:
Is the unwind-protect's clean form always evaluated?
I have this loop:
(catch 'QUIT
(while
(search-forward-regexp "\\([^\n\\]\\(?:\\\\\\\\\\)*\\|^\\(?:\\\\\\\\\\)+\\)%.*\n"
nil t)
(save-excursion
(let ((b (make-marker))
(e (make-marker))
MatchedStringOverlay
ACTION)
(set-marker b (match-beginning 0))
(set-marker e (point))
(setq MatchedStringOverlay (make-overlay b e))
(unwind-protect
(progn
(overlay-put MatchedStringOverlay 'face '(:background "OliveDrab1"))
(setq ACTION (read-char "Opzioni per eliminare la stringa commentata:
- [y] per eliminare la stringa con relativo \"newline\"
- [l] per eliminare la stringa mantenendo il \"newline\"
- [n] per mantenere la stringa commentata
- [q] per uscire da questo loop:
"))
(cond
((char-equal ACTION ?y)
(replace-match "\\1"))
((char-equal ACTION ?l)
(replace-match "\\1\n"))
((char-equal ACTION ?n)
nil)
((char-equal ACTION ?q)
(throw 'QUIT (remove-overlays b e)))
)
)
(read-string "UNWIND EXIT"))
(read-string "NORMAL EXIT")
)))
)
in which the unwind cleanup-form is always evalueted, but I need it to be evaluate only when something goes wrong (e.g. a quit of the script).
Where is my mistake? I thought it shouldn't be evaluate since the body form of unwind-protect exits normally.
The loop is meant to interactively remove some kinds of commented lines in LaTeX code, letting me choose if removing also the corresponding newline.
A:
This is a classic case where reading the docs gives you the answer immediately:
unwind-protect is a special form in ‘C source code’.
(unwind-protect BODYFORM UNWINDFORMS...)
Do BODYFORM, protecting with UNWINDFORMS.
If BODYFORM completes normally, its value is returned
after executing the UNWINDFORMS.
If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
The name is weird, but describes that the body form is protected against stack unwinding, which happens when running into an error. unwind-protect is therefore equivalent to the finally keyword as seen in Java and alike. If you want to handle errors, use condition-case (which is like case, but for error conditions).
|
[
"math.meta.stackexchange",
"0000010785.txt"
] | Q:
How many registered users are there?
Can I somewhere see the number of registered users on our site [ without multiplying the number of pages by 36, the number of users per page] ?
A:
A possible way to get an idea about this number is to look at the right (i.e. total reputation tab) of this page. As of today, it seems that there are $65\,508$ registered users.
On the other hand, I am sure that a lot of people create new account for every new question they have, and therefore the number of actual users is (much?) less than the number of registered accounts.
|
[
"stackoverflow",
"0007936043.txt"
] | Q:
Inpainting pixels between regions with nearest color in MATLAB
Is there an efficient way to fill in pixels with a value of zero between pixels with non-zero values with the nearest non-zero value, while leaving the rest of pixels at zero untouched?
To clarify, I am looking to inpaint those pixels whose closest distance to a non-zero pixel is lower than a given value (e.g. 4 pixels).
The image is initially represented as a matrix of uint32 integers.
In the example above, all the thin cracks between the colored regions should be filled with the surrounding color, while large black regions should remain the same (i.e. the routine should inpaint the pixels between the colored regions).
I imagine there is a way to do this via interpolation. In either case, I am looking for a relatively efficient solution.
A:
Given an input matrix A:
b = imclose(A==0,ones(3,3)) %only the big zero regions
c = imdilate(A,ones(3,3)) %inpainting all neighboring pixels
d = zeros(size(A));
d(b==0) = c(b==0); %copy the inpainting only in places where there are no big regions
I haven't tested it, so there may be some problems with the code. (if you made changes to the code to make it work please edit my answer)
|
[
"ell.stackexchange",
"0000046310.txt"
] | Q:
would you show me usages of the verb should in conditional type 2 and third –
My profs. has told me the fact that we could use the verb should as to conditional sentences" second and third", that is, probable and impossible sentences:
So, would you show me these, using the verb should?
A:
It's grammatically correct to use "should" instead of "would" for the pronouns I/we in conditional type 2 and type 3 sentences, but the use of "would" is more common and that of "should" is seldom. A few examples are given below:
If I worked harder, I would/should pass the exam. (type 2)
If I had worked harder, I would/should have passed the exam. (type 3)
if we had lots of money, we would/should travel round the world. (Type 2)
If we had had lots of money, we would/should have travelled round the world (type 3)
|
[
"webmasters.stackexchange",
"0000064967.txt"
] | Q:
Best way to get improve SEO ranking for image-based site
How do I best approach common SEO techniques for a website with images as the main content?
The problem here is the content is all image based, so other than Friendly URLS, H1/H2 tags, Sitemap, RSS Feed, Alt Img, what else can be done to gain search rankings?
I realise most search engines (if not all) are text based and text is how they better understand the business and "usefulness" of a site and therefore compare it with other sites, but other than social media and driving constant traffic what is the best thing to do or focus on?
A:
I would focus on:
Naming the images with real world phrases: beautiful-girl-with-roses.jpg
Adding complementary descriptions in the alt tag: alt="Beautiful red hair girl"
Good titles in your title tag: "Image of a red haired girl"
Good descriptions in your description tag: "Hi resolution image of a girl with great bokeh"
Nice formatted links including the description of the nex image if this apply: href="beautiful-girl-with-roses.html"
A:
Image sites are all about the authority of the site i.e
Back link quality and relevancy
Age of the site
Social interaction
Regular freshen content
Regular added content
You only need to search "Image of Flowers" and "Flowers Backgrounds" to see that Google does in fact rank 'thin content' on certain topics and searches, of course adding text content would help but of course if people want just images then simply adding content to satisfy the search engines would affect user experience because all people want is the images.
Google Image Search (Unique Images Preferred)
Unique images work best as Google has the ability to see if images are already stored somewhere else online, you can check this by dragging a image from Desktop into Google search and it'll scan for duplicates and well if they can tell that they can easily detect duplicates which ultimately may lead to less Google image search clicks).
With LESS you need MORE
Generally with LESS you need MORE, but with this said if everyone in the same category has LESS then you don't need as much of MORE. Social media is most likely your best bet as pictures can go viral which will help your SEO from all the social mentions and because more people see it they could even link using their blog or something.
Adding additional markup may help slightly but generally it's not treated as much as everyone would hope, off the page signals are still the most contributing ranking factor.
Suggestions that won't gimp the user experience and promote better search rankings
If possible and economy viable use a CDN to host the static files such as 'JS, CSS, JPG, PNG and so on' (Google does reward fast sites).
Adding a comment system might improve user experience while making the content that little bit less THIN and can be treated as a page update which is a big plus to 'Freshen Content'.
Ensure that the ALT describes the image well, a short sentence is ideal i.e `Pink Sunflower in a farmers field' rather than 'Sunflower'.
Many other ways on what are the best ways to increase a site's position in Google?
|
[
"stackoverflow",
"0003592496.txt"
] | Q:
how to open outside links in a new tab
On my website i have many outside links, as well as internal links.
i'd like some kind of solution in javascript or w/e that detects outside links and opens them in a new tab, but leaves internal links to be opened in the same tab.
thanks! =)
A:
function getXterlinks()
{
var Xterlinks = document.getElementsByTagName('A');
for (var i=0;i<Xterlinks.length;i++)
{
var eachLink = Xterlinks[i];
var regexp_isYourdomain="your-domain.com";
var regexp_ishttp=/(http(.)*:\/\/)/;
if( (eachLink.href != null) && (eachLink.href.match(regexp_isYourdomain) == null) && eachLink.href.match(regexp_ishttp)!=null )
{
eachLink.target ="_blank";
}
}
}
Source: http://www.mediawiki.org/wiki/Manual:Opening_external_links_in_a_new_window#How_to_make_external_links_open_in_a_new_window
|
[
"stackoverflow",
"0002128553.txt"
] | Q:
WinCE MFC checking for SIM card existen?
Is it possible to use WinCE MFC application to check if SIM card presents in device or not?
thanks.
A:
call SimInitialize and see if you get SIM_E_NOSIM.
|
[
"stackoverflow",
"0057823743.txt"
] | Q:
text overlapping in span when too long for viewport
On the header of my webpage, the text overlaps when it gets too long for the viewport.
This is the HTML code:
<h3 class="col s12 light-blue-text text-darken-4 content-header">
<span style="position: relative;">
Mice, fusilli and thin skin
</span>
</h3>
And this is the CSS class content-header (I'm using the materialize.css framework so don't worry about the col s12 light-blue-text and text-darken-4 classes.)
.content-header {
position: relative;
text-align: center;
border-bottom: 1px solid #020202;
line-height: 0.1em;
margin: 10px 0 20px;
}
.content-header span {
background-color: #fff;
}
This class adds a little line before and after the header.
This is the output I get:
Output in responsive mode
It should make a wordwrap when it doesn't have enough space.
A:
That's due to your line-height: 0.1em; setting for .content-header: The second line's baseline is only 0.1em below the first one's that way, causing the overlap when the text wraps. So change that to line-height: 1.1; or similar, at least for screens below a certain width, using a media query.
.content-header {
position: relative;
text-align: center;
border-bottom: 1px solid #020202;
line-height: 1.1;
margin: 0px 0 20px;
}
.content-header span {
background-color: #fff;
width: 150px;
display: inline-block;
position: relative;
top:1.1em;
}
<h3 class="col s12 light-blue-text text-darken-4 content-header">
<span style="position: relative;">
Mice, fusilli and thin skin
</span>
</h3>
|
[
"stackoverflow",
"0043957596.txt"
] | Q:
Error while fetching the full path name of an image in Android
In order to send an image to server, while getting the path of the image , the following code is used
private String getPath(Uri uri){
String path = null;
Cursor cursor = null;
try {
Toast.makeText(this,"Beginning of getPath()", Toast.LENGTH_LONG).show();
cursor=getContentResolver().query(uri,null,null,null,null);
cursor.moveToFirst();
String document_id=cursor.getString(0);
document_id=document_id.substring(document_id.lastIndexOf(".")+1);
cursor=getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,null,MediaStore.Images.Media._ID+"=?",new String[]{document_id},null);
cursor.moveToFirst();
path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
Toast.makeText(this,"At the end of getPath()", Toast.LENGTH_LONG).show();
}
catch(Exception e){
e.printStackTrace();
} finally {
cursor.close();
}
return path;
}
I have set two toast methods here to check the flow of control. I'm getting the first toast message at the beginning of the method but not getting the next one...which reflects the error in the that part of the code...
What might have gone wrong here.
Android stack trace gave the following'
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at the folowing line
path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
A:
In order to send an image to server, while getting the path of the image , the following code is used
That code will not work for arbitrary Uri values.
What might have gone wrong here
You are trying to derive a file path for a Uri.
Use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. Then, either:
Use the InputStream directly for uploading the content, if your HTTP client API supports that, or
Use the InputStream and a FileOutputStream (on some file that you control, such as in getCacheDir()) to make a copy of the content. Then, upload the copy, deleting the copy when you are done.
|
[
"stackoverflow",
"0018613896.txt"
] | Q:
How to submit form name as object to a php function
I am trying to learn mvc framework in php but then i could not find out a way in passing the form data to a php function in another php page. I am submitting the form and receiving it in the same page and then I am trying to pass the form data to the controller function which will handle the validation. I cannot figure out how should I pass the form data to the other function.
I can pass each data as parameter but then that would be lengthy if there are lots of data in the form. I was wondering if I could pass the form as an object (something like we pass object of structures) to another function and then use the data suitably. I have put in a code module below:
<?php
include('controller.php');
$controller = new Controller($model);
if (isset($_GET['formButton']))
$controller->submitButtonClicked();
?>
<form name="details" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="txt1">First Name:</label>
<input type="text" name="txt1" id="txt1"/>
<label for="password">Password:</label>
<input type="password" name="password" id="password"/>
<input type="submit" name="formButton" id="formButton" value="Submit"/>
</form>
Any help would be very helpful.
A:
The $_GET and $_POST superglobals are already arrays of the submitted form data, so you can simply use these in your controller. Just make the form submit to the controller file directly: this is cleaner and there's no need to pass the $_GET or $_POST (you should probably use post, but I don't know the context).
I assume you're building your own MVC from scratch. If so, you could do a handler.php controller, that every form submits to. This could loop the posted data like so:
// define Input class somewhere and include
$input = new Input();
foreach($_POST as $field => $value)
{
$input->$field = $this->validate($value);
}
In validate() you would do some general validation. Then you could use this new Input object wherever you need the input data. This is a very primitive example of how premade frameworks like CodeIgniter and Laravel use an Input helper class, and of course you can expand on this. Or better yet, save some extra work and utilize a good known framework like those mentioned in your project :)
|
[
"stackoverflow",
"0008656125.txt"
] | Q:
showing different data based on selected segment control in monotouch
I have an iPhone app I am building with MonoTouch (C#). My current view has a segmented control with three options. Depending on which segment is chosen, I want to display data related to the segment. The data will most likely require scrolling. My question is, what control(s) should I use to accomplish this? Do I use three ScrollView controls? If so, how do I show/hide each control based on the selected segment?
Thank you!
A:
I came across a situation like this. In short, I did it with a single UITableView and UITableSource. When the user selects one segment, the appropriate data source is replaced with the one that corresponds to that specific segment and the table is reloaded (tableView.ReloadData() in most occasions).
It might get a bit complex, if for example "Segment A" contains text-only rows and "Segment B" contains text + image rows. In this case, you will need a bit more logic in the UITableSource's GetCell method to determine what cell will be displayed based on the type of data.
To minimize complexity, I have created a custom interface and generic class that inherits it:
interface ITableRow
{
string RowTitle { get; set; }
string RowSubTitle { get; set; }
}
class TableRow<T> : ITableRow
{
public TableRow(string rowTitle, string rowSubtitle, T dataObject)
{
// fill the properties with values here
}
public string RowTitle { get; set; }
public string RowSubTitle { get; set; }
public T DataObject { get; set; }
}
My data source is always a List<ITableRow> (or a Dictionary<TSome, ITableRow> in some cases), so the UITableSource.GetCell implementation "knows" what to assign to each cell every time.
You could also extend it (I have) by adding the following constructor:
public TableRow(Func<string, T> rowTitleFunc, Func<string, T> rowSubtitleFunc, T dataObject)
: this(rowTitleFunc(dataObject), rowSubtitleFunc(dataObject), dataObject) {}
This way you can display different data in each row based on each row's "dataObject".
PS (off topic): Don't you just love C# on iOS?
|
[
"stackoverflow",
"0007404816.txt"
] | Q:
Emacs ruby-mode, indenting wildly inside parentheses?
Excuse my emacs newbiness here, but does anybody know how to get around this? When coding in emacs, in ruby-mode, it indents to the correct level (i.e. by 2 spaces) after all the keywords, like def, class, module, begin etc, but when breaking parameter lists across multiple lines, it indents to a seemingly random position, like 40 or so columns over.
I've been reading around emacs tab settings and seem to just be going around in circles and not getting to information I'm looking for, so I figured I'd ask here.
Here's a screenshot of where it is placing the cursor in a parameter list. I've tried indenting inside of curly braces (e.g. for a block, or a hash) and that is working ok, it's the parentheses that are messing it up.
A:
http://compgroups.net/comp.emacs/Ruby-mode-indentation-of-continuation-lines
(setq ruby-deep-indent-paren nil)
Or temporarily, within the current session:
M-x set-variable RET ruby-deep-indent-paren RET nil RET
Inside of a parentheses it will now indent like it does everywhere else. There is still a minor bug in the case of what I posted above. It indents 2 spaces further than I want it to, because I'm confusing it with the combination of ( and {.
|
[
"dba.stackexchange",
"0000165583.txt"
] | Q:
Best Way to design a table with different types of attachment
I am currently Building a table for message where user can send a message with different types of attachment,
Sender can:
send text per message
send one location per message
send one or multiple images per message
send one or multiple videos per message
Currently, this is my table design,
message
-id
-type (text,images,videos,location)
-sender_id
message_text
-id
-message_id
-body
message_location
-id
-message_id
-latitude
-longitude
message_images
-id
-message_id
-image_path
-image_height
-image_width
message_videos
-id
-message_id
-video_path
Am I doing things right?
My concern was user can attach multiple of images or videos but only one location.
A:
You are probably over-complicating matters by using separate tables for message, message_text and location. Just merge them into one table:
message
-id
-type
-sender_id
-body
-latitude
-longitude
If the columns may not have values, be sure to set them to NULLable in the table definition.
There are various valid reasons for using one to one relationships, for example for example if you expect to have a lot of records with shorter fields in the primary table but then only occasionally need records with longer fields in the secondary table but in most cases they are not necessary and only serve to complicate your design which will require more joins it otherwise would not.
From the general tone of your question you seem to be new to database design and I doubt you really want to do this. Keep everything about the message in one table and then you can inherently only have one location, one body, etc.
IF you wanted to create a one-to-one relationship the usual way you would go about this would be to make the primary key on the secondary table also a foreign key referencing the primary table. So both tables would have the same primary key value for a given record- this would ensure you could only have one.
https://www.mkyong.com/mysql/how-to-define-one-to-one-relationship-in-mysql/
As it is now, you could have multiple records in these tables, a one-to-many relationship.
But I would strongly suggest you just merge into one table.
Your attachment and image tables look fine, that will be a one-to-many relationship with separate primary keys and linked using a foreign key.
|
[
"mathematica.stackexchange",
"0000192055.txt"
] | Q:
SelectionMove within a GridBox?
I want to interactively manipulate the contents of a GridBox using keyboard commands. To approach this I need to control selection with something like SelectionMove but I cannot figure out the right parameters. How can I programmatically select individual elements and groups of elements within a GridBox?
A:
Finally got this working. It's a huge pain to find the current element in Mathematica, as we all know so that was basically what I needed to figure out how to find. But I did! And here's how I'm finding that:
Get["https://raw.githubusercontent.com/b3m2a1/mathematica-tools/master/FENaming.wl"]
getCurrentPosition[tag_] :=
Module[
{
nextObj =
Replace[
BoxObject[
FENamed[_, tag <> "_gridElement"],
{FE`BoxOffset -> FE`BoxParent[3]}
],
Except[_BoxObject] :>
EvaluationBox[]
],
prevObj,
body,
inds
},
prevObj =
Replace[
FrontEndExecute@
FrontEnd`ObjectChildren@
FrontEndExecute@FrontEnd`ParentBox[nextObj],
{
{___, left_, nextObj, ___} :> left,
{nextObj, ___, last_} :> last,
_ -> None
}
];
If[prevObj === None,
body = NotebookRead[prevObj];
inds =
FirstCase[nextObj,
TagBox[__,
BoxID -> (s_String?(StringStartsQ[tag <> "_Position"]))] :>
ToExpression@
StringSplit[StringSplit[s, "_Position", 2][[-1]], ","],
{-1, -1},
6
];
inds = inds - {0, 1},
body = NotebookRead[prevObj];
inds =
FirstCase[body,
TagBox[__,
BoxID -> (s_String?(StringStartsQ[tag <> "_Position"]))] :>
ToExpression@
StringSplit[StringSplit[s, "_Position", 2][[-1]], ","],
{-1, -1},
6
]
];
inds
];
Then a very simple mover within a tagged grid and updated element wrapper:
moveAcrossTags[tag_, {dx_, dy_}] :=
With[{pos1 = getCurrentPosition[tag]},
NotebookLocate@
FENamed[_,
tag <> "_Position" <>
StringRiffle[
Map[ToString, pos1 + {dx, dy}],
","
]
]
]
makeNamedGridElements[gridEls_, tag_String] :=
MapIndexed[
EventHandler[
FENamed[
FENamed[#,
tag <> "_Position" <> StringRiffle[Map[ToString, #2], ","]],
tag <> "_gridElement"],
{
"RightArrowKeyDown" :> moveAcrossTags["realGrid", {0, 1}],
"LeftArrowKeyDown" :> moveAcrossTags["realGrid", {0, -1}],
"DownArrowKeyDown" :> moveAcrossTags["realGrid", {1, 0}],
"UpArrowKeyDown" :> moveAcrossTags["realGrid", {-1, 0}]
}
] &,
gridEls,
{2}
]
Finally:
realGrid =
Grid[
makeNamedGridElements[#, "realGrid"] &@
Partition[
Thread@
Graphics[
Thread[{RandomColor[25], Disk[]}],
ImageSize -> 25
],
5]
]
Original
Here's the start of a solution using the FENamed structure I defined here. We just attach a findable tag to each thing via the BoxID parameter, then we automatically get a clean way to find an element:
makeNamedGridElements[gridEls_, tag_String] :=
MapIndexed[
FENamed[#, tag <> Map[ToString, #2]] &,
gridEls,
{2}
]
realGrid =
Grid@makeNamedGridElements[#, "realGrid_"] &@
Partition[
Thread@
Graphics[
Thread[{RandomColor[25], Disk[]}],
ImageSize -> 25
],
5]
Once we have the current element it's easy to increment to the next, but finding the current one is admittedly beyond my ken right now.
A:
Perhaps something crude like this could work:
nb = EvaluationNotebook[];
GridBox[{{"a", "b", "c"}, {"d", "e", "f"}}] // DisplayForm
(* select col 2, row 2 -> 5 *)
SelectionMove[nb, Previous, Cell, 2];
SelectionMove[nb, Before, CellContents]
Do[SelectionMove[nb, Next, Character, 2], 5]
SelectionMove[nb, All, Word, 1]
|
[
"sharepoint.stackexchange",
"0000266151.txt"
] | Q:
Is it possible to create custom themes in SP2019?
In SP Online we can create custom themes using theme generator and we can use PS commands to push theme and apply. But what about 2019? Here also same way? If yes then how to push the custom theme that was generated to SP 2019 modern sites? I am not able to find any API to do this.
A:
According to the release notes for SharePoint 2019 custom themes did not make the cut and MS has not made any commitment regarding a feature pack. So the short answer seems to be No.
Source : https://docs.microsoft.com/da-dk/sharepoint/dev/general-development/sharepoint-2019-development-platform
|
[
"math.stackexchange",
"0002821330.txt"
] | Q:
Sequences series problem
Show that square of any even natural number $(2n)^2$ is equal to sum of $n$ terms of some series of integers in A.P
Please don't solve the question . I want to have a general idea regarding these type of problems.
A:
The general idea regarding these types of problems, is an inspection of the summation formula of $n$ terms of an arithmetic progression :
$$
S_n = \frac{n}{2}(2a + (n-1)d)
$$
where $a$ is the first term and $d$ is the common difference.
In your case, $S_n = 4n^2$ is specified, and $a$ and $d$ are to be decided.
Write this expression down and simplify it : $4n^2 = \frac n2 (2a + (n-1)d)$, so $8n = 2a + (n-1)d$.
This is true for all integers $n$, and the left hand side $8n$ is a polynomial.
To decide $a$ and $d$ , we now have the following way : assume that $a$ and $d$ depend polynomially on $n$ (that is, $a$ and $d$ are polynomials with the variable as $n$ e.g. $a = 2n^2 + 3n+8$, $d = 5$ etc.) Notice that the degree of the left hand side is $1$ ,so the degree of the right hand side is $1$. Hence, we may assume that $a$ must be of degree $1$ in $n$, and $d$ must be a constant, so that when we multiply it by $n-1$ we get at most a one degree polynomial.
So, write $a = bn+c$, and therefore : $8n = 2bn+2c+ dn - d$, so $(8-2b-d)n + (d-2c) = 0$.
When a polynomial is zero, so are all the coefficients. Hence, $2b+d = 8$ and $2c = d$.
At this stage, we have two equations in three variables. You will get a solution (if not, then the problem is impossible). For example, $d = 4$ gives you $b=c=2$.
Therefore, the sum of the first $n$ terms of the AP which starts with $2n+2$ and has common difference $4$, is $4n^2$.
For example, take $n = 3$ to get $8+12+16 = 36 = 4 \times 3^2$.
There is more than one solution : $b = 0, d=8,c=4$ is another. Consequently, the sum of the first $n$ terms of an AP with first term $4$ and common difference $8$, is $4n^2$. For example, with $n = 4$ one gets $4 + 12 + 20 + 28 = 64 = 4 \times 4^2$.
Summarizing, when $S_n$ is a polynomial in $n$, we assume that $a$ and $d$ are polynomials in $n$, such that $a$ has same degree as $S_n - 1$ (note : the $n$ on the RHS of the sum of AP formula comes into play here), and $d$ has same degree as $S_n - 2$, and then equate coefficients of RHS and LHS to get equations in the unknown coefficients of $a$ and $d$. Finding a solution of this then gives the desired result.
|
[
"mathematica.stackexchange",
"0000228693.txt"
] | Q:
Solving complex differential equation with ParametricNDSolveValue
I am trying to solve a complex differential equation for the function $S(u,v)$ depending on the parameter $\omega$. The code is:
ClearAll["Global`*"]
m = 100;
L = 2;
r[u_, v_] = 2 m (1 + ProductLog[- ((u v)/E)]);
F[u_, v_] = (32 m^3)/r[u, v]^3 Exp[-(r[u, v]/(2 m))];
Vz[u_, v_] = FullSimplify [-2 (D[F[u, v], u] D[F[u, v], v])/F[u, v] +
4 D[r[u, v], u, v]/r[u, v] + 2/F[u, v] D[F[u, v], u, v] +
2/F[u, v] D[F[u, v], u] D[r[u, v], v] +
2/F[u, v] D[F[u, v], v] D[r[u, v], u]];
Z[u_, v_] = Exp[-I (u + v)/2 ω] S[u, v];
sol = ParametricNDSolveValue[{D[Z[u, v], u, v] +
F[u, v] (L (L + 1))/r[u, v]^2 Z[u, v] + Z[u, v] Vz[u, v] == 0,
S[u, -1] == 1, S[1, v] == 1},
S, {u, 1, 100}, {v, -100, -1}, ω]
I get the error
ParametricNDSolveValue::mconly: "For the method !("IDA"), only
machine real code is available. Unable to continue with complex values
or beyond floating-point exceptions"
So it seems that Mathematica expects real numbers, but it finds complex numbers instead. How can I solve the differential equation?
A:
This question can be addressed by solving for Z rather than S, splitting the PDE into its real and imaginary parts, and later constructing S if desired.
solr[ω_] := NDSolveValue[{D[Z[u, v], u, v] +
F[u, v] (L (L + 1))/r[u, v]^2 Z[u, v] + Z[u, v] Vz[u, v] == 0,
Z[u, -1] == Cos[1/2 (-1 + u) ω], Z[1, v] == Cos[1/2 (1 + v) ω]},
Z, {u, 1, 2}, {v, -2, -1}]
soli[ω_] := NDSolveValue[{D[Z[u, v], u, v] +
F[u, v] (L (L + 1))/r[u, v]^2 Z[u, v] + Z[u, v] Vz[u, v] == 0,
Z[u, -1] == -Sin[1/2 (-1 + u) ω], Z[1, v] == -Sin[1/2 (1 + v) ω]},
Z, {u, 1, 2}, {v, -2, -1}]
zr = solr[1];
Plot3D[zr[u, v], {u, 1, 2}, {v, -2, -1}, PlotRange -> All,
ImageSize -> Large, AxesLabel -> {u, v, z}, LabelStyle -> {15, Black, Bold}]
zi = soli[1];
Plot3D[zi[u, v], {u, 1, 2}, {v, -2, -1}, PlotRange -> All,
ImageSize -> Large, AxesLabel -> {u, v, z}, LabelStyle -> {15, Black, Bold}]
Two notes. First, the integration ranges of u and v have been greatly reduced, because the solution grows exponentially large otherwise, and Plot3D fails. Second, using ParametricNDSolveValue instead of SetDelayed and NDSolveValue causes the kernel to crash.
|
[
"stackoverflow",
"0050416427.txt"
] | Q:
Clarification on how to verify Google In App Purchase purchase token on the server?
Given that my server end point has received a Purchase Token relating to a Google In App Billing purchase, how do I go about programmatically verifying it and gaining access to its contents?
I can already verify a Google Sign-In token using php
$client = new Google_Client(['client_id' => $client_id]);
$payload = $client->verifyIdToken($token);
if ($payload)
return $payload['sub'];
But how would I use the Google_Client to verify a purchase token and gain access to its contents.
Is it really just a case of sending a GET to the Google server much like in the following Ruby example ?
Or is their a specific Google_Client command I should be calling?
I'm beginning to think it's a case of replicating the mentioned Ruby code in php using OAuth2 or something since the Google Docs do actually say that once the server has the purchase token to:
Use the Subscriptions and In-App Purchases portion of the Google Play Developer API to perform a GET request to retrieve the purchase
details from Google Play (Purchases.products for a one-time product purchase or Purchases.subscriptions for a subscription). The GET request includes the app package name, product ID, and a token (purchase token).
Just wanted some clarification if possible? Thanks.
A:
To verify and obtain the details of a purchase token resulting from a Google in app purchase in your client app, use the following code PHP:
putenv('GOOGLE_APPLICATION_CREDENTIALS=/home/mydir/credentials.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/androidpublisher');
$service = new Google_Service_AndroidPublisher($client);
$purchase = $service->purchases_products->get($packageName, $skuID, $purchaseToken);
You can then access all the information you need by the usual ways, e.g.
echo $purchase['orderId'];
A full list of accessor names can be found in the Google Docs here https://developers.google.com/android-publisher/api-ref/purchases/products
The packageName is the name of your application package, the skuID is the string SKU ID of the managed product, which you can create in the Google Developer Console. The purchase token is that which is returned to you within your client application on a successful in app purchase result, so you'll need to send that to your server end point via a POST command over HTML. Don't forget to use SSL/TLS to do this.
The credentials.json file is downloaded automatically from the Google Developer Consoler when you create a new Service Account under Settings/API access.
|
[
"mathematica.stackexchange",
"0000018967.txt"
] | Q:
Detect highest order of derivative in expression?
Is it possible to detect the highest order (or generally all orders) of derivatives in an expression?
Consider
eqn = D[a[x,t],t] == D[a[x,t],x,x]
How would I go about detecting that the highest order of the partial derivative in x is 2 in eqn?
I was thinking of using MatchQ, however this
MatchQ[Derivative[2, 0][a][x, t], eqn]
just returns False.
Thank you!
A:
How about this:
Cases[eqn, Derivative[orders__] -> {orders}, Infinity, Heads -> True]
(* Out: {{0, 1}, {2, 0}} *)
Now, you've got the orders of each derivative returned in a list that you can manipulate as you please.
|
[
"stackoverflow",
"0004945819.txt"
] | Q:
PEAR Mail, Mail_Mime and headers() overwrite
I'm currently working on a reminder PHP Script which will be called via Cronjob once a day in order to inform customers about smth.
Therefore I'm using the PEAR Mail function, combined with Mail_Mime. Firstly the script searches for users in a mysql database. If $num_rows > 0, it's creating a new Mail object and a new Mail_mime object (the code encluded in this posts starts at this point). The problem now appears in the while-loop.
To be exact: The problem is
$mime->headers($headers, true);
As the doc. states, the second argument should overwrite the old headers. However all outgoing mails are sent with the header ($header['To']) from the first user.
I'm really going crazy about this thing... any suggestions?
(Note: However it's sending the correct headers when calling $mime = new Mail_mime() for each user - but it should work with calling it only once and then overwriting the old headers)
Code:
// sql query and if num_rows > 0 ....
require_once('/usr/local/lib/php/Mail.php');
require_once('/usr/local/lib/php/Mail/mime.php');
ob_start();
require_once($inclPath.'/email/head.php');
$head = ob_get_clean();
ob_start();
require_once($inclPath.'/email/foot.php');
$foot = ob_get_clean();
$XY['mail']['params']['driver'] = 'smtp';
$XY['mail']['params']['host'] = 'smtp.XY.at';
$XY['mail']['params']['port'] = 25;
$mail =& Mail::factory('smtp', $XY['mail']['params']);
$headers = array();
$headers['From'] = 'XY <[email protected]>';
$headers['Subject'] = '=?UTF-8?B?'.base64_encode('Subject').'?=';
$headers['Reply-To'] = 'XY <[email protected]>';
ob_start();
require_once($inclPath.'/email/templates/files.mail.require-review.php');
$template = ob_get_clean();
$crfl = "\n";
$mime = new Mail_mime($crfl);
while($row = $r->fetch_assoc()){
$html = $head . $template . $foot;
$mime->setHTMLBody($html);
#$to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <'.$row['email'].'>'; // for testing purpose i'm sending all mails to [email protected]
$to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <[email protected]>';
$headers['To'] = $to; // Sets to in headers to a new
$body = $mime->get(array('head_charset' => 'UTF-8', 'text_charset' => 'UTF-8', 'html_charset' => 'UTF-8'));
$hdrs = $mime->headers($headers, true); // although the second parameters says true, the second, thrid, ... mail still includes the To-header form the first user
$sent = $mail->send($to, $hdrs, $body);
if (PEAR::isError($sent)) {
errlog('error while sending to user_id: '.$row['id']); // personal error function
} else {
// Write log file
}
}
A:
There is no reason to keep the old object and not creating a new one.
Use OOP properly and create new objects - you do not know how they work internally.
|
[
"stackoverflow",
"0000493090.txt"
] | Q:
Regex to strip lat/long from a string
Anyone have a regex to strip lat/long from a string? such as:
ID: 39.825 -86.88333
A:
To match one value
-?\d+\.\d+
For both values:
(-?\d+\.\d+)\ (-?\d+\.\d+)
And if the string always has this form:
"ID: 39.825 -86.88333".match(/^ID:\ (-?\d+\.\d+)\ (-?\d+\.\d+)$/)
A:
var latlong = 'ID: 39.825 -86.88333';
var point = latlong.match( /-?\d+\.\d+/g );
//result: point = ['39.825', '-86.88333'];
|
[
"stackoverflow",
"0017538027.txt"
] | Q:
Default language with one "values" folder
I just wrote an android application and I'm about to publish it. But I have a problem, the APK is uploaded ok, but when writing the information of the application in Google Play, detects "Spanish" as the default language.
In the code, I only have a unique folder named values. Shouldn't it detect default language as english? Or where is this default language configured?
Thanks
A:
You might have accidently checked Spanish when you were creating the listing. You can click on "Add translations", pick English, then switch it to the default language. Afterwards you should see a "Manage translations" option where you can remove Spanish from your languages.
|
[
"math.stackexchange",
"0001682683.txt"
] | Q:
Want to check that $\sum_{j=0}^{k-1}w^{ jm}=0$, $m\not\equiv 0 \pmod{k}$ where $w=e^{2\pi i/k}$
If $f(x)=\sum_{n=0}^{\infty}a_{n}x^{n}$, then
$$ \sum_{n=0}^{\infty}a_{kn+m}x^{kn+m}=\frac{1}{k}\sum_{j=0}^{k-1}w^{-jm}f(w^j x) \tag{1},$$
where $w=e^{2\pi i/k}$ is a primitive $k$th root of unity. This is a consequence of $\sum_{j=0}^{k-1}w^{ jm}=0$, $m\not\equiv 0 \pmod{k}$.
This is taken a proof from Special Functions page 14. I want to verify $(1)$. I suppose the series of $f(x)$ is convergent, and we rewrite the $(1)$ as follows
$$\sum_{n=0}^{\infty}a_{kn+m}x^{kn+m}=\sum_{n=0}^{\infty}\underbrace{\frac{1}{k}\sum_{j=0}^{k-1}w^{j(n-m)}}_{=:\,p(n)}a_{n}x^n.$$
If $n=\ell k+m$ for all $\ell\in\mathbb{Z}$, then
$$p(\ell k+m)=\frac{1}{k}\sum_{j=0}^{k-1}w^{j\ell k}=\frac{1}{k}\sum_{j=0}^{k-1}1^{j}=1.$$ I think the last sentence in the quote says that if $n\neq \ell k+m$ for all $\ell\in\mathbb{Z}$, then $p(n)=0$. But I am not sure how to check it in general.
A:
We have that $\;\omega\;$ is a root of $\;x^k-1\;$ and, in fact, of the $\;k-$th cyclotomic polynomial:
$$\sum_{j=0}^{k-1}\left(\omega^m\right)^j\stackrel{\text{geom. sum}}=\frac{1-\omega^{mk}}{1-\omega^m}=0\;,\;\;\text{because}\;\;\omega^{mk}=\left(\omega^k\right)^m=1\;\;\text{and}\;\;\omega^m\ne1$$
Why the condition $\;m\neq0\pmod k\;?$ Because otherwise
$$m=lk\implies \omega^m=\left(\omega^k\right)^l=1\implies\sum_{j=0}^{k-1}\left(\omega^m\right)^j=\sum_{j=0}^{k-1}1=k$$
Also, if $\;\omega^m=1\;$ we cannot for sure use the formula we used above in the first equality.
|
[
"japanese.stackexchange",
"0000032436.txt"
] | Q:
In Japanese, can we say an object asks a question?
I was just wondering, because in English we can say "This story begs the question" etc. The wording for English is very versatile, and I was wondering if Japanese has this as well, for example in this sentence:
このゲームは質問を頼む
A:
In English, an inanimate thing can frequently be the subject of a sentence as if the thing had its will. In Japanese, that happens less often, and many sentences are better translated into Japanese by selecting other words as the subject. Wikipedia has some examples of such sentences. To take a few:
The book will teach you the basic conversation of Spanish. (△その本はスペイン語会話の基礎を教える。)
→ By reading the book you can learn the basic conversation of Spanish. (その本を読めばスペイン語会話の基礎が学べる。)
The airplane enables you to reach Los Angels tomorrow. (△飛行機はあなたを明日ロサンゼルスに着くのを可能にする。
→ Thanks to the airplane, you can reach Los Angels tomorrow. (飛行機のおかげであなたは明日ロサンゼルスに到着することができる。)
The heavy snow prevented him from going home yesterday. (△あの大雪は彼の昨日の帰宅を妨げた。
→ Due to the heavy snow, he could not go home yesterday. (あの大雪のため、彼は昨日家に帰れなかった。)
This photo reminds me of my childhood. (△この写真は、子ども時代をわたしに思い起こさせる。)
→ When I see this photo, I recall my childhood. (この写真を見ると私は子どもの頃を思い出す。)
The English sentences are followed by the literal Japanese translation. Here "△" indicates that that Japanese sentence is probably understandable but unnatural, because an inanimate thing like book or airplane is the subject. To translate such sentences naturally, you have to rephrase them so that a living thing becomes the subject, as shown in the second line of each bullet.
|
[
"stackoverflow",
"0046205115.txt"
] | Q:
Firebase forgot password domain
I have a firebase app offering the "forgot password" capability.
Is there a way to make it link to my own hosting domain instead of appName-id.firebaseapp.com?
I tried adding it from hosting, and for the email templates, but I can't find a way to do it for the reset password link
A:
It seems like I can change the action URL, to:
https://my-hosting-domain/__/auth/action
So I guess this is solved
|
[
"stackoverflow",
"0048250251.txt"
] | Q:
Emiting websocket message from routes
I'm trying to setup my server with websockets so that when I update something via my routes I can also emit a websocket message when something on that route is updated.
The idea is to save something to my Mongo db when someone hits the route /add-team-member for example then emit a message to everyone who is connected via websocket and is a part of whatever websocket room that corresponds with that team.
I've followed the documentation for socket.io to setup my app in the following way:
App.js
// there's a lot of code in here which sets what to use on my app but here's the important lines
const app = express();
const routes = require('./routes/index');
const sessionObj = {
secret: process.env.SECRET,
key: process.env.KEY,
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
secret : 'test',
cookie:{_expires : Number(process.env.COOKIETIME)}, // time im ms
}
app.use(session(sessionObj));
app.use(passport.initialize());
app.use(passport.session());
module.exports = {app,sessionObj};
start.js
const mongoose = require('mongoose');
const passportSocketIo = require("passport.socketio");
const cookieParser = require('cookie-parser');
// import environmental variables from our variables.env file
require('dotenv').config({ path: 'variables.env' });
// Connect to our Database and handle an bad connections
mongoose.connect(process.env.DATABASE);
// import mongo db models
require('./models/user');
require('./models/team');
// Start our app!
const app = require('./app');
app.app.set('port', process.env.PORT || 7777);
const server = app.app.listen(app.app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
const io = require('socket.io')(server);
io.set('authorization', passportSocketIo.authorize({
cookieParser: cookieParser,
key: app.sessionObj.key, // the name of the cookie where express/connect stores its session_id
secret: app.sessionObj.secret, // the session_secret to parse the cookie
store: app.sessionObj.store, // we NEED to use a sessionstore. no memorystore please
success: onAuthorizeSuccess, // *optional* callback on success - read more below
fail: onAuthorizeFail, // *optional* callback on fail/error - read more below
}));
function onAuthorizeSuccess(data, accept){}
function onAuthorizeFail(data, message, error, accept){}
io.on('connection', function(client) {
client.on('join', function(data) {
client.emit('messages',"server socket response!!");
});
client.on('getmessage', function(data) {
client.emit('messages',data);
});
});
My problem is that I have a lot of mongo DB save actions that are going on in my ./routes/index file and I would like to be able to emit message from my routes rather than from the end of start.js where socket.io is connected.
Is there any way that I could emit a websocket message from my ./routes/index file even though IO is setup further down the line in start.js?
for example something like this:
router.get('/add-team-member', (req, res) => {
// some io.emit action here
});
Maybe I need to move where i'm initializing the socket.io stuff but haven't been able to find any documentation on this or perhaps I can access socket.io from routes already somehow?
Thanks and appreciate the help, let me know if anything is unclear!
A:
Your io is actually the socket object, you can emit events from this object to any specific user by -
io.to(userSocketId).emit('eventName', data);
Or you can broadcast by -
io.emit('eventName', data);
Just create require socket.io before using it :)
|
[
"stackoverflow",
"0017003725.txt"
] | Q:
Catel Framework Debug Error
I'm trying to learn Catel MVVM by getting the simplest of bare bones example of Catel to work on VS Express 2012 and keep getting an error. I think my problem lies in my "using" statements, references, or the header in my XAML. An auto-generated file writes the offending line as shown below in MainWindow.g.cs The code files are very short, so I've included them.
The model, viewmodel, and view are separated into three projects all under one solution.
Model- blank for now
ViewModel -MainWindowViewModel (no properties yet)
View -MainWindow.xmal, MainWindow.xmal.cs (no controls or properties yet)
I keep getting the following warning with an accompanying error:
The type 'Catel.Windows.DataWindow' in 'c:...\MainWindow.g.cs'
conflicts with the imported type 'Catel.Windows.DataWindow' in
'c:...\Catel.MVVM.dll'. Using the type defined in
'c:...\MainWindow.g.cs'.
and the error:
Catel.Windows.DataWindow < ViewModels.MainWindowViewModel > is
obsolete: 'Please use 'Catel.Windows.DataWindow' instead. Will be
removed in version '4.0'.'
C:...\MyFirstCatel\obj\Debug\MainWindow.g.cs
MainWindow.xaml
<Windows:DataWindow
x:Class="Catel.Windows.DataWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:MainWindowViewModel="clr-namespace:ViewModels"
xmlns:Windows="clr-namespace:Catel.Windows;assembly=Catel.MVVM"
x:TypeArguments="MainWindowViewModel:MainWindowViewModel"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock>Hello world!</TextBlock>
</Grid>
</Windows:DataWindow>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Catel.Windows;
namespace MyFirstCatel
{
public partial class MainWindow : Catel.Windows.DataWindow
{
public MainWindow()
{
InitializeComponent();
}
}
}
MainWindowViewModel.cs
using System.Windows;
using Catel.MVVM;
namespace ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
public MainWindowViewModel()
: base()
{
}
public override string Title { get { return "View model title"; } }
public string Slug
{
get { return GetValue<string>(SlugProperty); }
set { SetValue(SlugProperty, value); }
}
public static readonly Catel.Data.PropertyData SlugProperty = RegisterProperty("Slug", typeof(string), null);
}
}
And in MainWindow.g.cs
namespace Catel.Windows {
public partial class DataWindow : Catel.Windows.DataWindow<ViewModels.MainWindowViewModel>, System.Windows.Markup.IComponentConnector
{
private bool _contentLoaded;
... code removed for post ....
}
}
A:
There is only one thing that is wrong. Inside your xaml definition you still use the old way of specifying the vm type. Remove the x:TypeArguments and the error should go away.
|
[
"stackoverflow",
"0039045807.txt"
] | Q:
Pure DQL vs DQB?
Can someone elaborate performance of DQL and DQL? I am comfortable with both but concerned if there is some performance issues?
In short,
Which one is faster performance wise, Doctrine Query Language or Doctrine Query Builder?
A:
DQL is faster because the QueryBuilder is a step to build a DQL query.
Only use QueryBuilder if your query needs to be "built" (adding terms depending on some logic)
|
[
"stackoverflow",
"0062696642.txt"
] | Q:
Set interval with background image changing caused a lag
I'm trying to create an animation switching between 2 images used as the background image of a div here's my code:
var intervalloNavicella = setInterval(function() {
if (accese == true) {
var imageUrlSpacecrafat = "bk-nav-0" + currArea;
$("#spacecraft").css(
"background-image",
"url(assets/img/" + imageUrlSpacecrafat + ".png)"
);
accese = false;
} else {
var imageUrlSpacecrafat = "bk-nav-0" + currArea + "-b";
$("#spacecraft").css(
"background-image",
"url(assets/img/" + imageUrlSpacecrafat + ".png)"
);
accese = true;
}
}, 500);
It works, the only problem is that during the changing sometimes there are some moments when the animation "lag" and there is no background image. This happens a lot of times and only for a few milliseconds.
Is this a browser problem or this is about my code?
A:
Why not something like
var intervalloNavicella = setInterval(function(){
$('#spacecraft').toggleClass("spacecraftb")
}, 500);
.spacecraft {
background-image : url(assets/img/bk-nav-0A.png);
}
.spacecraftb {
background-image : url(assets/img/bk-nav-0B.png);
}
<div id="spacecraft" class="spacecraft"></div>
|
[
"gis.stackexchange",
"0000004259.txt"
] | Q:
How to dock the default ObjectInspector in a new parent container?
Into my object inspector fever, I noticed that the default Object Inspector object does not dock anymore.
I only have a TabPage control and two tabs, one of those hosting the default inspector. (check black marks)
The other tabs works fine.
Also, this is the code I'm using for the Inspect() method:
public void Inspect(IEnumRow objects, IEditor Editor)
{
SetParent(_Inspector.HWND, DefaultPanelHandle);
ShowWindow(_Inspector.HWND, SW_SHOW);
_Inspector.Inspect(objects, Editor);
}
Why the default does not dock anymore? Any workarounds?
A:
You can create a wrapper control which essentialy houses the ESRI's object inspector window and assures that any resizes are also reflected in the default inspector:
public class WindowContainerControl : Control
{
private readonly IntPtr _childHandle;
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool MoveWindow(IntPtr hWnd, int x, int y, int nWidth, int nHeight, bool repaint);
private const int SW_SHOW = 5;
public WindowContainerControl(IntPtr childHandle)
{
_childHandle = childHandle;
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
SetParent(_childHandle, Handle);
ShowWindow(_childHandle, SW_SHOW);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
if (IsHandleCreated)
{
MoveWindow(_childHandle, 0, 0, ClientSize.Width, ClientSize.Height, true);
}
}
}
Then, when you create the window for your custom object inspector (I assume it's an UserControl), you add this container in it and associate it with the ESRI's inspector handle. See below.
Here I assume the DefaultPanel is a Panel control in your tab page. Due to some weirdness you cannot place the container control directly to a tab page but you need to use an intermediate panel. Your scenario may be different, but I initialize the controls only when my implementation of IObjectInspector.HWND is first called:
// the container will reparent and house the default inspector
var windowContainer = new WindowContainerControl(_Inspector.HWND);
// when the size of the parent changes, the container's size changes
// as well, in turn the housed inspector window is also resized
windowContainer.Dock = DockStyle.Fill;
// The control containing the tabcontrol and it's pages.
// One of the pages has the panel in it (docked as well), exposed
// as the DefaultPanel property or field.
_myInspectorUserControl = new MyInspectorUserControl();
// Add the container in the custom inspector's designated panel
_myInspectorUserControl.DefaultPanel.Controls.Add(windowContainer);
// return the _myInspectorUserControl hwnd
You may not go for this exact solution (just tested to work in ArcMap 9.3.1), but you get the gist - you basically need to resize the inner default inspector whenever the parent's size changes. The WindowContainerControl class merely does the dirty work of altering its child's size to fill its client area. Thus you only need to dock the WindowContainerControl instance, it takes care of the rest.
|
[
"worldbuilding.stackexchange",
"0000135206.txt"
] | Q:
What energy sources would a species use if they didn't have access to fossil fuels?
I'm designing an alien race that hasn't developed electricity yet. Now, one thing about their species is that they haven't discovered fossil fuels on their planet to use, like coal, oil, etc. (The reason for this isn't clear at this moment but I think I can figure something out later.)
So I was thinking, if a civilization couldn't use fossil fuels as a starting point for generating energy, what alternate sources of energy would they begin with? Are renewables an option, or does that require more advanced technology in order to make? Another option, is the fact that plants on their planet have nervous systems, and maybe they could extract energy from them, however I think that still requires technology that is far ahead for their civilization and I'm not certain if such an "energy source" would last long or give enough energy.
So my question is, if a civilization can't use fossil fuels to develop, then what other energy sources exist as a starting point?
Note: I don't know if this is useful information or not, but they use bioluminescent plants to light up their cities at nights instead of making fire or gas lights.
A:
Wood
You said they don't have access to fossil fuels, but not to a forest. Using wood as fuel can be a good way to start gathering energy, in form of steam engine if you are looking for mechanical energy instead of heat. For the link:
A common hardwood, red oak, has an energy content (heat value) of 14.9 megajoules per kilogram [...]
Wood as fuel can be used in firewood, chips, wood pellets or sawdust, as residue from other process.
After your species advances more technologically, and want, for example, melt iron, they will develop charcoal using charcoal burner. From there, and there:
Charcoal burns at temperatures exceeding 1,100 degrees Celsius (2,010 degrees Fahrenheit). By comparison the melting point of iron is approximately 1,200 to 1,550 °C (2,190 to 2,820 °F). Due to its porosity, it is sensitive to the flow of air and the heat generated can be moderated by controlling the air flow to the fire. For this reason charcoal is still widely used by blacksmiths. Charcoal has been used for the production of iron since Roman times and steel in modern times where it also provided the necessary carbon. Charcoal briquettes can burn up to approximately 1,260 °C (2,300 °F) with a forced air blower forge.
[...]
Historically, charcoal was used in great quantities for smelting iron in bloomeries and later blast furnaces and finery forges.
Even more, you can make syngas with wood:
Like many other sources of carbon, charcoal can be used for the production of various syngas compositions; i.e., various CO + H2 + CO2 + N2 mixtures. The syngas is typically used as fuel, including automotive propulsion, or as a chemical feedstock.
In times of scarce petroleum, automobiles and even buses have been converted to burn wood gas (a gas mixture consisting primarily of diluting atmospheric nitrogen, but also containing combustible gasses, mostly carbon monoxide) released by burning charcoal or wood in a wood gas generator. In 1931 Tang Zhongming developed an automobile powered by charcoal, and these cars were popular in China until the 1950s and in occupied France during World War II (called gazogènes).
Water
From ancients times there is a certain machine called water mill. From the link.
A watermill or water mill is a mill that uses hydropower. It is a structure that uses a water wheel or water turbine to drive a mechanical process such as milling (grinding), rolling, or hammering. Such processes are needed in the production of many material goods, including flour, lumber, paper, textiles, and many metal products. These watermills may comprise gristmills, sawmills, paper mills, textile mills, hammermills, trip hammering mills, rolling mills, wire drawing mills.
The water wheel is medieval technology, while the water turbine is current technology.
Watermill works gathering mechanical energy from a flow of water, like a river.
Wind
In addition to watermills, there exist Windmills which channels mechanical power from the wind itself. From the link:
A windmill is a mill that converts the energy of wind into rotational energy by means of vanes called sails or blades. Centuries ago, windmills usually were used to mill grain (gristmills), pump water (windpumps), or both. The majority of modern windmills take the form of wind turbines used to generate electricity, or windpumps used to pump water, either for land drainage or to extract groundwater.
The today technology is called wind turbine.
Animals
Additionally, you can use animals, primary horses, in a horsemill. From the link:
A horse mill is a mill, sometimes used in conjunction with a watermill or windmill, that uses a horse engine as the power source. Any milling process can be powered in this way, but the most frequent use of animal power in horse mills was for grinding grain and pumping water. Other animal engines for powering mills are powered by dogs, donkeys, oxen or camels. Treadwheels are engines powered by humans.
A:
Poop! Poop! And more Poop!
But seriously, dried animal dung is a very common fuel, even today in some places.
You can burn it like wood.
Dry dung fuel (or dry manure fuel) is animal feces that has been dried
in order to be used as a fuel source. It is used as a fuel in many
countries around the world. Using dry manure as a fuel source is an
example of reuse of excreta. A disadvantage of using this kind of fuel
is increased air pollution. In India, this kind of fuel source is
known as "dung cakes". (ref)
You can power machines with it.
Stirling-Motor powered with cow dung in the Technical Collection Hochhut in Frankfurt on Main (ref)
You can power transportation.
The UK debuted its first poop-powered buses, which will transport
about 10,000 monthly commuters between Bath and Bristol Airport.
These "Bio-Buses" are the fruit of a partnership between the Bath Bus
Company and Bristol's sewage treatment system, which is run by a
company called GENeco. They can travel about 186 miles on the yearly
waste of five people, offering a more sustainable alternative to
natural gas-powered vehicles. (ref)
You can turn sewage into fuel in a variety of ways.
True to its rich history, poop-based energy has now evolved into a
multifaceted and diverse set of industries. In 2004, a waste
management facility in Renton, Washington received a $22,000,000
grant to build a power plant that could turn sewage into electricity.
The same year, a rancher figured out how to power his dairy farm with
cow patties and an engineering professor turned pig crap into crude
oil. (ref)
You can turn manure into natural gas.
Natural gas, though a significant contributor to climate change, is
the cleanest-burning fossil fuel. Turning cow manure into natural gas
would have three big advantages. First, it would turn animal waste, a
major source of carbon pollution, into a useful fuel. Second, it would
provide a new source of natural gas, which could be used to replace
dirtier fuels like coal and oil. Third, it would reduce the need for
fracking, the environmentally-destructive practice that extracts
natural gas from the earth. (ref)
Livestock waste yields biogas which is refined into natural gas (ref)
A:
Wind and water
To answer your question, look no further than the old industrial regions of the US and Europe right before coal became commercially viable. Every town had a mill pond, and below it, industry. Mills, presses, machine works, you name it. Plants had central shaft drive, with belts driving individual machines. That came off a water wheel.
Wind was used to pump. The famous Aermotor windmill, for instance. They are still in business, and are fairly crabby about people asking them how to make electricity with their windmill. Theirs is made to pump.
Transportation? Canals. That is how coal first made it to market in large enough quantities to become commercially useful.
Electricity transmits
For development of electricity, lack of fossil fuels wouldn't even be a speed bump. The first electric plants of any scale were hydro - starting for instance with facilities at Niagara Falls. It is still a large piece of the energy pie, especially in places rich with it, like eastern Canada and the American South. It even shows up in dry, dry California - flow is very poor but exploitable height makes up for it, like Oroville with a paltry 2000 CFM flow but 700' of head.
Coal already had it feet planted, but if it hadn't, windmill manufacturers would have had no trouble figuring out how to design windmill blades to run the right speed and autofeather so windmills can sync onto the power grid and do useful work.
There's a real problem with wind "cutting out on you" arbitrarily. In a hydro-heavy world, you solve that by using wind-generated electricity for backpumping (pumped storage). You have a significant pound (lake, reservoir, impoundment) at the bottom and the top of a hill. When there is a wind surplus, that energy is used to pump the water from the lower pound to the upper. (Aermotors would work on a primitive windmill-at-the-hill setup). When the wind slakes, water falls down through turbines. Examples: the pumped-storage projects at Muskegon and Niagara. (At Niagara the top pound is much higher than the top of the falls).
This function adds extremely well onto existing hydro dams - just build or adapt the system to include a pound at the bottom of the dam. The pound doesn't even have to be anywhere near the dam, just at the same altitude, e.g. The Thermalito Forebay, which is the lower pound at Oroville but miles away from it. Oroville backpumps from the far-too-small Thermalito Diversion Pool at its base, but as water level drops, water flows backwards from the Forebay to refill it.
Total grid capacity is then limited by the hydro capacity + average wind. The commercial market sorts out the rest.
|
[
"stackoverflow",
"0053348118.txt"
] | Q:
how to use datatable in php when we have large amunt of data
I used datatable jquery plugin it's working perfactly but now i have large amount of data like 100000 row so it just loading for 10-15 minutes can anyone suggent how to fix this loading issu with mysql and php using limit or something like this.
https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js
A:
Could you try a LIMIT clause in your query:
https://www.w3schools.com/php/php_mysql_select_limit.asp
Your offset can be calculated by using the current page number - which could be passed in using jquery/ajax.
|
[
"stackoverflow",
"0018210270.txt"
] | Q:
What is the difference between assert and static_assert?
I know that static_assert makes assertions at compile time, and assert - at run time, but what is the difference in practice? As far as I understand, deep down they are pieces of code, like
if (condition == false) exit();
Can someone give me an example of where only static_assert will work, or only assert?
Do they do anything a simple if statement can't do?
Is it bad practice to use them?
A:
You ask three questions, so I will try to answer each of them.
Can someone give me an example of where only static_assert will work, or only assert?
static_assert is good for testing logic in your code at compilation time. assert is good for checking a case during run-time that you expect should always have one result, but perhaps could somehow produce an unexpected result under unanticipated circumstances. For example, you should only use assert for determining if a pointer passed into a method is null when it seems like that should never occur. static_assert would not catch that.
Do they do anything a simple if statement can't do?
assert can be used to break program execution, so you could use an if, an appropriate error message, and then halt program execution to get a similar effect, but assert is a bit simpler for that case. static_assert is of course only valid for compilation problem detection while an if must be programmatically valid and can't evaluate the same expectations at compile-time. (An if can be used to spit out an error message at run-time, however.)
Is it bad practice to use them?
Not at all!
A:
static_assert is meant to make compilation fail with the specified message, while traditional assert is meant to end the execution of your program.
A:
OK, I'll bite:
Only static_assert works if you want compilation to stop unsuccessfully if a static condition is violated: static_assert(sizeof(void*) != 3, "Wrong machine word size");* Only dynamic assertions can catch dynamic conditions: assert(argc == 1);
Simple if statements have to be valid and compilable; static assertions cause compilation failures.
No.
*) A practical example might be to prevent the abuse of generic template constructions, such as int x; std::move<int&&>(x).
|
[
"stackoverflow",
"0026649032.txt"
] | Q:
Excel VBA - struggling to create macros which takes action on cell values by column
Very new to Excel VBA, and struggling.
I'm a junior C# developer, but am finding that writing simple statements in VBA is very tricky for me. Can anyone tell me how to write VBA code for the following pseudocode requirements please?
Insert True into Column E only WHERE there is a specific string value of X in column A
Insert False into Column E WHERE there is text (ie: something/anything) in column D AND no text (ie: nothing) in Column A
Delete X wherever there is a specific string value X in any cell in Column A.
Any help at all would be so greatly appreciated.
A:
Public Sub Text_Process()
Dim lngLastRow As Long
Dim lngRow As Long
Dim strColA As String
Dim strColD As String
lngLastRow = Sheet1.UsedRange.Rows.Count
For lngRow = 1 To lngLastRow ' change 1 to 2 if you have headings in row 1
strColA = Sheet1.Cells(lngRow, 1).Value ' store value in column A
strColD = Sheet1.Cells(lngRow, 4).Value ' store value of column D
Sheet1.Cells(lngRow, 5).Clear ' clear column E
If strColA = "X" Then ' or whatever you are looking for
Sheet1.Cells(lngRow, 5).Value = True
ElseIf strColA = "" And strColD <> "" Then
Sheet1.Cells(lngRow, 5).Value = False
End If
If strColA = "X" Then ' or whatever you are looking for
Sheet1.Cells(lngRow, 1).Clear ' clear out the value in column A, is this is what is requried?
End If
Next lngRow
End Sub
|
[
"arduino.stackexchange",
"0000066469.txt"
] | Q:
Is it possible to execute a code in runtime when gets updated over the air (OTA)?
I would like to build a lib like ArduinoOTA but with no downtime at runtime. To achieve that I am wondering if it is possible to create a simple setup and loop code to
Check for new releases
If we have a new one start download it
As download routine is not finished keep running the current release
When download has finished, swap current release to the new one.
Now the normal routine is running the new release.
I am pretty interested if it is possible to do by myself something like that.
I didn't find any paper or articles similar to this and I don't known if this is a challenge for Arduino scope or C/C++.
Maybe I am saying something bizarre but I have been thinking of save new release into flash memory, point to it and discard the old release from flash memory.
A:
On many Arduinos the processor is only a few dollar part. You are asking for a feature that only starts appearing on platforms where the processor is over an order of magnitude higher in price. Further, such inexpensive processors normally run a single program. Running a sketch while managing a download & update would best be done by two programs existing in an operating system. Again, likely requiring a processor an order of magnitude higher in price.
Instead, consider implementing your design using two different Arduinos. Swapping one out for the other after updating. Hot swapping may not be trivial. This really depends on how your application interfaces with the world. But likely will be much easier than solving the problem of designing the supporting software to make sketch updates transparent to the Arduino user.
|
[
"stackoverflow",
"0038450876.txt"
] | Q:
UFT/QTP = Not getting updated value from Excel
We are using UFT12.51 for test automation.
We are facing below issue ONLY when we put our scripts for night execution.
We have used '=Today()' function in excel to get today's date.
Today's date is 19 July 2016. When we put scripts for night execution, after 11:59PM excel should give updated date [ 20 July 2016] but it send 19 July 2016 & due which our validation get failed.
What can be done to get updated value from Excel after 11:59PM?
A:
Excel calculation of formulas doesn't work in datatables for UFT - it just reads the values and doesn't do the recalculation that you are looking for. You would be better placed not leaving a current date value in a datatable and instead simply using the vbscript Date function for the current date, which is available in UFT/QTP and would correctly set the date as you require.
|
[
"stackoverflow",
"0000212009.txt"
] | Q:
Do I have to explicitly call System.exit() in a Webstart application?
Recently I converted a Swing application to Webstart. The process was pretty straightforward, but I found that after I close all windows, my application's JVM did not terminate. The thread dump showed that there are a couple of non-daemon threads, notably Swing's EDT, AWT and a couple of websart related threads.
The actual strategy used is that each window increments a counter when it is created and decrements one when it is closed. The default close operation is DISPOSE_ON_CLOSE. Wen the counter reaches zero, I stop all threadpools and release all JNI resources.
When I launched the application from a bat file (same JARs), it terminated fine when all windows were closed, so I figured that the problem has something to do with Webstart.
Now the questions:
Can anybody tell me what exactly is happening? Why does Webstart leave zombie JVMs?
Is there a way to release the Webstart resources explicitly without halting the JVM?
I've always had the opinion that calling System.exit() encourages the sloppy practice of not releasing your resources and relying on the OS to clean up after you (which can lead to nasty surprises if you reuse the code later)... am I missing something?
See also the followup question for detecting whether the app has been launched by Webstart.
A:
Because of bugs in WebStart, yes. WebStart starts up a "secure thread" for it's own purposes that interacts with the EDT. This SecureThread prevents the automatic termination of the Java process one would expect when all windows and AWT resources are disposed.
For more information see http://www.pushing-pixels.org/?p=232
|
[
"stackoverflow",
"0050933139.txt"
] | Q:
My code won't round my float
After tinkering with the syntax and perusing the over blog related to floating number imprecision I thought I had cracked the nut with my attempt to round my numbers. But when I enter 0.41 in my terminal I get a runtime error instead of the the 4 coins it should take to get to 41p.
Is my syntax/formula correct for rounding floats correct?
//Prompt user for an amount of change
do
{
dollars = get_float("change owed: ");
}
while (dollars < 0);
//convert float (dollars) to integer (cents) and then round
int cents = round(dollars * 100);
int coins = 0;
while (cents >= 25)
{
coins++;
cents-= 25;
}
while (cents >= 10)
{
coins++;
cents -=10;
}
while (cents >= 5)
{
coins++;
cents +=5;
}
while (cents >= 1)
{
coins++;
cents -=1;
}
printf("%i\n", coins);
}
i am getting this error message - runtime error: signed integer overflow: 2147483646 + 5 cannot be represented in type 'int'
429496731
A:
Change
cents +=5;
to
cents -=5;
That said - don't use float for a problem like this. Read the input as a string and convert directly to an int or unsigned int
|
[
"stackoverflow",
"0017995399.txt"
] | Q:
2 Images in UITableViewCell
I want 2 images in my TableViewCell but I don't know how and I don't know if it's possible but the idea is.
![enter image description here][1]
Is this possible? If it is, how can I do this?
I googled but couldn't find the solution.
Thanks!
A:
Hope this is what this is looking for. Check below project
https://github.com/slysid/iOS/tree/master/TwoImages
Bharath
|
[
"stackoverflow",
"0003791096.txt"
] | Q:
Devise logged in root route rails 3
Heyya guys.
So i thought about this coolio idea, if you are logged in then you get some sort of dashboard, else you get an information/login/sign up page.. So how do i do that..
I mostly wants to do this in Routes = not something like
def index
if current_user.present?
render :action => 'logged_in'
else
render :action => 'logged_out'
end
end
thanks in advance!
/ Oluf Nielsen
A:
Think you may have been looking for this:
authenticated :user do
root :to => "dashboard#show"
end
root :to => "devise/sessions#new"
Note: it's authenticate*d*
A:
I too wanted this in my app, here's what I came up with.
MyCoolioApp::Application.routes.draw do
root :to => 'users#dashboard', :constraints => lambda {|r| r.env["warden"].authenticate? }
root :to => 'welcome#index'
get "/" => 'users#dashboard', :as => "user_root"
# ..
end
In Rails 3 you can use Request Based Contraints to dynamically map your root route. The solution above works for the Devise authentication gem but can be modified to support your own implementation.
With the above root_path or / will route to a WelcomeController#index action for un-authenticated requests. When a user is logged in the same root_path will route to UsersController#dashboard.
Hope this helps.
A:
I have the same problem and I solved it with this:
authenticated :user do
root :to => "wathever#index"
end
unauthenticated :user do
devise_scope :user do
get "/" => "devise/sessions#new"
end
end
Hope it helps.
|
[
"stackoverflow",
"0024132919.txt"
] | Q:
Magento Installation permission issue
I am using Fedora my Os System and was give permission 777 to /var/www/html.
I have try to install magento CE Version 1.9.0.1.But when i am trying to install magento from browser.it show permission issue
Path "/var/www/html/magento/app/etc" must be writable.
Path "/var/www/html/magento/media" must be writable.
Path "/var/www/html/magento/media/downloadable" must be writable.
Path "/var/www/html/magento/media/xmlconnect" must be writable.
Path "/var/www/html/magento/media/xmlconnect/system" must be writable.
Path "/var/www/html/magento/media/xmlconnect/system/ok.gif" must be writable.
Path "/var/www/html/magento/media/xmlconnect/custom" must be writable.
Path "/var/www/html/magento/media/xmlconnect/custom/ok.gif" must be writable.
Path "/var/www/html/magento/media/xmlconnect/original" must be writable.
Path "/var/www/html/magento/media/xmlconnect/original/ok.gif" must be writable.
Path "/var/www/html/magento/media/dhl" must be writable.
Path "/var/www/html/magento/media/dhl/logo.jpg" must be writable.
Path "/var/www/html/magento/media/customer" must be writable.
using chmod 777 -R /var/www/html and show same issue.I thought ,it can be user permission issue at /var/www/html/magento/ Can anyone help me ??
A:
Probably you have a problem with SELinux permissions. You should try this:
chcon -R -t httpd_sys_rw_content_t /var/www/html/magento/
chmod -R a+w /var/www/html/magento/
|
[
"stackoverflow",
"0011350686.txt"
] | Q:
Combine results of joins on two tables
I have 3 tables
items
tag_id
mark_id
tags_users
tag_id
user_id
marks_users
mark_id
user_id
Is there a way to select unique items for specific user_id without UNION and nested selects?
SELECT items.*
FROM items
INNER JOIN tags_users ON tags_users.tag_id = items.tag_id
AND tags_users.user_id = 5
UNION
SELECT items.*
FROM items
INNER JOIN marks_users ON marks_users.mark_id = items.mark_id
AND marks_users.user_id = 5
A:
Linked by (tag_id, mark_id)
SELECT DISTINCT i.*
FROM tags_users tu
JOIN marks_users mu USING (user_id)
JOIN items i USING (tag_id, mark_id)
WHERE tu.user_id = 5;
The DISTINCT should not be necessary, if you have defined multi-column primary or unique keys on the columns.
Linked by tag_id or mark_id
@Gordon's answer is perfectly valid. But it will perform terribly.
This will be much faster:
SELECT i.*
FROM items i
WHERE EXISTS (
SELECT 1
FROM tags_users tu
WHERE tu.tag_id = i.tag_id
AND tu.user_id = 5
)
OR EXISTS (
SELECT 1
FROM marks_users mu
WHERE mu.mark_id = i.mark_id
AND mu.user_id = 5
);
Assumes that entries in items itself are UNIQUE on (tag_id, mark_id).
Why is this much faster?
If you JOIN to two unrelated tables (like in @Gordon's answer), you effectively form a cross join, which are known for rapidly degrading performance with growing number of rows. O(N²). Say, you have:
100 users, 100 tags and 100 marks.
Every combination exists (simple hypothetical setup, real life data will be less balanced).
Results in 10,000 rows in each of the tables.
This will happen in @Gordon's query:
JOIN rows of items to tags_users. Each item is joined to 100 rows, resulting in
10,000 x 100 = 1,000,000 rows. (!)
JOIN that to marks_users. Each row is joined to 100 marks, resulting in
100,000,000 rows. (!!)
The WHERE clause is applied and the many duplicates are collapsed by DISTINCT, resulting in 10,000 rows.
Test with EXPLAIN ANALYZE. The difference will be obvious even with small numbers and staggering with growing numbers.
SQL Fiddle.
Benchmarks
I ran some quick tests with this setup on my machine (pg 9.1):
Gordon's query
SELECT DISTINCT i.*
FROM items i
LEFT JOIN tags_users tu on i.tag_id = tu.tag_id
LEFT JOIN marks_users mu on i.mark_id = mu.mark_id
WHERE 5 IN (tu.user_id, mu.user_id);
Total runtime: 38229.860 ms
Sanitized version
Pulling the condition on user_id into the JOIN clause cuts down on the combinations radically, but it is still a (much tinier) cross join.
SELECT DISTINCT i.*
FROM items i
LEFT JOIN tags_users tu on i.tag_id = tu.tag_id AND tu.user_id = 5
LEFT JOIN marks_users mu on i.mark_id = mu.mark_id AND mu.user_id = 5
WHERE tu.user_id = 5 OR mu.user_id = 5;
Total runtime: 110.450 ms
With EXISTS semi-joins
(see query above)
With this query, every row is checked once if it qualifies. You don't need a DISTINCT, because rows are not duplicated to begin with.
Total runtime: 26.569 ms
UNION
For completeness, the variant with UNION. Use UNION, not UNION ALL to remove duplicates:
SELECT i.*
FROM items i
JOIN tags_users tu ON i.tag_id = tu.tag_id AND tu.user_id = 5
UNION
SELECT i.*
FROM items i
JOIN marks_users mu ON i.mark_id = mu.mark_id AND mu.user_id = 5;
Total runtime: 178.901 ms
|
[
"es.stackoverflow",
"0000025836.txt"
] | Q:
MS SQL Server conexion android
tengo el siguiente código para un login, pero a la hora de ejecutar la aplicación, esta se cae por el método OnClickListener (servidor, y usuarios de la bdd omitidos por razones obvias)
package com.ciclomapp.ciclomapp.ciclomapp;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Login extends AppCompatActivity {
Button login;
EditText username, password;
Connection con;
String un, pass, db, sv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Login);
login = (Button) findViewById(R.id.button);
username = (EditText) findViewById(R.id.editText2);
password = (EditText) findViewById(R.id.editText4);
sv = "";
db = "";
un = "";
pass = "";
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckLogin checkLogin = new CheckLogin();
checkLogin.execute("");
}
});
}
public class CheckLogin extends AsyncTask <String, String, String> {
String z = "";
Boolean isSuccess = false;
String usernam = username.getText().toString();
String passwordd = password.getText().toString();
@Override
protected String doInBackground(String... params) {
if (usernam.trim().equals("") || passwordd.trim().equals(""))
z = "Please enter Username and Password";
else {
try {
con = connectionclass(sv, db, un, pass);
if (con == null)
{
z = "Check Your Internet Access!";
}
else
{
String query = "select * from login where email= '" + usernam.toString() + "' and contraseña = '"+ passwordd.toString() +"' ";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successful";
isSuccess=true;
con.close();
Toast.makeText(Login.this, "correcto", Toast.LENGTH_SHORT).show();
}
else
{
z = "Invalid Credentials!";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = ex.getMessage();
}
}
return z;
}
}
@SuppressLint("NewApi")
public Connection connectionclass(String user, String password, String database, String server)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + database + ";user=" + user+ ";password=" + password + ";";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return connection;
}
}
aqui dejo el layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_login"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ciclomapp.ciclomapp.ciclomapp.Login">
<TextView
android:text="E-Mail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="230dp"
android:id="@+id/textView11"
android:textSize="25sp" />
<TextView
android:text="No tienes cuenta? Registrate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="14dp"
android:id="@+id/textView9"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:textSize="20sp" />
<TextView
android:text="Contraseña"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="52dp"
android:id="@+id/textView2"
android:textSize="25sp"
android:layout_below="@+id/textView11"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="@+id/editText2"
style="@android:style/Widget.AutoCompleteTextView"
android:inputType="textEmailAddress"
android:background="@android:color/darker_gray"
android:layout_alignBottom="@+id/textView11"
android:layout_alignTop="@+id/textView11"
android:layout_alignParentEnd="true"
android:layout_alignStart="@+id/editText4"
android:textColor="@android:color/black"
tools:ignore="LabelFor" />
<Button
android:text="Iniciar sesión"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_marginBottom="13dp"
android:layout_above="@+id/textView9"
android:layout_centerHorizontal="true"/>
<EditText
android:inputType="textPassword"
android:ems="10"
android:id="@+id/editText4"
android:background="@android:color/darker_gray"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:textColor="@android:color/black"
android:layout_alignBottom="@+id/textView2"
android:layout_alignParentEnd="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/logo"
android:id="@+id/imageView2"
android:layout_above="@+id/editText2"
android:layout_centerHorizontal="true" />
</RelativeLayout>
y el logcat
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ciclomapp.ciclomapp.ciclomapp, PID: 10120
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ciclomapp.ciclomapp.ciclomapp/com.ciclomapp.ciclomapp.ciclomapp.Login}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:945)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.ciclomapp.ciclomapp.ciclomapp.Login.onCreate(Login.java:51)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:945)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
pd: lamentento publicar tanto código
A:
El error es indicado en tu mensaje desplegado en el LogCat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at com
Generalmente este problema ocurre cuando la instancia del botón "login", no existe en tu layout activity_main.xml o tiene un nombre diferente:
setContentView(R.layout.activity_main;
login = (Button) findViewById(R.id.button);
Actualización:
Al revisar el layout, tienes definida en el layout, para el botón la propiedad:
android:onClick="onClick"
Lo cual causa conflicto.
<Button
android:text="Iniciar sesión"
android:id="@+id/button"
android:onClick="onClick" />
Elimina esta propiedad:
android:onClick="onClick"
Ya que estas implementando un listener para esta acción.
Como llamar un método mediante la propiedad android:onClick :
Se define el método a ejecutar:
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Click para realizar tarea."
android:onClick="algunaTarea" />
Y en el código se define el método que recive como parametro la vista:
public void algunaTarea(View view) {
// Realiza tarea!
}
|
[
"stackoverflow",
"0001024166.txt"
] | Q:
Need a Switch component controlled via USB port
I need device switch component which an be controlled by code(.net,C# Or vb) ON/OFF state is enough..
I have code knowledge in C#, .net window application, I need to make a switch that can be controlled using code via USB port ... so that using that switch I will turn on/off electrical devices (fan,light) for a specific time interval.. For my MINI Project
Note: I need the brief note regarding components needed and how to assemble it.
If you know any link which resembles this type of project pls refer me.
thanks.
A:
You'll probably want to look into using an FTDI chip for this purpose. They do have a .NET interface available as well as traditional C DLLs.
FTDI offers two types of drivers - one emulates a simple COM port (Virtual COM Port, which is probably enough for you), and the other is more of a direct USB control (D2XX), although it still shows up as a COM port when the USB device is connected.
On the other hand, if you really only need on/off support, you could probably just use the .net serial port drivers for the most basic communication. Of course, the serial port drivers don't let you tie a serial port pin high or low, so you will need some method of reading the data coming from the PC. Many microcontrollers have freely available UART libraries exactly for this purpose, but you will need to also obtain an RS232 level shifting IC for this because the serial port from the PC outputs +/- 6V IIRC (might be +/- 12V), while most microcontrollers run off of and accept signals at 0/5V or 0/3.3V.
|
[
"stackoverflow",
"0049739408.txt"
] | Q:
Yii2 call PHP function in model dynamically from variable
Is it possible to call a model function dynamically via variables?
$model = $request['model'];
$action = $request['action'];
I have some models and several functions inside. Now I would like to call a model function based on the variables $model and $action. In this case, I need to call the model functions dynamically, depending on a request.
A:
For static function
assuming you a class eg:
\common\models\MyClass
with a
public static function mStatyFunction()
{
....
}
you can use the class name as var
$myClass = '\common\models\MyClass';
$myClass::myStatFunction();
or if you need also the the function name as var you could
$myFunc = 'myStatFunction';
$myClass::$myFunc();
for non static function you can simply create a new object
public function myDinaFunction()
{
....
}
$myObject = new MyClass();
and call the function
$myObject->myDinaFunction();
or also
$var = 'myDinaFunction";
$myObject->$var();
|
[
"math.stackexchange",
"0003340915.txt"
] | Q:
How to show that the category of finite vector spaces is indecomposable?
In [1] it is said that the category $\mathbf{FinVect}$ of finite vector spaces is a tensor category. I am trying to convince myself that this is indeed the case.
One of the properties that $\mathbf{FinVect}$ must satisfy for this to hold is that it is indecomposable. I cannot think of a way to show that. Here are the definitions which are relevant for this problem:
Def: Let $\mathbb C$ be a locally finite $\mathbb{K}$-linear abelian rigid monoidal category.
$\mathbb{C}$ is a multitensor category over $\mathbb{K}$ if $\otimes:\mathbb{C}\times\mathbb{C}\rightarrow \mathbb{C}$ is bilinear on morphisms.
A multitensor category $\mathbb{C}$ is decomposable if it is equivalent to a direct sum of nonzero multitensor categories.
If $\mathbb{C}$ is an indecomposable multitensor category and $\text{End}(1)\cong \mathbb{K}$ (as vector spaces), then $\mathbb{C}$ is a tensor category.
[1] Pavel Etingof et al. Tensor Categories. American Mathematical Society,
2015.
A:
If $\mathbf{FinVect}\simeq C\times D$ where $C$ and $D$ are both nonzero, let $c$ and $d$ be nonzero objects of $C$ and $D$, respectively. Then $(c,0)$ and $(0,d)$ are both nonzero objects of $C\times D$ (because their identity map is not equal to their zero map), but $\operatorname{Hom}((c,0),(0,d))\cong \operatorname{Hom}(c,0)\times\operatorname{Hom}(0,d)\cong 0$. This is a contradiction, since any two nonzero vector spaces have a nonzero linear map between them.
For some similar arguments for other categories, see my answer at Is Set "prime" with respect to the cartesian product? and its comments.
|
[
"stackoverflow",
"0026352601.txt"
] | Q:
Installing Laravel
I am on a windows 8 machine and I'm trying to learn laravel. I copy and pasted my PHP folder from C:\xampp to C:\php, installed composer, ran composer install then composer create-project laravel/laravel learning-laravel. So far everything was created so I went into the directory and tried to use 'php artisan serve' and got the following error.
C:\Users\denni_000\learning-laravel>php artisan serve
Warning: require(C:\Users\denni_000\learning-laravel\bootstrap/../vendor/autoloa
d.php): failed to open stream: No such file or directory in C:\Users\denni_000\l
earning-laravel\bootstrap\autoload.php on line 17
A:
Why you copied php folder
download composer install it.
download laravel latest version and store it on your xampp/htdocs/laravel
and run cmd with composer install command
For more follow install laravel on windows xampp
or Laravel 4.1 installation with composer in xampp
|
[
"stackoverflow",
"0032828791.txt"
] | Q:
What's with the extra threads reported by GDB?
I have a C++ application that starts as single thread and processes some video frames. For each frame the application spawns 2 threads that join and this is done in a loop for each frame.
I'm trying to investigate whether there is another thread that I haven't detected. The application is quite complex and loads shared libraries that may spawn threads of their own.
I use gdb's info threads for that.
This is what I get:
Id Target Id Frame
7 Thread 0x7fffde7fc700 (LWP 16644) "my_debugged_process" sem_wait ()
at ../nptl/sysdeps/unix/sysv/linux/x86_64/sem_wait.S:85
6 Thread 0x7fffdeffd700 (LWP 16643) "my_debugged_process" sem_wait ()
at ../nptl/sysdeps/unix/sysv/linux/x86_64/sem_wait.S:85
5 Thread 0x7fffdf7fe700 (LWP 16642) "my_debugged_process" sem_wait ()
at ../nptl/sysdeps/unix/sysv/linux/x86_64/sem_wait.S:85
4 Thread 0x7fffdffff700 (LWP 16641) "my_debugged_process" sem_wait ()
at ../nptl/sysdeps/unix/sysv/linux/x86_64/sem_wait.S:85
3 Thread 0x7fffe4988700 (LWP 16640) "my_debugged_process" sem_wait ()
at ../nptl/sysdeps/unix/sysv/linux/x86_64/sem_wait.S:85
2 Thread 0x7fffe5c0b700 (LWP 16639) "my_debugged_process" 0x00007ffff3dc812d in poll ()
at ../sysdeps/unix/syscall-template.S:81
* 1 Thread 0x7ffff7fc2800 (LWP 16636) "my_debugged_process" TheApplication::SomeClass::processFrame (this=0x743530, srcI=...,
dstI=...) at TheApplication.cpp:315
So the question is:
What are the threads from 2 to 7? Are they somehow related to my process? I only recognize thread 1.
I see that they are all waiting for a semaphore so I'm inclined to say that they belong to the debugger.
A:
First, what Jonathan said in the comments: on Linux, gdb does not create any threads in your process. gdb tries to have a reasonably minimal impact on your application -- it can't be zero but it is pretty close.
Second, what Jonathan said again: to try to understand the threads after they are running, get a backtrace and see if it makes any sense. For a single thread:
(gdb) thread 52 # e.g.
(gdb) bt
Or for all of them:
(gdb) thread apply all bt
Finally, to see threads when they are created, one way to try is to get a backtrace when the thread is started:
(gdb) break pthread_create
(gdb) commands
> bt
> cont
> end
This should print a stack trace when a thread is created. This won't necessarily work in all cases (some programs call clone directly) but it should be ok for well-behaved libraries.
|
[
"stackoverflow",
"0052918736.txt"
] | Q:
Split string into object
I'm looking for some guidance on how to split a string into object properties in C#, I'm struggling with how to do it.
For example I have a string of a filename like
Artist, Song, CreationDateTime
And I want to parse that into an object with properties of Artist, Song and CreationDateTime.
What would be the most efficient method? I'm struggling past delimiting the string by a comma into an array. From there it then can't be assigned to the properties.
A:
This should help you:
string strToParse = "MyArtist, MySong, MyCreationDate"; // your string
string [] arrayOfStrings = strToParse.Split(','); // split string to array by comma character
if (arrayOfStrings.Length != 3) // check if you splitted correct, and have 3 entries
return;
var anonymousType = new { Artist = arrayOfStrings[0], Song = arrayOfStrings[1], Date = arrayOfStrings[2] }; // replace anonymous type with your type
|
[
"stackoverflow",
"0040690023.txt"
] | Q:
What is the exact semantic of "from ... import" starement?
I've experiment with the statement,however the result did not match the official description.
Quotation is below:
The from form uses a slightly more complex process:
find the module specified in the from clause, loading and initializing it if necessary;
for each of the identifiers specified in the import clauses:
check if the imported module has an attribute by that name
if not, attempt to import a submodule with that name and then check the imported module again for that attribute
if the attribute is not found, ImportError is raised.
otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name
I created a namespace package named l007, within which submodule named l009 was placed.I typed "from l007 import l009" in the interpreter, the execution was ok, while in which case a ImportError should have been raised.
Is my understanding wrong?
A:
See this documentation:
When a submodule is loaded using any mechanism (e.g. importlib APIs, the import or import-from statements, or built-in __import__()) a binding is placed in the parent module’s namespace to the submodule object. For example, if package spam has a submodule foo, after importing spam.foo, spam will have an attribute foo which is bound to the submodule.
That is why the steps in your quote are in the order they are in. Even though l007 doesn't initially have an attribute l009, it will have one after the submodule import occurs.
|
[
"stackoverflow",
"0000960781.txt"
] | Q:
Rails cannot find model with same name as Ruby class
I'm fairly new to Ruby on Rails, and I have a project with a "Set" model. This is in Rails 2.3.2. Now the problem is that it can't find any methods on that model's class at all. For example: "undefined method find' for Set:Class" or "undefined methoderrors' for #". It seems to be trying to find those methods on the Ruby "Set" class instead my model class.
It might work if I could write the fully-qualified name of my Set model class like Module::Set, but I'm not sure what that would be. (And yes, I really do want my model name Set. Anything else would be awkward in the context of my app).
Any ideas?
A:
Don't name it Set. That way lies madness.
The deal is that defining the class fails because you're trying to redefine 'Set' which is already defined in the global context.
class Set < ActiveRecord::Base # You are attempting to define a constant 'Set'
# here, but you can't because it already exists
You can put your class in a module, and then you won't get the error because you'll be defining Set within a namespace.
module Custom
class Set < ActiveRecord::Base
end
end
However, every single time you want to use your Set class, you'll have to refer to it as Custom::Set. A lot of Rails magic won't work because it's expecting class names to be defined in the global context. You'll be monkeypatching plugins and gems left and right.
Far easier to just give it a different name.
class CustomSet < ActiveRecord::Base
All the magic works, and no monkeypatching required.
|
[
"gamedev.stackexchange",
"0000009684.txt"
] | Q:
Help me choose an engine
So far i've been trying to make a RTS in pygame but, i feel like 2d is not enough and pygame has me do a lot of stuff that i would not like doing. What i would like doing is working on the AI gameplay and such and not worying too much about how to display stuff,physics and the like too much.
So far Unity has boo which is supposed to be similar to python i wonder if that could work. How similar is it to python should i use this?
Other options as far as i can see are ogre3d python bindings and UDK.
Which would best suit my needs?
A:
First of all, if you don't want to worry about other aspects EXCEPT graphics (physics, etc), forget about using Ogre. It's a graphics engine, not a game engine.
Unity has all of the aspects that you want already in there and can offer you a quick turnaround time.
The UDK is a good one, but it does involve a bit more work to get up and running before you can focus on the AI and gameplay aspects.
If your aim is to get something up and running in a very short amount of time, go for Unity. If you don't like Boo (which personally I have no experience in whatsoever), you can always use the C# and/or Javascript alternatives.
|
[
"math.stackexchange",
"0002038783.txt"
] | Q:
Interpolate complex numbers in geometrical sense
Complex numbers can be used to represent rotations. Is it possible to interpolate between 2 normalized complex numbers in geometrical sense without going through the angles they represent?
Example:
a0 => z0 = sin(a0) + cos(a0) * i
a1 => z1 = sin(a1) + cos(a1) * i
I would like to obtain:
z = ...
where z represent the angle defined as a0 + (a1 - a0) * t, where t is [0, 1] without actually computing a0 and a1.
A:
Literally, mostly yes.
In practice, no.
Here's the literal approach:
Compute
$$
z = (1-s) z_0 + s z_1
$$
for some $s \in [0, 1]$. Then compute
$$
z' = \frac{z}{|z|}
$$
As long as $a_0$ and $a_1$ differ by less than 180 degrees, as $s$ varies from $0$ to $1$, the number $z'$ will range over all "rotations" between $z_0$ and $z_1$.
Here's the practical part:
The problem is that it won't do so "nicely": if $z_0$ and $z_1$ are near opposites, it'll mostly give you rotations near $z_0$ and $z_1$, "racing through" the rotations in the middle when $s \approx 0.5$.
The exact relation between $s$ and the $t$ you've named can be written out, so it's possible to do select the "s" values carefully to get a uniform-speed variation between $z_0$ and $z_1$...but it involves more mess than computing the angles in the first place.
There's another sense in which it's practically impossible. Consider the case where $a_0 = 0$ and $a_1 = 2\pi$. Then $z_0$ and $z_1$ are identical, and there's no way to know that they didn't arise from $a_0 = 0$ and $a_1 = 0$. If they arose from the first pair, then for $t = 0.5$, you want to compute $z = -1 + 0i$; if they arose from the second, then for $t = 0.5$, you want to compute $z = 1 + 0i$. In short you need to get two different answers from your interpolater given the same inputs. That's not possible.
|
[
"stackoverflow",
"0008252166.txt"
] | Q:
Bundling couchdb with android app
I am following the instructions here
http://www.couchbase.org/get/couchbase-mobile-for-android/current
After I start an instance of Couchdb, how do I push a couchapp from my machine to the emulator ?
A:
I noticed your question is old, but hope this answer is still useful to you. Here's what I did.
First, setup port forwarding to your emulator.
adb forward tcp:5985 tcp:5984
This makes the CouchDB instance running on your Android emulator available on port 5985 of your host machine. Verify it works with:
$ curl localhost:5985
You should get a response with version you have installed on your emulator:
{"couchdb":"Welcome","version":"1.2.0a-7b47329-git"}
If you're using the CouchApp toolchain, you can push the app from your file system to your emulator like this:
couchapp push . http://localhost:5985/my-app
Alternatively, if the app is already installed (pushed) on your server (assuming server is your local host machine) you can issue a replicate command (HTTP POST) that looks similar to this:
$ curl -H 'Content-Type: application/json' -X POST http://localhost:5984/_replicate -d ' {"source": "http://localhost:5984/my-app", "target": "http://localhost:5985/my-app", "create_target": true, "continuous": true} '
That should do the trick. Let me know if you run into any troubles.
|
[
"spanish.stackexchange",
"0000000463.txt"
] | Q:
How did the words "mataburros" and "tumbaburros" come to mean "dictionary"?
This recent question about irregular plurals led me to a couple of odd and interesting words that apparently mean "dictionary" in at least one sense each:
mataburros
tumbaburros
The connection between dictionaries and donkeys and their knocking over or killing seems tenuous at best. Does anybody know if there's a story behind them?
As a bonus question, my dictionary says mataburros is rioplatense and Wiktionary says it also means grille guard or bumper guard. Whereas for tumbaburros my dictionary says it's Mexican and also means bull bar. Do these regional tags and other senses match what you know?
A:
A una persona con pocos conocimientos se le dice coloquialmente "burro". Un "mataburros" es literalmente algo que elimina a los burros y de ahí que (en Argentina, por ejemplo) al diccionario se le diga "mataburros" pues ayuda a suprimir burros, es decir, personas sin conocimientos. Un caso similar sucede con "tumbaburros" que es otra de las maneras coloquiales (en México al menos) de referirse a un diccionario.
En cuanto al bono, mataburros con el significado de diccionario solo lo he escuchado en Argentina y tumbaburros, también con el significado de diccionario, solo se lo he escuchado a amigos mexicanos.
A:
According to the RAE's dictionary, "mataburros" means dictionary only in Argentina, Costa Rica, Cuba, Honduras, Uruguay and Venezuela; "tumbaburros", as you said, only in Mexico.
Since "burro" is also used to refer to ignorant/rude/uncivil people, the "mataburro" becomes an object that "kills" those kind of people.
A:
See hippietrail, the thing is that "burro" is used as a synonym to a person without education. That's why mataburro means mata ignorantes wich means (kill ignorance).
"Mataburro" actually is also used as bumper guard (Colombia AFAIK).
|
[
"stackoverflow",
"0057942284.txt"
] | Q:
Find unique words from an array of anagrams using Map in Javascript
I know how to do it without Map. It seems more logical to use Map for this task but I can't seem to implement it. Is this even possible?
So far I tied this:
function aclean(arr) {
let result = [];
let unique = new Map();
for(let i = 0; i < arr.length; i++){
let sorted = arr[i].toLowerCase().split("").sort().join("");
/*if (unique.add(sorted)) {
result.push(arr[i]);
}*/
}
return result;
}
let array = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"];
console.log(aclean(array));
The result should be: nap,teachers,ear or PAN,cheaters,era
A:
You could take a Set with the normalized (lower case, sorted) strings and return a filtered result.
function aclean(array) {
let unique = new Set();
return array.filter(s => {
let sorted = s.toLowerCase().split("").sort().join("");
if (!unique.has(sorted)) {
unique.add(sorted);
return true;
}
});
}
let array = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"];
console.log(aclean(array));
A:
You could loop over your array using .forEach(), and check at each iteration whether or not your Map has a key of the sorted word, if it doesn't, then you set the sorted word as the key, and the word associated with the word as the value. You can then return an array of your map's .values() to get your result:
function aclean(arr) {
let unique = new Map();
arr.forEach(word => {
let sorted = word.toLowerCase().split("").sort().join("");
if(!unique.has(sorted)) {
unique.set(sorted, word);
}
});
return [...unique.values()];
}
let array = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"];
console.log(aclean(array));
A:
I think Set is prefect for this case. You can do it in following steps.
First make a helper function which sorts to the strings.
Then create a unique array of sorted strings using Set and map()
Then map() that array again to the value in original array which is anagram of the sorted string.
const sort = str => str.toLowerCase().split('').sort().join('')
const aclean = arr => [... new Set(arr.map(sort))].map(x => arr.find(a => sort(a) === x))
let array = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"];
console.log(aclean(array));
|
[
"math.stackexchange",
"0002050950.txt"
] | Q:
Differentiation under the integral sign - line integral?
In the proof of Kelvin's circulation theorem it is common to do the following manipulation:
$$\newcommand{\p}[2]{\frac{\partial #1}{\partial #2}} \newcommand{\f}[2]{\frac{ #1}{ #2}} \newcommand{\l}[0]{\left(} \newcommand{\r}[0]{\right)}
\f{D \Gamma}{Dt}=\f{D}{Dt} \oint_{C(t)} \vec u \cdot d\vec x$$
$$=\oint_{c(t)} \f{D\vec u}{Dt}\cdot d\vec x+\oint_{c(t)}\vec u\cdot d\l \f{D\vec x}{Dt}\r$$
I am uneasy about the validity of this expression. Please can someone explain the logic and maths behind it.
A:
Sometimes non-rigorous derivations in physics are both expedient and illuminating, but this is definitely not the case with the linked "proof" of Kelvin's theorem.
First you can dispense with the outer material derivative and replace it with an ordinary derivative with respect to $t$. The circulation around a closed material curve $C(t)$ -- one that is convected with the flow and contains the same fluid particles -- has no explicit dependence on the spatial coordinates. Hence,
$$\frac{\partial \Gamma}{\partial t}+ \mathbf{u}\cdot \nabla\Gamma = \frac{D\Gamma}{Dt} = \frac{d\Gamma}{dt}.$$
Consider the one-dimensional analog
$$\left(\frac{\partial}{\partial t} + u\frac{\partial}{\partial x}\right)\int_a^{C(t)} u(x',t)\, dx' = \frac{d}{dt}\int_a^{C(t)} u(x',t)\, dx',$$
Assuming all functions are sufficiently smooth we can apply Leibniz's rule to obtain
$$\frac{d}{dt}\int_a^{C(t)} u(x',t)\, dx' = \int_a^{C(t)} \frac{\partial}{\partial t}u(x',t)\, dx' + u(C(t),t) C'(t).$$
This gives you a hint that you cannot merely interchange the derivative and the integral and that some type of "boundary term" is going to appear.
In the Lagrangian description of fluid flow there is a family of smooth maps
$$\mathbf{\xi}(\cdot,t) : \mathbb{R}^3 \to \mathbb{R}^3$$
for which a fluid particle located at $\mathbf{x}_0$ at time $t =0$ is located at $\mathbf{x} = \mathbf{\xi}(\mathbf{x}_0,t)$ at time $t$. We obtain the Eulerian velocity field according to $\mathbf{u}(\mathbf{x},t) = \mathbf{u}(\mathbf{\xi}(\mathbf{x}_0,t),t) = \frac{\partial}{\partial t} \mathbf{\xi}( \mathbf{x}_0,t) = \mathbf{\xi}_t( \mathbf{x}_0,t).$
At time $t$, the closed material curve $C(t)$ can be parametrized as $C(t) = \{\mathbf{x}(s,t) : 0 \leqslant s \leqslant 1\}$ and is the image of a curve $C(0)$ under the map $\mathbb{\xi}(\cdot,t) : \mathbf{x}_0(s) \mapsto \mathbf{x}(s,t).$
The circulation is given by
$$\Gamma(t) = \oint_{C(t)} \mathbf{u}(\mathbf{x},t) \cdot d \mathbf{x}= \int_0^1 \mathbf{u}(\mathbf{x}(s,t),t) \cdot \frac{\partial}{ \partial s} \mathbf{x}(s,t)\,ds.$$
With a change of variable $\mathbb{x} = \mathbb{\xi}(\mathbb{x}_0,t),$ we can express the circulation as
$$\Gamma(t) = \int_0^1 \mathbf{u}(\mathbf{\xi}(\mathbf{x}_0(s),t),t) \cdot \frac{\partial }{ \partial s} \mathbf{\xi}(\mathbf{x}_0(s),t)\,ds.$$
Now assuming the integrand is sufficiently smooth, we can take the derivative with respect to $t$ under the integral sign and split into two integrals to obtain
$$\frac{d\Gamma}{dt} = \int_0^1 \left[\frac{\partial}{\partial t}\mathbf{u}(\mathbf{\xi}(\mathbf{x}_0(s),t),t) + \nabla \mathbf{u}(\mathbf{\xi}(\mathbf{x}_0(s),t),t) \cdot \mathbf{\xi}_t( \mathbf{x}_0(s),t)\right] \cdot \frac{\partial}{ \partial s} \mathbf{\xi}(\mathbf{x}_0(s),t)\,ds \\ + \int_0^1 \mathbf{u}(\mathbf{\xi}(\mathbf{x}_0(s),t),t) \cdot \frac{\partial}{\partial t}\frac{\partial}{ \partial s} \mathbf{\xi}(\mathbf{x}_0(s),t)\,ds.$$
Reversing the change of variables and interchanging the $t-$ and $s-$derivatives in the second integral we get
$$\frac{d\Gamma}{dt} = \oint_{C(t)} \left[\frac{\partial}{\partial t}\mathbf{u}(\mathbf{x},t) + \mathbf{u}(\mathbf{x},t) \cdot \nabla \mathbf{u}(\mathbf{x},t) \right] \cdot d \mathbf{x} + \int_0^1 \mathbf{u}(\mathbf{\xi}(\mathbf{x}_0(s),t),t) \cdot \frac{\partial }{\partial s} \mathbf{\xi}_t(\mathbf{x}_0(s),t)\,ds \\ = \oint_{C(t)} \frac{D\mathbf{u}}{Dt}\cdot d \mathbf{x} + \int_0^1 \mathbf{u}\cdot \frac{\partial}{\partial s} \mathbf{u}(\mathbf{x}(s,t),t)\,ds .$$
I prefer to leave the second integral in this comprehensible parametric form rather than introduce the cryptic notation
$$\oint_{C(t)} \mathbf{u} \cdot d \left(\frac{D\mathbf{x}}{Dt}\right)$$
|
[
"stackoverflow",
"0008262043.txt"
] | Q:
Win32: How to create a bordless popup window
Win32 API provides many styles for window creating and I'm looking for a style that can remove a one-pixel border from the window that I created with this code:
DWORD dwExtStyle = 0;
DWORD dwStyle = WS_POPUPWINDOW;
m_hWnd = CreateWindowEx(
dwExtStyle,
className,
windowName,
dwStyle,
300,
300,
100,
100,
NULL,
NULL,
hInstance,
NULL);
ShowWindow(m_hWnd, SW_SHOW);
and I got the result:
What combination of flags can remove the black border from the window.
A:
Just use WS_POPUP instead of WS_POPUPWINDOW.
The macro WS_POPUPWINDOW is actually a set of flags:
#define WS_POPUPWINDOW (WS_BORDER | WS_POPUP | WS_SYSMENU)
The WS_BORDER flag is the one responsible of your black square.
|
[
"stackoverflow",
"0010432090.txt"
] | Q:
Conditional RequiredFieldValidator inside of a repeater
I have a repeater that holds a Radio button list, a textbox and a requiredfieldvalidator control. The Radiobuttonlist holds the following:
Meets (Value M)
Above (Value A)
Below (Value B)
N/A (Value(N/A)
The textbox is set to allow the user to input some justification for their answer, and the requiredfieldvalidator makes sure that the textbox is not empty, simple enough. However the scope has changed a bit and now the client wants the requiredfieldvalidator to fire ONLY if the answer is not "M".
I have tried setting a Load method for the validator, however when the validator loads it has no idea what the answer is in the RBL because it is fired before the user answers. I do not think that I can do a postback, because the repeater is handled within a Modal popup and if I do a postback I am not sure what will happen. How can I set my validator to false only if the user selects something other than "Meets"?
A:
try this:
java script:
<script type="text/javascript">
function UpdateValidator(radioID, validatorid) {
//enabling the validator only if the checkbox is checked
var enableValidator = $("#" + radioID).is(":checked");
ValidatorEnable(validatorid, enableValidator);
}
</script>
cs code:
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rd = e.Item.FindControl("myRb") as RadioButton;
RequiredFieldValidator rfv = e.Item.FindControl("myRfv") as RequiredFieldValidator;
// you can just pass "this" instead of "myDiv.ClientID" and get the ID from the DOM element
rd.Attributes.Add("onclick", "UpdateValidator('" + rd.ClientID + "','" + rfv.ClientID + "');");
}
}
|
[
"stackoverflow",
"0049374385.txt"
] | Q:
Accessing the first elements in a list of Lists [F#]
I'm currently interested in F# as it is different to everything I have used before. I need to access the first element of each list contained within a large list.
If I assume that the main list contains 'x' amount of lists that themselves contain 5 elements, what would be the easiest way to access each of the first elements.
let listOfLists = [ [1;2;3;4;5]; [6;7;8;9;10]; [11;12;13;14;15] ]
My desired output would be a new list containing [1;6;11]
Currently I have
let rec firstElements list =
match list with
| list[head::tail] ->
match head with
| [head::tail] -> 1st @ head then firstElements tail
To then expand on that, how would I then get all of the second elements? Would it be best to create new lists without the first elements (by removing them using a similar function) and then reusing this same function?
A:
You can use map to extract the head element of each child list:
let firstElements li =
match li with [] -> None | h::_ -> Some h
let myfirstElements = List.map firstElements listOfLists
I'm using Ocaml's speak with little lookup on F# so this may be inaccurate, but the idea applies.
EDIT: You can also use List.head which makes it more concise and will return a int list instead of int option list. However, it throws an exception if you hits an empty list. Most of the time, I'd avoid using List.head or List.tail in this case.
|
[
"stackoverflow",
"0045094826.txt"
] | Q:
i want to read csv file and parse it to array but always fail
my csv file link : https://drive.google.com/file/d/0B-Z58iD3By5wb2R2TnV0Rjc3Zzg/view
I already read many reference but I can not seperate my csv by "," (the delimiter not working properly). Is there a solution how could I get an array like this from that csv file:
`Array[0]=>
(
['username'] => Lexsa,
['date'] => 12/07/2017,
['retweet'] => null,
)`
`Array[1]=>
(
['username'] => any,
['date'] => 12/07/2017,
['retweet'] => null
)`
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
I try to use many reference but the result is always like this the code wont split the line with "," :
Array ( [0] => Array (["username","date","retweets","favorites","text","geo","mentions","hashtags","id","permalink"] => "Lexsa911","01/12/2016 0:05",0.0,0.0,"Kecelakaan - Kecelakaan Pesawat yang Melibatkan Klub-Klub Sepakbola http:// ht.ly/1IdL306EzDH",,,,"8,04E+17","https://twitter.com/Lexsa911/status/804008435020865536" )
A:
This is what I get when I open your tes.csv with less or gedit:
"""username"",""date"",""retweets"",""favorites"",""text"",""geo"",""mentions"",""hashtags"",""id"",""permalink"""
"""Lexsa911"",""01/12/2016 0:05"",0.0,0.0,""Kecelakaan - Kecelakaan Pesawat yang Melibatkan Klub-Klub Sepakbola http:// ht.ly/1IdL306EzDH"",,,,""8,04E+17"",""https://twitter.com/Lexsa911/status/804008435020865536"""
"""Widya_Davy"",""01/12/2016 0:05"",0.0,0.0,""Kecelakaan - Kecelakaan Pesawat yang Melibatkan Klub-Klub Sepakbola http:// ow.ly/h1Eh306EzHk"",,,,""8,04E+17"",""https://twitter.com/Widya_Davy/status/804008434588876803"""
"""redaksi18"",""01/12/2016 0:05"",0.0,0.0,""Klub Brasil Korban Kecelakaan Pesawat Didaulat Jadi Juara http:// beritanusa.com/index.php?opti on=com_content&view=article&id=39769:klub-brasil-korban-kecelakaan-pesawat-didaulat-jadi-juara&catid=43:liga-lain&Itemid=112 … pic.twitter.com/1K7OlZSX83"",,,,""8,04E+17"",""https://twitter.com/redaksi18/status/804008416188338176"""
"""JustinBiermen"",""01/12/2016 0:06"",0.0,0.0,""Video LUCU Kecelakaan Yg Sangat Koplak http://www. youtube.com/watch?v=pQFOY7 AdXck …"",,,,""8,04E+17"",""https://twitter.com/JustinBiermen/status/804008714738880512"""
So the issue is not the delimiter, but rather the enclosure. As you can see, each line is wrapped in quotes. So the entire line is considered to be a single column.
I suggest to fix the csv, e.g. remove the quotes until a row looks like
"username","date","retweets","favorites","text","geo","mentions","hashtags","id","permalink"
If you cannot do that for some reason, preprocess the csv to clean it up:
print_r(
array_map(
function($line) {
$single_quoted_line = str_replace(['"""', '""'], '"', $line);
return str_getcsv($single_quoted_line);
},
file("tes.csv")
)
);
|
[
"stackoverflow",
"0062082456.txt"
] | Q:
Subscribing to multiple observables sequentially with Rxjs
I am trying to make a http request only when my form is dirty. I tried using zip but it will still make the http request regardless as the pipe results will only apply on the subscribe block. Is there anyway for me to NOT nest the observables as I have to subscribe to another observable after the http call which will result is 3 nested layers of observable.
@ViewChild('form')
form: NgForm;
// only take events when form is dirty
const formValueChanges$ = this.form.valueChanges
.pipe(
debounceTime(500),
filter(() => this.form.dirty),
takeUntil(this._destroy$),
distinctUntilChanged(),
tap(result => {
console.log(result);
})
);
// http request returning an observable
const updateForm$ = this.tempService.update();
zip(formValueChanges$, updateForm$)
.subscribe((response) => {
console.log(response);
}
);
Intended Behaviour
this.form.valueChanges
.pipe(
debounceTime(500),
filter(() => this.form.dirty),
takeUntil(this._destroy$),
distinctUntilChanged(),
).subscribe(() => {
console.log("SAVED");
this.tempService.update().subscribe();
});
A:
You can use concatMap operator to be sure of the order, concatMap will wait for previous HTTP Observable to complete before mapping the new value from the form.
this.form.valueChanges
.pipe(
debounceTime(500),
filter(() => this.form.dirty),
takeUntil(this._destroy$),
distinctUntilChanged(),
concatMap(val => this.tempService.update())
).subscribe(console.log);
|
[
"stackoverflow",
"0004566887.txt"
] | Q:
UINavigationController as child view of UIViewController
I have an application that isn't nav based. So there is no UINavigationController in the App Delegate. However, I need to switch to a UINavigationController for a piece of the application. Steps I currently took...
Create a new Class that extends UIViewController
Added a UINavigationController via IB
Told IB that the new UIViewController's view is the view for the UINavigationController
The problem now is that the File's Owner needs it's view set. But via IB there is no way to specify this. So obviously, I'm not going about this the right way. Any tips in the right direction are much appreciated.
A:
connect your navigation controller in IB (in this case navController) and init it with your controller:
MessageViewController *mView = [[MessageViewController alloc]initWithNibName:@"MessageView" bundle:nil];
mView.navController = [[UINavigationController alloc] initWithRootViewController:mView];
[self presentModalViewController:mView.navController animated:YES];
[mView release];
|
[
"stackoverflow",
"0033374812.txt"
] | Q:
SpyOn returns Expected a spy, but got Function
I am testing a controller that calls a service(through the goToPage function) in order to redirect using the spyOn. It's simple but I am getting "Expected a spy, but got Function." error. What am I doing wrong?
This is my Spec:
var createController,service scope;
beforeEach(inject(function($rootScope, $controller,$injector){
service = $injector.get('service ');
scope = $rootScope.$new();
createController = function() {
return $controller('controller', {
'$scope': scope
});
spyOn(service , ['redirect']).andCallThrough();
};
}));
describe('test if service is called', function() {
it('should call the service', function() {
var controller=createController();
scope.goToPage();
expect(service.redirect).toHaveBeenCalled();
});
});
});
A:
First, you defined your spy after you called return, so that code will never be run. Second, define your spy in your test, not in beforeEach.
var createController,service scope;
beforeEach(inject(function($rootScope, $controller,$injector){
service = $injector.get('service ');
scope = $rootScope.$new();
createController = function() {
return $controller('controller', {
'$scope': scope
});
};
}));
describe('test if service is called', function() {
it('should call the service', function() {
var controller=createController();
spyOn(service , ['redirect']).andCallThrough();
scope.goToPage();
expect(service.redirect).toHaveBeenCalled();
});
});
|
[
"stackoverflow",
"0058450625.txt"
] | Q:
Understanding Ruby sort_by
I am new to ruby and I struggle understanding sort_by!. This method does something magically I really don't understand.
Here is a simple example:
pc= ["Z6","Z5","Z4"]
c = [
{
id: "Z4",
name: "zlah1"
},
{
id: "Z5",
name: "blah2"
},
{
id: "Z6",
name: "clah3"
}
]
c.sort_by! do |c|
pc.index c[:id]
end
This procedure returns:
=> [{:id=>"Z6", :name=>"clah3"}, {:id=>"Z5", :name=>"blah2"}, {:id=>"Z4", :name=>"zlah1"}]
It somehow reverses the array order. How does it do that? pc.index c[:id] just returns a number. What does this method do under the hood? The documentation is not very beginners friendly.
A:
Suppose we are given the following:
order = ['Z6', 'Z5', 'Z4']
array = [{id: 'Z4', name: 'zlah1'},
{id: 'Z5', name: 'blah2'},
{id: 'Z6', name: 'clah3'},
{id: 'Z5', name: 'dlah4'}]
Notice that I added a 4th hash ({id: 'Z5', name: 'dlah4'}) to the array array given in the question. I did this so that two elements of array would the same value for the key :id ("Z5").
Now let's consider how Ruby might implement the following:
array.sort_by { |hash| order.index(hash[:id]) }
#=> [{:id=>"Z6", :naCme=>"clah3"},
# {:id=>"Z5", :name=>"blah2"},
# {:id=>"Z5", :name=>"dlah4"},
# {:id=>"Z4", :name=>"zlah1"}]
That could be done in four steps.
Step 1: Create a hash that maps the values of the sort criterion to the values of sort_by's receiver
sort_map = array.each_with_object(Hash.new { |h,k| h[k] = [] }) do |hash,h|
h[order.index(hash[:id])] << hash
end
#=> {2=>[{:id=>"Z4", :name=>"zlah1"}],
# 1=>[{:id=>"Z5", :name=>"blah2"}, {:id=>"Z5", :name=>"dlah4"}],
# 0=>[{:id=>"Z6", :name=>"clah3"}]}
h = Hash.new { |h,k| h[k] = [] } creates an empty hash with a default proc that operates as follows when evaluating:
h[k] << hash
If h has a key k this operation is performed as usual. If, however, h does not have a key k the proc is called, causing the operation h[k] = [] to be performed, after which h[k] << hash is executed as normal.
The values in this hash must be arrays, rather than individual elements of array, due the possibility that, as here, two elements of sort_by's receiver map to the same key. Note that this operation has nothing to do with the particular mapping of the elements of sort_by's receiver to the sort criterion.
Step 2: Sort the keys of sort_map
keys = sort_map.keys
#=> [2, 1, 0]
sorted_keys = keys.sort
#=> [0, 1, 2]
Step 3: Map sorted_keys to the values of sort_map
sort_map_values = sorted_keys.map { |k| sort_map[k] }
#=> [[{:id=>"Z6", :name=>"clah3"}],
# [{:id=>"Z5", :name=>"blah2"}, {:id=>"Z5", :name=>"dlah4"}],
# [{:id=>"Z4", :name=>"zlah1"}]]
Step 4: Flatten sort_map_values
sort_map_values.flatten
#=> [{:id=>"Z6", :name=>"clah3"},
# {:id=>"Z5", :name=>"blah2"},
# {:id=>"Z5", :name=>"dlah4"},
# {:id=>"Z4", :name=>"zlah1"}]
One of the advantages of using sort_by rather than sort (with a block) is that the sort criterion (here order.index(hash[:id])) is computed only once for each element of sort_by's receiver, whereas sort would recompute these values for each pairwise comparison in its block. The time savings can be considerable if this operation is computationally expensive.
|
[
"stackoverflow",
"0039866108.txt"
] | Q:
Generate Signed Apk Error Multidex
My app is working properly. There is no problem. i want to build generated signed apk. The problem is building take too long and completed with errors.
Please check the image. Thanks.
Error:Execution failed for task ':app:transformClassesWithDexForRelease'.> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: java.lang.UnsupportedOperationException
here my gradle;
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "umut.com.anyidea"
minSdkVersion 19
targetSdkVersion 24
versionCode 1
versionName "1.0"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:multidex:1.0.1'
compile 'com.google.firebase:firebase-messaging:9.6.0'
compile 'com.google.firebase:firebase-core:9.6.0'
compile 'com.google.firebase:firebase-crash:9.6.0'
compile 'com.google.android.gms:play-services:9.6.0'
compile 'com.google.android.gms:play-services-auth:9.6.0'
compile 'com.android.support:cardview-v7:+'
compile 'com.android.support:support-v4:24.2.1'
compile 'com.afollestad.material-dialogs:core:0.9.0.1'
compile 'com.google.firebase:firebase-database:9.6.0'
compile 'com.google.firebase:firebase-auth:9.6.0'
compile 'com.firebaseui:firebase-ui-database:0.6.0'
}
apply plugin: 'com.google.gms.google-services'
A:
In versions of Google Play services prior to 6.5, you had to compile the entire package of APIs into your app. In some cases, doing so made it more difficult to keep the number of methods in your app (including framework APIs, library methods, and your own code) under the 65,536 limit.
From version 6.5, you can instead selectively compile Google Play service APIs into your app. For example, to include only the Google Fit and Android Wear APIs,
Please refer this document:
https://developers.google.com/android/guides/setup
for example if you need Google Account Login then just use :
com.google.android.gms:play-services-auth:9.6.1 not use compile 'com.google.android.gms:play-services:9.6.1'
|
[
"math.stackexchange",
"0001699330.txt"
] | Q:
Upper Bound on Number of Factors
Is there a theorem, lemma, or proof somewhere that proves an upper bound for the number of factors that a number can have?
If not, would it be fairly trivial to prove that it is $log_2 n$?
A:
given that log2(24) is approx. 4.5, but 24 has 8 factors. I have to say, that this is not an upper bound.
I personal looked for an upper bound recently to the number of factors function and I got sqrt(3*x), it might not be the tightest upper bound. but it works.
look at the image bellow
https://i.stack.imgur.com/0bWW9.png
|
[
"stackoverflow",
"0051086287.txt"
] | Q:
regex for phrase searching
I have to search phrase in big string may be length of 500 or 600 or greater now I have to check whether phrase exist or not
phrase = "Lucky Draw"
big string1 = "I'm looking for Lucky Draw a way to loop through the sentences and check"
big string1 = "I'm looking for specialLucky Draw a way to loop through the sentences and check"
big string3 = "I'm looking for Lucky Draws a way to loop through the sentences and check"
bool success = Regex.Match(message, @"\bLucky Draw\b").Success;
I am doing the above workaround but it does not satisfy all cases.
what I have to do when I have multiple phrases, I want to use linq in that case like :
bool success = Regex.Match(message, **arrayofstrings**).Success;
A:
You can use a loop to build one large regex of \b(phrase one|phrase two|phrase three|etc)\b from your array of phrases and then use that regex to match against your strings.
|
Subsets and Splits