text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
find unique timestamps per day
I have a list (i.e. my_list) of 10000 elements. Each element is a dataframe that has 4 columns (namely: id, eventTime, name, value). I would like to iterate through the list of dataframes and find for every dataframe the amount of 'eventTime' per day. This is what I have so far.
values_per_day = []
for aa in my_list:
find_values = my_list.eventTime.unique()
values_per_day.append(find_values)
The error is:
AttributeError: 'list' object has no attribute 'eventTime'
A:
You want to use the variable aa and not the my_list:
find_values = aa.eventTime.unique()
| {
"pile_set_name": "StackExchange"
} |
Q:
Show and hide a View with a slide up/down animation
I have a LinearLayout that I want to show or hide with an Animation that pushes the layout upwards or downwards whenever I change its visibility.
I've seen a few samples out there but none of them suit my needs.
I have created two xml files for the animations but I do not know how to start them when I change the visibility of a LinearLayout.
A:
With the new animation API that was introduced in Android 3.0 (Honeycomb) it is very simple to create such animations.
Sliding a View down by a distance:
view.animate().translationY(distance);
You can later slide the View back to its original position like this:
view.animate().translationY(0);
You can also easily combine multiple animations. The following animation will slide a View down by its height and fade it in at the same time:
// Prepare the View for the animation
view.setVisibility(View.VISIBLE);
view.setAlpha(0.0f);
// Start the animation
view.animate()
.translationY(view.getHeight())
.alpha(1.0f)
.setListener(null);
You can then fade the View back out and slide it back to its original position. We also set an AnimatorListener so we can set the visibility of the View back to GONE once the animation is finished:
view.animate()
.translationY(0)
.alpha(0.0f)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
view.setVisibility(View.GONE);
}
});
A:
I was having troubles understanding an applying the accepted answer. I needed a little more context. Now that I have figured it out, here is a full example:
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button myButton;
View myView;
boolean isUp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myView = findViewById(R.id.my_view);
myButton = findViewById(R.id.my_button);
// initialize as invisible (could also do in xml)
myView.setVisibility(View.INVISIBLE);
myButton.setText("Slide up");
isUp = false;
}
// slide the view from below itself to the current position
public void slideUp(View view){
view.setVisibility(View.VISIBLE);
TranslateAnimation animate = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
view.getHeight(), // fromYDelta
0); // toYDelta
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
}
// slide the view from its current position to below itself
public void slideDown(View view){
TranslateAnimation animate = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
0, // fromYDelta
view.getHeight()); // toYDelta
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
}
public void onSlideViewButtonClick(View view) {
if (isUp) {
slideDown(myView);
myButton.setText("Slide up");
} else {
slideUp(myView);
myButton.setText("Slide down");
}
isUp = !isUp;
}
}
activity_mail.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context="com.example.slideview.MainActivity">
<Button
android:id="@+id/my_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:onClick="onSlideViewButtonClick"
android:layout_width="150dp"
android:layout_height="wrap_content"/>
<LinearLayout
android:id="@+id/my_view"
android:background="#a6e1aa"
android:orientation="vertical"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="200dp">
</LinearLayout>
</RelativeLayout>
Notes
Thanks to this article for pointing me in the right direction. It was more helpful than the other answers on this page.
If you want to start with the view on screen, then don't initialize it as INVISIBLE.
Since we are animating it completely off screen, there is no need to set it back to INVISIBLE. If you are not animating completely off screen, though, then you can add an alpha animation and set the visibility with an AnimatorListenerAdapter.
Property Animation docs
A:
Now visibility change animations should be done via Transition API which available in support (androidx) package. Just call TransitionManager.beginDelayedTransition method with Slide transition then change visibility of the view.
import androidx.transition.Slide;
import androidx.transition.Transition;
import androidx.transition.TransitionManager;
private void toggle(boolean show) {
View redLayout = findViewById(R.id.redLayout);
ViewGroup parent = findViewById(R.id.parent);
Transition transition = new Slide(Gravity.BOTTOM);
transition.setDuration(600);
transition.addTarget(R.id.redLayout);
TransitionManager.beginDelayedTransition(parent, transition);
redLayout.setVisibility(show ? View.VISIBLE : View.GONE);
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="play" />
<LinearLayout
android:id="@+id/redLayout"
android:layout_width="match_parent"
android:layout_height="400dp"
android:background="#5f00"
android:layout_alignParentBottom="true" />
</RelativeLayout>
Check this answer with another default and custom transition examples.
| {
"pile_set_name": "StackExchange"
} |
Q:
Present ManyToMany in Django's Admin as horizontal-filter using related_name
I have the following:
class User(models.Model)
blablabla
class Product(models.Model)
authorized_users = models.ManyToManyField(
User,
related_name='shared_products',
)
I already configured the admin of Product to show authorized_users as an horizontal filter, in order to select all the users that can edit a product.
class ProductAdmin(admin.ModelAdmin):
filter_horizontal = (
'authorized_users',
)
admin.site.register(Product, ProductAdmin)
The problem is that I want to do the same in the admin of User, meaning that I want to have an horizontal filter for shared_products, in order to select the products that this user is able to edit. I have tried the following which clearly doesn't work:
class UserAdmin(admin.ModelAdmin):
filter_horizontal = (
'authorized_users',
)
admin.site.register(User, UserAdmin)
Other answers I have found recomend the usage of Inlines but as I have seen they are used to edit the model instance on the other end, which is not I what I want to do.
Does someone have an idea of how to achieve this?
A:
class UserAdminForm(forms.ModelForm):
products = forms.ModelMultipleChoiceField(
queryset=Product.objects.all(),
required=False,
widget=FilteredSelectMultiple(
verbose_name=_('Products'),
is_stacked=False
)
)
class Meta:
model = User
def __init__(self, *args, **kwargs):
super(UserAdminForm, self).__init__(*args, **kwargs)
if self.instance and self.instance.pk:
self.fields['products'].initial = self.instance.products.all()
def save(self, commit=True):
user = super(UserAdminForm, self).save(commit=False)
if commit:
user.save()
if user.pk:
user.products = self.cleaned_data['products']
self.save_m2m()
return user
class UserAdmin(admin.ModelAdmin):
form = UserAdminForm
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I Segue back, to a different view controller, and then forward, to another view controller
I'm dabbling in iOS app development for the first time, I have a project in mind and I'm currently working on the layout.
Basically I have a main view controller, and others (we'll just call them VC1, VC2 etc... for the sake of clarity)
App launches to VC1, you click the search button, a modal VC2 pops up with a recent, and a search bar. You type in a name and hit search, this is basically where I want it to segue Back to VC1, and then forward to VC3 (The players screen of the app)
Right now it goes VC1(SearchButtonAction) -> VC2(SearchPlayerAction) -> VC3 (but this looks weird with the transition from the modal to a view controller, and if I hit back it looks even weirder.
I want it to go
VC1(SearchButtonAction) -> VC2(SearchPlayerAction) -> VC1 -> VC3
I don't really know how to manage it or I would attach some code. Instead I've attached a screenshot of what I have working so far.
I'm not sure if I'm supposed to do something like prepareForSegue and make a boolean to flag if it should auto-segue on loading to send to VC3, but then I need to pass the data to VC1, just to pass it back to VC3, it seems messy, I'd just like to segue / pass the same data from VC2 back to VC3, going through VC1 though. I hope that's clear x.x
A:
There are a few options that you could use.
1. Unwind Segue
I've started using these recently, they can be really useful for passing data back from one VC to another. You basically add a function in the VC that you will be unwinding back to, in your case this will be VC1. This function in VC1 will be called when you dismiss VC2. You could then push to VC3 from here.
I have attached a brief code example, but here is a link to a good tutorial that will describe it better.
EXAMPLE
VC2
class ViewController2: UIViewController
{
let dataToPassToVC3 = "Hello"
@IBAction func dismissButtonTapped(_ sender: Any)
{
self.dismiss(animated: true, completion: nil)
}
}
VC1
class ViewController1: UIViewController
{
@IBAction func unwindFromVC2(segue:UIStoryboardSegue)
{
//Using the segue.source will give you the instance of ViewController2 you
//dismissed from. You can grab any data you need to pass to VC3 from here.
let VC2 = segue.source as! ViewController2
VC3.dataNeeded = VC2.dataToPassToVC3
self.present(VC3, animated: true, completion: nil)
}
}
2. Delegate Pattern
VC2 could create a protocol that VC1 could conform to. Call this protocol function as you dismiss VC2.
EXAMPLE
VC2
protocol ViewController2Delegate
{
func viewController2WillDismiss(with dataForVC3: String)
}
class ViewController2: UIViewController
{
@IBAction func dismissButtonTapped(_ sender: Any)
{
delegate?.viewController2WillDismiss(with: "Hello")
self.dismiss(animated: true, completion: nil)
}
}
VC1
class ViewController1: UIViewController, ViewController2Delegate
{
func viewController2WillDismiss(with dataForVC3: String)
{
VC3.dataNeeded = dataForVC3
self.present(VC3, animated: true, completion: nil)
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i use jQuery's .find method with a regular expression as the parameter?
I have an xml that i'd like to search for "alike" results, similar to what LIKE does in SQL.
I thought about doing something like $(xml).find('regexHere'), but i don't know how to do that.
If that's not the best method, could you recommend something else? The data i need to search is within node's parameters.
EDIT
$(xml).find('[cityName=Rio de Janeiro]')gives me exactly the node i'm searching for, because it's exactly the same string. But, if i search for Rioi don't get any results, even though the nodes of Rio de Janeiro and Rio Claro have the string i'm looking for.
I tried using $(xml).find('[cityName|="Rio"]') without luck, not a single result comes up, but if i change to Rio de Janeiroi get exactly what i need.
A:
To find all elements that have an attribute matching a certain regex, you can use .find("*") to select all elements and then .filter(...) to remove any that don't match:
For example, to find all nodes whose message attribute contains "hello world":
var elements = $(xml).find("*").filter(function() {
return /[Hh]ello [Ww]orld/.test($(this).attr("message"));
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I skip role in Ansible?
I have this playbook:
roles:
- { role: common}
- { role: mariadb}
- { role: wordpress}
What is want is in every role I want to have first task as some conditional which if true then I want to skip the whole role and playbook continues to next.
Now I can use when like this:
roles:
- { role: common, when: mvar is False }
But for that I have to evaluate the mvar in playbook itself but for that mvar I need all other vars etc. stuff which is in that role itself. So it will be easier for me to do in role.
Is there any way?
A:
In each role, in tasks/main.yml include a file with tasks only when the condition is met:
- include: real_tasks.yml
when: condition_is_met
| {
"pile_set_name": "StackExchange"
} |
Q:
Automatic properties
I am creating an application using Backbone which follows the structure below:
App = {
Models: {},
Views: {},
Collections: {},
Routers: {}
};
When designing an object – in this case, a View –, I do the following:
App.Views.ProductsView = Backbone.Model.extend();
But, I want something like:
App.Views.Products.IndexView = Backbone.Model.extend();
What's the big deal?
If I previously declare App.Views.Products = {}, everything will work – but I want to do it automatically; without any previous declaration.
Based on my problem, can you give me an idea?
A:
I'm not sure I get it, but you have declare the property before you can add properties to the chain ?
App.Models.Products = {};
App.Models.Products.IndexView = Backbone.Model.extend();
Of course, you could declare it in a number ways, for instance when you create App
App = {
Models : {
Products : {} // here
},
Views : {},
Collections : {},
Routers : {},
Views : {}
};
or as a literal containing the key etc
App.Models.Products = {
IndexView : Backbone.Model.extend();
}
As an answer to the edited question, you can't, javascript has no magic methods to create missing properties, you have to declare them yourself.
| {
"pile_set_name": "StackExchange"
} |
Q:
Populating a third table to maintain efficiency
I am currently working on a PHP/MySQL project for an assignment. In studying the efficient design of databases while working on the assignment I notice that in many cases it is good practice to create a third table when working with only two sets of data.
For example, if we have a table for "Students" and a table for "Addresses" it appears to be a good idea to create a third table i.e. "Student_Addresses" since a student can hypothetically have more than one address (separated parents etc.) and a single address can represent more than one student (siblings).
My question is: How do we go about populating that third table? Is there a way that it is done automatically using primary and/or foreign keys?
I've tried Google and my textbook to understand this but I've gotten nowhere. Links to tutorials or articles would be greatly appreciated.
Thanks for your help. I hope the question and example are clear.
A:
n:m or 1:m normalization rule
Option 1:
user table
id
f_name
s_name
......
user address table
id
user_id // this should be index only as foreign keys will allow 1:1 only
address line 1
address line 2
address line 3
address_type (home, office ....)
Option 2:
user table
id
f_name
s_name
......
address table
id
address line 1
address line 2
address line 3
address_type (home, office ....)
user_address table
userId
addressId
according to your description option 2 would be the right solution. After adding the data to user table and address table then you need to add the data to user_address table manually. Some Object relational mapper (ORM) may do add the data to the third table automatically but you need to define the relations. check http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html.
http://docstore.mik.ua/orelly/linux/sql/ch02_02.htm
http://www.keithjbrown.co.uk/vworks/mysql/mysql_p7.php
| {
"pile_set_name": "StackExchange"
} |
Q:
Harvesting Venus atmosphere to Terraform Mars
Since Mars has such a thin atmosphere, to Terraform we would need massive amounts of Nitrogen. Would it make sense to import it from Venus?
Also since venus's atmosphere is mostly co2, and we can make o2 from co2, could we just import o2 too? That might be faster than just creating o2 using plants on Mars.
A:
There are easier ways to enhance Mars's atmospheric pressure, so no, don't use Venus materials. I calculated the energy required to lift a kg of nitrogen — or a kg of anything, for that matter — out of Venus's gravity well, and uphill through the sun's gravity well to Mars. Getting it away from Venus was a small part of the total, but that total was nearly 700 MegaJoules, far more than chemically reacting 1 kg of anything could supply. Lugging stuff up the solar gravity well isn't easy!
But there are other ways. For example, there are many objects flying around in the solar system that contain huge amounts of volatiles, such as comets and some asteroids, and some of those are in orbits that are not as difficult to divert to Mars as lugging up from Venus. The savings in energy is greater than the energy needed to make N2 from the NH3 in, say, a comet.
That said, the amount of energy needed for this undertaking currently is far beyond what we can muster.
So no, for multiple reasons Venus shouldn't worry about somebody swiping its nitrogen!
A:
No. Moving N2 or O2 wouldn't make sense, because it would require moving about a quadrillion tons from one planet to another, while we've barely figured out how to move one ton up from one gravity well and down into another.
Once we can do that kind of engineering (pick a favorite technology from science fiction), we may have already become bored with terraforming.
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel 5.1: How to limit account access so one account can be accessed at one time
I am relatively new to Laravel, but I would like to restrict account access so that only one account can be logged into at one time. For example, if I were to log into my account on my work computer and then I logged in at my home computer simultaneously, it would not log me in and prompt me to logout of the first computer.
What is the best and correct way of doing this?
Many Thanks
A:
This is more a 'logic' question than one about Laravel. In short I would build something like this;
Add a field to the user table like 'active_at' with a timestamp in it and a 'active_device' with a unique value created based on this login (maybe based on the IP + device information);
When a users logs in I would update this fields;
Than in the background have some JavaScript call a script on the server every minute (or shorter depending on your wishes) that verifies the current logged in user and updates the 'active_at' timestamp field;
Then when logging in somewhere I would check if the 'active_at' is outdated and not matching the 'active_device' hash I would prompt the user to logout the other device which would empty these fields.
By setting things up in a way only the login-procedure is allowed to take over a device (and not the JavaScript activity ping) you won't end up battling between two devices :)
If you want to prompt with more information about the other device (as for now we only have a hashed device info string) you could either add another field with a human readable name for the device or use some sort of encrypted string so you could decrypt it when needed.
A final touch would be to let the server code handling step 3 destroy the current authentication session if the active_device hash is no longer matching. The coolest thing would be to redirect the user to a login page only asking for a password to revalidate the current device (and triggering a login procedure overwriting the active_device info).
| {
"pile_set_name": "StackExchange"
} |
Q:
can I combine meta or do I have to use only one?
I used to use this meta:
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
Now I want to change meta so that compatibility view in IE9 is disabled:
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
Now I don't understand much bout the first meta but my question is that can I only use one of the meta out of the two or can I combine them to include both of them? Which way would you recommend?
A:
If I am right in saying, you're question is actually "Whats the best way to do it, in terms of minimizing page size and improving site quality?"
As far as I know each META tag like that must be declared separately, because you are declaring 1 value for each.
| {
"pile_set_name": "StackExchange"
} |
Q:
What was the religion of the Arabic people before conversion to Islam?
What was the dominant religion of the Arabic people when Prophet Muhammed started the Islamic religion?
A:
In my History of Islam classes there was some review of Pre-Islamic Arabia and a few things were covered, from my class notes we talked about:
Arabia being a part of the major trade route along the Red Sea Coast, from southern Palestine to Yemen. Medina and Mecca were located along this route, Mecca was the more important city where caravans stopped and the Qadabah was a shrine used by the Pre-Islamic traders and worshippers
As to the Pre-Islamic religions many of the Islamic governments in the Arabian peninsula don't encourage much archaeology as they don't really want to have much known of it's ancient past. Much can be determined by other records of the surrounding nations, this is where much of the information comes from, but I wanted to note its hard to get original sources and information from digs in Arabia. Although if you take some of the information from the Qur'an in a historical context there is information on some of the ancient people's noted there, as well as other sources from around the time of its writing
The Arabs were Semites, so they were related to many groups in the region. Akkadians, Assyrians and others. Their language was related to Hebrew, Aramaic, Syriac and the Afro-Asiatic tongues.
The peoples who lived there were tribal and nomadic, this was known even until Mohammed's time, as tribes were very important with the first Caliphs. This is represented by the Bedouins who were raiders, attacking cities and caravans for supplies and possessions.
Around the time of Mohammed the Qadabah was a shrine to the natural gods and spirits, as the Pre-Islamic Arabs worshipped stones, trees, wells and tribal originations. The Qadabah had something like 350+ recorded respresentations of gods/spirits before Islam.
Allah was known as a God before Islam, although Allah is basically translated as God or the God so it may not be representative of the Islamic Allah and just a name carried forward
W. Montgomery Watt noted something called Tribal Humanism that may have been in place before Islam, I saw it as socialistic and tribal-orientated where there was a dispersal of goods but everything was done for the tribe. Practices tended to be naturalistic, with sacred sites being trees and stones.
Other religions in the area at the time were Judaism, Christians, Zoroastrians and something called hanif which is loosely translated as pagan but had more of a connection to a montheism which was considered pure and moral but not idolatory.
Most of this came from class notes and one of our major texts: An Introduction to Islam by Frederick Mathewson Denny
Hope that helps
A:
Short answer
Pre-Islamic Arabians were polytheistic, worshiping 360 gods; the chief god was the moon-god. They later became monotheistic because of Muhammad.
Long answer
In 1944, Gertrude Caton-Thompson (1888-1885), an influential English archaeologist, discovered a temple of the moon-god in southern Arabia. The symbols of the crescent moon and no less than 21 inscriptions with the name "sîn" were found in this temple. The temple reveals that it was active even in the Christian era. Evidence gathered from both North and South Arabia demonstrate that moon-god worship was clearly active even in Muhammad's day.
(from her book The Tombs and Moon Temple of Hureidah)
The title of this moon-god, sîn, was "al-ilah" which means "the deity" or "the god", meaning he was the chief god among the Arabians' 360 other gods. Its title was commonly used as a name instead of it's actual name.
"The god il or ilah [al-ilah] was originally a phase of the moon-god" — Carleton S. Coon, (Southern Arabia, p.399).
This god's name was eventually shortened to "allah" in Pre-Islamic times. People back then even used "allah" in naming their children. For example, Muhammad's father's name was Abdullah, meaning "slave of the allah", (they say his uncle's name Abu-Talib has contains the word "allah", but I can't figure it out).
The fact that the word "allah" is never defined in the quran, and that Muhammad assumed that the Arabs already knew who allah was; proves that the pre-Islamic Arabs already worshiped allah. While they believed that allah was the greatest god, Muhammad wanted to go a step further to say that allah was the only god.
For the Arabs, Muhammad said that he still believed in their moon-god allah, but to the Jews and Christians, he said that allah was their god. But, as you can see, allah, al-ilah, sîn, "the moon-god", or whatever you want to call it, is not the God of Abraham, Isaac, and Jacob... יהוה (YHWH or Yahweh)
(more information here)
A:
I take your question as "just before the advent of Muhammad." Therefore I will not delve into ancient history, and limit the answer to late-antiquity and early Middle Ages.
First of all we have to note that people in the Arabic Peninsula could (and can) be divided geographically between the (mostly) arid North (notwithstanding oases and narrow coastal regions) and the prosperous South, with its Sabaean-Yemenite people.
The South was dominated by sedentary kingdoms, and was the Arabia Felix of Roman sources, thanks to prosperous trade and local production of spices. This land became object of a struggle between Jewish and Christan preachers, with alternate phases. Judaism penetrated in the Arabian Peninsula as earlier, and became a crucial region after the destruction of the Temple in Jerusalem in AD 70. Christianity arrived later, but its universalism demanded conversion of the local people. The apex of Judaism was reached with the conversion of the King Dhu Nuwas and the subsequent massacre of Christians of Najraan. Immediately afterwards, with the approval of Byzantium, an expedition of Ethiopians, who were Christians, conquered the Kingdom and brought its independence to an end.
Judaism however survived until the advent of Islam.
The other areas of Arabia were instead populated by a complex marriage of sedentary people and nomadic Bedouins. The latter did not leave written records, but we know that the Arabic Hijaz was divided by the Christian zone of influence to the North (centred around Najraan) and the Jewish one to the South (gravitating Yathrib). These areas met in Mecca, which was to become the most important centre in the region, following the fall of the Sabaean South to the Ethiopians and the stalemate in the North between the Sasanid and Byzantine Empires.
The religion in Mecca was complex. Reportedly, at the time of the Quraysh domination, besides Christianity and Judaism a triad of goddesses was venerated: al-Laat, al-Uzzaa and Manaat. These were daughter of Allaah, which was interpreted as either the God of the Bible or another Semitic deity.
In these days, Arabia became haeresium ferax, a cradle of heresy.
The importance of Judaism/Christianity was evident in that the people of Mecca, and Arabs in general, considered themselves descendents of Abraham and Ismail, which are Biblical characters.
In the Sacred Months, the Arabs from far and wide would flock to the Holy City of Mecca and its Haram, the sacred precinct, and the Kaaba. They would gather for the Ukaaz, a fair which was also a scene of poetic contests, and climb the Holy Mountain of Arafaat for the pilgrimage. In the sixth century, a new concept of Arabia Sacra was emerging, alongside with the rise of the Arabs, finally aware of being a nation.
Muhammad was born in AD 570 circa.
Source: A Cambridge History of Islam, and references therein.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to handle different form submission in asp.net webform
I have four separate section where I would like to handle form submission in my page (Section #1 and #2 are shown when the user agent is in mobile):
Section #1 (mobile:
<div id="mSearchB" class="mSearchTextHolder">
<div class="mSearchInnerTextHolder">
<input type="search" placeholder="Search" class="txtMSearch" id="txtMSearch" />
</div>
</div>
Image for #1:
Section #2 (mobile):
<div class="brClear loginHolder floatLeft">
<input type="text" placeholder="Username" id="txtUsername" class="txtUsername styledTB floatLeft" />
</div>
<div class="floatLeft">
<input type="password" placeholder="Password" id="pwPassword" class="txtPassword styledTB floatLeft" />
</div>
<div class="floatLeft">
<a href="JavaScript:void(0);" title="Login" class="styledBtn logBtn floatLeft lightLinks">Login</a>
</div>
(Image for #2 hasn't been built yet but similar to #1)
Section #3 (non-mobile):
<div class="searchBox">
<input type="text" value="" placeholder="Search" id="searchB" />
<a href="JavaScript:void(0);" title="Search"><img src="theImages/searchWhite.png" alt="Search" title="Search" class="searchImg" /></a>
</div>
Section #4 (non-mobile):
<div class="brClear loginHolder">
<input type="text" placeholder="Username" id="txtUsername" class="txtUsername styledTB floatLeft" />
<input type="password" placeholder="Password" id="pwPassword" class="txtPassword styledTB floatLeft" />
<a href="JavaScript:void(0);" title="Login" class="styledBtn logBtn floatLeft lightLinks">Login</a>
</div>
Image for #3 and #4:
For #3 and #4, if I click on the search icon all three textboxes goes blank of the placeholder.
I haven't placed any form tag around any of the one above because the asp.net page already has one auto inserted on page creation.
How do I handle each submission separately, so clicking or hitting enter on one textbox doesn't submit the entire form for all?
A:
I haven't placed any form tag around any of the one above because the asp.net page already has one auto inserted on page creation.
That sounds like WebForms. In which case, basically, you don't separate your form posts. The entire page is one big form and any post-back triggering event is going to submit the entire form to the server.
The way it's done in WebForms is to have separate server-side click event handlers for separate buttons. So if "sub form 1" has Button1 and "sub form 2" has Button2 then each would have their own server-side handlers:
void Button1_Click(Object sender, EventArgs e)
{
// Button1 was clicked, handle it here
}
void Button2_Click(Object sender, EventArgs e)
{
// Button2 was clicked, handle it here
}
As for the "default" click action for pressing enter on other controls or things like that, you can wrap each "sub form" in a Panel control and set its DefaultButton property.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to position a custom label in highcharts
I am trying to do exactly what is in this official HighCharts fiddle: http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/members/renderer-label-on-chart/
However the example's "label" function has hardcoded the x(270) and y(50) parameters:
function (chart) { // on complete
var point = chart.series[0].points[8];
chart.renderer.label('Max observation', 270, 50, 'callout',
point.plotX + chart.plotLeft, point.plotY + chart.plotTop)
My chart obviously will require different parameters. I tried using point's plotX etc. However these are undocumented. in fact the are are not part of API as a (presumably) HighCharts developer points out in another answer - they are just inner properties to get coordinates where plot point. in other word, undocumented.
Using them is shorthand for getting values from point:
http://api.highcharts.com/highcharts#Point.x
http://api.highcharts.com/highcharts#Point.y
And translating to position via:
http://api.highcharts.com/highcharts#Axis.toPixels()
The links above seem completely unrelated.
I tried this to divine what those coordinates provide
}, function (chart) { // on complete
var point = chart.series[0].points[8];
chart.renderer.label('.'
, point.plotX.toFixed(0), point.plotY.toFixed(0), 'callout', point.plotX + chart.plotLeft, point.plotY + chart.plotTop)
.add();
});
seems plotX is some point situated a random set of pixels to the left of the chart series point that provides it (about 60ish) and seems to depend on the font you use.
A:
This seems to be what you're looking for:
var point = chart.series[0].points[8];
var pxX = chart.xAxis[0].toPixels(point.x, true);
var pxY = chart.yAxis[0].toPixels(point.y, true);
chart.renderer.label('Max observation', pxX, pxY, 'callout', point.plotX + chart.plotLeft, point.plotY + chart.plotTop);
Fiddle - Notice .toPixels works per Axis, so you need to determine the pixel representation of point X and point Y separately. The true parameter to the function positions the callout based on its point, rather than the top left corner of the callout.
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing the gradient color of `shap.summary_plot()` to specific 2 or 3 RGB gradient palette Colors
I have been trying to change the gradient palette colours from the shap.summary_plot() to the ones interested, exemplified in RGB.
To illustrate it, I have tried to use matplotlib to create my palette. However, it has not worked so far.
Could someone help me with that ?
This is what I have tried so far:
Creating an example with the iris dataset (No problem in here)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn.model_selection import train_test_split
import xgboost as xgb
import shap
# import some data to play with
iris = datasets.load_iris()
Y = pd.DataFrame(iris.target, columns = ["Species"])
X = pd.DataFrame(iris.data, columns = iris.feature_names)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=0, stratify=Y)
params = { # General Parameters
'booster': 'gbtree',
# Param for boosting
'eta': 0.2,
'gamma': 1,
'max_depth': 5,
'min_child_weight': 5,
'subsample': 0.5,
'colsample_bynode': 0.5,
'lambda': 0, #default = 0
'alpha': 1, #default = 1
# Command line parameters
'num_rounds': 10000,
# Learning Task Parameters
'objective': 'multi:softprob' #'multi:softprob'
}
model = xgb.XGBClassifier(**params, verbose=0, cv=5 , )
# fitting the model
model.fit(X_train,np.ravel(Y_train), eval_set=[(X_test, np.ravel(Y_test))], early_stopping_rounds=20)
# Tree on XGBoost
explainerXGB = shap.TreeExplainer(model, data=X, model_output ="margin")
#recall one can put "probablity" then we explain the output of the model transformed
#into probability space (note that this means the SHAP values now sum to the probability output of the model).
shap_values_XGB_test = explainerXGB.shap_values(X_test)
shap_values_XGB_train = explainerXGB.shap_values(X_train)
shap.summary_plot(shap_values_XGB_train, X_train, )#color=cmap
Until here if you run the code when should get the summary plot with the default colors. In order to change the default ones, I have tried to create my 2 color gradient palette as following:
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
RGB_val = 255
color01= (0,150,200) # Blue wanted
color04= (220,60,60) # red wanted
Colors = [color01, color04]
# Creating a blue red palette transition for graphics
Colors= [(R/RGB_val,G/RGB_val,B/RGB_val) for idx, (R,G,B) in enumerate(Colors)]
n = 256
# Start of the creation of the gradient
Color01= ListedColormap(Colors[0], name='Color01', N=None)
Color04= ListedColormap(Colors[1], name='Color04', N=None)
top = cm.get_cmap(Color01,128)
bottom = cm.get_cmap(Color04,128)
newcolors = np.vstack((top(np.linspace(0, 1, 128)),
bottom(np.linspace(0, 1, 128))))
mymin0 = newcolors[0][0]
mymin1 = newcolors[0][1]
mymin2 = newcolors[0][2]
mymin3 = newcolors[0][3]
mymax0 = newcolors[255][0]
mymax1 = newcolors[255][1]
mymax2 = newcolors[255][2]
mymax3 = newcolors[255][3]
GradientBlueRed= [np.linspace(mymin0, mymax0, n),
np.linspace(mymin1, mymax1, n),
np.linspace(mymin2, mymax2, n),
np.linspace(mymin3, mymax3, n)]
GradientBlueRed_res =np.transpose(GradientBlueRed)
# End of the creation of the gradient
newcmp = ListedColormap(GradientBlueRed_res, name='BlueRed')
shap.summary_plot(shap_values_XGB_train, X_train, color=newcmp)
But I haven't been able to get a change on the colors of the graphic. :
Can someone explain me how to make it for:
(A) 2 gradient color or
(B) 3 color gradient (specifying a color in the middle between the other 2) ?
Thank you so much for your time in advanced,
A:
As already shown here, my workaround solution using the set_cmap() function of figure's artists:
# Create colormap
newcmp = ListedColormap(GradientBlueRed_res, name='BlueRed')
# Plot the summary without showing it
plt.figure()
shap.summary_plot(shap_values_XGB_train, X_train, show=False)
# Change the colormap of the artists
for fc in plt.gcf().get_children():
for fcc in fc.get_children():
if hasattr(fcc, "set_cmap"):
fcc.set_cmap(newcmp)
Result
| {
"pile_set_name": "StackExchange"
} |
Q:
Best practise organizing XML-Schema Files
Say my company has lots of schemas, some for webservices, some for other purposes. There are common type definitions used in many of these schemas via import and also application specific schemas.
Now and then schemas are changed, versioned, and exported.
So far the company uses SVN to store the schema files. They are not structured efficiently, there are redundancies and other problems. There is no clear hirarchy of files and folders.
Question 1: Is it a good practise to use SVN to store and version XSD-Files. What would be an other good approach?
Question 2: How could I efficently structure the files? I would like to organize them in folders correlating the files' namespaces.
Question 3: When exporting, is it more common to give a flattend copy (one folder with all files) or keep the folder hirarchy according to the namespaces?
A:
Here's a piece of advise.
See OGC schema repository for example:
http://schemas.opengis.net/
This is one of the largest public schema repositories, widely used in the GIS industry. The schemas are far from perfect, but they've learned a lot of lessons.
To answer your questions:
You should separate the "specification version" of the schema and the "editorial version" or "revision". Once published, you may need to support several versions of one schema in parallel. For instance:
http://schemas.opengis.net/gml/3.2.1/
http://schemas.opengis.net/gml/3.1.1/
Both widely used in parallel.
So you should factor the "specification version" into the repository folder structure.
"Revisions" should be handled by the version control system. You may (and will) need to do fixes in already released versions.
If your schemas will be public, it might well make sense to put them into a public code repository like GitHub. This would allow your technical users to send you fixes via pull requests. (This is a feature I'd love to have for OGC schemas.) Community input may be very important. XML Schema is not the easiest thing to handle, even experienced devs make errors. The community would help to make things work.
Do use semantic versioning for your schemas. OGC in the current policy uses MAJOR and MINOR in namespace URIs, but not PATCH. So, for the GML 3.2.1 schema the namespace URI is:
http://www.opengis.net/gml/3.2
The schema URIs do not have to be identical to namespace URIs (compare http://schemas.opengis.net/gml/3.2.1/ with http://www.opengis.net/gml/3.2). If you use MAJOR.MINOR.PATCH in the folder and only MAJOR.MINOR in the namespace - then these URIs technically even can't be identical. But there should be a straightforward transformation. Having an URI like http://www.opengis.net/gml/3.2 I'll know where to look for the schema.
It's good to have one "entry file" per specification, like this one:
http://schemas.opengis.net/sld/1.1/sldAll.xsd
Be consistent with structures and naming.
If you have many related schemas in one repository, importing/including one another, better use relative links. This would make easier for other people to download and validate against local copies.
Do not do chameleon schemas. Don't even google it. Every specification should have its own namespace. No chameleon imports.
No, don't do any flattened copies. Why? Just give access to your schema repo plus maybe a ZIP containing all the schemas.
Include a license so that it is clear what the license is.
Check and compile your schemas with several known tools. Xerces, Oxygen, Xmlmind, XML Spy. JAXB/XJC on Java, xsd.exe for C#, PyXB for Python. Make sure it works OOTB.
Provide XML examples for your schemas.
| {
"pile_set_name": "StackExchange"
} |
Q:
Move list items in multiple lists with jQuery and save to MySQL
I try to change this code to work on multiple lists too and it is also important to drag and drop the items between the lists not only in the same list: link
Here is the code what I made:
<?php require("db.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Dynamic Drag'n Drop</title>
<script type="text/javascript" src="//code.jquery.com/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.7.3/jquery-ui.min.js"></script>
<style>
ul {margin:10px;padding:0;min-height:100px;min-width:100px;background-color:#87FFF5;}
#sortable1, #sortable2 {
float: left;
width: 400px;
}
#sortable1 li, #sortable2 li {
list-style: none;
margin: 0 0 4px 0;
padding: 10px;
background-color:#00CCCC;
border: #CCCCCC solid 1px;
color:#fff;
cursor:move;
}
#Result {
float:none;
clear:both;
width: 260px;
padding:10px;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(function() {
$("#sortable1, #sortable2").sortable({ connectWith: ".connectedSortable", opacity: 0.6, cursor: 'move',
update: function(event,ui) {
var order = $(this).sortable("serialize") + '&action=updateRecordsListings' + '&id=' + this.id + '&item='+ui.item[0].innerHTML;
$.post("updateDB.php", order, function(theResponse){$("#Result").html(theResponse);});
}
});
});
});
</script>
</head>
<body>
<div>
<ul id="sortable1" class="connectedSortable">
<?php
$query = "SELECT * FROM records_multiple WHERE list='sortable1' ORDER BY recordListingID ASC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<li id="recordsArray_<?php echo $row['recordID']; ?>"><?php echo $row['recordID'] . ". " . $row['recordText']; ?></li>
<?php } ?>
</ul>
<ul id="sortable2" class="connectedSortable">
<?php
$query = "SELECT * FROM records_multiple WHERE list='sortable2' ORDER BY recordListingID ASC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<li id="recordsArray_<?php echo $row['recordID']; ?>"><?php echo $row['recordID'] . ". " . $row['recordText']; ?></li>
<?php } ?>
</ul>
</div>
<div id="Result"></div>
</body>
</html>
The drag and drop function is working now great but I have problems to save the result to the MySQL database.
If I have more than one list I have to know the name of the new list where the item was dropped and the ID of the moved item. So I can save only that list and I can also change the list ID of the moved item.
If I use update: function(event,ui) the name of the list is not always correct. If I change it to receive: function(event,ui), it is correct, but calls the PHP file only if I move the item in an other list.
So how could I get back in any cases the name of the list where the item was moved or droped?
A:
Maybe you can use the
change( event, ui )Type: sortchange
This event is triggered during sorting, but only when the DOM position has changed.
http://api.jqueryui.com/sortable/#event-change
or if that didn't work, here is the complete list of options.
http://api.jqueryui.com/sortable/
UPDATE see this post.
jquery Sortable connectWith calls the update method twice ...
it is getting called twice you add the if statement and use update.
update: function(e,ui) {
if (this === ui.item.parent()[0]) {
//your code here
} }
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I make fixed nav-bar with jQuery slidetoggle method push content down rather than overlap it?
I was wondering if someone out there could help me find a solution to this problem. I'm currently designing a responsive mobile web page and I currently have a fixed navigation bar on scroll with a jQuery slide-toggle method that expands the menu.
My issue is that when I click on the 'menu-trigger' button, instead of pushing the rest of the content down like I would want it to, the menu overlaps the content beneath it.
I've tried searching for answers here and elsewhere, but I couldn't find a definitive answer. I'm sorry if this has already been posted.
I didn't post any code on this post but here is a hypothetical jfiddle I made replicating the same exact issue. I hope someone can help, I'm ready to rip my hair out!!
jQuery(document).ready(function() {
jQuery(".menu-trigger").click(function() {
jQuery(".menu-bar ul").slideToggle();
});
});
/*For Scrolling Purposes*/
body {
background:url(
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAPklEQVQYV2O8dOnSfwYg0NPTYwTRuAAj0QqxmYBNM1briFaIzRbi3UiRZ75uNgUHGbfvabgfsHqGaIXYPAMAD8wgC/DOrZ4AAAAASUVORK5CYII=
) repeat;
height: 2000px;
}
.menu-bar {
position: fixed;
top: 0;
width: 100%;
background: orange;
}
.menu-bar ul {
display: none;
}
.content {
margin-top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<!--Menu Bar Div-->
<div class="menu-bar">
<div class="menu-trigger">
<p>
Button
</p>
</div><!--/Menu Trigger-->
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div><!--/Menu Bar-->
<!--Content Div-->
<div class="content">
<ul>
<li>Some Content</li>
<li>Some Content</li>
<li>Some Content</li>
<li>Some Content</li>
</ul>
</div><!--/Content-->
</body>
Here is the jfiddle link. https://jsfiddle.net/Lq7qqnn9/
Background: Pretty good with HTML and CSS not so much with javascript!
A:
One option would be to use a placeholder item instead of a margin on your content. I.E. add a block behind your fixed block that maintains the height with it's fixed overlay.
jQuery(document).ready(function() {
jQuery(".menu-trigger").click(function() {
$(".menu-placeholder").css("height", $(".menu-bar").height());
jQuery(".menu-bar ul").slideToggle({
progress: function() {
$(".menu-placeholder").css("height", $(".menu-bar").height());
}
});
});
});
/*For Scrolling Purposes*/
body {
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAPklEQVQYV2O8dOnSfwYg0NPTYwTRuAAj0QqxmYBNM1briFaIzRbi3UiRZ75uNgUHGbfvabgfsHqGaIXYPAMAD8wgC/DOrZ4AAAAASUVORK5CYII=
) repeat;
height: 2000px;
}
.menu-placeholder {
width: 100%;
height: 50px;
}
.menu-bar {
position: fixed;
top: 0;
width: 100%;
background: orange;
}
.menu-bar ul {
display: none;
}
.content {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<!--Menu Bar Div-->
<div class="menu-bar">
<div class="menu-trigger">
<p>
Button
</p>
</div>
<!--/Menu Trigger-->
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<!--/Menu Bar-->
<!--Content Div-->
<div class="menu-placeholder"></div>
<div class="content">
<ul>
<li>Some Content</li>
<li>Some Content</li>
<li>Some Content</li>
<li>Some Content</li>
</ul>
</div>
<!--/Content-->
</body>
| {
"pile_set_name": "StackExchange"
} |
Q:
Writing unicode characters to file fails in PowerShell with Anaconda/Python
Just starting to use PowerShell on Windows 10 with the latest Anaconda3 and Python3.7 and cannot run the script due to encoding error. The script attempts to write a text file which contains some German characters and throws:
UnicodeEncodeError: 'charmap' codec can't encode character '\u0144' in position 10: character maps to <undefined>
I have tried chcp 65001 and setting set PYTHONIOENCODING=utf-8 but this does not help.
How does it work with PowerShell?
A:
That's a Python error not a Powershell error. If it was a Powershell issue, you'd get an exception that would look something like...
Attempted to divide by zero.
At line:1 char:1
+ 1/0
+ ~~~
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
Sabbir Ahmed gave a solution to this error (on Windows 10) in this post. You probably have a line that looks something like...
with open('filename', 'w') as f:
...
Change it to...
with open('filename', 'w', encoding='utf-8') as f:
...
A-
| {
"pile_set_name": "StackExchange"
} |
Q:
Storing credits in database
Just a quickey. I am developming website, where you can buy credits and spend them later for things on the website.
My question is, is it ok to store amount of credits with user (user table, column credits and iteger amount) or it is necessary (or just better) to have separate table with user id and amount ?
Thanks
A:
Both actually.
Considering that you'll be dealing with monetary transactions to get those credits, you want to be able to get a log of all transactions (depending of the laws in your country, you will NEED this). Therefore you'll need a credits_transactions table.
user_id, transaction_id, transaction_details, transaction_delta
Since programmatically calculating your current credit balance will be too costly for users with a lot of transactions, you'll also need a credit_balance row in your user table for quick access. Use triggers to automatically update that column whenever a row is inserted from credits_transactions (technically, update and delete shouldn't be allowed in that table). Here's is the code for the insert trigger.
CREATE TRIGGER ct_insert
AFTER INSERT ON credits_transactions
BEGIN
UPDATE users SET credit_balance = credit_balance + NEW.transaction_delta WHERE user_id = NEW.user_id;
END
;;
| {
"pile_set_name": "StackExchange"
} |
Q:
reload a specific section of a web page
Please I'm working with php, ajax and jquery. when I post a status the status is posted with ajax and php, so no entire page reloading happens, but the problem is I want the posted status to be viewed along side the already posted status which means that the old status need to be refreshed so the new posted status appear with me....I wish I could do that and update only the status section without the whole page...this is the code I use to Post the status without reloading.
$('input#post-submit').on('click', function(){
var post = $('textarea#userPost').val();
var azoul = $('input#token').val();
if($.trim(post) != '' && $.trim(azoul) === 'azoul_majidi15AJH45skLD')
{
$.ajax({
url:"post-post.php",
method:"POST",
data:{post:post,azoul},`enter code here`
dataType:"text",
success:function(data){
$('#post-state').text('Your Status was posted successfully');
}
});
}
});
A:
Inside the success of your ajax, replace the html of your old post div with new post content. $("#old_post_div").html("new_post_content");
Or you can use prepend or append so that the new content will be prepended or appended along with old content.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to make a unique batch number per day?
how to make a batch number per day,
for example, TODAY I manufacture products with no batch:
produk A With batch number => 29092016-1
produk B With batch number => 29092016-2
produk C With batch number => 29092016-3
TOMORROW no batch should be:
produk A With batch number => 30092016-1
produk B With batch number => 30092016-2
produk C With batch number => 30092016-3
DAY AFTER TOMORROW no batch should be:
produk A With batch number => 01102016-1
produk B With batch number => 01102016-2
produk C With batch number => 01102016-3
How do I have to write a code in PHP ??
i have code but no working :
$data_oto = mysql_fetch_array(mysql_query("select max(id_batch2) as maksi from batch2"));
function buatkode($nomor_terakhir, $kunci, $jumlah_karakter = 0){
$nomor_baru = intval(substr($nomor_terakhir, strlen($kunci))) + 1;
$nomor_baru_plus_nol = str_pad($nomor_baru, $jumlah_karakter, "0", STR_PAD_LEFT);
$kode = $kunci . $nomor_baru_plus_nol;
return $kode;}
$date_now=date('dmY');
$batch=buatkode($data_oto['maksi'],$date_now, 1);
mysql_query("INSERT INTO batch2(id_batch2,id_item) VALUES('$batch','$_POST[item]')");
A:
For generating a batch code it is a better way to including date on it. But for identifying the product and and its batch it should be better to include some standard format on the entire code
First 6 letters => date
Next three letters => Identify Product using any product identification code with preceding zeros or any symbols For Example "P1"
Next three letters => identifying batch code with preceding zeros or any symbols For Example "B1"
You can generate this by following method:
$date = date("dmY");
$product_identification = "P1";//this can be replaced by your own variable
$product_code = str_pad($product_identification, 3, "-", STR_PAD_LEFT); //Here "-" symbol used for preceding letters we can replace with 0 if required
$batch_identification = "B1"; //this can be replaced by your own variable
$batch_code = str_pad($batch_identification, 3, "-", STR_PAD_LEFT); //Here "-" symbol used for preceding letters we can replace with 0 if required
$code = $date.$product_code.$batch_code;
print $code; //will output 29092016-P1-B1
Based on this way you can generate such codes by your own
| {
"pile_set_name": "StackExchange"
} |
Q:
app.yaml vs appengine-web.xml which one to use?
I am using Google App Engine flexible to deploy my spring boot app. I see the configuration can be specified by app.yaml or appengine-web.xml. However, my questions are,
Which configuration file should I use for the Spring boot app, yaml or xml?
If xml, should I create web/WEB-INF/ folder and place the appengine-web.xml under that?
Also, if xml how to specify the "flex" environment choice (via which property) in the xml?
Thanks in advance.
A:
You need to use both files.
The app.yaml file covers configurations applicable to all flexible environment apps/services, regardless of the language they're written in, like:
the flex environment and other General settings
Network settings
Health checks
Service scaling settings
The web.xml config file has a very specific coverage, which doesn't overlap the app.yaml file's coverage:
The web.xml file is only used when deploying a Java app to a runtime
that includes the Jetty9/servlet3 server. For more details, see the
Java 8 / Jetty 9.3 Runtime.
As for your #2 question, you may have been looking at the standard env docs (check the docs/standard or docs/flexible strings in the doc's URL). From web.xml:
This file is named web.xml, and resides in the app's WAR under the
WEB-INF/ directory. web.xml is part of the servlet standard for
web applications.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to monitor Wildfly with Nagios?
I've read that it's possible to monitor Wildfly with Nagios in links like this one and I also know that there are solutions that provide that service as well.
Does anybody knows how to do that, how to monitor Wildfly with Nagios, any recommendations on how to start? Any reference would be very appreciated.
A:
You can consider using JSON based HTTP management API. Sample plugin (Python based) for JBossAS - standalone mode is available here https://github.com/aparnachaudhary/nagios-plugin-jbossas7. This should also work for WildFly.
Some details about WildFly HTTP Management API can be found here https://docs.jboss.org/author/display/WFLY9/The+HTTP+management+API
| {
"pile_set_name": "StackExchange"
} |
Q:
Nodejs 12 Callback not working for mysql connection?
I'm writing this code to run in AWS Lambda.
Looking at mysql connection documentation
I expect, if things are working with out errors, to get the message "Database connected successfully!"
and then to get a message "connected as id " but that is not the order that it is happening. Here is my code.
'use strict';
let mysql = require('mysql');
const connection = mysql.createConnection({
dateStrings: true,
host : process.env.rds_host,
user : process.env.rds_user,
password : process.env.rds_password,
database : process.env.rds_database,
port : process.env.rds_port
});
exports.handler = (event, context, callback) => {
//prevent timeout from waiting event loop
context.callbackWaitsForEmptyEventLoop = false;
let sql = 'SELECT * FROM company ORDER BY points DESC, name ASC';
let data = null;
console.log('\nGetCompanies SQL: ', sql);
let responseBody = "";
let statusCode = 0;
connection.connect(function(err) {
if (err) {
statusCode = 500;
responseBody = err;
}
else{
console.log("Database connected successfully!");
statusCode = 200;
responseBody = "Database connected successfully!";
}
});
console.log('connected as id ' + connection.threadId);
connection.query(sql, data, function(queryError, results) {
if(queryError) {
console.error(queryError.message);
callback(queryError);
}
else
{
console.log('\nGetCompanies Results: ', results[0]);
callback(null, results);
}
});
};
Here is the logged output:
INFO
GetCompanies SQL: SELECT * FROM company ORDER BY points DESC, name ASC 2020-01-01T11:52:57.813Z
INFO connected as id null 2020-01-01T11:52:57.952Z
INFO Database connected successfully! 2020-01-01T11:52:57.974Z
My thought was that the function that I supply to:
connection.connect(function(err) {
would execute before any code after connection.connect. Am I wrong to think that?
One more question: Why is the
connected as id null? I got that code (connection.threadId) straight from the mysql docs.
I know this is no big deal if all it effects is the order of log messages but I have other functions where I can't make queries because the connection isn't there yet.
It's quite confusing when it blows right past the
if (err) {
statusCode = 500;
responseBody = err;
}
else{
<do some connection.query code here>
}
I put these log messages here because this method works and my other method doesn't.
A:
would execute before any code after connection.connect. Am I wrong to think that?
The function you are passing to the connection.connect is called a
callback function. what that mean is, it will be called only after a
successful connection(or after the connection attempt is errored) is made. So the answer is no. The connection.connect is called and then immediately it will call the next statement. It will not wait for the current statement, because javascript is event driven and non blocking.
connected as id null? I got that code (connection.threadId) straight from the mysql docs.
This is because of the previous statement, you are logging the connectionId before a connection is obtained.
using Callbacks
Your code should be like the below. I haven't modified much, the connection to the database is made only after the callback of the connect event is called.
exports.handler = (event, context, callback) => {
//prevent timeout from waiting event loop
context.callbackWaitsForEmptyEventLoop = false;
let sql = 'SELECT * FROM company ORDER BY points DESC, name ASC';
let data = null;
console.log('\nGetCompanies SQL: ', sql);
let responseBody = "";
let statusCode = 0;
connection.connect(function (err) {
// we are inside the callback function a successful connection has been obtained , or error connecting to database
if (err) {
statusCode = 500;
responseBody = err;
}
else {
console.log("Database connected successfully!");
statusCode = 200;
responseBody = "Database connected successfully!";
}
// connection exists
console.log('connected as id ' + connection.threadId);
connection.query(sql, data, function (queryError, results) {
if (queryError) {
console.error(queryError.message);
callback(queryError);
}
else {
console.log('\nGetCompanies Results: ', results[0]);
callback(null, results);
}
});
});
};
using promises
If you could use promises to make your code readable and understandable.
import { promisify } from 'util';
exports.handler = async (event, context) => {
//prevent timeout from waiting event loop
context.callbackWaitsForEmptyEventLoop = false;
let sql = 'SELECT * FROM company ORDER BY points DESC, name ASC';
let data = null;
console.log('\nGetCompanies SQL: ', sql);
const connect = promisify(connection.connect);
const query = promisify(connection.query);
try {
const connection = await connect();
// connection exists
console.log('connected as id ' + connection.threadId);
const results= await query(sql);
return {
statusCode: 200,
responseBody: JSON.stringify(results)
}
} catch (err) {
return {
statusCode: 500,
responseBody: err.message
}
}
};
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create multi dimension arrays
When user submits form the data is stored in array & serialized & stored in the database, when user again submit another form then that data is stored in array & previous serialized array is fetched from database & is unserialized.
Now i want both these array to be multi dimensional, here is what I've tried
$post = array();
$post[] = $co_name = test_input($_POST['co_name1']);
this array is fetched from database
$db = unserialize($db);
$db[] = $post;
print_r($db);
After Printing this is what i get
Array
(
[0] => company_name
[1] => country
[2] => city
[3] => state
[4] => pincode
[5] => 2008
[6] => 01
[7] => 2008
[8] => Array
(
[0] => company_name
[1] => country
[2] => city
[3] => state
[4] => pincode
[5] => 2008
[6] => 01
[7] => 2008
)
)
Now my problem is second array is assigned to 8, how to perfectly create multi dimension array
My desired output is my array should like this
array(
0=>array(
0=>company_name
1=>country
),
1=>array(
0=>company_name
1=>location
)
)
A:
The following will give you a numerically indexed array with your POST data as one value and DB data as another value of a new array. If you var_dump / print_r() this, the output will look similar to your desired output:
$newArray = array($post, $db);
However; Your desired output shows a reduced number of keys for each result:
company_name
country
...(or did you only write these to make it easier to read?)
If you do want just those two keys, consider using PHP's array_filter function which takes your combined array (above: $newArray) and a callback function as arguments. This allows you to manipulate any of the keys and values of the input array, to make the returned array look exactly as you like.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I skip spaces when parsing a haskell string
I have the following definition in a parser using the Haskell ReadP library:
expr = chainl1 comp (string "===" >> return fun6)
How can I skip spaces before the === operator? I don't know how to include it in this syntax.
A:
ReadP has skipSpaces for exactly that usecase; your parser then becomes
expr = chainl1 comp (skipSpaces >> string "===" >> return fun6)
| {
"pile_set_name": "StackExchange"
} |
Q:
How an ETF pays dividend to shareholders if a holding company issues dividend
If I hold 100 shares of SPY ETF, and one of the participating companies (A) pays out a dividend of 1$ per share. Will I get any dividend? If yes, I guess I will not get 1$ per share of SPY.
It seems I will get x $/share of SPY, where x is the fraction of A in the SPY holdings.
Is this right?
A:
Join me for a look at the Quote for SPY.
A yield of 1.82%. So over a year's time, your $100K investment will give you $1820 in dividends.
The Top 10 holdings show that Apple is now 3% of the S&P. With a current dividend of 2.3%.
Every stock in the S&P has its own different dividend. (Although the zeros are all the same. Not every stock has a dividend.) The aggregate gets you to the 1.82% current dividend. Dividends are accumulated and paid out quarterly, regardless of which months the individual stocks pay.
A:
The amount, reliability and frequency of dividends paid by an ETF other than a stock, such as an index or mutual fund, is a function of the agreement under which the ETF was established by the managing or issuing company (or companies), and the "basket" of investments that a share in the fund represents.
Let's say you invest in a DJIA-based index fund, for instance Dow Diamonds (DIA), which is traded on several exchanges including NASDAQ and AMEX. One share of this fund is currently worth $163.45 (Jan 22 2014 14:11 CDT) while the DJIA itself is $16,381.38 as of the same time, so one share of the ETF represents approximately 1% of the index it tracks. The ETF tracks the index by buying and selling shares of the blue chips proportional to total invested value of the fund, to maintain the same weighted percentages of the same stocks that make up the index. McDonald's, for instance, has an applied weight that makes the share price of MCD stock roughly 5% of the total DJIA value, and therefore roughly 5% of the price of 100 shares of DIA.
Now, let's say MCD issued a dividend to shareholders of, say, $.20 per share. By buying 100 shares of DIA, you own, through the fund, approximately five MCD shares, and would theoretically be entitled to $1 in dividends. However, keep in mind that you do not own these shares directly, as you would if you spent $16k buying the correct percentage of all the shares directly off the exchange. You instead own shares in the DIA fund, basically giving you an interest in some investment bank that maintains a pool of blue-chips to back the fund shares. Whether the fund pays dividends or not depends on the rules under which that fund was set up. The investment bank may keep all the dividends itself, to cover the expenses inherent in managing the fund (paying fund management personnel and floor traders, covering losses versus the listed price based on bid-ask parity, etc), or it may pay some percentage of total dividends received from stock holdings. However, it will virtually never transparently cut you a check in the amount of your proportional holding of an indexed investment as if you held those stocks directly. In the case of the DIA, the fund pays dividends monthly, at a yield of 2.08%, virtually identical to the actual weighted DJIA yield (2.09%) but lower than the per-share mean yield of the "DJI 30" (2.78%).
Differences between index yields and ETF yields can be reflected in the share price of the ETF versus the actual index; 100 shares of DIA would cost $16,345 versus the actual index price of 16,381.38, a delta of $(36.38) or -0.2% from the actual index price. That difference can be attributed to many things, but fundamentally it's because owning the DIA is not the exact same thing as owning the correct proportion of shares making up the DJIA. However, because of what index funds represent, this difference is very small because investors expect to get the price for the ETF that is inherent in the real-time index.
| {
"pile_set_name": "StackExchange"
} |
Q:
Visualisation of proximity of points to 4d-sphere in Python
I am looking for a way to visualise the proximity of points to a 4-dimensional sphere. For a circle I can simply use a scatter plot and observe the distribution of points near the unit circle as shown below. For a 3D sphere I can do something similar. However, how would I go about visualising this for a 4-dimensional sphere?
Is there a way to reduce the dimensionality to project the entire space into 3D? Obviously I can just take the norm of the points and see how close it is to 1, but I would like to have a visual aid of some sort.
A:
Here is one way to convert 4-dimensional coordinates into 3-dimenstional coordinates that will give you a visualization of the distances of the points from the 4D sphere. Since you show no code or equations of your own I'll just give an overview. If you give more details on your own work then you can ask me for more details.
Take a point in 4 dimensions, let's say (x, y, z, w). Then convert those Cartesian coordinates to 4D spherical coordinates
(r, t1, t2, t3), where r is the distance of the point to the origin and t1, t2, t3 are reference angles. Formulas for the conversion are in Wikipedia's entry for n-sphere, though in my preferred transformation I would reverse the order of the Cartesian coordinates. In other words, we get the relations
w = r * cos(t1)
z = r * sin(t1) * cos(t2)
y = r * sin(t1) * sin(t2) * cos(t3)
x = r * sin(t1) * sin(t2) * sin(t3)
We now map that point to a point in 3D space by changing angle t1 to 90° (or pi/2 radians). This has the effect of "rotating" the point away from the w axis down into 3D space in regular spherical coordinates. The distances from the origin and from any 4-sphere centered at the origin were not changed. Now convert to 3D Cartesian coordinates with
z = r * cos(t2)
y = r * sin(t2) * cos(t3)
x = r * sin(t2) * sin(t3)
Now graph those as usual. Since distances to the origin and to the 4-sphere were not changed, this should be a useful visualization.
Looking at those equations, we realize that the values of x, y, and z were all divided by sin(t1). That means you could optimize the calculations by finding only sin(t1) with the formula
sin(t1) = sqrt((x*x + y*y + z*z) / (x*x + y*y + z*z + w*w))
There is no need to find r, t2, or t3 or even t1 itself. You need to be careful for the special case sin(t1) == 0.0, which happens only when x == y == z == 0. I would then map the 4D point (0, 0, 0, w) to the 3D point (w, 0, 0) and the visualization should still work well.
There are other, similar transformations you could use that may be more useful, such as changing angle t3 to zero rather than changing t1. This slightly reduces the calculations but you would need to permute the coordinates and the visualization uses only half the 3-sphere, I believe.
Of course, one way to graph that 3D point to a computer graphing surface is to now set t2 to 90° to get
y = r * cos(t3)
x = r * sin(t3)
and you will get a graph very much like the one you show in your question.
(NOTE: I changed the formulas above, based on further consideration of the best visualization.)
| {
"pile_set_name": "StackExchange"
} |
Q:
What area of Abstract Algebra do you find most interesting?
For my Abstract Algebra class, we will be doing small presentations (2 class periods) covering some topic in Abstract Algebra. Thus far, I have studied groups, rings, fields, modules, tensor products, exact sequences, algebras, some basic category theory, and some other things.
This semester we are presenting some subtopic of Abstract Algebra (presumably an extension of what we have already learned).
What are some topics you would suggest and why?
A:
Another topic could be the study of the three famous geometric constructions with compass and straight edge, or better, that they cannot be constructed as such: Squaring a circle, doubling the volume of a cube and trisecting an angle. For that you need rings and fields and all sorts of abstract algebra stuff. Did it a long time ago, forgotten for the most part, but this lingered in my mind.
A:
Geometric constructions are a cool application of field theory. For example, if a number $\alpha$ is constructible as a length, then the field extension $\mathbb{Q}[\alpha]$ is a degree power-of-two field extension over the rationals.
Further, asking whether a regular $n$-gon is constructible with a compass and straightedge is equivalent to asking whether the $n$th cyclotomic field can be built as a tower of quadratic field extensions.
A:
One topic that I find interesting is finite reflection groups. They have a lot of importance in studying highly symmetric geometric spaces.
A related, but distinct, topic would be to discuss the 17 wallpaper groups and illustrate the various patterns that are possible.
| {
"pile_set_name": "StackExchange"
} |
Q:
How Do I Add a Class to a CodeIgniter Anchor
I have the following:
'.anchor('','Home').'
and I want to add the following CSS class to it:
class="top_parent"
This is so that when it's rendered in the browser, the code will look something like the following:
<a href="#" class="top_parent">Home</a>
Thanks in advance, and any help is greatly appreciated.
--
Tom
A:
anchor('#', 'Home', array('class' => 'top_parent'));
A:
The Codeignitor function is defined as such:
function anchor($uri = '', $title = '', $attributes = '')
I would try sending an array with a class key and value first.
These functions are found inside the \system\helpers\ folder.
A:
You can specify an associative array of attributes for your Anchor. So, for example:
anchor('', 'Home', array('class' => 'top_parent'));
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieve string from Parse.com
I want to retrieve the current users string value on a specific column from the user class in Parse.com
I have tried this code:
NSString *columnString = [[[PFUser currentUser] objectForKey:@"columnKey"] stringValue];
This code logged an error saying "unrecognized selector sent to instance.."
What is the correct way to do this?
A:
If your column datatype is String then try below snippet.
NSString *str_ColumnString = [NSString stringWithFormat:@"%@",[[PFUser currentUser]valueForKey:@"columnKey"]];
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a JDO method analogous to the low-level App Engine Datastore API method get(Iterable keys)?
I want to get multiple entities from the App Engine datastore by passing a list of keys as the parameter. The low level API has a method for this: get(Iterable keys). Is there an analogous method available for the JDO interface as well?
A:
Try PersistenceManager.getObjectsById(Collection... keys)
| {
"pile_set_name": "StackExchange"
} |
Q:
List Index out of Range while constructing a Graphic
I'm having an error:
"Traceback (most recent call last):
File "C:\Python27\Lib\idlelib\Task4", line 13, in
if (y[i]-3)
With the following code:
from numpy import*
from matplotlib import pyplot
import random
Player1 = raw_input("Player 1 Name:")
Player2 = raw_input("Player 2 Name:")
pyplot.axis([0,8000,0,200])
a = random.randint(0,101)
x = range(8000)
y = [a]`enter code here`
i=0
while i<len(x):
b = random.randint(0,101)
if (y[i]-3)<b and b<(y[i]+3):
y.append(b)
i+=1
pyplot.plot(x,y)
pyplot.show()
Please help! Thanks!
A:
I suppose you intended to do the following.
if(y[0]-3)<b and b<(y[0]+3) ...
or
if(a-3)<b and b<(a+3) ...
The y=[a] statement generates a single element list containing only the generated randint.
There is a better trick for this in Python. Python, being awesome, can understand the following too
if (a-3) < b < (a+3) ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Nokogiri to scrape itemprop data
I have a div which looks like the following and I am trying to scrape the itemprop datetime data but I can't seem to get it to work.
<time itemprop="startDate" datetime="2019-03-28T19:00:00">
Thursday, March 28, 2019
</time>
The script below pulls the text for the date just fine (i.e., . Thursday, March 28, 2019), but the time selector throws this error.
undefined method `text' for nil:NilClass (NoMethodError)
I've searched Stackoverflow, and I've tried to map the time data but nothing works.
require 'rubygems'
require 'nokogiri'
require 'open-uri'
my_local_filename = "C:/data-hold-classes/Santa Fe College" + ".html"
data = Nokogiri::HTML(open(my_local_filename), "r")
classes = data.css(".col-xs-7")
classes.each do |item|
class = item.at_css("a b").text.strip #=> All details
date = item.at_css("a > div > time").text.strip #==> Thursday, March 28, 2019
#time = item.at_css("a datetime").text.strip #==>
puts class
puts date
#puts time
puts " "
end
My goal is to pull the datetime portion of the div so I can format it as time (e.g., 8:00PM)
A:
The line item.at_css("a > div > time") returns an element time.
a > div > time is a nested path to get that element. Now, you wanna get time, an attribute, not html element, so path a datetime will not return anything (cause we have no datetime element).
You can get date by using:
item.at_css("a > div > time")["datetime"].strip
Hope it helps :D
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL - String concatenated grouping WITHOUT DISTINCT
I'm wondering if this is possible - I have a table like this:
pk int, num int, name varchar(1)
1 1 'a'
2 1 'b'
3 1 'c'
4 1 'd'
5 1 'e'
6 2 'f'
7 2 'g'
8 2 'h'
9 2 'i'
10 2 'j'
And I'd like an output like this WITHOUT using a DISTINCT clause:
num result
1 a,b,c,d,e
2 f,g,h,i,j
Here are ddl statements for testing:
declare @tbl table (pk int, num int, name varchar(1))
insert into @tbl select 1, 1, 'a'
insert into @tbl select 2, 1, 'b'
insert into @tbl select 3, 1, 'c'
insert into @tbl select 4, 1, 'd'
insert into @tbl select 5, 1, 'e'
insert into @tbl select 6, 2, 'f'
insert into @tbl select 7, 2, 'g'
insert into @tbl select 8, 2, 'h'
insert into @tbl select 9, 2, 'i'
insert into @tbl select 10, 2, 'j'
The following query works, but I'd like to eliminate the DISTINCT clause if possible:
select DISTINCT num, stuff((select ',' + name from @tbl where num = t.num for xml path('')), 1, 1, '')
from @tbl t
Any idea how to do this in SQL 2012+?
A:
If you don't have a list of num values that you want, then you can create one. One rather silly way is:
select t.num,
stuff( (select ',' + name
from @tbl t2
where t2.num = t.num
for xml path('')
), 1, 1, '')
from (values (1), (2)) as t(num);
More commonly, this would be written as:
select t.num,
stuff( (select ',' + name
from @tbl t2
where t2.num = t.num
for xml path('')
), 1, 1, '')
from (select distinct num from @tbl) t;
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display "from" fields in comments via Facebook Graph API
I would like to find the id (app-scoped) for someone who has posted a comment on a public page.
For example, I get a list of recent posts/comments on the NY Times page via:
v2.11/nytimes/feed?fields=comments.limit(10){message,created_time,from},name,message,from&limit=2
The data returned looks like this:
"comments": {
"data": [
{
"message": "Wouldn’t know. Not paying $13/mo for this.",
"created_time": "2017-12-10T05:57:18+0000",
"id": "10151412260164999_10151414049324999"
}
],
There is no from field. The same is also true if I attempt to view the comment directly using it's id with
v2.11/10151412260164999_10151414049324999?fields=from,message,created_time
I have tried using the Facebook Graph API Explorer, using both my User Token, as well as an App Token.
A:
Since v2.11 of the Graph API, you need a Page Token to get user data of comments: https://developers.facebook.com/docs/graph-api/changelog/version2.11#gapi-90
User information will not be included in GET responses for any objects owned by (on) a Page unless the request is made with a Page access token. This affects all nodes and edges that return data for objects owned by a Page.
In other words: You can only get user information if you manage the Page.
Edit: Since the latests update in the Graph API, you have to get the App reviewed and you must go through Business Verification or Individual Verification. (thanx @Guiman04)
| {
"pile_set_name": "StackExchange"
} |
Q:
Error using categorical Abstract classes cannot be instantiated. Class 'categorical' defines abstract methods and/or properties
Why am I getting this error in matlab when running this command:
sp = categorical(species);
I have loaded two vectors of which one is:
species <150 x 1 cell>
A:
I am using MATLAB-2013a so, the command:
sp = categorical(species);
As we know species is loaded as a column vector and it needs to be converted to a matrix of double (positive values). We have to run following commands in order to make this vector compatible to the functions input-argument:
sp = nominal(species);
sp = double(sp);
These above two lines do the same work in MATLAB-2013a (as much as I know) in replacement for
sp=categorical(species);
| {
"pile_set_name": "StackExchange"
} |
Q:
Explode over every other word
Lets say I have a string:
$string = "This is my test case for an example."
If I do explode based on ' ' I get an
Array('This','is','my','test','case','for','an','example.');
What I want is an explode for every other space:
Array('This is','my test','case for','an example.').
The string may have an odd # of words, so the last item in the array may not contain two words.
Anyone know how to do this?
A:
I would look through the results, and concatenate the strings after the fact.
A:
$matches = array();
preg_match_all('/([A-Za-z0-9\.]+(?: [A-Za-z0-9\.]+)?)/',
'This is my test case for an example.',$matches);
print_r($matches);
yields:
Array
(
[0] => Array
(
[0] => This is
[1] => my test
[2] => case for
[3] => an example.
)
[1] => Array
(
[0] => This is
[1] => my test
[2] => case for
[3] => an example.
)
)
update fixed it to match a single word at the end of the sentence
A:
A function which can be used for different delimiters and numbers.
function explodeEveryNth($delimiter, $string, $n) {
$arr = explode($delimiter, $string);
$arr2 = array_chunk($arr, $n);
$out = array();
for ($i = 0, $t = count($arr2); $i < $t; $i++) {
$out[] = implode($delimiter, $arr2[$i]);
}
return $out;
}
Test code
var_dump(explodeEveryNth(' ', 'This is a test string', 2));
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS verically align text in anchor when display type block
I'm not too sure this can be done without pseudo elements - but what do I know.
I have a tab element which is an <LI>.
Inside each LI there is an <A>.
I want to achieve 2 things:
Make the A element fill the space of its parent LI. The height is
known but the width is variable.
Centre the text vertically,
Obviously this is easily done with 1 liners, simply add display:block and line-height to the anchor.
However, I need to allow for line wraps too.
So, to recap: fill the available space in the parent and vertically align text within its own block.
I can use flexbox or whatever, but at the moment, I can do one or the other not both.
A:
I'm using flex-box to wrap the items, giving the li elements a height of 50 px, and then the a tag a line-height of 50px.
Because of the line-height, the text is vertically centered.
Because of flex-box, the items wrap multiline.
ul {
width: 200px;
height: 200px;
border: 1px solid #c3c3c3;
list-style:none;
margin:0;
padding:0;
display: -webkit-flex; /* Safari */
-webkit-flex-wrap: wrap; /* Safari 6.1+ */
display: flex;
flex-wrap: wrap;
}
ul li {
width: 50px;
height: 50px;
position:relative;
text-align:center;
}
ul li a {
height:100%;
display:block;
line-height:50px;
}
ul li a:hover {
background-color:#333;
color:white;
}
<ul>
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
</ul>
| {
"pile_set_name": "StackExchange"
} |
Q:
Is Swift a dynamic or static language?
I'm just curious if Swift is dynamic like php or static, I mean can I generate classes while an application is running?
A:
It is static - very static. The compiler must have all information about all classes and functions at compile time. You can "extend" an existing class (with an extension), but even then you must define completely at compile time what that extension consists of.
Objective-C is dynamic, and since, in real life, you will probably be using Swift in the presence of Cocoa, you can use the Objective-C runtime to inject / swizzle methods in a Swift class that is exposed to Objective-C. You can do this even though you are speaking in the Swift language. But Swift itself is static, and in fact is explicitly designed in order to minimize or eliminate the use of Objective-C-type dynamism.
A:
Swift itself, is statically typed. When used with Cocoa, you get access to the objective-c runtime library which gives you the ability to use dynamic classes, messages and all. This doesn't mean the language itself is dynamically typed. You could do the same with C or any other language that supports a bridge to C by using libobjc.A.dylib.
| {
"pile_set_name": "StackExchange"
} |
Q:
Insert to particular location in Oracle DB table?
Suppose I have a table containing the following data:
Name | Things
-------------
Foo | 5
Bar | 3
Baz | 8
If I want to insert a row, so that the final state of the table is:
Name | Things
-------------
Foo | 5
Qux | 6
Bar | 3
Baz | 8
Is this possible?
I understand we don't typically rely on the order of rows in a table, but I've inherited some code that does precisely that. If I can insert to a location, I can avoid a significant refactor.
A:
As you say, you can't rely on the order of rows in a table (without an ORDER BY).
I would probably refactor the code anyway - there's a chance it will break with no warning at some point in the future - surely better to deal with it now under controlled circumstances?
A:
I would add a FLOAT column to the table and if you wanted to insert a row between the rows whose value in that column was 7.00000 and 8.000000 respectively, your new row would have value 7.50000. If you then wanted to insert a row between 7.00000 and 7.50000 the new row would get 7.25000, and so on. Then, when you order by that column, you get the columns in the desired order. Fairly easy to retrofit. But not as robust as one likes things to be. You should revoke all update/insert permissions from the table and handle I/O via a stored procedure.
| {
"pile_set_name": "StackExchange"
} |
Q:
Account is not allowed to suggest edits
From the morning, I was unable to edit any posts . I got the 'edit' tab freezed on my side. I can't click it anymore. When I bring my cursor to it, it says : " Account is not allowed to suggest edits ".
Can I know the reason behind that ? .
Thank you.
A:
Please read this, in particular:
What about abuse?
There are strict limits enforced. If a user (anonymous or registered) submits many rejected edits they will be automatically banned from suggesting edits for 7 days. The fixed size queue also helps protect us from abuse.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to wrap lists with proper indentation when using org-indent-mode?
In Org-mode I can get headlines wrap with proper indentation by using org-indent-mode. How can I do the same for lists, that is, how can I make it so that lists in Org-mode wrap with proper indentation?
If I insert
* Very very very very very very very very very very very very very very very very very very very long line
- Very very very very very very very very very very very very very very very very very very very long line
into an Org-mode buffer with org-indent-mode I get the following:
* Very very very very very very very very very very very very very very very
very very very very long line
- Very very very very very very very very very very very very very very very
very very very very long line.
Note that the second line of the list (the one starting with -) is not properly indented because it should align with the first letter of the start of the list. What I would expect is the following:
* Very very very very very very very very very very very very very very very
very very very very long line
- Very very very very very very very very very very very very very very very
very very very very long line.
I am running Org-mode 7.6 in GNU Emacs 23.3.1.
A:
This now seems to be the standard in Org-mode version 7.8.03. The news for the release of 7.8 stated that org-ident.el had been refactored for some improvements when used with visual-line-mode (and should be faster).
As a test I ran emacs -q and used Org-mode version 7.7 that comes with emacs24. It showed the undesired behaviour. Adding my local copy of 7.8 to my load-path and reloading org then refreshing the buffer C-c C-c on:
#+STARTUP: indent
added the extra spaces on additonal lines so that indentation matched what you expect.
Upgrading to 7.8.03 (or to current git-head) will provide you with the desired functionality.
Test results
Org-Mode 7.7
#+STARTUP: indent
* Very very very very very very very very very very very
very very very very very very very very long line
- Very very very very very very very very very very very
very very very very very very very very long line.
Org-Mode 7.8.03
#+STARTUP: indent
* Very very very very very very very very very very very
very very very very very very very very long line
- Very very very very very very very very very very very
very very very very very very very very long line.
| {
"pile_set_name": "StackExchange"
} |
Q:
"Many lost their life" or "Many lost their lives"
Many individuals lost their individual life.
or
Many individuals list their individual lives.
Each person has one life right?
A:
In cases like this, and unlike some other languages, English tends to use what is sometimes called a "distributed plural", so even though each person only has one life, the plural is used as though representing "all the lives together". Similarly: "The teacher asked the pupils to get their notebooks out".
A:
In the simplest sentences, the object agrees in number with the subject.
He is a student.
They are students.
However, the object does not need to agree with the number of the subject and the verb. None of these is incorrect:
Most families today own a car.
Both of them sprained an ankle during the trek.
They all thought they had an answer to the problem.
Teenage vandals are a problem in this neighbourhood.
In your sample sentences, the object life takes the plural pronoun their, and each of the sentences carries a different meaning.
Many lost their life. (All of them together had one life to lose: their life.)
Many lost their lives. (Each of them lost one or more lives, practically understood to mean that each of them lost their own life as people usually have only the one life to lose.)
All my opponents lost a life trying to collect that torque bow in Level 7 of the game.
All my opponents lost lives trying to collect that torque bow in Level 7 of the game.
You could also take a look at page 54 of Rodney Huddleston's English Grammar for some more details and examples.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can one specify a custom force function for a force-directed layout?
I want to experiment with an alternative family force functions for force-directed graph layouts.
For each node n_i, I can define a "force function" f_i such that
f_i ( n_i ) is identically zero; and
f_i ( n_j ), where n_i != n_j, is the force on node n_i that is due to some other node n_j.
The net force on node n_i should then be the vector sum of the forces f_i ( n_j ), where n_j ranges over all other nodes1.
Is there some way to tell d3.js to use these custom force functions in the layout algorithm?
[The documentation for d3.js's force-directed layout describes various ways in which its built-in force function can be tweaked, but I have not been able to find a way to specify an entirely different force function altogether, i.e. a force function that cannot be achieved by tweaking the parameters of the built-in force function.]
1IOW, no other/additional forces should act on node n_i besides those computed from its force function f_i.
A:
To achieve this, you'll need to create your own custom layout. There's no tutorial for this that I'm aware of, but the source code for the existing force layout should be a good starting point as, by the sound of it, the structure of your custom layout would be very similar to that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reading all lines in a file providing a relative path in .NET (F#)
I am looking for a method (I guess it is a static method) in the .NET libraries to let me specify a relative path when reading a file.
My code is:
let mycontent = Syste..IO.File.ReadAllLines ("C:\...\myfile.txt")
However I would like to specify a relative path. How to? It is some sort of MapPath I guess...
A:
A relative path is specified like this:
System.IO.File.ReadAllLines("myfile.txt");
which will search myfile.txt relative to the working directory executing your application. It works also with subfolders:
System.IO.File.ReadAllLines(@"sub\myfile.txt");
The MapPath function you are referring to in your question is used in ASP.NET applications and allows you to retrieve the absolute path of a file given it's virtual path. For example:
Server.MapPath("~/foo/myfile.txt")
and if your site is hosted in c:\wwwroot\mysite it will return c:\wwwroot\mysite\foo\myfile.txt.
A:
If you want paths relative to the directory in which your application resides (as opposed to the current working directory, which may be different), you can do the following:
module Path =
let appDir = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
let makeAppRelative fileName = System.IO.Path.Combine(appDir, fileName)
//Usage
let fullPath = Path.makeAppRelative "myfile.txt"
A:
You can pass a relative path to any function that accepts a file path, and it will work fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Matplotlib Plot time series with different periodicity
I have 2 dfs. One of them has data for a month. Another one, averages for the past quarters. I wanna plot the averages in front of the monthly data. How can I do it? Please note that I am trying to plot averages as dots and monthly as line chart.
So far my best result was achieved by ax1=ax.twiny(), but still not ideal result as data point appear in throughout the chart, rather than just in front.
import pandas as pd
import numpy as np
import matplotlib.dates as mdates
from matplotlib.ticker import ScalarFormatter, FormatStrFormatter, FuncFormatter
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
date_base = pd.date_range(start='1/1/2018', end='1/30/2018')
df_base = pd.DataFrame(np.random.randn(30,4), columns=list("ABCD"), index=date_base)
date_ext = pd.date_range(start='1/1/2017', end='1/1/2018', freq="Q")
df_ext = pd.DataFrame(np.random.randn(4,4), columns=list("ABCD"), index=date_ext)
def drawChartsPlt(df_base, df_ext):
fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
number_of_plots = len(df_base.columns)
LINE_STYLES = ['-', '--', '-.', 'dotted']
colormap = plt.cm.nipy_spectral
ax.set_prop_cycle("color", [colormap(i) for i in np.linspace(0,1,number_of_plots)])
date_base = df_base.index
date_base = [i.strftime("%Y-%m-%d") for i in date_base]
q_ends = df_ext.index
q_ends = [i.strftime("%Y-%m-%d") for i in q_ends]
date_base.insert(0, "") #to shift xticks so they match chart
date_base += q_ends
for i in range(number_of_plots):
df_base.ix[:-3, df_base.columns[i]].plot(kind="line", linestyle=LINE_STYLES[i%2], subplots=False, ax=ax)
#ax.set_xticks(date_base)
#ax.set_xticklabels(date_base)
# ax.xaxis.set_major_locator(ticker.MultipleLocator(20))
ax.xaxis.set_major_locator(ticker.LinearLocator(len(date_base)))
ax.xaxis.set_major_formatter(plt.FixedFormatter(date_base))
fig.autofmt_xdate()
# ax1=ax.twinx()
ax1=ax.twiny()
ax1.set_prop_cycle("color", [colormap(i) for i in np.linspace(0,1,number_of_plots)])
for i in range(len(df_ext.columns)):
ax1.scatter(x=df_ext.index, y=df_ext[df_ext.columns[i]])
ax.set_title("Test")
#plt.minorticks_off())
ax.minorticks_off()
#ax1.minorticks_off()
#ax1.set_xticklabels(date_base)
#ax1.set_xticklabels(q_ends)
ax.legend(loc="center left", bbox_to_anchor=(1,0.5))
ax.xaxis.label.set_size(12)
plt.xlabel("TEST X Label")
plt.ylabel("TEST Y Label")
ax1.set_xlabel("Quarters")
plt.show()
drawChartsPlt(df_base, df_ext)
A:
The way I ended up coding it is by saving quarterly index of df_ext to a temp variable, overwriting it with dates that are close to df_base.index using pd.date_range(start=df_base.index[-1], periods=len(df_ext), freq='D'), and the finally setting the dates that I need with ax.set_xticklabels(list(date_base)+list(date_ext)).
It looks like it could be achieved using broken axes as indicated Break // in x axis of matplotlib and Python/Matplotlib - Is there a way to make a discontinuous axis?, but I haven't tried that solution.
| {
"pile_set_name": "StackExchange"
} |
Q:
Show / hide Android softkeyboard on fragment replace
I have an Activity with a fragment. Let's say a list fragment with a list of things. Now I want to let the user add a thing, so I use the FragmentManager to replace the list fragment with an insert fragment which has an EditText. The EditText has the focus and the cursor is blinking. But the softkeyboard doesn't open.
Same thing other way round: if the user has entered the new thing and added it to the list, I replace the insert fragment back with a list fragment. But although there is no EditText anymore, the keyboard doesn't close.
What is the correct way to implement this? I can't believe that I have to show and hide the keyboard manually on all transitions?!
A:
I would to following things:
1. Extend Fragment class
2. Override onAttach() and onDetach() callbacks
3. Implement show and hide software keyboard method
sample code:
class MyFragment extends Fragment {
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
//show keyboard when any fragment of this class has been attached
showSoftwareKeyboard(true);
}
@Override
public void onDetach() {
super.onDetach();
//hide keyboard when any fragment of this class has been detached
showSoftwareKeyboard(false);
}
protected void showSoftwareKeyboard(boolean showKeyboard){
final Activity activity = getActivity();
final InputMethodManager inputManager = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), showKeyboard ? InputMethodManager.SHOW_FORCED : InputMethodManager.HIDE_NOT_ALWAYS);
}
}
A:
I have the same problem with my app and finally we have 2 options, at first create a general function and call this in all transitions or create a global transition how this:
public static void RemoveAndReplaceFragment(FragmentManager fragmentManager, int FragmentContent, Fragment PlaceHolderFragment,Activity context){
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragmentManager.findFragmentById(R.id.frgMainActivity))
.commit();
//Close keyBoard in transition
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(
Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.animation_fade_in,R.anim.animation_fade_out);
fragmentTransaction.replace(R.id.frgMainActivity, new PlaceholderFragment_MainActivity_AcceptAndFollowTask()).commit();
}
}
The best way is capture the transition event but we can't in this moment... Tell me if I helps you, good luck!
| {
"pile_set_name": "StackExchange"
} |
Q:
In Scratch, how do you copy a PART of a costume so that you can paste that object onto another costume?
Lets say I have two backdrops. One is a forest with a panda in it. Another is a zoo cage. I want to copy the panda in the forest costume and paste it into the zoo one.
I would prefer not to redraw the panda because I want the panda to look EXACTLY the same. I'd also prefer not to duplicate the forest with the panda in it and then redraw the zoo backdrop around it (although its starting to look like this is my only option).
I tried everything and looked everywhere and can't seem to find a Scratch-platform way of doing it. I simply want to know if there is a way to copy and past a part of a costume (not the whole costume). If its possible, knowing how to do it would be great for future use as well.
A:
Well, you have to delete the forest in the forest backdrop but not the panda. Use the rubber to remove all colors and avoid the panda (if you want to keep the forest backdrop, just duplicate it before).
Now make sure that the panda and the zoo costumes are at the same type (Bitmap or Vectorial)
Then with the selection tool, select the panda and press CTRL + C (or ⌘ + C on a Mac) to copy it. Go on the zoo costume and press CTRL + V (or ⌘ + V) to paste it.
Move it where you want and resize it as you need.
If you need, you can redraw the cage above the panda.
| {
"pile_set_name": "StackExchange"
} |
Q:
what's the difference between kafka.javaapi.* and org.apache.kafka.*?
I am a new learner of kafka.But what make me confused is that there seems to be two packages of kafka clients.
One is kafka.javaapi.* like
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
the other is org.apache.kafka.*. like
import org.apache.kafka.clients.producer.KafkaProducer<K,V>
which is shown is page http://kafka.apache.org/082/javadoc/index.html?org/apache/kafka/clients/producer
I don't know what's their differences.
A:
Before Kafka 0.8.2, kafka.javaapi.producer.Producer was the only official Java client (producer) which is implemented with Scala.
From Kafka 0.8.2, there comes a new Java producer API, org.apache.kafka.clients.producer.KafkaProducer, which is fully implemented with Java.
Kafka 0.8.2 Documentation says
We are in the process of rewritting the JVM clients for Kafka. As of 0.8.2 Kafka includes a newly rewritten Java producer. The next release will include an equivalent Java consumer. These new clients are meant to supplant the existing Scala clients, but for compatability they will co-exist for some time. These clients are available in a seperate jar with minimal dependencies, while the old Scala clients remain packaged with the server.
If you are interested in kafka.javaapi.producer.Producer, refer to 2.1 Producer API in Kafka 0.8.1 Documentation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prism 4.0 : Overriding InitializeShell() Method
I've been going through the documentation for creating Prism applications and setting up the Shell seems to be split into 2 methods, CreateShell() and InitializeShell()
For CreateShell I simply have:
protected override DependencyObject CreateShell()
{
return ServiceLocator.Current.GetInstance<Shell>();
}
The documentation says that code is needed in the IntializeShell() method to ensure it is ready to be displayed. The following is given as an example:
protected override void InitializeShell()
{
Application.Current.MainWindow = (Window)this.Shell;
Application.Current.MainWindow.Show();
}
I have noticed however that if I omit the first line and just call the Show() method it seems to work (MainWindow already appears to have Shell assigned to it). Can you tell me why this is the case, and why we still need to explicity set the MainWindow property here?
Also as I did not specifically register Shell to an interface within the container, how is it able to resolve Shell in CreateShell()?
A:
Question 1: Why does just calling Show() seem to work and why is Application.Current.MainWindow seem to be populated?
There are a few things you should check here. In a typical WPF application, the type for the main window can be specified in the App.xaml. If it is specified, WPF will instantiate one of those for you. This is not desirable because WPF won't use your container to instantiate your shell and any dependencies won't be resolved.
When you run that first line of code in InitializeShell, you'd be replacing the WPF-instantiated Shell object with the one you manually instantiated.
I looked at the code for the MEF and Unity bootstrappers and I don't see anywhere that MainWindow is being set, but I don't know if you might have customized the base bootstrappers, so that's something else to look for.
Show() works because you are simply showing the window you instantiated and the WPF-instantiated one isn't shown. This is my theory, but without seeing your code, it'd be tough to say for sure.
Question 2: How can Unity resolve something that hasn't been registered?
Unity can always resolve a concrete type, regardless of registration. It cannot resolve non-concrete classes that haven't been mapped to a concrete type. This is why Resolve<Shell> works, but Resolve<IMyInterface> doesn't unless you register a type.
| {
"pile_set_name": "StackExchange"
} |
Q:
credit card validation using jquery
The code is not validating the values correctly, when i put in a simple digit it is already triggering the code.
$(".validate-card-num").live('keypress', function() {
var ccNum = $(this).val();
//var visa = /^4[0-9]{12}([0-9]{3})?$/;
//var master = /^5[1-5]([0-9]{14})$/;
if(ccNum.test(/^4[0-9]{12}([0-9]{3})?$/)){
$("#img-visa").css("opacity","1");
$("#img-master").css("opacity","0.3");
}else if(ccNum.test(/^5[1-5]([0-9]{14})$/)){
$("#img-master").css("opacity","1");
$("#img-visa").css("opacity","0.3");
}else
$("#img-master, #img-visa").css("opacity","0.3")
});
for example i put in "5" the value triggers the regex but when i put in another value it disables the regex all together.
A:
You are not using the .test() function correctly.
This function is only available in RegExObject, and you are using it on a string.
Your code should be like this:
var ccNum = "Test CC";
var visa = new RegExp("Paste Your Visa Pattern Here");
//Then do the check
if(visa.test(ccNum)){
console.log('visa card');
}else{
console.log('not visa card');
}
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Command retrieve List nested inside column
Consider this table:
Employees Segment Function
John Retail Sales
Peter Retail Sales
Lucas Retail Sales
Steve Retail Sales
Maria Retail Sales
I want a list resulting, like this: (alias for the first column)
'Area' 'Employees'
Retail John,Lucas,Maria
Sales John,Lucas,Maria
To assemble the query I have only the list of Employees. So the condition should be something, like:
WHERE Employees IN('John','Maria','Lucas').
I only have access to query the DB.
I can mount the Employees list in a row, like this:
SELECT
Employees = Stuff(
(SELECT N', ' + Employees FROM table A WHERE Employees
IN('John','Maria','Lucas') FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)'),1,2,N'');
And I can create the 'Area' by merging Segment and Function like this:
SELECT Segment 'Area' FROM table
WHERE Employees IN('John','Maria','Lucas')
UNION SELECT Function 'Area' FROM table
WHERE Employees IN('John','Maria','Lucas')
I'd like to just merge those two selects using something as UNION, like this:
SELECT
Employees = Stuff(
(SELECT N', ' + Employees FROM table A WHERE Employees
IN('John','Maria','Lucas') FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)'),1,2,N'')
UNION
SELECT Segment 'Area' FROM table
WHERE Employees IN('John','Maria','Lucas')
UNION SELECT Function 'Area' FROM table
WHERE Employees IN('John','Maria','Lucas')
The result came out, like:
'Employees'
John,Maria,Lucas
Retail
Sales
Maybe I'm missing some detail on the UNION syntax, or it's not so simple as I expected.
A:
You can still use your UNION, you just have to do the STUFF() twice.
SELECT DISTINCT Segment AS 'Area'
, Stuff((SELECT N', ' + Employees
FROM table A
WHERE Employees IN('John','Maria','Lucas')
FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'') FROM table
WHERE Employees IN ('John','Maria','Lucas')
UNION
SELECT DISTINCT Func AS 'Area'
, Stuff((SELECT N', ' + Employees
FROM table A
WHERE Employees IN('John','Maria','Lucas')
FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'') FROM table
WHERE Employees IN ('John','Maria','Lucas')
| {
"pile_set_name": "StackExchange"
} |
Q:
how to reverse a stack
I have an assignment where I am suppose to take a single stack, show the output and then reverse it to show the output.
Its suppose to look like this
Stack:
262 115 74 26 34 243 22 734 113 121
Stack Reversed:
121 113 734 22 243 34 26 74 115 262
Instead mine is coming out like this
Stack:
262 115 74 26 34 243 22 734 113 121 121 113 734 22 243 34 26 74 115 262
Stack Reversed:
Can someone please look at my code and see what is going on. I have tried quite a few things but cannot get anything to work.
#include <stdio.h>
#include <iostream>
#include "linkedStack.h"
using namespace std;
template <class Type>
void printStack(linkedStackType<Type>& stack);
template <class Type>
void reverseStack(linkedStackType<Type>& stack);
int main(int argc, char **argv)
{
// Declare stack variables
linkedStackType<int> stack;
// Add some data to the stack
stack.push(121);
stack.push(113);
stack.push(734);
stack.push(22);
stack.push(243);
stack.push(34);
stack.push(26);
stack.push(74);
stack.push(115);
stack.push(262);
cout << "\nStack:\n ";
printStack(stack);
reverseStack(stack);
cout << "\nStack Reversed:\n ";
printStack(stack);
cout << "\n\n** Press any key to continue **\n";
getchar();
return 0;
}
template <class Type>
void printStack(linkedStackType<Type>& stack)
{
Type item;
linkedStackType<Type> tmpStack = stack;
while (stack.isEmptyStack() == false)
{
item = stack.top();
stack.pop();
cout << item << " ";
}
stack = tmpStack;
}
template <class Type>
void reverseStack(linkedStackType<Type>& stack)
{
Type item;
linkedStackType<Type> tmpStack;
while (stack.isEmptyStack() == false)
{
item = stack.top();
stack.pop();
tmpStack.push(item);
}
while (tmpStack.isEmptyStack() == false)
{
item = tmpStack.top();
tmpStack.pop();
stack.push(item);
cout << item;
}
stack = tmpStack;
return;
}
A:
I'm not 100%, but I imagine your code will work if you delete the second while loop of reverseStack.
template <class Type>
void reverseStack(linkedStackType<Type>& stack)
{
Type item;
linkedStackType<Type> tmpStack;
while (stack.isEmptyStack() == false)
{
item = stack.top();
stack.pop();
tmpStack.push(item);
}
//while (tmpStack.isEmptyStack() == false)
//{
// item = tmpStack.top();
// tmpStack.pop();
// stack.push(item);
// cout << item;
//}
stack = tmpStack;
return;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I type the result of awaiting a thunk dispatch?
I want to await the result of a thunk, which returns a string asynchronously. My problem is in the last line-- I can't figure out how to type cityName as string.
// error, Type 'ThunkAction, AppState, undefined,
any>' is not assignable to type 'string'.
The code works as intended, I just unfortunately need to type cityName as any
const getCity = (): Thunk<Promise<string>> => async (
dispatch,
getState
): Promise<string> => {
// ...
const city = await fetchCityApi(query);
dispatch(setUserCity(city));
return city;
};
export const getDataUsingCity = (): Thunk<void> => async dispatch => {
const cityName: string = await dispatch(getCity());
};
I am using a wrapper for Thunk that works great as long as my Thunks don't return a value:
export type Thunk<R> = ThunkAction<R, AppState, undefined, any>;
A:
This appears to be a bug within redux-thunk that was fixed within this commit. Using the modified ThunkDispatch type within the commit lets the above code work without error. However, a new version of redux-thunk has not been published since May of 2018, meaning this fix is not publicly available.
Looking through the related issues, you can also fix this by changing your definition of Thunk<R> to
export type Thunk<R> = ThunkAction<R, AppState, undefined, Action>;
This forces the correct overload of ThunkDispatch (the one that takes a ThunkAction) to be used. Otherwise, due to the any TypeScript cannot disambiguate which of the two to use, and therefore just picks the first one (the one that takes the plain Action). This is also why the above PR fixes the issue, as they rearrange the two overloads as to make TS choose the ThunkAction variant by default.
| {
"pile_set_name": "StackExchange"
} |
Q:
org.apache.openjpa.persistence.ArgumentException while running the main class
I using using maven simple java project
Im getting the following exception while running the main class
346 INFO [main] openjpa.Runtime - OpenJPA dynamically loaded the class
enhancer. Any classes that were not enhanced at build time
will be enhanced when they are loaded by the JVM.
414 INFO [main] openjpa.Runtime - Starting OpenJPA 2.3.0
<openjpa-2.3.0-r422266:1540826 fatal user error>
org.apache.openjpa.persistence.ArgumentException: The persistence provider is
attempting to use properties in the persistence.xml file to resolve the data
source. A Java Database Connectivity (JDBC) driver or data source class name
must be specified in the openjpa.ConnectionDriverName or
javax.persistence.jdbc.driver property. The following properties are available
in the configuration: "org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl@442ce698".
at org.apache.openjpa.jdbc.schema.DataSourceFactory.newDataSource(DataSourceFactory.java:72)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.createConnectionFactory(JDBCConfigurationImpl.java:849)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.getDBDictionaryInstance(JDBCConfigurationImpl.java:602)
at org.apache.openjpa.jdbc.meta.MappingRepository.endConfiguration(MappingRepository.java:1518)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:535)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:460)
at org.apache.openjpa.lib.conf.PluginValue.instantiate(PluginValue.java:121)
at org.apache.openjpa.conf.MetaDataRepositoryValue.instantiate(MetaDataRepositoryValue.java:68)
at org.apache.openjpa.lib.conf.ObjectValue.instantiate(ObjectValue.java:83)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.newMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:967)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.getMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:958)
at org.apache.openjpa.kernel.AbstractBrokerFactory.makeReadOnly(AbstractBrokerFactory.java:643)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:203)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:155)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:153)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:59)
at org.msharma.JpaImpl.main(JpaImpl.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
My entity clas
@Entity(name ="customer")
public class Customer implements Serializable{
@Id
@Column(name ="cust_id", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private long custId;
@Column(name = "first_name",length = 50, nullable = false)
private String firstName;
@Column(name = "last_name",length = 50)
private String lastName;
// By default column name is same as attribute name
private String street;
private String appt;
private String city;
@Column(name = "zip_code",length = 50, nullable = false)
private String zipCode;
@Column(name = "cust_type",length = 50, nullable = false)
private String custType;
@Version
@Column(name = "last_updated_time")
private Date updatedTime;
public Customer(){}
// getters and setters
}
This is my persistence.xml
<?xml version="1.0"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="testjpa" transaction-type="RESOURCE_LOCAL">
<provider>
org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>org.somepack.Customer</class>
<properties>
<property name="openjpa.ConnectionURL"
value="jdbc:mysql://localhost:3306/test"/>
<property name="openjpa.ConnectionDriverName"
value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionUserName" value="root"/>
<property name="openjpa.ConnectionPassword" value="pass"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
</properties>
</persistence-unit>
</persistence>
This is my mainClass
public static void main(String[] args) {
try {
EntityManagerFactory entityManagerFactory = Persistence
.createEntityManagerFactory("testjpa");
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
Customer customer = new Customer();
//set the properties to the customer object
entityManager.persist(customer);
entityTransaction.commit();
entityManager.close();
entityManagerFactory.close();
}
catch (Exception e){
e.printStackTrace();
}
}
How do I resolve the problem .
I have openjpa, openjpa-persistence-jdbc, mysql-connector-java dependencies in my POM.xml
and my persistence.xml is under src/main/resources
A:
As you said your persistence.xml is under src/main/resources so may be it is unable to read it
you must place it under src/main/resources/META-INF
One more thing add
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
to your persistence.xml.
If you add the openjpa.jdbc.SynchronizeMappings property as shown below OpenJPA will auto-create all your tables, all your primary keys and all foreign keys exactly to match your objects
| {
"pile_set_name": "StackExchange"
} |
Q:
Logging custom events in the Firebase Analytics console (Swift)
I'm trying to log custom events for my location rating app (Swift). After looking through examples it looks like you give attributes a value similar to a JSON database. I still haven't seen the event named logged in the analytics console (it's been about a week).It doesn't have any debug errors. Here is the instance:
FIRAnalytics.logEventWithName("Ratings", Parameters[
"rating": (indexPath.row + 1)
Any advice?
A:
The syntax for logging a custom event in Swift would be:
FIRAnalytics.logEventWithName("Ratings", parameters: [
"rating": (indexPath.row + 1)
])
Make sure that part of your code is getting executed by setting a break-point. Perhaps it's not being run.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to filter by embedded object field in elastic search
Here is my search object:
{
"_index": "search",
"_type": "product",
"_id": "2",
"_version": 1,
"found": true,
"_source": {
"datePublished": "2014-01-01T00:00:00-08:00",
"published": true,
"name": "Winter Coat",
"description": "A nice warm winter coat. If you get cold with this on, you've probably done something wrong.",
"brand": {
"name": "Burton"
}
}
}
and here is the query i'm trying to perform:
$query = new Query\QueryString('*' . 'winter' .'*');
$boolFilter = new Bool();
$brandFilter = new Term(['brand.name' => 'Burton']);
$boolFilter->addMust($brandFilter);
$filtered = new Filtered($baseQuery, $boolFilter);
return Query::create($filtered);
but i'm getting nothing back. What am i doing wrong?
A:
After some trial and error i found that terms is a somewhat unreliable way to do exact matching because of the tokenizer. For any field you want to exact match you need to make sure it is not analyzed. Alternatively, you can just use integer values (such and an object id) for exact matching. I ended up using ids in the cases of exact matching.
| {
"pile_set_name": "StackExchange"
} |
Q:
rounding a currency
i have the following code to round the currency
function MyRound(value :currency) : integer;
begin
if value > 0 then
result := Trunc(value + 0.5)
else
result := Trunc(value - 0.5);
end;
it worked well so far, my problem now is if i want to round a currency like 999999989000.40 it is giving negative value since Truc takes int and MyRound also returns int.
My possible solutions is to convert currency to string and get the string before . and convert the string back to currency. Is this a right approach? i am new to delpi so pls help me out.
A:
From my point of view, you have two options:
You use the Round function, as David Heffernan pointed;
You can use the SimpleRoundTo function, as described here. The advantage of SimpleRoundTo is that it receives parameters of Single, Double and Extended data types and they convert round very well numbers like those stated.
You don't need any type conversions. There are plenty of rounding functions already available to you. Just round the desired number.
A:
You are overcomplicating matters. You can simply use Round:
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
C: Currency;
begin
C := 999999989000.4;
Writeln(Round(C));
C := 999999989000.5;
Writeln(Round(C));
C := 999999989000.6;
Writeln(Round(C));
C := 999999989001.4;
Writeln(Round(C));
C := 999999989001.5;
Writeln(Round(C));
C := 999999989001.6;
Writeln(Round(C));
Readln;
end.
which outputs
999999989000
999999989000
999999989001
999999989001
999999989002
999999989002
If you don't want banker's rounding, and you really do want your Trunc logic then you do need to write your own function. But the problem with your function is that it was truncating to 32 bit integer. Make the function return a 64 bit integer:
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils, Math;
var
C: Currency;
function MyRound(const Value: Currency): Int64;
begin
if Value > 0 then
result := Trunc(Value + 0.5)
else
result := Trunc(Value - 0.5);
end;
begin
C := 999999989000.4;
Writeln(MyRound(C));
C := 999999989000.5;
Writeln(MyRound(C));
C := 999999989000.6;
Writeln(MyRound(C));
C := 999999989001.4;
Writeln(MyRound(C));
C := 999999989001.5;
Writeln(MyRound(C));
C := 999999989001.6;
Writeln(MyRound(C));
Readln;
end.
999999989000
999999989001
999999989001
999999989001
999999989002
999999989002
| {
"pile_set_name": "StackExchange"
} |
Q:
¿ Como centrar las cruces en el cuadro?
Hola tengo un problema en el archivo html, estoy tratando de adaptar un código que encontré en google de un juego, las tres en raya.
El problema es que le cambie el tamaño original y a la hora de centrar las "X" no lo consigo por vueltas que le doy.
Los ceros llegue a conseguirlo cambiando <circle cx="63" cy="63" r="40", pero como digo, en la "X" probé varias formas sin éxito.
Se que debo cambiar el valor de x e y, pero no doy con la clave justa.
Muestro el código .Gracias.
Aunque el problema esté en html muestro todo el código para que se vea el efecto, perdonen.
$(function () {
// Moves to win
var toWin = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[3, 5, 7]
];
function Player(name, mark) {
this.name = name;
this.mark = mark;
}
var computer = new Player('Player 2', 'x');
var human = new Player('Player 1', 'o');
var humanTurn = true;
function getCurrentPlayer() {
return humanTurn ? human : computer;
}
function hasMove(marks, move) {
var resp;
for (var i = 0; i < move.length; i++) {
var value = move[i];
if (marks.includes(value)) {
resp = true;
} else {
return false;
}
}
return resp;
}
function winSomebody() {
var xMarks = $('.' + getCurrentPlayer().mark).map(
function () {
var value = parseInt($(this).attr('value'));
return value;
}).get();
for (var i = 0; i < toWin.length; i++) {
var move = toWin[i];
if (hasMove(xMarks, move)) {
return true;
}
}
return false;
}
$('.col').click(function (event) {
var currentPlayer = getCurrentPlayer();
var target = $(event.currentTarget);
target.addClass(currentPlayer.mark);
target.find('.' + currentPlayer.mark).show();
target.off('click');
if (winSomebody()) {
$('.player-' + currentPlayer.mark).css('background-color', '#53DD6C');
} else {
humanTurn = !humanTurn;
currentPlayer = getCurrentPlayer();
$('.player div').css('background-color', '#0A20D9');
$('.player-' + currentPlayer.mark).css('background-color', '#3344D6');
}
});
});
body {
background-color: #09B6ED;
font-family: Roboto;
}
.container {
width: 400px;
height: 400px;
margin: 0 auto;
}
header {
color: #fff;
}
.title {
text-align: center;
}
.player {
display: flex;
background: #3344D6;
width: 400px;
margin: 20px auto;
}
.current {
background-color: #0A20D9;
}
.player div {
width: 50%;
text-align: center;
font-size: 100px;
}
.row {
background-color: #3344D6;
width: 100%;
height: 33.33%;
display: flex;
}
.col {
border: 3px solid #0A20D9;
width: 33.33%;
}
svg {
max-width: 100%;
max-height: 100%;
}
line {
stroke: #fff;
stroke-width: 12;
stroke-dasharray: 870;
stroke-dashoffset: 870;
animation-name: draw;
animation-duration: 1s;
animation-iteration-count: 1;
animation-fill-mode: forwards;
}
@keyframes draw {
to {
stroke-dashoffset: 0;
}
}
.delay {
animation-delay: 0.2s;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>las tres en raya</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>
<body>
<header>
<div class="title">
<h1>TRES EN RAYA</h1>
</div>
<div class="player">
<div class="player-o current">
o
</div>
<div class="player-x">
x
</div>
</div>
</header>
<section>
<div class="container">
<div class="row">
<div class="col" value="1">
<svg width="400" height="400" class="x" style="display: none">
<line x1="40" y1="40" x2="130" y2="130" />
<line x1="130" y1="40" x2="40" y2="130" class="delay" />
</svg>
<svg width="2000" height="2000" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
<div class="col" value="2">
<svg width="400" height="400" class="x" style="display: none">
<line x1="40" y1="40" x2="130" y2="130" />
<line x1="130" y1="40" x2="40" y2="130" class="delay" />
</svg>
<svg width="2000" height="2000" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
<div class="col" value="3">
<svg width="400" height="400" class="x" style="display: none">
<line x1="40" y1="40" x2="130" y2="130" />
<line x1="130" y1="40" x2="40" y2="130" class="delay" />
</svg>
<svg width="2000" height="2000" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
</div>
<div class="row">
<div class="col" value="4">
<svg width="400" height="400" class="x" style="display: none">
<line x1="40" y1="40" x2="130" y2="130" />
<line x1="130" y1="40" x2="40" y2="130" class="delay" />
</svg>
<svg width="2000" height="2000" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
<div class="col" value="5">
<svg width="400" height="400" class="x" style="display: none">
<line x1="40" y1="40" x2="130" y2="130" />
<line x1="130" y1="40" x2="40" y2="130" class="delay" />
</svg>
<svg width="2000" height="2000" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
<div class="col" value="6">
<svg width="400" height="400" class="x" style="display: none">
<line x1="40" y1="40" x2="130" y2="130" />
<line x1="130" y1="40" x2="40" y2="130" class="delay" />
</svg>
<svg width="2000" height="2000" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
</div>
<div class="row">
<div class="col" value="7">
<svg width="400" height="400" class="x" style="display: none">
<line x1="40" y1="40" x2="130" y2="130" />
<line x1="130" y1="40" x2="40" y2="130" class="delay" />
</svg>
<svg width="2000" height="2000" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
<div class="col" value="8">
<svg width="400" height="400" class="x" style="display: none">
<line x1="40" y1="40" x2="130" y2="130" />
<line x1="130" y1="40" x2="40" y2="130" class="delay" />
</svg>
<svg width="2000" height="2000" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
<div class="col" value="9">
<svg width="400" height="400" class="x" style="display: none">
<line x1="40" y1="40" x2="130" y2="130" />
<line x1="130" y1="40" x2="40" y2="130" class="delay" />
</svg>
<svg width="2000" height="2000" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
</div>
</div>
<section>
</body>
</html>
A:
Veo 2 probelmas:
El alto/ancho de los svg, lo he cambiado a valores de 100% para asegurar que ocupen el tama#o de los contenedores.
El SVG de las X estan mal posicionados el origen y destino de las patas de la X. Estos valores, creo, se ven mejor.
<line x1="20" y1="20" x2="110" y2="110" />
<line x1="110" y1="20" x2="20" y2="110" class="delay" />
Solucion:
$(function () {
// Moves to win
var toWin = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[3, 5, 7]
];
function Player(name, mark) {
this.name = name;
this.mark = mark;
}
var computer = new Player('Player 2', 'x');
var human = new Player('Player 1', 'o');
var humanTurn = true;
function getCurrentPlayer() {
return humanTurn ? human : computer;
}
function hasMove(marks, move) {
var resp;
for (var i = 0; i < move.length; i++) {
var value = move[i];
if (marks.includes(value)) {
resp = true;
} else {
return false;
}
}
return resp;
}
function winSomebody() {
var xMarks = $('.' + getCurrentPlayer().mark).map(
function () {
var value = parseInt($(this).attr('value'));
return value;
}).get();
for (var i = 0; i < toWin.length; i++) {
var move = toWin[i];
if (hasMove(xMarks, move)) {
return true;
}
}
return false;
}
$('.col').click(function (event) {
var currentPlayer = getCurrentPlayer();
var target = $(event.currentTarget);
target.addClass(currentPlayer.mark);
target.find('.' + currentPlayer.mark).show();
target.off('click');
if (winSomebody()) {
$('.player-' + currentPlayer.mark).css('background-color', '#53DD6C');
} else {
humanTurn = !humanTurn;
currentPlayer = getCurrentPlayer();
$('.player div').css('background-color', '#0A20D9');
$('.player-' + currentPlayer.mark).css('background-color', '#3344D6');
}
});
});
body {
background-color: #09B6ED;
font-family: Roboto;
}
.container {
width: 400px;
height: 400px;
margin: 0 auto;
}
header {
color: #fff;
}
.title {
text-align: center;
}
.player {
display: flex;
background: #3344D6;
width: 400px;
margin: 20px auto;
}
.current {
background-color: #0A20D9;
}
.player div {
width: 50%;
text-align: center;
font-size: 100px;
}
.row {
background-color: #3344D6;
width: 100%;
height: 33.33%;
display: flex;
}
.col {
border: 3px solid #0A20D9;
width: 33.33%;
}
svg {
max-width: 100%;
max-height: 100%;
}
line {
stroke: #fff;
stroke-width: 12;
stroke-dasharray: 870;
stroke-dashoffset: 870;
animation-name: draw;
animation-duration: 1s;
animation-iteration-count: 1;
animation-fill-mode: forwards;
}
@keyframes draw {
to {
stroke-dashoffset: 0;
}
}
.delay {
animation-delay: 0.2s;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>las tres en raya</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>
<body>
<header>
<div class="title">
<h1>TRES EN RAYA</h1>
</div>
<div class="player">
<div class="player-o current">
o
</div>
<div class="player-x">
x
</div>
</div>
</header>
<section>
<div class="container">
<div class="row">
<div class="col" value="1">
<svg width="100%" height="100%" class="x" style="display: none">
<line x1="20" y1="20" x2="110" y2="110" />
<line x1="110" y1="20" x2="20" y2="110" class="delay" />
</svg>
<svg width="100%" height="100%" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
<div class="col" value="2">
<svg width="100%" height="100%" class="x" style="display: none">
<line x1="20" y1="20" x2="110" y2="110" />
<line x1="110" y1="20" x2="20" y2="110" class="delay" />
</svg>
<svg width="100%" height="100%" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
<div class="col" value="3">
<svg width="100%" height="100%" class="x" style="display: none">
<line x1="20" y1="20" x2="110" y2="110" />
<line x1="110" y1="20" x2="20" y2="110" class="delay" />
</svg>
<svg width="100%" height="100%" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
</div>
<div class="row">
<div class="col" value="4">
<svg width="100%" height="100%" class="x" style="display: none">
<line x1="20" y1="20" x2="110" y2="110" />
<line x1="110" y1="20" x2="20" y2="110" class="delay" />
</svg>
<svg width="100%" height="100%" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
<div class="col" value="5">
<svg width="100%" height="100%" class="x" style="display: none">
<line x1="20" y1="20" x2="110" y2="110" />
<line x1="110" y1="20" x2="20" y2="110" class="delay" />
</svg>
<svg width="100%" height="100%" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
<div class="col" value="6">
<svg width="100%" height="100%" class="x" style="display: none">
<line x1="20" y1="20" x2="110" y2="110" />
<line x1="110" y1="20" x2="20" y2="110" class="delay" />
</svg>
<svg width="100%" height="100%" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
</div>
<div class="row">
<div class="col" value="7">
<svg width="100%" height="100%" class="x" style="display: none">
<line x1="20" y1="20" x2="110" y2="110" />
<line x1="110" y1="20" x2="20" y2="110" class="delay" />
</svg>
<svg width="100%" height="100%" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
<div class="col" value="8">
<svg width="100%" height="100%" class="x" style="display: none">
<line x1="20" y1="20" x2="110" y2="110" />
<line x1="110" y1="20" x2="20" y2="110" class="delay" />
</svg>
<svg width="100%" height="100%" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
<div class="col" value="9">
<svg width="100%" height="100%" class="x" style="display: none">
<line x1="20" y1="20" x2="110" y2="110" />
<line x1="110" y1="20" x2="20" y2="110" class="delay" />
</svg>
<svg width="100%" height="100%" class="o" style="display: none">
<circle cx="63" cy="63" r="40" fill="transparent" stroke-width="10" stroke="white" />
</svg>
</div>
</div>
</div>
<section>
</body>
</html>
Salu2..
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditional if element is on website refresh and if not move on with the code
I'm trying to get this conditional working but I'm getting traceback.
I want to look if the element is present on the website and if it is refresh and execute redeem_func() and if the element is not present at all
I want to not execute err_reddem_func() and move on to this
By the way, I don't know if it's relevant but if there was no error on the webpage it redirects to the last step website and saves URL to txt.
Exception in thread Thread-6:
Traceback (most recent call last):
File "C:\Users\lulu\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\lulu\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "c:/Users/lulu/Desktop/s/s/threaddo.py", line 352, in execute_chrome
s(elem[0], elem[1], elem[2])
File "c:/Users/lulu/Desktop/s/s/threaddo.py", line 323, in s
err_redeem_func()
File "c:/Users/lulu/Desktop/s/s/threaddo.py", line 314, in err_redeem_func
err_redeem = driver.find_element_by_class_name('error')
File "C:\Users\lulu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name return self.find_element(by=By.CLASS_NAME, value=name)
File "C:\Users\lulu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
'value': value})['value'] File "C:\Users\lulu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\lulu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"class name","selector":"error"} (Session info: chrome=74.0.3729.131)
(Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17763 x86_64)
My Code
def redeem_func():
capHome = cap_home()
print("redeem_func")
driver.execute_script("redemptionValidation(\"" + capHome + "\")")
time.sleep(10)
redeem_func()
time.sleep(1)
print(driver.current_url)
def err_redeem_func():
err_redeem = driver.find_element_by_class_name('error')
try:
if err_redeem.is_displayed() and err_redeem.is_enabled():
driver.refresh()
redeem_func()
except NoSuchElementException:
pass
err_redeem_func()
print(driver.current_url)
print("SAVING TO TXT")
finalCode = driver.current_url
f = open('t.txt','a')
f.write('\n' + finalCode)
f.close()
A:
Replace the below line
if err_redeem.is_displayed() and err_redeem.is_enabled():
with
if (len(driver.find_elements_by_class_name('error'))>0):
You are getting NoSuchElement exception because the script is trying to check if the element is enabled when the element is not there on the page.
| {
"pile_set_name": "StackExchange"
} |
Q:
Default Activity not found
Después de haber eliminado y volver a crear una actividad tengo el siguiente problema a la hora de iniciar mi aplicación, me sale "Default Activity not found" , este es el fichero AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity" />
<activity android:name=".SegActivity" />
<activity android:name=".TerceraActivity" />
<activity android:name=".QuartActivity" />
<activity android:name=".FinalActivity"></activity>
</application>
y el MainActivity :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Gracias!
A:
Tienes que tener en tu aplicación una Activity "default" que inicie la aplicación, para este caso debe tener definido el suguiente intent-filter:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Agregala a tu Activity Principal, por ejemplo:
<activity
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
| {
"pile_set_name": "StackExchange"
} |
Q:
When exactly does Stack Exchange make a new version of what you edit?
As you know, when you edit a post in SE communities (like SO), sometimes your edition will be a new version, and sometimes else the current post will be just updated.
According to some tests, I figured it out:
when there is a comment under the post after the last version, it will create a new version if you edit the post.
When 10 minutes passed since the last edition, then it will create a new version if you edit the post.
Anything else?
A:
That's about it. Edits by other people also cause a new revision, and the so-called grace-period lasts 5 minutes, not 10, and comments also end the grace period if they are quickly deleted (which might lead to confusion). Votes and flags do not count, and neither do deleting and undeleting your post.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fatal error: Uncaught exception with message 'couldn't connect to host' in /var/www/vhosts/abc.com/
I am using Curl to connect to a server and update data using the following function. The function works great and updates approx 400 records. After that it throws an error, please advise how to solve this issue ?
Fatal error: Uncaught exception with message 'couldn't connect to host' in /var/www/vhosts/abc.com/
comm_Api_Connection->put('https://www.vam...', Object(stdClass)) #2 /var/www/vhosts/abc.com/httpdocs/mysite/demo/comm-common1/Api.php(1530):
comm_Api::updateResource('/products/5250', Array) #3 /var/www/vhosts/abc.com/httpdocs/mysite/demo/sync_prod_inventory_new1.php(1088):
comm_Api::updateProduct('5250', Array) #4 {main} thrown in /var/www/vhosts/abc.com/httpdocs/mysite/demo/comm-common1/Api.php on line 204
The PHP Function is as follows
<?php
public function put($url, $body)
{
$this->addHeader('Content-Type', $this->getContentType());
if (!is_string($body)) {
$body = json_encode($body);
}
$this->initializeRequest();
$handle = tmpfile();
fwrite($handle, $body);
fseek($handle, 0);
curl_setopt($this->curl, CURLOPT_INFILE, $handle);
curl_setopt($this->curl, CURLOPT_INFILESIZE, strlen($body));
curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($this->curl, CURLOPT_URL, $url);
curl_setopt($this->curl, CURLOPT_PUT, true);
curl_exec($this->curl);
return $this->handleResponse();
}
A:
At a pinch I'd say you are opening too many connections to the server
Each time you call that method you open a new request, but don't close it. It will stay open until the timeout is reached
If your server only allows 400 simultaneous connections, anything after the 400th call to the method will fail
You need to close your connections after each request
curl_close($ch)
| {
"pile_set_name": "StackExchange"
} |
Q:
Button class toggle Issue with Bootstrap Accordion & Silverstripe
I'm using Bootstrap's accordion for a project built on Silverstripe. The markup mimic's Bootstrap's docs as follows, with the following differences: aria-expanded="false" and panel-collapsed does not have class in since I want all items closed by default.
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="heading1">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse1" aria-expanded="false" aria-controls="collapse1">
Panel title
</a>
</h4>
</div>
<div id="collapse1" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading1">
<div class="panel-body">
Lorem ipsum
</div>
</div>
</div>
</div>
It loads as expected, with all items closed. Clicking on the panel title opens and closes the panel body as expected. However, the action adds class="collapsed" to .panel-title > a on opening, and does not remove it with subsequent clicks.
This is my problem -- I need this class to toggle as it does on Bootstrap's example (no class when open, collapsed class when collapsed) so that I can style the title differently for each case.
I have spent hours on this and cannot figure out why it's not working. I've copied Bootstrap's code, and definitely have the latest version of bootstrap.min.js. I don't think I'm missing anything but maybe I've just been looking at it for too long. Please help!
A:
Ok, so the issue was the project is built with Silverstripe, which rewrites hash links to specify a URL before the anchor, so it was adding '/' before the anchor links.
The solution is to disable the hash links, or write a custom handler to remove the collapsed class.
Have edited the original question to include Silverstripe.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to study the causal impact on multiple time series of interest against multiple baselines
My data consist of time series of Wikipedia hits for football players. I want to use the CausalImpact package to explore the effect of the World Cup on their popularity which I base on their Wikipedia page hits. This is effectively seeing if the tournament works as a marketing campaign for their popularity on Wikipedia.
I use the Wikipedia hits from players who featured in the previous tournament as a baseline and exclude the players who featured in both as that would confound things.
date Messi Ronaldo # 2018 players
01/01/18 756 871
02/01/18 660 743
03/01/18 523 453
04/01/18 412 654
05/01/18 488 568
06/01/18 515 345
date Lahm Xavi # 2014 players
01/01/18 253 171
02/01/18 164 443
03/01/18 323 351
04/01/18 312 654
05/01/18 183 263
06/01/18 325 145
In R, I loop over each one of the time series for the players in this World Cup and compare them against a predictor series which is all of the players at the previous tournament.
But this seems a bit unwieldy because the time series are so variable. Some players barely get any hits, others have marked seasonality and others are constant. What is the appropriate way to select the predictor time series in a case like this? I've seen this answer but it refers to datasets being contemporaneous.
List = NULL
for (i in 1:length(levels(wikiHitsWC2018$article))){
data <- zoo(cbind(data_wideWC2018[i], data_wideWC2014[,1:119]),time.points)
impact <- CausalImpact(data, pre.period, post.period,model.args =
list(nseasons = 7, season.duration = 1))
List[[i]] <- impact
}
Hope you can help!
A:
A few thoughts:
Level of your data: In general, the level of your data determines the level of your inference. bsts followed by Causalimpact is a time series approach to impact estimation suitable for cases where one just doesn't have individual level data. In a B2B setting for example, one often only observes sales over time and the intervention date, e.g. marketing campaign. This is not the easiest data to work with and certainly not to make causal inference. In this time series setting, bsts and Causalimpact nevertheless provide a strategy to get an estimate of the intervention impact.
Now in your case, you have much more granular data, i.e. repeated
observations of individuals over a long time frame. This is a
balanced panel and somewhat the best data you can get, since in many
ways, panel data can enrich your analysis and allows you to do things
that time series data can't! Your data thus allows you to use
regression discontinuity, panel data models, propensity score matching, or bsts & CausalImpact with matched comparison group. I outline
below how this could look like.
Control group: A suitable comparison group in your case would be players who pre-qualified. This is a good comparison group since the pre-qualified eligible players match core team players very closely in skill, past performance and other characteristics relevant to the outcome you study: popularity of a player. Things that you need to account for in this set up are 1) non-random assignment of treatment, 2) spillover effects on the comparison and 3) pre-existing differences between treatment and comparison group.
(1) Selection into treatment occurs since you have to be really good to play in the core team at the world cup, which is not very random. Clearly, players get select into treatment (i.e. the core team) based on observable measures of skill and past performance, but likely also unobservable ability and motivation.
As a result (3), treatment and comparison group characteristics of players will differ pre-treatment and thus won't be balanced between treatment and comparison as it is the case under random assignment.
(2) A key assumption in any treatment comparison model is that the treatment has no effect on comparison players. However, a generally higher interest in football will have some effect on eligible players too, so the world cup has spillover effects on the comparison. A partially treated comparison group, in turn means the treatment estimate will be biased downward. Controlling for these problems requires understanding more about the data generation process and usually means collecting more granular data like yours.
RDD: A suitable identification strategy in this set up would be regression discontinuity design (RDD): For this you would need a score that measures player quality. Possibly this is publicly available. If not, you could construct a score that separates eligible players and core team players by some threshold, thus reverse-engineering the selection criteria to be admitted as a core team player in the world cup. This could be a weighted average of e.g. past performance and other continuous skill measures. A probit model explaining treatment on the past performance and skills would not work here, as it does not allow for discontinuities. In any case, it should be credible to say that selection into the treatment happens based on some threshold in this score, which is the cut-off that is exploited in regression discontinuity design (RDD).
Essentially, you assume that players very close to the cut-off are similar to an extent that some of the differences between them are random. This is realistic since for example some player may have had an injury, thus less training time and then performed less well that season. This can happen to any player. Hence within some narrow range around the cut-off, the characteristics of players are similar and the threshold can be thought of as a natural local experiment where the differences between the core and eligible players are "as good as random". If you now pick N core and eligible players near the cut-off in your quality score, you can then evaluate the effect of the world cup on core player popularity by plotting popularity (e.g. #clicks wikipedia or googletrends series hits) on the vertical axis and quality score for all players on the horizontal. To test whether the world cup increases popularity of players you basically look for a discontinous jump in popularity around the cut-off point in player quality. If so, you can attribute the jump to the fact that the player was a core player in the world cup, rather than just an eligible player. The estimated treatment effect is the size of the jump and if you also want the significance of the jump you can use local linear regression with a subset of the data around the threshold or polynomial regression with all the data. In either cases, your assumptions are that the model is linear and that treatment is independent of the X, i.e. that you managed to remove all selection on observables.
RDD works if you have a score that explains treatment assignment. You also need enough individuals within some narrow band around the cut-off. Further, it deals with problems 1-3. The score takes account of the non-random assignment (problem 1), by converting it to a local randomised experiment around the cut-off, which explains the selection into treatment. Problem 2 is about the key assumption that comparison players are Not affected by the treatment. Since the world cup has a non-exclusive publicity effect on any football player. Hence spillover effects on the comparison occur, which may bias the treatment effect downward. If you think these spill-over effects are significant, the causal effect of your RDD estimate will be a lower bound. As for problem 3, you have turned it into a local random experiment, where no pre-existing differences should exist between eligible players that marginally failed to be selected and the core team players.
To use bsts & CausalImpact on your data, you focus on the time series dimension of your data: Hence, you could predict individual core player popularity based on individual or aggregate popularity of eligible players. If your variation is high, maybe reducing the frequency of the data to a weekly level helps. Equally, you could take aggregate popularity of eligible players to predict aggregate popularity of core team players around the treatment as suggested before. Also, if you feel you don't have enough data with wikipedia series, maybe googletrends series for the player name is less sparse? In any case, it's worth looking at it, since you can use it in the regression component.
Selection of regression components: The validity of bsts & Causalimpact depends on the validity of covariates, which should a) mimic the trend of the target in the pre-treatment as closely as possible and b) be relevant to the outcome you are studying. The first part is a prediction task, so you practically, you could start by plotting the potential time series and choose the most correlated ones as a pre-selection. You can then apply standard model selection techniques, i.e. select the optimal number of regressors based on how well you could fit the target in the pre-treatment period. (one step ahead out of sample error, Harvey statistic). Part b) needs an answer in the context of your data, which in your case means you need to make model adjustments and choose covariates that account for problems 1-3!
To account for this you could use matching methods, which aim to balance characteristics between core team players and eligible players such that that the only remaining difference between the two groups is treatment assignment. This is done based on selected variables that are relevant to the outcome you are studying, i.e. popularity. One option is to use propensity score matching, which explains the treatment selection process based on observable characteristics. Effectively, it is like doing instrumental variables on the treatment, which is endogenous here and you end up constructing a score that measures the probability of being in the treatment group. You can then pick the eligible players that most closely match the core team players using Kernel density matching for example. At this stage, you have tried to control for the non-random assignment and selection into treatment in a similar way as you did under the RDD by balancing characteristics around a score. This accounts for problem 1 and 3, as long as there is no remaining unobservable differences between treatment and comparison group. Spillover effects will still downward bias your impact estimates. You can accept the estimate as a lower bound of the actual effect or try to estimate the size of the spillover effect separately.
Hence, the analysis could look as follows:
1) Match eligible players (comparison) with core team players (treatment) based on observable pre-treatment characteristics, which you can scrape from e.g. Wikipedia. The output of this step defines the comparison group.
2) Run bsts & CausalImpact using the comparison identified in the previous step.
If you want to predict individual-level effects, you may find this useful.
Now the only issue that you have not tested for is selection on unobservables which may confound the true relationship between a cause and an effect and thus significantly bias estimate results. The key advantage of panel data is that it optimally exploits and combines the time series and cross-section data generation process of your data and thereby allows you to answer questions that just cannot be answered with time series data alone, i.e. how to control for unobserved common factors. If for example, selection into the core team was in a rush under time pressure or includes family background of the player or some kind of foul play, this will result in selection based on unobservables. Since it's unobservable, it's harder to control for, but several options exist and you can test for it too.
Control function approach: If you have reason to believe that the selection on unobservables is a problem, you can test for it by comparing the estimates of a model that controls for sample selection versus a model w/o controlling for selection. If the coefficients are stable across the two specifications, then this is evidence that any selection bias is likely to be small; if the coefficients move substantially, then this indicates that selection bias significantly affects estimated results. If the latter is the case, you can control for selection using a control function approach similar to the two-step approach developed by Heckman. First, you explain treatment assignment using relevant regressors and construct the inverse mills ratio from the predicted score. Then you run a regression that explains popularity based on the regressors, including the Mills ratio.
Some more thoughts:
Choice of outcome variable: If you want to measure the effect of publicity on a single player, maybe $\frac{n\_wikipedia\_page\_hits\_player\_X}{n\_wikipedia\_page\_hits\_whole\_team}$ would be a metric that better reflects the effect on the player normalised by the popularity of the team.
Choosing an appropriate start for the pre-/post period needs careful consideration: Clearly, the treatment is somewhere between when the team constellation was released (the public learnt about it started looking at the players' profiles) and the date of the last game in the tournament (player publicity reached its peak).
To measure the effect of releasing the team constellation, setting
the start of the evaluation at the constellation release date may be suitable, especially if you are interested in the pure publicity effect of the tournament, independent of the player's performance. Also, in the case that this "release effect" is strong, setting the start date for impact evaluation later, can make your effect negative easily, since you are measuring the impact of a series that gets back to its normal level after a temporary shock.
Setting the start of the treatment at the date of the tournament would measure the effect of the incremental popularity of a player due to their
participation, performance at the games and other news/scandals at
the time of games with regards to the player and the team. The latter
is more than a marketing effect you are measuring.
| {
"pile_set_name": "StackExchange"
} |
Q:
Subgroups of external direct product.
I am trying to find all subgroups of order 4 in Z4 x Z4.
I have:
$\{0\} \times Z_4 = \langle(0,1)\rangle$
$Z_4 \times \{0\} = \langle(1,0)\rangle$
$\langle(1,1)\rangle$
$\langle(0,2)\rangle$
Have I missed any?
A:
Note that $\langle (0,2) \rangle$ is not of order $4$. However, $\langle (0,2),(2,0) \rangle$ is.
Note additionally that you're missing $\langle(1,3)\rangle,\langle(1,2)\rangle$, and $\langle(2,1)\rangle$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why there is an infinite recursion when function parameter is not defined as const reference?
I am having troubles understanding what might be causing the infinite recursion. There are two points that play a role in my problem
Depending on the place of definition of the global functions
Whether we mark the parameter as const-ref of the second function (either global or class member)
Here is the code
#include <iostream>
#include <optional>
#include <vector>
using dataType = int;
using dataTypeReturn = float;
//#define ENABLE_AFTER // For global fncs causes inf recursion
#define CONST_REF_FUNCTION // Causes expected behavior when !ENABLED_AFTER
#define CONST_REF_CLASS // Causes expected behavior
#ifndef ENABLE_AFTER
#ifdef CONST_REF_FUNCTION
// Causes expected behavior
std::vector<dataTypeReturn> foo(const dataType& bar){
#else
std::vector<dataTypeReturn> foo(dataType& bar){
#endif
std::cout << "foo(const dataType& bar)" << std::endl;
return std::vector<dataTypeReturn>(10, dataTypeReturn{});
}
#endif
std::vector<dataTypeReturn> foo(const std::optional<dataType>& bar){
std::cout << "foo(const std::optional<dataType>& bar)" << std::endl;
if(bar == std::nullopt)
return {};
return foo(*bar);
}
#ifdef ENABLE_AFTER
#ifdef CONST_REF_FUNCTION
// Causes infinite recursion
std::vector<dataTypeReturn> foo(const dataType& bar){
#else
std::vector<dataTypeReturn> foo(dataType& bar){
#endif
std::vector<dataTypeReturn> foo(const dataType& bar){
std::cout << "foo(const dataType& bar)" << std::endl;
return std::vector<dataTypeReturn>(10, dataTypeReturn{});
}
#endif
class Wrapper{
public:
std::vector<dataTypeReturn> foo(const std::optional<dataType>& bar){
std::cout << "foo(const std::optional<dataType>& bar)" << std::endl;
if(bar == std::nullopt)
return {};
return foo(*bar);
}
private:
#ifdef CONST_REF_CLASS
// Causes expected behavior
std::vector<dataTypeReturn> foo(const dataType& bar){
#else
// Causes infinite recursion
std::vector<dataTypeReturn> foo(dataType& bar){
#endif
std::cout << "foo(const dataType& bar)" << std::endl;
return std::vector<dataTypeReturn>(10, dataTypeReturn{});
}
};
int main(int argc, char** argv){
std::optional<dataType> myoptional(dataType{});
foo(myoptional);
Wrapper mywrapper;
mywrapper.foo(myoptional);
return 0;
}
In the case of the global functions, why depending on where I define the function the recursion happens or not? What would be the compile-process to decide what function to call?
In both cases, marking the parameter as const reference for the function that receives the underlying type of the optional does not incurr in the recursion, why? I was looking at the constructor implementations of std::optional and the only that could match I think is template < class U = value_type > constexpr optional( U&& value ); but I don't see how *bar ends up as a rvalue-ref.
A:
You are dereferencing a const optional<datatype>, you are using const value_type & optional::operator*() const, not value_type & optional::operator*().
A free function definition only looks at names declared preceding it. This is one of the reasons for having declarations of functions in headers. In the case of a member function, definitions of members see all the declarations of members.
foo(dataType& bar) is not a viable overload. If you haven't declared foo(const dataType& bar) before the definition of foo(const optional<dataType>& bar), the only viable overload is foo(const optional<dataType>& bar), which constructs a temporary optional. It deduces U as const dataType &, and const dataType & && is collapsed to const dataType &
| {
"pile_set_name": "StackExchange"
} |
Q:
Python OpenCV: Detecting a general direction of movement?
I'm still hacking together a book scanning script, and for now, all I need is to be able to automagically detect a page turn. The book fills up 90% of the screen (I'm using a cruddy webcam for the motion detection), so when I turn a page, the direction of motion is basically in that same direction.
I have modified a motion-tracking script, but derivatives are getting me nowhere:
#!/usr/bin/env python
import cv, numpy
class Target:
def __init__(self):
self.capture = cv.CaptureFromCAM(0)
cv.NamedWindow("Target", 1)
def run(self):
# Capture first frame to get size
frame = cv.QueryFrame(self.capture)
frame_size = cv.GetSize(frame)
grey_image = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 1)
moving_average = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_32F, 3)
difference = None
movement = []
while True:
# Capture frame from webcam
color_image = cv.QueryFrame(self.capture)
# Smooth to get rid of false positives
cv.Smooth(color_image, color_image, cv.CV_GAUSSIAN, 3, 0)
if not difference:
# Initialize
difference = cv.CloneImage(color_image)
temp = cv.CloneImage(color_image)
cv.ConvertScale(color_image, moving_average, 1.0, 0.0)
else:
cv.RunningAvg(color_image, moving_average, 0.020, None)
# Convert the scale of the moving average.
cv.ConvertScale(moving_average, temp, 1.0, 0.0)
# Minus the current frame from the moving average.
cv.AbsDiff(color_image, temp, difference)
# Convert the image to grayscale.
cv.CvtColor(difference, grey_image, cv.CV_RGB2GRAY)
# Convert the image to black and white.
cv.Threshold(grey_image, grey_image, 70, 255, cv.CV_THRESH_BINARY)
# Dilate and erode to get object blobs
cv.Dilate(grey_image, grey_image, None, 18)
cv.Erode(grey_image, grey_image, None, 10)
# Calculate movements
storage = cv.CreateMemStorage(0)
contour = cv.FindContours(grey_image, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE)
points = []
while contour:
# Draw rectangles
bound_rect = cv.BoundingRect(list(contour))
contour = contour.h_next()
pt1 = (bound_rect[0], bound_rect[1])
pt2 = (bound_rect[0] + bound_rect[2], bound_rect[1] + bound_rect[3])
points.append(pt1)
points.append(pt2)
cv.Rectangle(color_image, pt1, pt2, cv.CV_RGB(255,0,0), 1)
num_points = len(points)
if num_points:
x = 0
for point in points:
x += point[0]
x /= num_points
movement.append(x)
if len(movement) > 0 and numpy.average(numpy.diff(movement[-30:-1])) > 0:
print 'Left'
else:
print 'Right'
# Display frame to user
cv.ShowImage("Target", color_image)
# Listen for ESC or ENTER key
c = cv.WaitKey(7) % 0x100
if c == 27 or c == 10:
break
if __name__=="__main__":
t = Target()
t.run()
It detects the average motion of the average center of all of the boxes, which is extremely inefficient. How would I go about detecting such motions quickly and accurately (i.e. within a threshold)?
I'm using Python, and I plan to stick with it, as my whole framework is based on Python.
And help is appreciated, so thank you all in advance. Cheers.
A:
I haven't used OpenCV in Python before, just a bit in C++ with openframeworks.
For this I presume OpticalFlow's velx,vely properties would work.
For more on how Optical Flow works check out this paper.
HTH
| {
"pile_set_name": "StackExchange"
} |
Q:
Property placeholder from Configuration
With Spring in xml context we can simple load properties like this:
<context:property-placeholder location:"classpath*:app.properties"/>
Is there any chance to configure same properties inside @Configuration bean (~ from java code) without boilerplate?
Thanks!
A:
You can use the annotation @PropertySource like this
@Configuration
@PropertySource(value="classpath*:app.properties")
public class AppConfig {
@Autowired
Environment env;
@Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}
See: http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/annotation/PropertySource.html
EDIT: if you are using spring boot you can use @ConfigurationProperties annotation to wire the properties file directly to bean properties, like this:
test.properties
name=John Doe
age=12
PersonProperties.java
@Component
@PropertySource("classpath:test.properties")
@ConfigurationProperties
public class GlobalProperties {
private int age;
private String name;
//getters and setters
}
source:
https://www.mkyong.com/spring-boot/spring-boot-configurationproperties-example/
A:
Manual configuration can be done via following code
public static PropertySourcesPlaceholderConfigurer loadProperties(){
PropertySourcesPlaceholderConfigurer propertySPC =
new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[ ]
{ new ClassPathResource( "yourfilename.properties" ) };
propertySPC .setLocations( resources );
propertySPC .setIgnoreUnresolvablePlaceholders( true );
return propertySPC ;
}
Sources: Property Placeholder
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert a String to float in java
I'm trying to parse a String to a float with the float.parsefloat() method but it gives me an error concerning the format.
int v_CurrentPosX = Math.round(Float.parseFloat(v_posString)); //where v_posString is the float that I want to convert in this case 5,828
And the error:
Exception in thread "main" java.lang.NumberFormatException: For input
string: "5,828" at
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
A:
Your problem is that colon (,) is not a default locale in the JVM...
you can use a NumberFormat for that, with the right locale
String x = "5,828";
NumberFormat myNumForm = NumberFormat.getInstance(Locale.FRENCH);
double myParsedFrenchNumber = (double) myNumForm.parse(x);
System.out.println("D: " + myParsedFrenchNumber);
| {
"pile_set_name": "StackExchange"
} |
Q:
Minimal polynomial of $\sqrt{2}+\sqrt[3]{3}$.
Is there a way to show that the minimal polynomial of this number over $\mathbb Q$ has degree $6$ without too much annoying computations? I have "reduced" it to showing that both $\sqrt{2}$ and $\sqrt[3]{3}$ are in $\mathbb Q(\sqrt{2}+\sqrt[3]{3})$...
A:
There is a standard procedure for computing the minimal polynomial for the sum of two numbers from their minimal polynomials.
Let $f(X)$ and $g(Y)$ be the minimal polynomials of the algebraic numbers $\alpha$ and $\beta$. Set $Z=X+Y$. Now consider the polynomial $f(Z-Y)$ and eliminate from this the variable $Y$ using the relation $g(Y)=0$. Then thhe resulting polynomial involving just $Z$ is the minimal polynomial for $\alpha+\beta$.
Here it boils down to eliminating $Y$ from $ (Z-Y)^2-2$ using $Y^3-3=0$.
A:
Reference: Primitive Root Theorem
Just follow the proof, and you can show that the number $f$ in the proof, can be chosen to be $1$. Then $\mathbb{Q}(\sqrt 2, \sqrt[3]{3}) = \mathbb{Q}(\sqrt 2 + \sqrt[3]{3})$.
As $\alpha_1 = \sqrt 2$, and $\alpha_2 = -\sqrt 2$,
$\beta_1=\sqrt[3]{3}$, $\beta_2=\sqrt[3]{3} \omega$, $\beta_3= \sqrt[3]{3}\omega^2$, where $\omega=\exp(2\pi/3)$.
You just need the following equations are not true (which is obvious because one is real while the other is not),
$$-2\sqrt 2 = \sqrt[3]{3}-\sqrt[3]{3}\omega,$$
and
$$-2\sqrt 2 = \sqrt[3]{3}-\sqrt[3]{3}\omega^2.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
What is name of this soundtrack?
It plays while Boss of current stage is entering the arena. Game's name is "Swords and Sandals" (version 1 probably).
https://www.youtube.com/watch?v=uBh0EdT2bso
What is the music in this soundtrack called?
A:
This is Swords and Sandals II and if I'm not mistaken this music plays only during battle with John the Butcher. It's not easy to find all music from SS, but maybe you will find it here: https://soundcloud.com/oliverjoyce
Oliver Joyce is developer and composer from team 3RDSense, creators of Swords and Sandals.
| {
"pile_set_name": "StackExchange"
} |
Q:
Preventing duplicate usernames in Firebase
I'm trying to use Firebase security rules to prevent a number of undesirable situations happening in my app. The structure I have at the moment is:
"usernames": {
"twitter:123": "jack",
"google:456": "bob"
}
The issue here is that I can't implement security rules such that a third user (say facebook:789) can't come in and hijack the username 'bob' and get access to that user's data (my data is arranged by username).
What's the accepted fix for this scenario? I've tried reversing the key/value pairs, which allows uniqueness of usernames:
"usernames": {
"jack": "twitter:123",
"bob": "google:456"
}
However since this doesn't enforce uniqueness of UID, any user can spam usernames - the malicious facebook:789 could take any usernames not already taken, which would be a PITA to sort out.
Is there a way to solve this dilemma using Firebase security rules? Or is the only answer a trusted server? A trusted server would still present possible concurrency issues.
A:
Ok, I think I've got it. Like a lot of things in Firebase, the answer lies in diligent use of denormalisation :)
This solution is still a bit tentative, so please don't hesitate to correct/edit/comment/answer if you have corrections or a better idea.
The username/uid pairs need to be stored in both formats. For lack of a better name, I've called this an interlock:
{
"usernameInterlock" : {
"confirm" : {
"twitter:123" : "jack"
},
"request" : {
"jack" : "twitter:123"
}
}
}
Here are the security rules:
{
"rules": {
"usernameInterlock": {
"request": {
"$username": {
".read": true,
".write": "auth.uid == newData.val()
&& !(
data.exists()
&& root.child('usernameInterlock').child('confirm').child(data.val()).val() == $username
)"
}
},
"confirm": {
"$uid": {
".read": true,
".write": "auth.uid == $uid
&& root.child('usernameInterlock').child('request').child(newData.val()).val() == auth.uid"
}
}
}
}
}
The process is:
A user puts their uid in /usernameInterlock/request/$desiredUsername. This is writable unless /usernameInterlock/confirm/$uid_2 == $desiredUsername in which case it belongs to $uid_2. Anyone can request any usernames they want (and however many they want) because they don't mean anything unless they're under confirm. If someone goes too crazy this can be purged.
The user will then write $desiredUsername to /usernameInterlock/confirm/$uid. This can only be written to if the appropriate request child is already populated. This then becomes the canonical way of determining the user's username.
To verify a username, lookup /usernameInterlock/request/$username and then lookup the $uid obtained in /usernameInterlock/confirm/$uid, and if that value matches $username then the ($username, $uid) is a valid pair.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to maintain a docker image with slight modifications?
I've got a Docker image that is first built with a bunch of RUN commands that install software packages, dependencies, and copy files from a git repo. From this point forward, I want to create a new latest image only when the git repo is modified, but I don't want to repeat the entire process of installing the software. I just need to update the changed files and create the new image - so how does one create a image based on an existing image?
A:
Build a named and tagged image, start a new Dockerfile with FROM named:tagged
Personally I do think that one should consider the same security practices for software inside containers as on other servers. Therfore I do suggest to at least run a full container update for every " latest" build.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pig Latin fetching first field
I have below pig code for a sample file.
001,Rajiv,Reddy,21,9848022337,Hyderabad
002,siddarth,Battacharya,22,9848022338,Kolkata
003,Rajesh,Khanna,22,9848022339,Delhi
004,Preethi,Agarwal,21,9848022330,Pune
I load the above file using PIG load command & then loop thru it and get 2,3 fields as follows.
students = LOAD '/user/4965056e873066f2abe966b4129918/Pig_Data/students.txt' USING PigStorage(',') as (id:int,fname:chararray,lname:chararray,age:int,mob:chararray,city:chararray);
each1 = foreach students generate (id,fname,lname);
output of each1:
((001,Rajive,reddy)) etc.
Now i wanna get 1st field of each1 i.e.ID how to get it. I tried below code but showing error
each2 = foreach each1 generate(students.id)
Need to get the first filed from each2 relation.
A:
The extra parenthesis are added to the each1 relation, simply remove them:
students = LOAD '/user/4965056e873066f2abe966b4129918/Pig_Data/students.txt' USING PigStorage(',') as (id:int,fname:chararray,lname:chararray,age:int,mob:chararray,city:chararray);
each1 = foreach students generate id,fname,lname;
And you will get something like :
(001,Rajive,reddy)
For the each2 relation, you can get any filed of each1 without using the qualifier students, use filed name or filed position like this :
each2 = foreach each1 generate id;
each2 = foreach each1 generate $0;
And you will get something like :
(001)
| {
"pile_set_name": "StackExchange"
} |
Q:
java cache hashmap expire daily
I would like to have a HashMap<String, String>, that every day at midnight, the cache will expire.
Please note that it's J2EE solution so multiple threads can access it.
What is the best way to implement it in Java?
A:
Although the other suggestions can work to time the expiration, it is important to note that :
Expiration of the hashmap can be done lazily
i.e. without any monitor threads !
The simplest way to implement expiration is thus as follows :
1) Extend hash map, and create a local nextMidtime (Long) variable, initialized to System.currentTime....in the constructor. This will be set equal to the Next midnight time, in milliseconds...
2) Add the following snippet to the first line of the the "containsKey" and "get" methods (or any other methods which are responsible for ensuring that data is not stale) as follows :
if (currentTime> nextMidTime)
this.clear();
//Lets assume there is a getNextMidnight method which tells us the nearest midnight time after a given time stamp.
nextMidTime=getNextMidnight(System.currentTimeInMilliseconds);
A:
You want every single thing in the hashmap to be flushed at midnight?
If so I think I would create a new hashmap and substitute it for the original. Since the substitution is done in a single step and nothing else is trying to make the same change I believe it should be thread-safe.
Anything in mid-access will be allowed to finish it's access. This assumes that nothing else holds a reference to this hashmap.
If references to the hasmap are not consolidated to a single spot then I guess hashmap.clear() is your best bet if the hashmap is synchronized.
If the hashmap is not synchronized then you are only able to modify it from a single thread, right? Have that thread call hashmap.clear().
I think that covers all the cases.
A:
You might also look into using Guava's CacheBuilder, which allows you to create a customized instance of their Cache interface. Among other useful features, CacheBuilder allows you to set timed expiration, etc. to your own ends.
EDIT: I should note that you set expiration of entries based either on last access or last write, so this suggestion doesn't fit what you're asking for exactly, which is to flush everything once a night. You might still consider altering your design if using a third party API is an option. Guava is a very smart library IMHO, and not just for caching.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to change an encrypted volume's password w/o recreating the volume?
I have a 10G encrypted volume bundle created with Disk Utility. I want to change it's encryption password. How can I do that?
A:
You can use the "Change Password..." feature from the Images menu in Disk Utility. (Under the File menu in 10.7+. Hat tip to ymasood)
A:
hdiutil chpass image
You will be prompted for the passwords.
| {
"pile_set_name": "StackExchange"
} |
Q:
SignalR: Troubleshooting Suggestions for 404 Response at Connection() time
I am getting a 404 - Not Found Error at connection time in my QA environment. No issue with the same code in our dev integration environment.
I've looked at the other 404's reported here and was not able to find a good match.
Running fiddler, the outgoing request looks very similar in both environments.
Any suggestions on how to troubleshoot this further? Thanks.
* Test Server Connection OK *
var connection = $.connection('http://sdbntrwebdev01.sddev.lpl.com/AlertsService/request/' + token);
POST /AlertsService/request/7077342FE79A4EA99B939C24528EFB8E/negotiate HTTP/1.1
Host: sdbntrwebdev01.sddev.lpl.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
X-Requested-With: XMLHttpRequest
Referer: http://sdbntrwebdev01.sddev.lpl.com/alertsservice/healthcheck.aspx
Cookie: ASP.NET_SessionId=zadzj3je5ofm3e51350jl25b; Auth=7077342FE79A4EA99B939C24528EFB8E
Pragma: no-cache
Cache-Control: no-cache
Content-Length: 0
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 27 Mar 2012 23:51:41 GMT
* QA Server Connection gets 404 *
var connection = $.connection('http://sdalertwebqa01.qadmz.lpl.com/AlertsService/request/' + token);
POST /AlertsService/request/B8E02A155BBF4C55AC4E715C7F1CA968/negotiate HTTP/1.1
Host: sdalertwebqa01.qadmz.lpl.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
X-Requested-With: XMLHttpRequest
Referer: http://sdalertwebqa01.qadmz.lpl.com/alertsservice/healthcheck.aspx
Cookie: ASP.NET_SessionId=4zx05otp5oztqjqxvdaafa5e; Auth=B8E02A155BBF4C55AC4E715C7F1CA968
Pragma: no-cache
Cache-Control: no-cache
Content-Length: 0
HTTP/1.1 404 Not Found
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Tue, 27 Mar 2012 23:48:12 GMT
Content-Length: 1245
A:
Another guy here found the answer and I will share.
In IIS7, there is a setting called "URLRoutingModule-4.0". The "Edit Managed Module" dialog also contains a checkbox as "Invoke only for requests to ASP.NET applications or managed handlers". Un-check that checkbox.
This setting is at the "Default Web Site" level, double-click "Modules" from feature view to get a list of modules, double-click line item "URLRoutingModule-4.0" to launch the "Edit Managed Module" dialog.
| {
"pile_set_name": "StackExchange"
} |
Q:
How difficult it was to crack Navajo's language during WW2?
It is well known that during the WW2 America employed native American, namely Navajo people, to "encrypt" their radio communications. I read some time ago (I don't remember where) that their language was super effective and was considered very secure at the time of its deployment. And indeed it was, given that the Japanese never cracked it.
On the other hand I was reading this page on wikipedia that states
In addition many more Navajo served as code talkers for the military in the Pacific. The code they made, although cryptologically very simple, was never cracked by the Japanese.
Which got me wondering: Is it true that their code was "cryptologically" very simple? And if so, why didn't the Japanese crack it?
I mean I guess that there must be some weakness to this approach to cryptography, otherwise we would just invent a new language (which is fairly easy, albeit a little complex) instead of bothering with RSA, AES and whatnot.
Can you shed some light on this?
A:
Good question.
I'm a Native American, and this is pretty well-known to us. I also have experience with Chinese language and dialects. I'll explain why I'm mentioning the Chinese part later.
This is a very good example of security through obscurity. It works until it's figured out. However, there are so few Navajo speakers compared to English speakers, that it would've been incredibly difficult to find native speakers to learn from at the time. How would they know it's the Navajo language to begin with? It sounded alien to them.
While the code may have been simple, it's hard to find people to teach you that code. During WW2, Japanese in America were rounded up and placed in internment camps. Anyone caught sympathizing with them may have been likewise punished. The chances of finding a Navajo turncoat were extremely low.
Why is Encryption stronger than Languages and Dialects?
Regarding encryption, other people such as Thomas Pornin can explain this better than me, but I'll try to show you similarities:
Encryption is like a language. It's sort of like a conversion of one word (or character) to another set of highly different characters. With proper encryption, you can't convert A -> Z then Z -> A unless you have the key. With languages, you can compare words with similar meanings in other languages, and translate accordingly. With languages, your key is knowing the languages.
With proper encryption, you cannot do this. You cannot put properly-encrypted text into a decryption routine and get the results back. Not without the key. You need the key to decrypt it. With a hash, you can never get the message back, only verify whether or not it's genuine, but those can be vulnerable to collision attacks.
Here are some examples:
Pretend this is Encryption. The "key" to decrypting the
hidden message is to understand both languages. There is
a second hidden message which requires deeper understanding.
[English] [Chinese]
Hello -> 你好
Alpaca -> 草泥马
In the case of a hash (one-way), it could act like this:
[English]
Bring potter to Naria. The Death Star is ready for our war against the Time Lords.
[bcrypt]
$2a$04$38oxoVSWS9A97nkHYvxyD.FoLh7wxnHFTI2bOvg8XKZ/hA29BPEgS
With a hash, you would have to verify the contents against the message to see if they match. This is not really a method of encryption because you can't return the original message. You may eventually cause collisions as well.
In the case of AES 256 bit (two-way):
[English with key]
Find Potter and bring him to Narnia. The Death Star is ready for our war against the Time Lords.
[AES 256 encryption result]
Uz+07JfiUU8MwjJVCCefLpH8hFlP2mrjMbO4ArP7IbYVbpDFulUNf6GKDYw9fELI0oeni1sdD81E191BownSDPHvAnQ6TJTB63lYEodUj+ZxXVEvSetL+ZwXEgI9zS/R
How are you going to crack these? The same way as languages, actually. The difference is it's much, much harder to crack real encryption. Firstly, mapping a language and creating a translator is much, much easier than mapping an encryption database.
With one-way hashing, you would have to match every single combination of letters for every single encrypted character, to "crack" it, but that isn't going to return the message to you: it's only going to verify that the hash matches the message. With many hashing algorithms, collisions become a problem after a while.
With two-way encryption, you can get the original message back provided you have the key. Kind of like languages. Larger keys will very likely prevent brute force attacks, as with current technology, it would take longer than the estimated life of the universe to crack them. With languages, the "key" is understanding both languages.
This is why the Navajo "code" was cryptographically, "very simple" in comparison. The security through obscurity of the times made it very difficult to crack, but it would be easily very crackable today with current machines.
Having obscure dialects or languages can add an additional layer of "encryption," (note that the quotes indicate it's not really encryption) but, again, this is security through obscurity, and shouldn't be relied on by itself. In the case of encryption, these algorithms have been tested to be secure by well-educated researchers for a long time. Languages on the other hand, are much easier to learn.
Almost any idiot can learn a language. I'm living proof. Well-educated cryptographers and mathematicians can't crack many strong forms of encryption. What hope does the average layperson have?
Language and Dialect Usefulness
Regarding obscure dialects mentioned in #2, you can still see such things today. In fact, this isn't the only example of the Japanese getting owned by security through obscurity.
For example, the Chinese military relies on another layer of "encryption" (mind the quotes) -- which is really just security through obscurity -- with their dialects. During the last war with China, Japan wasn't able to "crack" the Wenzhou dialect because they didn't understand the implementation, and it was used against them.
Side note: considerable effort has been made by organizations such as Phonemica to demask obscure Chinese dialects.
Part of the problem with relying on dialects and languages today is that hacks are everywhere, so chances are high that someone will find your teaching manuals. Computers are at a good point where demasking a language or dialect could be automated in a very short time. On the other hand, real encryption is nigh unbreakable.
Once someone quickly learns your language or dialect, your security through obscurity would disappear very rapidly. This was used for thousands of years, but in modern times, it's not going to be that effective.
Is Security Through Obscurity Completely Invalid?
Despite what I've said, this does add another layer of obfuscation that is technically difficult to break. Even if your encrypted messages are broken, your attacker would still have to spend considerable time mapping it out. While it's child's played compared to proper encryption, security through obscurity does have it's uses, but you shouldn't rely on it entirely anymore.
A:
In addition to @Mark Buffalo's excellent response, there's another aspect -
For some communications it is sufficient to delay the adversary's access to the data, rather than to deny it. The 'Security through Obscurity' nature of Code Talking is sufficient to this limited goal.
Code Talkers, like the Navajo in the Pacific Theater, and more recently the Welch Fusiliers in Bosnia, have been used in tactical roles where the information being transmitted is only valuable for a narrow window of time. To quote (the fiction book) Cryptonomicon, where Daniel Waterhouse and Rod cCmndhd are talking about the use of Qwghlmians as Code Talkers:
"No, you confused the mid-glottal with the frontal glottal," Rod says.
"Honestly," Waterhouse says, "can you tell them apart over a noisy
radio?"
"No," Rod says. "On the radio, we stick to the basics: 'Get in there
and take out that pillbox or I'll kill you.' And that sort of thing."
The successes breaking cryptography in World War II involved months or weeks of work near the beginning of the war. Even by the end of the war, cracking the keys for a day's codes might not happen until hours or days had passed. When you're predicting something like the attack on Midway, which took months to plan and coordinate among large numbers of participants, that's fine (actually, at the time, it was still an astounding feat). But even if the equivalent techniques had been brought to bear on Code Talkers, the information transmitted would have been useless by the time it was 'decrypted' - the unit being told to move to Hill XYZ would have arrived and announced themselves long before the intercept was translated.
| {
"pile_set_name": "StackExchange"
} |
Q:
What will happen if I have 3,000 warnings but I chose to ignore them
I have to tune a Java EE application which needs to handle a transaction over 40 tps.
In each of every class, I see a lot of warnings such as unused variables, References to generic type Iterator should be parameterized, import ... is never used, local variable is never read and so on.
Will all of these warnings cause any performance defect to the application?
Does Java smart enough not to create a variable that is never used in run-time?
*I ran some tests on it and seems to be a memory hogging application; 10GB of heap can be filled up in less than 5 minutes with 1/4 of the throughput.
A:
Nothing will not happen. You will continue working on dirty and hard-to-understand code. It may be dangerous: because if you do not use variable you probably wanted to use it but by mistake used other one, so probably you code is buggy and this bug will be found on Friday, 6PM when you are going to go to the cinema with the girl of your life... :(.
Fixing of 3000 warnings is doable task. I did it at least twice with big and dirty projects. it may take about day or two. If I were you I'd do this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I be specifying IQueryable over List in my interfaces?
I'd like to know whether, when defining my interface, I should prefer IQueryable over List for groups of objects. Or perhaps IEnumerable is better, since IEnumerable types can be cast to IQueryable to be used with LINQ.
I was looking at a course online and it was dealing with EntityFramework, for which it is best to use IQueryable since LINQ uses it (okay there's more to it than that but probably not important right now).
The code below was used, and it got me thinking if I should be specifying IQueryable instead of List for my groups of objects.
namespace eManager.Domain
{
public interface IDepartmentDataSource
{
IQueryable<Employee> Employees { get; }
IQueryable<Department> Departments { get; }
}
If I were building an interface for a service that calls the repository to get Employees, I would usually specify
List <Employees>
but is this best practice? Would IQueryable give more flexibility to classes that implement my interface? What about the overhead of having to import LINQ if they don't need it (say they only want a List)? Should I use IEnumerable over both of these?
A:
The IQueryable interface is in effect a query on Entity Framework that is not yet executed. When you call ToList(), First() or FirstOrDefault() etc. on IQueryable Entity Framework will construct the SQL query and query the database.
IEnumerable on the other hand is 'just' an enumerator on a collection. You can use it to filter the collection but you'd use LINQ to Objects. Entity Framework doesn't come into play here.
To answer your question: it depends. If you want the clients of your repository to be able to further customize the queries they can execute you should expose IQueryable, but if you want full control in your repository on how the database is queried you could use IEnumerable.
I prefer to use IEnumerable, because that doesn't leak the use of Entity Framework throughout the application. The repository is responsible for database access. It is also easier to make LINQ to EF optimizations, because the queries are only in the repository.
| {
"pile_set_name": "StackExchange"
} |
Q:
QVideoWidget black window
I have added QVideoWidget as a child to QWidget, and I am trying to play local avi file, but without success. Here is the code:
#include "widget.h"
#include <QApplication>
#include <QtWidgets>
#include <QtMultimediaWidgets>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget window;
window.resize(320, 240);
window.setWindowTitle(QApplication::translate("childwidget", "Child widget"));
window.show();
QMediaPlayer *player = new QMediaPlayer;
QMediaPlaylist *playlist = new QMediaPlaylist(player);
playlist->addMedia(QUrl::fromLocalFile("/home/designer/Desktop/drop.avi"));
QVideoWidget *videoWidget = new QVideoWidget(&window);
player->setVideoOutput(videoWidget);
videoWidget->resize(320, 240);
videoWidget->show();
playlist->setCurrentIndex(1);
player->play();
return a.exec();
}
I included multimedia, multimediawidgets and widgets in my .pro file.
Also gstreamer packages are installed with sudo apt-get install gstreamer* libgstreamer* and version is 0.10.
I am running Debian Wheezy on VMWare and trying to build that code for i386 Desktop machine.
Am I missing something important so this code won't work? Only I get is black QVideoWidget window inside parrent QWidget.
A:
Your issue seem to be GStreamer-related. Please install a gst123 player (which is pure gstreamer-based player) and make sure it plays the file without printing errors. If it does not, QMediaPlayer will not play it either.
If gst123 does not work, it is either of:
You do not have all necessary GStreamer plugins installed to play this file. From my experience you need at least the following:
gstreamer-plugins-good
gstreamer-plugins-base
gstreamer-plugins-ugly
gstreamer-plugins-bad-orig-addon
gstreamer-plugins-qt5
gstreamer-plugins-bad
gstreamer-plugins-good-extra
gstreamer-plugins-ugly-orig-addon
gstreamer-plugins-libav
Make sure you install plugins for proper versions (if your machine has gstreamer_0.10 and gstreamer 1.x for example). Qt uses GStreamer 1.x
If you're using OpenSuSE, your GStreamer installation is crippled to be practically useless. You need to add Packman repository and reinstall all installed GStreamer packages with "vendor change".
For some videos the VDPAU driver breaks it in QMediaPlayer (while playing fine with gst123) - try to removing the gstreamer VDPAU plugin to check it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Trouble accessing attributes in the template - all attributes apart from 'name' show error '[attributename] is not defined'
The problem is that all Object attributes apart from 'name' call the error 'id/url/whatever is not defined' in the console when accessed from the template. A template with just 'name' displays fine and shows the correct name, but as soon as I call a different attribute, eg. id or url, it breaks. The object passed to the view is a parsed static JSON file with all items sitting on the same level and accessible from the console with e.g. collectionName.models[0].get('id');
What has me confused is that the name attribute works, as if it is predefined somewhere in backbone/underscore code as a default.
Am I missing something very obvious?
Since I can access the model data from the console, I think that there's something wrong with how the view itself handles the data, but I've tried rewriting it in a couple different ways and nothing seemed to make any difference.
All the relevant code.
Passed object format.
This is also what collectionName.models[0].attributes; returns in the console.
[{
"id":"0",
"name": "Building1",
"url": "building_1",
"floors":[{
"id":"0",
"name":"Ground Floor",
"image":"",
"rooms":[{
"id": "r_1",
"name": "Room 1",
},
{
"id": "r_2",
"name": "Room 2"
}]
}
}]
}
Example template code:
<span class="name"><%= name %></span>
<%= id %> <%= url %>
The router code:
routes: {
'': 'intro', // this route is using pretty much identical code and works fine, the model has the exact same format, the only difference is that all attributes work.
':id': 'firstLevel'
},
firstLevel: function (id) {
window.singleBuilding = new ThisBuilding({}, {idBuilding: id});
window.singleBuilding.fetch();
this.floorView = new FloorList({
collection: window.singleBuilding
});
var $intro = $('#intro');
$intro.empty();
$intro.append(this.floorView.render().el);
}
Views:
window.FloorSingleList = Backbone.View.extend({
className: 'floor-list',
initialize: function () {
this.template = _.template(tpl.get('floors-list-item'));
_.bindAll(this, 'render');
this.model.bind('change', this.render);
this.testModel = this.model.attributes; // I tried passing the attributes directly to the templatewithout .toJSON(), which worked exactly the same, as in only the 'name' attribute worked
},
render: function () {
console.log("The test data is:", this.testModel);
console.log("The actual model data is:", this.model);
var renderedContent = this.template(this.model.toJSON());
$(this.el).html(renderedContent);
return this;
}
});
window.FloorList = Backbone.View.extend({
tagName: 'section',
className: 'intro-list',
initialize: function () {
this.template = _.template(tpl.get('intro-list'));
_.bindAll(this, 'render');
this.collection.bind('reset', this.render, this);
this.collection.bind('change', this.render, this);
},
render: function (eventName) {
var $introList;
var collection = this.collection;
$(this.el).html(this.template({ }));
$introList = this.$('.intro-list');
collection.each(function (building) {
var view = new FloorSingleList({
model: building,
collection: collection
});
$introList.append(view.render().el);
});
return this;
}
});
Model code:
window.ThisBuilding = Backbone.Collection.extend({
model : Building,
initialize: function(models, options) {
// Initialising the argument passed on from the router.
this.idBuilding = options.idBuilding;
return this;
},
url : function(){
return "data.json"
},
parse: function (response) {
console.log("Passed parameters are :", this.idBuilding); // Returns the request parameters passed from the router.
return response[this.idBuilding];
}
});
Templates & Bootstrap
// templates are loaded during the bootstrap
tpl.loadTemplates(['header', 'intro-list', 'floors-list-item', 'building-list-item'], function() {
window.App = new ExampleApp();
Backbone.history.start();
});
A:
The problem is in how fetch in javascript is asynchronous...
firstLevel: function (id) {
window.singleBuilding = new ThisBuilding({}, {idBuilding: id});
window.singleBuilding.fetch(); // YOU FETCH HERE
this.floorView = new FloorList({
collection: window.singleBuilding
});
var $intro = $('#intro');
$intro.empty();
$intro.append(this.floorView.render().el); // AND RENDER WHILE YOU CAN'T ASCERTAIN THE FETCH HAS BEEN COMPLETED...
}
So what happens is that the render tries to read a collection that hasn't yet been initialized properly -> your models are not complete yet -> funny readings. Console log works with black magic when regarding to async operations. so it probably tells you something and the reality is something completely different So do this instead:
firstLevel: function (id) {
window.singleBuilding = new ThisBuilding({}, {idBuilding: id});
// Don't fetch here...
this.floorView = new FloorList({
collection: window.singleBuilding
});
var $intro = $('#intro');
$intro.empty();
$intro.append(this.floorView.el); // Don't render here
}
And then in the FloorList-view:
initialize: function () {
this.template = _.template(tpl.get('intro-list'));
_.bindAll(this, 'render');
this.collection.bind('reset', this.render, this);
this.collection.bind('change', this.render, this);
this.collections.fetch(); // fetch here, your binds take care of rendering when finished
}
Update 2: Apparently I saw complexity where there was none... Ignore everything below
From Backbone.js docs, on Model.toJSON()
Return a copy of the model's attributes for JSON stringification.
So it returns the attributes as JSON. Now backbone defines id as
A special property of models...
A property, not an attribute. Same goes for url. In a javascript object that represents a backbone Model, the attributes are stored in their own object within the object and the id- and url-properties are stored elsewhere in the model-object. For example the javascript object representing your model could look something like this:
{
...
attributes: Object // this is where your name attribute lives
...
id: 34, // this is your id property
...
__proto__: ctor, // this is where your url-function resides
...
}
UPDATE: The id-property is embedded onto the JSON in model.toJSON()
So when you do this.model.toJSON(), you create a JSON from the contents of your model-objects attributes-property and include the id-property. The url -property is not included in this. What you can do for example:
var renderedContent = this.template({
attributes: this.model.toJSON(),
url: this.model.url()
});
and in the template
<span class="name"><%= attributes.name %></span>
<%= attributes.id %> <%= url %>
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Entity Framework - ASP MVC Models - Relationships
I have some Models in my app like so:
public class Enquiry
{
[Key]
[Required]
public int EnquiryID { get; set; }
[Required]
[Display(Name = "Enquiry Type:")]
public virtual int EnquiryTypeID { get; set; }
public virtual EnquiryType EnquiryType { get; set; }
public virtual ICollection<DeliveryType> DeliveryTypes { get; set; }
}
public class EnquiryType
{
[Key]
public int EnquiryTypeID { get; set; }
[Display(Name = "Enquiry Type:")]
[MaxLength(100)]
public string EnquiryTypeName { get; set; }
}
public class DeliveryType
{
[Key]
public int DeliveryTypeID { get; set; }
public int EnquiryID { get; set; }
public string DeliveryName{ get; set; }
}
So the jist of it is. I have an Enquiry, each Enquiry has a Type of Enquiry (Sales, General, Technical etc..) so this is a One-to-One relationship. Each Enquiry can then have multiple DeliveryTypes attached to it, so its a One-to-Many relationship.
My question is, have I set this up correctly with my models above? Am I missing something? Do I have virtual's in the wrong place/not set up correctly? Do I need EnquiryID to be in my DeliveryType model?
A:
You do not need EnquiryID on the DeliveryType model. But, the EnquiryTypeID on the Enquiry should not be virtual. I would set it up like this:
public class Enquiry
{
[Key]
[Required]
public int EnquiryID { get; set; }
[Required]
[Display(Name = "Enquiry Type:")]
public int EnquiryTypeID { get; set; }
public virtual EnquiryType EnquiryType { get; set; }
public virtual ICollection<DeliveryType> DeliveryTypes { get; set; }
}
public class EnquiryType
{
[Key]
public int EnquiryTypeID { get; set; }
[Display(Name = "Enquiry Type:")]
[MaxLength(100)]
public string EnquiryTypeName { get; set; }
}
public class DeliveryType
{
[Key]
public int DeliveryTypeID { get; set; }
public string DeliveryName{ get; set; }
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it acceptable to publish a paper using an affiliation with a former employer?
Recently I've changed jobs, and consequently the field of research has also changed. But I'm still getting proposals for publications in the previous field, and it is interesting for me to accept some of them. My concern is about which affiliation to use: on one hand I gain all the knowledge in that field while working on the previous employer, also I hope they can cover my expenses related to the publication. On the other hand, I do not work for them anymore, and my current company has very little interest in my old field of research, and probably will not support it financially, but I think it is wise to mention them as well. As a compromise I'm thinking to put the previous employer in the affiliation, and the name of my new employer in the footnote, something like "currently at XYZ". Surely I'll discuss this issue with both, although the opinion of the community is also very valuable.
A:
If you have written the publication only with the resources and support of the former employer, then it is perfectly acceptable to do what you have written, and list the old address as your address for the "active" affiliations, and include a "present address" affiliation to show your updated physical location.
However, if your new employer does provide financial support, then you should list them accordingly. This is especially important if any of the actual research that makes its way into a publication has been performed while working for the new employer using their resources.
| {
"pile_set_name": "StackExchange"
} |
Q:
ios NSPredicate to find nearest value in NSDictionary
I have an array of dictionaries like this:
(
{ key = 1, value = 40},
{ key = 4, value = 50},
{ key = 8, value = 60}
}
These are like this,
for >=1 item cost is 40,
for >=4 item cost is 50 and like wise.
I would like to get the value for 5, which in this case is 50.
The piece of code I have tried is:
NSMutableArray *wallpaperPriceArray = [[NSMutableArray alloc]init]; // Assuming this has all the dictionary values
float wallpaperPriceValue = 0;
int itemNumber = 0;
for (int i = 0; i<wallpaperPriceArray.count; i++) {
int check = 0;
if(itemNumber >= [[wallpaperPriceArray objectAtIndex:i] intValue])
{
wallpaperPriceValue = [[[wallpaperPriceArray objectAtIndex:i] objectForKey:@"value"] floatValue];
check++;
}
if(i + 1 <= wallpaperPriceArray.count)
{
if(itemNumber >= [[wallpaperPriceArray objectAtIndex:i+1] intValue] && itemNumber < [[wallpaperPriceArray objectAtIndex:i+1] intValue])
{
wallpaperPriceValue = [[[wallpaperPriceArray objectAtIndex:i+1] objectForKey:@"value"] floatValue];
check++;
if(check == 2)
{
break ;
}
}
}
if(i + 2 <= wallpaperPriceArray.count)
{
if(itemNumber >= [[wallpaperPriceArray objectAtIndex:i+2] intValue] && itemNumber < [[wallpaperPriceArray objectAtIndex:i+2] intValue])
{
wallpaperPriceValue = [[[wallpaperPriceArray objectAtIndex:i+2] objectForKey:@"value"] floatValue];
check++;
if(check == 2)
{
break ;
}
}
}
A:
I Don't think the predicate is the right thing, Better would be to enumerate the objects here is some sample code:
NSArray *array = @[
@{ @"key" : @(1), @"value" : @(40)},
@{ @"key" : @(4), @"value" : @(50)},
@{ @"key" : @(8), @"value" : @(60)}
];
NSInteger searchedValue = 5; // <---
__block NSDictionary *closestDict = nil;
__block NSInteger closestValue = 0;
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSDictionary *dict = obj;
NSInteger key = [dict[@"key"] integerValue];
// Check if we got better result
if(closestDict == nil || (key > closestValue && key <= searchedValue)){
closestDict = dict;
closestValue = key;
if(key == searchedValue) { *stop = YES; }
}
}];
NSLog(@"value %@", closestDict);
| {
"pile_set_name": "StackExchange"
} |
Q:
Load in random .html file with PHP?
I have a folder which contains several html files: 1.html, 2.html, 3.html, etc., etc. in sequential order.
I would like for PHP to randomly load in these files into a PHP webpage that I have. How can I go about doing this?
Also -- is PHP the most efficient way to do this? Would jQuery be better?
A:
jquery could do it, but you'd have to send a list of the available files to the client beforehand, so it has a list to choose from. This would be required if you can't guaranteed there'll never be "holes" in the files, e.g. 1,2,4,5 (hey, where's 3?).
PHP can deal with the raw filesystem, and can always get the list of files, e.g.
<?php
$files = glob('*.html');
$random_file = $files[array_rand($files)];
include($random_file);
This will handle any .html file, regardless of holes in the numbering sequence, or even if they're numbered at all.
| {
"pile_set_name": "StackExchange"
} |
Q:
disable select option value when selected
I am using this code. But I'm facing a problem that when I select "one" in 1st select box and then in 2nd I select "two" and when I select again 2nd value to "three" but the value "two" remain disabled:
HTML code
// one
<select>
<option>Select</option>
<option value="1" >one</option>
<option value="two">two</option>
<option>three</option>
</select>
//two
<select>
<option>Select</option>
<option value="1" >one</option>
<option value="two">two</option>
<option>three</option>
</select>
This is JavaScript code:
$(document).ready(function(e) {
var $selects = $('select#players');
available = {};
$('option', $selects.eq(0)).each(function (i) {
var val = $.trim($(this).text());
available[val] = false;
});
$selects.change(function () {
var $this = $(this);
var selectedVal = $.trim($this.find('option:selected').text());
available[selectedVal] = true;
$selects.not(this).each(function () {
$('option', this).each(function () {
var optText = $.trim($(this).text()),
optCheck = available[optText];
if(optCheck) {
$(this).prop('disabled', true);
}
else {
$(this).prop('disabled', false);
}
});
});
}).change(); // Trigger once to add options at load of first
});
A:
Assuming you want to disable values in the other select-boxes once chosen, here is a sample.
<select>
<option value="" selected="selected">Select</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<select>
<option value="" selected="selected">Select</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
$(document).ready(function (e) {
var $selects = $('select');
$selects.change(function () {
var value = $(this).val();
if (value == "") {
return false;
}
$selects.not(this).each(function () {
$('option', this).each(function () {
var sel = $(this).val();
if (sel == value) {
$(this).prop('disabled', true);
} else {
$(this).prop('disabled', false);
}
});
});
}).change(); // Trigger once to add options at load of first
});
And a working fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Proofs of Jacobi's four-square theorem
What are the nicest proofs of Jacobi’s four-square theorem you know? How much can they be streamlined? How are they related to each other?
I know of essentially three aproaches.
Modular forms, as in, say, Zagier’s notes in “The 1-2-3 of Modular Forms”. The key facts here are that (a) the theta function is a modular form, (b) the space of modular forms of given weight and level is finite-dimensional (indeed 2-dimensional for the small level that is involved here). I feel reasonably certain that I can pare this down to fit my constraints without too much loss.
Elliptic functions. This, I understand, is the route originally chosen by Jacobi himself; it is also the one I have seen most often. There are many variants. Most of the time one proves Jacobi’s triple product identity first (good: see the constraints above) and then derives the theorem from it in several pages of calculations involving at least one miraculous-looking identity. My concerns here are two-fold. First – all of these identities (triple-product included) really rest on the same fact, namely, the low-dimensionality of the space of elliptic functions with given multipliers (or whatever they are called). However, even when this is said, this is not really fully and directly exploited in the proofs I’ve seen. Second – while some proofs of Jacobi’s triple product identity I’ve seen are reasonably streamlined, what comes thereafter always comes through as computational and very ad-hoc. Can any of this be helped?
– A variant of this approach is Ramanujan’s proof in Hardy-Wright. It’s concise, but I’d really like to see what it really rests on. Can it be made clearer, a little longer and a little less elementary?
Uspensky’s elementary proof, based on an identity of Liouville’s; there is an exposition of this in Moreno-Wagstaff. Liouville’s identity feels like a bit of magic to me – I feel there is really something about elliptic functions being snuck here, though I do not know exactly what.
What is your take on this? How are these approaches related? (I feel they have to be, in several ways. In particular, a Jacobi theta function is both an elliptic function and a modular form, depending on which variable you are varying.) What would be some ways of making the elliptic-function approach more streamlined and conceptual, without much in the way of calculations?
A:
There is a very nice and readable little book by Hurwitz from 1909 in which he describes the properties of the integer quaternions (later called Hurwitzian quaternions): the subring of the Hamiltonian quaternions of the form a + bi + cj + dk where a, b, c, and d are either all integers or all half-integers (like 3/2). Basically the point of the book is that this ring behaves pretty much like any other UFD, except that it is not commutative. So there are prime elements and unique factorization into them etc, when using the right notion of uniqueness to take care of the left/rigth business. Towards the end of the book he starts considering the finite quotients obtained by modding out the two sided ideals generated by these primes and doing a lot of counting inside these rings he deduces the four square theorem. It is not the most beautiful part of the book because there is a lot of 'administration' to keep track of, but it is a nice elementary proof of the theorem. I hope I can find the title.
A:
I thought I would write out the quaternion proof, because it is really quite elegant if you have good algebraic terminology. One note: I won't be proving quite the right result. Let $r(n)$ be the number of quadruples $(a,b,c,d)$ with $n=a^2+b^2+c^2+d^2$ such that either $a$, $b$, $c$ and $d$ are all in $\mathbb{Z}$, or are all in $(1/2) + \mathbb{Z}$. The formula I'll be proving is
$$r(n) = 24 \sum_{\begin{matrix} d|n \\ d \ \mathrm{odd} \end{matrix}} d \quad \mathrm{for}\ n>0$$
The question of allocating the terms between $\mathbb{Z}$ and $(1/2) + \mathbb{Z}$ is a bit messier.
Let $H$ be the ring of quaternions of the form $a+bi+cj+dk$, with $(a,b,c,d)$ as above.
The following lemmas are proved in many sources on the quaternion proof of the Lagrange theorem:
$\bullet$ Every right ideal of $H$ is principal.
$\bullet$ The right ideal $(a+bi+cj+dk) H$ has index $(a^2+b^2+c^2+d^2)^2$ in $H$.
Let $q(n)$ be the number of right ideals of $H$ that have index $n^2$. Since the unit group of $H$ has size $24$, we have $r(n) = 24 q(n)$. So we concentrate on computing $q(n)$.
Let $I = (a+bi+cj+dk)H$ be a right ideal of $H$ with index $n^2$. Then $(a+bi+cj+dk)(a-bi-cj-dk) = n \in (a+bi+cj+dk)H$. So $I/nH$ is an index $n^2$ ideal in the ring $H/nH$. We see that $q(n)$ is the number of index $n^2$ ideals in $H/nH$.
Now, by the Chinese remainder theorem, if $m$ and $n$ relatively prime, then $H/mnH \cong H/mH \times H/nH$. So $q(n)$ is multiplicative, and we are reduced to proving the claim for $n$ a prime power.
We start in the case $n = p^r$ for $p$ odd. Let $\mathbb{Z}_p$ be the $p$-adic integers and let $H_p := H \otimes \mathbb{Z}_p$. We will start by showing that the number of index $p^{2r}$ ideals in $H_p$ is $p^r+p^{r-1} + \cdots + p+1$. We then check that all of those ideals contain $p^r H$, so this is also the number of ideals in $H/p^r H$.
The point is that $H_p \cong \mathrm{Mat}_{2 \times 2}(\mathbb{Z}_p)$ (again, for $p$ odd). By a standard pigeon hole argument, we can find $u$ and $v$ with $u^2+v^2 + 1 \equiv 0 \mod p$; by Hensel's lemma, we can find $u$ and $v$ in $\mathbb{Z}_p$ with $u^2+v^2+1=0$. Let
$$I = \begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix} \quad
J = \begin{pmatrix} u & v \\ v & -u \end{pmatrix} \quad
K = \begin{pmatrix} v & -u \\ -u & -v \end{pmatrix}.$$
Then $I$, $J$ and $K$ obey the quaternion relations, and we get a map $H_p \to \mathrm{Mat}_{2 \times 2}(\mathbb{Z}_p)$. We claim that this map is bijective. It is a map between two free $\mathbb{Z}_p$-modules of rank four, so we just need to check that the determinant of this map is a unit of $\mathbb{Z}_p$. This determinant is $-4(u^2+v^2)=4$. Since $p$ is odd, we are fine.
So, set $E_p := \mathrm{Mat}_{2 \times 2}(\mathbb{Z}_p)$. Let's count index $p^{2r}$ right ideals $E_p$. Let $M$ be the $E_p$-module $\mathbb{Z}_p^2$. As a module over itself, $E_p \cong M^{\oplus 2}$. Right ideals is another word for submodules, so we want to count index $p^{2r}$ submodules of $M^{\oplus 2}$. Since $E_p$ is Morita equivalent to $\mathbb{Z}_p$, we know that $E_p$ submodules of $M^{\oplus 2}$ are in bijection with $\mathbb{Z}_p$-submodules of $\mathbb{Z}_p^{\oplus 2}$. A quick check shows that being index $p^{2r}$ in $M^{\oplus 2r}$ corresponds to being index $p^r$ in $\mathbb{Z}_p^{\oplus 2}$. Moreover, every index $p^r$ submodule of $\mathbb{Z}_p^{\oplus 2}$ is contained in $p^r \mathbb{Z}_p^{\oplus 2}$, so every index $p^{2r}$ submodule of $M^{\oplus 2}$ is contained in $p^r M^{\oplus 2}$, fulfilling an earlier promise, and allowing us to shift our attention to the finite problem of counting index $p^r$ submodules in $(\mathbb{Z}/p^r)^{\oplus 2}$.
We are reduced to showing that the number of index $p^r$ submodules of $(\mathbb{Z}/p^r)^{\oplus 2}$ is $p^r + p^{r-1} + \cdots p+1$. Proof by induction on $r$. Let $N$ be such a submodule. There are two cases:
(1) $N$ is not contained in $p (\mathbb{Z}/p^r \mathbb{Z})^{\oplus 2}$. In this case, $N$ is generated by a single element. The number of elements of $(\mathbb{Z}/p^r)^{\oplus 2}$ which generate a submodule of index $p^r$ is $p^{2r} - p^{2r-2}$. Two such elements give the same submodule if their ratio is a unit of $\mathbb{Z}/p^r$; the number of such units is $p^r-p^{r-1}$. So the number of $N$ in this case is $(p^{2r}-p^{2r-2})/(p^r - p^{r-1}) = p^r+p^{r-1}$.
(2) $N$ is contained in $p (\mathbb{Z}/p^r \mathbb{Z})^{\oplus 2}$. In this case, $N$ is an index $p^{r-2}$ submodule of $p (\mathbb{Z}/p^r \mathbb{Z})^{\oplus 2} \cong (\mathbb{Z}/p^{r-1} \mathbb{Z})^{\oplus 2}$. By induction, the number of options for such an $r$ is $p^{r-2} + p^{r-3} + \cdots p+1$.
Adding the two cases together, we are done.
Okay, so what about $2^r$? What one wants to show is that there is only one index $2^{2r}$ ideal in $H$.
I haven't found a ring theory way to do this, but a direct proof isn't hard. Notice that, if $a^2+b^2+c^2+d^2$ is even, then $(a,b,c,d)$ must be integers, and an even number of $(a,b,c,d)$ must be odd. So we can write $a+b+cj+dk = \epsilon + 2 (a' + b'i+c'j+d'k)$ which $\epsilon$ is one of $0$, $1+i$, $1+j$, $1+k$, $i+j$, $i+k$, $j+k$ or $1+i+j+k$. Each option for $\epsilon$ is divisible by $(1+i)$, and we also have $2=(1+i)(1-i)$. So we have shown that, if $a^2+b^2+c^2+d^2$ is even, then $1+i$ divides $a+bi+cj+dk$. By induction, then, $a^2+b^2+c^2+d^2 = 2^r$, then $a+bi+cj+dk$ is a unit times $(1+i)^r$.
A:
If you are interested only in Jacobi's formula for odd integers, there is an elementary proof based on the convolution formula $r_4(n)=\sum_{r+s=n}r_2(r)r_2(s)$, due to Dirichlet (Sur l'\'equation $t^2+u^2+v^2+w^2=4m$, J. Maths Pures et Appliqu\'ees 1 (1856), 210-214), and advocated by A. Weil (Sur les sommes de trois et quatre carr\'es (1974), Oeuvres Scientifiques Vol III, Springer-Verlag, 1979). We took this proof in our book with G. Davidoff and P. Sarnak, see section 2.4 of "Elementary number theory, group theory, and Ramanujan graphs", London Math. Soc. Students texts 55, Cambridge Univ. Press, 2003.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mark object as readonly
I am trying to emplement a user rights in my library. It looks like this.
class api:
def get_readonly_obj_by_id(self, user_id, obj_id) -> Obj:
self.user_can_read_obj(user_id, obj_id)
return self.session.query(Obj).get(obj_id)
def save():
self.session.commit()
Is it possible to mark this object as readonly?
obj = api.get_readonly_obj_by_id(user_id, obj_id)
obj.name = 'newName'
obj.user = new_user
api.save()
So all the changes made with save method wouldnt affect on this object in database.
Then i will create this method.
def get_write_obj_by_id(self, user_id, obj_id) -> Obj:
self.user_can_write_obj(user_id, obj_id)
return self.session.query(Obj).get(obj_id)
That will allow me to get rid of update_obj method.
def update_obj(self, user_id, obj_id, args: dict):
self.user_can_write_obj(user_id=user_id, obj_id=obj_id)
self.session.query(Obj).filter_by(id=obj_id).update(args)
return self.session.query(Obj).get(obj_id)
and will allow to edit objects directly like this
obj.name = 'newname' # if i received this object with get_writeble_obj method
api.save()
Models created with ActiveRecord approuch.
A:
In Python, it's relatively easy to protect values from accidental mutation, but next to impossible to protect them from intentional mutation.
If you just want to make it so that obj.name = 'NewName' will raise a TypeError, this is easy:
class MyObject:
def __setattr__(self, name, value):
if self._frozen:
raise TypeError(f"frozen '{type(self).__name__}' objects do not support assignment")
Of course you then need to go around the normal self.name = value mechanism to assign the values in the first place. Normally you either do this by calling super().__setattr__ or by going straight to self.__dict__[name], and often you want to do it in a __new__ method rather than an __init__ method. But if you're careful, you can also just do it before self._frozen = True.
If you need more flexibility, to freeze just some specific attributes while leaving others assignable, you can use a descriptor—the stdlib's @property without a setter works fine for this. If you also want to prevent creation of new attributes, you still need __setattr__—or you might want to consider using __slots__.
So, to construct an object, you might do something like this:
class Freezable:
def __new__(cls, *args, frozen=False, **kwargs):
obj = super().__new__(cls, *args, **kwargs)
super().__setattr__(obj, '_frozen', frozen)
return obj
def __setattr__(self, name, value):
if self._frozen:
raise TypeError(f"frozen '{type(self).__name__}' objects do not support assignment")
super().__setattr__(name, value)
And now, you can just make all of your classes into subclasses of Freezable. They'll need to handle the frozen construction parameter by ignoring it in __init__ (and explicitly passing it to super in __new__, if any of them need a custom __new__, but they probably won't).
Then, your get_readonly_obj_by_id just does something like:
return Whatever(user_id, obj_id, frozen=True)
But this won't stop someone from getting around the restriction if they want to. Whatever you do in your __setattr__, they can do directly. Or, if you're using a @property to store the value elsewhere, they can just assign to that elsewhere. Not to mention that they can just set obj,_frozen = False. (You can make them jump through the same hoops again, but that doesn't make it any more secure.)
If you have some other storage that is protected, you can always change your objects into some kind of proxy to that storage, instead of holding the values directly, but that's pretty complicated—and it relies on you having already built some kind of protected store; it isn't a way to build one in the first place.
Your database presumably is just such a protected store. But you don't want to proxy every attribute lookup and assignment through the database—in fact, you don't want anything written there at all until save.
But that means a hybrid approach is probably fine.
Use the "consenting adults" protection of __setattr__ and _frozen to protect people from accidentally mutating an object they won't be allowed to store.
If they go behind your back and find a way to mutate the object anyway, when they call save, you can block the update (or the database can do it automatically for you) and give them an exception.
| {
"pile_set_name": "StackExchange"
} |
Q:
"open_basedir restriction in effect" but file is in the correct dir
I am trying to move some sites to a new server (running Plesk 11) and I am getting the following Error:
Warning: file_exists() [function.file-exists]: open_basedir restriction in effect. File(configuration.php) is not within the allowed path(s): (C:\Inetpub\vhosts\domain.com\domains\domain.com\www\;C:\Windows\Temp) in
C:\Inetpub\vhosts\domain.com\domains\domain.com\www\index.php on line 18
But the configuration.php file is in C:\Inetpub\vhosts\domain.com\domains\domain.com\www\!
I am nearly getting crazy here as this makes absolutely no sense to me.
I can even set the open_basedir value to none and still get the same error.
Same also for using PHP 5.2 or 5.3.
The only thing which got me a little bit further was setting a dirname(__FILE__) in front of the call in index.php on line 18, but this is no solution as I can't alter all file references in the whole CMS. Because of this I also tried to add the www folder to the include path without any luck.
A:
AFAIK there has been a problem in Plesk with disabling open_basedir on Windows. Try to delete open_basedir key from registry
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\PHP\Per Directory Values\C\Inetpub\vhosts\yourdomain.com\httpdocs
| {
"pile_set_name": "StackExchange"
} |
Q:
Deploy Replicas in specific ports and hostname
I need to deploy a docker container in a swarm. I want to deploy 4 replica of the docker container. I want to set the port which each container will run and I need to know their hostname.
What I would is to lunch 4 replicas.
Replica 1 should listen to port 3001 and hostname slave1.
Replica 2 should listen to port 3002 and hostname slave2.
Replica 3 should listen to port 3003 and hostname slave3.
Replica 4 should listen to port 3004 and hostname slave4.
Each replica has the same Dockerfile (because the process which I want to run is the same). In the Dockerfile I expose all the 4 ports using the standard command:
EXPOSE 3001 3002 3003 3004
I tried this docker-compose file where I use 4 ports and deploy using "mode:replicated"
services:
slave:
image: "DOCKER_REPO_NAME"
deploy:
mode: replicated
replicas: 4
restart_policy:
condition: on-failure
networks:
- my_net
ports:
- "3001:3001"
- "3002:3002"
- "3003:3003"
- "3004:3004"
networks:
my_net:
external: true
but it is not working as I would and as described above.
Hope the description of the problem makes sense. Please let me know.
A:
I think you are misunderstanding docker swarm mode respectively the way it is supposed to work. Swarm mode is not working on container / node level but it is one level of abstraction higher - it is working with services.
A service consists of a given count of instances of containers running on a given count of nodes. Swarm will handle how many container instances are running in the swarm and it will handle on which nodes the service's containers are running (of course you can configure that by using params like replicas and constraints).
A great benefit of swarm mode is that you don't need to know anything about the infrastructure of the swarm. You don't care about which nodes are there and which container is running on which node.
Instead you just tell the swarm what service you want to contact and swarm mode will decide to which container on which node it will dispatch your request.
So in your example if your service is running on port 3001 and let's say there is an api endpoint called GET /hello you would request http://slave:3001/hello. This is where swarm mode comes into play and because it knows which containers are running on which nodes, it will decide where your request will be forwarded to.
If you want to have specific containers listening to specific ports on specific nodes you have to define multiple services and configure those using constraints and labels .. so your docker-compose.yml would look something like:
services:
slave1:
image: "DOCKER_REPO_NAME"
deploy:
mode: replicated
replicas: 1
placement:
constraints:
- node.labels.type == slave1
restart_policy:
condition: on-failure
networks:
- my_net
ports:
- "3001:3001"
slave2:
image: "DOCKER_REPO_NAME"
deploy:
mode: replicated
replicas: 1
placement:
constraints:
- node.labels.type == slave2
restart_policy:
condition: on-failure
networks:
- my_net
ports:
- "3002:3001"
slave3:
image: "DOCKER_REPO_NAME"
deploy:
mode: replicated
replicas: 1
placement:
constraints:
- node.labels.type == slave3
restart_policy:
condition: on-failure
networks:
- my_net
ports:
- "3003:3001"
slave4:
image: "DOCKER_REPO_NAME"
deploy:
mode: replicated
replicas: 1
placement:
constraints:
- node.labels.type == slave4
restart_policy:
condition: on-failure
networks:
- my_net
ports:
- "3004:3001"
networks:
my_net:
external: true
But be aware of the fact that this is destroying much of the benefits of swarm.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ruby: get 1.month into a string
Ruby has amazing time object handling. Eg. 1.month + 1.day
I'd like to convert 1.month to the string "1 month", and in a rails model.
How can I do that?
Thanks
A:
Using inspect gives back that string when I've tried it.
1.month.inspect #=> "1 month"
2.months.inspect #=> "2 months"
2.month.inspect #=> "2 months"
UPDATE
As a point of interest, I didn't find this answer in any documentation. (Maybe it's available somewhere, but I haven't seen it.) My first step was to try the two mostly likely candidates when trying to get a string value for something (to_s and inspect) and so I found it quickly that way. However, I continued to try to find a way that isn't based on using inspect by looking at what methods are available using 1.month.methods.sort and looking at the various to_* methods. This last can be a handy thing to try when attempting to figure out what a particular ruby object will provide.
| {
"pile_set_name": "StackExchange"
} |
Q:
Organizing a "speedback"
Speedback is the merging of speed-dating with feedback: a 2 min. 1-on-1 talk with all members of a group of people.
I'm in a team and I want to plan the ideal speedback setup: all team members have to give feedback to eachother.
I want to group people in a way that maximizes the concurrency of simultaneous pairs so we reduce the total time of the sessions.
Consider the input:
"alexandre", "sergiu", "joana", "tiago", "susana", "david"
combinations(6,2) = 15 possible pairs
1st session:
"alexandre" with "sergiu"
"joana" with "tiago"
"susana" with "david"
2nd session:
"alexandre" with "joana"
"sergiu" with "tiago"
"joana" with "david"
3rd session:
...
you get the ideia.. until everyone "dates" everyone.
I need all the possible pairs to be matched in the end.
Do you how to get this output? (or can you hint about the solution)?
A:
Suppose that your team contains $n$ people. Each round of discussions ("session") corresponds to a matching in the complete graph $K_n$. Therefore you want to partition into as few matchings as possible. The answer depends on the parity of $n$.
Case 1: $n$ is even. In this case, $K_n$ contains $\binom{n}{2}$ edges, and a matching contains at most $n/2$ edges. Hence we can hope for a partition of $K_n$ into $n-1$ perfect matchings. This is a standard problem, known as 1-factorization of the complete graph. Here is one solution:
$$
(0,n-1),(1,n-2),(2,n-3),(3,n-4),\ldots,(n/2-1,n/2) \\
(1,n-1),(2,0),(3,n-2),(4,n-3),\ldots,(n/2,n/2+1) \\
(2,n-1),(3,1),(4,0),(5,n-2),\ldots,(n/2+1,n/2+2) \\
\ldots
$$
Explanation: the $i$'th row consists of $(i,n-1)$ together with $(j+i,n-1-j+i \bmod n-1)$ for $1 \leq j \leq n/2-1$. For example, when $n = 6$ you get:
$$
(0,5),(1,4),(2,3) \\
(1,5),(2,0),(3,4) \\
(2,5),(3,1),(4,0) \\
(3,5),(4,2),(0,1) \\
(4,5),(0,3),(1,2)
$$
Case 2: $n$ is odd. In this case, $K_n$ still contains $\binom{n}{2}$ edges, but now each matching contains at most $(n-1)/2$ edges. Hence we can hope for a partition of $K_n$ into $n$ almost-perfect matchings. We can take the solution above for $n+1$, and just ignore the match of vertex $n$. This gives the following solution:
$$
(1,n-1),(2,n-2),(3,n-3),\ldots,((n-1)/2,(n+1)/2) \\
(2,0),(3,n-1),(4,n-2),\ldots,((n+1)/2,(n+3)/2) \\
(3,1),(4,0),(5,n-1),\ldots,((n+3)/2,(n+5)/2) \\
\ldots
$$
Explanation: the $i$th row consists of $(j+i,n-j+i \bmod n)$ for $1 \leq j \leq (n-1)/2$. For example, when $n = 7$ you get:
$$
(1,6),(2,5),(3,4) \\
(2,0),(3,6),(4,5) \\
(3,1),(4,0),(5,6) \\
(4,2),(5,1),(6,0) \\
(5,3),(6,2),(0,1) \\
(6,4),(0,3),(1,2) \\
(0,5),(1,4),(2,3)
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Minor ordering for finite graphs
Let $\mathcal{G}_{<\omega}$ be the set of graphs $G = (V,E)$ such that $V = \{0,\ldots,n\}$ for some $n \geq 0$ and $E \subseteq \mathcal{P}_2(V) = \{\{a,b\} : a,b \in V \textrm{ and } a\neq b\}$. We write $\mathcal{G}_{<\omega}/\cong$ for the set of isomorphism classes. The following defines an ordering relation on $\mathcal{G}_{<\omega}/\cong$:
$[G]_\cong \leq [H]_\cong$ if and only if there is a collection $\mathcal{S}$ of non-empty, connected and pairwise disjoint subsets of $H$ and a bijection $\varphi: G\to \mathcal{S}$ such that whenever $\{v,w\}\in E(G)$ there are $x\in\varphi(v), y\in\varphi(w)$ such that $\{x,y\} \in E(H)$.
In other words, this is the "minor ordering".
Questions:
1) Is $(\mathcal{G}_{<\omega}/\cong, \leq)$ a lattice?
2) If $P$ is a finite poset, is there an order-embedding $e: P\to \mathcal{G}_{<\omega}/\cong$?
A:
Re part (1): It's certainly not a lattice. For instance if $G$ is a four-vertex path and $H=K_{1,3}$, a four-vertex star, then the minimal graphs that contain both $G$ and $H$ as minors are a four-vertex graph with a triangle and a tail, or a five-vertex tree. Neither is a minor of the other: the five-vertex tree has too many vertices to be a minor of the four-vertex triangle-and-tail, and in the other direction taking a minor of a five-vertex tree can't produce anything with a cycle. So $G$ and $H$ have no unique least upper bound.
By the way, the way you define minors forces the graphs to be simple. This works, but the theory is often a little simpler (e.g. forbidden minors are smaller) if you allow multiple adjacencies and self-loops instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to split a text with more than one delimiter?
public static void main(String[] args){
String s=new String("f;sjdkfd:fdsfdf;df:FD::D:::F:RE:FRER:F:ER:FR:F:RF:GR:G:RG: :P");
String[] ss = s.split(":");
for(String token : ss){
System.out.println(token);
}
}
using this code, I can get the token between ":". But I wan to split the text with both ":"and";" at the same time. is that possible?
A:
You can use a regular expression:
String[] ss = s.split("[:;]")
So, the code will be:
public static void main(String[] args) {
String s = new String("f;sjdkfd:fdsfdf;df:FD::D:::F:RE:FRER:F:ER:FR:F:RF:GR:G:RG: :P");
String[] ss = s.split("[:;]");
for (String token : ss) {
System.out.println(token);
}
}
A:
You could use character class instead:
String[] ss = s.split("[:;]");
| {
"pile_set_name": "StackExchange"
} |
Q:
How to bulk delete by keys with python and appengine?
Is the next solution will work good in case of 10000+ items ?
q = db.GqlQuery('SELECT __key__ FROM Event where date_create < [DATE(2012, 1, 23)]')
db.delete(q)
What is the right solution to bulk delete ?
A:
As shown in the implementation, the datastore module will batch multiple delete RPCs if the number of keys is > MAX_DELETE_KEYS (500).
You should do this in a task queue as it might take more than 60s, and will trigger a DeadlineExceededException.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to describe meaning of R squared?
What is the correct interpretation of R squared? How do you typically write the results? Could I say something like
Age explained 30% of variation of the car condition index.
Please help :)
A:
As @MattReichenbach said, if you have Age is the only predictor in your model, then your wording is fine. However, in order to avoid specifying a particular variable, I would suggest the following wording: "the model explains 30% of variation of the car condition index" (also note the use of present tense, which to me sounds more natural and correct). Using "the model" will allow you easier modification of results reporting (more flexibility) in the future, for example, in case, if/when you will add more predictors to the model.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.