text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How can I create rounded corners In Adobe Illustrator in a specific way?
Say i'm rounding the corners of a word that i've typeset in Illustrator (as if i were creating a logo). That word is 'Kresge' and i've set it in 'Avenir Heavy', a sturdy sans-serif typeface. You'll notice that 'Kresge' contains letterforms that are naturally round like the 's' or the lowercase 'e'.
When i navigate to Illustrator's menu and select: Effects > Stylize > Rounded Corners, it brings up a dialog prompt asking me to specify the radius of the rounded corners and I do. In this case, i want the radius to be almost undetectable at 0.004 inches.
When i hit 'Okay', it does indeed round the edges of the letterforms. But the letters that are already rounded to some extent become jagged and loose their precise geometry. This is because the algorithm is trying to round a shape that already has round proportions. Makes sense.
What i'd like is for the style to focus only on the pointed "hard" edges of the 'e' or the 's', but not the entire letter. Is there a way to get Illustrator to do this? A way that might allow me to now have to go back in and smooth over the jagged edges of each letter after i've applied the style?
Example of what i'm experiencing (before & after corner rounding):
Thanks very much for your help!
A:
You're going to have to Outline the text and then use the Direct Select tool on the parts you want rounded. I'm also not sure how far back this feature exists but in Adobe Illustrator CC there's a Corner Radius function. Using the Direct Selection along with Corner Radius on specific points you can achieve the result you're after as so:
If you're using an older version with no Corners function you'll have to do it manually. Scott's third link in the original question's comments has some information on doing it that way.
| {
"pile_set_name": "StackExchange"
} |
Q:
Play/BoneCP message "releaseHelperThreads has been deprecated"
Does anyone know if the following message obtained when starting a Play 2.2 app is important or not?
WARN - releaseHelperThreads has been deprecated
-- it tends to slow down your application more.
I cannot find this setting anywhere, and most references to the message are just log output. I'm assuming it is a bonecp setting, but can't see where play is setting it, if, in fact, it is doing so.
A:
Judging from this, play is setting releaseHelperThreads to 0 (disabled?), but as the setting is deprecated, any call to the setter produces the warning message. If I understood the code comments correctly, the message will disappear once Play moves to BoneCP 0.8.0 or beyond. Bottom line: nothing to worry about.
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery setTimout ruins all func
I have the following function on JQuery to show my tooltips, but
when i try to add a timeout to make some delay before showing a tooltip nothing works(((
$('.help').mouseover(function(){
setTimeout(function{ //this is timeout if i delete this - evrthng goes well
$(this).find('div').stop().fadeIn(900);
var top = $(this).position().top;
var left = $(this).position().left;
var height = $(this).find(".tip").height();
$(this).find(".tip").css('top', top-height);
$(this).find(".tip").css('left', left)
}, 1000);
});
Please tell me what am i doing wrong?
A:
Inside setTimeout(), this refers to Window instead of to $('.help'). Try this:
$('.help').mouseover(function(){
var that = this;
setTimeout(function() {
$(that).find('div').stop().fadeIn(900);
var top = $(that).position().top;
var left = $(that).position().left;
var height = $(that).find(".tip").height();
$(that).find(".tip").css('top', top-height);
$(that).find(".tip").css('left', left)
}, 1000);
});
Take into account that setTimeout() is a method of Window.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I get Thunderbird to import a secure LDAP certificate?
I've got an LDAP server configured for in Thunderbird's address book (ldap.example.com). I'd like to use the SSL version, so I checked the 'Use SSL' box. It starts to work, but I get a certificate warning in response. Okay, sure, I know that server uses a funny certificate, so I'll add it.
I found the 'Add Security Exception' box readily enough, and it asks me for a server location. But I don't know what to put in there. The dialog box starts with https:// in it, but https://ldap.example.com doesn't work, and neither does anything like imaps:// or ldap:// or ldaps:// (is that a real protocol name? well, I tried it). LDAP really is the only service this server provides.
How can I get Thunderbird to read the certificate?
A:
In subsequent exploration I discovered that you can simply provide the URL https://ldap.example.com:636 (636 being the SSL+LDAP port) and Thunderbird will do the SSL negotation necessary to get the certificate, drop the connection, and never realize that it's not actually talking HTTP.
I'm going to file something with the Thunderbird bug tracker suggesting they take ldaps:// as a protocol specifier, instead of using that silly hack.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to return VM from many-to-many result?
I want to return from the GroupBook Class , A set of books they have same group id ...
I have this relation between those tables :
public class GroupBook
{
[Key]
public int Id { get; set; }
[Required]
public int Book_Id { get; set; }
[Required]
public string User_Id { get; set; }
[Required]
public int Group_id { get; set; }
public virtual AspNetUser AspNetUser { get; set; }
public virtual Book Book { get; set; }
public virtual Group Group { get; set; }
}
public partial class Group
{
public Group()
{
GroupBooks = new HashSet<GroupBook>();
}
[Key]
public int Group_id { get; set; }
[Required]
public string Group_name { get; set; }
public string Group_description { get; set; }
public string UrlSlug { get; set; }
public int state { get; set; }
[Required]
public string User_Id { get; set; }
public virtual AspNetUser AspNetUser { get; set; }
public virtual ICollection<GroupBook> GroupBooks { get; set; }
}
also my book table :
public partial class Book
{
public Book()
{
GroupBooks = new HashSet<GroupBook>();
}
[Key]
public int Book_id { get; set; }
[Required]
[StringLength(128)]
public string User_ID { get; set; }
public string UrlSlug { get; set; }
[Required]
public string Book_name { get; set; }
public string Book_Description { get; set; }
public virtual ICollection<GroupBook> GroupBooks { get; set; }
public virtual AspNetUser AspNetUser { get; set; }
}
and here is my Vm:
public class GroupVm
{
public List<Book> Book { set; get; }
}
I want to return in VM Set of books like this :
public ActionResult Index(int? Group_id)
{
Vm=db.books.where(//What to add here to return set of books that == the group id I will send via method)
}
As the previous example , I simply want to return set of books that exists with the same group_id , how to do that please ??
A:
Add DbSet<GroupBook> GroupBooks into your DbContext.
Then do something :
var vm = new GroupVm();
vm.Book = db.GroupBooks.Where(g => g.Group_id == Group_id).Select(g => g.Book).ToList();
| {
"pile_set_name": "StackExchange"
} |
Q:
Android AlarmClock() , setting alarm date
I am having trouble with setting a specific date to AlarmClock() rather than AlarmManager(). All the example I am having over internet shows to start an activity at a specific date using AlarmManager(). but my app dosent have / need a custom activity. I only need to register a system alarm on a specific day where it will ring like generic android system alarm.
Calendar c = Calendar.getInstance();
Intent alarmIntent = new Intent(AlarmClock.ACTION_SET_ALARM);
alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
alarmIntent.putExtra(AlarmClock.EXTRA_MESSAGE, "Polo!");
alarmIntent.putExtra(AlarmClock.EXTRA_HOUR, c.get(Calendar.HOUR_OF_DAY));
alarmIntent.putExtra(AlarmClock.EXTRA_MINUTES, c.get(Calendar.MINUTE) + 1);
context.startActivity(alarmIntent);
above is my code. I tried to use
alarmIntent.putExtra(AlarmClock.EXTRA_DAYS, c.get(Calendar.DAY_OF_MONTH));
but it only takes the current day.
Please help me setting alarm using the AlarmClock() on a specific day.
A:
From documentation:
EXTRA_DAYS (optional): Weekdays for repeating alarm.
So actually, AlarmClock.EXTRA_DAYS is for days in week when this alarm should ring, so you can't set exact date for the alarm. Example usage:
ArrayList<Integer> days = new ArrayList<Integer>();
days.add(Calendar.SATURDAY);
alarmIntent.putExtra(AlarmClock.EXTRA_DAYS, days);
| {
"pile_set_name": "StackExchange"
} |
Q:
Knockout js checkbox checked binding
In knockout js am trying to perform a foreach on an array of data to display check boxes. The issue I am having is that the checked databind does not appear to run until I interact with one of the boxes. For example, below I am generating 5 text boxes none of which are showing up as checked. However when I click "one", "two" and "four" also get checked as they should have been from the beginning.
Javascript:
var viewModel = {};
viewModel.choices = ["one", "two", "three", "four", "five"];
viewModel.selectedChoices = ko.observableArray(["two", "four"]);
viewModel.selectedChoicesDelimited = ko.dependentObservable(function () {
return viewModel.selectedChoices().join(",");
});
ko.applyBindings(viewModel);
HTML:
<ul class="options" data-bind="foreach: choices">
<li><label><input type="checkbox" name="NotifyMembers" data-bind="checked: $parent.selectedChoices, attr: { value: $data }" /><span data-bind="text: $data"></span></label></li>
</ul>
<hr />
<div data-bind="text: selectedChoicesDelimited"></div>
Fiddle is at: http://jsfiddle.net/bvGG3/1/
Thanks for your help.
A:
In Knockout before version 3.0 the bindings fired in order, so your problem is that your checked binding fires before your attr binding.
So you need to change the order of your bindings:
<input type="checkbox" name="NotifyMembers"
data-bind="attr: { value: $data }, checked: $parent.selectedChoices" />
Demo JSFiddle.
Or your original code will work when you update to 3.0 (demo JSFiddle).
| {
"pile_set_name": "StackExchange"
} |
Q:
Do mortals also reduce superficial damage in Vampire V5?
I'm a storyteller from Vampire v20, and there, vampires reduce bashing damage (that is, the equivalent for superficial damage in v5) because they are undead. But if I understand v5 rules right, superficial damage is halved almost every time, even if you are not. Is that true? Or do only undead halve their damage?
A:
Yes, superficial damage is halved in V5 for mortals and vampires alike. (p.126) This replaces what used to be handled by the soak roll.
| {
"pile_set_name": "StackExchange"
} |
Q:
Class Cast Exception retrieving Chosen date from childfragment to show in parent fragment
I have a parentfragment called Planning in which I want to show a DialogFragment called DatePickerfragment.The DatePickerFragment has a button that when clicked, will show a datepicker for the user. The user selects a date and that date should be passed to the Parent Fragment in a textview called 'date'.
Unfortunately, everytime I click the button the app crashes with this error:
java.lang.ClassCastException: com.example.android.meat_timealpha10.Activities.MainActivity cannot be cast to android.app.DatePickerDialog$OnDateSetListener
at com.example.android.meat_timealpha10.Fragments.DatePickerFragment.onCreateDialog(DatePickerFragment.java:29)
I know where the error is but I don't know how to fix it.
It refers to this line in the DatePickerDialogFragment:
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener)getActivity(), year, month, day );
The thing is I followed a youtube video and the guy doesn't seem to have any issues. Then again, he doesn't use nested fragments like me.
Does anyone know how to fix that error so that the chosen date gets displayed in the textview?
Here is my code:
XML of parent fragment :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Fragments.planning">
<Button
android:id="@+id/chooseDate"
style="@style/Widget.AppCompat.Button.Borderless.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="5dp"
android:elevation="0dp"
android:hint="touch here to select date"
android:textSize="20sp" />
<TextView
android:id="@+id/date"
android:layout_width="match_parent"
android:layout_height="30dp"
android:textColor="@color/blue" />
</LinearLayout>
Following is Child Fragment DatePickerFragment:
package com.example.android.meat_timealpha10.Fragments;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.TextView;
import com.example.android.meat_timealpha10.R;
import org.w3c.dom.Text;
import java.text.DateFormat;
import java.util.Calendar;
public class DatePickerFragment extends DialogFragment {
public String dateHolder;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener)getActivity(), year, month, day );
}
}
Code of parent fragment ( without imports )
public class planning extends Fragment implements DatePickerDialog.OnDateSetListener{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public planning() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment planning.
*/
// TODO: Rename and change types and number of parameters
public static planning newInstance(String param1, String param2) {
planning fragment = new planning();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_planning,
container, false);
final Button chooseDate = (Button)view.findViewById(R.id.chooseDate);
chooseDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getChildFragmentManager(), "date picker");
}
});
return view;
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
TextView date = (TextView)view.findViewById(R.id.date);
date.setText(currentDateString);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
I am fairly new at this so please try to make it easy enough to understand when answering my question.
Thanks in advance people!
A:
as it suggested, you can not cast activity to be a Listener, the error occurs in this line: (DatePickerDialog.OnDateSetListener)getActivity().
you need to implement DatePickerDialog.OnDateSetListener in your fragment and override onDateSet function:
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
...
return new DatePickerDialog(getActivity(), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
...
}}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to read header from http::response in Boost
Trying to use boost for http connection.
So far I have followed the official guide and I was able to get the response correctly and parse the body:
// Send the HTTP request to the remote host
http::write(stream, req);
// This buffer is used for reading and must be persisted
beast::flat_buffer buffer;
// Declare a container to hold the response
http::response<http::dynamic_body> res;
// Receive the HTTP response
http::read(stream, buffer, res);
// Write the message to standard out
std::cout << res << std::endl;
std::string body { boost::asio::buffers_begin(res.body().data()),
boost::asio::buffers_end(res.body().data()) };
The problem now is that I don't know how to get the header and check the status code. Any help?
A:
The status code is not a header, and it's just a property of the response object:
std::cout << res.result_int() << std::endl;
std::cout << res.result() << std::endl;
std::cout << res.reason() << std::endl;
for (auto& h : res.base()) {
std::cout << "Field: " << h.name() << "/text: " << h.name_string() << ", Value: " << h.value() << "\n";
}
Prints things like
200
OK
OK
Field: Age/text: Age, Value: 437767
Field: Cache-Control/text: Cache-Control, Value: max-age=604800
Field: Content-Type/text: Content-Type, Value: text/html; charset=UTF-8
Field: Date/text: Date, Value: Tue, 23 Jun 2020 16:43:43 GMT
Field: ETag/text: Etag, Value: "3147526947+ident"
Field: Expires/text: Expires, Value: Tue, 30 Jun 2020 16:43:43 GMT
Field: Last-Modified/text: Last-Modified, Value: Thu, 17 Oct 2019 07:18:26 GMT
Field: Server/text: Server, Value: ECS (bsa/EB15)
Field: Vary/text: Vary, Value: Accept-Encoding
Field: <unknown-field>/text: X-Cache, Value: HIT
Field: Content-Length/text: Content-Length, Value: 1256
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the dangers of hot-linking assets from other websites
Say there is a situation where site a is directly linking a font file
ie https://www.example.com/FONT.woff2
from site b.
Would it be possible for someone to make a URL rewrite rule to point to a malicious file then someone who would visit site a would download the malicious file instead of the intended one?
for example, the user would hit site a, site b would have a rewrite rule for the specified font so when that is called it would redirect to https://www.example.com/MALICIOUS.JS instead.
A:
Including resources from a third party site means that you include resources in your page where you have no control about the content of the resource. Thus, even if the content was the expected one at the time you've added the link it can change whenever it suites the owner of the site - or somebody which hacked the site. This is not restricted to a redirect as you envision but the third party site can serve a different content in the first place.
The impact of this depends on what kind of resources you hotlink. If you include JavaScript from a third party site (like done a lot when offering the ability to share on social media) then the third party can essentially fully control what gets displayed to the visitor of your site but also embed a keylogger in your page or similar. Including fonts might be a problem too since malicious fonts could be used multiple times in the past to use bugs in the browser or OS and execute malware.
And while replacing images will usually not result in unwanted code execution (unless another bug in image processing is exploited) you can get instead an image you don't actually want on your site. For example some sites punish unwanted hotlinking with "special" images but it might also be more harmful be used for phishing attacks as seen in this answer. See also this question for more ideas.
Note that the replaced resource still needs to match the expected type of resource. This means if the browser expects a font and the attacker serves a JavaScript file instead it will not be executed. But if the attacker serves a malicious font in this case it will be used.
For some types of resources and for some browsers subresource integrity will help to detect if third party resources gets changed and not load the resource in this case. But, this currently works mainly with script and css and for example not with fonts or images. And, it works currently only with Chrome, Opera, Firefox and Safari.
A:
There are many potential problems. If you are including javascript, they can do a lot of bad things, like keylogging or completely change the webpage to display a phishing page, or download malware, or something like that.
Even with just images, the user's privacy will be compromised because they will know the IP address and referrer. Even worse, they can include an http basic authentication requirement to the image and attempt to phish for credentials.
https://securitycafe.ro/2017/09/06/phishy-basic-authentication-prompts/
| {
"pile_set_name": "StackExchange"
} |
Q:
Recommendations for sysctl.conf settings to harden Linux against DDoS attacks?
A recent article from UNIXy http://blog.unixy.net/2010/08/the-penultimate-guide-to-stopping-a-ddos-attack-a-new-approach/ has suggestions to harden a Linux box against DDoS attacks.
Example of sysctl.conf
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
kernel.pid_max = 65536
net.ipv4.ip_local_port_range = 9000 65000
Any other recommendations for hardening Linux against DDoS attacks?
A:
You can also turn down the read/write socket buffers as well, which would decrease the amount of memory each inbound connection requires.
http://wwwx.cs.unc.edu/~sparkst/howto/network_tuning.php
You'll have to actually test it out for your application and your hardware (yes, those settings can cause weird side effects depending on your NIC), since you may break more than you save depending on your traffic flow.
| {
"pile_set_name": "StackExchange"
} |
Q:
Display multiple hidden divs using jquery?
I have a code something like this:
<div id="specialDiv">
<div id="div1">
<div id="div2">
</div>
</div>
<div>
The div1 and div2 are hidden and right now in order to display them i am doing something like this:
$('#div1').show();
$('#div2').show();
It works but is there an elegant way to do this other than
$('#speicalDiv div').show();
Thanks.
A:
You can use a multiple selector:
$("#div1, #div2").show();
| {
"pile_set_name": "StackExchange"
} |
Q:
Do all functions have an osculating circle?
Radius of curvature is defined as the radius of a circle that has a section that follows/approximates a function/curve over some interval. Now, it's easy to Google pictures of curves that have osculating circles drawn in and it seems obvious that this is a clever way of defining curvature of a function. But do all curves follow a part of a circle close up? I mean, many curves do look round at some points and it seems reasonable to assume you could fit the curve to a circumference a circle, but is this always true? If so, why are circles so special and can we prove that you can fit a circle into a curve? If not, what are the requirements that a circle fits?
A:
"All curves"? No.
Indeed, non-differentiable curves do not even have a tangent line.
A requirement for osculating circle, will be that the first and second derivatives exist and are non-zero. For the osculating circle, we use the circle with the same values of those two derivatives at that point.
Of course if the second derivative is $0$, then the osculating circle is actually a line.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dandelions taking over the lawn
My lawn was overrun with dandelions so I've used some Ortho Weed-B-Gon Max and that seems to be killing the dandelions very well. The problem is now my lawn is very sparse with grass. There just wasn't much grass there after killing the dandelions. I've thought about reseeding but every bag I look at wants me to till up the ground before putting the seed down. I've also thought about just using fertilizer but wasn't sure if that would do enough or even help the dandelions survive the herbicides.
What is the best approach to getting my lawn back to full grass the easist and cheapest way possible.
A:
The label for this product does not recommend applying grass seed until four weeks after the last application.
Once this waiting period is up buy or acquire:
a big bag of grass seed suitable for the light and soil in your lawn
enough compost or top soil to cover the sparse areas to a depth of 1/4" to 1/2"
Then
Use a rake to open up the soil.
Apply grass seed at a generous rate
top dress with compost or top soil
water in and continue to water until the seed sprouts
Do this twice a year in the spring and fall and you can put your Weed-B-Gon away!
A:
Dandelions grow on poor compacted soil. The soil can be poor or clay soil with drainage problems. They successfully grow where the grass struggles a bit. Whilst it would be less hassle to just re-seed grass, it probably won't improve the growing conditions (soil) and dandelions are likely to return. I would suggest ripping the soil and adding whatever is needed. That could be gypsum and/or sharp sand or crusher dust.
A:
Most weeds are opportunists. If your grass is not doing well, weeds will proliferate. Aerate your lawn by pulling plugs of soil out of your lawn. Go over it as many times as you can. Allow the plugs to disintegrate on top of your...lawn. Get a soil test done. Find out what nutrients are low, high, acceptable and what the pH of your soil is...do you have 1" of thatch or more? If so you might need to power rake up the thatch and remove it.
After the four weeks are up and you've gotten your tests back you will have the information you need to regrow your lawn. The pH should be 6.5-7.0. If not, apply lime. Use half the amount recommended. You want to raise the pH slowly in stages if possible. Buy the best lawn seed available. On the label you should see 'weed seed = zero'...make sure this seed is for your area.
Before spreading seed, I'd put fertilizer down. The absolute best stuff I have used is by Dr. Earth...lawn fertilizer. I am sure there are other products similar by now but they should be organic, extended release, have the proper amounts of NPK for your lawn soil (according to your soil tests), micronutrients and bacteria (one of these bacteria will help decompose thatch) to innoculate your soil with beneficial life.
Use a spreader for the fertilizer and apply the correct amount. It will be more than you are used to if you've been using inorganic fast release fertilizers. I think it is 9# per 1000 versus 5# per 1000 sq.ft.
If you've thatched and/or aerated, there should be enough soil to seed. You don't want too much soil or mulch dumped on top of your seed or it won't germinate. You want your seed in contact with soil, not mulch. Your soil could probably use the organic matter but you can do that later when your lawn is more mature. Also, test your soil again for pH. If it is below 6.5, add more lime. Never apply lime without testing first.
Apply the seed with your spreader, in the amount suggested on the package. Don't throw it on by hand and don't over-apply, either. Rake lightly with a leaf rake and then roll.
Keep the top continually moist. It might mean you water 2 or 3 times a day. Do not saturate. This takes almost 2 weeks. Allow the soil to dry a bit before your first mowing. Gradually allow the soil to dry out between waterings to train your lawn to have deep roots and becomes drought tolerant. Aim for once per week watering. When you water make sure the amount is enough to wet the soil 4-6" deep. Don't water again until your footprints in the grass are clear and the blades stay down. Then water deeply. And water during the day so that your grass isn't wet at night. This will prevent disease.
Mowing. Not sure where you live but if your grass is like ours in the Pacific Northwest, never mow below 3". These grasses have large root systems, genetically. If there isn't enough top growth to feed these roots, your grass will not thrive and the weeds will be back. Always make sure your blades are sharp. If you miss a week of mowing and the grass has gotten long, take it down in stages. Don't cut more than 1/3 of the height in one cutting. And remove the clippings. I haven't got much trust in mulching mowers. If this were a huge pasture I wouldn't remove clippings, but if you've invested all this effort, I'd use the clippings in my compost, to be used after decomposed.s
Your lawn should look lush and dark green. The 3" height will shade out weed seeds and help to preserve moisture.
Fertilize at least twice a year. The percentages of the nutrients are different from spring to summer and fall. Aerate once per year. Add a thin layer of compost after aeration. Water deeply and allow to dry out before watering again.
You shouldn't have to ever use an herbicide again.
| {
"pile_set_name": "StackExchange"
} |
Q:
No architectures to compile for (ARCHS=, VALID_ARCHS=armv7 armv7s)
I am using Xcode 4.5.2 and have a project which cannot be compiled for an iPhone running iOS 6.0.1 though other projects compile fine with the same settings as shown in the picture below.
Any ideas on how to solve this?
A:
You're probably using some third party lib that doesn't yet support armv7s architecture. You can just remove armv7s from your settings. Your app will still be able to run on iPhone 5 although it might not be taking full advantage of the new architecture.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does a Magic Trackpad have a button?
Does a Magic Trackpad have a button, as opposed to just being a trackpad? I am not sure if this even makes sense, so let me know if I need to clarify.
A:
Yes, it has two physical buttons on the edge lacking the battery tray. The two rubber feet on the bottom-front of the trackpad press against internal switches.
For these to activate, you have to use it on a hard surface. The software tap-to-click that senses your finger pad deforming as it taps the immovable glass surface also will trigger a tap independently from the physical buttons.
| {
"pile_set_name": "StackExchange"
} |
Q:
Winform GUI Thread - Should there be a single catch block?
I have read it here : CodeProject
and some other places that there should be a single catch block per thread. I don't quite understand this in context of winforms. Is it true also in case of winforms? I understand that worker threads should have a single catch block. But, I have multiple catch blocks on the UI(main) thread which always end up calling my private HandleError method passing the exception. This method then takes care about how to display the errors to an user. So, say I might have a try/catch block in button1_click handler and another try/catch block in another button2_click handler. Is this a good practice? Can someone tell me if I should do something differently. Thanks.
A:
I think you should read that rule as "there should at least be a single catch block per thread". Every thread, and certainly the main thread, should use catch blocks wherever appropriate.
| {
"pile_set_name": "StackExchange"
} |
Q:
Solidworks API and Winforms C# swApp (Standalone)
This is what solidworks tells you to do to reference swApp, but I keep getting NullReferenceException on the line that it is referenced.
Does anyone have any idea why? or How I go about repairing?
Can I reference it later on such as swApp = ????
private void button5_Click(object sender, EventArgs e)
{
//Save Drawing
ModelDoc2 swDoc = null;
int longstatus = 0;
swDoc = ((ModelDoc2)(swApp.ActiveDoc));
longstatus = swDoc.SaveAs3(
@"C:\Engineering\Engineering\SW Automation\Linear Actuator Technology\MLD Series\Prints\Configured Prints\" +
textBox1.Text + ".SLDDRW", 0, 2);
}
public SldWorks swApp;
A:
Figured it out thanks for the help everyone.
SldWorks swApp = null;
swApp = (SldWorks)Activator.CreateInstance(
Type.GetTypeFromProgID("SldWorks.Application"));
| {
"pile_set_name": "StackExchange"
} |
Q:
Linker failed with error code 1
I keep getting the error Linker command failed with exit code 1 and it seems to be because of my .h-file. In my stringsDE.h I define constant strings. Might this be the problem?
duplicate symbol _QUESTIONCATBUTTONMIXED in:
/Users/philip_air/Library/Developer/Xcode/DerivedData/juraQuiz-awgytksreajdjbdmoctjoffmzmmk/Build/Intermediates/juraQuiz.build/Debug-iphoneos/juraQuiz.build/Objects-normal/armv7/appLaunch.o
/Users/philip_air/Library/Developer/Xcode/DerivedData/juraQuiz-awgytksreajdjbdmoctjoffmzmmk/Build/Intermediates/juraQuiz.build/Debug-iphoneos/juraQuiz.build/Objects-normal/armv7/quizVC.o
ld: 17 duplicate symbols for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)
CODE:
http://pastebin.com/iGTVAb6K
A:
Declare all of your strings in your .h file using:
// QUESTIONCAT BUTTONS
extern NSString const *QUESTIONCATBUTTON1;
extern NSString const *QUESTIONCATBUTTON2;
extern NSString const *QUESTIONCATBUTTON3;
extern NSString const *QUESTIONCATBUTTONMIXED;
and then truly define them in one single .m file like this:
// QUESTIONCAT BUTTONS
NSString * const QUESTIONCATBUTTON1 = @"Zivilrecht";
NSString * const QUESTIONCATBUTTON2 = @"öffentliches Recht";
NSString * const QUESTIONCATBUTTON3 = @"Strafrecht";
NSString * const QUESTIONCATBUTTONMIXED = @"Gemischt";
| {
"pile_set_name": "StackExchange"
} |
Q:
Pyspark: sbt assembly: maxpermisze as unrecognized VM option
lucas@ubuntu:~/spark/spark$ sbt/sbt assembly
NOTE: The sbt/sbt script has been relocated to build/sbt.
Please update references to point to the new location.
Invoking 'build/sbt assembly' now ...
Unrecognized VM option 'MaxPermSize=512M'
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
When trying to build spark I have the above error. I'm not sure how I can fix it. The Java version is 1.9.
A:
First, I should say that java 1.9 is not officially out yet, therefore it's not recommended to use it unless you really have reasons for that. If using java 9 is not a must for you, then consider to switch to java 8. This will also fix the error because the MaxPermSize option in it is deprecated but not yet removed.
In case you still want to use java 9, you have to edit the file project/SparkBuild.scala to remove -XX:MaxPermSize=... from the javaOptions in it (I see 3 matches in spark 1.5.0)
| {
"pile_set_name": "StackExchange"
} |
Q:
Silex - UserProviderInterface always returns "Bad credentials"
I am trying to add Users saved in a database to my Silex website using the SecurityProvider.
I registered the security provider
$app['security.firewalls'] = array
(
'admin' => array
(
'pattern' => '^/admin',
'form' => array('login_path' => '/login', 'check_path' => '/admin/login_check'),
'logout' => array('logout_path' => '/admin/logout', 'invalidate_session' => true),
'users' => function() use($app)
{
return new Entity\UserProvider($app);
}
)
);
And the Entity\UserProvider($app) class goes as follow (only part of the code is shown)
class UserProvider implements UserProviderInterface
{
public function loadUserByUsername($username)
{
return new User('blabla', 'patate', ['ROLE_ADMIN'], true, true, true, true);
}
}
But even though i return a new User, and do not throw a UsernameNotFoundException the login page still gives me a Bad credentials. message.
Why am i getting this bad credentials message ? Did i forget something ? Did i mess up some config ?
Thanks
A:
Password encoder algorytms that are used in silex and on creating user differ.
Encoder in silex is set by parameter security.default_encoder
$app['security.default_encoder'] = function ($app) {
return $app['security.encoder.bcrypt'];
};
...
$app['security.encoder.bcrypt'] = function ($app) {
return new BCryptPasswordEncoder($app['security.encoder.bcrypt.cost']);
};
Use bcrypt for password encoding on user creation
return new User(
'blabla',
$app['security.encoder.bcrypt']->encodePassword('patate', ''),
['ROLE_ADMIN'],
true, true, true, true
);
Or change silex encoder to plaintext (without encoding) to check if login works
$app['security.default_encoder'] = function ($app) {
return new \Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder();
};
| {
"pile_set_name": "StackExchange"
} |
Q:
How to drop observations after a certain condition has been met in Python using pandas
I am using a pandas dataframe and I want to delete observations with the same name after they met the condition (cond=1).
My dataset looks like:
person cond
A 0
A 0
A 1
A 0
A 0
B 0
B 1
C 1
C 0
I want to get this:
person cond
A 0
A 0
A 1
B 0
B 1
C 1
I want the code to first check if the next person has the same name, then check if the condition is met (cond=1) and if so drop all the next lines with the same name.
Can someone help me with this?
A:
You can do this using groupby and apply a lambda that slices the df from the start until the first max value using idxmax, which in this case will be the first 1 value:
In [16]:
df.groupby('person')['cond'].apply( lambda x: x.loc[:x.idxmax()]).reset_index()
Out[16]:
person level_1 cond
0 A 0 0
1 A 1 0
2 A 2 1
3 B 5 0
4 B 6 1
5 C 7 1
You can also make an additional call to drop to remove the 'level_1' col:
In [23]:
df.groupby('person')['cond'].apply( lambda x: x.loc[:x.idxmax()]).reset_index().drop('level_1', axis=1)
Out[23]:
person cond
0 A 0
1 A 0
2 A 1
3 B 0
4 B 1
5 C 1
update
to handle the situation where you have no 1 in the group we can test if this is the case in the lambda:
In [24]:
import pandas as pd
import io
# setup some data
t="""person cond
A 0
A 0
A 1
A 0
A 0
B 0
B 1
C 1
C 0
D 0
D 0"""
df = pd.read_csv(io.StringIO(t), delim_whitespace=True)
df
Out[24]:
person cond
0 A 0
1 A 0
2 A 1
3 A 0
4 A 0
5 B 0
6 B 1
7 C 1
8 C 0
9 D 0
10 D 0
In [29]:
df.groupby('person')['cond'].apply( lambda x: x.loc[:x.idxmax()] if len(x[x==0]) != len(x) else x)
Out[29]:
person
A 0 0
1 0
2 1
B 5 0
6 1
C 7 1
D 9 0
10 0
Name: cond, dtype: int64
So here we test if all values are 0 and if so just return the group otherwise we slice as before
| {
"pile_set_name": "StackExchange"
} |
Q:
Element of that $\mathbb Q[\sqrt{2}]$ have a square root in $\mathbb Q[\sqrt{2}]$
So I am learning about Quadratic Fields and I have a question:
Consider $\mathbb Q[\sqrt{2}]$. So does every element of that $\mathbb Q[\sqrt{2}]$ have a square root in $\mathbb Q[\sqrt{2}]$. I think that this essentially means that . I don't know if this is right though. Is this true or false. If true why is it true and if falso can someone show me a counterexample.
A:
Let $\alpha = a+b\sqrt{2} \in \mathbb{Q}[\sqrt{2}]$ be such that $\alpha^2=\sqrt{2}$. Then we get
\begin{align*}
(a+b\sqrt{2})^2 & = \sqrt{2}\\
a^2+2b^2+2ab\sqrt{2} & = \sqrt{2}.
\end{align*}
This yields
\begin{align*}
a^2+2b^2 & = 0\\
2ab & = 1.
\end{align*}
But this has no solutions for $a,b \in \mathbb{Q}$. Thus there is no square root of $\sqrt{2}$ inside $\mathbb{Q}[\sqrt{2}]$.
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS why tableview always stop in breakpoint?
I create a TableView via StoryBoard. I connect all the element to a UITableViewCell class call PostTableCell. I already set identifier for the tableCell in StoryBoard. My code is as below:
class PopViewController: UIViewController ,IndicatorInfoProvider ,UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var popTableView: UITableView!
var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
popTableView.dataSource = self
popTableView.delegate = self
fetchInitialPost()
}
func fetchInitialPost(){
Alamofire.request(MyURL, method: .get).responseJSON{
response in
switch response.result{
case .success(let result):
let json = JSON(result)
guard let feedArr = json["feed"].array else{
return
}
for post in feedArr {
if let post = post.dictionary,let feed = Post.init(dict: post){
self.posts.append(feed)
}
}
self.popTableView.reloadData()
break
case .failure(let error):
print(error)
}
}
}
func indicatorInfo(for pagerTabScripController : PagerTabStripViewController ) -> IndicatorInfo {
return IndicatorInfo (title : "Pop")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostTableCell", for: indexPath) as! PostTableCell
cell.posts = self.posts[indexPath.row]
return cell
}
}
I think I do all I should do in order to make it work already. But when I run the project I gives me this error, but I don't have any error in console. The app is just blank and this error below pops out.
So what cause this problem? And how to solve this?
A:
This usually happens when there is a problem when loading the Storyboard.
I think (this has happend to me multiple times) you maybe have User Defined Runtime Attributes on popTableView in your Storyboard. If there are any that can not be set, because popTableView does not have the respective property, the debugger will show the behavior that you are seeing.
You can check if there are any User Defined Runtime Attributes by selecting the table view in Interface Builder an checking the Identity Inspector.
Try deleting any attributes that might cause problems.
Alternatively you forgot to connect the @IBOutlet in your Storyboard. You can check how to do that in the official documentation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Synchronize 2 Select Boxes
I have two select boxes:
<select name="county" id="countyselect">
<option value="Dixie">Dixie</option>
<option value="Hernando">Hernando</option>
<option value="Holmes">Holmes</option>
<option value="Jackson">Jackson</option>
<option value="Liberty">Liberty</option>
<option value="Putnam">Putnam</option>
</select>
<select name="site" id="siteselect">
<option value="Florahome">Florahome</option>
<option value="Green Swamp">Green Swamp</option>
<option value="NE Jackson County">NE Jackson County</option>
<option value="N Holmes County">N Holmes County</option>
<option value="S Liberty County">S Liberty County</option>
<option value="Suwannee">Suwannee</option>
</select>
When one box is changed, the other needs to change to the corresponding index (i.e. if Dixie is selected in "county", Florahome should be selected in "site"). My attempt using jQuery is below but does not seem to work.
$('select#countyselect').change(function() {
var countySelector = $('select#countyselect').attr("selectedIndex");
$('select#siteselect').attr('selectedIndex', countySelector);
});
$('select#siteselect').change(function() {
var siteSelector = $('select#siteselect').attr("selectedIndex");
$('select#countyselect').attr('selectedIndex', siteSelector);
});
Any ideas?
A:
You want prop, not attr. Something like:
function matchUp(selected, toselect)
{
var idx = selected.prop('selectedIndex');
toselect.prop('selectedIndex', idx);
}
$('#countyselect').change(
function() {
matchUp($('#countyselect'), $('#siteselect'));
}
);
$('#siteselect').change(
function() {
matchUp($('#siteselect'), $('#countyselect'));
}
);
function matchUp(selected, toselect)
{
const idx = selected.prop('selectedIndex');
toselect.prop('selectedIndex', idx);
}
$('#countyselect').change(
function() {
matchUp($('#countyselect'), $('#siteselect'));
}
);
$('#siteselect').change(
function() {
matchUp($('#siteselect'), $('#countyselect'));
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="county" id="countyselect">
<option value="Dixie">Dixie</option>
<option value="Hernando">Hernando</option>
<option value="Holmes">Holmes</option>
<option value="Jackson">Jackson</option>
<option value="Liberty">Liberty</option>
<option value="Putnam">Putnam</option>
</select>
<select name="site" id="siteselect">
<option value="Florahome">Florahome</option>
<option value="Green Swamp">Green Swamp</option>
<option value="NE Jackson County">NE Jackson County</option>
<option value="N Holmes County">N Holmes County</option>
<option value="S Liberty County">S Liberty County</option>
<option value="Suwannee">Suwannee</option>
</select>
| {
"pile_set_name": "StackExchange"
} |
Q:
UWP App crash in release mode in Windows.UI.Xaml.dll
So, this had been 4th day of me hunting down this one bug.
I was working on my app and in a past 2 released of my app. I ended up submit app to Microsoft Store that crash on start up.
My project is built using Windows Template Studio with slightly modify and using Microsft UI Library (Microsoft.UI.Xaml) that released a few weeks ago. But the issue might not relate to it.
I was always testing my app in debug mode and everything went fine but whenever I build in release mode it is just crash on startup with this error:
(Unhandled exception at 0x6587AA49 (Windows.UI.Xaml.dll) in app.exe: 0xC0000005: Access violation reading location 0x00000000.)
I tried changing my app to open into other pages and it work just fine. But when I move to home page it is this error right here showed up. ^
Here is what's my homepage code look like
Basically, it is a navigation view from Microsoft.UI library. With sub pages.
As my app is loaded, I can see a text on the sub page, my guees the issue might be somewhere from this page
Sorry, if the issue seems too vague. But I can't narrow down to specific code line and post it here.
If you need to clone the project, here is the link: https://github.com/ray1997/JustRememberUWP/tree/LatestRelease
A:
NVM, I was found out on my MainPage, right when the page was loaded. I was navigated to the same pages multiple times and it cause the app to get a StackoverflowException and crash.
| {
"pile_set_name": "StackExchange"
} |
Q:
Uploading Sketches from Windows Command Line
The resources I've found regarding the Command Line interface seem to be out of date so I was hoping to find someone with experience using it. I'm currently running Arduino 1.5.6-r2 BETA on Windows 8.1 looking to upload code to an Arduino Leonardo.
I'm trying to create a script(Powershell) file that I can just use to upload code without user intervention. The actual upload part using Arduino CLI is just straight not working for me. If my understanding is correct I should have it already due to my version of the Arduino IDE but none of the functionality works so I'm doubting myself.
Source: https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc
This is the command I'm attempting to run from Windows Command Prompt:
C:\Program Files (x86)\Arduino\arduino.exe --board arduino:avr:leonardo --port COM3 --upload C:\Users\Dev\Documents\Arduino\myProject\myProject.ino
Any insight into what I'm missing would be very much appreciated!
EDIT: Additionally, if anyone could provide information regarding the build/upload process which could lead me to a solution from within C# that would be even more amazing.
A:
Turns out that the Ignoring Bad Library Name error that I had been receiving regardless of if I ran Arduino IDE through command line or standalone was the issue. For whatever reason it was blocking the script with a dialog that then failed the upload regardless of if I manually moved through the popup.
Final setup for those looking for this in the future:
Windows 8.1 x64 with Arduino IDE version 1.5.6-r2(I will revert to 1.0.5 and test with that, and report results) using a Leonardo board. Command is as follows:
Working Directory: C:\Program Files (x86)\Arduino
arduino --board arduino:avr:leonardo --port COM14 --upload C:\Users\Dev\Documents\Arduino\sketch_jun06a\sketch_jun06a.ino
EDIT: As promised, I attempted this with version 1.0.5-r2 and was unsuccessful. Potentially a 1.5.+ feature.
| {
"pile_set_name": "StackExchange"
} |
Q:
what is a multiplicative group in prime order p?
on pg. 378 section 2 (Overview) it says "We let G be a multiplicative group of prime order p , and g be a generator of G. We let e : G x G --> $G_T$" be a bilinear map.
If somebody could please break each piece of this into smaller parts I would really appreciate it. Here is my attempt:
G is a multiplicative group in order p. Since G is cyclic this means any member of G multiplied by any integer mod p yields identity (1).
g being the generator, means that you always start with g. So you can raise g to a power or you can multiply g by a random integer. But you always have to get 1 mod p for it to be a member of G.
Before looking at binlinear map, I thought I should first read what a linear map is. According to wikipedia, a linear map always yields the same subspace of the input subspaces. So bilinear I think you can end up with something that is not linear (like an elliptic curve?).
My understanding of all this is quite fuzzy and I would appreciate it if someone could explain these to me in simple English or easy-to-understand drawings.
A:
$G$ is not the group of integers mod $p$.
$G$ is a group, that is a set with a composition that obeys the group axioms.
it is multiplicative, that is we agree to use $\cdot$ (and not $+$, say) as symbol for the composition
it s of order $p$, that is its underlying set has $p$ elements
$g$ is a generator, which im plies that $G$ is cyclic
$e\colon G\times G\to G_T$ is bilinear, that is for each $a\in G$, the map $G\to G_T$, $x\mapsto e(a,x)$ is linear and $x\mapsto e(x,a)$ is also linear
| {
"pile_set_name": "StackExchange"
} |
Q:
How to produce a scatterplot in Julia-lang with labelled points?
Using Julia-lang, how can a scatterplot of two vectors be plotted with pyplots (or GR) to label each point with a specific string? Eg. each paired (x,y) takes on the index value they both share? Example from MATLAB: image example
A:
Do you mean with GR or PyPlot themselves, or through Plots.jl? I know Plots.jl best - with that you'd do scatter(x,y, series_annotations = text.(1:length(x), :bottom)) .
Unfortunately it currently plots very close to the points - :bottom means that the bottom of the text touches the point.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does urllib.parse.urlencode not change '_' into %5F?
I am writing POST request for game I am trying to make scripts for. For this post, I am using the common req = urllib.request.Request(url=url, data=params, headers=headers) First though, I have a dictionary of the data needed for the request, and I must encode it with params = urllib.parse.urlencode(OrderedDict[])
However, this gives me a string, but not the proper one! It will give me:
&x=_1&y_=2&_z_=3
But, the way the game encodes things, it should be:
&x=%5F1&y%5F=2&%5Fz%5F=3
So mine doesn't encode the underscores to be "%5F". How do I fix this? If I can, I have the params that the game uses (in url, pre-encoded for), would I be able to use that in the data field of the request?
A:
Underscores don't need to be encoded, because they are valid characters in URLs.
As per RFC 1738:
Unsafe:
Characters can be unsafe for a number of reasons. The space
character is unsafe because significant spaces may disappear and
insignificant spaces may be introduced when URLs are transcribed or
typeset or subjected to the treatment of word-processing programs.
The characters < and > are unsafe because they are used as the
delimiters around URLs in free text; the quote mark (") is used to
delimit URLs in some systems. The character # is unsafe and should
always be encoded because it is used in World Wide Web and in other
systems to delimit a URL from a fragment/anchor identifier that might
follow it. The character % is unsafe because it is used for
encodings of other characters. Other characters are unsafe because
gateways and other transport agents are known to sometimes modify
such characters. These characters are {, }, |, \, ^, ~,
[, ], and `.
All unsafe characters must always be encoded within a URL.
So the reason _ is not replaced by %5F is the same reason that a is not replaced by %61: it's just not necessary. Web servers don't (or shouldn't) care either way.
In case the web server you're trying to use does care (but please check first if that's the case), you'll have to do some manual work, as urllibs quoting does not support quoting _:
urllib.parse.quote(string, safe='/', encoding=None, errors=None)
Replace special characters in string using the %xx escape. Letters, digits, and the characters _.- are never quoted.
You can probably wrap quote() with your own function and pass that to urlencode(). Something like this (fully untested):
def extra_quote(*args, **kwargs):
quoted = urllib.pars.quote(*args, **kwargs)
return str.replace(quoted, '_', '%5F')
urllib.parse.urlencode(query, quote_via=extraquote)
| {
"pile_set_name": "StackExchange"
} |
Q:
Link 2 comboboxes to a single function and return its value
I have two comboboxes that I would like to control with a single function, but I'm struggling to understand how to get the values from whichever combobox calls the callback.
from Tkinter import *
import ttk
class App(Frame):
def __init__(self, parent):
self.parent = parent
self.value_of_combo = "X"
self.initUI()
def information(self, type):
combo_var = self.type.get()
print combo_var
def initUI(self):
# Label
self.configlbl = Label(self.parent, text="Description")
self.configlbl.pack(side=LEFT)
# Type
self.linear_value = StringVar()
self.linear = ttk.Combobox(self.parent, textvariable=self.linear_value)
self.linear.bind('<<ComboboxSelected>>', self.information('linear'))
self.linear.pack(side=LEFT)
self.linear['values'] = ('X', 'Y', 'Z')
# UTCN
self.utcn_value = StringVar()
self.utcn = ttk.Combobox(self.parent, textvariable=self.utcn_value)
self.utcn.bind('<<ComboboxSelected>>', self.information('utcn'))
self.utcn.pack(side=LEFT)
self.utcn['values'] = ('A', 'B', 'C')
if __name__ == '__main__':
root = Tk()
app = App(root)
root.mainloop()
This code in it's simplest form, where I am up to, and it is the information function which needs a few extra nuts and bolts.
A:
The event object that is automatically passed when a bound function is called contains the attribute widget, which is the widget that triggered the event. So you can bind both comboboxes' <<ComboboxSelected>> to trigger self.information (without parentheses) and define that as
def information(self, event):
combo_var = event.widget.get()
print combo_var
| {
"pile_set_name": "StackExchange"
} |
Q:
how can I measure distance between my current location and a given address?
I write an android app
And I get from the server a list of addresses.
How can I measure the distance between a mobile client and a given address?
I guess I first have to convert the address to coordinates? how would you suggest doing this?
A:
The first, essential step is to find the users Location. To do this, check out http://developer.android.com/guide/topics/location/strategies.html
For different strategies on how to do this.
You'll end up with a Location object of the users location.
The next step is to get the coordinates of the address. To do this, you will need to use the Geocoder class. Create a new instance of it, and use "getFromLocationName("address", 1).get(0)" to get a Location object which is the closest result to "address" (replace "address" with whatever address you have from the server).
You may need to play around with this to get the right result.
The final step is easy, you can use the "usersLocation.distanceTo(addressLocation)", with "usersLocation" and "addressLocation" being the location object for the user and the remotely obtained address respectively.
This will give you a float, which is the distance in metres.
| {
"pile_set_name": "StackExchange"
} |
Q:
Parsing a complicated CSV generated on election nights
I have a Python script which parses a complicated CSV generated on election nights. Each row of the CSV represents a race. As I loop through the races, I store the candidates for each race into a list called cnds. The other variable to note is called num_win, and it holds the number of people who will be elected for that particular race. Usually it's just 1, but in cases like school boards, it can be much higher.
For illustration purposes, here's some sample data we might process:
num_win = 6
cnds = [
{ 'cnd' : 'Christine Matthews', 'votes' : 200, 'winner': False },
{ 'cnd' : 'Dexter Holmes', 'votes' : 123, 'winner': False },
{ 'cnd' : 'Gerald Wheeler', 'votes' : 123, 'winner': False },
{ 'cnd' : 'Timothy Hunter', 'votes' : 100, 'winner': False },
{ 'cnd' : 'Sheila Murray', 'votes' : 94, 'winner': False },
{ 'cnd' : 'Elisa Banks', 'votes' : 88, 'winner': False },
{ 'cnd' : 'John Park', 'votes' : 88, 'winner': False },
{ 'cnd' : 'Guadalupe Bates', 'votes' : 76, 'winner': False },
{ 'cnd' : 'Lynne Austin', 'votes' : 66, 'winner': False }
]
First attempt:
My initial version was pretty straightforward. Make a copy of cnds, sort it in order of vote count, and limit to all but the num_win number of candidates. These are the winners. Then loop through cnds and mark the winners.
winners = sorted(cnds, key=lambda k: int(k['votes']), reverse=True)[0:num_win]
for cnd in cnds:
for winner in winners:
if cnd['cnd'] == winner['cnd']:
cnd['winner'] = True
This works great -- except I realized later that it doesn't account for ties.
Since this script is for election night when the results are unofficial, I only want to mark as winners the candidates I am sure are winners. In the data above, the clear winners would be: Christine Matthews, Dexter Holmes, Gerald Wheeler, Timothy Hunter, and Sheila Murray. There is a tie for the sixth spot. Depending on the type of race, etc, it might be settled later by a runoff or some other mechanism. So, on election night, I simply wouldn't mark anyone else after those 5 as being a winner.
Here's the new code I've written, which accounts for tie situations:
# Make list of unique vote totals, with number of candidates who had those vote totals
# This code uses collections.Counter to make the list of uniques.
# http://stackoverflow.com/a/15816111/566307
uniques = Counter(cnd['votes'] for cnd in cnds).iteritems()
# Now convert the Counter() output into a sorted list of tuples.
uniquesCount = sorted( uniques, reverse=True )[0:num_win]
# How many candidates are there in this list?
# http://stackoverflow.com/a/14180875/566307
cndsInUniques = map(sum,zip(*uniquesCount))[1]
# There's too many candidates. Must be one or more ties
if cndsInUniques > num_win:
adjusted_num_win = num_win
# We need to remove items from the uniques list until we get the
# num of candidates below or equal to the num_win threshold.
while len(uniquesCount) > 0:
# delete last item
del uniquesCount[-1]
cndsInUniques = map(sum,zip(*uniquesCount))[1]
if cndsInUniques <= num_win:
adjusted_num_win = cndsInUniques
break
winners = sorted(cnds, key=lambda k: int(k['votes']), reverse=True)[0:adjusted_num_win]
# Right number of candidates means no ties. Proceed as normal.
else:
# Make list of candidates, sorted by vote totals
winners = sorted(cnds, key=lambda k: int(k['votes']), reverse=True)[0:num_win]
# loop through all candidates and mark the ones who are winners
for cnd in cnds:
for winner in winners:
if cnd['cnd'] == winner['cnd']:
cnd['winner'] = True
This code is working for me, but I feel like it's a lot of work to reach the adjusted_num_win number that I need. Can anyone suggest an alternative, or ways I might simplify this?
A:
# Make one more candidate than necessary into winners list
winners = sorted(cnds, key=lambda k: int(k['votes'], reverse=True)[0:num_win + 1]
# A tie to be resolved happens when two last candidates have equal vote count.
# if so, go backwards removing everybody with the same vote count.
# Binary search would work faster, of course. If a standard library
# provides something similar to std::lower_bound from STL - its even better.
index = num_win
while index > 0 and winners[index - 1]['votes'] == winners[num_win]['votes']:
index -= 1
# Finally, adjust your list
winners = winners[0:index]
PS: One more thing to mention. The final nested loop is not really the best approach. You should decorate the original list with the sequential numbers (or use some other method to remember initial ordering), sort it, mark the winners which are at the beginning of the list, and sort it by sequence numbers back to the original state.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL: Assigning sequence numbers
I would like to assign a sequence number as I add a group of rows to a table. How do I do this? I thought about using COUNT() or ROWID but I cannot figure out how.
Let's say I have a table with three columns: PlayListID, TuneID and SequenceNum
I want to create a new tune playlist, so I'm going to add a bunch of TuneID values for a PlayListID of 2 for example. The TuneIDs are ordered by artist, album and track number. Here's what I have at present:
SELECT TuneID From Tunes
WHERE ArtistID=2
ORDER BY AlbumID, TrackNum
I guess what I am trying to do is preserve the ordering information - ensure that when all tunes for PlayListID=2 are retrieved, they have a column that indicates their order. TrackNum cannot be used as their may be a number of albums and I may write another query to retrieve them in some other order as well.
So, how would I modify the below command to add an ascending column (sequence) value for each row inserted?
INSERT INTO Playlist (Name,Seq)
SELECT Name, ??? As Seq FROM Tunes
WHERE ArtistID=2
ORDER BY AlbumID, TrackNum
I'm using SQLite. I don't want to use autoincrement because I'd like the Seq number to be 1 for each PlaylistID.
A:
The SQL genius at work solved my problem. Here's the solution - creating a temporary table which has an auto incrementing column..
CREATE TEMP TABLE New_Playlist (Seq INTEGER PRIMARY KEY AUTOINCREMENT, TuneID INTEGER);
INSERT INTO New_Playlist (TuneID)
SELECT TuneID FROM Tunes
WHERE ArtistID=2
ORDER BY AlbumID, Track;
INSERT INTO Playlist (TuneID, Name, Seq)
SELECT t.TuneID, t.Name, np.Seq
FROM New_Playlist np JOIN Tunes t ON t.TuneID = np.TuneID;
DROP TABLE New_Playlist;
| {
"pile_set_name": "StackExchange"
} |
Q:
Expected value of a product of the Pauli matrices in different bases
I'm trying to reproduce the results of this article https://arxiv.org/abs/1801.03897, using Qiskit and Xanadu PennyLane.
Particularly, this part with expected values of the Pauli operators:
For Ansatz circuit from the mentioned article
I can get the same results for $\langle Z_0 \rangle$ and $\langle Z_1 \rangle$ but not for $\langle X_0X_1 \rangle$, $\langle Y_0Y_1 \rangle$. I calculate expected values in the following way:
$$\langle Z_0 \rangle = P(q_0=0)-P(q_0=1),$$
$$\langle Z_1 \rangle = P(q_0=0)-P(q_0=1).$$
And for a product of the Pauli matrices:
$$\langle X_0X_1 \rangle = [P(q_0=0)-P(q_0=1)]*[P(q_1=0)-P(q_1=1)],$$
$$\langle Y_0Y_1 \rangle = [P(q_0=0)-P(q_0=1)]*[P(q_1=0)-P(q_1=1)],$$
where $P(q_0=0)$ is probability of getting qubit 0 in state $|0\rangle$ and $P(q_0=1)$ is probability of getting qubit 0 in state $|1\rangle$.
In Qiskit for $\langle X_0X_1 \rangle$, $\langle Y_0Y_1 \rangle$ I use pre-measurement single-qubit rotations $H$ and $R_x(-\pi/2)$ respectively.
Help me understand, where I could make a mistake?
A:
Your expressions for $\langle X_0X_1 \rangle$ and $\langle Y_0Y_1 \rangle$ are correct under the assumption that the two qubits are independently random. In the case that they are correlated, these expressions will not yield the right answer.
This is because you have to think of $X_0X_1$, for example, as an operator in its own right, rather than just a combination of $X_0$ and $X_1$. This combined operator has eigenvalue $+1$ for any superposition of $|++\rangle$ and $|--\rangle$, and eigenvalue $-1$ for any superposition of $|+-\rangle$ and $|-+\rangle$. The expectation value is therefore
$$\langle X_0X_1 \rangle = P(q_0=0, q_1=0)+P(q_0=1, q_1=1)-P(q_0=0, q_1=1)-P(q_0=1, q_1=0).$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Effective algorithm for matching complex name variations using Java
I have to match a number of store names and I am having a difficult time getting Levenshtein and SoundEx to yield acceptable results given my data.
Here are a few examples of what I'm dealing with:
The Home Depot
Office Depot
Apple store
Apple
Walgreens
Walgreens Denver
Quiznos
Quiznos Sandwich Restaurants
So given "Quiznos Sandwich Restaurants", for example, I'd want to match it to "Quiznos"... "Walgreens Denver" to "Walgreens". I have a whole list of these store names.
Any help would be great.
A:
maybe try and narrow down the search field by "canonicalizing" a bit?
remove fluff like "the" and "store" from the query, run it through a dictionary to fix obvious mistakes and typos?, identifying and removing obvious location references (like "denver" above) could also help.
edit: to expand a bit (and name-drop a few other CS topics ;-) ) - if youre really looking at solving the "best" (most complex) way, you'd need to take your input string, run it through some parts-of-speech tagger (see helpful question here Java Stanford NLP: Part of Speech labels?) and then use the tagging data to remove connecting words (for example - "mcdonalnds around manhatten" - around could be identified and removed).
maybe it'll even help identify plural forms (dont know, never tried) so things like "home depots in washington" could be canonicalized to "home depot"
| {
"pile_set_name": "StackExchange"
} |
Q:
"Cookie Clicker Alpha" solution
I am trying to learn Clojure for some time. In my experience, it has been rather too easy to produce write-only code.
Here is a solution to a simple problem with very little essential complexity. Input and output formats are extremely simple, too. Which means all complexity in it must be accidental. How to improve its legibility, intelligibility?
Is the decomposition of the problem into functions all right?
Also other specific problems:
How to input/output numbers? Is there any benefit to use read-string instead of Double/parseDouble? How to format floating point numbers to fixed precision without messing with the default locale?
How to avoid the explicit loop/recur, which is currently a translation of a while loop?
Are there definitions that should/shouldn't have bee private/dynamic?
Problem
You start with 0 cookies. You gain cookies at a rate
of 2 cookies per second [...]. Any time you
have at least C cookies, you can buy a cookie farm. Every time you buy
a cookie farm, it costs you C cookies and gives you an extra F cookies
per second.
Once you have X cookies that you haven't spent on farms, you win!
Figure out how long it will take you to win if you use the best
possible strategy.
(ns cookie-clicker
(:use [clojure.string :only [split]])
(:require [clojure.java.io :as io]
[clojure.test :refer :all]))
;;See http://code.google.com/codejam/contest/2974486/dashboard#s=p1
(defn parse-double [s] (java.lang.Double/parseDouble s))
(defn parse-row [line]
(map parse-double (split line #"\s+")))
(defn parse-test-cases [rdr]
(->> rdr
line-seq
rest
(map parse-row)))
(def initial-rate 2.0)
(defn min-time [c f x]
(loop [n 0 ; no of factories used
tc 0 ; time cost of factories built
r initial-rate ; cookie production rate
t (/ x r)] ; total time
(let [n2 (inc n)
tc2 (+ tc (/ c r))
r2 (+ r f)
t2 (+ tc2 (/ x r2))]
(if (> t2 t)
t
(recur n2 tc2 r2 t2)))))
(java.util.Locale/setDefault (java.util.Locale/US))
(defn ans [n t]
(str "Case #" n ": " (format "%.7f" t)))
(defn answers [test-cases]
(map #(ans %1 (apply min-time %2))
(rest (range))
test-cases))
(defn spit-answers [in-file]
(with-open [rdr (io/reader in-file)]
(doseq [answer (answers (parse-test-cases rdr))]
(println answer))))
(defn solve [in-file out-file]
(with-open [w (io/writer out-file :append false)]
(binding [*out* w]
(spit-answers in-file))))
(def ^:dynamic *tolerance* 1e-6)
(defn- within-tolerance [expected actual]
(< (java.lang.Math/abs (- expected actual))
*tolerance*))
(deftest case-3
(is (within-tolerance
63.9680013
(min-time 30.50000 3.14159 1999.19990))))
(defn -main []
(solve "resources/cookie_clicker/B-large-practice.in"
"resources/cookie_clicker/B-large-practice.out"))
A:
I have to admit, the actual "solving the problem" component of this is a little over my head. But, I thought I'd try to answer your questions and give you some style/structure feedback, for what it's worth :)
You can simplify your ns declaration like this:
(ns cookie-clicker
(:require [clojure.string :refer (split)]
[clojure.java.io :as io]
[clojure.test :refer :all]))
(:require foo :refer (bar) does the same thing as :use foo :only (bar), and is generally considered preferable, especially as an alternative to having both :use and :require in your ns declaration)
I think Double/parseDouble is a good approach to parsing doubles in string form. Integer/parseInt is usually my go-to for doing the same with integers in string form. This is just a hypothesis, but Double/parseDouble might be faster and/or more accurate than read-string because it's optimized for doubles.
FYI, you can leave out the java.lang. and just call it as Double/parseDouble in your code. In light of that, you might consider getting rid of your parse-double function altogether and just using Double/parseDouble whenever you need it. The only thing is that Java methods aren't first-class in Clojure, so you would need to do things like this if you go that route:
(defn parse-row [line]
(map #(Double/parseDouble %) (split line #"\s+")))
(Personally, I still like that better, but you might prefer to keep it wrapped in a function parse-double like you have it. It's up to you!)
I think needing to mess with the locale might be a locale-specific problem... I tried playing around with (format "%.7f" ... without changing my locale and it worked as expected. Granted, I'm in the US :)
I think the legibility issues you're seeing might be related to having too many functions. You might consider condensing and renaming things and see if you like that better. I would re-structure your program so that you parse the data into the data structure at the top, something like this:
(defn parse-test-cases [in-file]
(with-open [rdr (io/reader in-file)]
(let [rows (rest (line-seq rdr))]
(map (fn [row]
(map #(Double/parseDouble %) (split row #"\s+")))
rows))))
(I condensed your functions parse-row, parse-test-cases and half of spit-answers into the function above)
Then define the functions that "do all the work" like min-time, and then, at the end:
(defn spit-answers [answers out-file]
(with-open [w (io/writer out-file :append false)]
(.write w (clojure.string/join "\n" answers)))
(def -main []
(let [in "resources/cookie_clicker/B-large-practice.in"
out "resources/cookie_clicker/B-large-practice.out"
test-cases (parse-test-cases in)
answers (map-indexed (fn [i [c f x]]
(format "Case #%d: %.7f" (inc i) (min-time c f x)))
test-cases)]
(spit-answers answers out)))
I came up with a few ideas above:
In your answers function you use (map ... (rest (range)) (test-cases)) in order to number each case, starting from 1. A simpler way to do this is with map-indexed. I used (inc i) for the case numbers, since the index numbering starts at 0.
I condensed (str "Case #" n ": " (format "%.7f" t))) into a single call to format.
I used destructuring over the arguments to the map-indexed function to represent each case as c f x -- that way it's clearer that each test case consists of those three values, and you can represent the calculation as (min-time c f x) instead of (apply min-time test-case).
As for your min-time function, I don't think loop/recur is necessarily a bad thing, and I often tend to rely on it in complicated situations where you're doing more involved work on each iteration, checking conditions, etc. I think it's OK to use it here. But if you want to go a more functional route, you could consider writing a step function and creating a lazy sequence of game states using iterate, like so:
(note: I'm writing step as a letfn binding so that it can use arbitrary values of c, f and x that you feed into a higher-order function that I'm calling step-seq -- this HOF takes values for c, f and x and generates a lazy sequence of game states or "steps.")
(defn step-seq [c f x]
(letfn [(step [{:keys [factories time-cost cookie-rate total-time result]}]
(let [new-time-cost (+ time-cost (/ c cookie-rate))
new-cookie-rate (+ cookie-rate f)
new-total-time (+ new-time-cost (/ x new-cookie-rate))]
{:factories (inc factories)
:time-cost new-time-cost
:cookie-rate new-cookie-rate
:total-time new-total-time
:result (when (> new-total-time total-time) total-time)}))]
(iterate step {:factories 0, :time-cost 0, :cookie-rate 2.0,
:total-time (/ x 2.0), :result nil})))
Now, finding the solution is as simple as grabbing the :result value from the first step that has one:
(defn min-step [c f x]
(some :result (step-seq c f x)))
| {
"pile_set_name": "StackExchange"
} |
Q:
Access second argument in getopts option using bash
Already asked question related this few days ago here
But this time the condition different,Having following bash script using getopts
#!/bin/bash
ipaddr=""
sysip=""
msgType=""
sshTimeout=""
bulbIndex=""
bulbstate=""
while getopts ":ht:d:A:r:s:m:" OPTION
do
case $OPTION in
h)
usage $LINENO
;;
t)
let "t_count += 1"
ipaddr="${OPTARG}"
echo -e $ipaddr
;;
d)
let "d_count += 1"
echo "Not supported"
exit 0
;;
A)
let "A_count += 1"
bulbIndex="${OPTARG}" # After -A option firsr argument is bulb index and second is state off/on
bulbstate=$3
printf "Set %s state on %s bulb\n" $bulbstate $bulbIndex
;;
r)
let "r_count += 1"
sysip="${OPTARG}"
echo -e $sysip
;;
m)
let "m_count += 1" #message type 1:text 2:number 3:Text&number
msgType="${OPTARG}"
echo -e $msgType
;;
s)
let "s_count += 1"
sshTimeout="${OPTARG}"
echo -e $sshTimeout
;;
?)
echo -e "wrong command sysntax"
exit 0
;;
esac
done
Above script working fine for all options except -A option.What is wrong with it let you know from below script execution steps
$ ./sample.bash -A 3 OFF
Set OFF state on 3 bulb
This is expected output but when i give multiple option then it behave wrong like
$ ./sample.bash -t 192.168.0.1 -r 192.169.0.33 -A 3 OFF
192.168.0.1
192.169.0.33
Set -r state on 3 bulb
Here i expect OFF instead -r and obviously it gives this output because this time it not $3 but it $7 but my problem is how i inform to script it's now $7 not $3.
And
$ ./sample.bash -t 192.168.0.1 -A 3 OFF -r 192.169.0.33 -m 1
192.168.0.1
Set -A state on 3 bulb
this time after -A all options are discarded and again -A instead OFF
How can i correctly access both arguments after -A option in any sequence of -A options?
Also any one have query regarding question let me know and frankly speaking whatever solution of it means very simple or hard but currently i don't know.
A:
Finally after playing with OPTIND have found the way to get it.Modified the -A option as follows in getopts
A)
let "A_count += 1"
let "index += $OPTIND" # where initial value of index is 2
bulbstate=${!index}
bulbIndex="${OPTARG}"
printf "Set %s state on %s bulb\n" $bulbstate $bulbIndex
((OPTIND++))
;;
| {
"pile_set_name": "StackExchange"
} |
Q:
c++ работа с файлами
Когда вывожу в файл данные (язык - c++), через fstream, они появляется в нём только после того, как я этот файл закрою (то есть, если ofstream file, то информация в нём появляется только после того, как file.close()). Как сделать так, чтобы информация в нём обновлялась автоматически после каждого вывода, т. к. так удобнее выполнять пошаговую отладку?
A:
Вызвать file.flush() и сбросить буфер.
Также буфер можно сбросить, отправив в поток std::flush.
file << std:flush;
std::endl кроме вставки новой строки также вызывает flush
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL: Importing csv into table with quotation marks
I have a csv where each row starts with quotation marks and ends with them too. How do I ignore the quotations at the start and end of the row when loading the csv into a table?
LOAD DATA LOCAL INFILE '/path/data.csv'
INTO TABLE test1
FIELDS TERMINATED BY ';'
LINES TERMINATED BY '\"\n'
IGNORE 1 ROWS;
I have tried
OPTIONALLY ENCLOSED BY '"'
but this refers to each specific field and not the entire row.
A:
As commented by Shadow and Barmar, the answer lies in the documentation :
If all the input lines have a common prefix that you want to ignore, you can use LINES STARTING BY 'prefix_string' to skip the prefix and anything before it. If a line does not include the prefix, the entire line is skipped. [...] The FIELDS TERMINATED BY, LINES STARTING BY, and LINES TERMINATED BY values can be more than one character.
Hence, use :
LOAD DATA LOCAL INFILE '/path/data.csv'
INTO TABLE test1
FIELDS TERMINATED BY ';'
LINES STARTING BY '"'
LINES TERMINATED BY '"\n'
IGNORE 1 ROWS;
| {
"pile_set_name": "StackExchange"
} |
Q:
Group Edition - API is not enabled/ ForcePad App
I have a Group Edition account. I downloaded the ForcePad app from App Store (it has been pulled down now but was available till some time back earlier) and it works perfectly on my org. However, if I build it from source (from the Github repo) and try to run it, I get the "API is not enabled" error on login. FWIW, I created a Connected App with full permissions on my org and I changed the consumer key and secret values in ForcePad app source code while building it.
A) I can't see the option to enable API on my org. Is it even possible to have API enabled on Group edition org?
B) If yes, then how?
C) If not, how does the ForcePad app work on my org - from the code, I can see it uses API calls.
I've been pulling my hair off trying to find how the App Store build of ForcePad works on my Group Edition org but why it prompts for API not enabled when I build it from source. Any expert guidance would be much appreciated.
A:
I wrote ForcePad.
Check out item 3 under the getting started section:
(Optional) ForcePad connects to environments that are not otherwise
API-enabled, like GE and PE orgs, by using a partner token. If you
have a Salesforce partner token, paste it into RootViewController.h
under PartnerTokenId.
That said, getting a partner token is a little trickier! You'd be best off checking with your account rep.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is my in-class decorator not Pythonic enough or PyCharm not smart enough in lint warning?
I want to define a decorator within a class. I don't want to define it as a separated, independent function, for this decorator is specifically for this class and I want to keep the correlated methods together.
The purpose of this decorator is to check some prerequisites, especially the database connection, SSH connection, etc., which are held by member variables, are still available. If not, the decorated function won't be called and some error reporting and clean-up works will be done.
I made the following testing class to test if it works, and the code did work well. But I found that PyCharm shows warnings to this piece of code. So I wonder, if it means that my code is not Pythonic, or PyCharm is not smart enough and gave this warning by mistake?
If my code is is not Pythonic, how to change?
If it is PyCharm's mistake, how shall I and my team configure PyCharm to let it specifically ignore this kind of warning while keep most other lint check?
class TestClass:
def __init__(self):
self.flag = True
def dec(func):
def wrapper(self, *args, **kwargs):
if not self.flag:
print("Won't run!")
return empty_fun(self, *args, **kwargs)
return func(self, *args, **kwargs)
def empty_fun(*args, **kwargs):
return None
return wrapper
@dec
def foo(self):
print("foo")
@dec
def bar(self, msg, more, *args, **kwargs):
print("message: %s" % msg)
print("more %s:" % more)
for item in args:
print("other item: %s" % item)
name = kwargs.get('name')
age = kwargs.get('age')
print('name: %s' % name)
print('age: %s' % age)
def main():
t = TestClass()
t.foo()
print('-'*10)
t.bar("abc", 'def', 'hij', 'klm', name='Tom', age=20)
if __name__ == '__main__':
main()
Here is the lint warning reported by PyCharm:
A:
Your code is technically correct (in that it will work as expected), with the caveat that dec will become a method of TestClass and will break if invoked as such. You should at least make it a staticmethod to avoid this.
wrt/ pythonicity, it IS indeed unpythonic to make this decorator part of the class when it's not needed. The fact it only applies to this class is not a reason to make it a member of the class, and even less to make it part of the public API.
You can probably add linter hints in comments to silence it, but I'd personnally just extract this decorator from the class, make it private, and document that it's only supposed to be used with this class.
As as side note: I assume your empty_func is a placeholder for the "error reporting and clean-up work" - else it's just plain useless -, but does it really need to be defined in the decorator?
| {
"pile_set_name": "StackExchange"
} |
Q:
How to call an Oracle function with a Ref Cursor as Out-parameter from C#?
I'm using a product that provides a database API based on Oracle functions and I'm able to call functions via ODP.NET in general. However, I can't figure out, how to call a function that includes a Ref Cursor as Out-parameter. All the samples I found so far either call a procedure with Out-parameter or a function with the Ref Cursor as return value. I tried to define the parameters similiarly, but keep getting the error that the wrong number or type of parameters is supplied.
Here is the function header (obviously obfuscated):
FUNCTION GetXYZ(
uniqueId IN somepackage.Number_Type,
resultItems OUT somepackage.Ref_Type)
RETURN somepackage.Error_Type;
These are the type definitions in "somepackage":
SUBTYPE Number_Type IS NUMBER(13);
TYPE Ref_Type IS REF CURSOR;
SUBTYPE Error_Type IS NUMBER;
And this is the code that I have tried:
string sql = "otherpackage.GetXYZ";
var getXYZCmd = OracleCommand oracleConnection.CreateCommand(sql);
getXYZCmd.CommandType = CommandType.StoredProcedure;
getXYZCmd.Parameters.Add("uniqueId", OracleDbType.Int32).Value = uniqueExplosionId;
getXYZCmd.Parameters.Add("resultItems", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
getXYZCmd.Parameters.Add("return_value", OracleDbType.Int32).Direction = ParameterDirection.ReturnValue;
The I tried the following different ways to call the function (of course only one at a time):
var result = getXYZCmd.ExecuteNonQuery();
var reader = getXYZCmd.ExecuteReader();
var scalarResult = getXYZCmd.ExecuteScalar();
But each of them fails with the error message:
Oracle.DataAccess.Client.OracleException: ORA-06550: line 1, column 15:
PLS-00306: wrong number or types of arguments in call to 'GETXYZ'
ORA-06550: line 1, column 15:
PLS-00306: wrong number or types of arguments in call to 'GETXYZ'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored.
So is it generally possible to call a function with a Ref Cursor as Out-parameter from C# with ODP.NET? I can call a function with the same structure with a Varchar2-Out-parameter instead of the Ref Cursor without problems...
Btw, I'm using ODP.NET version 2.112.2.0 from C#.NET 3.5 in Visual Studio 2008.
Thanks in advance for your help!
A:
You sure can. There are a few gotchas to be wary of but here is a test case
create or replace function testodpRefCursor(
uniqueId IN NUMBER
,resultItems OUT NOCOPY SYS_REFCURSOR) RETURN NUMBER
IS
BEGIN
OPEN resultItems for select level from dual connect by level < uniqueId ;
return 1;
END testodpRefCursor;
I have found that
functions likes to have the
ReturnValue as THE FIRST param
in the collection
BindByName is by default FALSE, so it defaults to BIND BY POSITION
Otherwise it is quite straight forward:
OracleCommand cmd = new OracleCommand("TESTODPREFCURSOR", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.BindByName = true;
// Bind
OracleParameter oparam = cmd.Parameters.Add("ReturnValue", OracleDbType.Int64);
oparam.Direction = ParameterDirection.ReturnValue ;
OracleParameter oparam0 = cmd.Parameters.Add("uniqueId", OracleDbType.Int64);
oparam0.Value = 5 ;
oparam0.Direction = ParameterDirection.Input;
OracleParameter oparam1 = cmd.Parameters.Add("resultItems", OracleDbType.RefCursor);
oparam1.Direction = ParameterDirection.Output;
// Execute command
OracleDataReader reader;
try
{
reader = cmd.ExecuteReader();
while(reader.Read() ){
Console.WriteLine("level: {0}", reader.GetDecimal(0));
}
} ...
Now for more samples go to your Oracle Home directory and look @ the Ref cursor samples in ODP.NET
for instance:
%oracle client home%\odp.net\samples\4\RefCursor
hth
| {
"pile_set_name": "StackExchange"
} |
Q:
need to filter data in mysql with data array
I have attached my data and need result, I need to filter data from the array list. I have show "2" data result.
How can I get my output in mysql data?
A:
You can use LIKE to do it
SELECT t.* FROM yourtable t
WHERE t.attr LIKE CONCAT('2,%')
OR t.attr LIKE CONCAT('%,2')
OR t.attr LIKE CONCAT('%,2,%')
Test data
CREATE TABLE `system_users` (
`id` varchar(32) NOT NULL,
`name` varchar(32) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `system_users`(`id`,`name`)
values
('1','1,5,3,12'),
('2','1,2,3'),
('3','1,12,13'),
('4','1,5,2,10,12'),
('5','2,3,4'),
('6','5,4,3,2');
Working query:
SELECT * FROM system_users u
WHERE u.name LIKE CONCAT('2,%')
OR u.name LIKE CONCAT('%,2')
OR u.name LIKE CONCAT('%,2,%');
Output result:
+----+-------------+
| id | name |
+----+-------------+
| 2 | 1,2,3 |
| 4 | 1,5,2,10,12 |
| 5 | 2,3,4 |
| 6 | 5,4,3,2 |
+----+-------------+
Also,as Praveen S mentioned,FIND_IN_SET() also works for you,it's more simple and elegant then LIKE
| {
"pile_set_name": "StackExchange"
} |
Q:
xo lint error: `document` is not defined
I've been a long time user of Standard, and now that I'm working on a new project, I've been asked to start writing semicolons.
I'm trying to use both xo, Babel and React, but I keep getting an error when I try to lint my code:
document is not defined. no-undef
I've tried adding an env option to the xo field in my package.json file, but no success.
My xo config:
"xo": {
"esnext": true,
"extends": "xo-react",
"space": true,
"rules": {
"react/jsx-space-before-closing": 0
}
}
A:
It is cumbersome to specify linting options such as /** global document **/ and edit a configuration file every time you use a global.
This error can be suppressed by using --env=browser option:
xo --env=browser [<file|glob> ...]
Note: Same problem comes with Node.js, where the linter will complain that require and friends are not defined. The switch has to change to --env=node in that case.
However, XO defaults the env to node, therefore this will not be a problem in most cases. You will need multiple environments if your project contains both client and server files. in that case, --env switch can be set multiple times:
xo --env=browser --env=node [<file|glob> ...]
| {
"pile_set_name": "StackExchange"
} |
Q:
CATransaction (still) Not Animating
I have a problem very similar to this one :
CATransaction Not Animating
I'm just trying to animate a view layer using CATransaction. My problem is that the transform is applied to the view immediatly.
I tried to perform the animation using performSelector:withObject:afterDelay: without success.
Here is my code :
- (void)viewDidLoad {
[super viewDidLoad];
view = [[[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)] autorelease];
view.backgroundColor = [UIColor blackColor];
[self.view addSubview:view];
[self performSelector:@selector(animateView) withObject:nil afterDelay:0.1];
}
-(void) animateView {
[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:3.0f] forKey:kCATransactionAnimationDuration];
CALayer *layer = view.layer;
layer.position = CGPointMake(20,
300);
CATransform3D transform = CATransform3DMakeScale(2.0f, 2.0f, 1.0f);
transform = CATransform3DRotate(transform, acos(-1.0f)*1.5f, 1.5f, 1.5f, 1.5f);
layer.transform = transform;
[CATransaction commit];
}
Does anybody knows what is going wrong ?
Thanks, Vincent.
A:
when animating a view's backing layer, you need to be inside a UIView animation block, not just a CATransaction:
[UIView beginAnimations:nil context:NULL];
// ... your animation code
[UIView commitAnimations];
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding the ResourceExhaustedError: OOM when allocating tensor with shape
I'm trying to implement a skip thought model using tensorflow and a current version is placed here.
Currently I using one GPU of my machine (total 2 GPUs) and the GPU info is
2017-09-06 11:29:32.657299: I tensorflow/core/common_runtime/gpu/gpu_device.cc:940] Found device 0 with properties:
name: GeForce GTX 1080 Ti
major: 6 minor: 1 memoryClockRate (GHz) 1.683
pciBusID 0000:02:00.0
Total memory: 10.91GiB
Free memory: 10.75GiB
However, I got OOM when I'm trying to feed data to the model. I try to debug as follow:
I use the following snippet right after I run sess.run(tf.global_variables_initializer())
logger.info('Total: {} params'.format(
np.sum([
np.prod(v.get_shape().as_list())
for v in tf.trainable_variables()
])))
and got 2017-09-06 11:29:51,333 INFO main main.py:127 - Total: 62968629 params, roughly about 240Mb if all using tf.float32. The output of tf.global_variables is
[<tf.Variable 'embedding/embedding_matrix:0' shape=(155229, 200) dtype=float32_ref>,
<tf.Variable 'encoder/rnn/gru_cell/gates/kernel:0' shape=(400, 400) dtype=float32_ref>,
<tf.Variable 'encoder/rnn/gru_cell/gates/bias:0' shape=(400,) dtype=float32_ref>,
<tf.Variable 'encoder/rnn/gru_cell/candidate/kernel:0' shape=(400, 200) dtype=float32_ref>,
<tf.Variable 'encoder/rnn/gru_cell/candidate/bias:0' shape=(200,) dtype=float32_ref>,
<tf.Variable 'decoder/weights:0' shape=(200, 155229) dtype=float32_ref>,
<tf.Variable 'decoder/biases:0' shape=(155229,) dtype=float32_ref>,
<tf.Variable 'decoder/previous_decoder/rnn/gru_cell/gates/kernel:0' shape=(400, 400) dtype=float32_ref>,
<tf.Variable 'decoder/previous_decoder/rnn/gru_cell/gates/bias:0' shape=(400,) dtype=float32_ref>,
<tf.Variable 'decoder/previous_decoder/rnn/gru_cell/candidate/kernel:0' shape=(400, 200) dtype=float32_ref>,
<tf.Variable 'decoder/previous_decoder/rnn/gru_cell/candidate/bias:0' shape=(200,) dtype=float32_ref>,
<tf.Variable 'decoder/next_decoder/rnn/gru_cell/gates/kernel:0' shape=(400, 400) dtype=float32_ref>,
<tf.Variable 'decoder/next_decoder/rnn/gru_cell/gates/bias:0' shape=(400,) dtype=float32_ref>,
<tf.Variable 'decoder/next_decoder/rnn/gru_cell/candidate/kernel:0' shape=(400, 200) dtype=float32_ref>,
<tf.Variable 'decoder/next_decoder/rnn/gru_cell/candidate/bias:0' shape=(200,) dtype=float32_ref>,
<tf.Variable 'global_step:0' shape=() dtype=int32_ref>]
In my training phrase, I have a data array whose shape is (164652, 3, 30), namely sample_size x 3 x time_step, the 3 here means the previous sentence, current sentence and next sentence. The size of this training data is about 57Mb and is stored in a loader. Then I use write a generator function to get the sentences, looks like
def iter_batches(self, batch_size=128, time_major=True, shuffle=True):
num_samples = len(self._sentences)
if shuffle:
samples = self._sentences[np.random.permutation(num_samples)]
else:
samples = self._sentences
batch_start = 0
while batch_start < num_samples:
batch = samples[batch_start:batch_start + batch_size]
lens = (batch != self._vocab[self._vocab.pad_token]).sum(axis=2)
y, x, z = batch[:, 0, :], batch[:, 1, :], batch[:, 2, :]
if time_major:
yield (y.T, lens[:, 0]), (x.T, lens[:, 1]), (z.T, lens[:, 2])
else:
yield (y, lens[:, 0]), (x, lens[:, 1]), (z, lens[:, 2])
batch_start += batch_size
The training loop looks like
for epoch in num_epochs:
batches = loader.iter_batches(batch_size=args.batch_size)
try:
(y, y_lens), (x, x_lens), (z, z_lens) = next(batches)
_, summaries, loss_val = sess.run(
[train_op, train_summary_op, st.loss],
feed_dict={
st.inputs: x,
st.sequence_length: x_lens,
st.previous_targets: y,
st.previous_target_lengths: y_lens,
st.next_targets: z,
st.next_target_lengths: z_lens
})
except StopIteraton:
...
Then I got a OOM. If I comment out the whole try body (no to feed data), the script run just fine.
I have no idea why I got OOM in such a small data scale. Using nvidia-smi I always got
Wed Sep 6 12:03:37 2017
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.59 Driver Version: 384.59 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
| 0 GeForce GTX 108... Off | 00000000:02:00.0 Off | N/A |
| 0% 44C P2 60W / 275W | 10623MiB / 11172MiB | 0% Default |
+-------------------------------+----------------------+----------------------+
| 1 GeForce GTX 108... Off | 00000000:03:00.0 Off | N/A |
| 0% 43C P2 62W / 275W | 10621MiB / 11171MiB | 0% Default |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes: GPU Memory |
| GPU PID Type Process name Usage |
|=============================================================================|
| 0 32748 C python3 10613MiB |
| 1 32748 C python3 10611MiB |
+-----------------------------------------------------------------------------+
I can't see the actual GPU usage of my script since tensorflow always steals all memory at the beginning. And the actual problem here is I don't know how to debug this.
I've read some posts about OOM on StackOverflow. Most of them happened when feeding a large test set data to the model and feeding the data by small batches can avoid the problem. But I don't why see such a small data and param combination sucks in my 11Gb 1080Ti, since the error it just try to allocate a matrix sized [3840 x 155229]. (The output matrix of the decoder, 3840 = 30(time_steps) x 128(batch_size), 155229 is vocab_size).
2017-09-06 12:14:45.787566: W tensorflow/core/common_runtime/bfc_allocator.cc:277] ********************************************************************************************xxxxxxxx
2017-09-06 12:14:45.787597: W tensorflow/core/framework/op_kernel.cc:1158] Resource exhausted: OOM when allocating tensor with shape[3840,155229]
2017-09-06 12:14:45.788735: W tensorflow/core/framework/op_kernel.cc:1158] Resource exhausted: OOM when allocating tensor with shape[3840,155229]
[[Node: decoder/previous_decoder/Add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](decoder/previous_decoder/MatMul, decoder/biases/read)]]
2017-09-06 12:14:45.790453: I tensorflow/core/common_runtime/gpu/pool_allocator.cc:247] PoolAllocator: After 2857 get requests, put_count=2078 evicted_count=1000 eviction_rate=0.481232 and unsatisfied allocation rate=0.657683
2017-09-06 12:14:45.790482: I tensorflow/core/common_runtime/gpu/pool_allocator.cc:259] Raising pool_size_limit_ from 100 to 110
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py", line 1139, in _do_call
return fn(*args)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py", line 1121, in _run_fn
status, run_metadata)
File "/usr/lib/python3.6/contextlib.py", line 88, in __exit__
next(self.gen)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/errors_impl.py", line 466, in raise_exception_on_not_ok_status
pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.ResourceExhaustedError: OOM when allocating tensor with shape[3840,155229]
[[Node: decoder/previous_decoder/Add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](decoder/previous_decoder/MatMul, decoder/biases/read)]]
[[Node: GradientDescent/update/_146 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_2166_GradientDescent/update", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
During handling of the above exception, another exception occurred:
Any help will be appreciated. Thanks in advance.
A:
Let's divide the issues one by one:
About tensorflow to allocate all memory in advance, you can use following code snippet to let tensorflow allocate memory whenever it is needed. So that you can understand how the things are going.
gpu_options = tf.GPUOptions(allow_growth=True)
session = tf.InteractiveSession(config=tf.ConfigProto(gpu_options=gpu_options))
This works equally with tf.Session() instead of tf.InteractiveSession() if you prefer.
Second thing about the sizes,
As there is no information about your network size, we cannot estimate what is going wrong. However, you can alternatively debug step by step all the network. For example, create a network only with one layer, get its output, create session and feed values once and visualize how much memory you consume. Iterate this debugging session until you see the point where you are going out of memory.
Please be aware that 3840 x 155229 output is really, REALLY a big output. It means ~600M neurons, and ~2.22GB per one layer only. If you have any similar size layers, all of them will add up to fill your GPU memory pretty fast.
Also, this is only for forward direction, if you are using this layer for training, the back propagation and layers added by optimizer will multiply this size by 2. So, for training you consume ~5 GB just for output layer.
I suggest you to revise your network and try to reduce batch size / parameter counts to fit your model to GPU
A:
This may not make sense technically but after experimenting for some time, this is what I have found out.
ENVIRONMENT: Ubuntu 16.04
When you run the command
nvidia-smi
You will get the total memory consumption of the installed Nvidia graphic card. An example is as shown in this image
When you have run your neural network your consumption may change to look like
The memory consumption is typically given to python. For some strange reason, if this process fails to terminate successfully, the memory is never freed. If you try running another instance of the neural network application, you are bout to receive a memory allocation error. The hard way is to try to figure out a way to terminate this process using the process ID. Example, with process ID 2794, you can do
sudo kill -9 2794
The simple way, is to just restart your computer and try again. If it is a code related bug however, this will not work.
If the above mentioned process does not work,it is likely you are using a data batch size that can not fit into GPU or CPU memory.
What you can do is to reduce the batch size or the spatial dimensions (length, width and depth) of your input data. This may work but you may run out of RAM.
The surest way to conserve RAM is to use a function generator and that is subject matter on its own.
A:
You are exhausting your memory, You can reduce the batch size, which would slow down the training process but let you fit the data.
| {
"pile_set_name": "StackExchange"
} |
Q:
A question about maximal subgroups
Let $G$ be a finite group and $H_1,\ldots, H_n$ a set of maximal subgroups of $G$. Let $\delta_{H_i}$ be delta functions with support on $H_i$, and let $A$ be the commutative algebra generated by $\delta_{H_i}$.
Question: is dimension of $A$ greater or equal to $n$?
Motivation: In 1961 G.E.Wall conjectured that the number of maximal subgroups in a finite group $G$ is less than the order of $G$. A positive answer to the above question will imply Wall's conjecture. In fact it will even imply a relative version of Wall's conjecture: the number of maximal subgroups in $G$ which contain a subgroup $H$ is bounded by the number of double cosets in $G$, see arXiv:1006.5947 for more discussions and motivations from subfactors.
The question seems to be combinatorial in nature: the basis of $A$ is simply the list of subsets of $G$ obtained by cutting with $H_i$'s. for $n =2,3$ one can check directly, and one may try induction on $n$. Any references on this will be appreciated.
A:
Wall's conjecture is now known to be false : see this question and the answers there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Trigger ImportDefinition through WSProxy
I made a script (SSJS) to create a new Import Definition in Marketing Cloud. That works well, and if I then trigger the import manually in the GUI the import successfully completes.
However, I also want to start the ImportDefinition from my script, but I can't find how to do it.
This is how I (successfully) create an ImportDefinition:
var api = new Script.Util.WSProxy();
var importDef = {
Name: "CreatedDE_" + CAMPAIGN_NAME,
CustomerKey: NEW_GUID,
AllowErrors: true,
DestinationObject: { // DestinationObject?
CustomerKey: DE_KEY
},
RetrieveFileTransferLocation: {
CustomerKey: "ExactTarget Enhanced FTP"
},
UpdateType: "Overwrite",
FieldMappingType: "InferFromColumnHeadings",
FileSpec: FILE_NAME, // set CSV file name
FileType: "CSV"
};
var res = api.createItem("ImportDefinition", importDef);
I can get the CustomerKey and the ObjectID from the res object after it is created. I tried to use that to start the ImportDefinition, like this (or CustomerKey or Name instead of ObjectID):
var res = api.performItem("ImportDefinition", { ObjectID: res.Results[0].NewObjectID },"start",{});
But it always gives an error, with very descriptive Error Messages like:
Exception occurred during [Perform] ErrorID: 1646841981
The response of the performItem looks as follows. Only the ObjectID is initialized, so would that be an indication that it did not initialize the object properly?
{"Status":"Error","StatusMessage":"","RequestID":"bd47e454-6f78-465d-b616-20122c398049","Results":[{"Object":{"Name":null,"CustomerKey":null,"AllowErrors":false,"DestinationObject":null,"RetrieveFileTransferLocation":null,"UpdateType":"AddAndUpdate","FieldMappingType":"InferFromColumnHeadings","FileSpec":null,"FileType":"CSV","FieldMaps":null,"Notification":null,"SubscriberImportType":"Email","MaxFileAge":0,"MaxFileAgeScheduleOffset":0,"MaxImportFrequency":0,"Delimiter":null,"HeaderLines":0,"AutoGenerateDestination":null,"ControlColumn":null,"ControlColumnDefaultAction":"AddAndUpdate","ControlColumnActions":null,"EndOfLineRepresentation":null,"NullRepresentation":null,"StandardQuotedStrings":false,"Filter":null,"DateFormattingLocale":null,"DeleteFile":false,"SourceObject":null,"DestinationType":0,"SubscriptionDefinitionId":null,"EncodingCodePage":0,"SmsMemberSharedShortCodeId":null,"HasMultipleFiles":false,"InteractionObjectID":null,"Description":null,"Keyword":null,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"ObjectID":"20e8daf1-e3d3-e911-a2dd-48df37015621","Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false},"Task":{"StatusCode":"Error","StatusMessage":"Exception occurred during [Perform] ErrorID: 270858153","OrdinalID":0,"ErrorCode":0,"ID":null,"TblAsyncID":0,"InteractionObjectID":"fbdb6f91-7520-45a9-b556-275de4306dd5"},"ProgramActivityInstanceId":null,"StatusCode":"Error","StatusMessage":"Exception occurred during [Perform] ErrorID: 270858153","OrdinalID":0,"ErrorCode":2,"RequestID":null,"ConversationID":null,"OverallStatusCode":null,"RequestType":"Synchronous","ResultType":null,"ResultDetailXML":null}]}
I also tried using the old fashioned API calls Platform.Function.InvokePerform() but that gives the same errors.
Anybody knows what is the correct way to start an ImportDefinition using WSProxy or another working method in SSJS?
A:
I found a workaround (a bit hacky), using WSProxy, by putting the ImportDefinition in an Automation. Somehow I don't have any authentication issues with starting an Automation from WSProxy! I did need to setClientID() on the WSProxy object though, to get this to work.
// SAME CODE AS ABOVE TO START WITH
var api = new Script.Util.WSProxy();
var importDef = {
Name: "CreatedDE_" + CAMPAIGN_NAME,
CustomerKey: NEW_GUID,
AllowErrors: true,
DestinationObject: { // DestinationObject?
CustomerKey: DE_KEY
},
RetrieveFileTransferLocation: {
CustomerKey: "ExactTarget Enhanced FTP"
},
UpdateType: "Overwrite",
FieldMappingType: "InferFromColumnHeadings",
FileSpec: FILE_NAME, // set CSV file name
FileType: "CSV"
};
var res = api.createItem("ImportDefinition", importDef);
// ADDED CODE TO USE AUTOMATION WORKAROUND
api.setClientId({ "ID": YOUR_CLIENT_ID });
var importObjectID = res.Results[0].NewObjectID;
var automationKey = Platform.Function.GUID();
var automationDef = {
Name: 'AutomatedImport_' + automationKey,
CustomerKey: automationKey,
Description: 'Automated Import',
AutomationTasks: [
{
Name: 'Import',
Activities: [
{
ObjectID: importObjectID,
Name: 'Import',
ActivityObject: {
"__Type__": "ImportDefinition",
ObjectID: importObjectID,
Name: 'Import'
}
}
]
}
],
'AutomationType': 'Scheduled'
};
res = api.createItem('Automation', automationDef);
res = api.performItem("Automation", { "CustomerKey": automationKey }, "start");
| {
"pile_set_name": "StackExchange"
} |
Q:
What is this bonsai plant with red-tinged leaves?
Can anyone identify this plant? It was purchased in southern Oregon.
A:
It's Berberis thunbergii atropurpureum, maybe 'nana', the dwarf version with a height of around 50 cm or the larger version which gets around a metre and a half planted in the ground. It's deciduous, and needs to be kept outdoors with at least 3 or 4 hours direct sunlight - without sun, the leaves will turn plain green. It will need protection from temperatures below -5degC, so plan to move indoors to a very cool room briefly or into a greenhouse until temperatures rise again, but don't keep it inside any longer than you have to. More info here http://www.bonsai4me.co.uk/SpeciesGuide/Berberis.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Window display table and buffer display table conflict in Emacs
In Emacs;
Is there a way for both window-display-table and buffer-display-table to have effect at the same time?
The reason is, I'm using Pretty-Control-L (from Emacs Goodies El script package) and whitespace (of whitespace.el, I think it is in the base Emacs distribution, but I’m not sure).
Pretty-Control-L visualizes form-feeds (^L) in a customized manner, by setting the entry for C-l in the window-local window-display-table.
Whitespace visualizes spaces, tabs and newlines by setting entries in the buffer-local buffer-display-table. (and also by using font-lock functionality).
These uses clashes (or rather, the use of a window-display-table and buffer-display-table clashes) since, if the window-display-table is non-nil it completely overrides any buffer-display-table for any buffer displayed in that window.
Quote from the Emacs Lisp manual:
38.21.2 Active Display Table
Each window can specify a display table, and so can each buffer. When
a buffer B is displayed in window W, display uses the display table
for window W if it has one; otherwise, the display table for buffer B
if it has one; otherwise, the standard display table if any. The
display table chosen is called the "active" display table.
[...]
(emphasis by me)
So, Is there any easy way to consolidate this? Or is the only way to re-code one of them to use the same mechanism as the other?
I've been considering writing a small (i.e. even smaller) crude variant of the form-feed visualization compatible with the white-space visualization that just uses some buffer-loading hook (or other) to put a hard-coded entry for ^L in the buffer-display-table. But I’d like to know if there’s any simpler alternative.
EDIT: To clarify the problem, here's a excerpt of an annotated "Interactive Lisp" session (i.e. from the *scratch*-buffer). This shows the commands and their output, and annotated with the effects:
;; Emacs is started with `-q', to not load my init-file(s).
;; First, write some sample text with tabs and line-feeds:
"A tab: and some text
A line-feed:and some text"
;; Make sure that it is a tab on the first line (input by `C-q TAB')
;; and a line-feed on the second line (input by `C-q C-l').
;; These probably won't copy properly into Stack Exchange.
;; This shows the spaces as center-dots, tabs as `>>'-glyphs and
;; new-lines as $'s (or perhaps other glyphs, depending on system
;; setup...). All of them fontified to be dimmed out on yellow/beige/white
;; background.
(whitespace-mode t)
t
;; This turns on pretty-control-l mode. The `^L' above will be
;; prettified... Since this sets the window display table, the glyphs
;; for the spaces/tabs/new-lines will disappear, but the background of
;; spaces/tabs will still be yellow/beige (since that's done with
;; fontification, not display tables).
(pretty-control-l-mode t)
t
;; This turns pretty-control-l mode OFF again. The form-feed will
;; revert to displaying as `^L'. However, the glyphs for the
;; spaces/tabs/new-lines will not re-appear, since this only removes
;; the `C-l'-entry in the window-display-list, not the entire list.
(pretty-control-l-mode 0)
nil
;; Nil the window-display-table, to verify that is the culprit. This
;; will re-enable the glyphs defined by whitespace-mode (since they
;; are still in the buffer display-table).
(set-window-display-table nil nil)
nil
;; To round of; this is my Emacs-version:
(emacs-version)
"GNU Emacs 23.4.1 (i686-pc-linux-gnu, GTK+ Version 2.24.12)
of 2012-09-22 on akateko, modified by Debian"
;;End.
A:
Sorry for your trouble. I don't see the problem you report, following your recipe. Perhaps the description is not complete? I can turn on both pretty-control-l-mode and whitespace-mode, and the behavior I see for each seems normal. Perhaps there is some custom setting you use for whitespace-style or something?
Anyway, maybe it would help if you make a change like this to pretty-control-l-mode. If so, let me know and I will apply it to pp-c-l.el. (To test, set the new option to nil.)
(defcustom pp^L-use-window-display-table-flag t
"Non-nil: use `window-display-table'; nil: use `buffer-display-table`."
:type 'boolean :group 'Pretty-Control-L)
(define-minor-mode pretty-control-l-mode
"Toggle pretty display of Control-l (`^L') characters.
With ARG, turn pretty display of `^L' on if and only if ARG is positive."
:init-value nil :global t :group 'Pretty-Control-L
(if pretty-control-l-mode
(add-hook 'window-configuration-change-hook 'refresh-pretty-control-l)
(remove-hook 'window-configuration-change-hook 'refresh-pretty-control-l))
(walk-windows
(lambda (window)
(let ((display-table (if pp^L-use-window-display-table-flag ; <=========
(or (window-display-table window)
(make-display-table))
(if buffer-display-table
(copy-sequence buffer-display-table)
(make-display-table)))))
(aset display-table ?\014 (and pretty-control-l-mode
(pp^L-^L-display-table-entry window)))
(if pp^L-use-window-display-table-flag ; <=========
(set-window-display-table window display-table)
(setq buffer-display-table display-table))))
'no-minibuf
'visible))
UPDATED to add comment thread, in case comments get deleted at some point:
BTW, I wonder if the hierarchy of display tables described in the doc shouldn't perhaps be applied using inheritance of some kind. Seems a bit primitive for one level (e.g. window) to completely shadow a lower level (e.g. buffer). You might consider sending a question about this to M-x report-emacs-bug. – Drew Sep 24 '14 at 16:36
Ping? Could you please let me know if the change above helps? Thx. – Drew Oct 14 '14 at 18:12
I just read this answer (I have not been around this part of the Internet for a while...). I will check this when I get round to it, perhaps in a few days or so. I'll get back with an ‘Answer approved’ (if it works), or comments (otherwise), as appropriate, later. – Johan E Oct 25 '14 at 22:32
I edited the question to add a more fleshed-out recipe for showing the problem. I'd be interested whether you get the same results. --- Also, is there a way to shadow a system installed .el-file with a user-supplied one (I'm really just a “user”, not a lisp-programmer...)? I don't really feel like messing with the files installed by deb-packages. (That's why I did the problem-recipe before testing your answer...) – Johan E Oct 27 '14 at 1:02
Five seconds after I wrote the last comment I realized that I could just paste the code into scratch and C-j-run it to test. (No need to edit any files.) The results: It works a charm! Thank you! (=> Answer accepted) However, I'd still like to know if you get the same results as I from my problem-recipe (before patching the code). – Johan E Oct 27 '14 at 1:09
I just followed your new recipe, and I saw everything you described (so clearly). And then I read the new comment that you just added. Glad to know that things work OK. Thx for your feedback. – Drew Oct 27 '14 at 1:12
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does this Applescript code produce the error "variable destination is not defined"?
As I stated in the subject this code produces the mentioned error when run via osascript. I can't run it from "Script Editor" as there is apparently no way to pass "command line" parameters then.
the code is as follows:
on run (clp)
if clp's length is not 2 then error "Incorrect Parameters"
local destination, libraryName
destination is clp's item 1
libraryName is clp's item 2
menuClick("iTunes", "File", "Library", "Export Library…")
set value of parentObject's text field "Save As:" to (libraryName and ".xml")
tell pop up button 1 of group 1 of window "New iTunes Library" of process "iTunes" of application "System Events" to click
repeat with ndx from 1 to (count of parentObject's menu 1)
if title of menu item ndx is "" then
select menu item (ndx - 1)
exit repeat
end if
end repeat
my switchDir(destination, "iTunes", "iTunes", true, false)
set the value of text field "Save As:" of window "iTunes" to (libraryName + ".xml")
tell button "Save" of window "iTunes" to click
return (destination and "/" and libraryName and ".xml")
end run
A:
get rid of:
destination is clp's item 1
libraryName is clp's item 2
and substitute with:
set destination to clp's item 1
set libraryName to clp's item 2
| {
"pile_set_name": "StackExchange"
} |
Q:
Multivariate normal conditioned on sum of squares
Suppose that $X_i$ are i.i.d. N(0,1) random variables, and set $S =
\sum_{i=1}^n X_i^2$. Then $S \sim \chi^2_{(n)}$, the $\chi^2$
distribution with $n$ degrees of freedom. Compute the induced
probability measure on $\mathbb{R}^n$: $$\mu^s_n(A) := P((X_1, \dots,
X_n) \in A | S = s),$$ where $A \subset \mathbb{R}^n$ is
Borel-measurable.
First, a proposed solution. Let $X = (X_1, ..., X_n)$. Then $S = \|X\|^2$. Moreover, for any rotation matrix $O$, $OX$ has the same distribution as $X$. Thus, for any rotation matrix $O$,
$$\mu^s(OA) = P(X \in OA | S = s) = P(O^{-1}X \in A | S = s) = \mu^s(A),$$
so $\mu$ is rotation invariant. Moreover, given that $S = s$, $X$ must lie on the sphere of radius $\sqrt{s}$, and $\mu^s(\mathbb{S}_{\sqrt{s}}^{n-1}) = 1$, where $\mathbb{S}_{\sqrt{s}}^{n-1}$ denotes the $n-1$-sphere in $\mathbb{R}^n$ of radius $\sqrt{s}$. Thus $\mu$ is a rotation-invariant probability measure which takes full mass on the $n-1$-sphere; by uniqueness of such measures, $\mu$ must be the uniform distribution on the $n-1$-sphere.
The problem I have is computing this explicitly. This measure is singular with respect to $\mathbb{R}^n$-Lebesgue measure, though theorems on regular conditional probabilities tell me this is a well-defined measure for each $s$.
Problem
Take $n = 2$, let $R^2 = X_1^2 + X_2^2$, $\theta = \arctan(X_2/X_1)$. We have
$$\left|\begin{pmatrix} \frac{\partial R}{\partial X_1} & \frac{\partial R}{\partial X_2} \\ \frac{\partial \theta}{\partial X_1} & \frac{\partial \theta}{\partial X_2}\end{pmatrix}\right| = \left|\begin{pmatrix} \frac{X_1}{\sqrt{X_1^2+X_2^2}} & \frac{X_2^2}{\sqrt{X_1^2+X_2^2}} \\ \frac{-X_2}{X_1^2+X_2^2} & \frac{X_1}{X_1^2+X_2^2}\end{pmatrix}\right| = \frac{1}{R}.$$
Hence, using independence of $X_1$ and $X_2$ and the density for a standard normal,
$$f(R,\theta) = f_{X_1,X_2}(X_1, X_2)\left|\frac{\partial (R,\theta)}{\partial (X_1,X_2)}\right|^{-1} = \frac{1}{2\pi}e^{-R^2}R.$$
From this we see further that $R$ and $\theta$ are actually independent, with $\theta$ being uniform on $(0,2\pi)$ (I know this is not the case in higher dimensions). Thus, the desired density should be
$$f(R,\theta | S = s) = \frac{f(s,\theta)}{f(s)} = \frac{1}{2\pi},$$
but this doesn't take into account the radius of the sphere.
I suspect the problem is with having a density on an $n-1$ dimensional submanifold and not taking into account the volume form correctly, but I'm not sure how to fix this. I'd also like some rigorous explanation of why (or if!) I am allowed to just apply the rules for conditional density like I did. Any help appreciated.
A:
Actually, when $n=2$, the density of $(R,\Theta)$ is the function $f_{R,\Theta}$ defined by
$$f_{R,\Theta}(r,\theta)=r\mathrm e^{-r^2/2}\mathbf 1_{r\gt0}\,\frac1{2\pi}\mathbf 1_{0\leqslant\theta\lt2\pi}.
$$
Thus, for every $r\gt0$, the conditional density of $\Theta$ conditionally on $R=r$ is the function $g_{\Theta\mid R=r}$ defined by
$$
g_{\Theta\mid R=r}(\theta)=\frac1{2\pi}\mathbf 1_{0\leqslant\theta\lt2\pi}.
$$
Since $g_{\Theta\mid R=r}$ does not depend on $r$, one sees that $R$ and $\Theta$ are independent.
Likewise, in every dimension $n\geqslant2$, the spherical coordinates read
$$
(X_1,\ldots,X_n)=R\cdot Z,
$$
where $R$ is in $[0,\infty)$ and $Z$ in $S^{d-1}$. Then, $R$ and $Z$ are independent and $Z$ is uniformly distributed on $S^{d-1}$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Group by and non distinct columns and data normalization
I have a large table(60 columns, 1.5 million records) of denormalized data in MS SQL 2005 that was imported from an Access database. I've been tasked with normalizing and inserting this data into our data model.
I would like to create a query that used a grouping of, for example "customer_number", and returned a result set that only contains the columns that are non distinct for each customer_number. I don't know if it's even possible, but it would be of great help if it was.
Edit:if my table has 3 columns(cust_num,cust_name_cust_address) and 5 records
|cust_num|cust_name|cust_address
|01 |abc |12 1st street
|02 |cbs |1 Aroundthe Way
|01 |abc |MLK BLVD
|03 |DMC |Hollis Queens
|02 |cbs |1 Aroundthe Way
the results from my desired query should just be the data from cust_num and cust_name because cust_address has different values for that grouping of cust_num. A cust_num has many addresses but only one cust_name.
Can someone point me in the right direction?
Jim
A:
No, this can't be done
| {
"pile_set_name": "StackExchange"
} |
Q:
Show/hide navigation on scroll position
This jquery show navigation menu when you scroll up page 0px up (in right-way). But trying to show after 200px (on page scroll-up), means not showing right way, want show and hide after 200px when scroll up page.
Jquery: Fiddle
// Script
lastScroll = 0;
$(window).on('scroll',function() {
var scroll = $(window).scrollTop();
if(scroll === 0){
$(".nav").removeClass("darkHeader");
} else if(lastScroll - scroll > 0) {
$(".nav").addClass("darkHeader");
} else {
$(".nav").removeClass("darkHeader");
}
lastScroll = scroll;
});
HTML:
<div class="nav">
Sticky top navigation bar
</div>
<div class="wrap">
<h3>Some filler text</h3>
Bacon ipsum dolor sit amet mollit ball tip occaecat brisket cupidatat meatball capicola. Capicola rump turducken, elit shankle cupidatat pastrami duis fatback. Sint occaecat kielbasa labore pastrami corned beef. Sunt swine bacon, fugiat dolor aute anim jerky nostrud et venison shankle consectetur boudin landjaeger.
Pork chop sed turkey aute, duis corned beef pariatur short loin proident culpa. Capicola filet mignon fugiat corned beef shank ea, commodo doner adipisicing eu salami. Doner laboris pariatur beef ribs non id. Andouille eu meatball consectetur ham hock. Ea dolore cillum cow pork loin aliquip leberkas id est corned beef dolore t-bone. In salami jerky cupidatat et.
</div>
Any advice? Example fiddle.
Thanks in advance.
A:
#One of the way i have found:
// Script
var lastScroll = 0;
var scrollUpStart = 0;
$(window).on('scroll',function() {
var scroll = $(window).scrollTop();
if(scroll === 0){
// we are at the top
$(".nav").removeClass("darkHeader");
} else if(lastScroll > scroll) {
// we are scrolling up
// we check if we have started scrolling up
if (scrollUpStart < scroll) {
// if we just started scrolling up, we set the 'marker'
scrollUpStart = scroll;
}
if (scrollUpStart - scroll > 200) {
$(".nav").addClass("darkHeader");
}
} else {
scrollUpStart = 0;
// we are scrolling down
$(".nav").removeClass("darkHeader");
}
lastScroll = scroll;
});
Example Fiddle :)
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS 7 taking screenshot of part of a UIView
I have a view (testView) that is 400x320 and I need to take a screenshot of part of this view (say rect = (50, 50, 200, 200)).
I am playing around with the drawViewHierarchy method in iOS 7 but I can't figure out how to do it correctly.
UIGraphicsBeginImageContextWithOptions(self.testView.bounds.size, NO, [UIScreen mainScreen].scale);
[self.testView drawViewHierarchyInRect:self.testView.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Any help will be appreciated!
Thanks.
A:
After getting the whole snapshot, you could draw it in a smaller Graphic Context in a way that you get the part you want:
UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), YES, [UIScreen mainScreen].scale);
[image drawInRect:CGRectMake(-50, -50, image.size.width, image.size.height)];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
EDIT: Better yet, draw the hierarchy directly in that smaller context:
UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), NO, [UIScreen mainScreen].scale);
[self.testView drawViewHierarchyInRect:CGRectMake(-50, -50, self.testView.bounds.size.width, self.testView.bounds.size.height) afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
| {
"pile_set_name": "StackExchange"
} |
Q:
Practical use of State or Strategy pattern
I have this in my code
switch (auctionType)
{
case AuctionTypes.OpenBid:
destination = new EnglishAuction();
break;
case AuctionTypes.FixedPrice:
destination = new BuyoutAuction();
break;
case AuctionTypes.ClosedBid:
destination = new SealedFirstPriceAuction();
break;
default:
destination = new Auction();
break;
}
What I am wondering is how do I eliminate the switch statement by using the Strategy or State pattern?
A:
The code you posted is indeed a factory. In a factory, switches are OK.
The Auction objects you return probably belong to a strategy. The difference between strategy and state is subtle, but important:
In a strategy, you're using different algorithms to accomplish essentially the same thing. The caller must not need to know this, it's an implementation detail. Some examples of strategies might be
In a computer game, you want your AI bad guys to attack the player. Different enemies might use different strategies because they might be able to fly over obstacles, teleport to the player or have different combat style.
In a HybridDictionary, operations might be implemented in a simple ListDictionary while the collection is small and use a Hashtable once the collection grows.
In a CAD application, you might have implemented different strategies to calculate the solution for a complex equation depending on a variety of factors to find the optimal level of speed vs. accuracy.
This sometimes leads to confusion, because the different monster's behavior is 'obvious' or at least visible to the end-user, while the latter aren't. On the other hand, it is visible because it's hopefully faster / more precise. It's just not that obvious, usually.
in a State pattern, on the other hand, the class will behave differently. The classical state pattern example is a TcpSocket class: The socket could be, among others, in connected or disconnected state. This is visible to the client, and calling Disconnect() on a disconnected socket is an error, as is calling Connect() on a socket that is already connected. The object itself can change its state, and it's visible and known to the outside.
Since you are using a factory, the Auction object returned will probably not change type during its lifetime as part of the normal operation. Implementations of state typically don't go through a factory because they are not interchangeable. Instead, you would create a TcpSocket which uses TcpSocketClosed internally and changes to TcpSocketConnected after you successfully called Connect().
A:
Just for fun, and with reference to @Raphaël's comment about a way of eliminating the switch statement in Java, you could get a similar result (albeit with more work) in C# like this:
Create an attribute which holds a Type and creates an instance of it using its parameterless constructor:
public class TypeAttribute : Attribute
{
private readonly Type _type;
public TypeAttribute(Type type)
{
_type = type;
}
public T CreateInstance()
{
return (T)Activator.CreateInstance(_type);
}
}
...decorate your enum with the attribute:
public enum AuctionTypes
{
[Type(typeof(EnglishAuction))]
OpenBid,
[Type(typeof(BuyoutAuction))]
FixedPrice,
[Type(typeof(SealedFirstPriceAuction))]
ClosedBid,
[Type(typeof(Auction))]
Default
}
...add an extension method:
public static class Extensions
{
public static Auction CreateAuction(this AuctionTypes auctionType)
{
return typeof(AuctionTypes)
.GetMember(auctionType.ToString())
.First()
.GetCustomAttributes(typeof(TypeAttribute), inherit: false)
.Cast<TypeAttribute>()
.First()
.CreateInstance<Auction>();
}
}
...which you can call like this:
var auction = auctionType.CreateAuction();
That's from memory and would be better if we had generic attributes, but there you go.
| {
"pile_set_name": "StackExchange"
} |
Q:
Json.NET (Newtonsoft.Json) - Two 'properties' with same name?
I'm coding in C# for the .NET Framework 3.5.
I am trying to parse some Json to a JObject.
The Json is as follows:
{
"TBox": {
"Name": "SmallBox",
"Length": 1,
"Width": 1,
"Height": 2 },
"TBox": {
"Name": "MedBox",
"Length": 5,
"Width": 10,
"Height": 10 },
"TBox": {
"Name": "LargeBox",
"Length": 20,
"Width": 20,
"Height": 10 }
}
When I try to parse this Json to a JObject, the JObject only knows about LargeBox. The information for SmallBox and MedBox is lost. Obviously this is because it is interpreting "TBox" as a property, and that property is being overwritten.
I am receiving this Json from a service that's coded in Delphi. I'm trying to create a C# proxy for that service. On the Delphi-side of things, the "TBox" is understood as the type of the object being returned. The inner properties ("Name", "Length", "Width", "Height") are then understood as regular properties.
I can serialize and deserialize a custom 'TBox' object that has Name, Length, Width, and Height properties. That's fine.
What I want to do is step through all the TBox sections in such a way as to extract the following three Json strings.
First:
{
"Name": "SmallBox",
"Length": 1,
"Width": 1,
"Height": 2 }
Second:
{
"Name": "MedBox"
"Length": 5,
"Width": 10,
"Height": 10 }
Third:
{
"Name": "LargeBox"
"Length": 20,
"Width": 20,
"Height": 10 }
Once I have these strings, I can serialize and deserialize to my heart's content.
I'm finding Newtonsoft.Json to be very good. I really don't want to go messing about with other frameworks if I can avoid it.
Any help would be greatly appreciated.
I have very limited input as to changes that can be made to the server.
A:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
JsonTextReader jsonReader = new JsonTextReader(reader);
jsonReader.Read();
while(jsonReader.Read())
{
if(jsonReader.TokenType == JsonToken.StartObject)
{
JObject tbox = JObject.Load(jsonReader);
}
}
However, note that the RFC says, "The names within an object SHOULD be unique" so if you can, recommend the format be changed.
EDIT: Here's an alternate design that doesn't have duplicate keys:
[
{
"TBox": {
"Width": 1,
"Length": 1,
"Name": "SmallBox",
"Height": 2
}
},
{
"TBox": {
"Width": 10,
"Length": 5,
"Name": "MedBox",
"Height": 10
}
},
{
"TBox": {
"Width": 20,
"Length": 20,
"Name": "LargeBox",
"Height": 10
}
}
]
A:
If I'm not mistaken, the correct answer to this is that your input is not actually JSON. So no, getting a JSON parser to parse it probably isn't going to work.
Maybe you don't have any control over the source of the input, so I'd use a Regex or something to pre-filter the string. Turn it into something like:
{"TBoxes":
[
{
"Name": "SmallBox",
"Length": 1,
"Width": 1,
"Height": 2
},
{
"Name": "MedBox",
"Length": 5,
"Width": 10,
"Height": 10
},
{
"Name": "LargeBox",
"Length": 20,
"Width": 20,
"Height": 10
}
]
}
And treat it like the array that it is.
| {
"pile_set_name": "StackExchange"
} |
Q:
Play Framework: Reading Version from Build.sbt
I've been seeing a bunch of questions about how to read a version from build.sbt, and there have been a lot of work-arounds provided for how to point build.sbt to conf/application.conf and have the version specified in conf/application.conf instead.
I have a Configuration object that needs to get in the version. I currently have it set up like this (How get application version in play framework and build.sbt), where the Configuration objects from application.conf. However, I'd still like to get it directly from build.sbt. How can I do that? Should I perhaps run a bash command on the build.sbt file to get the version from there? Any suggestions?
Thanks!
A:
We managed to get information via build-info, here's some detail configuration.
Add plugins (we also include sbt-git since we want git version as well) into project/plugins.sbt
addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "0.8.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.5.0")
Configure plugins in build.sbt
enablePlugins(BuildInfoPlugin)
enablePlugins(GitVersioning)
buildInfoKeys := Seq[BuildInfoKey](organization, name, version, BuildInfoKey.action("gitVersion") {
git.formattedShaVersion.?.value.getOrElse(Some("Unknown")).getOrElse("Unknown") +"@"+ git.formattedDateVersion.?.value.getOrElse("")
})
buildInfoPackage := "version"
Within views (*.html.scala), display those info simply by
Version @version.BuildInfo.version - build @version.BuildInfo.gitVersion
Or you can just using all values from BuildInfo in your java or scala code, by calling version.BuildInfo.XX
| {
"pile_set_name": "StackExchange"
} |
Q:
Reload tableview data duplicate
i'm using an NSTimer on the label text inside the uitableviewcell. This label text is updated every 5 seconds and every 5 seconds i call [reload theTableView]; Instead of updating it seem to duplicate instead of overwriting how come is that:
Here is a image when the data is reloaded:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
chatCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) cell = [[chatCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.backgroundColor = [UIColor colorWithRed:243/255.0f green:243/255.0f blue:247/255.0f alpha:1.0f];
cell.homeTeamLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 10, 140, 20)];
cell.homeTeamLabel.text = [[arrayBarclay objectAtIndex:indexPath.row] objectForKey:@"hometeam" ];
cell.homeTeamLabel.font = [UIFont systemFontOfSize:14.0];
cell.homeTeamLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:cell.homeTeamLabel];
cell.awayTeamLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 30, 140, 20)];
cell.awayTeamLabel.text = [[arrayBarclay objectAtIndex:indexPath.row] objectForKey:@"awayteam" ];
cell.awayTeamLabel.font = [UIFont systemFontOfSize:14.0];
cell.awayTeamLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:cell.awayTeamLabel];
cell.homeTeamScore = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.size.width-50, 10, 30, 20)];
cell.homeTeamScore.text = [[arrayBarclay objectAtIndex:indexPath.row] objectForKey:@"homescore" ];
cell.homeTeamScore.font = [UIFont systemFontOfSize:14.0];
cell.homeTeamScore.textColor = [UIColor blackColor];
[cell.contentView addSubview:cell.homeTeamScore];
cell.awayTeamScore = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.size.width-50, 30, 30, 20)];
cell.awayTeamScore.text = [[arrayBarclay objectAtIndex:indexPath.row] objectForKey:@"awayscore" ];
cell.awayTeamScore.font = [UIFont systemFontOfSize:14.0];
cell.awayTeamScore.textColor = [UIColor blackColor];
[cell.contentView addSubview:cell.awayTeamScore];
cell.time = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 40, 60)];
cell.time.textAlignment = NSTextAlignmentCenter;
cell.time.text = [[arrayBarclay objectAtIndex:indexPath.row] objectForKey:@"time" ];
cell.time.font = [UIFont systemFontOfSize:14.0];
cell.time.textColor = [UIColor blackColor];
[cell.contentView addSubview:cell.time];
}
A:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
chatCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil){
cell = [[chatCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
//It's better to move following code to chatCell
//And ChatCell className will also be better.
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.backgroundColor = [UIColor colorWithRed:243/255.0f green:243/255.0f blue:247/255.0f alpha:1.0f];
cell.homeTeamLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 10, 140, 20)];
cell.homeTeamLabel.font = [UIFont systemFontOfSize:14.0];
cell.homeTeamLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:cell.homeTeamLabel];
cell.awayTeamLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 30, 140, 20)];
cell.awayTeamLabel.font = [UIFont systemFontOfSize:14.0];
cell.awayTeamLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:cell.awayTeamLabel];
cell.homeTeamScore = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.size.width-50, 10, 30, 20)];
cell.homeTeamScore.font = [UIFont systemFontOfSize:14.0];
cell.homeTeamScore.textColor = [UIColor blackColor]
[cell.contentView addSubview:cell.homeTeamScore];
cell.awayTeamScore = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.size.width-50, 30, 30, 20)];
cell.awayTeamScore.font = [UIFont systemFontOfSize:14.0];
cell.awayTeamScore.textColor = [UIColor blackColor];
[cell.contentView addSubview:cell.awayTeamScore];
cell.time = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 40, 60)];
cell.time.textAlignment = NSTextAlignmentCenter;
cell.time.font = [UIFont systemFontOfSize:14.0];
cell.time.textColor = [UIColor blackColor];
[cell.contentView addSubview:cell.time];
}
//Move [arrayBarclay objectAtIndex:indexPath.row] out will be better.
NSDictionnary *contentDict = [arrayBarclay objectAtIndex:indexPath.row];
cell.homeTeamLabel.text = [contentDict objectForKey:@"hometeam"];
cell.awayTeamLabel.text = [contentDict objectForKey:@"awayteam"];
cell.homeTeamScore.text = [contentDict objectForKey:@"homescore" ];
cell.awayTeamScore.text = [contentDict objectForKey:@"awayscore" ];
cell.time.text = [contentDict objectForKey:@"time" ];
return cell;
}
If you want to reuse a cell, you'd better init its subviews in its init method. cellForRowAtIndexPath: will be called any time cell will be displayed. If you need addsubview dynamically, remove previous added views first.
| {
"pile_set_name": "StackExchange"
} |
Q:
RShiny dynamic Popup (can move)
I work on a dashboard and I would like to create a dynamic popup , ie we can move.
I can create a pop-up but this one is static, I like that one can take it and move it to the right, left ...
A example of my pop up :
library(shiny)
library(shinyBS)
shinyApp(
ui =
fluidPage(
sidebarLayout(
box(actionButton("tabBut", "View Table")),
mainPanel(
bsModal("modalExample", "Data Table", "tabBut", size = "large",
dataTableOutput("distTable"))))),
server =
function(input, output, session) {
output$distTable <- renderDataTable({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = 30 + 1)
tab <- hist(x, breaks = bins, plot = FALSE)
tab$breaks <- sapply(seq(length(tab$breaks) - 1), function(i) {
paste0(signif(tab$breaks[i], 3), "-", signif(tab$breaks[i+1], 3))})
tab <- as.data.frame(do.call(cbind, tab))
colnames(tab) <- c("Bins", "Counts", "Density")
return(tab[, 1:3])},
options = list(pageLength=10))}
)
result
And I want that the user can move this window.
If you have ideas of option to change, or so if you know any means other than BS Shiny on to create new window...
Thank you in advance and sorry for my English !
A:
You can try to do it manyally :
1) Add script
2) add draggable
3) edit css
like:
ui =
fluidPage(
tags$head(HTML('<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>')),
tags$script(HTML(' $(window).load(function(){
$("#modalExample").draggable({
handle: ".modal-header"
});
});')),
tags$style(HTML("
.modal-backdrop.in {
opacity: 0;
}
")),
sidebarLayout(
box(actionButton("tabBut", "View Table")),
mainPanel(
bsModal("modalExample", "Data Table", "tabBut", size = "large",
dataTableOutput("distTable")))))
| {
"pile_set_name": "StackExchange"
} |
Q:
Proof Verification - $\exists a \in S (a\ge S_a)$
I wanted to prove that $\exists a \in S (a\ge S_a)$ where $S$ is an finite set of real numbers with order $n$ and $S_a$ is the average of the set. This is my proof so far:
Assume $a_i = a_k, i,k \text{ are integers and } \in [1,n]$. Also assume $a_i < S_a = \frac{\sum a_i}{n}$
The last statement implies $na_i < \sum a_i = na_i$ which is a contradiction.
Now, can we generalize this statement for $a_i \neq a_k$ by saying that the amount $S_a - a_i$ for some $a_i<S_a$ is compensated by adding it to some $a_k > S_a$?
A:
Let $$S=\{a_{1},a_{2},........a_{n}\}$$ be the finite set. Assume there is no element $a$ in $S$ such that $a\ge S_{a}$. Now $$\sum_{i=1}^{n} a_{i} = n.S_{a}$$ . But according to our assumption each $a_{i} \lt S_{a}$. Hence $$a_{1}+a_{2}+.....a_{n} \lt {S_{a}+S_{a}+......S_{a}}_{\{\ \ added\ \ n \ \ times}\} $$ i.e. $$\sum_{i=1}^{n} a_{i} \lt n.S_{a}$$
Thus the contradiction in general case. So there must exist an $a_{m}$ for some $m\le n$ such that $$a_{m} \ge S_{a}$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Merge large number of polygons using QGIS
I have a series of polygons that are the output of another GIS program - I need to merge the polygons into a single polygon. I have tried a couple of different methods with no luck. I have tried to use the "Dissolve" tool, using the Dissolve all - however this led to an essentially empty output (most probably because there isn't a common attribute between all the polygons). I have tried to use the calculator in the attribute table (there are around 350 000 polygons) to add a dummy column but it doesn't show in the Dissolve tool.
I am finding the merge tool does the job - to a point, but ultimately is extremely time consuming. Is there a way to merge all polygons in a layer without too many steps? Ultimately I just need the geographic area, the values/names etc are entirely irrelevant for what I'm currently doing. I have tried to select all within the attribute table by using the "invert selection" option (a recommendation on another site) but this doesn't appear to do anything. I have also read about a SelectPlus plugin, but no luck finding this one either.
Any suggestions greatly appreciated.
EDIT: Sorry it's a single file that I'm wanting to merge the polygons in (want the outline of all of them together, there are no gaps).
EDIT2: and while it's very slow, I've now found how to select all the polygons at once (using the radius selection option), which at least seems to be working if I do in stages.
A:
Using QGIS, apart from the Vector -> Geprocessing Tools - Dissolve Menu entry, you can also use Processing (formerly named Sextante), which offers dissolving by GRASS and SAGA.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to start a link when entering page?
I have this link on my web page:
<a id="demo03" href="#modal-03">DEMO03</a>
How can I make that link run automatically, when I enter my page?
Hope you can help me!
Thanks :-)
A:
Try like this
<html>
<head></head>
<body>
<a id="demo03" href="#modal-03">DEMO03</a>
<script type="text/javascript">
(function() {
var link = document.getElementById('demo03');
link.click();
})();
</script>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
Turn On GPS on rooted devices
This question about turning on/off GPS programatically on android has been discussed many times, and the answer is always the same: You can't for security/privacy reasons.
But is there any way for rooted devices to turn on gps with some edit in system settings..
A:
There is a working solution fot rooted. See in one of my answers in profile. I cannot elaborate right now (in hospital). But currently you need root and busybox. I'm trying to make it working without busybox. Tested with 2.3.5 4.0.1 and 4.1.2
http://rapidshare.com/files/3977125468/GPSToggler-20130214.7z
| {
"pile_set_name": "StackExchange"
} |
Q:
Sequalize adds primary key to query implicitly
I'm using sequelize-typescript and it implicitly adds primary key column to all create queries which is a problem because I don't want to set this id by myself (IDENTITY_INSERT is set to OFF).
@Table({
timestamps: false,
})
class Table extends Model<Table> {
@PrimaryKey
@Column
MyId: string;
@Column
column: string;
}
table.create({column: 'value'});
This ends up with query:
sql: 'INSERT INTO [Table] ([MyId],[column]) OUTPUT INSERTED.* VALUES (NULL,'value');'
And error:
SequelizeDatabaseError: DEFAULT or NULL are not allowed as explicit identity values.
The query I need to get is:
INSERT INTO [Table] ([column]) OUTPUT INSERTED.* VALUES ('value');
Any help is much appreciated!
A:
First of all - remove @PrimaryKey decorator.
After model is added to sequelize instance do next:
Table.removeAttribute('id');
Now id won't be added to queries but will be used for ordering in select methods so set your own order by:
Table.findAll({where: {column: 'value'}, order: ['MyId']});
And of course using this means that your DB knows which column is primary key and increments it by itself.
| {
"pile_set_name": "StackExchange"
} |
Q:
Redirect back to previous page django
I am building a django app for which one component is simple CRUD for some models. I have created add, edit, delete, view details and listing pages. I have given the buttons to edit and delete records on listing page as well as view details page. Since the edit buttons from listing page and inner details page use same views and templates, the success url can either link back to view details page or listing page. I would like to add code so that if user goes to edit page from view details then is redirect back to details page on success, but if the user goes to edit page from listing page then the user is redirected to listing page (also listing page has pagination so user should go back to page s/he was on.
A:
One way to do this would be to store the url that the user came from in their session and then redirect them back to the url on success. This mixin could be added to your views
class RedirectToPreviousMixin:
default_redirect = '/'
def get(self, request, *args, **kwargs):
request.session['previous_page'] = request.META.get('HTTP_REFERER', self.default_redirect)
return super().get(request, *args, **kwargs)
def get_success_url(self):
return self.request.session['previous_page']
Then you can just subclass this mixin in your class based views
class MyModelUpdateView(RedirectToPreviousMixin, UpdateView):
model = MyModel
| {
"pile_set_name": "StackExchange"
} |
Q:
How to transform an element in a page using css3 transforms?
i got a div that looks like this:
+---------+
| |
+---------+
and I want to transform it like this:
+---------+
/ \
+-------------+
How can i do that ?
A:
If you wish to use CSS transforms, see here
HTML
<div class='trapezoid'></div>
CSS
.trapezoid {
display: inline-block;
overflow: hidden;
margin: 0 3em;
/**outline: solid 1px;/**/
width: 10em;
height: 10em;
transform: rotate(45deg);
-webkit-transform: rotate(45deg);
}
.trapezoid:before {
display: block;
background: red;
content: '';
}
.trapezoid:before {
width: 20em; height: 3em;
transform: rotate(-45deg) translate(-4.142em, -2.6em);
-webkit-transform: rotate(-45deg) translate(-4.142em, -2.6em);
}
For a simpler implementation, see this fiddle
HTML
<div></div>
CSS
div {
border-bottom: 100px solid red;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
height: 0;
margin-top:30px;
width: 100px;
}
A:
If by "how to transform" you mean how to rotate on the x axis applying a perspective to achieve deepness, then you can do it by using CSS3 transform's perspective and rotate3d:
Running example
HTML
<div class="box">
Hover me
</div>
CSS
.box{
width: 300px;
height: 100px;
background: silver;
font-size: 4em;
margin: 100px;
}
.box:hover{
transform : perspective(400px) rotate3d(1, 0, 0, 50deg);
}
You may wanna read this other answer too.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add a custom column which is not present in table in active admin in rails?
in my rails application, i have installed active admin. in users index page, by default, all columns are getting displayed(User table columns). I want to add a custom column called "become user" in this users index view (which is not a column in User's table). under this column i want to display user name as a hyperlink. up on clicking of that link the admin will be logged in to that particular user account. in order to implement this switching feature, i am using switch user gem. how to customise this view in Active Admin? and how to generate a link for all users in active admin
ActiveAdmin.register User do
permit_params do
permitted = [:email, :fname, :lname, :phone]
# permitted << :other if resource.something?
# permitted
end
# Filterable attributes on the index screen
filter :email
filter :fname
filter :lname
filter :phone
filter :current_sign_in_at
filter :created_at
# Customize columns displayed on the index screen in the table
index do
selectable_column
id_column
column :email
column :fname
column :lname
column :phone
column :current_sign_in_at
# column :sign_in_count
column :created_at
# actions
end
form do |f|
inputs 'Details' do
input :email
input :password
input :fname
input :lname
input :phone
end
actions
end
controller do
end
end
A:
You need to go with approach, that is called virtual attribute in your model:
class User < ApplicationRecord
def become_user
"I am a virtual attribute of this user"
end
end
Then add it to your ActiveAdmin setup
PS: check this for some additional details: Is there an easier way of creating/choosing related data with ActiveAdmin?
| {
"pile_set_name": "StackExchange"
} |
Q:
Can not catch assert call from native dll in .NET
I am using one function from native .dll in C# code and sometimes the following assert is calling:
#include <assert.h>
...
assert(e > 0.0);
But I can not catch it in my .NET application (it's just crashing). How can I handle this?
A:
At least by reading the Wiki:
When executed, if the expression is false (that is, compares equal to 0), assert() writes information about the call that failed on stderr and then calls abort().
And the MSDN
Evaluates an expression and, when the result is false, prints a diagnostic message and aborts the program.
so no exception... an error message and the program dies. Nothing to catch here :-)
Then we could talk about the difference in parameters handling between C and C#... In C you kill the program with an assert, in C# you throw a catcheable exception (ArgumentException)... Different methodologies :-)
Now, how to handle it? Don't cause assert to fail is a good method :-) assert are terminal errors (because even in C they can't be handled), so they shouldn't happen.
| {
"pile_set_name": "StackExchange"
} |
Q:
In photoshop 7, how do I change the font layer background color without rasterizing the layer?
In photoshop 7, how do I change the font layer background color without rasterizing the layer?
A:
Tough one, Photoshop 7 is almost 8 years old. I've to be honest, I'm not sure what you mean by font layer background color (UPDATE: now I know). A font layer is transparent by default, and the only color you can change is the color of the text/font itself (but I assume you know how to do that).
Layer effects were introduced in PS6 if I recall, but that's not going to help either because they are only affecting the pixels in the layer (here, the text).
In later PS versions you can transform a layer into a smart object, and apply the Invert filter to that smart layer; e.g. a black text on white would become a white text on a black background. Unfortunately, I tried and while you can transform a text layer into as mart object, you can't apply an Invert filter on it. An Invert Adjustment Layer with a layer mask is not working either. The whole issue here is that I don't think PS gives you access to the bounding box of a text layer. If you Control+Click on the layer, it will select the outline of the text, not its bounding box.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add fragment from ViewModel in MVVM architecture
I am using DataBinding and following MVVM architecture, now i am stuck on how to add new fragment from ViewModel as we need defined click event on ViewModel. Here is my MainViewModel class
public class MainViewModel {
private Context context;
public MainViewModel (Context context) {
this.context = context;
}
public void onClick(View v) {
}
}
here is my xml where i have defined click event
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="viewmodel"
type="com.example.MainViewModel" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{viewmodel::onClick}"
android:text="click me"/>
</RelativeLayout>
</layout>
now how can i get supportFragmentManager or childFragmentManager from my ViewModel class? I have tried to use activity.getSupportFragmentManager() and activity.getChildFragmentManager() but it doesn't have that kind of method.
I know we can add fragment with following code
getActivity().getSupportFragmentManager().beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out).
add(R.id.container, fragment, "").addToBackStack("main").commit();
but how to do it in ViewModel class
A:
Since you have your Context available, you have two possibilities:
public class MainViewModel {
private Context context;
public MainViewModel (Context context) {
this.context = context;
}
public void onClick(View v) {
//use context:
((AppCompatActivity) context).getSupportFragmentManager();
//OR use the views context:
if(v.getContext() instanceof AppCompatActivity) {
((AppCompatActivity) v.getContext()).getSupportFragmentManager();
}
}
}
It may be useful to check whether the context is an instance of your activity (like MainActivity) or AppCompatActivity, or if it is null before calling any method.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is this very simple return std::move(thread handle) failing?
#include <iostream>
#include <thread>
using namespace std;
thread&& launch(){
thread launchee([](){
this_thread::sleep_for(chrono::milliseconds(280));
cout<<"HA!"<<endl;
});
return move(launchee);
}
int main(int argc, char **argv){
thread mine(launch());
mine.join();
}
compiled with g++-4.6 -std=c++0x 1.cpp -o e1 -pthread
Outputs "terminate called without an active exception", then the program aborts.
This should work, shouldn't it??
A:
You want to return a thread by value, not an rvalue-reference:
std::thread launch() {
std::thread launchee([](){
std::this_thread::sleep_for(std::chrono::milliseconds(280));
std::cout<<"HA!"<<std::endl;
});
return launchee;
}
The reason is that std::move (and std::forward) are just a cast operation from an lvalue to an rvalue-reference, but unless you use that to actually move into some other object, the original object remains unmodified. In the original code you are then taking a reference to a local object and exiting the function, the std::thread inside the function is then destroyed and it calls terminate (as per contract of std::thread, for any other object it would just return a dangling reference to a destroyed object).
| {
"pile_set_name": "StackExchange"
} |
Q:
C# crop, scale, rotate image
I use a javascript client plugin for manipulate image inside the browser (JQuery Guillotine). After I will want manipulate the image with the server but I don't know which library can help me for do this job.
When I call the server I send these information:
{ scale: 1.4, angle: 270, x: 10, y: 20, w: 400, h: 300 }
A:
I would recommend the AForge.net imaging library. I've used it before and found it easy to implement, reliable and quick. It does everything, but you may find that it's overkill for what you need.
I used it in a kinect project that needed to measure the distance between a person's pupils. After finding the eye with the kinect I used this library to cut out the image of the eye, then apply several filters (and some other imaging magic) to pinpoint the center of the each pupil. This was occurring at about 30fps and this image processor (on a fairly decent machine) kept up with the demand and didn't miss a beat.
Or, seeing as you're just resizing, cropping and rotating, you could just use the System.Drawing libraries already built in to .net
Here are a few examples to get you started: http://dotnet-snippets.com/snippet/crop-and-resize-images/676
| {
"pile_set_name": "StackExchange"
} |
Q:
$A\in \mathrm{Mat}_n(\mathbb{Z})$ is the matrix representing $f$. Show that if $\mathrm{Coker}(f)$ is finite, then $|\det A|=|\mathrm{Coker}(f)|$.
Let $M$ be a free $\mathbb{Z}$-module of rank $n$, and $f:M\to M$ be a homomorphism of $\mathbb{Z}$-modules.
$A\in \mathrm{Mat}_n(\mathbb{Z})$ is the matrix representing $f$ with respect to a fixed $\mathbb{Z}$-basis of $M$.
Show that if $\mathrm{Coker}(f):=M/\mathrm{Im}(f)$ is finite, then $|\det A|=|\mathrm{Coker}(f)|$, and for a prime $p$ with $p\nmid |\mathrm{Coker}(f)|$ the induced map $f':M/pM\to M/pM$ is an isomorphism of
$\mathbb{Z}/(p)$-modules.
A:
The point is that by the structure theorem for finitely generated modules over a PID, you can make two separate base changes of $M$, so that with respect to the two new bases, the matrix of $f$ looks like
$$
D = \begin{bmatrix}
d_{1} \\
& d_{2}\\
&& d_{3}\\
&&& \ddots\\
&&&&d_{n}
\end{bmatrix}
$$
for integers $d_{i} > 0$ (as the cokernel is finite, see just below).
Thus
$$
\operatorname{Coker}(f)
\cong
\mathbb{Z} / d_{1} \mathbb{Z} \oplus \dots \oplus \mathbb{Z} / d_{n} \mathbb{Z}
$$
has order
$$
d_{1} \dots d_{n} = \det(D).
$$
Now if $S, T$ are the matrices of the two base changes, we will have
$$
S A T = D,
$$
so that
$$
\det(D) = \pm \det(A),
$$
as $S, T$ are invertible integer matrices.
| {
"pile_set_name": "StackExchange"
} |
Q:
Equal distance in \itemize
I am using \itemize environment to list my quantities. i.e.
\begin{itemize}
\item veloity = 20
\item Average velocity = 10
\end{itemize}
I dont want to put manual spaces to adjust '=' sign, because my quantity name is longer. Is there any solution or I am too lazy?
Document class is book.
Thnx for your time :)
A:
Below I defined the AlignedItemize enviroment to which you pass in the text that is the widest in that particular list. The \MakeBox then typsets the parameter to the appropriate width.
\begin{AlignedItemize}{Average velocity}
\item $\MakeBox{Velocity} = 20$
\item $\MakeBox{Average velocity} = 10$
\end{AlignedItemize}
yields:
Code:
\documentclass{article}
\usepackage{enumitem}
\usepackage{calc}
\newcommand*{\WidestText}{}%
\newcommand*{\MakeBox}[1]{\makebox[\widthof{\WidestText}][l]{#1}}
\newenvironment{AlignedItemize}[1]{%
\renewcommand*{\WidestText}{#1}%
\begin{itemize}
}{%
\end{itemize}%
}%
\begin{document}
\begin{AlignedItemize}{Average velocity}
\item $\MakeBox{Velocity} = 20$
\item $\MakeBox{Average velocity} = 10$
\end{AlignedItemize}
\end{document}%
| {
"pile_set_name": "StackExchange"
} |
Q:
Error starting app on Heroku using Devise
When pushing a new app to heroku, then running heroku rake db:migrate I get the following error:
heroku rake db:migrate
rake aborted!
Please install the postgresql adapter: `gem install activerecord-postgresql-adapter` (pg is not part of the bundle. Add it to Gemfile.)
Does anyone have any idea why it's asking for postgresql? In my gemfile the only db gem I'm using is sqlite.
This app is using Devise for authentication, that's the only gem out of the ordinary in the app's gemfile. On a sidenote, when I attempt to follow the advice, bundler throws:
Could not find gem 'activerecord-postgresql-adapter (>= 0)' in any of the gem sources listed in your Gemfile.
A:
you can't use sqlite3 on Heroku, you have to use their Postgres or use your own external Db.
In your gemfile do
group :development do
gem 'sqlite3'
end
group :production do
gem 'pg'
end
to let you use sqlite3 locally and postgres on Heroku.
| {
"pile_set_name": "StackExchange"
} |
Q:
GUI control with markdown capabilities at import/export
I'm not sure if this is the right Stack Exchange page to ask (perhaps Programmers is also suitable, although they oppose software-technical questions).
However, for a program that should act as a client to a internal knowledge database, I'm investigating Rich Text controls/widgets from different frameworks. This Rich Text control should display a subset of HTML. Only h1-h6, b, i, img (embedded or not), lists and simple tables are supported.
The text is saved in the data model as markdown code.
Now I need a control that displays this markup with online editing (just like text processors) and can save the contents again as markdown.
The client can be written in Python (with PyQt or wxPython) or C# with WinForms.
I've tested the Rich Text controls in these frameworks, but they were not suitable. WinForms' RichEditBox outputs strange RTF, the others some horribly formatted HTML.
Now I want to extend an existing control in such a way that it holds the contents as markdown in every given second.
Are there any good, open-sourced controls/widgets for the mentioned target platforms that could act as a good start?
A:
Your requirement seems like a bit of an edge case as markdown was specifically designed to be easily written by humans, for processing into other formats. You're doing the opposite, still...
I'm not aware of any WYSIWYG controls that save to Markdown, so you'll probably have to roll your own. What you can do is subclass an existing control and implement a persistence mechanism that fetches the control contents and generates Markdown. That will be tricky because most rich text or HTML editiors will support more features than Markdown does. You should be able to implement the control's input features to limit them to the supported subset in Markdown. There may be some Python projects that will help with the parsing. Pyth looks minimal, but could be useful.
There are plenty of Markdown to Format X converters, but the only tool I know that goes the other way is (Markdownify) which is in PHP.
| {
"pile_set_name": "StackExchange"
} |
Q:
Decompress a zip file with Swift
I made a game in Swift but I need to download .zip files on my website, and use the content (images) in game.
Actually, I download the .zip file and store it in documents, and I need to unzip the file into the same documents folder.
I tried marmelroy's Zip, iOS 9 Compression module and tidwall's DeflateSwift but none of these worked. It could be good if it was compatible with iOS 8.
A:
I recently released a Swift native framework that allows you to create, read and update ZIP archive files: ZIP Foundation.
It internally uses libcompression for great compression performance.
Unzipping a file is basically just one line:
try fileManager.unzipItem(at: sourceURL, to: destinationURL)
A full example with some context would look like this:
let fileManager = FileManager()
let currentWorkingPath = fileManager.currentDirectoryPath
var sourceURL = URL(fileURLWithPath: currentWorkingPath)
sourceURL.appendPathComponent("archive.zip")
var destinationURL = URL(fileURLWithPath: currentWorkingPath)
destinationURL.appendPathComponent("directory")
do {
try fileManager.createDirectory(at: destinationURL, withIntermediateDirectories: true, attributes: nil)
try fileManager.unzipItem(at: sourceURL, to: destinationURL)
} catch {
print("Extraction of ZIP archive failed with error:\(error)")
}
The README on GitHub contains more information. All public methods also have full documentation available via Xcode Quick Help.
I also wrote a blog post about the performance characteristics here.
A:
I just find the following library called Minizip. Try it
You can use Zip framework to unZip your file using Swift. Simply written in Swift
Sample Code
do {
let filePath = NSBundle.mainBundle().URLForResource("file", withExtension: "zip")!
let unzipDirectory = try Zip.quickUnzipFile(filePath) // Unzip
let zipFilePath = try Zip.quickZipFiles([filePath], fileName: "archive") // Zip
}
catch {
print("Something went wrong")
}
If not works for minizip, you can go with ZipArchive, its not written in swift but in Objective-C
A:
I got it work with SSZipArchive and a bridging header:
Drag & drop the SSZipArchive directory in your project
Create a {PROJECT-MODULE-NAME}-Bridging-Header.h file with the line import "SSZipArchive.h"
In Build Settings, drag the bridging header in Swift Compiler - Code generation -> Objective-C Bridging Header.
Use SSZipArchive in your Swift code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Text Translator API keys expiring
I recently migrated the old Microsoft Translator API to the new Azure portal APIs and created one Text Translator API resource with Pay-As-You-Go subscription and S1 pricing tier. I created the 2 keys and both were working fine last Friday (01/27) but now I get a lot of errors and messages. One of them says: Reason - The key used is expired.
So, some questions about that:
Where do I see the expiration date of my keys?
How can I get keys that don't expire or autoregenerate?
[Bonus question] What's the difference between KEY 1 and KEY2 (I see both work the same)
Thanks!
A:
There were authentication issues occurring that have since been resolved.
1 & 2 Keys do not expire on a pay as you go plan.
There actually is no difference between key 1 & 2, they both will pull from the same allowance/quota. One can be used as a backup.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set opacity on UICollectionView background without affect opacity of UICollectionViewCell?
I have set the color of a UICollectionView with an image pattern like so:
self.collectionView.backgroundColor = [UIColor colorWithPatternImage:image];
I would like to set the alpha of the collectionView without affecting the alpha of the UICollectionViewCell. Is there a way to do this? Setting the alpha of collectionView also affects the UICollectionViewCell, so I already tried that. What else should I try/what else will actually work?
Thanks for any tips.
A:
Use the -colorWithAlphaComponent: method of UIColor:
[self.collectionView setBackgroundColor:[[UIColor redColor] colorWithAlphaComponent:0.5]];
This will result in only the background having a non-1 alpha value.
A:
If you only want to change the opacity without changing the color or need to keep track of the color itself, you can use:
self.collectionView.backgroundColor = [self.collectionView.backgroundColor colorWithAlphaComponent:0.5f];
There are two possible "backgrounds" on UICollectionView that you may want to change the opacity of. The backgroundColor property is the simplest, but only changes the full color background. There's also the backgroundView which can have subviews which will not change opacity if you just change the background color opacity. You can change the opacity of the backgroundView with:
self.collectionView.backgroundView.alpha = 0.5f;
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding two xmls. Working with XSLT transformer
I am looking for solution for a scenario which is troubling me a lot.
I am working on mule 3.3.
I have some incoming XML and a second XMLcoming from the enricher.
Now the xml from the enricher is to be added into my input XML.
My flow looks like below (abstract)
<flow name="main" >
<file:inbound ....>
<enricher target="#[variable:myProperty]">
<vm:outbound .... />
</enricher>
<xslt transformer .... />
.......
.......
<file:outbound ..>
</flow>
My Mule Flow part and the XSL as given below
<mulexml:xslt-transformer maxIdleTransformers="2" maxActiveTransformers="5" xsl-file="C:\NSBTransformerXSL.xsl" outputEncoding="UTF-8" doc:name="XSLT">
<mulexml:context-property key="RefXML" value="#[header:INVOCATION:RefXML]" />
</mulexml:xslt-transformer>
My XSL is given below
<xsl:param name="RefXML"></xsl:param>
<xsl:template match="@*|node()">
<xsl:copy >
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="TXRequest">
<xsl:copy copy-namespaces="no" >
<xsl:apply-templates select="@* | node()"/>
<xsl:copy-of select="$RefXML"/>
</xsl:copy>
</xsl:template>
Thanks..
A:
Use an XSL-T transformer and pass the XML fragment you got from the enricher to your XSL as a named parameter.
That way you can easily combine two XMLs.
The correct way of doing this would be to parse RefXML as a DOM element, then pass it as an XSL parameter, but a bug in Mule prevents this :(
So the only option is a verbatim copy of the string value of RefXML:
<xsl:value-of select="$RefXML" disable-output-escaping="yes" />
Not super satisfying but it works.
| {
"pile_set_name": "StackExchange"
} |
Q:
Physical Interpretation of Gibbs Free Energy
I know that $\Delta G = \Delta H - T\Delta S$ and that if $\Delta G$ less than $0$ a reaction will be spontaneous. What I am wondering is what is the actually physical interpretation of Gibbs free energy. I mean, if the Gibbs free energy of a particular reaction $20\ \mathrm{J\ mol^{-1}}$, what does that actually mean?
A:
Gibbs free energy is a measure of the total non-expansionary work that a system can do. So in the case of your example, that system has the potential to do 20 joules of non-expansionary work per a mole of substance. Non-expansionary work refers to work other than pressure-volume work, such as electrical work. Hence not only is Gibbs free energy is important to tell whether a reaction will be spontaneous or not, it is also important to engineers as they tell how much non-expansionary work a system, such as motor engine, can do.
Gibbs free energy is really derived is from the Clausius inequality which is: $$dS\geq \frac{dq}{T}$$ Basically is states that in a reaction, the change in entropy must always be equal (in the case of an ideal gas) or greater than the transfer of heat energy divided by temperature. Therefore, for a reaction to be spontaneous, the following relation must be satisfied: $$dS-\frac{dq}{T}\geq0$$ Now, lets assume that the pressure is constant so we can simplify this relation.
Constant Pressure
Enthalpy is given by: $$\Delta H_p = \Delta U + p\Delta V$$
and internal energy by: $$\Delta U = q + w$$
Now by substituting $\Delta U$ in the expression for enthalpy we get: $$\Delta H _p= q + w + p\Delta V$$ Now, since w = $-p\Delta V$, the above equation simplified so that: $$\Delta H_p = q$$ So, now in the Clausius inequality, we can substitute dq with dH and multiply by $T$ to get: $$TdS \geq dH$$ Now by integrating both sides and putting all the variables on one side, we get the question for gibbs free energy: $$\Delta G = \Delta H - T\Delta S$$ and hence this is why $\Delta G$ has to be negative for a reaction to be spontaneous
A:
I'm going to concentrate on the $T\,S$ term (which you likely find the most mysterious) and hopefully give a little more physical intuition.
The $T S$ term arises roughly from the energy that is needed to "fill up" the rotational, vibrational, translational and otherwise distractional thermal energies of the constituents of a system. Simplistically, you can kind of think of its being related to the idea that you must use some of the energy released to make sure that the reaction products are "filled up" with heat so that they are at the same temperature as the reactants. So the $T S$ term is related to, but not the same as, the notion of heat capacity: let's look at this a bit further.
Why can't we get at all the energy $\Delta H$? Well, actually we can in certain contrived circumstances: let's look at these circumstances to find out why in a meaningful definition we must leave behind an amount $T\,\Delta S$. Let's think of the burning of hydrogen:
$$\ce{H2 + 1/2 O2 -> H2O};\quad\Delta H \approx 143\:{\rm kJ\,mol^{-1}}\tag{1}$$
This is a highly exothermic reaction, and also one of the reactions of choice if you want to throw three astronauts, fifty tons of kit and about a twentieth of the most advanced-economy-in-the-world’s-1960s GDP at the Moon.
The thing about one mole of $\ce{H2O}$ is that it can soak up less heat than the mole of $\ce{H2}$ and half a mole of $\ce{O2}$; naively this would seem to say that we can get more heat than the enthalpy change $\Delta H$, but we'll see this is not so. We imagine a thought experiment, where we have a gigantic array of enormous heat pads (all individually like an equilibrium “outside world") representing all temperatures between absolute zero and $T_0$ with a very fine temperature spacing $\Delta T$ between them. On my darker days I find myself imagining an experimental kit that looks eerily like a huge pallet on wheels of mortuary shelves, sliding in and out as needed by the experimenter! We bring the reactants into contact with the first heat pad, which is at a temperature $T_1 = T_0 - \Delta T$ a teeny-tiny bit cooler than $T_0$ thus reversibly drawing some heat $\Delta Q(T_1)$ off into the heat pad. Next, we bring the reactants into contact with the second heat pad at temperature $T_2 = T_0 - 2\,\Delta T$, thus reversibly drawing heat $\Delta Q(T_2)$ off into that heat pad. We keep cooling then shifting to the next lowest heat pad until we have visited all the heat pads and thus sucked all the heat off into our heat pads: see my sketch below:
Now the reactants are at absolute zero. There is no heat needed to "fill them up" to their temperature, so we can extract all the enthalpy $\Delta H$ from the reaction as useful work. Let's imagine we can put this work aside in some ultrafuturistic perfect capacitor, or some such lossless storage for the time being.
Now we must heat our reaction products back up to standard temperature, so that we know what we can get out of our reaction if the conditions do not change. So, we simply do the reverse, as sketched below:
Notice that I said that $\ce{H2O}$ soaks up less heat than the reactants. This means that, as we heat the products back up to standard temperature, we take from the heat pads less heat in warming up the water than we put into them in cooling the reactants down.
So far, so good. We have gotten all the work $\Delta H$ out into our ultracapacitor without losing any! And we're back to our beginning conditions, or so it seems! What's the catch?
The experimental apparatus that let us pull this trick off is NOT back at its beginning state. We have left heat in the heat pads. We have thus degraded them: they have warmed up ever so slightly and so cannot be used indefinitely to repeatedly do this trick. If we tried to do the trick too many times, eventually the heat pads would be at ambient temperature and would not work any more.
So we haven’t reckoned the free energy at the standard conditions, rather we have simply calculated the free energy $\Delta H$ available in the presence of our unrealistic heat sink array. To restore the system to its beginning state and calculate what work we could get if there were no heat sink array here, we must take away the nett heat flows we added to all the heat pads and send them into the outside World at temperature $T_0$. This is the only "fair" measure, because it represents something that we could do with arbitrarily large quantities of reactants without the presence of artificial, finite resources like heat pad arrays.
But the outside World at $T_0$ is warmer than any of the heat pads, so of course this heat transfer can’t happen spontaneously, simply by dent of Carnot’s statement of the second law!
We must therefore bring in a reversible heat pump and use some of our work $\Delta H$ to pump this heat into the outside world to restore standard conditions: we would connect an ideal reversible heat pump to each of the heat pads in turn and restore them to their beginning conditions, as sketched below:
This part of the work that we use to run the heat pump and restore all the heat pads, if you do all the maths, is exactly the $T\,\Delta S$ term.
The above can also cast some light on an endothermic reaction. In such a reaction, we imagine having an energy bank that we can borrow from temporarily. After we have brought the products back up to temperature, we find we have both borrowed $-\Delta H$ from the energy bank and put less heat back into the heat pads than we took from them. So heat can now flow spontaneously from the environment to the heat pads to restore their beginning state, because the heat pads are all at a lower temperature than the environment. As this heat flows, we can use a reversible heat engine to extract work from the heat flowing down the gradient. This work is, again, $-T\,\Delta S$, which is a positive work gotten from the heat flowing down the temperature gradient. The $-T\,\Delta S$ can be so positive that we can pay back the $\Delta H$ we borrowed and have some left over. If so, we have an endothermic reaction, and a nett free energy: this energy coming from the heat flowing spontaneously inwards from the environment to fill the higher entropy products (higher than the entropy of the reactants). A good thought experiment here is to imagine towing an iceberg into warmer latitudes, and then putting it into contact with the outside world through heat engines which convert a fraction $1-T_\mathrm i/T_\mathrm o$ of the heat flowing into work.
Take heed that, in the above, I have implicitly assumed the Nernst Heat Postulate -the not quite correct third law of thermodynamics - see my answer here for more details. For the present discussion, this approximate law is well good enough.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why can you mix Partial Derivatives with Ordinary Derivatives in the Chain Rule?
This question is a simplified version of this previous question asked by myself.
The following is a short extract from a book I am reading:
If $u=(x^2+2y)^2 + 4$ and $p=x^2 + 2y$ $\space$ then $u=p^2 + 4=f(p)$ therefore $$\frac{\partial u}{\partial x}=\frac{\rm d f(p)}{\rm d p}\times \frac{\partial p}{\partial x}=2xf^{\prime}(p)\tag{1}$$ and $$\frac{\partial u}{\partial y}=\frac{\rm d f(p)}{\rm d p}\times \frac{\partial p}{\partial y}=2f^{\prime}(p)\tag{2}$$
I know that the chain rule for a function of one variable $y=f(x)$ is $$\begin{align}\color{red}{\fbox{$\frac{{\rm d}}{{\rm d}x}=\frac{{\rm d}}{{\rm d}y}\times \frac{{\rm d}y}{{\rm d}x}$}}\color{red}{\tag{A}}\end{align}$$
I also know that if $u=f(x,y)$ then the differential is
$$\begin{align}\color{blue}{\fbox{${{\rm d}u=\frac{\partial u}{\partial x}\cdot{\rm d} x+\frac{\partial u}{\partial y}\cdot{\rm d}y}$}}\color{blue}{\tag{B}}\end{align}$$
I'm aware that if $u=u(x,y)$ and $x=x(t)$ and $y=y(t)$ then the chain rule is $$\begin{align}\color{#180}{\fbox{$\frac{\rm d u}{\rm d t}=\frac{\partial u}{\partial x}\times \frac{\rm d x}{\rm d t}+\frac{\partial u}{\partial y}\times \frac{\rm d y}{\rm d t}$}}\color{#180}{\tag{C}}\end{align}$$
Finally, I also know that if $u=u(x,y)$ and $x=x(s,t)$ and $y=y(s,t)$ then the chain rule is $$\begin{align}\color{#F80}{\fbox{$\frac{\partial u}{\partial t}=\frac{\partial u}{\partial x}\times \frac{\partial x}{\partial t}+\frac{\partial u}{\partial y}\times \frac{\partial y}{\partial t}$}}\color{#F80}{\tag{D}}\end{align}$$
Could someone please explain the origin or meaning of equations $(1)$ and $(2)$?
The reason I ask is because I am only familiar with equations $\color{red}{\rm (A)}$, $\color{blue}{\rm (B)}$, $\color{#180}{\rm (C)}$ and $\color{#F80}{\rm (D)}$ so I am not used to seeing partial derivatives mixed up with ordinary ones in they way they were in $(1)$ and $(2)$.
Many thanks,
BLAZE.
A:
This is often confusing because there is a conflation of the symbol for a function argument as opposed to a function itself. For example, when you write $f(p) = p^2 + 4$, you are thinking of $f$ as a function and $p$ as the argument of that function, which could be any dummy variable. In fact, let us write $f(\xi) = \xi^2+4$, which is the same function with simply another symbol representing the rule that $f$ implies. At the same time, you are using the symbol $p$ as a function $p(x,y) = x^2 + 2y$. Now, with the functions $f(\xi)$ and $p(x,y)$ you have $u(x,y) = f \circ p\,(x,y)$; that is, $u$ is the composition of $f$ with $p$. Hence, using the chain rule and suppressing the variables $x$ and $y$, you have
$$
\frac{\partial u}{\partial x} = f'(p)\, \frac{\partial p}{\partial x} = \frac{d f}{d \xi} (p) \, \frac{\partial p}{\partial x}
$$
where $f' = \frac{d f}{d \xi}$ since we changed the argument symbol of $f$ to $\xi$ -- notice that $\frac{d f}{d\xi}$ is still evaluated at the function $p$ by the chain rule. If we wanted to to explicitly show where the variables $x$ and $y$ would manifest, we would have
$$
\frac{\partial u}{\partial x}(x,y) = f'(p(x,y))\, \frac{\partial p}{\partial x}(x,y) = \frac{d f}{d \xi} (p(x,y)) \, \frac{\partial p}{\partial x}(x,y).
$$
Hopefully this helps.
A:
The given function $u$ has two variables $x$ and $y$. So, it makes sense to talk about partial derivatives $\frac{\partial u}{\partial x}$ and $\frac{\partial u}{\partial y}$. While you take another 'variable' $p$ for $u$, then you have a function of one variable, but which is dependent of other two variables, and so is $u$ then.
In other words you have: $$\frac{\partial u(p(x,y))}{\partial x}=\frac{\partial u(p)}{\partial p}\frac{\partial p(x,y)}{\partial x}$$ and $$\frac{\partial u(p(x,y))}{\partial y}=\frac{\partial u(p)}{\partial p}\frac{\partial p(x,y)}{\partial y}.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Display attached pdf in browser within iframe - rails
I have module which had a attachments functionality which uploads pdf files.
I need to display stored pdf in the app within the browser/iframe and without downloading it. Is there a gem or chance which will show/read pdfs in rails.
Note : The pdfs will contain images,text content etc.
Thanks in advance
Ranjit
A:
yes, there is a gem is named Prawn in github. Check it out.
But there is more flexible way to implement this feature with Google Docs. You can embed your pdf with google docs viewer.
Simply:
<a href="https://docs.google.com/gview?url={YOUR_PDF_URL}&embedded=true">Your Pdf Viewer</a>
Thanks.
A:
In your controller define a function like the following:
def show_pdf
pdf_filename = File.join(Rails.root, "tmp/my_pdf_doc.pdf")
send_file(pdf_filename, :filename => "your_document.pdf", :disposition => 'inline', :type => "application/pdf")
end
In your environment config (developemnt.rb/production.rb)file :
config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
The config modification enables the web server to send the file directly from the disk.
You can have a look at this question Recommended way to embed PDF in HTML?
A:
This worked for me:
In the 'show.hmtl.erb'
<iframe src=<%= @certificate.certificate_pdf %> width="600" height="780" style="border: none;"> </iframe>
just put the embedded ruby of the file as the source worked for me after hours and hours of searching. 'certificate' is my model, and 'certificate_pdf' is my attachment file.
| {
"pile_set_name": "StackExchange"
} |
Q:
SVG hovers with fallbacks
What is the bestpractice, when I need to have SVG images with SVG hovers with fallbacks?
I mean SVG images with PNG fallbacks (normal, reaponsive 2x, 3x), and change them on hover to other SVG images with PNG fallbacks?
Is it better to use <img /> or <picture> + <source /> + <img /> tag with jQuery (or vanilla, but I already use jQuery), or to have it all in CSS as backgrounds? If jQuery, does it mean swapping srcsets? If CSS, how do I best include @2x and @3x image versions?
Also, how does the used method affect preloading of the hovers? It would surely be much better without blinking.
So far I have this, I need to change them on hover to 1hov.svg, 1hov.png, [email protected], [email protected]
<a href="#">
<picture>
<source type="image/svg+xml" srcset="logos/1.svg">
<img src="logos/1.png" srcset="logos/[email protected] 2x, logos/[email protected] 3x" alt="logo">
</picture>
</a>
A:
Here is a HTML + jQuery solution I found. It swaps the src and sourcesets to their hover alternatives. Includes the hovers preloading.
HTML
<a href="#" target="_blank">
<picture>
<source type="image/svg+xml" srcset="logos/1.svg" data-swap-srcset="logos/1hov.svg">
<img src="logos/1.png" data-swap-src="logos/1hov.png"
srcset="logos/[email protected] 2x, logos/[email protected] 3x" data-swap-srcset="logos/[email protected] 2x, logos/[email protected] 3x" alt="logo">
</picture>
</a>
jQuery
//preload hovers
$("source[data-swap-src]").each(function(){
$('<img/>')[0].src = $(this).attr("data-swap-src");
});
$("img[data-swap-src]").each(function(){
$('<img/>')[0].src = $(this).attr("data-swap-src");
$('<img/>')[0].srcset = $(this).attr("data-swap-srcset");
});
$("a").hover(function(){
var newone = $(this).find("img").attr("data-swap-src");
$(this).find("img").attr("data-swap-src", $(this).find("img").attr("src"));
$(this).find("img").attr("src", newone);
newone = $(this).find("img").attr("data-swap-srcset");
$(this).find("img").attr("data-swap-srcset", $(this).find("img").attr("srcset"));
$(this).find("img").attr("srcset", newone);
newone = $(this).find("source").attr("data-swap-srcset");
$(this).find("source").attr("data-swap-srcset", $(this).find("source").attr("srcset"));
$(this).find("source").attr("srcset", newone);
}
);
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditional if statement ($post->ID == get_the_ID) not working
The following code should read: If the current custom post type (bbp_forum), is the one being displayed, assign the class 'current' to its respective <li> tag. But for some reason the class 'current' (to highlight the current bbp_forum link) is being displayed in all the <li> tags:
<body <?php body_class(); ?>>
<div id="wrapper" class="hfeed">
<div id="header">
<div id="masthead">
<div id="branding" role="banner">
<h1><a href="<?php echo home_url( '/' ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
</div><!-- #branding -->
<div id="access" role="navigation">
<?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) ); ?>
</div><!-- #access -->
</div><!-- #masthead -->
<ul id="forums">
<?php global $post; $cat_posts = get_posts('post_type=bbp_forum');
foreach($cat_posts as $post) : ?>
<li <?php if($post->ID == get_the_ID()){ ?>class="current" <?php } ?>>
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a>
</li>
<?php endforeach; ?>
</ul><!-- #access -->
</div><!-- #header -->
<div id="main">
Any suggestions?
A:
The expression will always be true. Take a look at get_the_ID();
function get_the_ID() {
global $post;
return $post->ID;
}
So your code is effectively running as;
if ( $post->ID == $post->ID ) // always true!
Instead, cache the ID of the main post in a variable, then compare that instead.
<?php
global $post;
/**
* @var int Current post ID.
*/
$the_post_ID = $post->ID;
/**
* @var array All posts for bbp_forum.
*/
$cat_posts = get_posts('post_type=bbp_forum');
?>
<?php foreach ( $cat_posts as $post ) : ?>
<li<?php if ( $post->ID == $the_post_ID ) echo ' class="current"'; ?>>
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a>
</li>
<?php endforeach; ?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Derivation of the radial momentum operator
I have been studying Quantum Mechanics and when my book was going through the Hydrogen wave equation, it was talking about this equation:
$$ \frac{p_r^2}{2\mu} +\frac{L^2}{2\mu r^2}+V(r)=E$$
I completely understand how they got to this formula, but then they said they could use the above equation to write Schrodinger's equation for spherical coordinates using de Brogie's relations and appropriate operators. My book then said finding said operators is a "lengthy though not particularly difficult exercise." It then said that the appropriate operator for pr2 is the next equation:
$$(p_r^2)_{op}=-\hbar^2\frac{1}{r^2}\frac{\partial}{\partial r}(r^2\frac{\partial}{\partial r})$$
I am fairly new to operators so I tried to derive this operator. My result was:
$$(p_r^2)_{op}=-\hbar^2 r\frac{\partial}{\partial r}(r\frac{\partial}{\partial r})$$
I realize this result is wrong, and from reading other forums, I'm pretty sure I got the above result from finding the radial component of the momentum operator and then just operating on itself or in essence "squaring" it. This leaves me completely lost on how to get the correct equation from my book. If somebody could help me understand how I can derive the proper operator that would be great.
A:
The correct radial momentum operator is in fact
$$p_{r} = -i\hbar\left(\frac{\partial}{\partial r} + \frac{1}{r}\right)$$
This is hermitian. And as you rightly point out, squaring it does indeed yield the radial part of the Laplacian (times $-\hbar^2$):
$$p_r^2 \psi = -\hbar^2\left(\frac{\partial}{\partial r} + \frac{1}{r}\right)\left(\frac{\partial\psi}{\partial r} + \frac{\psi}{r}\right) = -\hbar^2\left(\frac{\partial^2\psi}{\partial r^2} + \frac{2}{r}\frac{\partial\psi}{\partial r}\right) $$
You might find this related post useful. The derivation of the above radial momentum operator can be found in this paper, though I should add that this particular result is well known (see for instance, the QM textbook by R. Shankar, e.g. the excerpt at https://books.google.com/books?id=sDvrBwAAQBAJ&lpg=PP1&pg=PA216#v=onepage&q=radial%20momentum&f=false).
Edit: The point here is that the ''usual'' operator $-i\hbar\frac{\partial}{\partial r}$ is not hermitian.
| {
"pile_set_name": "StackExchange"
} |
Q:
DFS over string trie (prefix)
I wrote the following prefix trie:
class TrieNode {
char letter;
HashMap<Character,TrieNode> children;
boolean fullWord;
TrieNode(char letter) {
this.letter = letter;
children = new HashMap<Character, TrieNode>();
this.fullWord = false;
}
}
class Tree{
static TrieNode createTree() {
return (new TrieNode('\0'));
}
static void insertWord(TrieNode root, String word) {
int l = word.length();
char[] letters = word.toCharArray();
TrieNode curNode = root;
for (int i = 0; i < l; i++) {
if (!curNode.children.containsKey(letters[i]))
curNode.children.put(letters[i], new TrieNode(letters[i]));
curNode = curNode.children.get(letters[i]);
}
curNode.fullWord = true;
}
}
I would like to add DFS method in order to find the first node that has more than 1 child (so it will show me the longest common prefix).
I wrote this code:
static void DFS(TrieNode node) {
for (TrieNode tn: node.children.values()){
DFS(tn);
if (node.children.size()>2)
System.out.println("found the first vertex");
}
}
But it doesn't work. What am I doing wrong?
A:
Well, first we need to clarify that longest common prefix here means the longest common prefix of any two or more strings in the trie tree.
So, your DFS method won't work well because it simply traverse the whole tree and will output "found the first vertex" on visiting any node whose children.size() > 2 (It should be >=2 here)
What we want here is finding the longest common prefix only. So we need some extra information about which is the longest one. It's easy to see that in my example above:
root --depth: 0
|
a --depth: 1
|
b --depth: 2
/ \
c f --depth: 3
/|\
d g k --depth: 4
\
k --depth: 5
The longest common prefix node has children.size()>1 AND has max depth. In this case, it's node c
So here's one possible correct DFS:
static int max=-1;
static TrieNode maxNode=null;
static void dfs(TrieNode node, int depth){
if(node.children.size()>1 && depth>max){
max=depth;
maxNode=node;
}
for (TrieNode tn: node.children.values())
dfs(tn,depth+1);
}
public static void test(){
TrieNode root = Tree.createTree();
Tree.insertWord(root, "abcd");
Tree.insertWord(root, "abcg");
Tree.insertWord(root, "abckk");
Tree.insertWord(root, "abf");
dfs(root,0);
System.out.println("Max node:"+maxNode.letter);
}
After running of dfs, the maxNode will hold the node which longest common prefix stops. it's node c in this case.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding all selforthogonal indecomposable modules
Given a finite dimensional algebra $A$ with finite global dimension such that there are only finitely many basic tilting modules. Then every selforthogonal indecomposable module $M$ (that is a module with $\mathrm{Ext}_A^i(M,M)=0$ for all $i \geq 1$) is a direct summand of a tilting module and thus there are only finitely many such indecomposable selforthogonal modules. See 3.9 in https://arxiv.org/abs/1803.10707.
Question 1: Is there an effective method to obtain every indecomposable selforthogonal module in a nice way? For example using the GAP-package QPA.
(A nice method would for example be an "Auslander-Reiten" theory for indecomposable selforthogonal modules in such algebras, where one can obtain every such module using certain exact sequences starting from just one such module.)
Question 2: Is there an example of an Auslander algebra with infinitely many selforthogonal indecomposable modules?
A:
Concerning your second question, it is claimed in the proof of Corollary 4.8 in a recent preprint by Iyama-Zhang that Kajita showed in his Master's
thesis that the Auslander algebra of the linearly oriented path with at
least 6 vertices has infinitely many classical tilting modules.
So it has in particular infinitely many indecomposable selforthogonal modules.
Let's now turn to the first question.
Considering the set $\mathfrak{T}$ of (isomorphism classes of basic) tilting $A$-modules with the partial order induced by the inclusion order of the corresponding perpendicular subcategories, $\mathfrak{T}$ becomes a finite lattice.
According to Happel-Unger there is an arrow $T \to T'$ in the Hasse diagram of $\mathfrak{T}$ if and only if $T = X \oplus M$ and $T' = Y \oplus M$ with $X$, $Y$ indecomposable fitting into an exact sequence
$$
0 \to X \xrightarrow{f} M' \xrightarrow{g} Y \to 0
$$
where $f$ is a minimal left and $g$ a minimal right $\mathrm{add}(M)$-approximation.
Given that QPA can compute minimal approximations, we can start with the set $\{P_1,\ldots,P_n\}$ of indecomposable projective $A$-modules and use BFS (or another graph-traversal algorithm) to find all sets $\{T_1,\ldots,T_n\}$ of indecomposable $A$-modules such that $T = \bigoplus_i T_i$ is a tilting module.
The union of all these sets $\{T_1,\ldots,T_n\}$ is then the set of indecomposable selforthogonal $A$-modules.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible with JQuery to have one image fade out & another fade in on top of each other without having to mess with their positioning?
I think the best way to demonstrate this is with a jsfiddle example. As you may notice from this example, the first image does fade out as the second one fades in, but the second image also pushes the first image down. After that, the image that is currently displayed will instantly disappear when the next image starts to fade in. Also, StackOverflow demands code with jsfiddle links, so here's my HTML:
<div id="slideshow">
<img width="400px" src="https://consumermediallc.files.wordpress.com/2014/11/totinos-stock-08-2014.jpg" alt="" />
<img src="https://36.media.tumblr.com/66fa7962b68e90da541078fcc9efdc25/tumblr_inline_nnby3oQs8s1si7eaa_500.jpg" alt="Lightning Ghost" />
<img src="http://ak-hdl.buzzfed.com/static/2014-05/enhanced/webdr02/14/7/enhanced-3829-1400068353-2.jpg" alt="Girraffe-dog" />
<img src="https://www.colourbox.com/preview/2291250-terrible-grimace-men-with-shovel.jpg" alt="Purpleish Kitty" />
</div><!--slideshow-->
and here's my JQuery:
$(function () {
//make the div take up the space given
$('div#slideshow').width('100%');
//make each slide fits within that div easily
$("div#slideshow > img").width("60%");
//hide the first image
$('#slideshow img:gt(0)').hide();
setInterval(function () {
//put each slide up for six seconds and cause it to fade out while the
//new one fades in over a period of two seconds
$('#slideshow :first-child').fadeTo(2000, 0)
.next('img').fadeTo(2000, 1).end().appendTo('#slideshow');
}, 6000);
});
I want the images to transition on top of each other evenly, but I want to do that without modifying the CSS position style properties of the parent div and it's images. The reason I don't like formatting the images to have the position:absolute property is because it separates the slideshow from the webpage. I don't like having to reposition the slideshow every time I change something on my webpage. I greatly appreciate any help you can give, even if you can clarify that what I'm asking for is impossible.
A:
Just add this CSS. I know that you didn't want to use positioning but there is no way around it. However, by setting position:relative on the #slideshow div the img elements are absolutely positioned relative to the #slideshow container which means you can move the #slideshow container anywhere and the img elements will follow.
slidshow{
position: relative;
}
slideshow img{
position: absolute;
top:0;
left:0;
}
Here is the modified fiddle: https://jsfiddle.net/75wczrw7/5/
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between apache camel multicast and recipent-list patterns?
So, after reading some documentation and getting a lot of help from you guys here, I finally implemented a recipient list that chooses the endpoints dynamically (a dynamic recipient list):
http://camel.apache.org/recipient-list.html
http://camel.apache.org/recipientlist-annotation.html
In my code, MainApp_A generates reports every 10 seconds, and I want it to send the reports to all the servers at the same time, instead of doing it one by one. Thus I have developed the following route.
MainApp_A
main.addRouteBuilder(new RouteBuilder(){
@Override
public void configure() throws Exception {
from("direct:start").multicast().parallelProcessing()
.beanRef("recipientListBean", "route").end()
.log("${body}");
}
});
RecipientListBean
@RecipientList
public Set<String> route(String body) {
return servers; //returns a collection of several severs
}
I also checked the documentation for the Multicast pattern and the Dynamic route:
http://camel.apache.org/multicast.html
http://camel.apache.org/dynamic-router.html
Now I have a few questions and I am confused. So I have a few questions:
Is the recipient dynamic list simply the junction of the Multicast pattern with the Dynamic Route Pattern?
the multicast() call alone is purely sequential right? What is the difference between using multicast() and recipientList()?
For both multicast() and recipientList() to be concorrent I have to use parallelProcessing(). In my case, which is more efficient?
A:
The dynamic router is used to evaluate which endpoints to send a specific message to at runtime, one endpoint at a time. Recipient List is a set of endpoints to send the very same message to.
I recommend you to read EAI patterns by Gregor Hohpe and Bobby Woolf for some background and insight.
http://www.eaipatterns.com/
Multicast allows a hard coded recipient list and recipientList(..) allows endpoints computed at runtime. Both are "recipient lists".
They will likely be equally efficient, if you don't have a lot of logic (say DB lookups) computing the endpoints in the recipient list - the invocation of the endpoints is likely by far the hardest part for Camel. Anyway - a static "multicast" is more readable.
In Camel, a reason for choosing one construct over another is often readability of the route. You should be able to look at a route and follow what it does (given you know EIP). At least, that's a good aim.
| {
"pile_set_name": "StackExchange"
} |
Q:
Opposite of ax.scatter.remove()?
I have a scatter plot in matplotlib
import matplotib.pyplot as plt
fig, ax = plt.subplots()
scatter = ax.scatter([0], [0])
scatter.remove() # remove the scatter from figure
Is there a method of scatter to add it (back) to the figure?
A:
The scatter is a matplotlib.collections.PathCollection. To add such a collection to an axes use ax.add_collection:
ax.add_collection(scatter)
Complete example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
scatter = ax.scatter([0], [0])
scatter.remove()
ax.add_collection(scatter)
plt.show()
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL71501 - How to Suppress this Error
My team/company tried out SSDT for a few small projects and we were quite impressed.
Recently we investigated use of SSDT for one of our larger existing applications and got FLOODED with SQL71501 errors for external database references.
There is quite a web of database coupling for the application, so that is understandable.
Is there some way to suppress/disable/turn off this check so a SSDT project can build regardless of these unresolved references?
Most discussion on this Error Code incorrectly describe it as a warning, not an Error.
Visual Studio 2015 Enterprise - latest SSDT pack
SQL 2008
A:
I was just about to cleanup a few of these in my solution after upgrading to a new version of sql server. I'm on VS2017 but I think this was the same.
If you have database projects in the solution already for the referenced databases, then you can just add database references to the project throwing the errors. If you already have these references, edit the reference properties and set Suppress Reference Warnings to true.
[EDIT: Suppress Reference Warnings seems to have no affect on invalid references.]
If you don't have database projects for the solutions, you will need to add them. You won't necessarily need to fill them in with all of the database object if you check the Suppress Reference Warnings box.
Good luck!
| {
"pile_set_name": "StackExchange"
} |
Q:
Как добавить клас active к текущей ссылке после перехода по ней, а в предыдущей забрать
Я использую ruby on rails, есть шаблон для меню, на каждую страницу.
На классе active висить css чтоб стилизовать текущую ccылку.
Вопрос: как добавить класс "active" после клика к ccылке, а в предыдущей забрать?
<div class="l-mnu">
<ul>
<li class="l-cat active"><%= link_to "Нове", root_path %></li>
<li class="l-cat"><%= link_to "Чоловіче", mens_path %></li>
<li class="l-cat"><%= link_to "Жіноче", womens_path %></li>
<li class="l-cat"><%= link_to "Аксесуари", accessories_path %></li>
<li class="l-cat"><%= link_to "Новини", news_path %></li>
<li class="l-cat"><%= link_to "Контакти", contact_path %></li>
</ul>
</div>
JS
$(document).ready(function(){
$('.l-mnu ul li a').click(function(){
if($(this).parent().hasClass('active')){
return false;
}
$('.l-mnu ul li').removeClass('active');
$(this).parent().addClass('active');
});
});
A:
У вас была ошибка синтаксиса.
Сам код работающий.
$(document).ready(function(){
$('.l-mnu ul li a').click(function(){
if($(this).parent().hasClass('active')){
return false;
}
$('.l-mnu ul li').removeClass('active');
$(this).parent().addClass('active');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>.active { background: #FF0 }</style>
<div class="l-mnu">
<ul>
<li class="l-cat active"><a href="#">New</a></li>
<li class="l-cat"><a href="#">Mens</a>
<li class="l-cat"><a href="#">Womens</a>
</ul>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
xCode Inellisense not showing up for UIPopoverController
Does anyone know why my xCode intellisense does not show up when I type in UIPopoverCont...
A:
Its been an ongoing issue. Please open a bug report with Apple if one doesn't already exist. BTW, for non-microsoft stuff it has usually been called things like "autocomplete" or "code completion". MS just had to make their own trademark for the common feature back in the day.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unity save camera image at a specific rate
In my project, I am saving camera images to a folder, but it saves ~60 per second. How could I reduce the amount of images it saves to about 10 per second?
void Update()
{
if (TLB)
{
DirectoryInfo p = new DirectoryInfo(path);
FileInfo[] files = p.GetFiles();
saveFrame(path, "TLB", fileCounter);
fileCounter = files.Length + 1;
}
}
void saveFrame(string path, string type, int counter)
{
RenderTexture rt = new RenderTexture(frameWidth, frameHeight, 24);
GetComponentInChildren<Camera>().targetTexture = rt;
Texture2D frame = new Texture2D(frameWidth, frameHeight, TextureFormat.RGB24, false);
GetComponentInChildren<Camera>().Render();
RenderTexture.active = rt;
frame.ReadPixels(new Rect(0, 0, frameWidth, frameHeight), 0, 0);
GetComponentInChildren<Camera>().targetTexture = null;
RenderTexture.active = null;
Destroy(rt);
byte[] bytes = frame.EncodeToPNG();
string filename = path + type + "/" + "/" + frameName(type, counter);
File.WriteAllBytes(filename, bytes);
}
A:
Repeating code execution after a certain time interval in Unity
Using Update() method:
// Invoke the method after interval seconds
public float interval = 0.1f;
// time counter
float elapsed = 0f;
void Update()
{
elapsed += Time.deltaTime;
// if time is elapsed, reset the time counter and call the method.
if (elapsed >= interval)
{
elapsed = 0;
TakeShot();
}
}
void TakeShot()
{
// do your thing here...
}
Using InvokeRepeating() method:
// Invoke the method after interval seconds
public float interval = 0.1f;
float delaySeconds = 0f; // delay the first call by seconds
void Start()
{
InvokeRepeating("TakeShot", delaySeconds, interval);
}
void TakeShot()
{
// do your thing here...
}
NOTE: Both methods are framerate and time-scale dependent.
Hope this helps :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Permission denied with Rails 3.1, paperclip gem and nginx
Using Rails 3.1 with the paperclip gem on nginx I get the following 500 error when attempting to upload images:
Permission denied - /webapps/my_rails_app/public/system
Observing the guidance offered elsewhere on this issue, I have modified my directory permissions such that
drwxr-xr-x 3 www-data www-data 4096 Mar 10 17:57 system
And, it would appear, this permission structure is maintained for all public sub-directories.
Yet, having restarted nginx, the error persists.
Do I need to modify nginx.conf or take another hack at permissioning the affected directory?
A:
When I've run into this in the past, it's generally because the Rails application was started by a user or process that is not a part of the www-data group, and is not the www-data user. I'd first check to confirm that the www-data is in fact running your app.
This can be done using ps awwwx and perhaps some grep logic to find your app in the process stack.
I might suggest that you change the directory permissions to allow any member of the www-data group to write to the directory as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Geocode a list of address into a map in qgis?
I have a list of country and city capitol on a Excel, and I want to upload them into a map in QGIS?
A:
You need to use the MMQGIS plugin and Geocode a CSV file
Make sure that your Excel have at list a Country row and to Address rows
Then save as a "CSV UTF-8 (comma delimited" file, in some Windows you will see only the "comma delimited".
Once you have the file go the Geocode in the MMQGIS, upload the file and fill up the blanks. It's important to save the output file in a predefined folder.
After you press the "OK" button it will take some time but you have the address on your map. In this case all the word capitols
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.