text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
No 'Access-Control-Allow-Origin' header is present - Food2Fork API call with AJAX
My group and I are starting our first project, and ten minutes into API testing, I hit a wall and have been unable to create a successful access control header. Can anyone help me work through this error?
var userSearch = "chicken"
function apiCall() {
var queryURL = "http://food2fork.com/api/search?key=3a4f22fb3ddd09f03521f9daf18117a1&q=" + userSearch; //+ "&sort=r"
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response) {
console.log(response);
});
};
apiCall();
"Failed to load http://food2fork.com/api/search?key=3a4f22fb3ddd09f03521f9daf18117a1&q=chicken: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
CORS means you can't access the remote site through a browser directly - proxies are your salvation
https://stackoverflow.com/a/46774307/7427111
You need to use a reverse proxy to defeat CORS in browser. You can use a tool like this: CORS Proxy
| common-pile/stackexchange_filtered |
DialogFlow - Returning a long response from the webhook via paged results
I have a custom DialogFlow that on fulfilment, processes the user input and extracts a search keyword. DialogFlow then sends the search keyword to my Webhook.
My Webhook looks up the search keyword in a database that I have, and returns the result back.
Now, this mostly works great as long as the results are short. The user searches, and the results are returned back and is read by Google Assistant.
But when the results are long and exceed a certain character count, the search results get cut and are followed by ellipses. This is very shortly followed by a "Google Assistant Not Responding" error message. It might be worth noting that Google Assistant doesn't even manage to begin to read the text. It just crashes.
Now, what I want to happen is for the long results to be displayed. Something similar to when you ask Google Assistant to look up movies:
Or maybe even a paged result that a user can scroll through.
If you have an output that you see today that you want to replicate, my attack would be to try and determine what is being sent by Actions on Google that causes the desired output today. Looking at your example, it feels like some kind of carousel of cards that have titles, a link and some text.
Are you asking about this for the Google Assistant specifically, or for other Dialogflow integrations as well?
@Prisoner I'm asking this about the DialogFlow integrations. How do I implement something similar to my DialogFlow
Each Dialogflow integration (Facebook, Slack, Actions on Google, etc) has different features, capabilities, and limits. There is no one solution that will work for all of them.
If you are giving a long answer, however, keep in mind that some of the formats aren't well suited for long answers and this can create a poor UX. Spoken answers on the Assistant, for example, should be kept short.
If you are looking for a reply along the lines of what you illustrate, you can use something like multiple cards to represent the various replies. Some platforms, such as Facebook, will support this. If you're developing for the Assistant, Actions on Google supports a Carousel/List visual selector.
Actually I was about to edit the question. I've made my webhook return fulfillmentMessages and Cards. When I try it on DialogFlow, it works, but it crashes on Actions on Google and when I test on my device. I'll check out the Carousel/List visual selector and figure out how to make my Python Webhook return that. Thank you!
If you do have problems doing so, ask another question and show the code that you're using.
| common-pile/stackexchange_filtered |
Difference between two datetime with Excel formula
I have 4 columns : Date1, Time1, Date2, Time2.
My objective is to know the time difference between two datetime in format hh:mm:ss.
Some examples :
Date1 | Time1 | Date2 | Time2 | ExpectedResult
12/11/2019 | 12:00:00 | 16/11/2019 | 15:00:00 | 99:00:00
10/11/2019 | 11:10:00 | 10/11/2019 | 12:09:15 | 00:59:15
...
With VBA there is no problem. However, is it possible to do it wihtout VBA but with a formula? Thank you.
Format
Date1 and Date2 have the format : *14/03/2012
Time1, Time2 and ExpectedResult have the format : hh:mm:ss
Already tried
=(Date2+Time2)-(Date1+Time1)
But the result is 03:00:00. Days are not present.
Are you sure that you have correct formats?
I updated my question with formats used.
This seems like a formatting issue. When I try the formula you gave, I get 4.13 (days) then I simply multiply it with 24 and get 99.
https://support.office.com/en-us/article/add-or-subtract-time-16aa6697-6d6e-49c1-8e2c-3398a7cad6ad
As mentioned here, use a custom format<EMAIL_ADDRESS>In your case you want [hh]:mm:ss;@
| common-pile/stackexchange_filtered |
Wildfly 10 Clustering does not work when a project's new release deployed with Infinispan Cache
I have a cluster environment on AWS with Wildfly 10. It consists of two nodes. When 2 exactly same war in two nodes, environment works perfect. But when some changes happens on a project I want to shutdown one of the nodes and try to deploy new version. After that I want to change the other node content. But I get the following error;
15:37:51,190 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 72) MSC000001: Failed to start service jboss.infinispan.aero.default: org.jboss.msc.service.StartException in service jboss.infinispan.aero.default: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
at org.wildfly.clustering.service.AsynchronousServiceBuilder$1.run(AsynchronousServiceBuilder.java:107)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
at org.infinispan.commons.util.ReflectionUtil.invokeAccessibly(ReflectionUtil.java:172)
at org.infinispan.factories.AbstractComponentRegistry$PrioritizedMethod.invoke(AbstractComponentRegistry.java:870)
at org.infinispan.factories.AbstractComponentRegistry.invokeStartMethods(AbstractComponentRegistry.java:639)
at org.infinispan.factories.AbstractComponentRegistry.internalStart(AbstractComponentRegistry.java:628)
at org.infinispan.factories.AbstractComponentRegistry.start(AbstractComponentRegistry.java:531)
at org.infinispan.factories.ComponentRegistry.start(ComponentRegistry.java:222)
at org.infinispan.cache.impl.CacheImpl.start(CacheImpl.java:849)
at org.infinispan.manager.DefaultCacheManager.wireAndStartCache(DefaultCacheManager.java:621)
at org.infinispan.manager.DefaultCacheManager.createCache(DefaultCacheManager.java:572)
at org.infinispan.manager.DefaultCacheManager.getCache(DefaultCacheManager.java:440)
at org.jboss.as.clustering.infinispan.DefaultCacheContainer.lambda$getCache$6(DefaultCacheContainer.java:119)
at org.jboss.as.clustering.infinispan.DefaultCacheContainer.getCache(DefaultCacheContainer.java:120)
at org.jboss.as.clustering.infinispan.DefaultCacheContainer.getCache(DefaultCacheContainer.java:114)
at org.wildfly.clustering.infinispan.spi.service.CacheBuilder.start(CacheBuilder.java:80)
at org.wildfly.clustering.service.AsynchronousServiceBuilder$1.run(AsynchronousServiceBuilder.java:102)
... 4 more
Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache default on node1
at org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete(StateTransferManagerImpl.java:224)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.infinispan.commons.util.ReflectionUtil.invokeAccessibly(ReflectionUtil.java:168)
... 18 more
15:37:51,253 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "infinispan"),
("cache-container" => "aero"),
("replicated-cache" => "default")
]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.infinispan.aero.default" => "org.jboss.msc.service.StartException in service jboss.infinispan.aero.default: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache default on node1"}}
15:37:51,261 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "infinispan"),
("cache-container" => "aero"),
("replicated-cache" => "default"),
("component" => "backup-for")
]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.infinispan.aero.default" => "org.jboss.msc.service.StartException in service jboss.infinispan.aero.default: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache default on node1"}}
15:37:51,262 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "infinispan"),
("cache-container" => "aero"),
("replicated-cache" => "default"),
("component" => "backups")
]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.infinispan.aero.default" => "org.jboss.msc.service.StartException in service jboss.infinispan.aero.default: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache default on node1"}}
15:37:51,264 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "infinispan"),
("cache-container" => "aero"),
("replicated-cache" => "default"),
("component" => "eviction")
]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.infinispan.aero.default" => "org.jboss.msc.service.StartException in service jboss.infinispan.aero.default: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache default on node1"}}
15:37:51,268 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "infinispan"),
("cache-container" => "aero"),
("replicated-cache" => "default"),
("component" => "expiration")
]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.infinispan.aero.default" => "org.jboss.msc.service.StartException in service jboss.infinispan.aero.default: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache default on node1"}}
15:37:51,269 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "infinispan"),
("cache-container" => "aero"),
("replicated-cache" => "default"),
("component" => "locking")
]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.infinispan.aero.default" => "org.jboss.msc.service.StartException in service jboss.infinispan.aero.default: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache default on node1"}}
15:37:51,270 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "infinispan"),
("cache-container" => "aero"),
("replicated-cache" => "default"),
("component" => "partition-handling")
]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.infinispan.aero.default" => "org.jboss.msc.service.StartException in service jboss.infinispan.aero.default: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache default on node1"}}
15:37:51,270 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "infinispan"),
("cache-container" => "aero"),
("replicated-cache" => "default"),
("component" => "state-transfer")
]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.infinispan.aero.default" => "org.jboss.msc.service.StartException in service jboss.infinispan.aero.default: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache default on node1"}}
15:37:51,271 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "infinispan"),
("cache-container" => "aero"),
("replicated-cache" => "default"),
("store" => "none")
]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.infinispan.aero.default" => "org.jboss.msc.service.StartException in service jboss.infinispan.aero.default: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Unable to invoke method public void org.infinispan.statetransfer.StateTransferManagerImpl.waitForInitialStateTransferToComplete() throws java.lang.Exception on object of type StateTransferManagerImpl
Caused by: org.infinispan.commons.CacheException: Initial state transfer timed out for cache default on node1"}}
My infinispan cache definition on standalone-ha.xml is;
<subsystem xmlns="urn:jboss:domain:infinispan:4.0">
<cache-container name="aero" default-cache="default">
<transport lock-timeout="60000"/>
<replicated-cache name="default" mode="SYNC">
<transaction mode="BATCH"/>
</replicated-cache>
</cache-container>
...
And my cache definition on Java is;
public class ApplicationCache {
@Resource(lookup = "java:jboss/infinispan/cache/aero/default")
private Cache<String, String> cache;
.....
}
What is my problem and how can I fix it?
Thanks for any help.
EDIT My jgroups configuration;
<subsystem xmlns="urn:jboss:domain:jgroups:4.0">
<channels default="ee">
<channel name="ee" stack="s3ping"/>
<channels>
<stacks>
<stack name="s3ping">
<transport type="TCP" socket-binding="jgroups-tcp" diagnostics-socket-binding="jgroups-diagnostics"/>
<protocol type="S3_PING">
<property name="access_key">
<%= @s3_access_key %>
</property>
<property name="secret_access_key">
<%= @s3_secret_access_key %>
</property>
<property name="prefix">
<%= @s3_bucket %>
</property>
<property name="timeout">
60000
</property>
</protocol>
<protocol type="MERGE2"/>
<protocol type="FD_SOCK" socket-binding="jgroups-tcp-fd"/>
<protocol type="FD"/>
<protocol type="VERIFY_SUSPECT"/>
<protocol type="BARRIER"/>
<protocol type="pbcast.NAKACK"/>
<protocol type="UNICAST2"/>
<protocol type="pbcast.STABLE"/>
<protocol type="pbcast.GMS"/>
<protocol type="UFC"/>
<protocol type="MFC"/>
<protocol type="FRAG2"/>
</stack>
</stacks>
</subsystem>
EDIT 2 Other nodes stack trace;
I had to add this as image because SO limits me about chracter size.
Could you please post your JGroups configuration? My lucky guess is that you use a discovery protocol (like TCPPING) with static list of nodes whereas you should use some dynamic discovery protocol (like MPING).
I am using s3ping. A shared the necessary part.
What does the logs from the other node show?
I have added other node's stack trace
Does your web application include new classes which are serialized within the session? To me it seems that the cache i can't be synchronized if you start the changed node. Maybe there is a class you removed in the session or the new war create a new session with classes which are not provided by the old one. Interesting might be if you check whether the same procedure works everytime correct with to identical war's (not sure whether you test that several times with existing sessions). Also you can show what the changes of the war are (or reduce it for a test)
there is no change in classes stored in caches. I am sure about it. Also, if wars become identical, it works without any problem. I also tried that I remove my cache and deploy two different version of an application. At this situation session replication does not work also.
WildFly creates a module for every deployment. In order for the new version of your application to be considered the same module as the previous version, you need to ensure that the runtime name of the deployment does not include a version number - as this is used to generate the module name for the deployment.
There are 2 ways to do this:
1. Just remove the version from your archive name - this will allow you to use the file scanner based deployment without issue.
2. Deploy your application via the console/CLI, and specify a consistent runtime name. See: https://docs.jboss.org/author/display/WFLY10/Application+deployment
Care must be taken to preserve serialized form of your cached objects between deployment versions. If serialized form cannot be preserved, you should create an isolated cluster to use with the new deployment version such that the data in the distributed cache stays segregated.
I tried first way before and it did not work. I will try second way. I hope it helps
I wonder what is the difference of way 2 from running standalone.sh.
| common-pile/stackexchange_filtered |
Set hours in 00:00:00 in react-datepicker
How set from Thu Sep 24 2020 14:59:41 GMT+0300 (Eastern European Summer Time) on Thu Sep 24 2020 00:00:00 GMT+0300 (Eastern European Summer Time) ?
A date picker shouldn't generate a time component in the first place. Where did 14:59 come from?
For initial date i use new Date().
new Date(new Date().setHours(0,0,0,0)) - good work.
Thank you, its working as expected.
| common-pile/stackexchange_filtered |
DateTime<Utc> compiles but not DateTime<Local> querying a table with a column defined as timestamp with time zone
I have a postgresql-table with a column defined as timestamp with time zone. The table is mapped to this struct:
#[derive(Serialize, Queryable)]
pub struct Location {
pub publication_time: DateTime<Utc>,
pub id: i32,
pub name: String,
pub latitude: BigDecimal,
pub longitude: BigDecimal,
}
The schema have this definition:
table! {
locations {
publication_time -> Timestamptz,
id -> Integer,
name -> Text,
latitude -> Numeric,
longitude -> Numeric,
}
}
(partial) Cargo.toml:
serde = "1.0.125"
serde_json = "1.0.64"
serde_derive = "1.0.125"
diesel = { version = "1.4.6", features = ["postgres", "r2d2", "chrono", "numeric"] }
bigdecimal = { version = "0.1.0", features = ["serde"] }
chrono = { version = "0.4.19", features = ["serde"] }
The function that queries the database:
fn get_all_locations(pool: web::Data<Pool>) -> Result<Vec<Location>, diesel::result::Error> {
let conn = pool.get().unwrap();
let items = locations.load::<Location>(&conn)?;
Ok(items)
}
This is then serialized to a JSON-array using serde_json. The DateTime in the database is 2021-04-08 15:02:02.514+02. When DateTime is Utc the program compiles fine, but the DateTime shown in UTC like 2021-04-08T13:02:02.514Z. I changed publication_time to DateTime<Local> to retain the time zone information but then cargo build fails with:
error[E0277]: the trait bound `DateTime<Local>: FromSql<diesel::sql_types::Timestamptz, Pg>` is not satisfied
--> src/controller.rs:21:27
|
21 | let items = locations.load::<Location>(&conn)?;
| ^^^^ the trait `FromSql<diesel::sql_types::Timestamptz, Pg>` is not implemented for `DateTime<Local>`
|
= help: the following implementations were found:
<DateTime<Utc> as FromSql<diesel::sql_types::Timestamptz, Pg>>
= note: required because of the requirements on the impl of `diesel::Queryable<diesel::sql_types::Timestamptz, Pg>` for `DateTime<Local>`
= note: 2 redundant requirements hidden
= note: required because of the requirements on the impl of `diesel::Queryable<(diesel::sql_types::Timestamptz, diesel::sql_types::Integer, diesel::sql_types::Text, diesel::sql_types::Numeric, diesel::sql_types::Numeric), Pg>` for `models::Location`
= note: required because of the requirements on the impl of `LoadQuery<_, models::Location>` for `locations::table`
I have another program that insert to this table and this works and the only difference is derive(Deserialize, Insertable).
#[derive(Deserialize, Insertable)]
pub struct Location {
pub publication_time: DateTime<Local>,
pub id: i32,
pub name: String,
pub latitude: BigDecimal,
pub longitude: BigDecimal,
}
if I recall correctly sql doesn't have a local timestamp, it's converted to utc everytime. How would postgresql retrieve this information ?
Mapping a Timestamptz field to a DateTime<Local> is not supported by diesel itself, as it only provides the corresponding impl for DateTime<Utc>.
You can work this around by using the #[diesel(deserialize_as = "…")] attribute on the corresponding field and providing your own deserialization wrapper:
#[derive(Serialize, Queryable)]
pub struct Location {
#[diesel(deserialize_as = "MyDateTimeWrapper")]
pub publication_time: DateTime<Local>,
pub id: i32,
pub name: String,
pub latitude: BigDecimal,
pub longitude: BigDecimal,
}
pub struct MyDatetimeWrapper(DateTime<Local>);
impl Into<DateTime<Local>> for MyDatetimeWrapper {
fn into(self) -> DateTime<Local> {
self.0
}
}
impl<DB, ST> Queryable<ST, DB> for MyDateTimeWrapper
where
DB: Backend,
DateTime<Utc>: Queryable<ST, DB>,
{
type Row = <DateTime<Utc> as Queryable<ST, DB>>::Row;
fn build(row: Self::Row) -> Self {
Self(<DateTime<Utc> as Queryable<ST, DB>>::build(row).with_timezone(&Local))
}
}
Thank you for your suggestion. I implemented it but get the error "error[E0599]: no method named with_timezone found for associated type <DateTime<Utc> as diesel::Queryable<ST, DB>>::Row in the current scope
--> src/models.rs:43:18
|
43 | Self(row.with_timezone(Local))
| ^^^^^^^^^^^^^ method not found in <DateTime<Utc> as diesel::Queryable<ST, DB>>::Row
@kometen I've fixed the code by added the missing conversion.
Thank you. :-) That was a delight.
| common-pile/stackexchange_filtered |
Search_tweets() (rtweet package) does not return all expected columns
I'm using the rtweet package and it's not returning the database with all columns with the search_tweets() function. The database has only 35 columns and no columns "screen_name" and "mentions_screen_name". Please how to get the rest of the columns? Below an example the columns returned.
tweets.df <- search_tweets("science")
names(tweets.df)
[1] "created_at" "id"
[3] "id_str" "full_text"
[5] "truncated" "display_text_range"
[7] "entities" "metadata"
[9] "source" "in_reply_to_status_id"
[11] "in_reply_to_status_id_str" "in_reply_to_user_id"
[13] "in_reply_to_user_id_str" "in_reply_to_screen_name"
[15] "geo" "coordinates"
[17] "place" "contributors"
[19] "is_quote_status" "retweet_count"
[21] "favorite_count" "favorited"
[23] "retweeted" "possibly_sensitive"
[25] "lang" "retweeted_status"
[27] "quoted_status_id" "quoted_status_id_str"
[29] "quoted_status" "text"
[31] "favorited_by" "display_text_width"
[33] "quoted_status_permalink" "query"
[35] "possibly_sensitive_appealable"
You seem to have installed the development version of rtweet 0.7.0 < rtweet > 1.0.0 which is not released yet on CRAN. Could you post the packageVersion("rtweet") output?
The devel version of rtweet returns only the columns returned by the API but the user information is retrieval via users_data(tweets.df). There you will find the id and screen name of the user who posted the tweets.
The previous mentions_screen_name is the in_reply_to_screen_name column.
Please make sure that you read the documentation of the version you are using
Get users data of the tweets using users_data method
tweets <- search_tweets("science", n = 100)
users <- users_data(tweets)
# get screen names of users
users["screen_name"]
| common-pile/stackexchange_filtered |
jquery not serving partial correctly
This should be an easy question for anyone who has served a rails partial via jquery.
This line of code:
$('div#status-chg-form').html('<%= escape_javascript(render(:partial => statusform)) %>').dialog('open');
is part of a script to serve a partial in a modal dialog. When the dialog pops up I get only a literal string inside that reads:
<%= escape_javascript(render(:partial => statusform, :remote => true)) %>
This is rails 3.1.
(edited to add:)
$(rails_partial = "<%= escape_javascript(render(:partial => statusform)) %>");
$('div#status-chg-form').append(rails_partial).dialog('open');
I have also tried the above to pass the html as a string, thinking there was some problem with the way jquery was processing this. Still doesn't work.
Is this code inside a .erb file?
Yes, the partial is an .erb file
I tried removing the .erb extension from the partial and I still get the same result.
Is the file which contains <%= (not the partial file referred by status form is a .erb file? what's the full filename of both of the partial and the file refer to the partial?
statusform isn't in quotes. Could this be the problem?
Is your erb code being processed as part of an ajax response? Or is it being loaded with the initial file load. See this railscast: http://railscasts.com/episodes/136-jquery
shigeya - the partial name is _statusform.html.erb. The link calling this jquery dialog script is index.html.erb.
kyle - tried putting quotes around statusform. same result.
checking out the railscast now
Ok in reviewing the railscast I think the answer to a previous question regarding the file names, the .js code is in a .js file not a .js.erb file.
So in summary, the link is located in index.html.erb, which calls a dialog function script in a file named work_orders.js which in turn is supposed to be serving _statusform.html.erb inside the dialog.
I'm still reviewing this railscast episode and trying to get my brain around this. The railscast is 4 years old and I started out on rails 3.1 which is part of my challenge with this.
It looks as if your code is not being processed as erb prior to be sent out to the client.
I'd recommend reviewing this Railscast:
"Railscast 136 - JQuery"
It will walk you through exactly how to do what you're having an issue with.
Thanks I'm checking this out now.
| common-pile/stackexchange_filtered |
How can I use extended bootstrap 5 colors on Angular?
I'm using Bootstrap 5 on an Angular 12 project (with scss), and I can't find a way to use the new extended bootstrap 5 color pallete (like indigo-300 or pink-200 etc.) I don't know if I need to import them somehow or how can I do that on Angular.
After asking and check, I arraived to two conclusions:
If you only want to use these colors in a class simple use the variable
.custom
{
color:$indigo-300;
}
But if you want to use as primary color, e.g. your styles.scss should be like
//see it's necesary import both scss/functions and scss/variables
@import "../node_modules/bootstrap/scss/functions";
@import "../node_modules/bootstrap/scss/variables";
$primary: $pink-600;
$secondary: $yellow-300;
$success: $green;
$info: $cyan;
$warning: $yellow;
$danger: $red;
$light: $gray-100;
$dark: $gray-900;
//futhermore it's necesary override the $theme-colors
$theme-colors: (
"primary": $primary,
"secondary": $secondary,
"success": $success,
"info": $info,
"warning": $warning,
"danger": $danger,
"light": $light,
"dark": $dark
);
@import '../node_modules/bootstrap/scss/bootstrap.scss';
Thank you very much, it turns out I was importing bootstrap's functions and variables the wrong way
Hi, I tried your snippet, it works for the colors, but in some way, the structure of the grid of the page is broken. It is strange, because only that page has problem and I am actually touching only the colors.
| common-pile/stackexchange_filtered |
How to make modal warning on blogger?
I want put modal on blogger when my website is open (on homepage), the warning I want is something similar like this.
You might need to use a javascript plugin like SweetAlert
| common-pile/stackexchange_filtered |
EventListener for a fresh app startup after being fully shut down
What are the Ti.App.addEventListener for when a app start up from being totally shut down(iPhone: Double click on home button and removed from apps running in background mode). I need a listener for this new/fresh start up of The app. ‘resume’ don’t work in this case. Hope someone knows.
I ask for a eventListener that detects that the app has been shut down from running in background mode ala:
Ti.App.addEventListener('resume', function(e)
all do 'resume' is not the right one in this case. Resume and pause don´t do the job.
You can simply fire your app start up function directly from app.js. This will only get evaluated during app start and not during app resume.
| common-pile/stackexchange_filtered |
LOB Windows store App Quality and Crash Reports
I am working with LOB windows store app, which will not go to the store, it will be used by the company employees. My Question, Is there any way to report when the app crash? , something like the app dashboard when the app is published to the store.
Thanks for help.
You can use 3rd party library to get log about crash and exception. I have used MarkedUp. Another way is to create own web service which sends crash log to some database.
| common-pile/stackexchange_filtered |
How to change format of current paragraph without using Selection
I have the code below without using Selection.
Sub Format paragraph()
Dim wdDoc As Document
With wdDoc.Range.Find
.Font.Size = 12
.Text = "?"
.Execute
End With
End Sub
When the character with font size = 12 is found, how can I change the format of the current paragraph? for example:
wdDoc.Paragraph(current).Font.Size = 14
wdDoc.Paragraph(current).Font.Color = wdBlue
Thanks for any help.
The trick is to work with a specific Range object, which can be used to access its "parent" paragraph. When Find.Execute is successful, the Range being searched contains the found item (same as the selection jumps to the found item). For example:
Sub Format paragraph()
Dim rng as Range, para as Paragraph
Dim wdDoc As Document
Set wdDoc = ActiveDocument. 'Missing in code in question...
Set rng = wdDoc.Content 'Content returns the Range
With rng.Find
.Font.Size = 12
.Text = "?"
If .Execute = True Then
Set para = rng.Paragraphs(1)
para.Font.Size = 14
para.Font.Color = wdBlue
End If
End With
End Sub
@Cindy_Meister Hi Cindy. Thanks for your answer. That seems to be what I need. There are several paragraphs, some with font size 12 and others with other fonts. So, how to include your With rng.find block in a while loop? Or should I count first the paragraphs that match the style I want and then do a for loop to apply the same changes to the other paragraphs?
@GerCas a loop is the usual way. There are lots of examples for using that with Find here and elsewhere. For example https://stackoverflow.com/a/52596708/3077495 Rather than applying manual formatting you might consider applying a paragraph STYLE that defines the required formatting. That's just one step and, if the formatting needs to change again at a later point, simply changing the style definition is one-step in the UI - no macro required.
@Cindy_Meister Hi Cindy. Thanks fot you suggestions and link shared.
| common-pile/stackexchange_filtered |
What is your first TDD test when building a robust file importer?
I've read a lot lately about TDD, but I've only seen small examples.
Now I have to start with a (not large, but more than just a single class) file importer which has to be robust, so it has to check whether the file is present (on the FTP server), if it isn't reschedule itself, don't crash when the file is corrupted, is re-runnable etc.: a importer that can be started and hasn't to be checked for the log files every day.
So when starting to build such a program, where do i start with TDD?
Is it at the lowest level, like implementing the GetFile() or the Reschedule() and then working my way up, or do I create the 'Controller' first and let that one fail first because I did not set any test file and the drill down in all the functionalities?
I guess I would start with what I was trying to accomplish. So, for example, if I were writing some sort of personal finance software I would start with something like:
@Test
public void importsTransactionsFromQuicken() {
List transactions = new QuickenImporter().importFrom("filename.qfx");
assertSomeStuffAbout(transactions);
}
Now, once you have that working, you could refactor and mock out the file handling to avoid some I/O. This will probably drive out an abstraction for reading the file.
Next, start looking for some other scenarios. For example, you give corrupt files as an example. Well, what should happen in the event of a corrupt file?
@Test
public void logsAndRemovesCorruptFiles() {
File cf = new CorruptFile();
Logger ls = new LogSpy();
// Note, this might be the refactored interface for after mocking out I/O
QuickenImporter qi = new QuickenImporter(cf, ls);
List transactions = qi.import();
assertEmptyList(transactions);
assertFileWasDeleted(cf);
assertCorruptLogEntryWasWritten(ls);
}
You can see I did some refactoring, including some constructor injection, etc. but the tests really drove out the next step. As far as the "Reschedule" function, well it seems to violate the Single Responsibility Principle so it may belong in another class, for instance in an ImportScheduler class. If that's the case I know what I want the importer behavior to be when it can't find the file, so I'll make another test:
@Test
public void doesntReturnAnyTransactionsWhenFileNotPresent() {
QuickenImporter qi = new QuickenImporter(new NonExistentFile(), NULL_LOGGER);
List transactions = qi.import();
assertEmptyList(transactions);
}
Now, in order to test the scheduling component I can write an ImportSchedulerTest with test cases for both conditions (when I have a file and when I do not).
Hope that helps!
i like this. Especialy the way to work: start with a hardcoded filename, and then add some dependencies when the more complex import asks for it. I've to check out the mocking, i've expiremented a very little with it yet. Till now i tend to create large integration tests and not unit tests, in which i use a real ftp server (hard to test the 'server not available' scenario) and real files (does work for the situation to test non existing files, corrupt files etc.)
How then would you mock the FTP server? is that a fake ftp class that returns a bytearray when you ask for a file? Is that then also called a mock? And would you then also insert that in the quickenimporters' constructor as a dependency?
Something like that (having not done this type of FTP integration before I'm not sure). When you're just getting started don't bother with mocking frameworks, just write a dummy class (within the test) that contains the mocked behavior. For purposes of this discussion, just use the word Fake don't get caught up on the semantics of Mocks, stubs, spies, etc.
Since the main focus of a file importer is to import a file (yes?) that ought to be your first port of call. Write a test to ensure that you are able to retrieve a file.
Personally, I would sketch out what you want to implement using UML before getting down to coding. It will help you identify what you need to write.
Well - start at the start. The first nicely testable bit of functionality is "it has to check whether the file is present on the FTP server". I can think of at least two test cases for that: the file is present, and the file isn't present. That's two tests. What about the server isn't present? What' supposed to happen then? Well, test that, too. As you describe what your unit is supposed to do, in English as you've done in the question, translate the description into tests.
There's no bit of functionality you don't want to work, is there? Then test all of it. The order in which you write the tests doesn't (much) matter - in the end you will want every bit tested (and if you're really following TDD, every bit will have been tested before that bit was even written).
allright, thanks. I made the assumption (i think from the examples i've read) that the order had to be a sort of expanding level, so a bottom-up or top-down way of working.
| common-pile/stackexchange_filtered |
Trouble installing Visual Studio 2013 Express for Windows (error with vcredist?)
update: the same issue is happening with the visual c++ redistributables
I'm having trouble installing Visual Studio 2013 for Windows (the version for developing apps). I'm trying to install this on the Surface Pro 2 256GB edition running an up to date windows 8.1.
I'm getting an error with the "Microsoft Visual C++ 2013 x86 Minimum Runtime - 12.0.21005"
"The Temp folder is on a drive that is full or inaccessible. Free up space on the drive or verify that you have write permission on the Temp folder."
A screenshot of the issue:
I tried searching google but I wasn't able to find anyone else with the same problem (this error coming up on Visual Studio 2013). The suggestions I saw were to verify the hash of the iso to verify that it was correct, check that I have the proper write permissions to the temp folder, and to disable/enable user account control (UAC).
The sha1 of the iso I downloaded matched the hash listed on the download website. I also tried using the web installer and ran into the same issue.
The SYSTEM entry, my user account, and the ADMINISTRATORS entry all had full permissions on the %Temp% folder (which leads to C:\Users\\AppData\Local\Temp).
User account control was enabled when I tried to install (it was on the second from the top entry, so from levels 0-3 it was on 2). I tried the install when this was disabled and when it was enabled (I also tried restarting between these changes).
Nothing so far has worked. I'd really appreciate some help in the issue. I'm pretty lost on where to go from here.
The log file throws its first and last errors here:
[0B94:0B50][2013-12-09T12:24:44]e000: Error 0x80070660: Failed to install MSI package.
[0B94:0B50][2013-12-09T12:24:44]e000: Error 0x80070660: Failed to execute MSI package.
[1768:176C][2013-12-09T12:24:44]e000: Error 0x80070660: Failed to configure per-machine MSI package.
[1768:176C][2013-12-09T12:24:44]i000: MUX: Installation size in bytes for package: vcRuntimeMinimum_x86 MaxAppDrive: 0 MaxSysDrive: 534206 AppDrive: 0 SysDrive: 534206
[1768:176C][2013-12-09T12:24:44]i000: MUX: Return Code:0x80070660 Msi Messages:0 Result Detail:0 Restart:None
[1768:176C][2013-12-09T12:24:44]i000: MUX: Set Result: Return Code=-2147023264 (0x80070660), Error Message=, Result Detail=, Vital=True, Package Action=Install, Package Id=vcRuntimeMinimum_x86
[1768:176C][2013-12-09T12:24:44]i319: Applied execute package: vcRuntimeMinimum_x86, result: 0x80070660, restart: None
[1768:176C][2013-12-09T12:24:44]e000: Error 0x80070660: Failed to execute MSI package.
[0B94:0B50][2013-12-09T12:24:44]i318: Skipped rollback of package: vcRuntimeMinimum_x86, action: Uninstall, already: Absent
[1768:176C][2013-12-09T12:24:44]i000: MUX: Installation size in bytes for package: vcRuntimeMinimum_x86 MaxAppDrive: 0 MaxSysDrive: 0 AppDrive: 0 SysDrive: 0
[1768:176C][2013-12-09T12:24:44]i000: MUX: Return Code:0x0 Msi Messages:0 Result Detail:0 Restart:None
[1768:176C][2013-12-09T12:24:44]i000: MUX: Reset execution Result
[1768:176C][2013-12-09T12:24:44]i000: MUX: Reset Result
[1768:176C][2013-12-09T12:24:44]i319: Applied rollback package: vcRuntimeMinimum_x86, result: 0x0, restart: None
[0B94:0B50][2013-12-09T12:24:44]i351: Removing cached package: vcRuntimeMinimum_x86, from path: C:\ProgramData\Package Cache\{13A4EE12-23EA-3371-91EE-EFB36DDFFF3E}v12.0.21005\
[0B94:1388][2013-12-09T12:24:44]i304: Verified existing payload: cab45B5F4C0549AFC5572730914330147F5 at path: C:\ProgramData\Package Cache\{5411060C-8F8C-393D-8D3B-26AF2C92FABB}v12.0.21005\packages\vs_minshellcore\cab1.cab.
[1768:0AE0][2013-12-09T12:24:44]e000: Error 0x80070642: BA aborted verify of payload: cab45B5F4C0549AFC5572730914330147F5
[1768:0AE0][2013-12-09T12:24:44]e314: Failed to cache payload: cab45B5F4C0549AFC5572730914330147F5 from working path: C:\Users\Paarth\AppData\Local\Temp\{78095723-ced1-49b3-b0ac-8598452ef0ec}\cab45B5F4C0549AFC5572730914330147F5, error: 0x80070642.
[0B94:1388][2013-12-09T12:24:44]i351: Removing cached package: vcRuntimeMinimum_x86, from path: C:\ProgramData\Package Cache\{13A4EE12-23EA-3371-91EE-EFB36DDFFF3E}v12.0.21005\
[0B94:1388][2013-12-09T12:24:44]w353: Unable to remove cached package: vcRuntimeMinimum_x86, from path: C:\ProgramData\Package Cache\{13A4EE12-23EA-3371-91EE-EFB36DDFFF3E}v12.0.21005\, reason: 0x80070003. Continuing...
[0B94:1388][2013-12-09T12:24:44]i351: Removing cached package: Preparation_Uninstall, from path: C:\ProgramData\Package Cache\556D811C-F676-3675-83D7-C534B57A1C15\
[0B94:1388][2013-12-09T12:24:44]i351: Removing cached package: vs_preclean_winexpress, from path: C:\ProgramData\Package Cache\A2105C10829819F72E3A96DBFE7D9CA0972151F1\
[1768:176C][2013-12-09T12:24:44]i000: MUX: Apply Complete: Disk Space Used in bytes for Installation: MaxAppDrive: 0 MaxSysDrive: 1527808 AppDrive: 0 SysDrive: 1159168
[1768:176C][2013-12-09T12:24:44]i000: MUX: Free Disk Space after install: SystemDrive C:\<PHONE_NUMBER>92 bytes AppDrive C:\<PHONE_NUMBER>92 bytes
[1768:176C][2013-12-09T12:24:44]i000: MUX: Go to Finished page.
[1768:176C][2013-12-09T12:24:44]i399: Apply complete, result: 0x80070660, restart: None, ba requested restart: No
have you moved the folder C:\Windows\Temp?
@magicandre1981 No, I haven't. One of the other recommendations I saw was to clear my local temp directory. Was I supposed to clear C:\Windows\Temp as well?
ask this Microsoft and provide them the log files: http://social.msdn.microsoft.com/Forums/en-US/vssetup
I came upon this question while looking to solve the same problem. I figured it out! Make sure your C:\Windows\Installer folder is accessible. I'm not sure why it's complaining about Temp, but there we go.
My C:\Windows\Installer folder wasn't a folder at all, but a shortcut to a location that no longer existed. Making it a folder fixed the issue for me.
Thanks for the answer! In my case with Visual Studio 2017 installer, I got the same error message and I didn't even have any C:\Windows\Installer. I just created the folder and the installer works.
| common-pile/stackexchange_filtered |
Nested Interval Theorem: Another part
Let [a1, b1] ⊇ [a2, b2] ⊇ · · · be a sequence of intervals. If lim(bi − ai) → 0, then ∩[an, bn] is a singleton set.
I have proved the first part which says that the infinite intersection of such subsets is not empty and is a closed interval. But how do I prove this part? I tried solving it by assuming that the intersection contains two unequal numbers x and y. And then by generating real numbers between them I was trying to reach some kind of contradiction but was not able to proceed.
Can someone help me with this proof?
Assume two different points x and y. Both of them are of the form $a(n)<X<b(n) , a(n)<y<b(n)$. So $0<|x-y|<|a(n)-b(n)|< €$. Difference of two constant number is less than any positive number €>0. Deduce that $X=y$
Conclude the sequences $a_n$ and $b_n$ are increasing and decreasing, respectively.
Since $[a_n, b_n]$ is a closed interval, $a_n \leq b_n$. So conclude that $a_n$ and $b_n$ are bounded above and below, respectively.
By the Monotone Convergence Theorem, they converge. That is, $a_n \rightarrow a$ and $b_n \rightarrow b$.
Then $\bigcap_n [a_n, b_n]=[a,b]$
But since $b_n - a_n \rightarrow 0$, by the algebra of limits, we have that $a=b$.
Therefore, $[a,b]=\{ x\}$ for some $x \in \mathbb{R}$. We can also conclude that $x$ is unique.
If you have proved that the intersection is a closed interval, then if you assume there exist $x$ and $y$ distinct in the intersection you have the whole interval $[x, y] $ in it as well. This is impossible since it has positive measure.
| common-pile/stackexchange_filtered |
Maven package error
I am working on a project which requires a geotools dependency. Before I was getting the following error:
Exception in thread "main" java.lang.IllegalStateException: cannot initilize transformation: Authority "EPSG" is unknown or doesn't match the supplied hints. Maybe it is defined in an unreachable JAR file?
at com.test.geometricutils.TransformProjection.initializeTransformer(TransformProjection.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.spark.deploy.JavaMainApplication.start(SparkApplication.scala:52)
at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:879)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:197)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:227)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:136)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: org.opengis.referencing.NoSuchAuthorityCodeException: Authority "EPSG" is unknown or doesn't match the supplied hints. Maybe it is defined in an unreachable JAR file?
at org.geotools.referencing.factory.ManyAuthoritiesFactory.noSuchAuthority(ManyAuthoritiesFactory.java:488)
at org.geotools.referencing.factory.ManyAuthoritiesFactory.getAuthorityFactory(ManyAuthoritiesFactory.java:466)
at org.geotools.referencing.factory.ManyAuthoritiesFactory.getCRSAuthorityFactory(ManyAuthoritiesFactory.java:547)
at org.geotools.referencing.factory.AuthorityFactoryAdapter.createCoordinateReferenceSystem(AuthorityFactoryAdapter.java:799)
at org.geotools.referencing.factory.ThreadedAuthorityFactory.createCoordinateReferenceSystem(ThreadedAuthorityFactory.java:730)
at org.geotools.referencing.DefaultAuthorityFactory.createCoordinateReferenceSystem(DefaultAuthorityFactory.java:179)
at org.geotools.referencing.CRS.decode(CRS.java:488)
at org.geotools.referencing.CRS.decode(CRS.java:416)
at
which was solved by the following dependency:
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.11.0</version>
</dependency>
And the project build successfully without any error. Now, I am trying to package my project into a jar using this command:
mvn assembly:assembly -DdescriptorId=jar-with-dependencies
But I am getting the same error message again. I don't know why it is running in intellij as a project, but not after running the package command.
Any help or hint would be appreciated.
have you try mvn clean before mvn assembly:assembly -DdescriptorId=jar-with-dependencies? And why are you using this particular goal instead of mvn package?
yes, I'm using mvn clean before this command. I want exectuable jar of scala project for spark-submit thats why I'm using this command.
First, you need one of the EPSG factories (rather than xerces) to fix your first issue - see the GeoTools FAQ for more detail.
Secondly, when assembling a fat (or uber) jar you need to pay special attention to the spi control files as described in the GeoTools FAQ.
You can check your geotools' version in maven repository. And you should ensure all geotools' version is suitable especially gt-epsg-hsql.
| common-pile/stackexchange_filtered |
How do I calculate two text boxes and display the answer in another?
I am trying to add the two text boxes and show the result in a third, whenever I try to add the third box, it makes it invalid. Any suggestions?
Here is my code!
<br>
<br>
<p4>Calculate Two Fields</p4>
<p4 id="answer"></p4>
<br>
<br>
Number 1<input type="text" id="num1" <br>
<br>
Number 2<input type="text" id="num2" <br>
<br>
<button onclick="calculate()">Calculate</button>
<script>
function calculate() {
var field1 = document.getElementById(num1).value;
var field2 = document.getElementById(num2).value;
var result = parseFloat(field1) + parseFloat(field2)
if (!isNaN(result))
{
document.getElementById("answer").innerHTML = "The answer is " + result;
}
</script>
getElementById('num1') here id should be in quote, otherwise it will be treated as variable.
Also you forgot the } at the end
function calculate() {
var field1 = document.getElementById('num1').value;
var field2 = document.getElementById('num2').value;
var result = parseFloat(field1) + parseFloat(field2);
if (!isNaN(result))
{
document.getElementById("answer").textContent= "The answer is " + result;
}
}
<br>
<br>
<p4>Calculate Two Fields</p4>
<p4 id="answer"></p4>
<br>
<br>
Number 1<input type="text" id="num1" <br>
<br>
Number 2<input type="text" id="num2" <br>
<br>
<button onclick="calculate()">Calculate</button>
Please don't use .innerHTML unless you are assigning HTML elements.. Instead use textContent..
What about if decimal number?
This worked!!! Thank you so much! I have been trying to figure it out for two day, thank you for helping me realize this!
I cant see any mistake except ; or } .
Its better to use onchange or other events events to remove clicking to get better ui/ux.
But you can do it with angularjs better.you can use ng-model for each input and in third input write {{model1+model2}}.
You can do it with vue.js too .the different is that you should use vmodel instead of ng-model.
Try.....
$("#second").keyup(function() {
var total = 0;
$('.smtab_tot').each(function(_i, e) {
var val = parseFloat(e.value);
if (!isNaN(val))
total += val;
});
$('#total').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
input 1 : <input type="number" class="smtab_tot" id="first">
<br>
input 2 : <input type="number" class="smtab_tot" id="second">
<br>
total : <input type="text" id="total">
There is no jquery involved in the question and tags as well..
This is called using Thor's hammer to kill an ant
| common-pile/stackexchange_filtered |
Why is Class not appearing in blue in Xcode?
I have a class called PlayingCard. I am trying to use it in a class called PlayingCardDeck.
I have imported PlayingCard.h in PlayingCardDeck.h
#import "PlayingCard.h"
@interface PlayingCardDeck : Deck
@end
When I try to call a class method in PlayingCardDeck.m it doesn't appear in blue. XCode does see the class in autocomplete but it is not in blue when selected. In this example, I am trying to call the init method.But, I get the error expected expression as if it XCode does not know what the PlayingCard class is. The error for the calls to card.rank = and card.suit= don't work either because I believe that PlayingCard is not being recognized. This doesn't make sense as I have defined the class and imported it into PlayCardDeck.h Can someone shed some insight? Thanks in advance.
#import <Foundation/Foundation.h>
#import "Deck.h"
#import "PlayingCard.h"
@interface PlayingCardDeck : Deck
@end
#import "PlayingCardDeck.h"
@implementation PlayingCardDeck
-(id) init
{
self = [super init];
if (self) {
for(NSString *suit in [PlayingCard validSuits])
for(NSUInteger rank =1; rank <= 10; rank++)
PlayingCard *card = [[PlayingCard alloc] init];
card.rank = rank;
card.suit = suit;
}
}
@end
@interface PlayingCard : Card
@property (strong, nonatomic) NSString* suit;
@property (nonatomic) NSUInteger rank;
+(NSArray *) validSuits;
//+(NSUInteger) maxRank;
@end
Which class method are you calling on PlayingCardDeck? Have you @synthesized the properties? Does it crash at runtime, or is it giving you compiler errors?
Your lack of { and } in those for loops give you trouble.
This code
if (self) {
for(NSString *suit in [PlayingCard validSuits])
for(NSUInteger rank =1; rank <= 10; rank++)
PlayingCard *card = [[PlayingCard alloc] init];
card.rank = rank;
card.suit = suit;
}
Actually mean this
if (self) {
for(NSString *suit in [PlayingCard validSuits]) {
for(NSUInteger rank =1; rank <= 10; rank++) {
PlayingCard *card = [[PlayingCard alloc] init];
}
}
card.rank = rank;
card.suit = suit;
}
Now you can clearly see that the card variable is out of scope.
You should add { and } to explicitly define the scope of the for loops like this
if (self) {
for(NSString *suit in [PlayingCard validSuits]) {
for(NSUInteger rank =1; rank <= 10; rank++) {
PlayingCard *card = [[PlayingCard alloc] init];
card.rank = rank;
card.suit = suit;
}
}
}
| common-pile/stackexchange_filtered |
Programmatically Labeling a Signal in Simulink
I'm attempting to write a script that generates a basic Simulink model and I'd like to know if there's a way to programmatically label a signal line. I've looked at the add_line function (which is what I'm using to add the lines), but I don't see an option for defining anything like a Name or Label property.
Is there a way to do this?
add_line returns a handle to the newly created line, so you could also write:
lineHandle = add_line('sys','oport','iport');
set_param(lineHandle, 'Name', 'yourSignalName');
| common-pile/stackexchange_filtered |
Grp and Ab are not equivalent as categories
I am trying to understand an example leading to the notion of adjoint.
Let $\mathbf{Grp}$ and $\textbf{Ab}$ denote the category of groups and abelian groups, respectively. Further, suppose that $U: \textbf{Ab} \to \textbf{Grp}$ denotes the forgetful functor and $F: \textbf{Grp} \to \textbf{Ab}$ be the abelization functor, i.e. for $G \in \text{Ob}(\textbf{Grp})$, we set $F(G) := G/G'$ with $G' = [G,G]$ being the commutator subgroup of G.
The claim is that (1) $F \circ U \cong \text{id}_{\textbf{Ab}}$, but (2) $U \circ F \not \cong \text{id}_{\textbf{Grp}}$.
Can you explain why (1) and (2) holds?
Is $U$ the inclusion functor? The forgetful functor takes us to the category of sets, right?
@JohnDouma : the inclusion is also a forgetful functor (it forgets that the group is abelian)
@MaximeRamzi If I include the integers in the category of groups it doesn't cease to be abelian.
@JohnDouma : I know. That's not the point - you can still forget that it was abelian and treat it as a group (which happens to be abelian). That's a forgetful functor which forgets a property - the forgetful functor to sets forgets structure, but forgetting a property is still forgetting something. See e.g. https://ncatlab.org/nlab/show/stuff%2C+structure%2C+property#examples
Let $A$ be abelian group. Apply $U$ to get $U(A)=A$. Now apply $F$ to get $FU(A) = A/A'$. Now, since $A$ is abelian, $A' = \{e\}$ is trivial. Thus, $FU(A)=A/A' \cong A$.
Now, choose $G$ nonabelian. Apply $F$ to get $F(G) = G/G'$. Now apply $U$ to get $UF(G) = G/G'$. Since $G$ was nonabelian, $G' \neq \{e\}$ and therefore $UF(G) = G/G' \not\cong G$.
Claim 1 holds, because for every group you can find a (natural) isomorphism between $FU(G)$ (the abelianization of $G$, that was already abelian and has just been regarded as a mere group, forgetting abelianity: the commutator subgroup $[G,G]$ is trivial if $G$ is abelian; actually, if and only if). If you're new to the concept of "natural isomorphism", this is a good first instance of how they work.
So, (somewhat sloppily, but this is the main idea) claim 2 holds by virtue of the fact that there exists at least one group that is not abelian. For example, the free group of two elements.
| common-pile/stackexchange_filtered |
Opening a new form using windows form c++
I'm a new programmer trying to have a multiple form.
I tried to open a new form using a button:
{
//This will open the ordering widow
NewOrder^ order = gcnew NewOrder;
order->Show();
//This one is to hide the current form
this->Hide();
}
but it gives me an error message says that:
\projects\cppwinform1\cppwinform1\MyForm.h(135): error C2227: left of '->Show' must point to class/struct/union/generic type
\projects\cppwinform1\cppwinform1\MyForm.h(135): note: type is 'unknown-type
where line 135 is order->Show();
Please if someone can help me fixing that, and just open my other form
thnx
Questions seeking debugging help ("why isn't this code working?") must include the desired behavior and the shortest code necessary to reproduce it in the question itself. Please read how to create a [MCVE].
Might you need to put brackets after gcnew's classname?
Is this an answer or a question/comment?
| common-pile/stackexchange_filtered |
Drag behavior not working right?
I'm trying to find the problem with the drag behavior setup that I have in my program, because it seems like the drag won't even activate. I'm using http://jsfiddle.net/da37B/317/ as the reference code for my program.
Here's the relevant code:
vis.selectAll(".nodes")
.data(nodes)
.enter().append("circle")
.attr("class", "nodes")
.attr("cx", function (d) {
return xRange(d.x);
})
.attr("cy", function (d) {
return yRange(d.y);
})
.attr("r", "10px")
.attr("fill", "black")
.attr("transform", "translate(" + p.x + "," + p.y + ")")
.call(drag); <------
// Define drag beavior
var drag = d3.behavior.drag()
.on("drag", dragmove);
function dragmove(d) {
var x = d3.event.x;
var y = d3.event.y;
d3.select(this).attr("transform", "translate(" + x + "," + y + ")");
}
And here's the full code: https://jsfiddle.net/4o5pch1q/1/
The jsfiddle doesn't seem to contain the code you have in the question?
The reason you don't see any effect is that you have an error in your jsfiddle. Please check the console for such obvious things in the future.
Once the obvious error is fixed (including moving the definition of drag up so that it's defined before it's being used), the only thing that remains is to tell D3 how to get the origin of the element being dragged (otherwise the circle "jumps" on drag):
var drag = d3.behavior.drag()
.origin(function(d) { return d; })
.on("drag", dragmove);
Complete demo here.
Thanks for the help. Is there any reason why the demo I was using didn't need the origin function?
There wasn't anything else on the page -- you usually need the origin function if the mouse position doesn't give you the coordinates within the SVG as well. In your case, the SVG is offset because of the other elements.
Ok, I understand. I've noticed a problem with the dragging where if you drag a dot somewhere, let go of it, and then try to drag it again, it will jump to the original coordinate before the second drag attempt. Is there any way to fix it?
Argh, forgot to update the data on drag. I've fixed that and updated the link in the answer, sorry about that.
Oh ok, that makes sense too. Thanks
| common-pile/stackexchange_filtered |
Phantom unreadable drives, hd0 through hd4, are causing errors
In Grub, in addition to hd5, which is my actual drive, there are hd0 through hd4. Trying to ls them says they have an unknown filesystem. When grub loads, it prints several pages of
error: failure reading sector 0x80 on hd0
error: failure reading sector 0x80 on hd1
etc. It also does this after selecting the OS.
This all started after I added another partition to my (btrfs-formatted) root drive, so maybe it has something to do with that.
What causes this, and how do I fix it?
Are you saying that you don't know the origins of hd0 through hd4?
@rickhg12hs Yes.
What does fdisk -l /dev/hd show?... Or whatever the device is
@rickhg12hs I'm not at that computer right now, but Linux doesn't see any additional drives (only grub does)
One possible cause of these phantom devices are from your BMC. Various BMCs, which provide IPMI and often a KVM function, will create virtual USB devices when you're using the KVM (also commonly called iKVM.)
While I don't know of a solution for Grub to ignore certain devices, here are a few workarounds:
Manually edit your grub entry at boot to use the correct hdX device for that boot only.
Disconnect iKVM sessions during boot.
I hope somebody comes along with a better answer for this! I've also seen hardware consoles with KVMs (like the Tripp-Lite B070-008-19-IP 8-port rack-mounted console with IP KVM) do this, so suspect anything that connects to the USB bus.
I am not using KVM. This is on a bare metal laptop.
| common-pile/stackexchange_filtered |
Observability inequality for the 1D transport equation
Let $(a,b) \subset (0,1)$. Consider the following transport equation
$$z_t+z_x=0, \ (t,x)\in(0,T)\times(0,1), \\z(t,0)=0, \ z(0,x)=z_0(x).$$
It is clear that the solution to the above equation is given by $z(t,x)=z_0(x-t),\ \text{if} \ x-t\in (0,1)$ and $0$ otherwise.
I want to prove the following observability inequality: There exists a positive constant $C$ such that
$$\int_0^T \int_a^b z_0^2(x-t)dxdt\geq C\int_0^1z_0^2(x)dx.$$
I know that this inequality is satisfied if and only if $T \geq 1-b$ and $a=0$ but I don't see how to prove it. Any ideas or references?.
Thank you.
We have $0\le a\le b\le1$ and $T\in(0,\infty)$. We want to know when there is a positive constant $C$ such that
$$\int_0^T dt\, \int_a^b dx\, u^2(x-t)\geq C\int_0^1 dx\,u^2(x) \tag{1}$$
for all measurable functions $u\colon\mathbb R\to\mathbb R$ such that $u(x)=0$ for $x\notin(a,b)$.
The answer is: never. Indeed, without loss of generality $a<b$. The left-hand side of (1) is
$$\int_0^T dt\, \int_a^b dx\, u^2(x-t) \\
=\int_{\mathbb R} ds\, u^2(s)\int_{\mathbb R} dt\,1\{s\in(0,1),t+s\in(a,b),t\in(0,T)\} \\
=
\int_0^1 ds\,u^2(s)w(s),$$
where
$$w(s):=\max[0,\min(T,b-s)-\max(0,a-s)].$$
Clearly, the weight function $w$ is continuous, so that $w(b-)=w(b)=0$.
Letting now $u:=1_{(b-h,b)}$ with $h\downarrow0$, we see that the left-hand side of (1) is $\int_{b-h}^b ds\,w(s)=o(h)$, whereas the right-hand side of (1) is $C\int_{b-h}^b ds=Ch$, so that (1) fails to hols for any real $C>0$.
Added in response to a comment by the OP: Note that
$$w(s)=\max[0,\min(T,b-a,b-s,T-a+s)]\ge\min(b-1,T-a)=:m$$
for all $a\in[0,1]$ and $s\in[0,1]$.
So, (1) will hold with $C=m$. If you now want $C$ to be $>0$, just require that $m$ be $>0$; that is, (in addition to the condition $a\in[0,1]$) require that $b>1$ and $T>a$.
Thank you Mr. Pinelis for this clarification. Does the inequality any chance to hold for some $T, a, b$ ?. Because in control theory, this is a classical result but I can not find it in any book. Thank you again sir.
@Gustave : As my answer shows, the inequality cannot hold for any $T,a,b$ satisfying your conditions $0\le a\le b\le1$ and $T\in(0,\infty)$. The most probable reason why you cannot find this "classical result" in any book is that you remember the result incorrectly. However, as now shown in the addition to my answer, your inequality will hold if $a\in[0,1]$,$b>1$, and $T>a$.
Thank you sir for the great answer. I'm very thankful for you.
| common-pile/stackexchange_filtered |
Unable to Install Tensorflow , tensorflow-base-1.12 error
I am trying to conda install tensorflow in an environment which I created.
The downloading and extracting of packages starts but one particular package named 'tensorflow-base-1.12' only gets 76% downloaded and "FileNotFoundError(2, 'No such file or directory')" this error is shown.
Below is the screenshot
Image Link
Can you rerun the install in verbose mode? conda install tensorflow -vv
What channel are you using? Does conda install -c conda-forge tensorflow also produce the error?
I received the same error today. I am running windows 10 and a relatively fresh install of conda. I also updated my base conda install.
Try creating a separate environment and then pip install it. It worked for me.
I had the same problem, and I found that the package directory path is too long.
Reinstall anaconda to shorter path (C:\Anaconda in my case), it will work well.
In my case, I had to create a separate environment and pip install it.
| common-pile/stackexchange_filtered |
Run-time Error 3075 in MS Access while appending email distribution to table via SQL
I have the following function defined in MS Access VBA:
Function SendToEMail(iTo As String, iFrom As String, icc As String, ibcc As String, iSubject As String, iBody As String, iSystem As String, iAttachments As String)
strSQL = "INSERT INTO tblEmail ([To], [From], [CC], [BCC], [Subject], [Body], [Create_Time], [System], [Attachments]) IN '\\ahmtroy03\Email.accdb' VALUES ('" & iTo & "', '" & iFrom & "', '" & icc & "', '" & ibcc & "', '" & iSubject & "', '" & iBody & "', #" & Now() & "#, '" & iSystem & "', '" & iAttachments & "');"
DoCmd.RunSQL strSQL
End Function
This function inserts records into a table. Each record is an email. When appending to this table, I get error 3075 and it references the [To] field. I've changed some info for privacy. All other distributions come through okay but THIS one doesn't make it.
<EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS>
VBA supports breaking a long line of code into multiple lines using a line continuation character sequence at the end of the line. That would be a space followed by an underscore. It would make your code much easier to read.
The Attachments field gets data? I would be surprised. If Attachments is an attachment type field, should not be able to enter objects into attachment field like that. http://sourcedaddy.com/ms-access/working-with-attachment-fields.html
@June7 it's custom. It takes a test varibale that is either a file path or folder path. If it's a file, it gets attached. If it's a folder, each file in the folder get attached.
This is just an insert into a table. What happens after is working fine. Actually getting the data into the table is where this error is happening.
| common-pile/stackexchange_filtered |
Close gmail after sent an email
My App send email via intent and works very fine.
The problem is, after the first email, i can't send further email because gMail (in this case) although it seems to work perfectly, does not send anything, because, i think, it remain opened in background.
So, I have to close my app, kill all processes (and thus kill Gmail) with a task-killer and reboot.
Is there a way to close the email client after sent the first email?
Thanks.
EDIT:
Here is the intent:
private void shareIntent(String string) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
saveDir=("/Scorepad/.temp");
if (string=="png" ) {
exportToBmpHandler("Shared_Image", saveDir);// here create and save the bitmap
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/Scorepad/.temp/Shared_Image.png"));
}
else {
try {
exportPdf("Shared_Pdf", saveDir+"/"); // here create and save the pdf
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sharingIntent.setType("image/pdf");
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/Scorepad/.temp/Shared_Pdf.pdf")); }
try {
startActivityForResult(Intent.createChooser(sharingIntent, "Share image using"), EMAIL);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getBaseContext(),"There are no email clients installed.", Toast.LENGTH_SHORT).show();
} finally {}
}
And this is the Activity onResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PROJECT_FILE && resultCode == Activity.RESULT_OK) {
// .................
}
if (requestCode == CREATE_CHORDS && resultCode == Activity.RESULT_OK) {
// .............
}
if(requestCode==EMAIL && resultCode==Activity.RESULT_OK){
Toast.makeText(this, "Mail sent.", Toast.LENGTH_SHORT).show();}
/* if (requestCode==EMAIL && resultCode==Activity.RESULT_CANCELED)
{ Toast.makeText(this, "Mail canceled.", Toast.LENGTH_SHORT).show();} */
super.onActivityResult(requestCode, resultCode, data);
}
can you show us what tried so far? Can you show us your code?
Hi B770, the purpose is to send a bitmap as attachement and this is ok for the first email. To send other emails with bitmap i must close the app, clean with task manager and restart. Thanks for your attention
have you tried to log the different steps? Perhaps something is blocking. By logging the different steps you can see where the problem occures.
I have the same problem, 3rd party app only sends one email with attachment if target email is the same. However it sends two emails when I send to two different target email address. It sucks
failure of result delivery
I just figured out, Gmail sort of only sends an email which has either different subject, content, attachment or cc/bcc than the last email sent within several minutes.
| common-pile/stackexchange_filtered |
Regenerate Windows default hostnames
I am looking for a way to re-generate the default hostname on Windows, or to know how it is been generated to set it as hostname when it has been changed already.
Those usually looks like DESKTOP-ABCDEFG where the 2nd part is like a serial number.
The last Name of a Windows Workstation (7/8/10) is saved in the registry under:
HKLM\Software\Microsoft\SchedulingAgent\OldName
The is no 'history' of all the names a workstation ever had, but this may help you in this case. (kudos to the guys of ugg.li)
| common-pile/stackexchange_filtered |
getFragmentManager from ArrayAdapter
I have a listView fulled from my custom ArrayAdapter. In each view there is a button. I want to change the current fragment when the button is clicked. This is my code:
public class CheckInSArrayAdapter extends ArrayAdapter<JSONObject> {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getViewOptimize(position, convertView, parent);
}
public View getViewOptimize(int position, View convertView, ViewGroup parent) {
......
viewHolder.commentBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
??? <<<<<
});
return convertView;
}
private class ViewHolder {
...
public Button commentBtn;
}
}
So now, i can't invoke getFragmentManager from the OnClickListener. How can i do?
You can define callback in your adapter and pass an instance in at construction or you can checkout listView.setOnItemClickListener()
OK, maybe i'm a bit late but, maybe it will help some people to do this.
In the class where you call the adapter, you need to extends or implements "FragmentActivity". Then your Activity will contain a fragmentManager.
When you call your Adapter call it with the class that extends FragmentActivity
MyAdapterName = new MyAdapterName(MyClassName.this, Objects);
Then in your adapter in getView() - do this.
final Context context = parent.getContext();
FragmentManager fm = ((Activity) context).getFragmentManager();
Be carefull to use the good android FragementManager
- android.app.FragmentManager
not android.support.v4.app.FragmentManager;
is it possible to use android.support.v4.app.FragmentManager;
@VV i don't know, but you can try, just replace the import with android.support.v4.app.FragmentManager and see if it's ok!
its so late but here no one answered this question so.
you can invoke fragment manager in your getview method using
FragmentManager fm = ((Activity)context).getFragmentManager();
getFragmentManager() is a method of Activity class .
for example
holder.tvBuy.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Fragment fragment;
fragment = new Buy();
((Activity)context).getFragmentManager().beginTransaction().replace(R.id.content_frame,fragment).commit();
}
}
here you need to pass your activity as context to your adapter.
hope it will help someone....
This worked for me. The most valuable part was ((Activity)context).getFragmentManager().beginTransaction().replace(R.id.content_frame,fragment).commit(); as I am used to just using getActivity() instead of creating one that way.
thank you ... you just saved my life :D
I wanna know where did you get the idea ???
I mean do you have some url or doc to look at .. just to understand what you just did
@Ayoub Good to hear, its helps. well i don't have any doc or url, because this code is a portion of one of my own project.
| common-pile/stackexchange_filtered |
Load dynamic content from php on submitting a form
I have created a page "index.php" with a lot of divs and I need to refresh only one of the divs when the form is submitted.
This div loads the content from chat_window.php which is as follows:
<div id="chatbox">
<?php echo $res; ?>
</div>
<!-- Chat user input form-->
<?php echo $formchat; ?>
chat_window.php uses dynamic content - $res and $formchat from chat.php.
Everytime I post the form the content of $res and $formchat is modified and I need to reflect the same in my page which loads chat_window.php.
I used AJAX and jQuery to do the same as follows:
$(document).ready(function() {
$("#submit").click(function() {
var name = $("input#chat").val();
var dataString = "chat="+ name;
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
}
});
$("#chatwrapper").load(chat_window.php);
return false;
});
});
The index.php has a div to show the chat_window as follows:
<!-- Chat window-->
<div id="chatwrapper">
<?php include ("chat_window.php"); ?>
</div>
As per my analysis, when I post the form, $res and $formchat are getting updated in the php. But when I load the chat_window.php, it doesnot loads the modified values. It rather loads the initial static values.
(Please dont suggest setInterval() as I dont want to refresh the page automatically).
I got my work done. Though I used another way of doing it.
What I have understood after few days of R&D is that, when we submit the form to a php, the request is sent with input params. When your php file processes this request, it might be updating some global variables. It completes processing the request and returns the control back to the calling index.php page.
The important thing to notice is:
The variable updates made while processing the form submit request do not persist after the control is returned. The global php variables will only get updated when the page gets refreshed.
So, if there is a strict requirement to avoid page refresh, collect the processed data from the php in some output string and pass it back to index.php like this:
$responseString = $res . "|" . $formchat;
echo $responseString;
The success parameter of .ajax will receive this output and accordingly you can update your chat window or any other form.
Try moving the .load() statement into the ajax success handler:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load("chat_window.php");
}
});
The $.ajax() call is asynchronous, which means that execution does not pause waiting for the response, rather, it moves on directly to the .load() call. (Which is also asynchronous, so really you've no guarantee about the order the response from each call will come in unless you don't make the second call until the first one finishes.)
It should work (aside from the missing quotation marks that I just added, which were missing in your question too). Are you sure it's reloading the initial values as compared to doing nothing at all?
I checked it after adding the quotations. But no success. Though the request is being processed (which i checked using alerts), but "chat_window.php" doesnot gets the refreshed value of $res.
Javascript is non-blocking, so it means that the interpreter does not wait for jobs to complete before processing the next one.
In your code, $("#chatwrapper").load('chat_window.php'); is being called pretty much before the ajax request above it completes. You will need to use the ajax success event to call the reload.
Try:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load('chat_window.php');
}
});
Thanks for the reply. I have even tried the above. Unfortunately, it doesnot work. :(
are there any Javascript errors showing up? Try using Firebug to see the response from the ajax call.
| common-pile/stackexchange_filtered |
Ubuntu 19.04 lm-sensors functions only partially
After upgrading from Ubuntu 18.10 to Ubuntu 19.04 (Disco Dingo) the command /usr/bin/sensors -A no longer shows the fan information. Before upgrate I get this kind of information:
fan1: 334 RPM (min = 0 RPM)
fan2: 864 RPM (min = 0 RPM)
fan6: 1076 RPM (min = 0 RPM)
SYSTIN: +23.0°C (high = +98.0°C, hyst = +95.0°C) sensor = thermistor
CPUTIN: +27.5°C (high = +80.0°C, hyst = +75.0°C) sensor = thermistor
AUXTIN0: +23.5°C sensor = thermistor
AUXTIN2: +23.0°C sensor = thermistor
AUXTIN3: +97.0°C sensor = thermistor
PECI Agent 0: +30.0°C (high = +98.0°C, hyst = +95.0°C)
PECI Agent 0 Calibration: +27.0°C
Core 0: +27.0°C (high = +80.0°C, crit = +100.0°C)
Core 1: +33.0°C (high = +80.0°C, crit = +100.0°C)
Core 2: +30.0°C (high = +80.0°C, crit = +100.0°C)
Core 3: +29.0°C (high = +80.0°C, crit = +100.0°C)
while after upgrade I get only this:
asus-isa-0000
cpu_fan: 0 RPM
acpitz-acpi-0
temp1: +27.8°C (crit = +119.0°C)
coretemp-isa-0000
Package id 0: +34.0°C (high = +80.0°C, crit = +100.0°C)
Core 0: +32.0°C (high = +80.0°C, crit = +100.0°C)
Core 1: +34.0°C (high = +80.0°C, crit = +100.0°C)
Core 2: +33.0°C (high = +80.0°C, crit = +100.0°C)
Core 3: +32.0°C (high = +80.0°C, crit = +100.0°C)
I have the modules coretemp and nct6775 already declared into /etc/modules (same as for Ubuntu 18.10) and I also run sudo sensors-detect which also recommends those modules.
I have an Asus H370-I motherboard with an i3-8300 Intel CPU.
What is the problem and how should I solve it?
Editing /etc/default/grub and adding acpi_enforce_resources=lax to GRUB_CMDLINE_LINUX_DEFAULT might solve your problem.
So it looks something like this...
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_enforce_resources=lax"
I have read though that adding this may cause instability.
| common-pile/stackexchange_filtered |
How can i send data from my forms to a summarypage in React?
I am currently learning react and I want to send data from user input in my forms. I want the data to be collected on a new page. I also want the total price for my getCartTotal component to been shown up at the same page.
Do you have any tips for me?
here is my code so far :
import React, { useContext } from "react";
import { StoreComponent } from "../../components/StoreComponents";
import { Button } from "@mui/material";
import "../../styles/Order.css";
function Order() {
const { getCartTotal } = useContext(StoreComponent);
return (
<form className="place-order">
<div className="place-order-left">
<p className="title">Delivery information</p>
<div className="multi-fields">
<input type="text" placeholder="Firstname"></input>
<input type="text" placeholder="Lastname"></input>
</div>
<input type="email" placeholder="E-mail"></input>
<div className="multi-fields">
<input type="text" placeholder="Address"></input>
</div>
<div className="multi-fields">
<input type="text" placeholder="zipcode"></input>
<input type="text" placeholder="city"></input>
</div>
<input type="text" placeholder="phone"></input>
</div>
<div className="place-order-middle">
<p className="title">Payment</p>
<div className="multi-fields">
<input type="text" placeholder="cardnumber"></input>
</div>
<div className="multi-fields">
<input type="text" placeholder="expired"></input>
<input type="text" placeholder="CVC-code"></input>
</div>
</div>
<div className="place-order-right">
<div className="cart-total">
<h2>Cart Total</h2>
<div>
<div className="cart-totals-details">
<p>Sum</p>
<p>{getCartTotal()} $</p>
</div>
<hr></hr>
<div className="cart-totals-details">
<p>Fee</p>
<p>{getCartTotal() === 0 ? 0 : 2} $</p>
</div>
<hr></hr>
<div className="cart-totals-details">
<b>Total</b>
<b>{getCartTotal() === 0 ? 0 : getCartTotal() + 2} $</b>
</div>
</div>
<Button variant="contained">Pay now</Button>
</div>
</div>
</form>
);
}
export default Order;
I am also new as well, here I have prepared a solution for you.
But I cannot explain things to you using exact industry terminologies.
However, I will expalin what is going around as my understanding.
import "./App.css";
import Home from "./components/Home";
import Child from "./components/FormComponent";
import Summary from "./components/SummaryComponent";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import { useState } from "react";
function App() {
// declaring a state variable to hold the form data once the form is submitted.
//I dont think we can pass prop between two child components.
// so what we do is we pass the data to their immediate parent component
//and then pass down from their to the next component.
const [formData, setFormData] = useState("");
// This function is passed as prop to FormComponent,
//which then when we submit the will be called and will set the form data.
const transferToSummaryComponent = (data) => {
setFormData(data);
};
return (
<div className="App">
<h1>App</h1>
<Router>
<Routes>
<Route path="/home" Component={Home} />
<Route path="/child" element={<ChildComponent
onSubmit={transferToSummaryComponent} />} />
//function being passed as prop.
<Route path="/summary" element={<SummaryComponent
data={childData} />} />
//once form data is set, it is then passed as prop to needed component.
</Routes>
</Router>
</div>
);
}
export default App;
import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
const FormComponent = (props) => {
const navigate = useNavigate();
// to handle and hold the inputs given in forms.
const [formData, setFormData] = useState({
name: '',
email: '',
cartTotal: '' //this is for total price or getCartTotal.
//unlike other fields, this is not being retrieved from user input.
// so we get a hold to this value a little differently. with a function below.
})
// function to get a hold to cartTotal.
const calculateCartTotal = () => {
return "$500";
//this block can be replaced with your logic. For now i think it can be as:
// const { getCartTotal } = useContext(StoreComponent);
// return getCartTotal
// not sure this will work. but if you can somehow retireve the value,
// it will surely be passed to next component.
};
//Just handling input but notice cartTotal is being handled slightly differently.
const handleInput = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value, cartTotal: calculateCartTotal() })
}
// handling the form submission. here, the function we passed from our
//App.js is being called "props.onSubmit(formData".
//Note: this 'onSubmit' is not related to form's onSubmit.
//If in App.js we have onWhatever={transferToSummaryComponent} instead of
//onSubmit={transferToSummaryComponent}, then it would be props.onWhatever(formData).
const handleSubmit = (e) => {
e.preventDefault();
props.onSubmit(formData)
//function passed as prop from App.js is called which take the parameter,
//the state variable formData. Dont confuse this with formData of App.js.
//They dont relate and work in their own components.
// and when we call this function, it will go back to App.js and
//perform whatever is written in its block which for now is setFormData(formData).
//If in App.js our state variable was declared as, [receivedData, setReceivedData],
//then we would have our function as
//setReceivedData(whatever variable is declared in function defination.)
navigate("/summary");
// this will route you to next page. And since on this Route defination, we are passing
//the receivedData(formData of App.js) as prop to the component
//we can then receive the formData in the component and work with it as needed.
}
return (
<div>
<form onSubmit={handleSubmit}>
<input type='text'
name='name'
value={formData.name}
onChange={handleInput}></input>
<input type='text'
name='email'
value={formData.email}
onChange={handleInput}></input>
<button type='submit'>Send Data</button>
</form>
</div>
)
}
export default FormComponent
import React from 'react'
const SummaryComponent = ({ data }) => { //received formData as prop.
return (
<div>
<h1>Data Of Child Component</h1> // using them as needed
<h2>Name: {data.name}</h2>
<h2>email: {data.email}</h2>
<h2>Total: {data.cartTotal}</h2>
</div>
)
}
export default SummaryComponent
The topic you're looking for is controlled input forms in React. The basic idea is to utilize hooks to maintain the form data. For example, in your case, you can create a new useState() hook and store an object with all the fields of the form. you can then pass this object as props to be rendered on any page.
Declare the object in the parent (depending on where you want to send data) using a useState() and then you can pass it around as props wherever required.
If you want I would be happy to write the codes or provides some reference material.
| common-pile/stackexchange_filtered |
What replaces SecurityTokenCache in .NET 4.5
When WIF was separate, you could create SessionSecurityTokenHandler and specify a token cache for use in something like a web farm scenario. Now, SessionSecurityTokenHandler in .NET 4.5 doesn't have that constructor parameter. Is there something equivalent in .NET 4.5?
Found the replacement. It is documented here:
http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.sessionsecuritytokencache.aspx
| common-pile/stackexchange_filtered |
What will be the sum of the numbers in the $100^{\text{th}}$ step?
So this question states that a triangle is found where in between every $2$ numbers, their sum will be found in the next step, an example can be found below for the first $3$ steps. The question asks what will be the sum of the numbers in the $100^{\text{th}}$ step? I managed to find a pattern that states $S_n=S_{n-1}+2 \times 3^{n-1}$ if $S_k$ is the sum of step $k$. However, is this pattern correct and if it is then why? Also, can this triangle relate to Pascal's triangle? Thank you anyways.
But the third row adds to $28$, your formula gives $26$. Can you write one more row?
@Krishna I noticed that this triangle is similar to Pascal's and that is how I got the $2^n$ in my equation. However, the second part of my equation would be the harder one to prove as it does not have a huge relation with Pascal's triangle.
@farruhota Thank you for that notice I realized I had a mistake and meant to say $S_n=S_{n-1}+2 \times 3^{n-1}$ This will be fixed.
I do not understand how the third row is made from the second, let alone how subsequent rows are made.
@Servaes The same numbers from the second row have been written down again but this time with an extra number between each $2$ numbers being their sum. So the $4$ came from being the sum of $1+3$ and the from the $5$ sum of $3+2$
$S_n=3S_{n-1}-2, n>1; S_1=4$
This is triangular OEIS sequence A049456 which states row sums are OEIS sequence A034472 3^n+1.
Every number in the $n+1$-th row either comes directly from the $n$-th row, or is the sum of two neighbouring numbers in the $n$-th row. Every number in the $n$-th row has two neighbours (except the first and last) and so it is in two sums. So in summing the $n+1$-th row, we in fact sum every number from the $n$-th row three times (except the first and last). This yields the recursive formula
$$S_{n+1}=3S_n-2.$$
Your recurrence equation is also correct. Note that:
$$S_n=S_{n-1}+2\cdot 3^{n-1}, S_1=4 \Rightarrow \frac{S_n}{3^n}=\frac13\cdot \frac{S_{n-1}}{3^{n-1}}+\frac23 \Rightarrow \\
a_n=\frac13a_{n-1}+\frac23, a_1=\frac43 \Rightarrow a_n=\left(\frac13\right)^n+1=\frac{S_n}{3^n} \Rightarrow \\
S_n=3^n+1.$$
| common-pile/stackexchange_filtered |
Get and act on dynamically-added controls in WPF
I'm programatically adding a series of controls based on a dictionary describing the controls various settings. Here are two of the entries as an example (I truncated the rest to save space):
// Translation array from fix shortname to various data about them
private Dictionary<string, Dictionary<string, string>> fixers = new Dictionary<string, Dictionary<string, string>>
{
["F1"] = new Dictionary<string,string> {
["PrefName"] = "KillF1UnhelpfulHelp",
["Img"] = @"/graphics/F1key.png",
["Title"] = @"Diable F1 ""Help"" function",
["Description"] = @"
Have you ever hit the F1 key by accident and had a distracting and unhelpful window or webpage open as a result?
Windows set the F1 key to a generic help function that basically never helps and always gets in the way.
Enable this control to disable that obnoxious design choice. Note that some programs still respond to F1 on their own accord,
but this will stop the default Windows behavior in things like Windows Explorer at least.
",
["Tags"] = "#Keyboard,#Rage"
},
["CMD"] = new Dictionary<string, string>
{
["PrefName"] = "RestoreAdminCMDContext",
["Img"] = @"/graphics/CMD.png",
["Title"] = @"Restore ""Open Admin CMD Window Here"" to Windows Explorer",
["Description"] = @"
When you need to run commands in CMD, it's usually in a specific folder. Windows used to have an option when you CTRL+Right Click
to show ""Open CMD HERE"" on a folder. This restores that function AND it's at administrative level (and you don't need to CTRL+CLICK to see it)
",
["Tags"] = "#Windows Explorer,#TimeSaver"
},
}
The controls themselves are just custom boxes with a few grid components, buttons, etc. Fairly simple. They are currently correctly generated and then added to the window as follows:
Code that adds them:
public MainWindow()
{
InitializeComponent();
var fixNames = fixers.FixerNames();
foreach (string key in fixNames)
{
var temp = fixers.GetFix(key);
// Be sure to pass this along as well
temp["Name"] = key;
fixerBoxes[key] = new FixerBox(temp);
FixersArea.Children.Add(fixerBoxes[key]);
}
FixerBox f1box = (FixerBox)FixersArea.FindName("F1");
StatusBox.Text += "Tags are:"+ f1box.FixerTags;
}
This is the XAML for the window where the controls are being added:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Name="StatusBox" Width="600" MinHeight="40" Background="Beige"/>
<ScrollViewer Grid.Row="1" ScrollViewer.VerticalScrollBarVisibility="Visible">
<WrapPanel Name="FixersArea" Orientation="Horizontal" Width="auto" ></WrapPanel>
</ScrollViewer>
</Grid>
And this is the output:
Everything works as expected, but how do you reference a dynamically generated custom control? I tried a few ways of referencing it by name or some other value and testing by printing out some of the text to the status box:
FixerBox f1box = (FixerBox)FixersArea.FindName("F1");
StatusBox.Text += "Tags are:" + f1box.FixerTags;
But this results in an exception saying that f1box was null. So the finder isn't working. I found a few methods online for finding a child element by name, but those didn't work either and are fairly long so I'll exclude them.
The bottom line is that I'll need to get/set the state of the controls, show and hide them based on filters, and respond to their click events. I could probably handle the click response in the control itself, but the rest is going to be main-window stuff for sure (the controls will be affected by filtering and various save/load of settings).
why not f1box = fixerBoxes["F1"]?
I figured that out just a moment ago myself. I was looking at this too much from an HTML viewpoint. It works fine. If you post that as the answer (bascially stop referencing the "Document" and reference the existing objects instead), I'll accept it.
The FindName method uses x:Name values in Xaml to find children. If you need a dynamically added child to be available via FindName you need to explicitly register its name in C#:
FixersArea.RegisterName(key, fixerBoxes[key]);
Then you can use the following code to retrieve the child:
FixerBox f1box = (FixerBox)FixersArea.FindName("F1");
However, since you already maintain a dictionary of your fixerBoxes, you can do this:
FixerBox f1box = fixerBoxes["F1"];
Thanks for adding the detail of registername! that might solve a second problem I'm having :)
| common-pile/stackexchange_filtered |
Query takes very long time
I'm a newbie to POSTGIS and I wonder if someone could help me out.
I have loaded all postal codes with their geographical coordinates (geography) and created an index on this coordinate.
When I run the following query it works just fine (within a few millisecond over a few million instances)
SELECT
postcode, huisnummer, huisletter, huisnummertoevoeging,
ST_X(geolocatie :: geometry) as latitude,
ST_Y(geolocatie :: geometry) as longitude,
st_distance(geolocatie, ST_SetSRID(ST_Point(4.3387478, 51.9808117), 4326)) as afstand
FROM inspire
WHERE ST_DWithin(geolocatie, ST_SetSRID(ST_Point(4.3387478, 51.9808117), 4326), 1000)
ORDER BY afstand
LIMIT 5;
geolocatie is of type geography and I have defined the following index on geolocatie
CREATE INDEX inspire_geolocatie_index
ON public.inspire USING gist
(geolocatie)
TABLESPACE pg_default;
This works fine as long as there are neighbors, but the query seems to have difficulties for the use case that there are no neighbors. Any suggestions please?
If you do "LIMIT 5" then it stops after finding the first five matches. That might be the first five rows of your table. It will be quick. If your condition has no matches, PostGIS has to try every row. Is that the problem?
@Spacedman I think in this case, PG would always execute the ORDER BY (that you can try and rewrite to geolocatie <-> ST_SetSRID(ST_Point(4.3387478, 51.9808117), 4326) for a possible boost...and maybe place the point creation into a CTE), and should not interfere with the no-neighbor case...I also cannot reproduce this; could you add your table structure in more detail and the EXPLAIN ANALYZE <your_query> output for both cases? PG/PostGIS versions might be nice, too.
btw., it is advisable to use explicit casts, if only for clarity here, e.g. ST_SetSRID(ST_Point(4.3387478, 51.9808117), 4326)::geography; most functions will have multiple signatures where a cast can make a huge difference (and many don't have an implicit cast like here).
My mistake yes, I didn't notice the "order by". it will have to compute all the distances.
You are so helpful. Thank you so much! For me it's a real adventure :). BTW I looked at your suggestions and using the explicit cast ::geography did the trick I now do get a very fast response without any answers. And that's exactly what I want.
You do have a solid query right there, and I can´t seem to reproduce your issue (as per the title), assuming a correctly created and indexed geography column.
If I were to improve things here, I´d use
SELECT
postcode, huisnummer, huisletter, huisnummertoevoeging,
ST_X(geolocatie::geometry) AS latitude,
ST_Y(geolocatie::geometry) AS longitude,
ST_Distance(geolocatie, ST_SetSRID(ST_MakePoint(4.3387478, 51.9808117), 4326)::geography) AS afstand
FROM inspire
ORDER BY geolocatie <-> ST_SetSRID(ST_MakePoint(4.3387478, 51.9808117), 4326)::geography
LIMIT 5;
The KNN operator <-> as the ORDER BY parameter is ultimate in performance when used properly; I would even forgo a limiting filter, especially as ST_DWithin, in my experience, adds overhead and denies the planner the much desired index (only) scans more often than not.
I wouldn´t recommend this without proper transformation (as, e.g. @Michael proposed), but an index forcing alternative filter option would be
SELECT
postcode, huisnummer, huisletter, huisnummertoevoeging,
ST_X(geolocatie::geometry) AS latitude,
ST_Y(geolocatie::geometry) AS longitude,
ST_Distance(geolocatie, ST_SetSRID(ST_MakePoint(4.3387478, 51.9808117), 4326)::geography) AS afstand
FROM inspire
WHERE geolocatie::geography && ST_Expand(ST_SetSRID(ST_MakePoint(4.3387478, 51.9808117), 4326), 0.01)
ORDER BY geolocatie <-> ST_SetSRID(ST_MakePoint(4.3387478, 51.9808117), 4326)::geography
LIMIT 5;
i.e. using the bbox intersection operator && directly; major drawback here is the dependency on the geometry type (and thus the CRS units) for ST_Expand, that leaves you with a dangerous 0.01 degrees (~1.1km, but only at the equator) to be used as distance parameter without a meter based projection.
Without your adding details to the question, issue tracking will be difficult; to start with, the EXPLAIN ANALYZE <your_query> for both plans is almost mandatory for query performance related questions, as well as your PostgreSQl/PostGIS versions.
To be sure to have an geography index: CREATE INDEX idx_inspire_geolocatie ON inspire USING GIST (cast(geolocatie as geography));
Thank you ThingumaBob. Your answer was very helpful. Using the explicit cast, as you suggested, solved the problem.
Your suggested queries also perform very well, viz.1 millisecond. Really good!. The original modified query takes 0.057 seconds using your first suggestion to use an explicit cast, which is not bad either. I still have a lot to learn....
You mention your query has difficulties for the case that are no neighbours - this is due to the 'where' statement, which excludes observations beyond 1000 units of your coordinate system. In the documentation of st_dwithin it states the following concerning distance: units are in those of spatial reference.
This brings me to a second point: 1000 units in WGS84 would be very far. You should use a projected coordinate system with st_transform. For the Netherlands this would be EPSG 28992.
To know which points are within 1000 meters you can execute following query:
SELECT
postcode, huisnummer, huisletter, huisnummertoevoeging,
ST_X(ST_Transform(geolocatie,28992) :: geometry) as latitude, -- assuming your geometry is in 4326
ST_Y(ST_Transform(geolocatie,28992) :: geometry) as longitude,
ST_Distance(
ST_Transform(geolocatie,28992),
ST_Transform(ST_SetSRID(ST_Point(4.3387478, 51.9808117),4326),28992)) as afstand ,
ST_DWithin(
ST_Transform(geolocatie,28992) ,
ST_Transform(ST_SetSRID(ST_Point(4.3387478, 51.9808117),4326),28992),1000) as within_distance
FROM inspire
ORDER BY afstand
Performance wise, this can be improved by adding a geometry to the table in advance with the project geometry and adding an index.
-- Add the column
ALTER TABLE inspire ADD COLUMN geom_28992 geometry;
-- Set the column
UPDATE inspire SET geom_28992 = st_transform(geom,28992);
-- Create an index
CREATE INDEX idx_geom_28992_inspire ON inspire USING GIST(geom_28992);
For st_dwithin to work efficiently both geometries need to be indexed: the index of reference geometry needs to be in a table as well, with index.
-- Reference geom
CREATE TABLE reference_geom AS
SELECT ST_Transform(ST_SetSRID(ST_Point(4.3387478, 51.9808117),4326),28992) geom_28992;
-- Create an index
CREATE INDEX idx_geom_28992_reference_geom ON reference_geom USING GIST(geom_28992);
Finally, you can execute the query
SELECT postcode, huisnummer, huisletter, huisnummertoevoeging,
st_distance(i.geom_28992,g.geom_28992) distance,
true::boolean within_distance
FROM inspire i
INNER JOIN reference_geom g ON st_dwithin(i.geom_28992,g.geom_28992,1000)
UNION ALL
SELECT postcode, huisnummer, huisletter, huisnummertoevoeging,
null AS distance,
false::boolean within_distance
FROM inspire i,reference_geom
WHERE st_dwithin(i.geom_28992,g.geom_28992,1000) = FALSE
For more interesting applications have a look at nearest neighbour problems in Postgis, for instance here and here.
there's hidden advice here, but some misconceptions, too; 1st: for point-on-point proximity searches, an index is not necessarily beneficial (but seeing to it being in place doesn´t hurt either), since bboxes of points are in fact the points themselves; 2nd: for each single geometry, only the index of the filtered table will make a difference in performance. 3rd: using geography type will, in fact, implicitly use meter as units when in use with appropriate functions, and ST_Distance and ST_DWithin will both implicitly cast the second input geometry to the type of the first, if possible
Thanks, it makes senses that for point-on-point proximity searches the index is not beneficial; I simply had a look at the documentation. Also, I was not aware that using ST_Distance and ST_DWithin with the geography use meters as units, but the documentation indeed states it clearly.
| common-pile/stackexchange_filtered |
Spring security and Tomcat
I'm facing a problem while trying to add j_spring_security_check as an action in my login.jsp
' method="POST">
This is my form, but when I type my default acc/pw admin/admin, instead of getting redirected to the users page, I get the following error
type Status report
message /java-blog/%3Cspring:url%20value=%22/j_spring_security_check%22%20/%3E
Can you give me a hand and tell me where the problem is?
I have security.xml where I've set login page as /login and intercept url as /users** and I've also imported the security.xml spring configuration bean into the applicationContext
The server I'm using is Tomcat 7.
what actual error are you getting
I haven't copied the form header properly: - this is it, but there seems to be a problem with the "POST" method because when i submit my username and password, instead of getting redirected by the spring security to Users, i get the above error message /java-blog/%3Cspring:url%20value=%22/j_spring_security_check%22%20/%3E and it seems it can't be found, can the problem come from Tomcat, because the app was Tested on jetty and worked fine, or maybe it is in the encoding or controller.
Be sure to include the taglib at the top of your jsp file:
<%@ include file="../layout/taglib.jsp" %>
instead of
<form class="form-signin" role="form" action='<spring:url value="/j_spring_security_check" />' method="POST">
use this
<form class="form-signin" role="form" action="<spring:url value='/j_spring_security_check' />" method="POST">
Also make sure you have included the spring jsp taglibs in your login form jsp.
| common-pile/stackexchange_filtered |
Copy temp file before it's deleted
I had an idea to write some useful code so that the recently downloaded temp files like installation files and other media files can be copied to somewhere safe location before it gets deleted.
string dir = "c:\\Users\\neal\\appdata\\Local\\Temp";
string newdir = "D:\\";
var directory = new DirectoryInfo(dir);
var myFile = (from f in directory.GetFiles()
orderby f.LastAccessTime descending
select f).First();
var myDir = (from f in directory.GetDirectories()
orderby f.LastAccessTime descending
select f).First();
myFile.CopyTo(newdir, true);
The above method doesn't actually work. And I'm not sure why. I guess every file may not have access rights (installation files).
Any idea or any other logic out there?
A few points: Firstly you're not using myDir at all at the moment. Secondly you're using .First() - this will only get you the first file in the directory, which is probably the only one you're seeing copied. You probably want more of a recursive approach to this problem.
How about xcopy called from a .bat script. No need to complicate this.
Yeah, I'd agree with Chris, unless there's a specific need to do this in code. You could look at robocopy - I've found that does the trick nicely.
You can avoid myDir for now Because there are other parts where it will used.
LastAccessTime is pretty broken nowadays.
I definitely agree that there are already proven solutions to this, however if you wish to implement something in code you should check out the FileSystemWatcher http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx
This will notify your program of changes to the directory you are watching so you can take action.
This is half the solution i was looking for.This is after i find the exact file that has been downloaded recently to temp folder.
It is not necessary to know the file in advance. If you monitor the temp directory with a filter of "" and handle the events you are interested in, any file Created, Modified, or Deleted will provide the full path in the event that is raised. So you will automatically get the new file and be able to do something with it with very little code.
| common-pile/stackexchange_filtered |
Selenium is not calling the website
I'm trying selenium for the first time. My code is as follows:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
import selenium.webdriver.support.ui as ui
import selenium.webdriver.support.expected_conditions as EC
import os
import time
class expediaUnitTest():
def __init__(self):
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-ssl-errors')
dir_path=os.getcwd()
chromedriver=dir_path+"\chromedriver"
os.environ["webdriver.chrome.driver"]=chromedriver
driver=webdriver.Chrome(chrome_options=options,executable_path=chromedriver)
def timerPractice(self):
time.sleep(5)
def gotoexpedia(self):
self.driver.get("https://www.expedia.com/")
def teardown(self):
self.driver.close()
if __name__=="__main__":
obj=expediaUnitTest()
obj.gotoexpedia()
A new chromebrowser is called but it does not access the webpage. I get the errormessage:
AttributeError: 'expediaUnitTest' object has no attribute 'driver'
When i give the timePractise(), it works perfectly,as in the browser disappears after the given number of seconds. But it does not seem to be calling a function.
Ps: I'm following the online tutorial given here:https://www.youtube.com/watch?v=zZjucAn_JYk
He doesn't have the problem that I'm having.
Can someone please help?
You are missing self when creating the instance of the driver. So instead of
driver=webdriver.Chrome(chrome_options=options,executable_path=chromedriver)
it should be
self.driver=webdriver.Chrome(chrome_options=options,executable_path=chromedriver)
(in the video they are doing it exactly that way)
Thank you so much!!
| common-pile/stackexchange_filtered |
Speed Up Visual Studio Publish Web Process
I am using Visual Studio 2012 Professional to deploy my ASP.Net MVC website.
The problem is that when I use the one click publish feature, my web application comes to a screeching halt and it takes about 5 minutes for the website to respond normally again.
What are some things I can do to speed up this process to reduce or eliminate the amount of downtime for my users?
Are you using Web Deploy, File System, or FTP, etc.?
I am using web deploy.
Does the site just run slow immediately after deployment or do requests in fact timeout? If the site is just laggy you may find that caching is the cause. Take a look at what's going on with Fiddler or a similar tool, that should point you in the right direction.
I publish to a separate copy of the site on the live server and I have a script which I then run on the server to compare the live site with the copy and only update new/changed files/directories and delete removed ones. This cuts down the downtime quite a bit, especially if there have only been minor changes.
| common-pile/stackexchange_filtered |
*Overwrit*labels
If you've ever tried adding labels to a really dense plot, then you'll realise that sometimes labels will overlap one another, making them hard to read. We're going to do something similar but in 1D.
Input will be a sequence of (label, x-coordinate) pairs, and output will be the result of drawing each point and label, in the given order. An asterisk * representing the point should be placed at the given x-coordinate and the label should follow. Any existing characters will be overwritten.
For instance, if the input was
Hello 0
World 8
Fizz 3
Buzz 5
PPCG 16
X 9
Then the following would happen:
*Hello
*Hello *World
*He*Fizz*World
*He*F*Buzzorld
*He*F*Buzzorld *PPCG
*He*F*Buz*Xrld *PPCG
The final line should then be outputted.
I/O rules
Input may consist of any number of pairs. Each label will only consist of uppercase and lowercase letters, and label lengths will be at most 127 chars. Each x-coordinate will be between 0 and 127 inclusive.
Input may be in any convenient list or string format such that the pairs are unambiguous and labels/x-coordinates alternate in the input. For example, a format like [("Hello", 0), ("World", 8) ...] or [0 "Hello" 8 "World" ...] is fine. However, you may not assume two separate lists of labels and x-coordinates.
Functions and full programs are both okay.
Any spots not covered by a label should be represented with a space. However, there may not be any extraneous leading or trailing whitespace aside from a single optional trailing newline.
Examples
Input:
OneLabel 10
Output:
*OneLabel
Input:
Heathrow 0
Edinburgh 2
London 4
Liverpool 6
Oxford 8
Output:
*H*E*L*L*Oxfordl
Input:
alpha 20
beta 4
gamma 57
delta 3
epsilon 22
zeta 32
eta 53
theta 27
Output:
*delta *a*epsi*thetazeta *eta*gamma
Input:
abc 5
d 5
abc 10
ABCDEFGHIJKLMNOPQRSTUVWXYZ 127
Output:
*dbc *abc *ABCDEFGHIJKLMNOPQRSTUVWXYZ
Note that labels and/or x-coordinates may be repeated.
If the x coords are [0,127] and the strings are (0,127], can a label run off the far right end of the line, or is it protected? That is, does "foo 127" end the line with "*" or "*foo"? Just checking if the string should have a soft or hard ending.
@PotatoOmeletteSandwich My intention was so that the total length fits within 255, so the maximal output length will occur when there is a length 127 label at x-coordinate 127. The final output should not be truncated in any way, except to remove trailing whitespace.
CJam, 24 23 19 bytes
l~Sf.*'*f*:.{S^+1=}
This reads the input as a CJam array of coordinate-label pairs.
Try this fiddle in the CJam interpreter or verify all test cases at once.
Thanks to @MartinBüttner for helping me save 4 bytes!
How it works
l~ Read a line from STDIN and evaluate it.
Sf For each pair, push the pair and " "; then:
.* Perform vectorized repetition.
[X "label"] " " .* -> [(X spaces) "label"]
'*f* Join each resulting pair, using '*' as separator.
:.{ } Reduce by the following vectorized operator:
Push two characters (A and B).
S^ Compute the symmetric difference of B and " ".
This pushes "B " for a non-space B and "" otherwise.
+1= Append and select the second character (with wrap).
This selects B for "AB " and A for "A".
I just added a test case and thought I'd leave a comment saying that no, it didn't break this submission - CJam's interpreter output just word wraps. Just in case anybody gets confused.
Python 2, 67 bytes
z=''
for a,b in input():z=(z+' '*b)[:b]+'*'+a+z[len(a)-~b:]
print z
Takes input like [('Heathrow', 0), ('Edinburgh', 2), ('London', 4), ('Liverpool', 6), ('Oxford', 8)] and prints the result.
Python doesn't allow strings to be modified, and converting to and from a list is expensive. So, this recreates the string z to add in a new word. We take the b characters before the word, padding with spaces if needed, then the new text with an asterisk, then the part of z after the new word. Note that trailing spaces are never added.
The reduce version is 3 chars longer (70):
lambda I:reduce(lambda z,(a,b):(z+' '*b)[:b]+'*'+a+z[len(a)-~b:],I,"")
Pyth, 20 bytes
V.Tmrj" *"d9Qpe+d-Nd
Try it online: Demonstration or Test Suite
Explanation
V.Tmrj" *"d9Qpe+d-Nd
m Q map each pair d of the input to:
j" *"d join d by the string " *"
r 9 range-length encode
(this gives x-coordinate spaces, a star and the label)
.T transpose this table
V for N in ^:
-Nd remove spaces from N
+d add a space at the beginning
e take the last character
p and print it (without newline)
This is way better than what I had.
JavaScript ES6, 104 bytes
c=>(a=Array(255).fill(" "))&&c.map(([u,v])=>a.splice(u,v.length+1,..."*"+v))&&a.join``.replace(/ +$/,"")
Example Usage
Input into a compliant console:
t = [[0,"Hello"],[8,"World"],[3,"Fizz"],[5,"Buzz"],[16,"PPCG"],[9,"X"]];
(c=>(a=Array(255).fill(" "))&&c.map(([u,v])=>a.splice(u,v.length+1,..."*"+v))&&a.join``.replace(/ +$/,""))(t);
Output from the last statement:
"*He*F*Buz*Xrld *PPCG"
Explanation
This creates an anonymous function from c to three expressions that have been logically-ANDed together. The first two statements are always truthy, and the JS short-circuit rules say that whenever the first is truthy, return the entire value on the right hand side (without coercing to boolean): so this is formally equivalent to
(function (c) {
a = Array(255).fill(" "); // global variable `a` overwritten
c.map(function (x) { // only side-effects are used here.
var u = x[0], v = x[1]; // ES6 destructuring
a.splice(u, v.length + 1, ..."*" + v)); // main logic
});
return a.join("").replace(/ +$/, ""); // postprocessing and trim
})
The first statement has to be wrapped in parentheses above because the assignment operator = has lower precedence than the logical-AND operator &&.
The "rest parameter" assembly ..."*"+v is also part of ES6; it concatenates a leading * to the string and then interprets it as a list-like parameter, splitting it into a bunch of arguments which are provided to Array.prototype.splice, which takes (m, n, ...rest) and modifies its array at position m to remove n elements and then insert all of the rest arguments. To accomplish this before ES6 you would use the more cumbersome:
[].slice.apply(a, [u, v.length + 1].concat(("*" + v).split("")))
The array then gets concatenated with the empty string and trailing whitespace is deleted.
Jelly, 14 bytes
0x;”*;µ/€Ṛo/o⁶
Try it online!
Takes input as a list of pairs [coordinate, label]. The last test case does work, TIO simply has wrapping
How it works
0x;”*;µ/€Ṛo/o⁶ - Main link. Takes a list of pairs I
€ - Over each pair P in I:
µ - Run the following, using:
/ - C (coord) as the left argument and L (label) as the right:
0x - Repeat 0 C times
;”* - Concatenate "*"
; - Append L
Ṛ - Reverse I
o/ - Reduce columnwise by logical OR
This replaces 0s with the next non-zero element
o⁶ - Replace the remaining zeros with spaces
Javascript 121 chars
Using non-standard features, works on Firefox.
x=Array(255).fill(" ");eval(prompt()).map(s=>{s[0].split``.map((n,i)=>x[s[1]+i+1]=n);x[s[1]]="*"});x=x.join``.trimRight()
Older version:
x=Array(255).fill(" ");eval(prompt()).map(s=>{s[0].split``.map((n,i)=>x[s[1]+i+1]=n);x[s[1]]="*"});x=x.join``.replace(/ +$/,"")
x=Array(255).fill(" "); //Creates an array with spaces
eval(prompt()) //Gets some input, has to look like [["Hello",4],["Hi",14],["Oi",0]]
.map(s=>{s[0].split``.map((n,i)=>x[s[1]+i+1]=n);x[s[1]]="*"}); //Main "logic"
x=x.join``.replace(/ +$/,"") //Gets rid of the trailing spaces
/ +/ makes much more sense than \s disappointed I missed that! Could you save bytes using x=' '.repeat(255); and avoiding the .join?
@DomHastings: JS strings are immutable so you would have to .split('') it into a mutable data structure, but at that point Array(255).fill(' ') is shorter. In my version most of my savings come from (a) using the "you can give either a function or program" rule to delete eval(prompt()) in exchange for c=> and (b) using the builtin Array.prototype.slice method with a rest parameter to shorten the logic part a little bit.
@ChrisDrost ah of course... I forget it's just an accessor! Shame[].map.call(s[0], doesn't save any either...
Ruby, 94 81 75 bytes
Golfed:
s=" "*128;$<.map{|l|w,p=l.split;p=p.to_i;s[p..w.size+p]="*"+w};$><<s.rstrip
Here's the ungolfed code:
s = " "*128
$<.map{|l| # for each line entered via stdin, ctrl+D to stop
w,p = l.split # had to move the chomp down here
p = p.to_i # there's no 'to_i!'...
s[p..w.size+p] = "*"+w # in the range of *foobar, replace the string
}
$><<s.rstrip # output suggested by w0lf
Thanks @w0lf for the suggestions on mapping the input!
Thanks @w0lf and @Not that Charles for the thought on removing a variable.
See the Ruby golfing tips. In this case you could apply the $<.map{|l|...} is shorter than while l=gets;...;end tip and probably replace puts with $><< (which does not require the extra space).
also, I think .chomp can be removed.
In this case, now that you mention it, I think it's likely very safe to remove, as .to_i will catch that. Good thought. Thanks @w0lf!
You're welcome! Here's a shorter version in which I applied the tips above and a few more: http://ideone.com/BiOvV5. Feel free to post it in your answer if you like it.
Wow, that's a cool approach. Shows me I still have a lot to learn about golfing.
Why not drop the need for d with s[p,w.length+1]="*"+w?
1 byte: "*" -> ?*
@daniero at least the version of ruby I'm using converts ?* to the character code 42, which cannot be added to the string following it.
@PotatoOmeletteSandwich Upgrade your Ruby. 1.8.7 is end-of-lifed! also, you should be able to use the s[int, int] form instead of s[range] for 1 char savings.
Perl, 66 bytes
63 bytes script + 3 bytes for -p
$}||=$"x128;/\s+/,substr$},$',1+length$`,"*$`"}{$_=$};s/\s+$/
/
Nothing too special, utilising the variables $` and $' which are 'before the match' and 'after the match' respectively, instead of splitting the string. I used a $} for the string variable as originally it was saving me a byte, but isn't any more!
Example run:
$perl -p overwritlabels.pl <<< 'Hello 0
World 8
Fizz 3
Buzz 5
PPCG 16
X 9'
*He*F*Buz*Xrld *PPCG
Perl, 65 bytes
62 bytes script + 3 bytes for -p
Another version that prints out each line (for one less byte!). (Yes, I made this because I didn't read the question properly...)
$}||=$"x128;/\s+/;substr$},$',1+length$`,"*$`";$_=$};s/\s+$/
/
Example run:
$perl -p overwritlabels.pl <<< 'Hello 0
World 8
Fizz 3
Buzz 5
PPCG 16
X 9'
*Hello
*Hello *World
*He*Fizz*World
*He*F*Buzzorld
*He*F*Buzzorld *PPCG
*He*F*Buz*Xrld *PPCG
PHP -- 84 bytes
<? foreach(array_chunk(array_slice($argv,1),2) as $p) echo "␣[".($p[1]+1)."G*$p[0]";
^ ESC character (\x1b)
Uses ANSI escape codes to position the cursor (\x1b[XG, featuring the Escape character and X being the 1-based coordinate), followed by the * then the input string for that row. Accepts input on the command line of the form:
php filename.php Heathrow 0 Edinburgh 2 London 4 Liverpool 6 Oxford 8
php filename.php abc 5 d 5 abc 10 ABCDEFGHIJKLMNOPQRSTUVWXYZ 127
Accepts multi-word entries if they're in quotes, since they're command line arguments.
C++11, 95 bytes
Why not?
As a function, receive input as a map<int, string> named v containing the position and the string.
string t(255,' ');for(auto&m:v){int i=m.first;t[i++]='*';for(auto&c:m.second)t[i++]=c;}cout<<t;
Usage
#include <iostream>
#include <map>
using namespace std;
int main(){
map<int,string> v{{0,"Heathrow"},{2,"Edinburgh"},{4,"London"},{6,"Liverpool"},{8,"Oxford"}};
string t(255,' ');for(auto&m:v){int i=m.first;t[i++]='*';for(auto&c:m.second)t[i++]=c;}cout<<t;
}
Check it Running Here
Husk, 13 bytes
Fż|mF(J'*eR'
Try it online!
Takes a list of pairs (coordinate, label) as input. N.B.: there is a space character at the end of the code.
Explanation
Fż|mF(J'*eR'
m For each pair in the input
F apply the following function using the pair members as arguments
R' Repeat a space (coord) time
e put this in a list with the label
J'* and join the strings in the list with "*"
F Fold over the resulting list
ż by zipping strings together
(keeping extra characters in the longer string unchanged)
| with OR (Second argument if truthy else first. Spaces in Husk are falsy)
Japt, 18 bytes
rÈh'*+YÎYÌ}Sp#ÿ)x1
Try it online!
Takes input as an array of [label, x-coordinate]
Explanation:
rÈh'*+YÎYÌ}Sp#ÿ)x1 #
Sp#ÿ # Store 255 spaces as X
r } ) # Do this for each pair in order:
Èh # Overwrite part of X:
YÌ # Starting at index equal to the second item of the pair
'* # Write "*"
+YÎ # Write the first item of the pair
x1 # Remove any remaining whitespace on the right side
Canvas, 9 bytes
H{}0┘*;+╋
Try it here!
Same as my Stax answer, except canvas is better at grid overlaps.
GolfScript, 29 bytes
~""\{~." "*3$\+<"*"+\+.,@>+}/
Try it online!
Stax, 11 8 bytes
┤6╧ß╡⌠░$
Run and debug it
Takes input as a list of pairs [coordinate, label]. Thanks to caird coinheringaahing for the testcases.
Explanation
zsFE'*s+|%
zs push empty list and swap with the input
F for each element,
E push each item onto stack
'*s+ add asterisk to label
Stack: [index,label]
|% embed in the array
| common-pile/stackexchange_filtered |
javafx 8 overlapping layers eventhandling
I have two layers in my program with different elements in each layer. The two layers are overlapping but the elements in the layers are not. I want to show a tooltip when the mouse hovers over a node in each layer but right now the top layer only gets the event.
Below is attached a minimal example:
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
StackPane root = new StackPane();
Pane p1 = new Pane();
Pane p2 = new Pane();
Arc arc = new Arc(150,150,100,100,0,360);
arc.setType(ArcType.CHORD);
arc.setFill(null);
arc.setStroke(Color.BLUE);
arc.setStrokeWidth(20);
Rectangle rectangle = new Rectangle(100,100);
rectangle.setX(100);
rectangle.setY(100);
Tooltip.install(arc, new Tooltip("Semiring"));
Tooltip .install(rectangle,new Tooltip("Rectangle"));
p1.getChildren().add(arc);
p2.getChildren().add(rectangle);
root.getChildren().addAll(p2,p1);
primaryStage.setScene(new Scene(root, 300, 300));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Nothing happens on the rectangle
Use
p1.setPickOnBounds(false);
This essentially means mouse events are only delivered to p1 if the mouse is over a non-transparent pixel in p1. Thus when the mouse is not over the arc, mouse handling is delegated to p2, as required.
Thank you, that was just what I need to do. It is worth noting that it matters which layer the p1.setPickOnBounds(false); is set on. It has to be the outer layer or it doesn't work.
| common-pile/stackexchange_filtered |
Not able to use setState() outside of scaffold in flutter
I have created one method outside the scaffold in the build method but not able to setState() from there.
I have written code like this :
@override
Widget build(BuildContext context) {
//Method that returns alert dialog
method(){
setState(() {
selectedType = newValue;
enableBrand = true;
});
}
//Main scaffold from where i'm calling the alert dialog method
return scaffold()
}
But this doesn't work, the state is not getting updated, so can anyone suggest what is the issue here?
I want to show an AlertDialog on click of a button so i have created a method for that in the build method and trying to setState() from there but it is not working.
Thanks in advance.
Could you maybe share all the code in your build method? Your code doesn't make any sense right now
There is 600 lines of code that's why i have put just these lines
I have added more explanation in the post itself, please check @Er1
if you want to update your dialog box, u can warp your dialog box with stateful builder
can you please show how? @Mrvd
add your dialog box UI code in stateful bulder
void _showDialog() {
showDialog(
context: context,
builder: (context) {
return StatefulBuilder( // StatefulBuilder
builder: (context, setState) {
return AlertDialog(
actions: <Widget>[
],
);
},
);
},
);
}
First of all, is your class extending StatefulWidget?
In the onPressed of your button you could do something like this example.
An AlertDialog can give back a value when popped. I just took the example Alertdialog for now and returned a String.
Then you can set your state with the new value.
onPressed: () async {
var newValue = await showDialog(
context: context,
builder: (c) => AlertDialog(
title: Text('AlertDialog Title'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('This is a demo alert dialog.'),
Text(
'Would you like to approve of this message?'),
],
),
),
actions: <Widget>[
FlatButton(
child: Text('Approve'),
onPressed: () {
Navigator.of(context).pop("YOUR_NEW_VALUE");
},
),
],
));
//newValue now has the value "YOUR_NEW_VALUE"
setState((){
selectedType = newValue;
enableBrand = true;
});
}
| common-pile/stackexchange_filtered |
How to add options to the menu item that is asosiated with your component.
I Have created a component in Joomla 2.5, I have succesfully installed it, and now I need to add some options that will be configured at the menu view. So when a user ads a new menu item to a menu and the menu type is my component, then he can also select some parameters at the menu item view. How can I do this?
It's on the first page of the docs for developing an MVC component for Joomla 2.5:
http://docs.joomla.org/Developing_a_Model-View-Controller_%28MVC%29_Component_for_Joomla!2.5_-_Part_05
To access these params from within your component look at " Accessing the parameters - frontend" on this page:
http://docs.joomla.org/Component_parameters
yep thank you I was also readint his now. I was wondering how I can get the parameter now. I added the parameters that i Needed, but it seems that I cant access them from the view nor from the model for some reason. But anyway thank you I will ask again if I can't find anything else
| common-pile/stackexchange_filtered |
Web scraping (Graph Scraping) with BeautifulSoup
I want to scrape the below web page.
https://stadt-aachen.e2watch.de/details/objekt/175
I want to get the graph of the page for any specific date. I am not understanding which class should I write for the scraping.
I am using the below code but getting empty strings.
import bs4
import requests
from bs4 import BeautifulSoup
r= requests.get('https://stadt-aachen.e2watch.de/details/objekt/175')
soup = bs4.BeautifulSoup(r.text,"xml")
soup.find_all('div',{'class':'highcharts-container '})
what you want to extract actually ?
The graph/chart of the given link.
Welcome to SO. You are using Beatufulsoup for scrapping of web page but graphs are not pure HTML or in other words are rendered from the data. Its not clear from your question whether you are looking for data used to generate the graph or the graph itself which might be in image format.
I want both the data and the image from the graph.
I know I'm late. But I saw your question today and was very interested in finding out how to get the image out of that website, and I worked out a solution.
So first off, the data you want to scrape are <path> tags with multiple values inside a <svg> tag.The <svg> tag can be located by the class.
The content is loaded in dynamically through JavaScript. So I tried multiple libraries and solutions but what works best is Selenium. Selenium is a Web Driver controlled by Python code.
So our plan is to load the content in using selenium and then pass the driver source to BeautifulSoup to scrape it.
Then we store the <svg> tag inside the variable html and pass it to the screenshot() method of hti (Html2Image)
And there you have the graphic from the website. With Selenium you can change the timeframe you want to scrape and get any graphic you want.
import time
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from html2image import Html2Image
#Download and place the Driver in the location you want
PATH = "C:\\Program Files (x86)\\chromedriver.exe"
driver = webdriver.Chrome(PATH)
url = 'https://stadt-aachen.e2watch.de/details/objekt/175'
#This loads the page with the content
driver.get(url)
driver.maximize_window()
time.sleep(5)
#Then you use BS4 to scrape the driver with the loaded graphic
soup = BeautifulSoup(driver.page_source)
driver.quit()
#Here you locate the svg tag and store it in a variable html
graphic = soup.findAll('svg', {'class': 'highcharts-root'})
html = str(model[0])
#This open the html2image object and creates a png from the html in the size of the svg
hti = Html2Image()
hti.screenshot(html_str=html, size=(970,600), save_as='output.png')
Let me know if you have questions or other problems with scraping.
| common-pile/stackexchange_filtered |
Restore Windows Server 2008 R2
Earlier today, I tried to restore my Windows Server 2008 R2 server from a Windows Server backup file. The process it followed (which I had used in the past on Server 2003) was
Do quick load of OS from CD
Restore backup from external drive.
When I went to restore, I didn't see an option to restore entire system. I had to choose volumes, applications, system state etc. I chose system state and the restore completed; however the server bluescreened when it came back up.
My question is, when doing a restore in the way that I described above, do I need to first restore the C drive, then restore the system state?
Any help or suggestion would be greatly appreciated.
Are you simply asking HOW to restore a 2008 server using the built in Windows backup? Technet covers that: http://technet.microsoft.com/en-us/library/494ff831-ddb7-4c50-aa3d-19c8deb84efb
Yes I am since the way I originally tried failed. I was able to restore the server using another method; i.e. Boot from CD and do a repair. Just not sure which is the best method. Thanks for your help.
Per your comment, I'm making this my answer. There isn't a "best" way...so much as there is a preferred method depending on what you are wanting to recover and the scope of the recovery.
Because it appears you are using the built in Windows Backup utility:
You can learn about the various methods to restore your 2008 server here: http://technet.microsoft.com/en-us/library/494ff831-ddb7-4c50-aa3d-19c8deb84efb
Specifically, if you are wanting a full system restore, you can find that info here: http://technet.microsoft.com/en-us/library/cc755163
Bear in mind that when dealing with a domain controller, it is different and you'll need to read the first link and subsequent links about AD/DC restores to fully grasp their implications.
Thank you so much for the posts. I really appreciate it.
| common-pile/stackexchange_filtered |
What is command to look list of redirect rules, iptables
im using command like this :
iptables -t nat -A PREROUTING -p tcp -d <IP_ADDRESS> --dport 4080 -j DNAT --to-destination <IP_ADDRESS>:4088
My question what is command to look all rules in the selected chain. I'm using iptables -L but it doesn't display anything. But, that's command is successfull to redirect.
iptables -L -t nat
use the table name with -t
Thx it works. Then, how to delete the rules?
In the command that you have specified use -D instead of -A .
| common-pile/stackexchange_filtered |
pyalgotrade trouble with exit-order-event (onExitOk)
Struggelig a bit with my trading algo. It seems that the orders cant finish before the next onBars() is called, and the quantities become a mess. Im using the enterLongLimit() to enter a trade, which calls onEnterOk() when it finishes - but im using limitOrder to exit parts of a position based on some technical indicator, and that doesnt seem to call onExitOk().
def onExitOk(self, position):
print("Exit ok", position.getExitOrder().getExecutionInfo().getDateTime())
def onEnterOk(self, position):
print("Enter ok", position.getEntryOrder().getExecutionInfo())
def _closePosition(self, price, qty, reason, date):
print("Closing position with price", price, "and closing qty", qty)
brk = self.getBroker()
shares = brk.getShares(self.instrument) * qty
print("Cash now before sell: ", brk.getCash(self.instrument))
self.info("Sell BTC %s at %s because %s on %s " % (shares, price, reason, date))
self.position = self.limitOrder(self.instrument, price, shares*-1)
print("Cash now after sell: ", brk.getCash(self.instrument))
Execution:
Closing position with price 746.3 and closing qty 0.5
Cash now before sell: 17.423283999999967
Cash now after sell: 17.423283999999967
The cash before and after the limitOrder is the same, so i have to wait for the event to come in. Ideas?
Do you get all the printouts from onEnterOk and onExitOk events? I cannot get those to work for some reason even though my strategy executes 2.5k trades in backtesting through stop and limit orders - whatever code I put into those events does not get executed.
It seems like it depends on which method is used to open a position - for some reason stop, limit and stop-limit orders to not trigger onEnter/onExit events, but enterLong or enterShort do.
I had a similar problem and then after some digging I found that onEnter and onExit events are only triggered when a position is opened using one of the enterLong or enterShort methods. Trades executed with stop, limit or stop-limit orders do not trigger onEnter or onExit events which is a real shame.
This what the comments in the source code say, ie.:
def onEnterOk(self, position):
"""Override (optional) to get notified when the order submitted to enter a position was filled. The default implementation is empty.
:param position: A position returned by any of the enterLongXXX or enterShortXXX methods.
:type position: :class:`pyalgotrade.strategy.position.Position`.
"""
pass
See the strategy class code.
Your limit order should still work as expected even though you do not get the notification.
| common-pile/stackexchange_filtered |
Sylow subgroups of quotient groups
Could somebody explain in detail the steps required to solve this problem?
Let $p$ be a prime dividing $o(G)$. Show that every Sylow $p$-subgroup of $G/K$ is of the form $PK/K$, where $P$ is a Sylow $p$-subgroup of $G$.
I'll sketch some steps for you:
(i) Suppose $|K| = p^a m$ and $|G| = p^{a + b} mn$, where $m$ and $n$ are not divisible by $p$. Then $|G / K| = p^b n$. What is the order of a Sylow $p$-subgroup of $G / K$?
(ii) Show that every subgroup of $G / K$ is of the form $H/K$, where $H$ is some subgroup of $G$ containing $K$. Deduce that any Sylow $p$-subgroup of $G / K$ is of the form $H/K$ for some subgroup $H$ of order $p^{a + b}m$.
(iii) By Sylow's theorems, this $H$ contains a Sylow $p$-subgroup $P$. What is the order of $P$? Convince yourself that $P$ is also a Sylow $p$-subgroup of $G$.
(iv) If you can now show that $ PK = H$, then you are done. Since you already know that $P$ and $K$ are both subgroups of $H$, it is enough (why?) to show that $|PK| = |H|$, i.e. that $|PK| = p^{a+b}m$. But $|P| = p^{a + b}$ and $|K|=p^a m$, and $m$ is not divisible by $p$. Now apply Lagrange's theorem...
Sorry i am weak in mathematics and i dont understand, please explain steps in clearly ..
@Raj Could you please tell me what you already understand and what you don't understand? Also, did you make any progress on this question yourself? What are your thoughts?
I dont understand anything about this question, this question is a assignment for me, i need a solution for this question..and i have a 20 questions more to solve for assignment i forgot mathematics because from 3 years gap please help out tommarow is the last date for submition and if you help me to answer another questions i will send you that questions also if you dont mind send me your mail is i will send through in that mail
Dear @Raj, I'm sorry to hear about your situation, but this website is not an assignment-solving service. However, if you state what have already learnt about Sylow's theorems and what you've tried for this question and where you're stuck, then people will be more than happy to help you out. :)
Could you please suggest me some books for learn mathematics in understanding way...for M.Sc
@Raj I learned this stuff from Dummit and Foote, Abstract Algebra.
How to apply lagranges theorem for this question
| common-pile/stackexchange_filtered |
Featured Questions
There is no section saying 'Featured Questions' in the 'Unanswered Questions Tab'.
How do I find those questions that have active bounties on them?
The "Featured" tab only appears if there are featured questions to show. Currently, I don't think we have any active bounties, which is why the tab isn't there.
Also, as far as I know, the tab appears on the main home page and under "Questions". It doesn't appear in the "Unanswered questions" section.
Now a featured question has come.
| common-pile/stackexchange_filtered |
Changing screen in Skyrim?
So I started Skyrim and I noticed that the screen doesn't fully fit on my TV. I can't find an option to change this though. I have it on Xbox 360 and is there a way to make it fit the screen perfectly?
Go to Settings>System Settings>Display> and play with the setting to see if that works. For most modern TVs the optimal resolution is named 1080i or 1080p depending on what device your using. It can also depend on whether you are using HDMI or AV.
did it work Bucky?
| common-pile/stackexchange_filtered |
integrate $2\int _0^2\:r^2\sqrt{(1-(r-1)^2)} dr$
I have to solve the integral $\int _0^2\:\int _{-arccos\left(r-1\right)}^{arccos\left(r-1\right)}\: r(rcos(\theta)+rsin(\theta)) d\theta dr$. I have to do it in this order specifically, so I can't change it to $drd\theta$ .
I got to $2\int _0^2\:r^2\sqrt{(1-(r-1)^2)} dr$, but I don't know how to continute from here. I have tried to substitute $r-1$ with $sin(p)$, but that didn't seem to work either.
(I'd prefer a hint or suggestion for what kind of technique or subsitution I'm supposed to use here over a complete answer)
If $r-1 = \sin(p)$ then the integral becomes
$$ 2 \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} (\sin(p)+1)^2 \cos^2(p) dp = 2 \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \left[ \sin^2(p)\cos^2(p) + 2\sin(p)\cos^2(p) + \cos^2(p)\right] $$
Integrating the second and third terms should be fairly straight forward (right?). For the first term, we can use $$ \sin^2(p)\cos^2(p) = \frac{1}{4} \sin^2(2p) = \frac{1- \cos(4p)}{8}$$
| common-pile/stackexchange_filtered |
How to Display Hidden Characters While Typing?
How can I configure vim to display hidden characters like tabs or spaces ONLY while those characters are typed? I do not want tabs and/or space replaced with special characters like ">" or "_" when the file is written.
You're quite welcome, dan0! Too bad you didn't stick around for the answer to your question and will probably never even read this comment. :-)
Checkout listchars. This is what I have in my ~/.vimrc:
set list
set listchars=tab:→\ ,extends:»,precedes:«,trail:▒,nbsp:·
Show a right arrow for tabs, a semi-filled block for trailing whitespace, and a middot for non-breaking spaces. This is purely for display; the file does not contain those fancy characters.
Drew Neils' Vimcasts are amazing, take a look at this one. It help me made the transition from Textmate to Vim
http://vimcasts.org/episodes/show-invisibles/
| common-pile/stackexchange_filtered |
Globally asymptotic stable gradient system has unstable point
Given a gradient system
$$\frac{d\theta_1}{dt}=-\sin(\theta_1-\theta_2)$$
$$\frac{d\theta_2}{dt}=-\sin(\theta_2-\theta_1)$$
The system is a gradient system since
$$\frac{d\vec \theta}{dt}=-\nabla V(\vec\theta) = -\nabla(1-\cos(\theta_1-\theta_2))$$
Since the system is invariant by replacing all $\theta_i$ to $\theta_i+\alpha$, this will leads to a continuum of equilibria. To remove this freedom, we fix $\theta_1=0$, then the system becomes
$$\frac{d\theta_2}{dt}=-\sin(\theta_2)$$
It has two equilibrium points $\theta_2=0$ and $\theta_2=\pi$.
The energy function is $V(\theta_2)=-\cos(\theta_2)+1.$
The second derivative of $V(\theta_2)$ is $\cos\theta_2$.
Since the second derivative is negative on $\theta_2=\pi$, it is an unstable equilibrium point.
Since the second derivative is positive $\theta_2=0$, it is a locally asymptotically stable (LAS) equilibrium point.
Since this is a gradient system, only $\theta_2=0$ is locally asymptotically stable, then it is globally asymptotically stable (GAS).
But it is a little counterintuitive in the sense of convexity of energy function: how comes that the energy function is concave on $\theta_2=\pi$, and $\theta_2=0$ is globally asymptotically stable?
For example, let say the figure of an energy function looks like the following
and it is convex on the local minimum, and concave on the local maximum. How come all trajectories will converge to the local minimum?
As illustrated in the figure, trajectories starting from the part behind the local maximum cannot converge to the local minimum.
This is very unclear. What is your problem here? The gradient is defined to be converging to a local minimum or more generally to a point where the gradient is zero. If sufficiently close to the global minimum, it will converge to it. Finally, your system has more than four equilibrium points, it has in fact a continuum of equilibrium point $\theta_1=\theta_2$.
@KBS I think global stable equilibrium point of the system is different from global minimum of $f(x)$. By verifying the second derivative of $f(x)$, we obtain the local stability of the 4 equilibrium points, which gives that only $(0,0)$ is locally asymptotically stable. Since the system is a gradient system, and only $(0,0)$ is stable and all others are unstable, we can conclude that $(0,0)$ is globally asymptotically stable. This is from the perspective of stability theory.
We know that all trajectories will eventually converge to $(0,0)$ by the above stability analysis. But, if we rethink about this fact from perspective of the energy function $f(x)$, it seems not possible that all trajectories will converge to $(0,0)$: since some trajectories will be blocked from converge to it by the concave property of the other state (trajectories near the other state have to climb up to the hill and then downhill, and then converge to $(0,0)$.
Read again what I wrote and also try to understand what a gradient system is and how it evolves on the manifold described by the energy function. Moreover, it is not because one equilibrium is stable and the other unstable, that the stable one is globally stable. You need to spend more time on the analysis of Dynamical Systems. That may be true for certain classes of gradient systems but not for dynamical systems in general.
I just re-edit the description by fixing $\theta_1=0$ to avoid a continuum of equilibria.
$\theta_1$ is a state that evolves over time, you cannot just set it to the value you want.
I just did some simulations and $(0,0)$ is not globally stable as I said. If the difference between the initial value for the state is small enough, both states will converge to the same value which is the average of the initial conditions. That can be proven by linearization. Your whole reasoning is incorrect.
@KBS The system is invariant by replacing all $\theta_i$ to $\theta_i+\alpha$. Thus the rotational symmetry leads to a continuum of equilibria. Setting $\theta_1=0$ is to remove this freedom.
I am sorry but you do not decide what the state at equilibrium will be. If you pick $(0,2)$ as initial condition, the state will converge to (1,1).
@KBS Situation changes by letting $\theta_1=0$. For this new system, it is globally stable at $\theta_2=0$.
Note that this is exactly solvable: if the state starts in $\theta_1 = \theta^* + \delta$, $\theta_2 = \theta^-\delta$, the exact solution is $\theta^ \pm \tan^{-1}(e^{-2t}\tan\delta)$.
@KBS About 'Since all other equilibrium points are unstable, the only stable equilibrium point becomes globally stable.': this can be deduced by the fact that all attractors of gradient systems are fixed points, i.e. trajectories will all converge to a fixed point. In other words, we do not need to bother by other kinds of attractors such as limit cycles and so on.
Since all other equilibrium points are unstable, all trajectories will converge to the only stable equilibrium point, thus it is globally asymptotically stable.
@HJ_dynamics What about this system then? You have a continuum of stable equilibrium points... And do not tell me that you set $\theta_1=0$ because you do not get to choose where the system ends up. The game to pick an initial condition and see where the system goes.
@KBS About this system (without letting $\theta_1=0$), it has a continuum of locally stable equilibrium points $\theta_1=\theta_2$. Other continuum of equilibria $\theta_1=\theta_2+\pi$ and $\theta_1=\theta_2-\pi$ are unstable. Trajectories will eventually converge to one of points lies on $\theta_1=\theta_2$. I don't see any contradiction.. Where arises a contradiction?
As $\dot θ_1+\dot θ_2=0$, the sum is constant and one can replace $θ_2=c-θ_1$ to get a single equation
$$
\dot θ_1=-\sin(2θ_1-c)
$$
This has indeed a stable equilibrium at $2θ_1-c=0$ and unstable equilibria at $2θ_1-c=\pm\pi$, continued with period $2\pi$ on the right side, thus period $\pi$ in $θ_1$.
| common-pile/stackexchange_filtered |
pandas dataframe loop through rows
I have a 6000*5 dataframe which is like:
0 1 2 3 4
0.001 0.020 0.502 0.773 0.332
0.021 0.120 0.202 0.113 0.000
0.001 0.420 0.432 0.003 0.123 ...
Now I want to loop through each of those 6000 rows and compare values in the same row to get the largest element and store column index in a new dataframe. Say, for the first row the largest element should be 0.773, second row should be 0.202, third row be 0.432. So I need a new dataframe like
3 2 2
...
How to approach this question?
am i to infer that you have no prior experience with Python? maybe no prior experience with computer programming in general?
I am new to python, if this were in java it could be quite easy
You can use idxmax() like below.
df['max_col'] = df.idxmax(axis=1)
DataFrame.idxmax(axis=0, skipna=True)
Return index of first occurrence of maximum over requested axis.
NA/null values are excluded.
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html
| common-pile/stackexchange_filtered |
LWJGL - Text's color changes background's color
I have a serious problem with my LWJGL program.
If I set one of my text's colour, the background's color changes, too.
I think I know why, I just put all of the drawing things in an infinite loop, and maybe that's the reason.Can you help me with this? Am I correct with the reason of the problem? If yes, how can I solve that? If not, what do you think, what is the problem?
Here's my code:
The main class:
<!-- language: lang-java -->
public class DoomMain {
public static final int WIDTH = 640;
public static final int HEIGHT = 480;
public static final int SCALE = 1;
private static State state;
public DoomMain() {
try {
Display.setDisplayMode(new DisplayMode(WIDTH*SCALE,HEIGHT*SCALE));
Display.setTitle("Tomco - Doom");
Display.create();
} catch(LWJGLException e) {
e.printStackTrace();
}
while(!Display.isCloseRequested()) {
state = State.MENU;
switch(state) {
case INTRO:
new Intro();
break;
case MENU:
new MainMenu();
break;
case CREDITS:
break;
case GAME:
break;
default:
break;
}
Display.update();
Display.sync(60);
}
Display.destroy();
}
public static void main(String[] args) {
new DoomMain();
}
}
The MainMenu class:
<!-- language: lang-java -->
public class MainMenu {
private Texture background;
private TrueTypeFont doomfont;
private boolean ana = false;
public MainMenu() {
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
glClearColor(0.0f,0.0f,0.0f,0.0f);
glEnable(GL11.GL_BLEND);
glBlendFunc(GL11.GL_SRC_ALPHA,GL11.GL_ONE_MINUS_SRC_ALPHA);
glViewport(0,0,DoomMain.WIDTH,DoomMain.HEIGHT);
glMatrixMode(GL11.GL_MODELVIEW);
glMatrixMode(GL11.GL_PROJECTION);
glLoadIdentity();
glOrtho(0,DoomMain.WIDTH,DoomMain.HEIGHT,0,1,-1);
glMatrixMode(GL11.GL_MODELVIEW);
glShadeModel(GL_SMOOTH);
drawBackground();
drawText();
glDisable(GL_TEXTURE_2D);
}
private void drawBackground() {
try {
background = TextureLoader.getTexture("PNG",new FileInputStream(new File("res/textures/mainmenu/doom_00340461.png")));
} catch (FileNotFoundException e) {
e.printStackTrace();
Display.destroy();
} catch (IOException e) {
e.printStackTrace();
Display.destroy();
}
glBegin(GL_QUADS);
{
glTexCoord2f(0,0);
glVertex2f(0,0);
glTexCoord2f(1,0);
glVertex2f(background.getTextureWidth(),0);
glTexCoord2f(1,1);
glVertex2f(background.getTextureWidth(),background.getTextureHeight());
glTexCoord2f(0,1);
glVertex2f(0,background.getTextureHeight());
}
glEnd();
}
private void drawText() {
Color.white.bind();
try {
InputStream inputStream = ResourceLoader.getResourceAsStream("res/fonts/DooM.ttf");
Font awtFont = Font.createFont(Font.TRUETYPE_FONT,inputStream);
awtFont = awtFont.deriveFont(24f);
doomfont = new TrueTypeFont(awtFont,ana);
} catch(Exception e) {
e.printStackTrace();
}
doomfont.drawString(200,100,"Start new game",Color.red);
}
}
have you tried clearing the color after drawing the string? i think i vaguely remember something like this...
Aside: are you loading the background from a file every time through the loop? That's bound to be very slow. Don't do that. Load it once and cache it.
Simiil: With glClear or glClearColor? I tried glClear(GL_COLOR_BUFFER_BIT) after drawing the string. Still buggy. Thomas: Thanks for the advice. How I can cache it? Please help, I'm beginner in OpenGL.
You have a much bigger problem here though. You create a new MainMenu object every frame. In addition your load your texture and font every single frame. Make the object once and load the resources once, then start rendering stuff. The way you do it now is terribly inefficient.
Why do you need to call Color.white.bind() when you already pass a color to drawString(...)?
First if all : The Color.white.bind() call in your drawText() function is probably what is affecting the background.
Here is a quick and dirty example of how to only load the data once. I've moved data loading to the loadData() function. The DoomMain class is created once after the screen is opened, loadData() is called before the main loop and you call your drawing using menu.draw().
Ideally you would load all the resources you need in one place first, then pass the objects to DoomMain at initialization. You might want to use that texture and font in other places as well.. and you don't want to load it multiple times.
public DoomMain()
{
// Open screen here since we need a context to make textures etc
...
// Make objects for your different parts
MainMenu menu = MainMenu();
menu.loadData(); // <- Loads the texture and font
while(!Display.isCloseRequested())
{
state = State.MENU;
switch(state) {
...
case MENU:
menu.draw();
break;
...
}
Display.update();
Display.sync(60);
}
Display.destroy();
}
MainMenu
public class MainMenu
{
private Texture background;
private TrueTypeFont doomfont;
private boolean ana = false;
public MainMenu() { }
public void loadData()
{
// Load the background texture
try {
background = TextureLoader.getTexture("PNG",new FileInputStream(new File("res/textures/mainmenu/doom_00340461.png")));
} catch (FileNotFoundException e) {
e.printStackTrace();
Display.destroy();
} catch (IOException e) {
e.printStackTrace();
Display.destroy();
}
// Load and initialize the font here
try {
InputStream inputStream = ResourceLoader.getResourceAsStream("res/fonts/DooM.ttf");
Font awtFont = Font.createFont(Font.TRUETYPE_FONT,inputStream);
awtFont = awtFont.deriveFont(24f);
doomfont = new TrueTypeFont(awtFont,ana);
} catch(Exception e) {
e.printStackTrace();
}
}
public void draw()
{
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
glClearColor(0.0f,0.0f,0.0f,0.0f);
glEnable(GL11.GL_BLEND);
glBlendFunc(GL11.GL_SRC_ALPHA,GL11.GL_ONE_MINUS_SRC_ALPHA);
glViewport(0,0,DoomMain.WIDTH,DoomMain.HEIGHT);
glMatrixMode(GL11.GL_MODELVIEW);
glMatrixMode(GL11.GL_PROJECTION);
glLoadIdentity();
glOrtho(0,DoomMain.WIDTH,DoomMain.HEIGHT,0,1,-1);
glMatrixMode(GL11.GL_MODELVIEW);
glShadeModel(GL_SMOOTH);
drawBackground();
drawText();
glDisable(GL_TEXTURE_2D);
}
private void drawBackground()
{
... bind background texture
... draw your quad
}
private void drawText()
{
doomfont.drawString(....);
}
}
Thanks for your help. I changed the code like that, but now, I've got a NullPointerException in the main class. Any ideas why? EDIT: Oh, maybe I know why. Maybe because the images and the fonts are declared in an other function. I mean, I give the "real" pictures and fonts to the variables in the loadData(), and I use them on the drawBackground() and drawText() parts.
Oh, I fixed the NullPointerException, I just forgot to call the menu.loadData(); But there's a new, interesting bug. Instead of a picture in the background, there are some letters and signs, like that: http://oi39.tinypic.com/2ugyx6o.jpg
Do you bind your texture before you draw the quad?
Oh, that was the problem. Thanks. But the main bug is still there. The background's color changes with the text's color :S
Did you remove the Color.white.bind()?
By default, the texture will be multiplied by the current color. As a state machine, the "current color" is whenever you set it last. In your case, when you draw text; when you enter the loop again, that same color is used for the texture.
To simplify the problem, you can reduce the whole drawText routine to just setting the color:
LOOP:
a) draw background
b) set color
results in: ... set color; draw background ...
The glClear function clears the buffers of what is already drawn, but not the color to be used next.
As a solution, you can explicitly change the color just before you draw the texture. glColor3f(1.0f, 1.0f, 1.0f) will produce the texture as is, and any other value will work as a color filter (just as it is now).
Another solution is to change the texture drawing behavior with glTexEnv. Assuming the texture is GL_RGBA, then calling glTexEnv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) works. The linked page contains a table with different settings and their effects.
Thank you for your help with it, but with the help of Grimmy, I solved the problem!
Giving this one points because it addresses the root cause of the issue. I got greedy and solved a couple of other problems as well.
| common-pile/stackexchange_filtered |
"'toolchain' unexpected" in go.mod file
I just recently pulled changes in my project that included the toolchain directive. The issue is that GoLand does not recognize it as a valid directive. The image shows the output from the IDE as well as the red underlining with it; note that I am still able to run everything fine even though this is the case. I suspect it has something to do with syntax highlighting, but honestly I am not sure.
This is the output of go version:
go version go1.22.0 linux/amd64
I have also verified that my GoLand is using 1.22.0 by checking File -> Settings -> Go -> GOROOT.
I have attempted invalidating the cache and restarting the IDE, restarting my machine altogether, and have done some Google searches to see if there are others experiencing the same issue but have yet to find anything.
What version of GoLand are you using? (support for toolchain was added in 2023.2).
For some context, I thought I had downloaded the most recent version of GoLand through the clicky menu, however after seeing that it only brought me to 2023.1.2 I had to manually go to their website and get 2023.3.4 and install that. This fixed the toolchain problem as @Brits mentioned in the comments.
There is likely a way to properly update the GoLand version; admittedly I have not found it and am sticking with what works at the moment.
| common-pile/stackexchange_filtered |
How can I reduce "follow me" ads in adsense for publishers?
On pages I publish, I have adsense display ads, which often seem to show "follow me" or "remarketing" ads (relevant to the user's recent searches) rather than contextual ads (those relevant to the page in question). My ad block in this case is 250x250.
How can I reduce the number of follow me ads, and get more page-relevant ads to show?
This is deep content site, and each page is definitely about a specific topic.
Is there a specific reason you want to do that? Adsense usually shows whatever ads will earn you most.
The integrity of my pages is more important than revenue. The ads compliment the pages in question, providing a commercial insight into the same topics.
I think that there isn't any way to refuse them in Adsense. The "follow me" ads are an option in Adwords and is called "Remarketing".
You can find documentation here:
http://www.google.com/ads/innovations/remarketing.html
So it seems you're using Adsense as a feature of your site and not just as a source of revenue. I would say that's counter-intuitive to the point and purpose of Adsense and software like it. Adsense is working from the wealth of knowledge it has gained about your users and algorithmically finds ads it thinks will get better conversions. Sometimes that means ads relevant to the content of the page, much of the time (in my experience, at least) it means I will see lots of ads for Panama City Beach since Google knows I plan to go there.
Having 100% relevant ads on your page certainly makes sense from the perspective of a content provider. Perhaps there are other products out there (perhaps Google itself could create a spinoff) that would achieve that. But currently Adsense's algorithms don't seem to do that.
Note: AdSense is advertises to publishers for just this use (context relevant ads).
There is no way to block "follow me" ads.
However, I'm not sure that contextual ads inherently have "more integrity". Ads on any subject can be good or bad.
My advice would be to block all the sensitive categories in "Allow & block ads", as these typically worse adverts. Then keep an eye on the ad review center to block anything that looks spammy.
"Follow me" ads are unrelated to my page content. I don't have any sensitive categories: if my page happens to be about alcohol I'd want alcohol ads, not "follow me" ads.
To whoever downvoted, please let me know what is incorrect in the answer.
@Bryce not sure if you misunderstood but "sensitive categories" is an option in Adsense. And I still maintain that even if you could limit it to contextual ads only, there would still be many ads that do not have "integrity".
Mr/Ms DisgruntledGoat: yes I understood. I want ads that match the theme of my pages always, even if that topic is sensitive. I do not want ads for shoes on a page about tampons. The tampon page works best when tampon ads are shown. I might some day have a viagra page, in which case I (yes) want viagra ads.
| common-pile/stackexchange_filtered |
Jumping to a specific point/with a specific offset in assembler for a ARM7 processor
As an assignment for my class i have to implement a code in assembler allowing to jump a specific distance for our arm7 processor we are simulating. My question is, how do we specify the distance we want to jump in code?
I currently have this code :
main :
mov r1, #5
add r0, r2, r3
b test
mov r1, #5
test :
add r0, r2, r3
mov r1, #5
My aim is to be able to jump a few bits to see if my simulations sees that there is a jump and that she calculates correctly the jumping distance
Thank you in advance for any help
b test is already a jump with a specific distance. Isn't that good enough? Anyway, depending on your assembler, instead of using a label you could use an offset from the current location, usually something like $+4 or .+4
Does Thumb mode allow you to add pc, #16 or something? I think you can do that in ARM mode. Unlike most ISAs, the program counter is one of the general-purpose registers in ARM, and you can read and/or write it with most instructions. (Although there are special restrictions about not using PC for some). pc reads as 2 instructions after the current one.
assembly language is specific to the assembler, what assembler are you using (kiel, gnu as, etc)?
I dont think gnu assembler for thumb lets you directly set the offset, it either wants a label or the specific destination address. you can of course do it mathmatically, move pc into a lower register add/subtract the offset, orr with 1 if needed, bx.
@old_timer: In GAS, . is the start of the current instruction. So Jester's b .+4 suggestion gets the assembler to calculate the right encoding to reach that target. (And yes, it's not going to be just +4, so you're right you can't specify the branch offset directly.)
I didnt see that Jester had already said that I tried 8 and +8 not .+8, sorry.
| common-pile/stackexchange_filtered |
How to delete mail form sent folder after sending?
I am currently writing code using vbscript to automate sending of email.
How do I delete that very same email that I sent in the sent folder?
Below is my code:
Dim ToAddress
Dim FromAddress
Dim MessageSubject
Dim MyTime
Dim MessageBody
Dim MessageAttachment
Dim ol, ns, newMail
ToAddress = "site.net"
MessageSubject = "stuff"
MessageBody = "SEND"
MessageAttachment = "C:\Users\Bellere\Desktop\numbers.csv"
Set ol = WScript.CreateObject("Outlook.Application")
Set ns = ol.getNamespace("MAPI")
Set newMail = ol.CreateItem(olMailItem)
newMail.Subject = MessageSubject
newMail.Body = MessageBody & vbCrLf
newMail.RecipIents.Add(ToAddress)
newMail.Attachments.Add(MessageAttachment)
newMail.Send
Any help is appericated!
Thanks!
Add this and this should do for the first occurrence of the sent item from the script
Const olMailItem = 0
Const olFolderSentMail = 5
Dim ToAddress
Dim FromAddress
Dim MessageSubject
Dim MyTime
Dim MessageBody
Dim MessageAttachment
Dim ol, ns, newMail
Dim oMail ' <- added
ToAddress = "site.net"
MessageSubject = "stuff"
MessageBody = "SEND"
MessageAttachment = "C:\Users\Bellere\Desktop\numbers.csv"
Set ol = WScript.CreateObject("Outlook.Application")
Set ns = ol.getNamespace("MAPI")
Set newMail = ol.CreateItem(olMailItem)
newMail.Subject = MessageSubject
newMail.Body = MessageBody & vbCrLf
newMail.RecipIents.Add(ToAddress)
newMail.Attachments.Add(MessageAttachment)
newMail.Send
' Search for the first occurrence of the sent item (Subject and first recipient address)
Set newMail = Nothing
For Each oMail In ns.GetDefaultFolder(olFolderSentMail).Items
If oMail.Subject = MessageSubject And oMail.Recipients(1).Address = ToAddress Then
Set newMail = oMail
Exit For
End If
Next
If Not newMail Is Nothing Then newMail.Delete
This section describes how to use the Microsoft Outlook 11.0 Object Library to Delete messages from the Outlook Inbox in Visual Basic .NET.
Dim tempApp As Outlook.Application
Dim tempSent As Outlook.MAPIFolder
Dim SentItems As Outlook.Items
Dim tempMail As Object
tempApp = CreateObject("Outlook.Application")
tempSent = tempApp.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail)
SentItems = tempSent.Items
Dim DeleteMail As Outlook.MailItem
For Each newMail In SentItems
DeleteMail.Delete()
Next
Note : The most improtant point here to performing all tasks is to add a reference to "Microsoft Outlook object library", In case of
Microsoft Outlook 2000, Add "Microsoft Outlook 9.0 object library"
Microsoft Outlook 2002, Add "Microsoft Outlook 10.0 object library"
Microsoft Outlook 2003, Add "Microsoft Outlook 11.0 object library"
Microsoft Outlook 2007, Add "Microsoft Outlook 12.0 object library"
OP bellere is seeking for VBS code, not VBA. No references - need create Const for the Outlook internal values.
| common-pile/stackexchange_filtered |
Azure SQL DB find all Tables in all Databases
Perhaps this is not even possible but I am interested in seeing all Tables across all my Azure SQL DB Databases.
I can use sys.databases to get a list of Databases and sys.tables to get a list of Tables but cannot seem to figure out the correct combination to return Tables per Database.
Is this possible in Azure using straight T-SQL? If not, is there a practicable alternative?
Please see David Makogon answer https://stackoverflow.com/questions/17584084/get-a-list-of-all-resources-in-my-azure-subscription-powershell-preferably/17585877#17585877
Did you problem has been solved? I am checking to see how things are going there on this issue.
Yes, the problem is solved. Do I understand correctly that the solution you provided uses PowerShell?
@Lee Liu - Please see my response from 2 days ago.
I didn't use PowerShell, i just used C# code about ADO.NET to execute T-SQL command straightly and then display the results on the web page。
We can use straight T-SQL in Azure SQL DB.
According to your requirements, I have some demos for your reference:
Get all tables in a specify data base:
/// <summary>
/// get all Tables in a data base
/// </summary>
/// <param name="DataBaseName">For example: MyDataBase1</param>
/// <returns></returns>
public ActionResult QueryAllTables(string DataBaseName)
{
ContentResult content = new ContentResult();
SqlConnection conn = new SqlConnection("Server=tcp:dotxxxxxxx.database.windows.net,1433;Initial Catalog="+ DataBaseName + ";Persist Security Info=False;User ID=xxxx;Password=xxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;");
try
{
conn.Open();
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "select id,name from sysobjects where xtype='U'";
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
string tableInfo = "id:"+reader[0].ToString()+ " name:"+reader[1].ToString();
content.Content += tableInfo + "\r\n";
}
}
else
{
content.Content = "No Table";
}
}
catch (Exception ex)
{
content.Content = ex.Message;
}
return content;
}
Screenshot of result:
Get all tables from each data base
/// <summary>
/// get all data bases' names
/// </summary>
/// <returns></returns>
public List<string> QueryAllDbName()
{
ContentResult content = new ContentResult();
List<string> list = new List<string>();
using (SqlConnection conn = new SqlConnection("Server=tcp:xxxxxxx.windows.net,1433;Initial Catalog=DotNetAppSqlDb20180410043804_db;Persist Security Info=False;User ID=xxxxx;Password=xxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"))
{
try
{
conn.Open();
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT Name FROM SysDatabases ORDER BY Name";
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
string DbName = reader[0].ToString();
list.Add(DbName);
}
}
else
{
list = null;
}
}
catch (Exception ex)
{
content.Content = ex.Message;
}
}
return list;
}
public ActionResult QueryAllTablesFromEachDb()
{
ContentResult content = new ContentResult();
List<string> DbNames = QueryAllDbName();
foreach (string DbName in DbNames)
{
using (SqlConnection conn = new SqlConnection("Server=tcp:xxxxxxxxx.database.windows.net,1433;Initial Catalog="+ DbName + ";Persist Security Info=False;User ID=xxxxxx;Password=xxxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"))
{
try
{
conn.Open();
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = System.Data.CommandType.Text;
content.Content += "DataBase Name: " + DbName + "\r\n";
command.CommandText = "select id,name from sysobjects where xtype='U'";
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
string tableInfo = " Table id:" + reader[0].ToString() + " Table name:" + reader[1].ToString();
content.Content += tableInfo + "\r\n";
}
}
reader.Close();
}
catch (Exception ex)
{
content.Content = ex.Message;
}
}
}
return content;
}
Screenshot of result:
| common-pile/stackexchange_filtered |
Extracting Related Date and Location from a sentence
I'm working with written text (paragraphs of articles and books) that includes both locations and dates. I want to extract from the texts pairs that contain locations and dates that are associated with one another. For example, given the following phrase:
The man left Amsterdam on January and reached Nepal on October 21st
I would have an output such as this:
>>>[(Amsterdam, January), (Nepal, October 21st)]
I tried splitting the text through "connecting words" (such as "and" for example) and work on part as follows: find words that indicate a location ("at", "in", "from","to" etc.) and words that indicate a date or time ("on", "during" etc.), and join what you find. However, this proved to be problematic, as there are too much words that indicate location and date, and sometimes the basic "find" method cannot distinguish between them.
Assume that I am able to identify a date as such, and given a word that starts with a capital letter, I am able to determine if it is a location or not. The main issue is connecting between them, and making sure they are.
I figured that tools like ntlk and scapy will assist me here, but there isn't enough documentation to help me find an exact solution to this kind of problem.
Any help would be appreciated!
Scapy is not relevant here because it is used to craft packets on a real network, not a neural network.
@RossJacobs Thank you for your input! Removed it from the tags.
This seems like a Named Entity Recognition problem. Following are the steps to the same. For a detailed understanding, please refer to this article.
Download Stanford NER from here
Unzip the zipped folder and save in a drive
Copy the “stanford-ner.jar” from the folder and save it just outside the folder as shown in the image below.
Download the caseless models from https://stanfordnlp.github.io/CoreNLP/history.html by clicking on “caseless” as given below. The models in the first link also work however, the caseless models help in identifying named entities even when they are not capitalized as required by formal grammar rules.
Run the following Python code. Please note that this code worked on a windows 10, 64 bit machine with Python 2.7 version.
Note: Please ensure that all the paths are updated to the paths on the local machine
#Import all the required libraries.
import os
from nltk.tag import StanfordNERTagger
import pandas as pd
#Set environmental variables programmatically.
#Set the classpath to the path where the jar file is located
os.environ['CLASSPATH'] = "<your path>/stanford-ner-2015-04-20/stanford-ner.jar"
#Set the Stanford models to the path where the models are stored
os.environ['STANFORD_MODELS'] = '<your path>/stanford-corenlp-caseless-2015-04-20-models/edu/stanford/nlp/models/ner'
#Set the java jdk path. This code worked with this particular java jdk
java_path = "C:/Program Files/Java/jdk1.8.0_191/bin/java.exe"
os.environ['JAVAHOME'] = java_path
#Set the path to the model that you would like to use
stanford_classifier = '<your path>/stanford-corenlp-caseless-2015-04-20-models/edu/stanford/nlp/models/ner/english.muc.7class.caseless.distsim.crf.ser.gz'
#Build NER tagger object
st = StanfordNERTagger(stanford_classifier)
#A sample text for NER tagging
text = 'The man left Amsterdam on January and reached Nepal on October 21st'
#Tag the sentence and print output
tagged = st.tag(str(text).split())
print(tagged)
#[(u'The', u'O'),
# (u'man', u'O'),
# (u'left', u'O'),
# (u'Amsterdam', u'LOCATION'),
# (u'on', u'O'),
# (u'January', u'DATE'),
# (u'and', u'O'),
# (u'reached', u'O'),
# (u'Nepal', u'LOCATION'),
# (u'on', u'O'),
# (u'October', u'DATE'),
# (u'21st', u'DATE')]
This approach works for a majority of the cases.
Brilliant, thank you! Is there any way to locally add locations for this Stanford DB? Sometimes I work with extreme cases - for example, small, unknown villages, not country names (e.g. Nepal) - and given the fact that I can recognize a location and such, I want that the above script will also recognize it as a location when tagging.
The named entities are recognized based on features. They do not look for exact words. On one hand this is good because it doesn't matter if the name of a person is American or Nepali. While on the other hand, since it is a generalized model, it will not identify some obvious names that humans can identify. An approach that worked for the author is to use a look up list of names and also deploy Stanford NER on top of it. Thus some ensemble approach can be used.
| common-pile/stackexchange_filtered |
How does electron-forge/publisher-github work?
I have my created my github token and set GITHUB_TOKEN value in my env, but I get to the "distributables" step which is strangely misspelled and then it dies. Its like its looking for a release version 1.0.2 which does not exist. I assume this publish action will create the release? Its very unclear how this works from the docs.
✔ Loading configuration
✔ Making a squirrel distributable for win32/x64 [1m17s]
✔ Running postMake hook
› Artifacts available at: ..\out\make
❯ Publishing distributables
✖ [publisher-github] Running the publish command
› Not Found
› Searching for target release: v1.0.2
An unhandled rejection has occurred inside Forge:
HttpError: Not Found
at ...console\node_modules\@octokit\request\dist-node\index.js:86:21
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
my repo is public, not sure what else I need to do here? The docs really don't provide much detail. https://www.electronjs.org/docs/latest/tutorial/tutorial-publishing-updating
TY!
I was confused about the name and owner fields because the documentation does not fully explain that if you are using an org, then name should be the org name which was my issue here.
publishers: [
{
name: '@electron-forge/publisher-github',
config: {
repository: {
owner: 'MyOrg',
name: 'my-repo'
},
prerelease: false,
draft: true
}
}
]
| common-pile/stackexchange_filtered |
How to open a VBScript file with a variable?
I'm starting a VBScript sometimes from a Windows batch file:
FOR /F %%i IN (list.txt) DO vbscript.vbs
and I want to receive the %%i variable in the VBScript.
Run the VBScript with %%i as its argument:
FOR /F %%i IN (list.txt) DO vbscript.vbs %%i
and assign the argument to a variable inside the VBScript:
var = WScript.Arguments(0)
| common-pile/stackexchange_filtered |
Implement Angular Caching conditionally on requests
Implement Caching in Angular with interceptor only for a few requests & not every request conditionally through a boolean.
I have been checking for online solutions about caching only few requests and not all. Sadly there's not any apt solution for this purpose.
Hence I decided to write one very simple Caching methodology to cache specific requests.
This can be done by below:
Create a cache.interceptor & cache.service like below and add it to the providers of app.module like so:
providers:[
CacheService,
{ provide: HTTP_INTERCEPTORS, useClass: CachingInterceptor, multi: true }]
CachingInterceptor code: The interceptor will only cache requests when it sees a particular header('cache-response') set by your services that make the http call.
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
// Add the service we created in Step 1
import { of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { CacheService } from './cache.service';
@Injectable()
export class CachingInterceptor implements HttpInterceptor {
constructor(private readonly cacheService: CacheService) {
}
intercept(req: HttpRequest, next: HttpHandler): Observable> {
// Don't cache if it's not a GET request
if (req.method !== 'GET') {
return next.handle(req);
}
// delete cache if no header is set by service's method
if (!req.headers.get('cache-response')) {
if (this.cacheService.cacheMap.get(req.urlWithParams)) {
this.cacheService.cacheMap.delete(req.urlWithParams);
}
return next.handle(req);
}
// Checked if there is cached data for this URI
const cachedResponse = this.cacheService.getFromCache(req);
if (cachedResponse) {
// In case of parallel requests to same URI,
// return the request already in progress
// otherwise return the last cached data
return (cachedResponse instanceof Observable) ? cachedResponse : of(cachedResponse.clone());
}
// If the request of going through for first time
// then let the request proceed and cache the response
return next.handle(req)
.pipe(tap(event => {
if (event instanceof HttpResponse) {
this.cacheService.addToCache(req, event);
}
}));
}
}
CacheService Code: This service is used to add/get from cache.
import { HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class CacheService {
cacheMap = new Map(null);
getFromCache(req: HttpRequest): HttpResponse | undefined {
const url = req.urlWithParams;
const cached = this.cacheMap.get(url);
if (!cached) {
return undefined;
}
return (this.cacheMap.get(url)).response;
}
addToCache(req: HttpRequest, response: HttpResponse): void {
const url = req.url;
const entry = { url, response, addedTime: Date.now() };
this.cacheMap.set(url, entry);
}
}
In your services:
getMethod(int param1, cache = false): any {
let headers: HttpHeaders;
if (cache) {
headers = new HttpHeaders({ 'cache-response': 'true' });
}
return this.http.get(
'http://apiUrl',
{ headers }
);
}
And thats it. You have an interceptor that cache's only requests that have a header set.
Implement Caching in Angular with interceptor only for a few requests & not every request conditionally through a boolean.
I have been checking for online solutions about caching only few requests and not all. Sadly there's not any apt solution for this purpose.
Hence I decided to write one very simple Caching methodology to cache specific requests.
This can be done by below:
Create a cache.interceptor & cache.service like below and add it to the providers of app.module like so:
providers:[
CacheService,
{ provide: HTTP_INTERCEPTORS, useClass: CachingInterceptor, multi: true }]
CachingInterceptor code: The interceptor will only cache requests when it sees a particular header('cache-response') set by your services that make the http call.
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
// Add the service we created in Step 1
import { of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { CacheService } from './cache.service';
@Injectable()
export class CachingInterceptor implements HttpInterceptor {
constructor(private readonly cacheService: CacheService) {
}
intercept(req: HttpRequest, next: HttpHandler): Observable> {
// Don't cache if it's not a GET request
if (req.method !== 'GET') {
return next.handle(req);
}
// delete cache if no header is set by service's method
if (!req.headers.get('cache-response')) {
if (this.cacheService.cacheMap.get(req.urlWithParams)) {
this.cacheService.cacheMap.delete(req.urlWithParams);
}
return next.handle(req);
}
// Checked if there is cached data for this URI
const cachedResponse = this.cacheService.getFromCache(req);
if (cachedResponse) {
// In case of parallel requests to same URI,
// return the request already in progress
// otherwise return the last cached data
return (cachedResponse instanceof Observable) ? cachedResponse : of(cachedResponse.clone());
}
// If the request of going through for first time
// then let the request proceed and cache the response
return next.handle(req)
.pipe(tap(event => {
if (event instanceof HttpResponse) {
this.cacheService.addToCache(req, event);
}
}));
}
}
CacheService Code: This service is used to add/get from cache.
import { HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class CacheService {
cacheMap = new Map(null);
getFromCache(req: HttpRequest): HttpResponse | undefined {
const url = req.urlWithParams;
const cached = this.cacheMap.get(url);
if (!cached) {
return undefined;
}
return (this.cacheMap.get(url)).response;
}
addToCache(req: HttpRequest, response: HttpResponse): void {
const url = req.url;
const entry = { url, response, addedTime: Date.now() };
this.cacheMap.set(url, entry);
}
}
In your services:
getMethod(int param1, cache = false): any {
let headers: HttpHeaders;
if (cache) {
headers = new HttpHeaders({ 'cache-response': 'true' });
}
return this.http.get(
'http://apiUrl',
{ headers }
);
}
And thats it. You have an interceptor that cache's only requests that have a header set.
| common-pile/stackexchange_filtered |
Outlook password encoding for email services (IMAP, SMTP)
I’m trying to make sense of how different mail clients log onto IMAP and SMTP
services. There are the normal ones and then there is Outlook.
Outlook seems to unconditionally encode passwords as Latin-1; when I enter the
password tösttöst it logs onto the server with the bytes
74f6737474f67374. (Thunderbird is smarter: it attempts UTF-8 first
(74c3b6737474c3b67374) and, if that fails, retries in Latin-1.)
The underlying Windows system is set to a German locale and translation
so Latin-1. Hence my questions:
What determines the encoding Outlook uses for passwords?
What encoding do other locales use, say a Japanese or Kannada localization
of Windows and/or Office?
Is there a simple (as in: non-technical users can do it by following a
step-by-step guide) way of forcing UTF-8?
If not, can Outlook be made to fall back on UTF-8 like Thunderbird does?
The rationale for UTF-8 (or any consistent universal encoding!) is that I’d
like to avoid blowing up the server side password db with entries for every
possible encoding that customers might be using implicitly.
Are you seeing this during SASL PLAIN or during SASL LOGIN? The former is required to be UTF-8 by spec (so Outlook using Latin1 for PLAIN would be a bug), while the latter is Microsoft's "whatever we feel like using".
@user1686: For both login and plain. Even if I configure cyrus and postfix to only advertise PLAIN, Outlook invariably uses the single-byte encoding. FWIW I surveyed some freemail providers. Gmail disallows non-ASCII passwords altogether. GMX allows arbitrary Unicode in passwords; their imapd accepts both UTF-8 and Latin-1 encoded creds iff they use the Latin-1 subset of Unicode. This does not however work for non-Latin-1 encodings, e. g. a password containing Greek codepoints can only be used as UTF-8, not ISO 8859-7.
Even weirder, Outlook will encode a non-Latin1 password with completely useless codepoints: the string töstτεστ arrives as 74f673743f3f3f3f … At this point I’m close to declaring it a lost cause.
So I tried it out and installed the Greek language pack of Office. All language settings in Office are now set to Greek. No observable change. When I enter the password ΤΕΣΤτεστ for say SMTP, Outlook sends 3f3f3f3f3f3f3f3f to the server. This is just bizarre.
| common-pile/stackexchange_filtered |
Searching google news articles Python
im currently thinking about writing about a script which is looking out for new articles from google news search.
So I want to download the first 10-20 articles and safe it into a folder.
Best would be only the main text not the whole html file.
So as an example:
Searchterm "FC Barcelona"
Folder "01.01.2020" articles in here
What is the actual question?
| common-pile/stackexchange_filtered |
Ruby cronjob not working with RVM
According to the RVM docs
/home/vagrant/.rvm/wrappers/ruby-2.1.3@global/ruby /home/vagrant/workspace/crons/Test.rb
should work.
When I punch this line into my console it executes the script. However the crontab line
* * * * * /home/vagrant/.rvm/wrappers/ruby-2.1.3@global/ruby /home/vagrant/workspace/crons/Test.rb
which should run it every minute, does nothing.
Suggestions?
OS: Ubuntu 14.04 LTS
try adding sudo -u vagrant to the command line
the command line works fine but the cronjob doesn't do anything
I believe the cronjob fails to run the ruby, since the process is run as root (unless told otherwise), and my guess is that root doesn't have ruby installed. by adding sudo -u vagrant you run the process with the correct user, and it might work better.
I made this wrapper shell script
#!/bin/bash
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
ruby /path/to/Test.rb
and my crontab has
1 4 * * * /bin/bash -l -c '/path/to/wrapper.sh'
it works wonderfully now
| common-pile/stackexchange_filtered |
Can't read and write files fast enough for my script to recognize changes
Im writing a script that will eventually be able to tweet form a twitter account when my favourite YouTuber Casey Neistat uploads a new video. However, in order to do that, I wrote a program that (should) be able to compare a 'output.txt' file of all the links to his previous videos to a new one when it recognizes that the previous list of YouTube links does not include a recently uploaded video. I made two methods, one called 'mainloop' that runs over and over to see if a previous list of all Casey Neistat's videos is the same as a string of new links retrieved from the method 'getNeistatNewVideo'. However the problem i'm having, is that once the program recognizes a new video, it goes to the method 'getNewURL' that will take the first link recorded in the 'output.txt' file. But when I say to print this new URL, it says there is nothing there. My hunch is that this is because python is not reading and writing to the output.txt file fast enough, however I may be wrong.
My code is as follows:
import bs4
import requests
import re
import time
import tweepy
'''
This is the information required for Tweepy
CONSUMER_KEY =
CONSUMER_SECRET =
ACCESS_KEY =
ACCESS_SECRET =
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
End of Tweepy Information
'''
root_url = 'https://www.youtube.com/'
index_url = root_url + 'user/caseyneistat/videos'
def getNeistatNewVideo():
response = requests.get(index_url)
soup = bs4.BeautifulSoup(response.text)
return [a.attrs.get('href') for a in soup.select('div.yt-lockup-thumbnail a[href^=/watch]')]
def mainLoop():
results = str("\n".join(getNeistatNewVideo()))
past_results = open('output.txt').read()
if results == past_results:
print("No new videos at this time")
else:
print("There is a new video!")
print('...')
print('Writing to new text file')
print('...')
f = open("output.txt", "w")
f.write(results)
print('...')
print('Done writing to new text file')
print('...')
getNewURL()
def getNewURL():
url_search = open('output.txt').read()
url_select = re.search('(.+)', url_search)
print("New Url found: " + str(url_select))
while True:
mainLoop()
time.sleep(10)
pass
How do you know that slow I/O is the issue? How's your main loop running? Infinitely or triggered by some push event? Does it pause? How large are the output files? Is string compare the culprit?
It runs infinitely. My apologies for a not-so-detailed post, I am very new to programming.
Ah just noticed you pause every 10 seconds. So 10s = 0s in latency of your method. Now how much time reading a page takes in your system? BSoup is also engaged in parsing the long youtube page everytime... such a page takes 5-10s just for downloading and parsing for my pc
How much time is it currently taking? Did you try changing that 10 second to some other value?
You likely need to close the file after writing to it. That is, after f.write(results), put a f.close(). Even better, look into opening files with a so-called "context manager", also called a "with-statement". This will automatically close the file for you.
Turns out the file did need f.close() after it to work properly. Thanks jme!
Ahh perfect! Even I didn't see that - and even I keep forgetting to close the file handle...
You never close the files and that may be the problem. For instance, in mainLoop() you should have:
f = open("output.txt", "w")
f.write(results)
f.close()
or even better:
with open('output.txt', 'w') as output:
output.write(results)
In general, it's a good idea to use the with statement in all places where you open a file (even if it's in 'r' mode) as it automatically will take care of closing the file and it also makes it clear which section of the code is working on/with the file at a given time.
| common-pile/stackexchange_filtered |
unable to update wget version
I want to update my wget version to 1.22 which is currently 1.19 using the command :
curl -O https://ftp.gnu.org/gnu/wget/wget-1.21.tar.gz
but getting following error:
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
curl: (35) OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to ftp.gnu.org:443
Doesn't seem to work at all.
... why are you trying to update wget to 1.22 by downloading the source code? And if you have to use the source code, why are you trying to download 1.21 instead of 1.22?
Unless you have an overwhelmingly important reason to use 1.22 over the 1.19 you already have, just stick to the version your distribution provides and wait for it to update. If the maintainers are competent, they'll have backported any actual security issues.
@Shadur I want to upgrade my curl version and to do that i need to upgrade the wget version
@Aviator no, that is factually wrong. And you definitely will render your system inoperable if you simply replace the installed libcurl with a different version, so this whole endeavour seems very ill-advised
Sincere advice: Don't. Wait for your distribution's maintainers to package the update. Judging by the questions you're asking and the reasons you're giving, you do not know nearly enough to effectively update manually and you're going to drastically wreck your system if you try.
| common-pile/stackexchange_filtered |
using a media query to only target tablet and dektop
I am trying to use the NOT operator in media queries
like this
.media{
@media screen and not (max-width: 600px){
display: flex;
flex-direction: row;
align-items: stretch;
}
}
but its not working, i am getting an error, any clue anyone
You should do this:
@media screen :not(media) (max-width: 600px){
display: flex;
flex-direction: row;
align-items: stretch;
}
its not compiling in .scss, i tried it gives me an error
| common-pile/stackexchange_filtered |
changing value 0/nan to max distance (urg/hokuyo node)
Trying to map a quite big open space but some values returned from the node is 'nan' which i suspect are areas which has no obstacle or whatsoever at max distance. How can i turn this 'nan' into a defined value so gmapping can mark it as free space?
Originally posted by charkoteow on ROS Answers with karma: 121 on 2015-01-09
Post score: 1
Are you using the urg_node or the hokuyo_node? The lasers send error codes telling what types of erroneous readings they are getting. The urg_node turns all error readings into NaN, but the hokuyo_node turns errors that are reported as "outside of max distance" into INF. Check out this chunk of code from the hokuyo_node to see where they are setting INF values. Having INF values will allow you to specifically know that there are no objects in range, then you could use a LaserScanRangeFilter to move all INF values to a max_range+1 value. Then you can use ~maxRange and ~maxUrange params in gmapping to properly handle these readings.
In summary, I've had much better luck with hokuyo_node than urg_node for specifically the reason you are describing.
Originally posted by jarvisschultz with karma: 9031 on 2015-01-09
Post score: 4
Comment by charkoteow on 2015-01-09:
played with the filters. amazing. it's working now. thank you very much.
Comment by charkoteow on 2015-01-09:
edit: i was using the urg_node before. going to use hokuyo_node from now on since it can support the old uhg-08lx
jarvisschultz' answer above is right, but for those who want an example, a starting point for me was changing from this
<launch>
<node name="pioneer_driver" pkg="p2os_driver" type="p2os_driver">
</node>
<node name="hokuyo_node" pkg="hokuyo_node" type="hokuyo_node">
</node>
<node pkg="tf" type="static_transform_publisher" name="laser_broadcaster" args="0.1 0 0.1397 0 0 0 1 base_link laser 100" />
<node pkg="tf" type="static_transform_publisher" name="camera_broadcaster" args="0.1 0 0.1397 0 0 0 1 base_link camera_link 100" />
</launch>
to this
<launch>
<node name="pioneer_driver" pkg="p2os_driver" type="p2os_driver">
</node>
<node name="hokuyo_node" pkg="hokuyo_node" type="hokuyo_node">
</node>
<node pkg="laser_filters" type="scan_to_scan_filter_chain" name="laser_filter">
<rosparam command="load" file="[path]/hokuyo_config.yaml" />
<remap from="base_scan" to="scan" />
</node>
<node pkg="tf" type="static_transform_publisher" name="laser_broadcaster" args="0.1 0 0.1397 0 0 0 1 base_link laser 100" />
<node pkg="tf" type="static_transform_publisher" name="camera_broadcaster" args="0.1 0 0.1397 0 0 0 1 base_link camera_link 100" />
</launch>
with [path]/hokuyo_config.yaml like;
scan_filter_chain:
- name: range
type: LaserScanRangeFilter
params:
lower_threshold: 0.2
upper_threshold: .inf
See http://answers.ros.org/question/209018/using-laser_filters-to-convert-inf-readings-to-max_range-1-from-hokuyo/ and http://answers.ros.org/question/208992/changing-value-of-nan-in-urg_node-to-max-distance/ .
Originally posted by Will Chamberlain with karma: 56 on 2017-06-01
This answer was NOT ACCEPTED on the original site
Post score: 1
| common-pile/stackexchange_filtered |
SQL Server : UPDATE, SET with apostrophe in data
The update statement below is throwing an error because of the ' within the ''
UPDATE Table
SET [Company Name] = 'O'Donald Media Inc'
WHERE [Company Name] = 'O'Donald Media Inc'
Does anyone have a way to handle this?
Thanks
When writing SQL by hand, use 'O''Donald Media Inc' for the string syntax. The '' sequence in a SQL string literal is a special encoding for a single apostrophe.
However, if done programmatically (ie. from code), use placeholders.
How do I escape a single quote in SQL Server?
SQL injection on INSERT
| common-pile/stackexchange_filtered |
'API' object has no attribute 'search' using Tweepy
I am trying to scrape Twitter profiles for a project I am doing. I have the following code
from tweepy import OAuthHandler
import pandas as pd
"""I like to have my python script print a message at the beginning. This helps me confirm whether everything is set up correctly. And it's nice to get an uplifting message ;)."""
print("You got this!")
access_token = ''
access_token_secret = ''
consumer_key = ''
consumer_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
tweets = []
count = 1
"""Twitter will automatically sample the last 7 days of data. Depending on how many total tweets there are with the specific hashtag, keyword, handle, or key phrase that you are looking for, you can set the date back further by adding since= as one of the parameters. You can also manually add in the number of tweets you want to get back in the items() section."""
for tweet in tweepy.Cursor(api.search, q="@BNonnecke", count=450, since='2020-02-28').items(50000):
print(count)
count += 1
try:
data = [tweet.created_at, tweet.id, tweet.text, tweet.user._json['screen_name'], tweet.user._json['name'], tweet.user._json['created_at'], tweet.entities['urls']]
data = tuple(data)
tweets.append(data)
except tweepy.TweepError as e:
print(e.reason)
continue
except StopIteration:
break
df = pd.DataFrame(tweets, columns = ['created_at','tweet_id', 'tweet_text', 'screen_name', 'name', 'account_creation_date', 'urls'])
"""Add the path to the folder you want to save the CSV file in as well as what you want the CSV file to be named inside the single quotations"""
df.to_csv(path_or_buf = '/Users/Name/Desktop/FolderName/FileName.csv', index=False)
however, I keep getting the error "API" object has no attribute "search" from the line "for tweet in tweepy.Cursor(api.search, q="@BNonnecke", count=450, since='2020-02-28').items(50000):" I am not really sure why and don't know how to resolve this issue.
Thanks so much!
| common-pile/stackexchange_filtered |
SetWindowsHookEx is injecting 32-bit DLL into 64-bit process and vice versa
I've been working on an application that requires monitoring thread specific mouse activity (WH_MOUSE) on another process and encountered something very curious.
After finding out that this is not possible via exclusively managed code if I don't want to use WH_MOUSE_LL and that I'd need a native DLL export to inject itself in the target process, I set out and created it in C++ according to what scattered documentation I could find on the subject and then tried using it to hook into Notepad.
Although according to GetLastWin32Error the injection succeeded, I was not getting notified of mouse events. After nearly giving up and going for the low level global hook option, I re-read the "Remarks" section of this article which made me suspect that the problem may be because of the "bitness" of my code vs notepad:
A 32-bit DLL cannot be injected into a 64-bit process, and a 64-bit
DLL cannot be injected into a 32-bit process. If an application
requires the use of hooks in other processes, it is required that a
32-bit application call SetWindowsHookEx to inject a 32-bit DLL into
32-bit processes, and a 64-bit application call SetWindowsHookEx to
inject a 64-bit DLL into 64-bit processes.
However, both my native DLL and managed application were compiled as x64, and I was trying to hook into the 64-bit version of notepad, so it should've worked fine, but I took a shot in the dark anyway and went into the SysWOW64 folder and opened the 32-bit Notepad from there, tried hooking in again and this time the hook worked beautifully!
Curiously, I then recompiled both my native DLL and managed app as x86 and tested it it against the 32-bit Notepad and it didn't work, but it worked on my normal 64-bit Notepad!
How am I possibly seem to be able to inject a 32-bit DLL into a 64-bit process and vice versa!
Although my original problem has been solved and I can continue with my app's development, the curiosity as to why I'm observing this strange inverse behavior from SetWindowsHookEx is driving me insane, so I really hope someone will be able to shed some light on this.
I know this a lot of talk and no code, but the code for even a sample app is rather large and comes in both managed and unmanaged flavors, however I'll promptly post any piece of the code you think might be relevant.
I've also created a sample app so you can test this behavior yourself. It's a simple WinForms app that tries to hook into Notepad and displays its mouse events:
http://saebamini.com/HookTest.zip
It contains both an x86 version and an x64 version. On my machine (I'm on a 64-bit Windows 7), the x86 version only works with 64-bit Notepad, and the x64 version only works with 32-bit Notepad (from SysWOW64).
UPDATE - Relevant Bits of Code:
C# call to the unmanaged library:
public SetCallback(HookTypes type)
{
_type = type;
_processHandler = new HookProcessedHandler(InternalHookCallback);
SetCallBackResults result = SetUserHookCallback(_processHandler, _type);
if (result != SetCallBackResults.Success)
{
this.Dispose();
GenerateCallBackException(type, result);
}
}
public void InstallHook()
{
Process[] bsProcesses = Process.GetProcessesByName("notepad");
if(bsProcesses.Length == 0)
{
throw new ArgumentException("No open Notepad instance found.");
}
ProcessThread tmp = GetUIThread(bsProcesses[0]);
if (!InitializeHook(_type, tmp.Id))
{
throw new ManagedHooksException("Hook initialization failed.");
}
_isHooked = true;
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int GetWindowThreadProcessId(IntPtr hWnd, IntPtr procid);
// 64-bit version
[DllImport("SystemHookCore64.dll", EntryPoint = "InitializeHook", SetLastError = true,
CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.Cdecl)]
private static extern bool InitializeHook(HookTypes hookType, int threadID);
[DllImport("SystemHookCore64.dll", EntryPoint = "SetUserHookCallback", SetLastError = true,
CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.Cdecl)]
private static extern SetCallBackResults SetUserHookCallback(HookProcessedHandler hookCallback, HookTypes hookType);
C++:
HookProc UserMouseHookCallback = NULL;
HHOOK hookMouse = NULL;
HINSTANCE g_appInstance = NULL;
MessageFilter mouseFilter;
bool InitializeHook(UINT hookID, int threadID)
{
if (g_appInstance == NULL)
{
return false;
}
if (hookID == WH_MOUSE)
{
if (UserMouseHookCallback == NULL)
{
return false;
}
hookMouse = SetWindowsHookEx(hookID, (HOOKPROC)InternalMouseHookCallback, g_appInstance, threadID);
return hookMouse != NULL;
}
}
int SetUserHookCallback(HookProc userProc, UINT hookID)
{
if (userProc == NULL)
{
return HookCoreErrors::SetCallBack::ARGUMENT_ERROR;
}
if (hookID == WH_MOUSE)
{
if (UserMouseHookCallback != NULL)
{
return HookCoreErrors::SetCallBack::ALREADY_SET;
}
UserMouseHookCallback = userProc;
mouseFilter.Clear();
return HookCoreErrors::SetCallBack::SUCCESS;
}
return HookCoreErrors::SetCallBack::NOT_IMPLEMENTED;
}
int FilterMessage(UINT hookID, int message)
{
if (hookID == WH_MOUSE)
{
if(mouseFilter.AddMessage(message))
{
return HookCoreErrors::FilterMessage::SUCCESS;
}
else
{
return HookCoreErrors::FilterMessage::FAILED;
}
}
return HookCoreErrors::FilterMessage::NOT_IMPLEMENTED;
}
static LRESULT CALLBACK InternalMouseHookCallback(int code, WPARAM wparam, LPARAM lparam)
{
if (code < 0)
{
return CallNextHookEx(hookMouse, code, wparam, lparam);
}
if (UserMouseHookCallback != NULL && !mouseFilter.IsFiltered((int)wparam))
{
UserMouseHookCallback(code, wparam, lparam);
}
return CallNextHookEx(hookMouse, code, wparam, lparam);
}
Since your problem is about the hooking, show the code setting the hook, and the hook itself (where you get the mouse events).
@ElderBug, thanks for your interest. I've updated the question with relevant bits of code.
My best guess about your problem :
The Windows hook system is able to hook both 32-bit and 64-bit application, from any bitness. The thing is, as you pointed, you can't inject a DLL into an application with the wrong bitness. To make this work, Windows will normally inject the DLL if it can, but if it can't, it will setup a callback that use the hooking application message loop. Since the message loop is handled by the OS, it is used to make a call from different bitness.
In your case, the only thing that work is the message loop way. And there is a good reason for that : your 64-to-64 and 32-to-32 calls have no chance to succeed, because the hook is in the injected DLL, that is, in a different process than your application.
Nothing happens in your case because your UserMouseHookCallback stay to NULL. Indeed, the call to SetUserHookCallback() is done in the application DLL instance, but UserMouseHookCallback is unchanged in the target DLL instance. Once injected, the DLL is in a different process, and should be considered as such. You have to find another way to call back the application (maybe post a message, like in the 32-to-64 case, and/or make use of shared sections).
To test this, put something like MessageBox() in InternalMouseHookCallback(). The box should appear even in 64-to-64 and 32-to-32.
Are you saying that this approach is fundamentally wrong and since my application and the target process will each have their own instance of the DLL, setting the callback (or any other field for that matter) before injecting the DLL will be lost once the DLL is in the target process? Is there a way that I can make this assignment persist so the injected DLL is able to call my application directly?
@SaebAmini DLL loading is not like a fork(), you don't carry anything from the previous process. It doesn't make any sense, because there is no previous process, just a DLL being loaded. Imagine if your program loading user32.dll inherited the space from some random process. You can make data persist between instance with shared sections, but it won't help you since you can't make a call between processes, since they are in different virtual spaces.
I see, that makes sense, just like state isn't shared between different consumers of a library, that'd be crazy, and the target process is really just another consumer. I think you have answered both parts of my question, thanks for a great answer :) now I have to find a way to make the DLL notify my app regardless of where it is.
@SaebAmini There are many ways for inter-process communication. None of them are as simple as making a call, so you have to choose the best fit for you. One time in this case I used a named Event, to which you can add a shared section to pass data.
@SaebAmini For light and easy IPC between processes, take a look at WM_COPYDATA. Very handy!
@manuell thanks, I'll have a look next time I have to venture into these murky waters :)
| common-pile/stackexchange_filtered |
Get value for each day in month
I have a table :
+--------------+
| stat |
+--------------+
| date |
| onlineUsers |
| messagesSent |
+--------------+
I gather statistics every 10 minutes and save them to db. How can I get date, max(OnlineUsers), sum(messagesSent) for each day in period of time with single sql query?
This is a pretty basic aggregation query. If you are using SQL, you should know the basics and group by is a basic.
Easiest way, I think, is creating some function to generate query with SELECT * WHERE DATE(\date`) = DATE(`every_day_in_period`)`. But I understand that it is wrong.
As simple as :
SELECT date, MAX(OnlineUsers), SUM(messagesSent)
FROM stat
WHERE date BETWEEN '2014-05-01' AND '2014-05-31'
GROUP BY date
In this case it'll return all rows from table for this period I think, but I need only 30 with summed information for day. Column Date has datetime datatype and keeps not only date but time also.
ok, expanding your idea with DATE(date) i get my information
General problem in this situation is that not all the time periods have any data. Hence you get a gap. For example if you wanted to know the number of people who logged on to a system each day of the month you could do:-
SELECT logon_date, COUNT(*)
FROM logon_table
GROUP BY logon_date
If nobody had logged on one day then that date would be missing while you probably want that date with a count of 0. This problem becomes really obvious when you try a draw a graph with the results.
Solution is to generate a range of all the basic unit and then join that against the actual data.
For example:-
SELECT aDate, MAX(OnlineUsers), SUM(messagesSent)
FROM
(
SELECT DATE_ADD('2014-05-01', INTERVAL units.i + 10 * tens.i DAY) AS aDate
FROM (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
CROSS JOIN (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
)
LEFT OUTER JOIN stat
ON sta.`date` = sub1.aDate
WHERE aDate BETWEEN '2014-05-01' AND '2014-05-31'
GROUP BY aDate
This is using a couple of sub queries to generate all the numbers from 0 to 99 and adding that to the start date (you could add a smaller number, this is just for convenience). The real data is then left joined to this list of dates, and from the results of that you can use the aggregate functions to get the details you want.
You can easily expand this idea for different time period (eg, the hours of the day, etc).
| common-pile/stackexchange_filtered |
Monomorphisms in $\mathcal{C}\!at_\infty$
I'm trying to work through what the $(-1)$-truncated morphisms are in $\def\Catinf{\mathcal{C}\!at_\infty} \Catinf$.
BLUF: The correct characterization is that $F : C \to D$ is a (-1)-truncated map of $\infty$-categories iff, on hom spaces, $C(X,Y) \to D(FX, FY)$ is a (-1)-truncated map of spaces whose essential image contains the equivalences.
I've seen it stated, e.g. at nLab, that these should be precisely the full-and-faithful functors.
However, by <IP_ADDRESS> of Higher Topos Theory, a functor $F : C \to D$ is $(-1)$-truncated iff the diagonal $\Delta : C \to C \times_D C$ is an equivalence (i.e. $(-2)$-truncated).
Consider the model given by simplicially enriched categories, and the special case that $C$ and $D$ are the ordinary categories ${\bf 1} + {\bf 1}$ and ${\bf 2}$ respectively. That is, $C$ is the discrete category with two elements, and $D$ adjoins a single morphism between them.
Since all of the hom-spaces are either empty or the point, these are fibrant objects. Furthermore, $C \to D$ is a fibration on hom-sets, and has the equivalence lifting property. Thus, $F$ is a fibration of the model structure.
Thus, the ordinary pullback computes the homotopy pullback, and it's easy to see that $C \to C \times_D C$ is, in fact, an isomorphism of simpicially enriched categories.
But $C \to D$ is very much not a full functor.
Instead, if I've worked through the details correctly, a functor $F : C \to D$ being $(-1)$-truncated is equivalent to the weaker condition
$C(X,Y) \to D(FX, FY)$ is a $(-1)$-truncated map of spaces
If $FX \simeq FY$, then $X \simeq Y$
This includes full-and-faithful functors, but it also includes more general examples.
So I have conflicting information. Is nLab in error? Have I made an error? Have I made some other serious misunderstanding?
$F$ is $(-1)$-truncated iff (i) each $C(X,Y)\to D(FX,FY)$ is a $(-1)$-truncated map of spaces which (ii) has all isos $FX\xrightarrow{\sim} FY$ in its effective image.
Somewhere along the way, I accidentally replaced (-1)-truncated map of hom-spaces with a bastardization of the characterization of (-1)-truncated spaces. I've corrected my post to undo that error.
Monomorphisms in $Cat_\infty$ are characterized this way in Secion 5.1 of Ayala-Francis-Rozenblyum. I'm not sure if that's the earliest reference.
The characterization I gave is basically obvious if you take complete Segal spaces as your model for $Cat_\infty$, btw.
The statement at nLab is indeed incorrect, but your condition is also too strong. The first part should be replaced with a weaker condition that the map $C(X,Y) \to D(FX,FY)$ is a $(-1)$-truncated map of spaces.
Thanks; it's good to know I'm not completely wrong here. Also, I have (-1)-truncated map in my work, but somewhere along the line mixed that up with the characterization of (-1)-truncated homotopy types being either empty or (-2)-truncated. Thank you for correcting that too before I did anything depending on that mistake!
@Questioner Oh, also the second part in your condition is too weak. As noted by Charles Rezk, you should also require that the image of $X \simeq Y$ is the original $FX \simeq FY$.
I guess I did do something depending on that mistake! :(
| common-pile/stackexchange_filtered |
explain the command `printf -- "#!${opt_E}"`
I am not able to understand this command and getting confused :
here are things i executed on linux trying to undertand its working
[root@testgfs2 final_scripts]# printf -- "#!${opt_E}"
printf -- "#reset{opt_E}"
#reset{opt_E}[root@testgfs2 final_scripts]# printf -- "#!${opt_E}"
printf -- "#"#reset{opt_E}"{opt_E}"
##reset{opt_E}{opt_E}[root@testgfs2 final_scripts]# echo !$
echo "#"#reset{opt_E}"{opt_E}"
##reset{opt_E}{opt_E}
how does this work and i don't know under what topic it comes so i am unable to find it on google also.
also what does -- doing after printf
See What does “--” (double-dash) mean?.
Note that ! is reinterpreted by Bash, so try using dash or some other shell that doesn't do history expansion.
The correct way to write it would have been printf '#!%s' "$opt_E" BTW
See Bash reference manual:
!!:$
designates the last argument of the preceding command. This may be shortened to !$.
If this behavior is undesired you can just escape ! with backslash:
% echo "\!$"
!$
In a script, the characters #! are not special in this context. The snippet printf -- "#!${opt_E}" calls the printf command with two arguments: --, and #! concatenated with the value of the opt_E variable. The argument -- tells printf that even if there are subsequent arguments beginning with -, they are not to be interpreted as options; it doesn't make a difference here since #!${opt_E} doesn't begin with -. The double quotes around #!${opt_E} protect # from being interpreted as a comment start character, and they protect the value of opt_E from being split into separate words which are interpreted as wildcard patterns.
If the value of opt_E doesn't contain any % or \ character, then this command prints #! followed by the value of opt_E, with no final newline. In general, the command interprets the value of opt_E as a printf format.
If you try this out in an interactive shell, you may see strange effects due to ! being interpreted as a history expansion character, which automatically recalls previous commands. To avoid this, add a \ before !. ! is also interpreted literally within single quotes: printf -- '#!${opt_E}'.
If you're replaying a script, you'll have to have set opt_E to the right value first. If you're trying to debug a script, add set -x on the second line (insert it just below the initial #! line): the shell will print a trace of each line as it executes it.
| common-pile/stackexchange_filtered |
How to create tabs with linebreaks?
I want to create tabs with jQuery and CSS that are capable to contain text with linebreaks.
I tried several jQuery tab plugins including jQuery Ui's tabs, but all of them are messing around the layout, when you insert a line break (e.g. with "br"-tag) into the tab heading.
Now I use the simple and lightweight liteTabs jQuery plugin by Nicola Hibbert, but I think the solution lies in the CSS and will be independent from that.
Here's my code:
<div class="example-2">
<ul>
<li>
<a href="#1">
Tab 1 line 1 <br />
line.....2<br />
line......3
</a>
</li>
<li><a href="#2">Tab 2<br /> </a></li>
<li><a href="#3">Tab 3</a></li>
</ul>
<div name="#1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ultricies fermentum tempor.
Maecenas rutrum augue vehicula nisi feugiat tempus. Aenean pretium fringilla eleifend.
Ut posuere vestibulum lorem quis iaculis. Nullam luctus ipsum aliquam justo convallis egestas.
</div>
<div name="#2">
Maecenas rutrum augue vehicula nisi feugiat tempus. Aenean pretium fringilla eleifend. Ut posuere vestibulum lorem quis iaculis.
Nullam luctus ipsum aliquam justo convallis egestas. Vivamus mattis nunc molestie nisi tincidunt gravida. Aliquam erat volutpat.
Donec a dolor vitae quam gravida pharetra euismod eget metus. Ut nisi quam, molestie vitae semper non, malesuada quis justo.
Quisque magna velit, eleifend hendrerit vestibulum non, dignissim sed felis.
</div>
<div name="#3">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ultricies fermentum tempor.
Maecenas rutrum augue vehicula nisi feugiat tempus. Aenean pretium fringilla eleifend. Ut posuere vestibulum lorem quis iaculis.
Nullam luctus ipsum aliquam justo convallis egestas. Vivamus mattis nunc molestie nisi tincidunt gravida. Aliquam erat volutpat.
Donec a dolor vitae quam gravida pharetra euismod eget metus. Ut nisi quam, molestie vitae semper non, malesuada quis justo.
Quisque magna velit, eleifend hendrerit vestibulum non, dignissim sed felis.
</div>
</div>
The example is here at jsfiddle.
Simply use instead of is better due to new HTML5 standard. The second version works equally good though. But it is from xhtml.
thank you for this information. Unfortunately when using instead of the syntax-highlighting in jsfiddle shows "unclosed" tags.
In order to keep the layout from breaking, you need to add a fixed height to your unordered list (UL) element. Then, you can set your List Items (LI) and anchor tags (A) to 100%.
Adding the following CSS rules to your CSS should fix the layout issue. You just need to decide how large your tabs are going to be:
ul { height: 56px; }
li { height: 100%; }
a { height: 100%; }
Here is a fiddle with the fixed layout: http://jsfiddle.net/VkH5R/15/
Is that what you were looking for?
this solution in fact works almost OK if we can estimate the height of the tabs beforehand, to make it more dynamic, you can just use script to auto-set all the values no matter what you change to the tabs' text as well as font-size ... check this demo http://jsfiddle.net/viphalongpro/VkH5R/16/
I can't think of another way to solve this without using JavaScript to calculate the height, and then manipulate the DOM after the fact. In CSS, in order to stretch a child element to 100% of the height of it's parent, the parent needs to have a defined value for height set.
| common-pile/stackexchange_filtered |
R - Perform Function on Matrix Values using Value Location
I'm building a software that takes advantage of R's matrix calculations to build a heat map. Assuming I've got the following as my starting matrix:
-1.8784 -1.8783 -1.8782
53.5919 0 0 0
53.592 0 50 0
53.5921 0 0 0
How would I transform it into the following?
-1.8784 -1.8783 -1.8782
53.5919 0 12.5 0
53.592 12.5 25 12.5
53.5921 0 12.5 0
i.e. what I'm trying to do is reduce the value at a certain point by increasing the surrounding values to give a more steady gradient on the map.
I've tried utilising apply, but I can't seem to work out how to pass the location of the current index being worked on into the function. For loops are, obviously, an option but they're famously slow in R and I would quite like to have some level of optimisation to this.
Is there any more elegant solution than iterating through each value in the matrix?
The following may do what you want. It is certainly possible to it more elegantly I believe. But my linear algebra is too far away to do that off the top of my head though.
First, I construct some toy data.
Matrix to "smooth":
x <- 0*diag(10)
x[8,4] <- x[6,7] <- x[3,3] <- 50
print(x)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 50 0 0 0 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 50 0 0 0
[7,] 0 0 0 0 0 0 0 0 0 0
[8,] 0 0 0 50 0 0 0 0 0 0
[9,] 0 0 0 0 0 0 0 0 0 0
[10,] 0 0 0 0 0 0 0 0 0 0
Next, we define a helper matrix that can be utilized in matrix-matrix multiplication:
b <- 0*diag(10)
b[col(b) == row(b) + 1] <- 0.5
b[col(b) == row(b) - 1] <- 0.5
print(b) # A symmetric matrix with the first off-diagonal set to 0.5
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0.0 0.5 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
[2,] 0.5 0.0 0.5 0.0 0.0 0.0 0.0 0.0 0.0 0.0
[3,] 0.0 0.5 0.0 0.5 0.0 0.0 0.0 0.0 0.0 0.0
[4,] 0.0 0.0 0.5 0.0 0.5 0.0 0.0 0.0 0.0 0.0
[5,] 0.0 0.0 0.0 0.5 0.0 0.5 0.0 0.0 0.0 0.0
[6,] 0.0 0.0 0.0 0.0 0.5 0.0 0.5 0.0 0.0 0.0
[7,] 0.0 0.0 0.0 0.0 0.0 0.5 0.0 0.5 0.0 0.0
[8,] 0.0 0.0 0.0 0.0 0.0 0.0 0.5 0.0 0.5 0.0
[9,] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.5 0.0 0.5
[10,] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.5 0.0
Do the computation:
res <- x %*% b + b %*% x + x
res
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 25 0 0 0 0 0 0 0
[3,] 0 25 50 25 0 0 0 0 0 0
[4,] 0 0 25 0 0 0 0 0 0 0
[5,] 0 0 0 0 0 0 25 0 0 0
[6,] 0 0 0 0 0 25 50 25 0 0
[7,] 0 0 0 25 0 0 25 0 0 0
[8,] 0 0 25 50 25 0 0 0 0 0
[9,] 0 0 0 25 0 0 0 0 0 0
[10,] 0 0 0 0 0 0 0 0 0 0
Edit This yields the same:
d <- 0.5*diag(10)
d[col(d) == row(d) + 1] <- 0.5
d[col(d) == row(d) - 1] <- 0.5
res2 <- x %*% d + d %*% x # or crossprod(d, x) + tcrossprod(x, d)
print(res2)
Thank you very much, I didn't even consider doing matrix multiplication to get the result I wanted! I'll play around with the helper matrix and see if I can get a nice smooth gradient.
Glad I could help. You should probably also spend some time investigating the Matrix package. I guess representing them as a sparse matrices and utilizing that would bring down the computation time.
| common-pile/stackexchange_filtered |
Two colors ordered heatmap
In this example
R heatmap ggplot2 ordered as data file
I've changed data input to this one where for the second column every value is 0 so it should we filled in white
people,1,2,3
Ej1,1,0,0
Ej2,0,0,1
Ej3,0,0,1
Ej4,1,0,0
Using the same code as in the post
library(reshape2)
library(ggplot2)
library(scales)
library(plyr)
data <- read.csv("fruits.txt", head=TRUE, sep=",")
data$people <- factor(data$people,levels=rev(data$people))
data.m = melt(data)
data.m <- ddply(data.m, .(variable), transform, rescale = rescale(value))
data.m <- ddply(data.m, .(variable), transform, rescale = rescale(value))
p <- ggplot(data.m, aes(variable, people)) + geom_tile(aes(fill = rescale),
colour = "white")
p + scale_fill_gradient(low = "white", high = "steelblue")
But the X2 variable column is filled with a different color instead of white as shown in the image.
I've been trying to change the scale_fill_gradient(low = "white", high = "steelblue") to the scale_color_gradient but couldn't find out how.
The problem appears to be how rescale is being applied to your data frame. For a vector x, rescale(x) checks if the range of x is 0, and if this is the case it will use the mean of the to range, whose default value is to=c(0,1):
rescale(rep(0,4),to=c(0,1))
[1] 0.5 0.5 0.5 0.5
When ddply applies the .FUN rescale to your data frame, when it considers variable X2, the range of value is 0, as in case above.
The rescale column in data.m is showing a value of 0.5 for X2, explained by the above. So the ggplot is plotting the data correctly.
people variable value rescale
1 Ej1 X1 1 1.0
2 Ej2 X1 0 0.0
3 Ej3 X1 0 0.0
4 Ej4 X1 1 1.0
5 Ej1 X2 0 0.5
6 Ej2 X2 0 0.5
7 Ej3 X2 0 0.5
8 Ej4 X2 0 0.5
9 Ej1 X3 0 0.0
10 Ej2 X3 1 1.0
11 Ej3 X3 1 1.0
12 Ej4 X3 0 0.0
One way around this is to dump the use of ddply here, and just operate on the data frame directly, forcing rescale to operate on the entire value column (rather than via .(variables)) and so avoiding the 0 range problem for X2.
library(reshape2)
library(ggplot2)
library(scales)
library(plyr)
data <- read.csv("fruits.txt", head=TRUE, sep=",")
data$people <- factor(data$people,levels=rev(data$people))
data.m = melt(data)
#data.m <- ddply(data.m, .(variable), transform, rescale = rescale(value))
data.m[,"rescale"]<-rescale(data.m[,"value"],to=c(0,1))
p <- ggplot(data.m, aes(variable, people)) + geom_tile(aes(fill = rescale), colour = "white")+ scale_fill_gradient(low = "white", high = "steelblue")
p
^ No problem. Please come again
| common-pile/stackexchange_filtered |
Linux; How do I find logs if a program I'm running uses certain ports?
I am running CentOS 5 with csf firewall. I'm running a program that can't connect to another server (using some port that is blocked by csf I presume). Where is the log file for 'ports'?
You may have better luck on http://serverfault.com/
Hi:This might be off-topic, but you can verify current port status by issuing: netstat -tap and see which ports are being used. Hope this helps.
Netstat is the command to use to get ports and network activity. To diagonise server processes I usually use:
netstat -tln
This yields port numbers in tcp mode listening. To identify associated processes you can also use -p to grab the pid. Here is the IANA ports list.
I found my answer right after searching a few more threads.
# tail -f /var/log/messages
Shows the UDP message but not the port.... Hmm....
Because UDP does not usually have specific ports except for well-known protocols.
Btw I overlooked this---- the above command actually showed the port. It was labeled "DPORT"
Is this correct? I thought it meant dynamic (port) for some reason.
| common-pile/stackexchange_filtered |
For Here or over "there?" - ex deo nascimur in christo morimur per spiritum sanctum reviviscimus?
I am uncertain about this ... so I'm asking on meta first. Over on Christianity.SE, I posted this question:
ex deo nascimur in christo morimur per spiritum sanctum reviviscimus?
Which for ease of access, I'll just repost below. My question is simple - would it be more appropriate for here (because there may be biblical sources) instead of over there? thanks.
Ex Deo Nascimur,
In Christo Morimur,
Per Spiritum Sanctum Reviviscimus
From God we are born,
In Christ we die,
(and) in (/per) the Holy Spirit we are reborn (revived)
This is an old saying I think is attributed to the Rosicrucians.
I'm trying to back track it further as it clearly predates them by at
least a millennia.
Any ideas on the origins?
Christianity.SE is the right place for that. It is not a question of hermeneutics.
thanks Caleb. Just wondering additionally - if I were to ask about certain, specific linguistic aspects to the Latin to English translations of this, would it then be appropriate for here? (Hmmmm... I see from your SE sites that you've been on English Lang. Usage tons ... it seems like there's a parallel problem of overlap between hermeneutics.SE and C~.SE just as there is between English Language Usage and English Language Learners.)
This is not a general linguistics site, it's a Biblical hermeneutics site so the subject area is the process of iterpreting the Bible. Some random Latin saying doesn't necesarrily have anything to do with that.
hmmm ... sorry Caleb, that doesn't make any sense to me. How can the 'process of interpreting the Bible' not involve the subject area of translations, which requires deep linguistics? Perhaps you meant only that 'some random Latin saying doesn't necessarily' fall under hermeneutics? But if the saying wasn't random - and did have its origins piecemeal from the Bible, where would I ask about it? The linguists would migrate it here or maybe to C~SE, wouldn't they? thx
I didn't say linguistics doesn't play a role in hermeneutics, I said linguistics does not define the scope of this site. Most Biblical hermeneutics questions involve linguistics but involving linguistics does not make something on topic here. Sayings of Christians or churches in any language are likewise not a subset of Biblical hermeneutics and thus off topic here.
ok - still not clear where the razor slices thru my question - no worries...
@HowardPautz I think this previous meta Q&A is the "razor". Your Latin text isn't a text drawn from any recognized biblical canon - correct?
@David - That's part of why I asked - I am uncertain how much, if any of it comes from recognized canon. It's also possible that parts of it are alterations. This is why I'm unsure if posting here is the right place ... but I read the intention and help files and (perhaps mistakenly) thought this was a better choice than C~.SE. Suggestions? Thanks!
@HowardPautz Even if bits and phrases were quotations from Scripture, the context of the thing you are asking about is not the context of Scripture it is the context of the author(s) and their work, whether an individual or a group. That puts it in the domain of one of the religious sites such as [christianity.se].
@Caleb (DUH! The light bulb finally illuminates above Howard's head.) Thank you! With that and David's link above, I hope I now understand. Again there's a gray area though - if I found that a portion of this 'saying' where based on (say) a poor translation of a specific Scripture passage, it would be on-topic if I could site same (and still give the whole saying as context to assist in thinking about it), right?
@HowardPautz Glad that makes some sense. In the case of something that is a quote it might be on topic here only if you were asking what the source meant in the context of Scripture, interpreting what the quoter might have meant would still be off topic. Evaluating their translation might work here, again if you knew what the source was and that it was intended as a translation.
@Caleb - understood. Trying now to navigate the labyrinth of "texts [...] open for examination" David links to above. I suspect some of this originates from Tertiary texts --- but is probably too obscure to have been studied much...
@HowardPautz the SE framework can be a bit confusing. You may find this post helpful: Why can't I ask my 'big question'?
@Daи thanks - in addition to being generally helpful, did you want me to understand that also specific to this post being migrated here from hermeneutics? (The "Why can't ... question" is on meta.hermeneutics.) Yes, it can be difficult to make questions focused, specific enough for SE - especially when they deal with high level matters, such as Christianity, hermeneutics, philosophy, etc. It also has a lot to do with the people on each site. Philosophy.se, Mathematics.se, Physics.SE for instance, tolerate, even encourage discussion-style comments, whereas many other sites prefer otherwise.
@HowardPautz I meant it more in general, SE-wide.
| common-pile/stackexchange_filtered |
Dependency Injection and code maintainability
I am working on a (vb.net/asp.net) project that is using interfaces to provide dependency injection. But to me, it feels like the maintainability of the code has been killed. When I want to read through the code, I can't simply jump to the code of a related class that is used. All I see are the interfaces, and so I have to hunt through the project to figure out what classes are doing the implementation. This really hurts my productivity.
Yes, I know I now can implement the interfaces with a wide variety of replacement classes. But for example, I know I'm not changing my data source any time soon--there is no need for me to enable the ability to swap that out. All of this dependency injection seems like overkill to me (in fact, the only real reason it is there is to support mock classes for unit testing). I've actually read several places that state DI is actually better for maintainability. But that assumes you already know where everything is and you know which class you need to update. Finding out where to look is the part that is killing me.
So, my question is: Is there a better way to traverse through the code? Is there a better way to make the code more maintainable? Are we just doing it wrong? Or is this par for the course?
dependency injection is about maintanability, scalability and loose coupling, not about making your task of "code traversal" easier.
Install ReSharper. 2. Go to any interface method call. 3. CTRL-ALT-B
@RMP1984 How is it more maintainable when just trying to find out where to look is non obvious? This is the point where I don't understand the support for DI for its maintainability.
you really seem to be equating "ease of navigating code" with "maintainability". These are two very different things...
There is definitely some overhead to DI, especially when your configuration is separated from your code. While this is par for the course, it does get easier to deal with over time, and as you get a better understanding of the code.
However, there is tooling that can help - Have a look at Resharper or CodeRush. Both offer excellent improvements to the code navigation experience in Visual Studio. Resharper has excellent "Go To Symbol" or "Go To Implementation" methods that quickly help you navigate to the implementation of your interface, wherever it may be.
To the point about maintainability: In general, a loosely coupled design becomes more important as time passes, because there will be change. The more tightly coupled your code is, the harder it is to make small changes without affecting the overall application. This is where depending on interfaces is very very important -- whether or not you choose to use Dependency Injection.
I guess this is where I don't see the advantages of modifying a class that implements your interface rather than modifying a concretely referenced class. Interfaces allow for multiple implementations, it doesn't necessarily allow an implementation change to be encapsulated.
It does help, but maybe not in your application. If all your interfaces always expose exactly the same set of behaviours as your implementations, then yes, there's little difference between the implementation and interface. Interfaces per se do not magically improve your design, they are just a necessary tool when designing loosely coupled components.
Also, if you cannot understand the code you're working with without going into the implementation of the interface, then that's a different issue. For eg, I know that IList has an Add method -- if, when using a class that implements IList, I need to know how Add is implemented, then my class is dependent on the implementation of IList rather than the IList interface. Designing components so that they do not have this type of dependency on implementation is what is important. That is what allows you to make changes to your app safely
Maintainability is many different things. Overall, it addresses the degree to which you can keep evolving an application by adding new features.
Yes, it may become more difficult to understand how collaborators are connected, so that aspect of maintainability may suffer by introducing loose coupling.
However, once you've figured out how the code base works, you should be better able to add new features without slowing down. In that sense, maintainability is much improved by loose coupling.
It's not a silver bullet, though. Loose coupling is a prerequisite for maintainable code, not a guarantee.
| common-pile/stackexchange_filtered |
Update content of popup on a polygon click event in Leaflet?
I work with Leaflet.js v 1.7.1 and have stuck with a problem of updating popup content data of data The data set is on a local disk Currently I have a local set of data:
var data =[
{
type: "Feature",
properties: {
id: "1",
type: "type1",
pedestrians:"",
vehicles:""
},
geometry: {
type: "Polygon",
coordinates: [...]
}
},
{
type: "Feature",
properties: {
id: "2",
type: "type1",
pedestrians:"",
vehicles:""
},
geometry: {
type: "Polygon",
coordinates: [....]
}
}
];
The data are loaded by
var mygeoJson = L.geoJSON(data, {
onEachFeature: setFeature,
style: setStyle,
}).addTo(this.map);
function setFeature(feature: any, layer: any) {
if (feature.properties) {
layer.bindPopup(Object.keys(feature.properties).map(function (k) {
return k + ": " + feature.properties[k];
}).join("<br />"), {
maxHeight: 200
}); /*loaded and popup bind default properties from data object */
}
layer.on({
"mouseover": highlightFeature,
"mouseout": resetHighlight,
"click" : function(e:any){
/* for simplicity here is a set of new data for update */
var newpedestrians = 'new pedestrians data';
var newVehicles = 'new vehicles data' ;
/* here should be a code to update values of the mygeoJson properties for the clicked shape area*/
/*pedestrians and vehicles and displayed in popup*/
}
}
)
}
Data updates would be grabbed from a REST server only for the properties "pedestrians" and "vehicles", not the whole data set.
How can I update data in the popup with new newPedestrians and newVehicles data?
For simplicity of the problem API calls are not written, instead I wrote two new values for properties to update.
If my approach is not ideal and the problem cannot be solved based on this idea and piece of the code, can someone, offer a better solution?
If I understand you correctly, you want to update certain feature properties when popup is requested by click and before it's shown, so that popup displays updated data?
Yes, you are right !
One way to display popup with always updated data would be to attach event processing function to feature layer event popupopen and then update popup content in that function every time popup is opened. In this case popup content can initially be set as empty.
Code could then look something like this:
function updatePopup(evt) {
var propertyValue;
var newPedestrians = getNewPedestriansData();
var newVehicles = getNewVehiclesData();
var feature = evt.target.feature;
var popupContent = Object.keys(feature.properties).map(function (k) {
if (k == 'pedestrians')
propertyValue = newPedestrians;
else if (k == 'vehicles')
propertyValue = newVehicles;
else {
propertyValue = feature.properties[k];
}
return k + ": " + propertyValue;
}).join("<br />");
evt.popup.setContent(popupContent);
}
function setFeature(feature: any, layer: any) {
if (feature.properties) {
layer.bindPopup('', {
maxHeight: 200
});
layer.on('popupopen', updatePopup);
}
layer.on({
"mouseover": highlightFeature,
"mouseout": resetHighlight,
});
}
var mygeoJson = L.geoJSON(data, {
onEachFeature: setFeature,
style: setStyle,
}).addTo(this.map);
| common-pile/stackexchange_filtered |
Why to take the absolute value of the wave function before squaring it?
For obtaining the probability distribution we should take the absolute value of the Schrodingër Wave Function 'Ψ'and then square it. But why to take first the absolute value if the square is going to give us a positive number anyways?
see for details http://mathworld.wolfram.com/AbsoluteSquare.html
The wave function can be complex, for example $\psi(x)=Ae^{-x^2/2\sigma^2+ikx}$. Squaring that won't even give a real quantity, let alone a positive one. That's where the absolute value kicks in, it turns a complex function into a real one. In this case $|\psi(x)|^2dx=|A|^2e^{-x^2/\sigma^2}dx$, which now has the physical interpretation of a probability distribution density.
This is because the values of the wavefunction are complex numbers. Squaring a complex number doesn't necessarily give you a positive number, or even a real one. For example, $i^2=-1$, and $(1+i)^2 = 2i$.
| common-pile/stackexchange_filtered |
Conditional serving of web pages based on "Accept" header with express?
I understand that you can serve static content over express with:
app.use(express.static(__dirname + "../../../public_html"));
However, I'm trying to have express change the presentation of the content it delivers based upon the "Accept" header the the response sends over. Normally, the content that I have is requested in a JSON format through a REST API so the url is: http://blah.com/this/that/item and that works well.
However, I would also like for users to be able to access that same page from a browser which would send over something like: Accept:text/html and because of that header, see a page with correct formatting (CSS/JS/HTML/etc) to present the same information.
Right now, I'm trying to serve the content through:
if (req.accepts("text/html")) {
res.sendfile("/", {
root: "../../../public_html"
});
res.status(200);
return;
}
Where public_html holds index.html and the relative directories with the CSS and JS. I won't send that file whenever this is finished, but I figured it would be a good start and then add the JSON content after I figured out how to serve static content based on the Accept header.
Is there a better way to do this?
You're on the right track. Here's a nice example from Express about using req.accept:
app.use(function(req, res, next){
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.render('404', { url: req.url });
return;
}
// respond with json
if (req.accepts('json')) {
res.send({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
});
Updated:
You can use res.send to send files without rendering:
res.set('Content-Type', 'text/html');
res.send(new Buffer(fs.readFile(__dirname + 'index.html'));
This would require me to use a rendering engine though, correct? What about if I want to serve up a static html page instead? I may be incorrect, I only read about how res.render needs a render engine and then read about jade and that it needs a specific, separate markup.
You can just use res.format to do the same thing. The example from the express docs:
res.format({
text: function(){
res.send('hey');
},
html: function(){
res.send('<p>hey</p>');
},
json: function(){
res.send({ message: 'hey' });
}
});
You can read more about it here: http://expressjs.com/en/api.html#res.format
| common-pile/stackexchange_filtered |
What is the functionality of .dart_tool folder in a Flutter application?
I am new to flutter and I encountered this folder .dart_tool. I am able to find the uses of each folder and files, except this one. I want to know what purpose does this folder serves.
As @Shri noted in his answer, the Flutter documentation says:
The .dart_tool directory, which is new in Dart 2, is used by pub and other tools. It replaces the .pub directory as of the 2.0.0-dev.32.0 SDK release.
However, I would also add that it contains a package_config.json file that specifies packages' locations and versions (which could cause a problem that I addressed in this answer), as well as Flutter build caches (in a flutter_build directory).
From the documentation,
The .dart_tool directory, which is new in Dart 2, is used by pub and other tools. It replaces the .pub directory as of the 2.0.0-dev.32.0 SDK release.
Anyone who wonders what is pub, It is the package repository for flutter and Dart Applications.
A Package Repository is a place where all the packages (like libraries, jars) are stored in the internet (once downloaded they may get stored in the local machine and then we call it a local repository).
| common-pile/stackexchange_filtered |
R count variable in Vector by split/Group?
I have the following Dataset (not the real Dataset)
The Dataframe has lots of players (player2, player3 etc) and Dates and reported status. I am trying to summarize the Number of Fails in each date for each player.
Players <- rep("player1", 24)
Date <- c(rep("2020-10-22", 6), rep("2020-10-21", 8), rep("2020-10-18",10))
status <- c("Enter", "start", "stop", "start" , "stop", "Exit",
"Enter", "start", "start_fail", "start", "stop", "start", "stop", "Exit",
"Enter", "Enter_Fail", "start", "stop", "start",
"injured", "start_fail", "start", "stop", "Exit")
df <- data.frame(Players = Players, Date = Date, status= status)
x = c("Enter_fail", "start_fail")
I grouped the Data by group_by and did the count
df %>% group_by(Players, Date) %>% summarise(fail_count = sum(status %in% x)
But the problem is, if the status "injured" is read, the corresponding start_fail is not counted as failure.
Does this work:
> library(dplyr)
> df %>% mutate(fail_count = case_when(lag(status) != 'injured' & grepl('[Ff]ail$',status) == TRUE ~ 1,
+ status == 'injured' & grepl('[Ff]ail$',status) == TRUE ~ 0,
+ TRUE ~ 0)) %>% filter(fail_count == 1) %>%
+ group_by(Players, Date) %>%
+ summarise(fail_count = sum(fail_count))
`summarise()` regrouping output by 'Players' (override with `.groups` argument)
# A tibble: 2 x 3
# Groups: Players [1]
Players Date fail_count
<chr> <date> <dbl>
1 player1 2020-10-18 1
2 player1 2020-10-21 1
>
Thanks for the reply. The count works, but what i am trying is, in the Date 2020-10-18 , the actual fail_count is 1 , because, the second failure happened because of injury hence is not counted in fail_count. Basically, whenever Injured is read in the column, next 'Fail' is not counted
@SriRam, have made changes to my code, please check if it works for you now.
| common-pile/stackexchange_filtered |
Creating bean using annotation on-demand
I have a service that can have multiple jobs running simultaneously, all these are long running jobs, thus i have a requirement of statistics showing how these jobs are working, i am using MXbeans for this. As of now i have single bean that encapsulates the stats for all the running jobs, but this is not easy to read as it has a number of compositeData's in it, so i am thinking of creating individual beans for each job.
Now here is the challenge, as these jobs are added at runtime so the count of them is not fixed, i was planning to create a bean using the @Bean annotation
@Bean
public JobsStats jobOne() {
return new JobsStats ();
}
All this logic is working fine for me, where i am stuck is how to create a new bean ONLY when a new jobs is created at runtime, how i can this be achieved?
What you are trying to do is very specific and the places where I have needed this has always been state aware multithreaded code,ie. You may not reslly need this. Either way You need to annotate the bean for lazy creation and then where you want to use the bean you need a beanfactoryaware object that you can use to create the bean. I'm not near a pc today, so hopefully somebody else and provide a code sample
I cannot really understand your question. I think you could try to use either prototype or custom scoped beans.
@Leon - can you please provide me a sample code for this.
| common-pile/stackexchange_filtered |
Django: How to dynamically set view cache timeout value?
Within the view itself, I want to be able to set the cache timeout value upon returning a result. The reason for this is if the view returned an error, I want the timeout to be shorter.
Right now, I have the timeout set as static:
url(r'^view/(.+)/', cache_page(24 * 60 * 60)(MyView.as_view()), name='view')
You can do it manually in your view class. Something like:
class MyView(View):
def get(self, *args, **kwargs):
response_data = cache.get('some_key')
if response_data is None:
response = super(MyView, self).get(*args, **kwargs)
cache.set('some_key', response.content, 300)
else:
response = HttpResponse(response_data)
return response
Unfortunately, this doesn't answer the question as this only shows how to cache & retrieve raw data. The work that cache_page() does for you in terms of caching the entire response and setting headers is lost here.
to set cache_key Use: cache_key = learn_cache_key(request, response, timeout, self.key_prefix, cache=self.cache) and to set headers use: patch_response_headers(response, timeout). refer UpdateCacheMiddleware class
| common-pile/stackexchange_filtered |
WPF: Datagrid is updating header after adding or removing item at binding collection
I have binded a ObservableCollection (loaded from an ORM) to a WPF-DataGrid and on programm start I'm changing the header titles, adding self-developed AutoFilters to the column headers and setting some columns to visibility collapsed. That works everything very well.
But if I'm adding an new or removing an excisting Item to/from the ObservableCollection then the DataGrid refreshes completely and I'm loosing the changed column titles, the AutoFilters and the columns I have collapsed on program start are also visible.
At the moment I don't know how I can solve this problem. I'm looking forward for your help.
Thank you!
Try setting AutoGenerateColumns of the DataGrid to False.
For example:
<DataGrid AutoGenerateColumns="False">
That's a good idea. Currently I'm using the AutoGenerateColumns-function when I'm loading the columns from the database but I don't really need it because the columns normaly not changes. Tomorrow I will try to code the columns fix in the code. When I'm ready I give a feedback if this is the solution...
| common-pile/stackexchange_filtered |
Unexpected gaps in IDENTITY column
I'm trying to generate unique purchase order numbers that start at 1 and increment by 1. I have a PONumber table created using this script:
CREATE TABLE [dbo].[PONumbers]
(
[PONumberPK] [int] IDENTITY(1,1) NOT NULL,
[NewPONo] [bit] NOT NULL,
[DateInserted] [datetime] NOT NULL DEFAULT GETDATE(),
CONSTRAINT [PONumbersPK] PRIMARY KEY CLUSTERED ([PONumberPK] ASC)
);
And a stored procedure created using this script:
CREATE PROCEDURE [dbo].[GetPONumber]
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].[PONumbers]([NewPONo]) VALUES(1);
SELECT SCOPE_IDENTITY() AS PONumber;
END
At the time of creation, this works fine. When the stored procedure runs, it starts at the desired number and increments by 1.
The strange thing is that, if I shut down or hibernate my computer, then the next time the procedure runs, the sequence has advanced by almost 1000.
See results below:
You can see that the number jumped from 8 to 1002!
Why is this happening?
How do I ensure that numbers aren't skipped like that?
All I need is for SQL to generate numbers that are:
a) Guaranteed unique.
b) increment by the desired amount.
I admit I'm not a SQL expert. Do I misunderstand what SCOPE_IDENTITY() does? Should I be using a different approach? I looked into sequences in SQL 2012+, but Microsoft says that they are not guaranteed to be unique by default.
This is a known and expected issue - the way IDENTITY columns are managed by SQL Server has changed in SQL Server 2012 (some background); by default it will cache 1000 values and if you restart SQL Server, reboot the server, fail over, etc. it will have to throw out those 1000 values, because it won't have a reliable way to know how many of them were actually issued. This is documented here. There is a trace flag that changes this behavior such that every IDENTITY assignment is logged*, preventing those specific gaps (but not gaps from rollbacks or deletes); however, it is important to note that this can be quite costly in terms of performance, so I'm not even going to mention the specific trace flag here.
* (Personally, I think this is a technical problem that could be solved differently, but since I don't write the engine, I can't change that.)
To be clear about how IDENTITY and SEQUENCE work:
Neither is guaranteed to be unique (you need to enforce that at the table level, using a primary key or unique constraint)
Neither is guaranteed to be gapless (any rollback or delete, for example, will produce a gap, this specific problem notwithstanding)
Uniqueness is easy to enforce. Avoiding gaps is not. You need to determine how important it is for you to avoid these gaps (in theory, you should not care about gaps at all, since IDENTITY/SEQUENCE values should be meaningless surrogate keys). If it is very important, then you should not be using either implementation, but rather roll your own serializable sequence generator (see some ideas here, here and here) - just note that it will kill concurrency.
Lots of background on this "problem":
SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry
identity increment is jumping in sql server database
Identity column value suddenly jumps to 1001 in sql server
This is problem of SQL Server. All you can do is reseed the column.
delete the entries with wrong column id.
Reseed the column identity.
And then the next entry has proper ID to it.
Reseed Identity using following sql command :
DBCC CHECKIDENT ('YOUR_TABLE_NAME', RESEED, 9) -- 9 is last correct Id
What do you mean with "delete the entries"?
Hmmm .. seems deleting entries might just lead to data loss.
| common-pile/stackexchange_filtered |
Python FastCGI under IIS - stdout writing problems
I'm having a very peculiar problem in my Python FastCGI code - sys.stdout has a file descriptor of '-1', so I can't write to it.
I'm checking this at the first line of my program, so I know it's not any of my code changing it.
I've tried sys.stdout = os.fdopen(1, 'w'), but anything written there won't get to my browser.
The same application works without difficulty under Apache.
I'm using the Microsoft-provided FastCGI extension for IIS documented here: http://learn.iis.net/page.aspx/248/configuring-fastcgi-extension-for-iis60/
I am using these settings in fcgiext.ini:
ExePath=C:\Python23\python.exe
Arguments=-u C:\app\app_wsgi.py
FlushNamedPipe=1
RequestTimeout=45
IdleTimeout=120
ActivityTimeout=30
Can anyone tell what's wrong or tell me where I should look to find out?
All suggestions greatly appreciated...
Forgive me if this is a dumb question, but I notice this line in your config file:
Arguments=-u C:\app\app_wsgi.py
Are you running a WSGI application or a FastCGI app? There is a difference. In WSGI, writing to stdout isn't a good idea. Your program should have an application object that can be called with an environment dict and a start_response function (for more info, see PEP 333). At any rate, your application's method of returning will be to return an iterable object that contains the response body, not writing to stdout.
Either way, you should also consider using isapi-wsgi. I've never used it myself, but I hear good things about it.
Not a dumb question at all - I should have mentioned this in my question...
app_wsgi.py invokes a FastCGI library which then calls my WSGI app. It's the FastCGI library that is having problems writing to stdout.
Do you have to use FastCGI? If not, you may want to try a ISAPI WSGI method. I have had success using:
http://code.google.com/p/isapi-wsgi/
and have also used PyISAPIe in the past:
http://sourceforge.net/apps/trac/pyisapie
Is the can't most more that 1 URL a self-imposed or SO imposed constraint ? Anyway ... http://sourceforge.net/apps/trac/pyisapie
SO imposed since I was a new user, but I fixed it now
I believe having stdout closed/invalid is in accordance to the FastCGI spec:
The Web server leaves a single file
descriptor, FCGI_LISTENSOCK_FILENO,
open when the application begins
execution. This descriptor refers to a
listening socket created by the Web
server.
FCGI_LISTENSOCK_FILENO equals
STDIN_FILENO. The standard descriptors
STDOUT_FILENO and STDERR_FILENO are
closed when the application begins
execution. A reliable method for an
application to determine whether it
was invoked using CGI or FastCGI is to
call
getpeername(FCGI_LISTENSOCK_FILENO),
which returns -1 with errno set to
ENOTCONN for a FastCGI application.
On windows, it's possible to launch a proces without a valid stdin and stdout. For example, if you execute a python script with pythonw.exe, the stdout is invdalid and if you insist on writing to it, it will block after 140 characters or something.
Writing to another destination than stdout looks like the safest solution.
I'm already using python.exe to try to ensure that I'm getting a valid stdout. I've got a valid stdin that can read data, but not a valid stdout...
Unfortunately, the FastCGI spec says the server is listening for me to write FastCGI data on stdout, so I can't just change the way I do it...
Following the PEP 333 you can try to log to environ['wsgi.errors'] which is usualy the logger of the web server itself when you use fastcgi. Of course this is only available when a request is called but not during application startup.
You can get an example in the pylons code: http://pylonshq.com/docs/en/0.9.7/logging/#logging-to-wsgi-errors
| common-pile/stackexchange_filtered |
Continuity of Fourier series with decay condition on coefficients
Let $\theta \in \ell^2(\mathbb{N})$ satisfy
$$
\sum_{j=1}^n \theta_j^2 a_j^2 \leq Q
$$
for some $Q > 0$ where
$$
a_j = \begin{cases}
j^\beta & \text{$j$ even}\\
(j-1)^\beta & \text{$j$ odd}
\end{cases}
$$
for some $\beta > 1/2$. Let $\{\varphi_j\}_{j=1}^\infty$ denote the trigonometric basis of $[0,1]$, i.e. $\varphi_1(x) = 1$, $\varphi_{2k}(x) = \sqrt{2} \cos(2\pi k x)$ and $\varphi_{2k+1}(x) = \sqrt{2} \sin(2\pi k x)$ for $k \in \mathbb{N}$. Show that $f = \sum_{j=1}^\infty \theta_j \varphi_j$ is continuous.
I know that $\varphi_j$ is Lipschitz with constant $\pi\lfloor j+1 \rfloor$ but I don't think that helps very much. Any ideas?
Note first that the hypothesis is just a silly way of writing $$\sum_{j=1}^\infty\theta_j^2j^{2\beta}<\infty.$$
Proof by Looking it Up
The hypothesis says precisely that $f$ is in the Sobolev space often denoted $H^\beta$; since $\beta>1/2$ the Sobolev Embedding Theorem shows that $f$ is continuous.
Actual Proof
$$\sum|\theta_j|=\sum|\theta_j|j^\beta j^{-\beta}\le\left(\sum\theta_j^2j^{2\beta}\right)^{1/2}\left(\sum j^{-2\beta}\right)^{1/2}<\infty,$$since $2\beta>1$. So the series converges uniformly, hence $f$ is continuous.
Proof of a Stronger Result
Say $x<y$ and $y-x$ is small. Choose an integer $N$ with $1/2\le N(y-x)\le 2$. Now $$f(y)-f(x)=\left(\sum_{j=1}^N+\sum_{j=N+1}^\infty\right)\theta_j(\phi_j(y)-\phi_j(x)):=I+II.$$Now the Lipschitz constant for $\phi_j$ shows that $$I\le c(y-x)\sum_{j=1}^N\theta_jj^\beta j^{1-\beta}\le c(y-x)\left(\sum_{j=1}^N\theta_j^2j^{2\beta}\right)^{1/2}\left(\sum_{j=1}^Nj^{2-2\beta}\right)^{1/2}\le c(y-x)N^{\frac32-\beta}\le c(y-x)^{\beta-\frac12}.$$To estimate $II$ you just use the fact that $|\phi_j|\le1$: $$II\le 2\sum_{j=N+1}^\infty\theta_j j^\beta j^{-\beta}\le c\left(\sum_{j=N+1}^\infty j^{-2\beta}\right)^{1/2}\le cN^{\frac12-\beta}\le c(y-x)^{\beta-\frac12}.$$Since $\beta-\frac12>0$ this shows that $f\in Lip_{\beta-\frac12}$.
Note
It's worthwhile spending some time understanding this argument, because the outline "use a trivial uniform estimate for the high-order terms and the Lipschitz condition on the low-order terms" comes up a lot in this sort of thing.
| common-pile/stackexchange_filtered |
Trying not to repeat myself with Rails data manipulation
I'm fairly new to rails, an an intermediate programmer in general, but I'll try to be as clear as I can.
I have a database table for Products, which owns a field called category. Category has two possible values, call them Category1 and Category 2. The goal is to retrieve all the Products and display them in HTML organized by Category. I can make this work, but I know there has to be a better way.
My method now is to get my Products like so:
@category1_products = Product.all(conditions: { category: "Category1" })
@category2_products = Product.all(conditions: { category: "Category2" })
and then output the data something like this:
<table>
<tr>
<td>Category1 Name</td>
<% @category1_products.each do |product| %>
<td><%= product.name %></td>
<td><%= product.description %></td>
<td><%= product.price %></td>
<% end %>
</tr>
<tr>
<td>Category2 Name</td>
<% @category2_products.each do |product| %>
<td><%= product.name %></td>
<td><%= product.description %></td>
<td><%= product.price %></td>
<% end %>
</tr>
</table>
I would like to accomplish this using a single instance: get all Products at once, group them by Category, and then output them by looping through one Category at a time (including the Category Names). This seems like a pretty elementary concept to me, but I'm having trouble getting my head around it.
@products_by_category = Product.all.group_by(&:category)
This is a Ruby (read: not ActiveRecord) method to turn an Array into a Hash based on some condition of the objects it contains.
In your view (assuming you want one row per product, and not one per category):
<table>
<% @products_by_category.each do |category,products| %>
<tr>
<th><%= category %></th>
</tr>
<% products.each do |product| %>
<tr>
<td><%= product.name %></td>
<td><%= product.description %></td>
<td><%= product.price %></td>
</tr>
<% end %>
<% end %>
</table>
Thank you, I am indeed trying to create a single category row with multiple product rows associated with it.
Rails' group_by is great for this type of problem:
@grouped_products = Product.all.group_by(&:category)
and then in the view, just loop over @grouped_products:
<table>
<tr>
<% @grouped_products.each do |category, products| %>
<td><%= category %></td>
<% products.each do |product| %>
<td><%= product.name %></td>
<td><%= product.description %></td>
<td><%= product.price %></td>
<% end %>
<% end %>
</tr>
</table>
Thank you, that is exactly what I wanted to know.
| common-pile/stackexchange_filtered |
Change image display from base64 to src according to the email client
I want to view the images inside the email signature on all email clients.
Initially I created my signature using the classic:
<img src="https://drive.google.com/uc?export=view&id=1e0siJmU...">
This worked great for gmail and apple mail but outlook gives problems as it doesn't download images for security. Annoying! I have seen that instead outlook desktop displays images without problems if they are embedded via base64 code like this:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/...
. Now, however, it does not work in gmail as it does not even display the images and therefore the related social links.
So I thought of doing a sort of if clause that identifies the client and based on that write what kind of image I want to insert as a background-image on the style applied to the html body
I searched a lot on the web and on the stack and found many articles that dealt with conditional css but none that dealt with image change
I decided to use conditional css and came:
<body>
<!--[if mso]>
<style type="text/css">
#photo {
background-image: url('data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/...');
background-size:contain;
}
</style>
<!--<![endif]-->
<!--[if !mso]>
<style type="text/css">
#photo {
background-image: url('https://drive.google.com/uc?export=view&id=1e0siJmU...');
background-size:contain;
}
</style>
<!--<![endif]-->
<img id="photo">
</body>
but unfortunately it doesn't work. tips? thanks!
| common-pile/stackexchange_filtered |
Accessing shared SqlContext in spark 2.1
I am creating sqlContext at one time and just accessing it every other time.
I have created sqlcontext using this syntax :
class A {
static SparkConf conf = new SparkConf().setMaster("local").setAppName("SparkApp");
static JavaSparkContext sc = new JavaSparkContext(conf);
static SQLContext sqlContext = new SQLContext(sc);
public static void main(String[] args) throws InterruptedException {
Thread.sleep(86400000);
}
}
public class B {
public static void main(String[] args) {
System.out.println(A.sqlContext);
}
}
I can access this sqlContext from another file B after creation.
But when i create sqlContext using sparkSession like this :
class A {
public static SparkConf conf = null;
public static JavaSparkContext context = null;
public static SparkListener listener = null;
public static SQLContext sqlContext = null;
public static SparkSession sparkSession = null;
public static void main(String[] args) throws InterruptedException {
conf = new SparkConf();
sparkSession = SparkSession.builder().appName("TestCsv").master("local").config(conf)
// .enableHiveSupport()
.getOrCreate();
context = new JavaSparkContext(sparkSession.sparkContext());
sqlContext = sparkSession.sqlContext();
Thread.sleep(86400000);
}
}
public class B {
public static void main(String[] args) {
System.out.println(A.sqlContext);
}
}
I am able to create sqlContext.
Now when i try to access this sqlContext from another file B it gives me null.
In the second case SQLContext is initialized inside main function, which is never called. If you change your code to:
public class B {
public static void main(String[] args) {
A.main()
System.out.println(A.sqlContext);
}
}
In the first case SQLContext is initialized when it is declared.
In general to share context I'd initialize it in
object App {
public static void main(String[] args) {
val spark = SparkSession.builder.getOrCreate()
}
}
main and use getOrCreate method when necessary:
public class B {
public static void main(String[] args) {
System.out.println(SparkSession.builder.getOrCreate().sqlContext);
}
}
What if i initialized it through a static function? I don't want it to initialize at every call.It needs to be one-time task for initialization. All i am saying is after initialization i would able to get access.
| common-pile/stackexchange_filtered |
Add multiple arrays in Python
What I have created so far
I have created an 18x18 square matrix of zeros called ‘master_matrix’.
I have created an array called ingreso_datos, whose column 0 [col 0] indicates the data label.
I have created a for loop where:
For each data label I will have a little_matrix whose values will be assigned to master_matrix in their corresponding rows and columns. As this happens inside a for loop, for this example I get 6 master_matrix (in my variable list only the last one is read, that is, the sixth master_matrix).
What i need to do
What I'm looking for now is to add the 6 master_matrix that come from the for loop.
I have tried to do it one by one but the problem is that the data could change and I think it would not be efficient, I would greatly appreciate your help, regards.
import numpy as np
I have created an 18x18 square matrix of zeros called ‘master_matrix’
master_matrix = np.zeros((18, 18))
I have created an array called 'ingreso_datos', whose column 0 [col 0] indicates the data label.
# Data label |-------1(i) 2(i) 3(i) 1(j) 2(j) 3(j) --|
# [Col0] |------[Col1] [Col2] [Col3] [Col4] [Col5] [Col6] --|
ingreso_datos = [[ 1, 13, 14, 15, 7, 8, 9],
[ 2, 16, 17, 18, 10, 11, 12],
[ 3, 7, 8, 9, 1, 2, 3],
[ 4, 10, 11, 12, 4, 5, 6],
[ 5, 7, 8, 9, 10, 11, 12],
[ 6, 1, 2, 3, 4, 5, 6]]
For each data label I will have a 'little_matrix' whose values will be assigned to 'master_matrix'
in their corresponding rows and columns. As this happens inside a for loop, for this example I get 6
'master_matrix' (in my variable list only the last one is read, that is, the sixth 'master_matrix').
indices = [] # moved outside of the loop
for i in range(len(ingreso_datos)):
indices.append([ingreso_datos[i][0], ingreso_datos[i][1], ingreso_datos[i][2], ingreso_datos[i][3],
ingreso_datos[i][4], ingreso_datos[i][5], ingreso_datos[i][6]])
for row in indices:
indices = np.array(row[1:])
indices -= 1
d = 5
s = 0.2
e = 0.05
y = 5000000
little_matrix = np.array([[ s*y/d, 0, 0, -s*y/d, 0, 0],
[ 0, y*e/d**3, y*e/d**2, 0, -y*e/d**3, y*e/d**2],
[ 0, y*e/d**2, y*e/d, 0, -y*e/d**2, y*e/d],
[-s*y/d, 0, 0, s*y/d, 0, 0],
[ 0, y*e/d**3, -y*e/d**2, 0, y*e/d**3, -y*e/d**2],
[ 0, y*e/d**2, y*e/d, 0, -y*e/d**2, y*e/d]])
master_matrix[np.ix_(indices, indices)] = little_matrix
What I'm looking for now is to add the 6 master_matrix that come from the for loop.
master_matrix.sum()
I edited your question for clarity. I also move the indices=[] to the right place. But I wonder why you are creating that. I think np.array(indices) will be the same as the ingreso_datos array. indices = np.array(row[1:]) might be replaced with indices=ingreso_datos[i, 1:] for the ith row. This could probably be cleaned up considerably.
In [68]: ingreso_datos = np.array([[ 1, 13, 14, 15, 7,
...: 8, 9],
...: [ 2, 16, 17, 18, 10, 11,
...: 12],
...: [ 3, 7, 8, 9, 1, 2,
...: 3],
...: [ 4, 10, 11, 12, 4, 5,
...: 6],
...: [ 5, 7, 8, 9, 10, 11,
...: 12],
...: [ 6, 1, 2, 3, 4, 5,
...: 6]])
In [69]: ingreso_datos.shape
Out[69]: (6, 7)
That indices creation doesn't do anything significant:
In [70]: indices = [] # moved outside of the loop
...: for i in range(len(ingreso_datos)):
...: indices.append([ingreso_datos[i][0], ingreso_datos[i][1], ingreso_datos[i][2], ing
...: reso_datos[i][3],
...: ingreso_datos[i][4], ingreso_datos[i][5], ingreso_datos[i][6]])
...:
...:
In [71]: np.array(indices).shape
Out[71]: (6, 7)
In [72]: np.allclose(ingreso_datos, np.array(indices))
Out[72]: True
little_matrix doesn't need to be in the loop, since it doesn't change:
In [74]: little_matrix
Out[74]:
array([[ 200000., 0., 0., -200000., 0., 0.],
[ 0., 2000., 10000., 0., -2000., 10000.],
[ 0., 10000., 50000., 0., -10000., 50000.],
[-200000., 0., 0., 200000., 0., 0.],
[ 0., 2000., -10000., 0., 2000., -10000.],
[ 0., 10000., 50000., 0., -10000., 50000.]])
As for your iteration on row:
In [75]: np.array(indices[0][1:])-1
Out[75]: array([12, 13, 14, 6, 7, 8])
In [77]: ingreso_datos[0,1:]-1
Out[77]: array([12, 13, 14, 6, 7, 8])
So your iterative assignment to master_matrix becomes:
In [78]: master_matrix=np.zeros((18,18))
In [80]: for row in ingreso_datos:
...: indices = row[1:]-1
...: master_matrix[np.ix_(indices,indices)]=little_matrix
...:
In [81]: master_matrix
Out[81]:
array([[ 200000., 0., 0., -200000., 0., 0.,
-200000., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0.],
[ 0., 2000., 10000., 0., -2000., 10000.,
0., 2000., -10000., 0., 0., 0.,
0., 0., 0., 0., 0., 0.],
...
I suspect we can eliminate that iteration as well, but that'll take some more work.
Looking at the indices as a whole:
In [88]: x = ingreso_datos[:,1:]-1
In [89]: x
Out[89]:
array([[12, 13, 14, 6, 7, 8],
[15, 16, 17, 9, 10, 11],
[ 6, 7, 8, 0, 1, 2],
[ 9, 10, 11, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[ 0, 1, 2, 3, 4, 5]])
I see some overlap. For example the last row over writes some of the values written by row 2:
In [90]: master_matrix[:6,:6]
Out[90]:
array([[ 200000., 0., 0., -200000., 0., 0.],
[ 0., 2000., 10000., 0., -2000., 10000.],
[ 0., 10000., 50000., 0., -10000., 50000.],
[-200000., 0., 0., 200000., 0., 0.],
[ 0., 2000., -10000., 0., 2000., -10000.],
[ 0., 10000., 50000., 0., -10000., 50000.]])
In [91]: master_matrix[np.ix_(x[2],x[2])]
Out[91]:
array([[ 200000., 0., 0., -200000., 0., 0.],
[ 0., 2000., 10000., 0., -2000., 10000.],
[ 0., 10000., 50000., 0., -10000., 50000.],
[-200000., 0., 0., 200000., 0., 0.],
[ 0., 2000., -10000., 0., 2000., 10000.],
[ 0., 10000., 50000., 0., 10000., 50000.]])
(notice the sign change in the bottom right corner).
Given that over lap it's impossible to replicate the iterative assignment with one call.
Thanks for the feedback.
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.