text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
Permission error, having trouble loading parquet files from AWS S3 to SQL Server 2022
Basically every time I try to connect to AWS bucket to grab a parquet file in SQL Server 2022, I am getting a permission error
Cannot find the CREDENTIAL 's3_dc', because it does not exist or you do not have permission.
Code:
exec sp_configure @configname = 'polybase enabled', @configvalue = 1;
RECONFIGURE;
exec sp_configure @configname = 'polybase enabled';
CREATE DATABASE SCOPED CREDENTIAL s3_dc
WITH IDENTITY = 'IDENTITY',
SECRET = 'SECRET' ;
CREATE EXTERNAL DATA SOURCE s3_ds
WITH (LOCATION = 's3://s3.amazonaws.com',
CREDENTIAL = s3_dc );
GO
SELECT *
FROM OPENROWSET(BULK 'buckett/haz/data/data.parquet',
FORMAT = 'PARQUET',
data_source = 's3_ds') AS [cc];
That's the error message:
Cannot find the CREDENTIAL 's3_dc', because it does not exist or you do not have permission.
I tried disabling firewall, and tried logging in as SQL Server user and as a windows user, still getting same error.
does it work to add a GO before CREATE EXTERNAL DATA SOURCE s3_ds ?
nope, it didn't make any deference
does it help? https://stackoverflow.com/questions/68554261/cannot-find-the-credential-db-scoped-creds-because-it-does-not-exist-or-you
Have you read the CREATE EXTERNAL DATASOURCE documentation? In discussing the CREATE DATABASE SCOPED CREDENTIAL it says, Must be a database scoped credential, where the IDENTITY is hard-coded to IDENTITY = 'S3 Access Key' and the SECRET argument is in the format = '<AccessKeyID>:<SecretKeyID>'
Thank you so much!. If you can change your reply as a post I'll mark it as a solution because it fixed my problem!
With below command check if your scoped credentials are exist or not
SELECT * FROM sys.database_scoped_credentials;
If they exist still facing the issue you need to give permission to access the DATABASE SCOPED to your user, use below command to grant permisson:
GRANT REFERENCES ON DATABASE SCOPED CREDENTIAL::[{credential_name}] TO [{user}];
For more information refer this Document
Updated answer to help other community members as @AlwaysLearning said
while creating credentials Identity should be hardcoded as IDENTITY = 'S3 Access Key'
SECRET value also should be in proper format of <access_key_id>:<secret_key_id>
For more information refer this Create external data source documnet
| common-pile/stackexchange_filtered |
How to iterate over pandas multiindex dataframe using index
I have a data frame df which looks like this. Date and Time are 2 multilevel index
observation1 observation2
date Time
2012-11-02 9:15:00 79.373668 224
9:16:00 130.841316 477
2012-11-03 9:15:00 45.312814 835
9:16:00 123.776946 623
9:17:00 153.76646 624
9:18:00 463.276946 626
9:19:00 663.176934 622
9:20:00 763.77333 621
2012-11-04 9:15:00 115.449437 122
9:16:00 123.776946 555
9:17:00 153.76646 344
9:18:00 463.276946 212
I want to run some complex process over daily data block.
Pseudo code would look like
for count in df(level 0 index) :
new_df = get only chunk for count
complex_process(new_df)
So, first of all, I could not find a way to access only blocks for a date
2012-11-03 9:15:00 45.312814 835
9:16:00 123.776946 623
9:17:00 153.76646 624
9:18:00 463.276946 626
9:19:00 663.176934 622
9:20:00 763.77333 621
and then send it for processing. I am doing this in for loop as I am not sure if there is any way to do it without mentioning exact value of level 0 column. I did some basic search and found df.index.get_level_values(0), but it returns all the values and that causes loop to run multiple times for a given day. I want to create a Dataframe per day and send it for processing.
One easy way would be to groupby the first level of the index - iterating over the groupby object will return the group keys and a subframe containing each group.
In [136]: for date, new_df in df.groupby(level=0):
...: print(new_df)
...:
observation1 observation2
date Time
2012-11-02 9:15:00 79.373668 224
9:16:00 130.841316 477
observation1 observation2
date Time
2012-11-03 9:15:00 45.312814 835
9:16:00 123.776946 623
9:17:00 153.766460 624
9:18:00 463.276946 626
9:19:00 663.176934 622
9:20:00 763.773330 621
observation1 observation2
date Time
2012-11-04 9:15:00 115.449437 122
9:16:00 123.776946 555
9:17:00 153.766460 344
9:18:00 463.276946 212
You can also use droplevel to remove the first index (the useless date index):
In [136]: for date, new_df in df.groupby(level=0):
...: print(new_df.droplevel(0))
...:
observation1 observation2
Time
9:15:00 79.373668 224
9:16:00 130.841316 477
...
That helps!. I was following rather roundabout way - first finding index lable and then slicing it using iloc.
Where has this been for the last 3 years of my life. Such a clean method thank you!
This method is neat, but how to apply changes from these subframes to the main dataframe? Searching it through loc or iloc makes the computations extremely slow.
@Manaslu if you can wrap the changes into a function you can use df.groupby('key').apply(function)
Great! Fast and clean way to solve the problem. This is much faster than iterating over dates and getting df.loc[date].
I am facing a similar problem. Can this multiindex dataframe be grouped by observation instead of date?
@SoumyaC You can group by "time" with df.groupby(level=1) (or df.groupby(level="Time") ... or iterate column by column with df.items()
What about this?
for idate in df.index.get_level_values('date'):
complex_process(df.ix[idate], idate)
Careful with this solution, note that each value of idate can be hit multiuple times.
You should be doing
for idate in np.unique(df.index.get_level_values('date')):
Note tha additional np.unique.
I think df.index.get_level_values('date').unique() may better as @melbay pointed out.
Tagging off of @psorenson answer, we can get unique level indices and its related data frame slices without numpy as follows:
for date in df.index.get_level_values('date').unique():
print(df.loc[date])
Late to the party, I found that the following works, too:
for date in df.index.unique("date"):
print(df.loc[date])
It uses the level optional parameter of the Index.unique method introduced in version 0.23.0.
You can specify either the level number or label.
Another alternative:
for date in df.index.levels[0]:
print(df.loc[date])
The difference with the df.index.unique("date") proposed by @sanzoghenzo is that it refers to the index level by its number rather than name.
| common-pile/stackexchange_filtered |
security of cipher due to subsequent permutations
I am recently studying Mathematics of Cryptography from book by B. Forouzan in which I came across permutation groups.
a set of permutations with the composition operation is a group. This
implies that using two permutations one after another cannot
strengthen the security of a cipher, because we can always find a
permutation that can do the same job because of the closure property.
I did not understand the part :
always find a permutation that can do the same job because of the
closure property
Can anyone Please explain?
This doesn't really feel on-topic for SO to me, since it's a purely mathematical / cryptographical question. You might want to ask it over at [crypto.SE] instead. You might also want to take a look at this existing question there.
Better asked on Cryptography because it is not about software develop.
Also asked and answered on crypto. This question needs to be closed here.
I think the rough idea behind that quote is something like this.
Assume you have a set of all permutations of "abc", that is:
Your set is: "abc" ,"acb", "bca", "bac", "cab, "cba".
Let's take "abc".
Permute it once and get say: "cba" (Let's say permuting once means you encrypt it).
Now let's assume you want to strengthen above permutation by permuting it once again (encrypt it once more), e.g. now you permute "cba" and arrive at "bac".
That quote says that in theory you could have arrived at "bac" from "abc" in a single permutation too (in a single encryption), thus your additional permutation didn't really make much sense from this point of view. Because it says basically what you can do in two permutations you can effectively also do in a single permutation.
shouldn't it be "That quote says that in theory you could have arrived at "bac" from "abc" in a single permutation too (in a single encryption)" instead of "That quote says that in theory you could have arrived at "bac" from "cba" in a single permutation too (in a single encryption)"?
@POOJAGUPTA yes like that.
| common-pile/stackexchange_filtered |
I want to insert a link in an email in cakephp
i want to send a mail to users, the mail is sending , but the link in it is now showing as a link, I also want to embed a logo in the mail but the logo is not showing, below is my code. I am using cake 2.8
$Email = new CakeEmail();
<EMAIL_ADDRESS>Africal College of Surgeons'));
$Email->to($email);
$Email->subject('Reviewer Invitation From West African College of Surgeons');
$Email->send('Dear Reviewer, You have been invited by the Head of Faculty of $faculty from the West'
. 'African College of Surgeons to register as a reviewer. Please click on the link '
. 'below to register'
. 'http://wacscoac.org/edms/users/addreviewer');
$Email->attachments('img/logo.png');
Assuming you want the logo to be also the link:
I think the best way is to use a template so you can use the Html helper inside your .ctp file
$Email->attachments(['img/logo.png'=> [
'file' => 'img/logo.png',
'mimetype' => 'image/png',
'contentId' => 'logo'
]]);
$Email->template('test');
$Email->emailFormat('html');
$Email->viewVars(array(
'faculty' => "Faculty",
));
$Email->send();
Specifying the contentId is useful if you want the attachment inline, as explained in the manual here
After that you have to create a template in \src\Template\Email\html\test.ctp
<p>Dear Reviewer,</p>
<p>You have been invited by the Head of Faculty of <?= $faculty ?>
from the West African College of Surgeons to register as a reviewer.</p>
<p>Please click on the link below to register</p>
<?= $this->Html->link(
'<img src="cid:logo" alt="">',
'http://wacscoac.org/edms/users/addreviewer',
['escape' => false]);
?>
In my own opinion i would use HTML tags
<a href = "site you desire">Link tage</a>
But keep in mind that you need to set
$headers .= "Content-type: text/html\r\n";
for the email , good luck.
$link = '<a href="http://wacscoac.org/edms/users/addreviewer"'>
<img src="img/logo.png" alt="">
</a>';
and then
$Email->send('Dear Reviewer, You have been invited by the Head of aculty of $faculty from the West'
. 'African College of Surgeons to register as a reviewer. Please click on the link '
. 'below to register'
. $link);
@ AIPD TECH, thanks, but this is the error i got Error: Call to a member function image() on a non-object
thanks, but what if the logo.png is in the webroot folder?
Just remove the img from path. I will suggest to use template for sending email. $Email->emailFormat('html');
| common-pile/stackexchange_filtered |
What is the difference between / and /* in web.xml
I am seeing 2 different URL pattern in web.xml. May I know what kind of URL matches with this pattern. It would be great if anyone explain this with example.
<filter-mapping>
<filter-name>samplewithstar</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>samplewithoutstar</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
Does this answer your question? Difference between / and /* in servlet mapping url pattern
When you give /* it will select all the html tags.
| common-pile/stackexchange_filtered |
Approach to roll down a Covered Call
If I sell a covered call and the stock declines some time before expiry, what would be a strategic approach to roll down the call to protect the downside, or are there any other approach to do it? Do I just buy back the call and sell another at lower strike?
I am not worried about losing upside potential and only considering premium as profit from this trade.
By definition, you are 'losing upside potential' when you write a covered call (CC). It has an asymmetric risk profile with a limited upside while bearing most of the downside risk.
The delta of the call represents how much the call will deteriorate for the first dollar of underlying loss. Since delta declines as share price drops, the smaller delta gets, the larger your loss will become. Rolling down is a defensive strategy which only provides a limited hedge which will only modestly 'protect the downside'.
Alternatively, you can use in-the-money (ITM) short calls. That will provide more premium and more protection but is likely to lock in an upside loss. In addition, using deeper ITM (in the U.S.) may result in a non qualified CC which causes loss of LT status in the underlying. So unless you are willing to take the risk, when rolling the CC down, you should avoid locking in a loss should the underlying reverse strongly to the upside.
The most efficient way to roll the call down would be using a vertical spread order rather than legging out of the initial short call and into the new short call. You'll have a better chance of shaving something off of both B/A spreads and it will eliminate the market risk of the underlying moving down between single executions.
IMO, a more 'strategic approach' for the current volatility in the market would be to collar your long stock positions at little to no cost. It could even be done for a small credit, depending on the strikes chosen. You'd give up the short call premium to pay for the long put but that would put a loss limit under your positions. It's synthetically equivalent to a vertical spread. Should the underlying collapse, you could either exit at the predetermined loss or if you want to continue owning the underlying, roll the put and call down, lowering your cost basis.
There are more sophisticated and aggressive approaches such as over writing short calls (CC or collar) as well as buying more puts for a collar but that's for those who understand, accept and can manage the risk.
There are a few old sayings about covered calls"
"Sometimes it like picking up peanuts in front of a steamroller"
" Most of the time you eat like a bird and sometimes, you sh*t like an elephant"
Covered calls are for providing income or executing a target sale price. They're not a good plan for bear markets.
| common-pile/stackexchange_filtered |
Multiple Full outer join on store number
I have a SQL Server query that shows each store number, sales for today vs. sales for last year. From two different tables.
Now I would like to add another table that shows the store name. How can I do that?
The store name is found in a table called [Company$Store] and the field "Name".
I want it to Join on [Company$Store].No_ = [Company$Trans_ Sales Entry].[Store No_]
This is the query where i want to add it:
Select t.Store, t.Sales, a.[Last year]
From (Select [Company$Trans_ Sales Entry].[Store No_] As Store,
Sum([Company$Trans_ Sales Entry].[Net Amount] * -1) As Sales
From [Company$Trans_ Sales Entry]
Where [Company$Trans_ Sales Entry].Date = Convert(date,GetDate())
And [Company$Trans_ Sales Entry].[Store No_] Not Like '5%'
Group By [Company$Trans_ Sales Entry].[Store No_]
) t
Full Outer Join
(Select [Company$Archived Sales Entry].[Store No_] As Store,
Sum([Company$Archived Sales Entry].[Net Amount] * -1) As [Last year]
From [Company$Archived Sales Entry]
Where [Company$Archived Sales Entry].Date = Convert(date,DateAdd(week, -52, GetDate()))
Group By [Company$Archived Sales Entry].[Store No_]
) a
On a.Store = t.Store
Order By t.Store
Hope someone can help!
Select [Company$Trans_ Sales Entry].[Store No_] As Store, [Company$Store].[Name],
Sum([Company$Trans_ Sales Entry].[Net Amount] * -1) As Sales
From [Company$Trans_ Sales Entry]
JOIN [Company$Store]
ON [Company$Store].No_ = [Company$Trans_ Sales Entry].[Store No_]
Where [Company$Trans_ Sales Entry].Date = Convert(date,GetDate())
And [Company$Trans_ Sales Entry].[Store No_] Not Like '5%'
Group By [Company$Trans_ Sales Entry].[Store No_], [Company$Store].[Name]
| common-pile/stackexchange_filtered |
PDF digital signature: seed value dictionary, MDP (PDF 1.7 32000-1:2008)
The PDF 1.7 specification says:
seed value dictionary, Key MDP: "[..] A value of 0 defines the signature as an author signature (see 12.8, “Digital Signatures”). The values 1 through 3 shall be used for certification signatures and correspond to the value of P in a DocMDP transform parameters dictionary (see Table 254). [..]"
My questions:
Author signature is a synonym for certification signature, isn't it?
If author signature is equivalent to certification signature:
The differentation between 0 (author signature) and 1-3 (certification signature) seems irritating. What is the idea behind?
Or went something wrong and the specification means approval signature instead of author signature? (The Java doc of the Adobe AEM Forms API supports this, see setMdpValue)
If approval signature is meant:
Setting the MDP (in seed value dictionary) to 0 would require an approvale signature. Would that imply that any changes to the document will invalidate the signature?
Generell question to approval signature:
Does an approval signature really protect the signed document from any changes? (An approval signature can have a FieldMDP, so changes to fields can be allowed?)
Final question:
I'd like to predefine a signature field, where the signer shall attach an approval signature, that will get invalid by any changes to the signed document. How to do this? (By setting the MDP (in seed value dictionary) to 0?)
Thanks for any answers, also to a subset of my questions.
Concerning the first questions: you can safely assume that a MDP seed value of 0 indicates that the signature shall be an approval signature.
ISO 32000-1 does not know the term "author signature". The PDF Reference 1.7 (from which the ISO norm is derived) uses the term "author signature" for what now is known as "certification signature", but the corresponding except from the reference explicitly says that MDP seed 0 means "not an author signature":
A value of 0 defines the signature as
an ordinary (non-author) signature
Concerning questions 4 & 5: No, an approval signature without any further ado is the type of signature that allows the most changes, slightly more than MDP 3, cf. this answer on stack overflow.
Concerning your final question: consider using a signature field lock dictionary with an Action value All to lock all form fields. Unfortunately this still allows certain changes. If you are prepared to use a PDF 2.0 feature, though, you can set LockDocument to true in the signature field seed value dictionary and also set bit 8 in the Ff value there to make that seed mandatory.
the corresponding except from the reference explicitly says that MDP seed 0 means "not an author signature" -> regarding this document from this page the reference says author signature, I have not the ISO document maybe there it is correct
consider using a signature field lock dictionary with an Action value All to lock all form fields. -> okay, to reach this, I just would set the lock dictionary (key Action) to "All"? In combination with a MDP seed value of 0 the signature is an approval signature which get invalid by changing any field values?
"okay, to reach this, I just would ..." - In theory yes. I don't know whether this is interoperably implemented. In particular I think that many PDF signature validators don't analyze the changes in additional document revisions but instead merely indicate that the signature applies to a former document revision. Adobe Acrobat, on the other hand, can be expected to honor the field lock mechanism.
| common-pile/stackexchange_filtered |
How do I get link and text when the <a> wraps another element using XPath?
The example below reflects data similar to what I'm using (I can't show my live data, due to company policy). It is pulled from this answer and this answer.
My goal is to pull the text of the <a> element, as well as the link itself.
from lxml import html
post1 = """<p><code>Integer.parseInt</code> <em>couldn't</em> do the job, unless you were happy to lose data. Think about what you're asking for here.</p>

<p>Try <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Long.html#parseLong%28java.lang.String%29"><code>Long.parseLong(String)</code></a> or <a href="http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#BigInteger%28java.lang.String%29"><code>new BigInteger(String)</code></a> for really big integers.</p>

"""
post2 = """
<p><code>Integer.parseInt</code> <em>couldn't</em> do the job, unless you were happy to lose data. Think about what you're asking for here.</p>

<p>Try <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Long.html#parseLong%28java.lang.String%29"><code>Long.parseLong(String)</code></a> or <a href="http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#BigInteger%28java.lang.String%29"><code>new BigInteger(String)</code></a> for really big integers.</p>

"""
doc = html.fromstring(post1)
for link in doc.xpath('//a'):
print link.text, link.get('href')
Unfortunately, this returns the following:
None http://docs.oracle.com/javase/7/docs/api/java/lang/Long.html#parseLong%28java.lang.String%29
None http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#BigInteger%28java.lang.String%29
Notice that my link.text is empty. This is because the link wraps a <code> block.
If I use post2, it returns the correct results:
PROJ.4 http://trac.osgeo.org/proj/
OpenSceneGraph http://www.openscenegraph.org/
How can I modify my loop to handle both the standard URL (post2) and a link wrapping another object (post1)?
Change
print link.text, link.get('href')
to
print link.text_content(), link.get('href')
then your output will be
Long.parseLong(String) http://docs.oracle.com/javase/7/docs/api/java/lang/Long.html#parseLong%28java.lang.String%29
new BigInteger(String) http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#BigInteger%28java.lang.String%29
for both post1 and post2 as requested.
| common-pile/stackexchange_filtered |
An integral inequality involving exponentials and $H^1(\mathbb{R}^2)$
Let $\beta, \alpha>1$, and $u \in H^1(\mathbb{R}^2$). I'm trying to show that $$\int_{\mathbb{R}^2}\left(e^{\beta u^2(x)} -1\right)^{2\alpha}dx \leq \int_{\mathbb{R}^2}(e^{2\alpha \beta u^2(x)}-1)dx$$
I tried to use a series expansion of the exponential and the fact that $u \in L^q(\mathbb{R}^2)$ for every $q\geq 2 $, but did not make much progress. Any help is much appreciated.
Did you try polar coordinates .? This reminds me integral of $e^{x^2}$ and i suppose you integrate on du or $d \alpha$?
The integral is over $\mathbb{R}^2$, and the function $u$ need not be radial, so I'm not completely sure how to use polar, but I'll give it a shot.
This has nothing to do with $L^p$ or $H^1$, this follows simply from the estimate $(x-y)^\alpha \leq x^\alpha - y^\alpha$ for $0\leq y \leq x$ and $\alpha>1$ (if we were lazy, we would only consider $y=1$ which is all we need here).
To see the above inequality, note that this is equivalent to showing that $$f(s)=1-s^\alpha -(1-s)^\alpha\geq 0$$ for $s\in [0,1]$ (divide the original inequality by $x^\alpha$ for $x\neq 0$). The new inequality follows immediately from $f(0)=f(1)$ and $$f''(s) = \alpha (\alpha-1)(-s^{\alpha-2}-(1-s)^{\alpha-2})<0$$ for $s\in (0,1)$.
| common-pile/stackexchange_filtered |
asp sitemap for a folder
I want to create a sitemap for my application. Is it possible to point a node to a folder so all pages in this folder will have the role set by the node?
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode title="Private Pages" roles="Provate" url="">
<siteMapNode title="Secure folder" url="/MainFolder">
</siteMapNode>
</siteMapNode>
Thanks to anyone who can help
Roles for a folder are not set in your sitemap. You should rather create a local web.config file in the folder and setup your authorization rules there.
What you CAN do in a sitemap is to have a node visible or invisible to users and all subnodes can inherit the setting.
Note that whether or not a user can SEE a link in your menu is not related to whether or not the user can ACCESS the resource by pointing the browser to resource's url.
That's why you should have both: authorization rules in local configuration files (to prevent users from accessing resources) and sitemap rules (to prevent users from seeing links in the menu).
| common-pile/stackexchange_filtered |
How to understand the proof of disjoint closed set with distance $d > 0$
I am not student in Mathematics.
The following proof comes from the book: Real Analysis, by Elias and Rami (p.18):
The folloing is my problem:
It seems the yellow part implies the result (but it does not prove anything). What is the difference between the yellow part and the conclusion $d(K,F)\geq\delta>0$? (Hope to know the logic of this proof)
If no the condition "$K$ is compact", just "$K$ is closed", then there may not exist $\delta_x>0$ such that $d(x,F)>3\delta_x$. Correct?
I am not sure I understand your second problem. Could you clarify it?
That $3\delta_x$ exists is due to the fact that $x\in K$ implies $x\notin F$ by the assumption that the sets are disjoint, and since $F$ is closed its complement is open, so we may find an open ball around $x$ disjoint from $F$. The condition that $K$ is compact is only used to reduce the cover to a finite subcover.
About the first problem, it is a common procedure in these proofs: the point is that here you can take whatever $\delta_x$, so in particular you pick one (in this case $3\delta_x$) that becomes handy to establish the conclusion.
BTW, the finiteness of the subcover is relevant in order to be able to ensure that $\min(\delta_1,...,\delta_ N)$ is greater than zero. For infinitely many $\delta_x>0$ we would have $\inf({\delta_x})$ which could possibly be zero.
@Kolmin , clearly speaking, can I use the yellow part to prove $d(F,K)>0$?
What I will say so is because the yellow statement says for each $x\in K$, $d(x,F)>3\delta_x$. So $d(F,K)>0$? Maybe I am not quite familiar with the way of proof in real analysis.
The second problem just says if I change the condition to "$K$ is closed" (may not be compact). Then $\delta_x$ may not exist?
d(x,F)>3δx>δx>0 for each x∈K, hence d(K,F)>0? Why are you not done when you show δx>0 exists via line 1? Is the proof done with just the assertion that "F is closed" and "F and K are disjoint"?
Example that the distance between 2 closed disjoint sets can be 0 is here.
@ililil so just confirm your answer. Your answer is that to the line 1(yellow part), we still have to show $\delta_x$ indeed $>0$?
Similar question here with solution.
@sleevechen "the yellow statement says for each $x∈K, d(x,F)>3δ_x$ . So $d(F,K)>0d(F,K)>0$?" No, because the definition of $d(A,B)$ is $inf{d(x,y)|x∈A, y∈B}$ while $d(x,B)> \delta_x$ for each $x \in x$ only means $inf{d(x,y)|y \in B}> \delta_x$ for each $x \in A$ so $d(A,B)=inf{d(x,y)|x∈A, y∈B}=inf{d(x,B)|x∈A}$ could still be zero.
| common-pile/stackexchange_filtered |
How to fetch an entire paginated list / refetch the entire paginated list?
I have a "classic" cursor based pagination of items.
I have to do two things with this items:
fetch all items of this list when components did mount
refetch all the list when a button is pressed
Using react-apollo for the first point my solution is:
use a Query component to load the first data set
when the last fetched data set is loaded I get the endCursor from it
use the endCursor and the fetchMore (from the Query render props) to load the next data set (passing variables and updateQuery to the fetchMore function)
if there are more results loop to #2
For the second solution:
I'm using refetch (from the Query render props) to reload the piece of the store with new data
Use the same loop of the first solution (with the loadMore function) to fetch other results
All of these implementations are not so easy to write / maintain / reuse, so my question are:
am I missing something? there is a better solution to this scenario?
| common-pile/stackexchange_filtered |
android studio doesn't start on mac
I installed Android Studio, but it doesn't run normally.
OS: macos Big Sur 11.1 (20C69)
android studio version: android-studio-ide-201.6953283-mac
java version: 1.8
~ java -version
java version "1.8.0_231"
Java(TM) SE Runtime Environment (build 1.8.0_231-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.231-b11, mixed mode)
When I ran it with a double click, it stopped loading as shown in the screenshot below.
So I tried running it in cli. The program was run but some error logs:
~ sudo /Applications/Android\ Studio.app/Contents/MacOS/studio
Password:
2021-01-02 14:28:27.213 studio[24845:598977] allVms required 1.8*,1.8+
2021-01-02 14:28:27.214 studio[24845:598977] Can't find bundled java.The folder doesn't exist: /Applications/Android Studio.app/Contents/jbr
2021-01-02 14:28:27.214 studio[24845:598977] Can't find bundled java.The folder doesn't exist: /Applications/Android Studio.app/Contents/jdk
2021-01-02 14:28:27.234 studio[24845:598986] WorkingDirectory is absent in Info.plist. Current Directory: /Users/centell
2021-01-02 14:28:27.234 studio[24845:598986] fullFileName is: /Applications/Android Studio.app/Contents/bin/studio.vmoptions
2021-01-02 14:28:27.234 studio[24845:598986] fullFileName exists: /Applications/Android Studio.app/Contents/bin/studio.vmoptions
2021-01-02 14:28:27.234 studio[24845:598986] Value of STUDIO_VM_OPTIONS is (null)
2021-01-02 14:28:27.234 studio[24845:598986] Processing VMOptions file at /Applications/Android Studio.app/Contents/bin/studio.vmoptions
2021-01-02 14:28:27.235 studio[24845:598986] Done
2021-01-02 14:28:27.235 studio[24845:598986] Processing VMOptions file at /var/root/Library/Application Support/Google/AndroidStudio4.1/studio.vmoptions
2021-01-02 14:28:27.237 studio[24845:598986] Done
2021-01-02 14:28:27.237 studio[24845:598986] Processing VMOptions file at
2021-01-02 14:28:27.241 studio[24845:598986] No content found
2021-01-02 14:28:32,835 [ 3815] WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.AndroidInitialConfigurator)
2021-01-02 14:28:35,525 [ 6505] WARN - nSystem.impl.ActionManagerImpl - keymap "Xcode" not found [Plugin: com.intellij]
2021-01-02 14:28:35,746 [ 6726] WARN - nSystem.impl.ActionManagerImpl - keymap "ReSharper" not found [Plugin: com.android.tools.ndk]
2021-01-02 14:28:35,966 [ 6946] WARN - nsions.impl.ExtensionPointImpl - Extension to be removed not found: class org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer
2021-01-02 14:28:37,602 [ 8582] WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=org.jetbrains.android.compose.AndroidComposeAutoDocumentation)
2021-01-02 14:28:37,820 [ 8800] WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.apk.ApkProjectComponent)
2021-01-02 14:28:37,821 [ 8801] WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.apk.issues.SetupIssueReporter)
2021-01-02 14:28:40,418 [ 11398] WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.apk.symbols.DebugSymbolNotifications)
2021-01-02 14:28:43,214 [ 14194] WARN - ugins.textmate.TextMateService - Missing builtin bundles, checked:
/var/root/Library/Application Support/Google/AndroidStudio4.1/plugins/textmate/lib/bundles
/Applications/Android Studio.app/Contents/plugins/textmate/lib/bundles
2021-01-02 14:28:45,652 [ 16632] WARN - com.intellij.util.xmlb.Binding - no accessors for class org.jetbrains.kotlin.idea.highlighter.KotlinDefaultHighlightingSettingsProvider
2021-01-02 14:28:46,671 [ 17651] WARN - #com.android.ddmlib - * daemon not running; starting now at tcp:5037
2021-01-02 14:28:46,967 [ 17947] WARN - #com.android.ddmlib - * daemon started successfully
2021-01-02 14:28:47,603 [ 18583] WARN - openapi.wm.impl.ToolWindowImpl - ToolWindow icons should be 13x13. Please fix ToolWindow (ID: Problems View) or icon jar:file:/Applications/Android%20Studio.app/Contents/lib/icons.jar!/general/warning.svg
2021-01-02 14:28:47,928 [ 18908] WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.apk.ApkWritingAccessProvider)
2021-01-02 14:28:48,778 [ 19758] WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.gradle.notification.GeneratedFileNotificationProvider)
2021-01-02 14:28:48,820 [ 19800] WARN - Container.ComponentManagerImpl - Do not use constructor injection (requestorClass=com.android.tools.idea.apk.editor.notification.ApkReloadNotificationProvider)
2021-01-02 14:28:52.581 studio[24845:598977] Warning: Expected min height of view: (<NSButtonJAction: 0x7fa1cb28bcd0>) to be less than or equal to 30 but got a height of 32.000000. This error will be logged once per view in violation.
2021-01-02 14:29:05,916 [ 36896] ERROR - ellij.util.text.DateFormatUtil - Unable to load library 'CoreFoundation':
dlopen(libCoreFoundation.dylib, 9): image not found
dlopen(libCoreFoundation.dylib, 9): image not found
Native library (darwin/libCoreFoundation.dylib) not found in resource path (/Applications/Android Studio.app/Contents/lib/bootstrap.jar:/Applications/Android Studio.app/Contents/lib/extensions.jar:/Applications/Android Studio.app/Contents/lib/util.jar:/Applications/Android Studio.app/Contents/lib/jdom.jar:/Applications/Android Studio.app/Contents/lib/log4j.jar:/Applications/Android Studio.app/Contents/lib/trove4j.jar:/Applications/Android Studio.app/Contents/lib/jna.jar:/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/lib/tools.jar)
java.lang.UnsatisfiedLinkError: Unable to load library 'CoreFoundation':
dlopen(libCoreFoundation.dylib, 9): image not found
dlopen(libCoreFoundation.dylib, 9): image not found
Native library (darwin/libCoreFoundation.dylib) not found in resource path (/Applications/Android Studio.app/Contents/lib/bootstrap.jar:/Applications/Android Studio.app/Contents/lib/extensions.jar:/Applications/Android Studio.app/Contents/lib/util.jar:/Applications/Android Studio.app/Contents/lib/jdom.jar:/Applications/Android Studio.app/Contents/lib/log4j.jar:/Applications/Android Studio.app/Contents/lib/trove4j.jar:/Applications/Android Studio.app/Contents/lib/jna.jar:/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/lib/tools.jar)
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:302)
at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:455)
at com.sun.jna.Library$Handler.<init>(Library.java:192)
at com.sun.jna.Native.load(Native.java:596)
at com.sun.jna.Native.load(Native.java:570)
at com.intellij.util.text.DateFormatUtil.getMacFormats(DateFormatUtil.java:363)
at com.intellij.util.text.DateFormatUtil.getDateTimeFormats(DateFormatUtil.java:303)
at com.intellij.util.text.DateFormatUtil.<clinit>(DateFormatUtil.java:46)
at com.intellij.ide.fileTemplates.impl.FileTemplateManagerImpl.getDefaultProperties(FileTemplateManagerImpl.java:158)
at com.intellij.ide.fileTemplates.FileTemplateUtil.templateToRegex(FileTemplateUtil.java:426)
at com.intellij.ide.fileTemplates.FileTemplateUtil.getTemplatePattern(FileTemplateUtil.java:418)
at com.intellij.codeInspection.defaultFileTemplateUsage.FileHeaderChecker.checkFileHeader(FileHeaderChecker.java:52)
at com.intellij.codeInspection.defaultFileTemplateUsage.DefaultFileTemplateUsageInspection.checkFile(DefaultFileTemplateUsageInspection.java:58)
at com.intellij.codeInspection.AbstractBaseJavaLocalInspectionTool$1.visitFile(AbstractBaseJavaLocalInspectionTool.java:67)
at com.intellij.psi.impl.source.xml.XmlFileImpl.accept(XmlFileImpl.java:57)
at com.intellij.codeInspection.InspectionEngine.acceptElements(InspectionEngine.java:69)
at com.intellij.codeInspection.InspectionEngine.createVisitorAndAcceptElements(InspectionEngine.java:60)
at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.runToolOnElements(LocalInspectionsPass.java:297)
at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.lambda$null$3(LocalInspectionsPass.java:266)
at com.intellij.util.AstLoadingFilter.forceAllowTreeLoading(AstLoadingFilter.java:155)
at com.intellij.util.AstLoadingFilter.forceAllowTreeLoading(AstLoadingFilter.java:147)
at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.lambda$null$4(LocalInspectionsPass.java:265)
at com.intellij.util.AstLoadingFilter.disallowTreeLoading(AstLoadingFilter.java:126)
at com.intellij.util.AstLoadingFilter.disallowTreeLoading(AstLoadingFilter.java:115)
at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.lambda$visitPriorityElementsAndInit$5(LocalInspectionsPass.java:265)
at com.intellij.concurrency.ApplierCompleter.execAndForkSubTasks(ApplierCompleter.java:149)
at com.intellij.openapi.application.impl.ApplicationImpl.tryRunReadAction(ApplicationImpl.java:1104)
at com.intellij.concurrency.ApplierCompleter.lambda$wrapInReadActionAndIndicator$1(ApplierCompleter.java:105)
at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:627)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:572)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:61)
at com.intellij.concurrency.ApplierCompleter.wrapInReadActionAndIndicator(ApplierCompleter.java:117)
at com.intellij.concurrency.ApplierCompleter.lambda$compute$0(ApplierCompleter.java:96)
at com.intellij.openapi.application.impl.ReadMostlyRWLock.executeByImpatientReader(ReadMostlyRWLock.java:168)
at com.intellij.openapi.application.impl.ApplicationImpl.executeByImpatientReader(ApplicationImpl.java:168)
at com.intellij.concurrency.ApplierCompleter.compute(ApplierCompleter.java:96)
at com.intellij.concurrency.JobLauncherImpl.invokeConcurrentlyUnderProgress(JobLauncherImpl.java:55)
at com.intellij.concurrency.JobLauncher.invokeConcurrentlyUnderProgress(JobLauncher.java:49)
at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.visitPriorityElementsAndInit(LocalInspectionsPass.java:269)
at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.inspect(LocalInspectionsPass.java:193)
at com.intellij.codeInsight.daemon.impl.LocalInspectionsPass.collectInformationWithProgress(LocalInspectionsPass.java:115)
at com.intellij.codeInsight.daemon.impl.ProgressableTextEditorHighlightingPass.doCollectInformation(ProgressableTextEditorHighlightingPass.java:84)
at com.intellij.codeHighlighting.TextEditorHighlightingPass.collectInformation(TextEditorHighlightingPass.java:52)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$null$1(PassExecutorService.java:442)
at com.intellij.openapi.application.impl.ApplicationImpl.tryRunReadAction(ApplicationImpl.java:1109)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$doRun$2(PassExecutorService.java:435)
at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:627)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:572)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:61)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.doRun(PassExecutorService.java:434)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$run$0(PassExecutorService.java:410)
at com.intellij.openapi.application.impl.ReadMostlyRWLock.executeByImpatientReader(ReadMostlyRWLock.java:168)
at com.intellij.openapi.application.impl.ApplicationImpl.executeByImpatientReader(ApplicationImpl.java:168)
at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.run(PassExecutorService.java:408)
at com.intellij.concurrency.JobLauncherImpl$VoidForkJoinTask$1.exec(JobLauncherImpl.java:171)
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Suppressed: java.lang.UnsatisfiedLinkError: dlopen(libCoreFoundation.dylib, 9): image not found
at com.sun.jna.Native.open(Native Method)
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:191)
... 58 more
Suppressed: java.lang.UnsatisfiedLinkError: dlopen(libCoreFoundation.dylib, 9): image not found
at com.sun.jna.Native.open(Native Method)
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:204)
... 58 more
Suppressed: java.io.IOException: Native library (darwin/libCoreFoundation.dylib) not found in resource path (/Applications/Android Studio.app/Contents/lib/bootstrap.jar:/Applications/Android Studio.app/Contents/lib/extensions.jar:/Applications/Android Studio.app/Contents/lib/util.jar:/Applications/Android Studio.app/Contents/lib/jdom.jar:/Applications/Android Studio.app/Contents/lib/log4j.jar:/Applications/Android Studio.app/Contents/lib/trove4j.jar:/Applications/Android Studio.app/Contents/lib/jna.jar:/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/lib/tools.jar)
at com.sun.jna.Native.extractFromResourcePath(Native.java:1095)
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:276)
... 58 more
2021-01-02 14:29:05,927 [ 36907] ERROR - ellij.util.text.DateFormatUtil - Android Studio 4.1.1 Build #AI-201.87<IP_ADDRESS>53283
2021-01-02 14:29:05,927 [ 36907] ERROR - ellij.util.text.DateFormatUtil - JDK: 1.8.0_242-release; VM: OpenJDK 64-Bit Server VM; Vendor: JetBrains s.r.o
2021-01-02 14:29:05,927 [ 36907] ERROR - ellij.util.text.DateFormatUtil - OS: Mac OS X
2021-01-02 14:29:05,928 [ 36908] ERROR - ellij.util.text.DateFormatUtil - Last Action:
2021-01-02 14:29:24.395 studio[24845:598977] Warning: Expected min height of view: (<NSButtonJAction: 0x7fa1cebf3f70>) to be less than or equal to 30 but got a height of 32.000000. This error will be logged once per view in violation.
2021-01-02 14:29:24.395 studio[24845:598977] Warning: Expected min height of view: (<NSButtonJAction: 0x7fa1cebf56b0>) to be less than or equal to 30 but got a height of 32.000000. This error will be logged once per view in violation.
2021-01-02 14:29:24.396 studio[24845:598977] Warning: Expected min height of view: (<NSButtonJAction: 0x7fa1cebf6a00>) to be less than or equal to 30 but got a height of 32.000000. This error will be logged once per view in violation.
2021-01-02 14:29:24.397 studio[24845:598977] Warning: Expected min height of view: (<NSButtonJAction: 0x7fa1cc67aa30>) to be less than or equal to 30 but got a height of 32.000000. This error will be logged once per view in violation.
2021-01-02 14:29:25.355 studio[24845:598977] Warning: Expected min height of view: (<NSButtonJAction: 0x7fa1cc737760>) to be less than or equal to 30 but got a height of 32.000000. This error will be logged once per view in violation.
2021-01-02 14:29:25.356 studio[24845:598977] Warning: Expected min height of view: (<NSButtonJAction: 0x7fa1cc6e47f0>) to be less than or equal to 30 but got a height of 32.000000. This error will be logged once per view in violation.
2021-01-02 14:29:25.357 studio[24845:598977] Warning: Expected min height of view: (<NSButtonJAction: 0x7fa1cc738d20>) to be less than or equal to 30 but got a height of 32.000000. This error will be logged once per view in violation.
2021-01-02 14:29:25.357 studio[24845:598977] Warning: Expected min height of view: (<NSButtonJAction: 0x7fa1cc73a1b0>) to be less than or equal to 30 but got a height of 32.000000. This error will be logged once per view in violation.
2021-01-02 14:29:25.358 studio[24845:598977] Warning: Expected min height of view: (<NSButtonJAction: 0x7fa1cc73b5c0>) to be less than or equal to 30 but got a height of 32.000000. This error will be logged once per view in violation.
2021-01-02 14:29:25.838 studio[24845:598977] Warning: Expected min height of view: (<NSButtonJAction: 0x7fa1cc197840>) to be less than or equal to 30 but got a height of 32.000000. This error will be logged once per view in violation.
2021-01-02 14:29:25.840 studio[24845:598977] Warning: Expected min height of view: (<NSButtonJAction: 0x7fa1cc1987f0>) to be less than or equal to 30 but got a height of 32.000000. This error will be logged once per view in violation.
2021-01-02 14:29:28,238 [ 59218] WARN - com.intellij.util.xmlb.Binding - no accessors for class org.jetbrains.kotlin.idea.scripting.gradle.GradleScriptInputsWatcher$Storage
2021-01-02 14:29:28,258 [ 59238] WARN - com.intellij.util.xmlb.Binding - no accessors for class org.jetbrains.kotlin.idea.core.script.configuration.utils.ScriptClassRootsStorage
How do I run Android Studio normally?
I am still facing the same issue. So I installed IntelliJ IDEA and Android development with it.
Your log tells the error:
2021-01-02 14:28:27.214 studio[24845:598977] Can't find bundled java.The folder doesn't exist: /Applications/Android Studio.app/Contents/jbr
2021-01-02 14:28:27.214 studio[24845:598977] Can't find bundled java.The folder doesn't exist: /Applications/Android Studio.app/Contents/jdk
You can try to reinstall Java.
or else, Try to reinstall android Studio and check if it works.
I think the problem is that MacOS is still trying or has failed to verify Android Studio.app. Try opening up your terminal and type in:
xattr -d com.apple.quarantine /Applications/Android\ Studio.app
This command makes sure MacOS skips verification for given App, so it should start.
I reinstalled it several times, but it does not work. Even xattr didn't solve the problem.
uninstall your JDK and redownload and install it.
or else, you can also try to delete ~/Library/Preferences/AndroidStudio and retry the above steps
I did all of that but failed. so I tried the IntelliJ idea, open it successfully.
I got an error: "No such xattr: com.apple.quarantine" ; does this not work on MacOS mojave?
Oh, I guess that meant I had already previously removed the extended attributes, and still it wasn't working, so something else is wrong.
| common-pile/stackexchange_filtered |
Removing .php extension with htaccess
I'm trying to remove the extensions from my pages in the URL bar.
Example: ../about.php => ../about
The code I'm using right now in my htaccess file is one I found here:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]
Stored it in the root of my website folder (same folder that contains the 2 webpages).
But this doesn't seem to work.. Live example here. What am I doing wrong?
Not sure what you are trying to achieve. For now it looks like it makes no sense really.
I'm trying to make my URL's cleaner by removing the .php from the url so that people can access the site by going to www.example.com/about instead of www.example.com/about.php
This is actually not how you do friendly urls
If you want your URL to look like .../about, then you need to make your link point to .../about. Read the duplicate reference, please.
You can use this code in root .htaccess for removing .php extension:
RewriteEngine on
# redirect /dir/file.php to /dir/file, important to use %{THE_REQUEST}
RewriteCond %{THE_REQUEST} \s/+(?:index)?(.*?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,L,NE]
# rewrite /dir/file to /dir/file.php
# %{DOCUMENT_ROOT}/$1\.php -f makes sure there is a matching .php file for the
# given name
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]
PS: For SEO purposes you must have first 301 rule in place otherwise it will be bad for SEO since both /about and /about.php will serve same content.
Reference: Apache mod_rewrite Introduction
Apache mod_rewrite Technical Details
Just uploaded this in my htaccess file but doesn't seem to work.. To be clear the htaccess file is in the same folder als my index.php and about.php file
That means you are not using it in DocumentRoot folder. Try updated code now.
Edit: I've placed it one folder above and now I can access the about page by going to www.jnbwd.be/test/about! But when I click on the link from the index page there is still the exentsion in the URL
Edit: gonna try the new code!
Use updated code in root .htaccess (one level above test)
Thanks man! Works great :) Is there any way you could explain the code :)?
Sure adding explanation and reference link to answer.
@jnb13 You shouldn't use 301 redirects to "make links pretty". It incurs a double roundtrip and will break POST submits. Instead, actually make your links point to what they're supposed to look like in your HTML source.
While agreeing totally with the point @deceze raised that links in HTML should be updated to to be without .php but first 301 rule is still needed for the old search engine links or other incoming links from other sites.
@anubhava Yes, such redirects are useful for SEO if the site is already live. But please make it clear that it's for that purpose, and is not the primary means of removing the extension from the URL.
I should have stated maybe that this was for SEO purpose.. But SEO wise this solution is ok?
Yes for SEO purposes you must have first 301 rule in place otherwise it will be bad for SEO since both /about and /about.php will serve same content.
| common-pile/stackexchange_filtered |
How to get the ProgID of an installed application by a command?
There are some applications that are not shown by name but by ProgID, is there any way to get the name of that key in the registry?
https://learn.microsoft.com/en-us/windows/win32/com/-progid--key
Where are these applications shown?
There are several, including Blender, antivirus, mouse software, etc. I need to get that ID but without going manually to the registry, the problem is that when you install the program generates different ProgID, it is not always the same number.
Where are you seeing these progids? Are they visible anywhere in a GUI? RegisteredApplications?
Nowhere in the GUI does this number appear
I see them in the uninstall key.
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall{25DF2B02-C761-49C6-81D9-B29B7838A9AC}
I don't know if this Powershell script can help you or not ? Get-ProgID or This Get-ProgID.ps1
Thanks, although this returns all the ProgIDs, I just need a specific one to save it in a variable
@Dave you can filter by this example and i don't know what is the name that you are looking for ? Just an example : Get-ProgID | Where-Object { $_.ProgID -like "*Namethat you Know*" }
That's the problem, the key name is not always the same. It is generated randomly at each new installation. I need to access a value inside that uninstall key but I don't see a way to get that address from the registry (because of that ProgID)
Is it the uninstall entry you are interested in and not really the progid?
I know the registry values inside that key but since I don't know the ProgID I can't access it
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall{Here is the ProgID}
With other programs there is no problem because it shows the name
Microsoft recommends that ISVs create progids in the form of Company.Appname or Company.Appname.Suffix but that is irrelevant since the uninstall key name you are interested in is not actually a progid at all! Progids are used by file/protocol associations and COM. Some browsers use Appname.Hash where the hash is calculated by hashing the path.
The uninstall key name can be anything (but hopefully does not collide with anyone else). MSI installers use a GUID (this GUID maps to something MSI related, the product code). Other installers often use some variation of the application name.
You should enumerate all the uninstall registry keys and compare the start of the key name to whatever app you are interested in and/or look at the strings (like DisplayName, Publisher and UninstallString) inside the uninstall key.
Powershell knows how to map the MSI GUIDs:
get-wmiobject Win32_Product | Format-Table IdentifyingNumber, Name
| common-pile/stackexchange_filtered |
what happens with items/lists when the creating user is deleted?
I have a user usr1 that i need to remove completely from a site collection.
usr1 has created several lists and items within these lists.
If i remove the user programmatically:
ClientContext.Web.SiteUsers.Remove(usr1)
What happens to the lists and items?
Nothing happens with the list or the item, but when a user clicks on the author name (usr1) she won't see the removed users profile page. Unless items have unique permissions only accessible by usr1, you're good to go.
| common-pile/stackexchange_filtered |
Xamarin Forms Custom renderer ios
I am trying to create a custom control .
Below is my code
public class BoxControlRenderer:ViewRenderer<BoxControl,BoxControlView>
{
BoxControlView boxControlView;
protected override void OnElementChanged (ElementChangedEventArgs<BoxControlView> e)
{
base.OnElementChanged (e);
this.lineControlView = new BoxControlView (this.Bounds);
this.SetNativeControl(this.boxControlView);
}
protected override void OnElementPropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged (sender, e);
if (e.PropertyName == BoxControlView.BoxControlProperty.PropertyName)
{
this.boxControlView.BoxControlProperty = this.Element.CheckedValue;
}
}
}
My BoxControlView View:
[Register("BoxControlView")]
public class BoxControlView :UIView
{
UIImageView imageView;
BoxControl _control;
[Export("initWithFrame:")]
public BoxControlView(CGRect bounds)
: base(bounds)
{
imageView = new UIImageView (new CGRect (0, 0, 40, 18));
}
private bool _boxControlProperty;
public bool BoxControlProperty
{
get {
return _boxControlProperty;
}
set{
value = _boxControlProperty;
OnPropertyChanged ("BoxControlProperty");
SetNeedsDisplay ();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler (this, new PropertyChangedEventArgs (propertyName));
}
public override void Draw (CoreGraphics.CGRect rect)
{
base.Draw (rect);
this.BackgroundColor = UIColor.Green;
BoxControlProperty = _control.CheckedValue;
Action OnImageViewTapped = () => {
if(BoxControlProperty)
imageView.Image = UIImage.FromFile("test1.png");
else
imageView.Image = UIImage.FromFile("test2.png");
};
var tapGesture = new UIGestureRecognizer ();
tapGesture.AddTarget (OnImageViewTapped);
imageView.AddGestureRecognizer (tapGesture);
}
}
BoxControl:
public class BoxControl :View
{
public static readonly BindableProperty BoxControlProperty = BindableProperty.Create<BoxControl, bool>(z=>z.CheckedValue,false);
public bool CheckedValue
{
get{
return (bool)GetValue (BoxControlProperty);
}
set{
SetValue (BoxControlProperty, value);
}
}
}
In the above code the onDraw method is not getting called.
While debugging the Xamarin Studio crashes if we keep any breakpoint in
protected override void OnElementChanged (ElementChangedEventArgs<CheckBoxControl> e) method or Draw method.
Do you have the DependencyService export line at the top of your renderer file?
Similar to:
[assembly: ExportRenderer (typeof (BoxControl ), typeof (BoxControlRenderer))]
I don't see it there, so I have to ask. Then again, I haven't used the most recent version of Xamarin.Forms (1.3) yet. This is how I did custom renderers for a sample project: http://www.joesauve.com/using-xamarin-auth-with-xamarin-forms/. Look for the iOS section about 1/3 of the way down the page.
| common-pile/stackexchange_filtered |
Knock Sensor using 555 Timer with a timed light
I have seen a few Knock Sensors using the Piezo Speaker and the Arduino. I am wondering if there is a way to eliminate the Arduino and utilize a 555 Timer and other simpler components so that when the Piezo sensor detects a Knock it triggers a Relay to illuminate a light either in three successive pulses lasting 3 seconds or a continuous on time of 3 seconds then off again until the next Knock? ie: (Knock: Blink Blink Blink, or Knock Light on(3 seconds)off) I apologize, I have just started learning some of this.
Look up 555 or 556 one shot mode
Use a 555 timer as a monostable with a 3 second timeout directly driving an LED, pull the 555's input up to Vcc, and trigger the 555 with a negative-going cap-coupled pulse generated by the piezo loudspeaker and amplified enough to drive the 555's trigger input to lower than Vcc/3.
| common-pile/stackexchange_filtered |
Tikz drawing layer by layer
I wanted to make a similar structure based on this example. But I'm currently stuck at this point:
The top layers should be left and rigth aligned
I think the code can be WAY better
Here is my MWE:
\documentclass{article}
\usepackage{xcolor}
\usepackage{tikz}
\usetikzlibrary{chains}
\usetikzlibrary{positioning}
\definecolor{mycolor}{RGB}{8,108,131}
\begin{document}
\begin{tikzpicture}[
scale=0.75,
start chain=1 going below,
start chain=2 going right,
node distance=1mm,
desc/.style={
scale=0.75,
on chain=2,
rectangle,
rounded corners,
draw=black,
very thick,
text centered,
text width=8cm,
minimum height=12mm,
fill=mycolor!30
},
1/.style={
fill=mycolor!10
},
2/.style={
fill=mycolor!30
},
3/.style={
fill=mycolor!50
},
4/.style={
fill=mycolor!70
},
5/.style={
fill=mycolor!70
},
level/.style={
scale=0.75,
on chain=1,
minimum height=12mm,
text width=2cm,
text centered
},
every node/.style={font=\sffamily}
]
% Levels
\node [level] (Level 5) {Layer 5};
\node [level] (Level 4) {Layer 4};
\node [level] (Level 3) {Layer 3};
\node [level] (Level 2) {Layer 2};
\node [level] (Level 1) {Layer 1};
% Descriptions
\chainin (Level 5); % Start right of Level 5
\node [desc, 5] (5) {Applications layer};
\node [ scale=0.75,
rectangle,
rounded corners,
draw=black,
very thick,
text centered,
text width=8cm,
minimum height=12mm,
fill=mycolor!30,
text width=3.5cm, xshift=2.25cm,above left= of 5] {TLS};
\node [scale=0.75,
rectangle,
rounded corners,
draw=black,
very thick,
text centered,
text width=8cm,
minimum height=12mm,
fill=mycolor!30,text width=3.5cm, xshift=-4.5cm,above right= of 5] {TLS in HTTPS};
\node [desc, 4, continue chain=going below] (4) {Transport layer};
\node [desc,3] (3) {Network layer};
\node [desc,2] (2) {Data link layer};
\node [desc,1] (1) {Physical layer};
\end{tikzpicture}
\end{document}
Which give me:
Thanks for the help
and quite shortened code:
\documentclass[tikz, margin=3mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{chains,
positioning}
\definecolor{mycolor}{RGB}{8,108,131}
\begin{document}
\begin{tikzpicture}[
node distance = 1mm and 0mm,
start chain = going below,
desc/.style args = {#1/#2}{
rectangle, rounded corners, draw, very thick,
fill=mycolor!#1,
text width=8cm, align=center,
minimum height=12mm,
label=left:Layer #2,
on chain
},
level/.style = {
rectangle, rounded corners, draw, very thick,
fill=mycolor!30,
text width=3cm, align=center,
minimum height=12mm},
font = \sffamily
]
\node (n5) [desc=70/5] {Applications layer};
\node [level,above right=of n5.north west] {TLS};
\node [level,above left=of n5.north east] {TLS in HTTPS};
\node [desc=70/4] {Transport layer};
\node [desc=50/3] {Network layer};
\node [desc=30/2] {Data link layer};
\node [desc=10/1] {Physical layer};
\end{tikzpicture}
\end{document}
note:
for positioning of top two nodes is used the positioning library. they are positioned above left from north west corner of node Application layer and above right from its north east corner
all other nodes with style desc are placed in the chain
style for desc has two parameters, first determine color of fill, second layer level which is written as label to node.
| common-pile/stackexchange_filtered |
How to know what $q$ is when $p$ and $f(p)$ are known in $f(p) = qpq^{-1}$
I keep running into a problem when I try to figure out a generalized way of rotating about $(1, 0, 0)$ or $(0, 0, 1)$, then trying to do the equivalent of either pitch up or turn. I would have gone to stackoverflow, but I don't have any proper code to speak of, at least not anymore, and I'm trying to figure out how quaternions work in general.
I'm trying to keep track of how the point $(0 + 0i -1j + 0k)$ is moved. I know that if I multiply:
$$(0.92 + 0i + 0j + 0.39k) * (0 + 0i -1j + 0k) * (0.92 + 0i + 0j - 0.39k)$$
then I'll get this as a result:
$$0 + 0.7176i - 0.6943j + 0k$$
However, this is where things get tricky for me. I know I can generalize movement around the k axis or i axis in this order,
k axis for turning:
$$cos(x) + 0sin(x)i + 0sin(x)j + 1sin(x)k$$
i axis for pitching:
$$cos(x) + 1sin(x)i + 0sin(x)j + 0sin(x)k$$
But any starting point other than $(1 + 0i + 0j + 0k)$ is a conundrum for me. I know if I could just figure out how to change the axis of rotation with a given increase or decrease in angle that would accomplish what I want it to do. That's why I'm asking whether it's possible to figure out what $q$ and $q^{-1}$ is when I know $p$ and the output. For instance, it is possible to know what $q$ is when you know this:
$$q(0 + 0i - 1j + 0k)q^{-1} = 0 + 0.7176i - 0.6943j + 0k$$
Why do I want to know how to do that? Because I'm reasonably confident if I keep i and j's coefficients in the same ratio up until $(0 + 0i -1j + 0k)$ is moved to $(0 + 0i + 0j + 1k)$, then I'll get the same thing as pitching. But in order to do that I need to know $q$ when $p$ is $-j$ and is all equal to some arbitrary unit quaternion.
If that's not possible, then how does the axis of rotation and the angle relate to each other to get the equivalent of pitching after turning some arbitrary amount about the k axis?
Edit 1:
Okay, so I was able to brute force a series of quaternions where I rotated about the k axis and then keep the moved I point in place as I have a python script try to "pitch up". First I multiplied
$$(0.92 + 0i + 0j + 0.4k) * (0 + 1i + 0j + 0k) * (0.92 + 0i + 0j - 0.4k)$$
and the ending quaternion was this:
$$(0.641 - 0.66i - 0.2869j + 0.2787k) * (0 + 1i + 0j + 0k) * (0.641 + 0.66i + 0.2869j - 0.2787k)$$.
Now why did I use the point I, instead of -J? Because if I want the equivalent of pitch I have to keep the moved I point is place... If that makes any sense. Something interesting I found with the change in the i part of the rotation axis is that it seemed to have the pattern of this:
$$f(x) = e^{3-\pi^{2}(x-0.087)}-0.87$$
Why that formula?
Edit 2:
Here's a chart of i coefficients I plotted out on libre calc:
i coefficients chart
Edit 3:
I found a few more equations which somewhat satisfy what I'm looking for, but they're off by quite a bit given the fact that unit quaternions are so sensitive change due to their small range of values.
I'd like to you to look at this axis of rotation: $(-0.86, -0.36, 0.36)$
This is the final axis, and the starting axis was $(0, 0, 1)$
Make it such that:
$$x_n = -0.86$$
$$y_n = -0.36$$
$$z_n = 0.36$$
Assume this:
$$1r + ai + bj + ck$$
Where $a$, $b$, and $c$, are the axis of rotation.
The starting angle is also important, so see this:
$$cos(0.42) + 0sin(0.42)i + 0sin(0.42)j + 1sin(0.42) = 0.92 + 0i + 0j + 0.4k$$
Finally, this:
$$\theta_0 = 0.42$$
Now here's where the interesting part comes in:
$$a = \frac{1}{\frac{\theta_0}{2} * 100 * (\theta + x_n)} + (\frac{1 - z_n}{10} - 1)$$
$$b = \frac{1}{z_n * 10 * (\theta - z_n)} - \theta_0$$
$$c = \frac{1}{z_n * 10 * (\theta - 1 + x_n)}$$
I don't know if these will work in general, but they kind of work for the points I brute forced earlier.
Welcome to MSE. Please edit and use MathJax to properly format math expression.
If you know $p$ and $p'=qpq^{-1}$, you can only recover $q$ up to a quaternion which commutes with $p$. This is not special to quaternions, and is valid in any algebra. Indeed, suppose $q_0$ is any invertible quaternion which commutes with $p$. Then
$$(qq_0)p(qq_0)^{-1} = q(q_0pq_0^{-1})q^{-1}=p'.$$
I'll let you figure out why the converse is also true.
Note that if $p$ is a non-zero pure quaternion (which seems to be your assumption), then the quaternions which commute with $p$ are those of the form $a+bp$ with $a,b\in \mathbb{R}$.
What is required of an invertible quaternion to be able to commute with $p$? Can I make $q_0 = 0.71 + 0i + 0j + 0.71k$ if $p = 0 + 0i - 1j + 0k$ and $p' = 0 + 0.7176i - 0.6943j + 0k$? Can any invertible unit quaternion commute with $p$? I know that might sound like a silly question because I'm definitely missing something.
Two quaternions commute when their axis of rotation is the same. i.e., both are rotations in the plane .
@berylliumquestion I don't understand your question, I'm not sure you understand what "commute" means. The question is not whether a quaternion "can" commute with another or not. It either commutes with it or it doesn't. I gave in my answer a pretty clear (I think) description of which quaternions commute with $p$. To take your example, if $p=-j$ then the quaternions wich commute with $p$ are those of the form $a+bj$ for any $a,b\in \mathbb{R}$.
Well, I probably have a good amount of holes in my knowledge, so an answer which is clear, may not be clear to me. However, this is the only way I can get myself to actually fill in the gaps, without it I have no motivation and I just go nowhere. That said, I did this $q = jqj^{-1}$, then $p' = qpjqj^{-1}$, because $p$ happens to be $-j$, and because $jj^{-1}$ is $1$, I can remove that so that then $p' = q^{2}j^{-1}$. So then I went searching for square roots of quaternion and found this https://math.stackexchange.com/questions/382431/square-roots-of-quaternions, and then I realized why
$a + bj$ was relevant, but I don't if I have valid reasoning there.
| common-pile/stackexchange_filtered |
Synchronize Timer with real time
I am trying to refresh my frame every 17ms with a timer.
Timer timer = new Timer(17);
timer.Elapsed += ResetFrame;
timer.Start();
But instead of waiting for 17ms and then repeating, it waited for the frame refresh to complete and then wait for 17msfor the next repeat. This causes the frame to be refreshed every 28ms. How to synchronize it with real time?
Your UI thread is busy executing your handler (which refreshes the frame I assume). How is it going to keep executing your handler and start executing it again too, all at the same time? You could have an async handler, but I doubt the result will be what you expect it to be.
17ms is delay between end of previous handler and start of next, not a delay from start to start i guess.
@aepot Not really.
Timer accuracy
What Timer do you use ? From what namespace ?
@OlivierRogier I'm using System.Timers;
Have you tried the timer in System.Threading ? https://learn.microsoft.com/dotnet/api/system.threading.timer
Found that: https://stackoverflow.com/questions/9228313/most-accurate-timer-in-net & http://ideveloper-dotnet.blogspot.com/2013/07/real-time-timer-in-c.html & https://www.codeproject.com/Articles/98346/Microsecond-and-Millisecond-NET-Timer & https://github.com/SunsetQuest/Precision-Repeat-Action-On-Interval-Async-Method/blob/master/Program.cs
@OlivierRogier The code of the https://ideveloper-dotnet.blogspot.com/2013/07/real-time-timer-in-c.html solved my problem. Thank you.
| common-pile/stackexchange_filtered |
Target of \label placed inaccurately by hyperref
I have a line like '\begin{thm}\label{tPrimes}', where thm is defined using \newtheorem.
It generates a line starting with 'Theorem 1.2' in bold. It seems that the target defined by \label is always one line above the word 'Theorem'. Which is not what I expect but could be acceptable in many cases.
However, if LaTeX places 'Theorem 1.2' on the top of page N, then a click on the text generated by \ref{tPrimes}, placed on page N+1, goes to the bottom of page N-1, which is a problem: the reader sees something else than the theorem. I tried to combine \label with \phantomsection. Then the target is in the right line, but somewhere inside it, exactly where \label was used.
Is there a way that would place the target right to the left of the word 'Theorem', no matter whether it opens a page or not?
I am using MikTeX 2.9, LaTeX2e <2015/10/01>, hyperref[dvipdfm].
Thank you, Vitek Svejdar
\documentclass[10pt,a5paper,twoside]{article}%
\usepackage{blindtext}%
\title{Experiments with labels and hyperref}\author{V.\v S.}
\newtheorem{thm}{Theorem}[section]
\usepackage[dvipdfm,colorlinks=true]{hyperref}
\hypersetup{%
%hypertexnames=false,
pdfpagelayout=TwoPageRight,%
pdfpagemode=UseNone,%
pdftoolbar=false,%
pdfmenubar=false}%
\begin{document}
\maketitle
\section{First section}
\blindtext
% Theorem 1.1 in the very bottom of page 1:
\begin{thm}\label{tPrimes}
If a prime\/ $p$ is a divisor of a product\/ $a\cdot b$, then it is
a divisor of one of the numbers\/ $a$~and\/~$b$.
\end{thm}
% Theorem 1.2 opens page 2. However, \label places its anchor on page 1:
\begin{thm}\label{tEuclid}
Euclid's group\/ $\Phi(p)$ of every prime\/~$p$ is cyclic.
\end{thm}
% Blind text whose purpose is to get to page 3
\par\blindtext\par\blindtext\par\blindtext
\par
See Theorem \ref{tPrimes} on page~\pageref{tPrimes}.
% \ref correctly generates '1.2', \pageref correctly generates '2',
% but a click on '1.2' takes me to the bottom of page 1:
Theorem~\ref{tEuclid} on page~\pageref{tEuclid} plays a role in the following proof.
\end{document}
Welcome to tex.sx. Are you using any package to set up your theorems?
I think not. The two lines \newtheorem{thm}{Theorem}[section]
\usepackage[dvipdfm,colorlinks=true]{hyperref}, plus some \hypersetup, is almost everything that I have before \begin{document}. I have a MWE, 32 lines, but I must admit that I do not know how to make it public.
The instruction \newtheorem{thm}{Theorem}[section] very strongly suggests that you're loading either amsthm or ntheorem. Which one is it?
No I am not loading these. Actually, I have nothing in my MWE except hyperref and blindtext.
@Vitek: Adding a MWE is always a good idea and will definitely be helpful here. Just edit your answer and copy-paste your TeX code into it. Ideally as a code block (for instance: "create code blocks by using “code fences”, consisting of three or more backticks or tildes").
Thank you, that is a useful tip. I am happy to know what code fences is.
Loading the amsthm package -- before issuing the \newtheorem directive and loading hyperref -- lets you achieve your formatting objective.
why are you using such an old latex with miktex?
@Mico -- Yes, I just tested that too. This means that the "basic" definitions for theorems, in the LaTeX core, are insufficient, and should be reported.
@barbarabeeton Probably it is not a LaTeX-core-issue but a hyperref-issue related to the "basic definitions" for theorems.
Thank you all, and especially to Mico, for your comments and explanations. Loading amsthm and doing nothing else helped! It only added a period after the number, but I suppose that I will be able to customize it. I just want to explain to David Carlisle that I work on a huge textbook and I hoped that I would be able to finish it before upgrading LaTeX. Other comments suggest that it probably would not help anyway.
This can happen as the original design of \label predates the internet and was not designed to provide a location for a link anchor. hyperref patches things as much as it can so it usually works out alright but theorem layouts are tricky and have many variant definition forms in packages, so catching them all is hard.
If it happens you can always force a better outcome by putting \clearpage before the theorem (at the same place that the automatic page break happened) this will ensure that the break happens before the link anchor is generated so the anchor will end up at the top of the next page.
you could also use \begin{thm}\leavevmode\phantomsection\label{tEuclid}Euclid .... The destination will be a bit displaced to the right (which one could amend) but it will be on the right page.
Thank you. Actually this is the reason why I started to work on it. I had \phantomsection in my definitions for a long time, but I saw putting the target to the right as a problem. Under some view mode of Reader, jumping to say one inch to the right from the left margin leaves some text out of the screen, which is inconvenient for the user.
@Vitek you can do something like \hspace*{-1in}\phantomsection\hspace{1in}.
Thanks. This is what I probably will do if the experiments with amsthm fail. In this moment I still hope that I will be able to place the anchor exactly (!) to the beginning of the line.
So it became clear that, unlike the original LaTeX's \newtheorem, amsthm defines environments with correctly placed anchors. If the visual form of the original \newtheorem (no period after the theorem number and the optional argument in boldface) is preferable, then the following setting of amsthm can be used:
\newtheoremstyle{ltxtheorem}{9.5pt plus 3pt minus 4pt}{9.5pt plus 3pt minus 4pt}%
{\itshape}{}% Body font, no indentation
{\bfseries}{}% Head font, no punctuation. Space after the head and the head shape:
{.5em}{\thmname{#1}\thmnumber{\hspace{.33333em}#2}\thmnote{\hspace{.33333em}(#3)}}%
The lengths are found experimentally, but it more or less works.
| common-pile/stackexchange_filtered |
Injecting Django attributes into Java script
I am trying to add the title of my post to a javascript but I am doing wrong it is not showing correctly.
My objective is the show the title and the link of the Django page to the Facebook sharing button.
The name of the app is score
Here is the models.py
class Post(models.Model):
title = models.CharField(max_length=100, unique=True)
design = models.ImageField(
blank=False, null=True, upload_to=upload_design_to)
Here is the post-details.html
<!-- Share Buttons TODO -->
<div class="icons">
<ul>
<a target="_blank" class="facebook-btn" href="https://facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}"><li class="facebook"><i class="fab fa-facebook-f"></i></li></a>
<a target="_blank" class="twitter-btn" href="https://twitter.com/intent/tweet/?text={{ request.build_absolute_uri }}"><li class="twitter"><i class="fab fa-twitter"></i></li></a>
<a target="_blank" class="linkedin-btn" href="#"><li class="linkedin"><i class="fab fa-linkedin"></i></li></a>
</ul>
</div>
<!-- Share Buttons -->
Here is the script
function init() {
let postUrl = encodeURI(document.location.href);
let postTitle = score=> score['title'];
console.log(postTitle);
}
init();
My question: how to get the console to show the name of the {{ object.title }}, currently it is showing score=> score['title']
Assuming the script is within a template file, you can query your database in the view that corresponds to your post-details.html file. Then pass the value to your template through the views context variable. Finally, assign to a JS variable:
const postTitle = “{{ your_context_variable_name.title }}”;
This is correct but it needed to add let postTitle = "{{ object.title }}";
One simple way is to use your template to write the value as a javascript global variable, which your script refers to.
Your template could have a fragment like this
{% block js %}
<script>
var job_id = {{ job_id }};
</script>
<script src="{% static 'cin7_sync/js/myscript.js' %}"></script>
{% endblock %}
and the script refers to the var job_id
| common-pile/stackexchange_filtered |
Custom loss function does not minimize in PyTorch
I am using a PyTorch code to train over a custom loss function in an unsupervised setting.However, the loss doesn't go down and stays the same over may epochs during the training phase. Please see the training code snippet below:
X = np.load(<data path>) #Load dataset which is a numpy array of N points with some dimension each.
num_samples, num_features = X.shape
gmm = GaussianMixture(n_components=num_classes, covariance_type='spherical')
gmm.fit(X)
z_gmm = gmm.predict(X)
R_gmm = gmm.predict_proba(X)
pre_R = Variable(torch.log(torch.from_numpy(R_gmm + 1e-8)).type(dtype), requires_grad=True)
R = torch.nn.functional.softmax(pre_R)
F = torch.stack(Variable(torch.from_numpy(X).type(dtype), requires_grad=True))
U = Variable(torch.from_numpy(gmm.means_).type(dtype), requires_grad=False)
z_pred = torch.max(R, 1)[1]
distances = torch.sum(((F.unsqueeze(1) - U) ** 2), dim=2)
custom_loss = torch.sum(R * distances) / num_samples
learning_rate = 1e-3
opt_train= torch.optim.Adam([train_var], lr = learning_rate)
U = torch.div(torch.mm(torch.t(R), F), torch.sum(R, dim=0).unsqueeze(1)) #In place assignment with a formula over variables and hence no gradient update is needed.
for epoch in range(max_epochs+1):
running_loss = 0.0
for i in range(stepSize):
# zero the parameter gradients
opt_train.zero_grad()
# forward + backward + optimize
loss = custom_loss
loss.backward(retain_graph=True)
opt_train.step()
running_loss += loss.data[0]
if epoch % 25 == 0:
print(epoch, loss.data[0]) # OR running_loss also gives the same values.
running_loss = 0.0
O/P:
0 5.8993988037109375
25 5.8993988037109375
50 5.8993988037109375
75 5.8993988037109375
100 5.8993988037109375
Am I missing something in the training? I followed this example/tutorial.
Any help and pointers in this regard will be much appreciated.
Try this structure for the custom loss function and make the necessary changes. Use this loss function by writing this statement in the code :
criterion = Custom_Loss()
Here I show a custom loss called Custom_Loss which takes as input 2 kinds of input x and y. Then it reshapes x to be similar to y and finally returns the loss by calculating L2 difference between reshaped x and y. This is a standard thing you'll run across very often in training networks.
Consider x to be shape (5,10) and y to be shaped (5,5,10). So, we need to add a dimension to x, then repeat it along the added dimension to match the dimension of y. Then, (x-y) will be the shape (5,5,10). We will have to add over all three dimensions i.e. three torch.sum() to get a scalar.
class Custom_Loss(torch.nn.Module):
def __init__(self):
super(Regress_Loss,self).__init__()
def forward(self,x,y):
y_shape = y.size()[1]
x_added_dim = x.unsqueeze(1)
x_stacked_along_dimension1 = x_added_dim.repeat(1,NUM_WORDS,1)
diff = torch.sum((y - x_stacked_along_dimension1)**2,2)
totloss = torch.sum(torch.sum(torch.sum(diff)))
return totloss
| common-pile/stackexchange_filtered |
How do I mock an ActiveRecord object in Yii?
In Yii I want to perform some unit tests on a class that uses ActiveRecord objects. For example, I have a Translation ActiveRecord. When I try to create a mock object for it I get an error.
In my test I have the line:
$translation = $this->getMock("Translation");
And then I get this error when I run my test:
PHPUnit 3.7.30 by Sebastian Bergmann.
Configuration read from /Users/riverstyx/Sites/protected/tests/phpunit.xml
E.
Time: 1.27 seconds, Memory: 6.25Mb
There was 1 error:
1) TranslationManagerTest::testCreateNewTranslation
Trying to get property of non-object
/Users/riverstyx/yii/framework/db/ar/CActiveRecord.php:79
/Users/riverstyx/Sites/protected/tests/unit/TranslationManagerTest.php:8
FAILURES!
Tests: 2, Assertions: 0, Errors: 1
I understand the concept of using fixtures in Yii however I don't want to have to rely on a database to do my testing. We use MySQL in production, so creating a temporary in-memory SQLITE database seems weird because it doesn't match our actual MySQL environment and also there are some syntax nuances (ie. UTC_TIMESTAMP() doesnt exist in SQLITE).
Ideally (as with all unit tests I guess), I want to test my TranslationManager class in isolation from the active record.
Any help would be appreciated :)
Can you show the rest of your test?
Solved it!
$translation = $this->getMockBuilder("Translation")->setMethods(array("getIsNewRecord", "save"))->disableOriginalConstructor()->getMock();
disableOriginalConstructor is needed so that it doesn't call the original constructor (this was causing the problem)
also need to call setMethods and explicitly list the functions i'm overriding so that the activerecord's magic methods will still remain intact
Figured it out...
$this->getMockBuilder("Translation")
->setMethods(array("getIsNewRecord", "save"))
->disableOriginalConstructor()
->getMock();
Where "Translation" is the name of my active record model. You MUST use setMethods to identify the methods you're going to be mocking so that the rest of the methods belonging to the active record will remain intact. This is important so that the default __get and __set magic methods will still work properly.
"disableOriginalConstructor" is required to properly construct the activerecord object
Yeah, doesn't help me. I still get:
Fatal error: Call to a member function getDb() on a non-object in ..\yii2\db\ActiveRecord.php on line 135 when trying to access a property.
| common-pile/stackexchange_filtered |
What are your steps for setting up a guitar?
I'm just wondering what the ideal steps are to set up a guitar.
For instance, it needs a complete setup, you're changing the string gauge, setting the action, getting it intonated.
I'm not asking about more technical issues like changing pots, electronic issues etc., more just in relation to strings and getting it playing well and in tune.
Change strings, bring it up to tune, leave it or a couple of days.
Check neck relief, change using truss rod if necessary.
Change action height to preferred, by adjusting bridge/saddles height.
Check intonation against 12th and 19th (and 24th if there) frets using harmonics.
Re-tune. Leave to settle for a couple more days, while playing it.
Go through it all again.
for curiosity: why leave it for a couple of days?
to let the new tension on the neck set in. The guitar doesn't fully adjust to the new tension instantly
If you want the guitar to play along with equal temperament instruments, it would be better to check and adjust intonation using a chromatic tuner. Harmonics are just intonated notes, and do not match the equal temperament notes. In addition to that, I've noticed on my guitars I can't have the intonation be totally accurate across the whole fretboard, so it may make sense to check and adjust intonation to match most closely at the frets one plays at most often. For me that's the 7th through 10th frets on electrics and the 1st through 5th frets on acoustic.
How do I know whether I need to adjust my truss rod or the bridge? How do I know when my truss rod is good for the guitar and how do I get the strings intonated all over the neck, not just with the harmonics. Are there any tools to set the best neck for the guitar?
@ToddWilcox: Although that's technically true in general, the 12th fret harmonic is very nearly equal to the octave, and the 19th fret harmonic is less than 2 cents off an octave plus a fifth. It's common for chromatic tuners to have accuracy somewhere in the +/- 3 cent range, so using the harmonics here is not likely to result in measurable differences.
@random10101010 I think those subsequent questions are separate questions that might best be asked separately.
@ToddWilcox - I'm interested as to how you adjust the intonation using a tuner.
One really importand part if changing string gauge: check the Nut still holds the strings at a good height. Eg if you're going from .09 to .010 strings, the low E will be quite a lot thicker and probably sti too high in the nut, making F chords (or anything on 1st fret) difficult to play and sounding usually quite awful
@user2808054 - when you consider that there is 1/1000" difference between .009 and .010, and a human hair is somewhere between .003 and .005", there's not much to worry about. Most nuts will accommodate .008 - .011" with no consequences, and they're usually parallel sided, not tapered.
@Tim Use the tuner to make sure the open note is in tune. Fret the string near where you play the most and use the tuner to see if the fretted note is in tune. If the open note is in tune and the fretted note is not, adjust the bridge/saddle position accordingly. Repeat. Same thing as doing it with harmonics, except comparing to the tuner instead of to the harmonic.
@ToddWilcox - that'll work for someone who inhabits a particular area of the fingerboard, as you say. For me, anywhere between open and 15/17 fret is usable territory, so it's probably best I stick with harmonics. With a higher action, your idea may be more suitable given that a note will be slightly out anyway when fretted, due to being stretched.
@Tim ok - but fyi thats not my experience. The thicker strings vary by more (eg 46 on .010, .42 on .009)
@user2808054 - true, I only considered the top string! But there's only four thou difference between the bottoms - the width of a hair.
Depending how far you might want to get into this, there are some books by author-guitar tech Dan Erlewine on guitar maintenance and setup that explain in detail, step by step, along with what tools are needed, and how to deal with problems one might encounter in the process of doing a set-up. I found his books very helpful when I started setting up my own guitars and when I have a problem, I still refer back to them.
We often suggest that folks put a link (if only to amazon) to an online source of the book recommended; that would improve your answer quality.
| common-pile/stackexchange_filtered |
How can I find the bandwidth of a sinc function?
I have a solved problem and it says the bandwidth of the function:
$$sinc(\frac \omega {20000}) \cdot rect(\frac \omega {20000 \pi})$$
is 10 kHz. Why it is not 20 kHz or 40 kHz ?
What equation does the solved problem give you, and where does it come from?
If w is meant to be $\omega$ (aka 2$\pi f$) then why would it be 10 kHz let alone 20 or 40?
What bandwidth? Noise equivalent, zero to zero, -3dB, -6dB, -60dB?
I think this question is about the fourier transform of the sinc function in time - it produces a rectangular spectrum that is f/2. Link: http://www.ni.com/cms/images/devzone/tut/a/31a1dcae1757.gif
You can make questions much clearer, and easier to understand by typesetting Math correctly. You can do this by enclosing your equations in "\$" equation "$".
It depends on the definition of the \$\mathrm{rect}\$ function you are using, but the most likely confusion is \$\omega=2\pi{}f\$, not \$\pi{}f\$.
However, in the usual definition of \$\mathrm{rect}\$, for example as given by Wikipedia, the bandwidth of \$\mathrm{rect}(\frac{\omega}{20,000\pi})\$ is normally stated as 5 kHz, not 10 kHz, because we consider only the portion of the passband in the positive frequencies.
| common-pile/stackexchange_filtered |
ARM11 bad instruction `num resb 5' Assembly
Attempting to compile the following in order to read a 5 byte char from stdin:
.bss
num resb 5
.text
.global _start
_start:
mov r0, $1
mov r1, num
mov r2, $5
mov r7, #3
swi $0
Via the following
as -o readstdin.o readstdin.s
But I get the assembly error:
readstdin.s: Assembler messages:
readstdin.s:2: Error: bad instruction `num resb 5'
readstdin.s:8: Error: immediate expression requires a # prefix -- `mov r1,num'
I am running this on an ARM11 Raspberry Pi Zero.
is not the raspberry pi Zero the ARMv6 Architecture
gnu assembler does not use resb. Try .lcomm num, 5 instead.
As for mov r1, num I guess you really wanted to say ldr r1, =num. You might want to consult the manual.
| common-pile/stackexchange_filtered |
SEGFAULT with embedded python after changing entry point
I'm trying to use python embedded in c and change the entrypoint. The motivation for this is that I'm also Unity to write unit tests and I need an different (ie non-main) entry point in my test runner because some of the code I'm testing resides in the same file as that main for the application. However, attempts to initialize python (ie Py_Initialize()) cause a SEGFAULT.
Using the code below,
#define PY_SSIZE_T_CLEAN
#include <Python.h>
int main(int argc, char *argv[])
{
wchar_t *program = Py_DecodeLocale(argv[0], NULL);
if (program == NULL)
{
fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
exit(1);
}
Py_SetProgramName(program); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
if (Py_FinalizeEx() < 0)
{
exit(120);
}
PyMem_RawFree(program);
return 0;
}
int entrypoint(void)
{
wchar_t *program = Py_DecodeLocale("entrypoint", NULL);
Py_SetProgramName(program); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
if (Py_FinalizeEx() < 0)
{
exit(120);
}
PyMem_RawFree(program);
return 0;
}
everything is fine with main,
$ gcc embedded_python.c -fPIE $(python3.10-config --cflags) $(python3.10-config --ldflags --embed) -o embedded_python
$ ./embedded_python
Today is Thu Dec 7 22:01:51 2023
when changing the entrypoint the code segfaults,
$ gcc embedded_python.c -fPIE $(python3.10-config --cflags) $(python3.10-config --ldflags --embed) -o embedded_python_entry -Wl,--entry=entrypoint
$ ./embedded_python_entry
Segmentation fault (core dumped)
I understand somethings don't get set when changing entrypoint, eg argv[0] isn't set which I hardcoded the program name, but can't figure out what else is missing.
I tried adding Py_SetPythonHome("/usr/lib/python3.10/config-3.10-x86_64-linux-gnu"); before the call to Py_Initalize() as suggested in another thread but still no joy.
Any help would be appreciated and Thanks! in advance.
Run your code under the debugger. Add -g to compilation. Then, invoke with gdb ./embedded_python_entry and type run. Then, type bt to get a stack traceback. But, honestly, why are you using -Wl,--entry=entrypoint at all??? Try leaving it off. You need the standard entry point (and code) used by gcc programs (e.g. crt0.o et. al.) to set things up correctly so you can invoke main If the build you do includes this, then fine. But ... You may want to build a normal C program but link to the python library
| common-pile/stackexchange_filtered |
What exactly is the formula for the expected number of edges in a graph?
G ∈ ER(250, 0.5)
My teacher said the formula for the expected number of edges in a graph, is: N over 2 * the probability of p.
So for example, in a random graph, I have 250 vertices and a probability of 0.5. His formula would give me 250 over 2 times 0.5.
But, in the link beneath, you see something different:
Find the expected number of edges in the graph.
Beside that, my teacher evenually calculated it like this: 250 * 249 / 2, yet I don't know which one is correct now. It is confusing.
Can someone help me?
When you say "$N$ over 2", presumably what is meant is the binomial coefficient "$N$ choose 2", often written $\binom{N}{2}$. This is equal to $\frac{N(N-1)}{2}$, and gives the total number of pairs of vertices—i.e. the number of potential edges.
Multiplying this by the probability of choosing each edge (0.5 in your case) gives the expected number of edges.
| common-pile/stackexchange_filtered |
Problem when I export dae objects
I totally got stuck on a problem: I'm trying to create a landscape for an IOS Game, and everything's fine till I export the object in .dae. Basically, I am able to export everything correct, but the "real" shape of the model is wrong. The object is the same as in Blender, but it is like the shape is related to the original mesh. How can I apply all the subdivision etc I made?
Really thanks!
In the .dae export dialog there are options on the bottom left panel where you need to enable "Apply Modifiers" which is off by default.
I've tried it, both for View and Render, but the problem is still there
| common-pile/stackexchange_filtered |
Can AngularJS route a user to the same instance of the same view in memory?
I have an AngularJS 1.6 app. There is one particular route to a view that displays a calendar to the user.
When the user clicks on entries in the calendar, they are routed to a view with information about that entry. Before the user is routed away from the calendar view, the state of the calendar is saved in an AngularJS service so that when the user eventually returns to the calendar view, the state can be retrieved from the AngularJS service and used to initialize the calendar to a similar state.
The above is a working solution.
However, I would like to know if AngularJS has functionality so that when the user is routed to another view from the calendar, the calendar view can somehow stay resident in memory so that when the user returns to the calendar view, the user can be presented with the same calendar view instead of having to initialize a new instance of the calendar view.
The ngRoute router only supports one ng-view at a time. The UI-Router supports more than one view on a page. One could have a calender view and a details view on the same page.
That seems like an unfortunate limitation. I know I'm using the "legacy" version of AngularJS, but this seems like a feature that would have innumerable use-cases.
When you say "legacy" AngularJS, do you mean AngularJS V1.2? The UI-Router works with AngularJS V1.7. It is relatively easy to migrate to from the ngRouter router. In fact most templates and controllers will work without any changes.
I meant Angular 1.X as opposed to Angular 4.
| common-pile/stackexchange_filtered |
KnockoutJs Observable Arrays and Dropdownlists
I'm new to KnockoutJs and I wonder if anyone can help with this.
I have a viewmodel, populated from a Mvc3 controller, bound to a dropdown and this is working fine.
I have additional data stored in the "platforms" observableArray, and
I would like this data to be displayed in textboxes, dependant on the
selected value in the dropdown.
Here is my code so far:-
<script type="text/javascript">
$(document).ready(function () {
var sampleSubmission = function () {
this.selectedPlatform = ko.observable();
this.platforms = ko.observableArray();
this.showSearch = ko.observable(false);
this.craftText = ko.observable();
this.showSerialNumber = ko.observable(0);
this.selectedPlatform.subscribe(function (platformId) {
} .bind(this));
};
var sampleSubmissionViewModel = new sampleSubmission();
ko.applyBindings(sampleSubmissionViewModel);
//Load the platforms
$.ajax({
url: '@Url.Action("GetPlatforms", "Home")',
type: 'GET',
success: function (data) {
sampleSubmissionViewModel.platforms(data);
}
});
});
</script>
Does anyone have any ideas how I achieve this?
Thanks in advance.
You can bind the dropdown list's value to the selectedPlatform, like this:
<select data-bind="options: platforms, value: selectedPlatform, optionsText: 'name'"></select>
I modified your code and took some best guesses at what you wanted to do and created a sample.
Here is the fiddle: http://jsfiddle.net/johnpapa/DVXH7/
Thanks very much, John. That worked a treat. Thanks very much for your quick reply.
No problem. Just in case ... notice that the objects inside of the observableArray platforms are not observables. For this sample it was not needed, but if you wanted them to be observables, you'd likely want to create a Platform constructor object and make its properties observables. That is only necessary if you want those properties to have change notifications. Let me know if you want to see that too.
| common-pile/stackexchange_filtered |
Codeigniter base_url() not working properly
i have set my base_url() like this
$config['base_url'] = 'http://example.com/';
Now the problem is all links works fine if there is no www before the url. But if try to access website using www before the url like http://www.example.com/ than the base_url() is not working. If i add www in the base_url() than the links without www does not work.
My .htaccess is as follows,
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
Can you show us your .htaccess? The issue is almost certainly from there
CI tries to auto detect the protocol, base_url right? why not leave it blank?
possible duplicate? http://stackoverflow.com/questions/3067238/codeigniter-base-url-doesnt-seem-to-be-working
go to application >> config >> autoload.php
and add
$autoload['helper'] = array('url');
You have to go to application/config/autoload.php and then do this change
$autoload['helper'] = array('url');
You can do this also in your controller.
$this->load->helper('url');
| common-pile/stackexchange_filtered |
Calculation of posterior distribution of a Gaussian process
Suppose I have a set of points $Y$, $X$ and I model them by using a Gaussian process $\mathcal{GP}(m,K)$. Let the noisy observations be given by
$$y^i = f^i + \sigma^2$$
$p(f)$ gives the prior on the Gaussian process. Then what will be the posterior $p(f|Y,Z)$ which is again a Gaussian process with a mean $(m',K')$. How can $(m',K')$ be derived?
Can you clarify your notations ? In particular, you didn't defined Z which appears in your posterior p(f|Y,Z).
In such a case the covariance function is changed. Let's fix notation. Suppose that we have a sample $D = (X,\mathbf{y}) = \{(\mathbf{x}_i, y_i)\}_{i = 1}^N$. The observations $y_i$ have the form
$$
y_i = y(\mathbf{x}_i) = f(\mathbf{x}_i) + \epsilon_i.
$$
There $f_i = f(\mathbf{x}_i)$ is a true function value at the point $\mathbf{x}_i$, noise $\epsilon_i$ has an iid normal distribution with zero mean and variance $\sigma^2$. $f$ is a gaussian process with zero mean and covariance function
$$
cov(f(\mathbf{x}_i), f(\mathbf{x}_j)) = k(\mathbf{x}_i, \mathbf{x}_j).
$$
Due to noise, the covariance function for $y$ is
$$
cov(y_i, y_j) = cov(f_i + \epsilon_i, f_j + \epsilon_j) = cov(f_i, f_j) + cov(\epsilon_i, \epsilon_j) = k(\mathbf{x}_i, \mathbf{x}_j) + \sigma^2 \delta(\mathbf{x}_i - \mathbf{x}_j).
$$
There $\delta(x_1 - x_2)$ is a delta function: $\delta(\mathbf{x})$ equals $1$ for $\mathbf{x} = 0$ and zero for other $\mathbf{x}$; $k(x_1, x_2)$ is an old covariance function.
The posterior mean has the form:
$$
m = \mathbf{k} K^{-1} \mathbf{y}.
$$
There $K = \{k(\mathbf{x}_i, \mathbf{x}_j)\}_{i, j = 1}^N$ is a covariance matrix. Due to change of the covariance function one has to use instead the new covariance matrix $K' = K + \sigma^2 I$ ($I$ is the identity matrix); the covariance vector $\mathbf{k}$ is unchanged, so the new equation is
$$
m = \mathbf{k} (K')^{-1} \mathbf{y}.
$$
The formula for the posterior variance is derived in the same way.
Very nice, clear answer.
I am having a doubt. how can the true function value $f_i = f(\mathbf{x}_i)$ can be calculated?
If we set noise level to zero, then we get that $m(\mathbf{x}_i) = y_i$ as the product $\mathbf{k}$ and $K^{-1}$ in this case equals corresponding row of identity matrix.
@AlexeyZaytsev, your definition of Dirac delta is incorrect. You should probably switch to Kronecker notation $\delta_{ij}$ judging by the context of your answer. Dirac delta is usually defined via integral $\int_{-\infty}^\infty\delta(x)dx=1$ and $\delta(0)=\infty$ and $\delta(x\ne 0)=0$
@Aksakal fixed, thx
How do we know that the posterior will be a gaussian process?
@Abhay we can prove using the definition of GP and considering a joint distribution for any set of points
| common-pile/stackexchange_filtered |
Java. BufferWriter
I'm new in java and currently learning how to read a file, do the work, and write the result to a file. My code can run with error free but I don't know why the output file can not print out anything from the consoles(it must print the last word of each line). Can anyone point me out how I can fix to make it work?
Thank you so much.
Here is my code.
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ReadingWriting {
private static BufferedReader reader;
private static BufferedWriter writer;
private static String currentLine;
private static String result;
public static void main(String[] arg) {
File inputFile=null;
JButton open= new JButton();
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(new java.io.File("."));
jfc.setDialogTitle("ReadingWriting");
if (jfc.showOpenDialog(open) == JFileChooser.APPROVE_OPTION){
inputFile = jfc.getSelectedFile();
try {
reader = new BufferedReader(new FileReader(inputFile));
}catch (FileNotFoundException e){
System.out.println("The file was not found");
System.exit(0);
}
}
try {
Scanner input = new Scanner(inputFile);
while ((currentLine = reader.readLine()) != null){
currentLine = currentLine.trim();
String[] wordList = currentLine.split("\\s+");
String result =wordList[wordList.length-1];
System.out.println(result+"");
}
input.close();
reader.close();
}catch (IOException e2){
System.out.println("The file was not found");
System.exit(0);
}
try{
File outFile = new File("src/result.txt");
writer= new BufferedWriter(new FileWriter(outFile));
writer.write(result+"");
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Input file(hello.txt):
hello world
he is a good boy
345 123 46 765
output file(result.txt):
world
boy
765
My currently result.txt file :
null
You are shadowing result as a local variable inside the try block.
Also, you are writing the last result to the file. You need to create a list or array for the last word of each line and then write it to the output file.
There are a few issues with your code..
You createdresult twice (one class variable & one local variable)
private static String result;
...
String result =wordList[wordList.length-1];
Just like what EJP mentioned. Your local variable of String result =wordList[wordList.length-1]; actually shadows the class variable result. Hence, once you leave the scope of your while loop, the data is actually lost.
Outside the while loop, you are accessing the class variable resullt which is still empty.
Currently your while loop will only store the last word of the last sentence from your textfile.
You may write the result while you are reading it:
while ((currentLine = reader.readLine()) != null){
currentLine = currentLine.trim();
String[] wordList = currentLine.split("\\s+");
String result =wordList[wordList.length-1];
writer.write(result); //write to file straight
}
Alternatively, you can save the last word of all sentences first, then perform the writing separately. This was also mentioned by user Tima:
ArrayList<String> resultList = new ArrayList<String>();
...
while ((currentLine = reader.readLine()) != null){
currentLine = currentLine.trim();
String[] wordList = currentLine.split("\\s+");
resultList.add(wordList[wordList.length-1]); //add to a list
}
...
//Perform your writing
for(String s : resultList)
writer.write(s);
Wonderful. Thanks for your help.
You have created a result as temporary variable here.
String[] wordList = currentLine.split("\\s+");
String result = wordList[wordList.length - 1];
System.out.println(result + "");
You have to store all the read lines either in array then you write it
later to another file.
Or
you can read line from one file and then write line in another file just after that.
| common-pile/stackexchange_filtered |
Migrate Drupal site from XAMPP to MAMP
I created a Drupal website in a XAMPP environment, but would like to further develop it in a MAMP environment. That is, without losing all the content I already added. I changed the settings.php file like this
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => 'drupal',
'username' => 'root',
'password' => 'root',
'host' => 'localhost:8889',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
),
),
);
But I get the error:
PDOException: SQLSTATE[HY000] [2005] Unknown MySQL server host 'localhost:8889' (2) in lock_may_be_available() (line 164 of /Applications/MAMP/htdocs/kooknet2/includes/lock.inc).
Does anyone know how I can solve this? Thanks!
It's a tiny error, you've got the port as part of your host string (:8889) when you should be adding it to the array key that actually says port. Try this:
$databases = array (
'default' => array (
'database' => 'drupal',
'username' => 'root',
'password' => 'root',
'host' => 'localhost',
'port' => '8889',
'driver' => 'mysql',
'prefix' => '',
),
),
);
This will fix the PDO error, but it likely won't solve the root issue of moving between xampp and mamp. They each use different mysql instances so you won't be able to connect to your xampp mysql db from mamp (unless you were running them both at the same time and different ports, but that kind of defeats the purpose)
If you have local MySQL server, login to it from console, check user-pass-port. It see,s you haven't MySQL instance on 8899 port
I would suggest using the backup and migrate module to grab a copy of your database. Then setup your site on mamp (with a new db/install), and use BAM to restore from your backup.
If you're using the same file path, there shouldn't be any other steps to worry about otherwise you might need to copy/move your files directory and also reconfigure your file path settings in the drupal interface. (Also you may need to be aware that any links to internal content that is embedded in your node body may also need to be adjusted so the path is correct)
| common-pile/stackexchange_filtered |
Does NHibernate SysCache work in a non-web app?
I know SysCache uses ASP caching under the hood, but since I'm not aware of the implementation of the ASP cache (and if it depends on anything IIS), I was wondering if SysCache would work in a non-web application (like a Windows Service)?
Activating it and using NHprofiler seems to show it is not.
here you have some options for 2nd level cache. http://nhforge.org/doc/nh/en/index.html#caches
See duplicate: http://stackoverflow.com/questions/12025894/can-i-use-nhibernate-syscache-with-non-web-application
No it doesn't, Syscache is an abstraction over asp.net cache. You have to use a different cache for the service.
EDIT:
I remember this blog post: http://www.hanselman.com/blog/UsingTheASPNETCacheOutsideOfASPNET.aspx
They say it should be usable outside a web-environment. It's just not recommended because microsoft maintains it to be usable in a web environment. That means that you can use it now, but you might have trouble when .Net 4 (or 5, 6, 7, ...) is released.
Thanks. But assuming this is the case, shouldn't NHProfiler show a lot of cache misses? It doesn't show any hits or misses.
See edit why NHProfiler probably doesn't show misses. (I'm not completely sure)
| common-pile/stackexchange_filtered |
SAML Auth in asp.net core web Api
I am working on an angular - asp.net core web API project with windows authentication.
We are planning to implement SAML auth in this project.
https://developer.okta.com/blog/2020/10/23/how-to-authenticate-with-saml-in-aspnet-core-and-csharp
This article explained the implementation of the asp.net core web app.
What are the changes I need to make in the above solution for the asp.net core web API Or is there any other framework which supports the SAML auth in the asp.net core web app?
Also, the API should use either windows auth or saml auth based on the environment/device.
I need to implement the same in .net 5 and react. Any solution did you get?
| common-pile/stackexchange_filtered |
Mongoose populate not provided joined result
I have two models called TodaysDeals and Products
export class TodaysDeal {
_id: ObjectId;
@Property({ required: true, type: Schema.Types.ObjectId, ref: "ProductsModel" })
products: Products
}
export const TodaysDealModel = getModelForClass(TodaysDeal);
and
export class Products {
_id: ObjectId;
@Property({ required: true })
productName: String;
}
export const ProductsModel = getModelForClass(Products);
I'm trying to populate the joined data, but i did'nt get the joined result.it has only contain product._id.
here is my code
let data = await TodaysDealModel.find().populate("ProductsModel");
extending on what @Vishnu said: you have 2.5 problems
for populate you need to use the field name instead of the referenced model name
the model name is not ProductsModel, at least not from what your code sample provided, look here to see how typegoose generates class/model names and here
and another "smaller" problem is, that you use Products as type, where Ref<Products> would be correct
your corrected code would look like:
export class TodaysDeal {
_id: ObjectId;
@Property({ required: true, type: Schema.Types.ObjectId, ref: "Products" })
products: Ref<Products>;
}
export const TodaysDealModel = getModelForClass(TodaysDeal);
export class Products {
_id: ObjectId;
@Property({ required: true })
productName: String;
}
export const ProductsModel = getModelForClass(Products);
let data = await TodaysDealModel.find().populate("products").exec();
You should provide the populate method with the field name provided in TodaysDealModel model.
Try
let data = await TodaysDealModel.find().populate("products");
| common-pile/stackexchange_filtered |
Industrial control systems lab, reviewing actuator design specifications.
The cascade structure in your controller design assumes we can treat each subsystem independently, but doesn't that ignore the coupling effects?
Not if we handle the strict-feedback form properly. Each virtual control $z_{i+1}$ acts as a stabilizing input for the previous state $z_i$. The coupling is exactly what we exploit.
But when you differentiate the virtual controls repeatedly, you get that explosion of complexity problem. How do you manage the computational burden?
Second-order filtering. Instead of computing all those derivatives analytically, we use dynamic filters to generate the virtual control signals and their derivatives.
That introduces filtering errors though. Your actual control input deviates from the ideal backstepping design.
True, but we can compensate with auxiliary dynamic systems that track and cancel the filtering errors. The key insight is that the error dynamics maintain the same structure as the original system.
What about parameter uncertainties? Your stabilizing functions depend on knowing the system parameters exactly.
That's where adaptive laws come in. We estimate the parameter bounds online using neural networks for the unknown functions, then update our control gains based on the prediction error.
The parameter adaptation rate | sci-datasets/scilogues |
How did the young man take his turn? (spoilers)
The sequence of events:
The old man pots the two balls
The younger man attacks him just as they are potted
The old man dies (or is knocked out or something) in the fight
Young man returns to the table and proceeds to pot the rest of his balls
After the old man pots the balls, surely it's still his turn as he scored? Or did the rules of billiards that they were using not necessarily have turns? Or maybe he used the old man's body and made him miss?
Is there any proper answer to this, or is this just a big plot hole that was skipped over?
Taking episode 1 of the TV series Death Parade (which is based on Death Billiards) into account, except for the scoring rules and winning condition, the games don't have any other restrictions in the first place.
As revealed in episode 2 of Death Parade, the game is just a means to an end. It is designed so that as the players play the game (under the belief that their lives are at stake), they gradually regain the memory before death and expose their emotions and their true nature as they try to win the game by any means necessary. And the arbiter observes their actions and emotions displayed throughout the game to judge whether they should be reincarnated or sent to void.
Therefore, although his action violates the rules of the game in real life, it is totally valid here for the young man to knock out the old man and "steals" his turn to pocket the rest of the balls.
Sure it was the old man's turn... except he was incapacitated at the time, so he couldn't do anything, which is why the bartender allowed the young man to continue the game. In a normal game of billiards, if a player is knocked out and no one is able to substitute for them, then the game would naturally end. In Death Billiards, however, ending the game was not an option, so the young man decided to take over the old man's turn and finish the game
| common-pile/stackexchange_filtered |
IoC or Dependency Injection frameworks to support for an MVVM framework
I have been developing a new MVVM framework here.
It has some interesting concepts, but I'd like to support multiple IoC containers. Right now I'm supporting just MEF, because it comes with .Net 4.0.
What are some of the more common IoC/DI frameworks I should look into supporting from the start? I'm thinking maybe 3 or so.
Castle Windsor? Ninject?
EDIT:
Just to clarify, I'm asking which IoC/DI frameworks are commonly used today. I was hoping to also learn of some of the new hotness that's out there and I've not heard of yet.
How do you support them? Have you looked at CommonServiceLocator? Or my http://docs.griffinframework.net/specification/
I haven't worked out the how yet. I was considering abstracting that out myself, but I'll check out your link.
Look at the way ASP.NET MVC uses a DI container: it does not. It has a DefaultControllerFactory implementation that works with Activator.CreateInstance and it is very easy to plug in your own controller factory that works with your own DI container.
Yes, that's what I want to do. I want to provide a MEFFactory, WindsorFactory, NinjectFactory, etc. What are some commonly used containers I can support out of the box? (This is what my question is asking)
Unity and Castle Windsor should be a must in my opinion, especially Unity since it's used in Prism and it is part of the Enterprise Library (for portability). And Castle windsor for its easy of use (for a broader community)
A library or framework should not use a DI Container - only applications should use containers.
Libraries and frameworks should be designed so that they are friendly to any sort of DI, whether or not the user wants to use a container or Poor Man's DI.
Assume that the user will be using Poor Man's DI and you will automatically be container agnostic.
There is a View <-> ViewModel hookup mechanism that uses DI in my framework. This is the reason for using a container. I don't want the user of my framework to have be manually setting DataContext on his Views. I see your point though.
I want to support containers similar to how Caliburn does: http://caliburn.codeplex.com
Move your DI logic out of your library and encapsulate it into an interface that sets the datacontexts for you. Then the application developer used there DI container of choice to implement your interface
Yes that's exactly the idea. Then I would have separate libraries for supporting MEF, Castle Windsor, etc. My question asks which of these libraries to support.
Prism offers the same kind of IoC/DI that he wants to implement, so library/frameworks may very well use them as long as they offer to switch to another one easily if it doesn't suit the user.
An alternative would be to provide a simple IoC Container just like Mvvm Light does.
I have just supported MEF instead of that. I don't see a reason to do that when MEF ships with .Net 4.0.
| common-pile/stackexchange_filtered |
Facebook developer app: Unable to save Contact Email or app Domains
In short, i am not able to save any information in the facebook developer app > settings > basic section. Whether it be adding a platform, updating a platform, or even adding a Contact Email or domain.
I have another FB app and its setup just fine. I have now added a second FB app and everything is setup minus this SETTINGS>BASIC tab as nothing will save. if i add a platform and do a 'quick start' tour, it will successfully add a new platform, but i am not able to make changes.
Anytime i click 'save changes', all the fields just flash then nothing happens. i have tested this in Chrome, FF and IE. All other fields in all other tabs work fine. I have gone through dozens of sites looking for an answer. Any thoughts to offer?
edit
http://stackoverflow.com/q/35859147/1427878
It looks like there is some issue with the service. Developer console shows a bad request made to their basic settings service.
Thanks. I tried again this morning from a different pc on a different network, and it worked just fine. maybe it was their service? maybe something with my machine/connection? thanks
| common-pile/stackexchange_filtered |
Can the radial blur zoom outwards not inwards?
How do you create the effect in photoshop to make shapes appear to shoot out from the center of an image, a bit like light rays.
Radial blur with zoom seems to blur both out from the center and towards to the center (the effect you would see if you were moving in relation to an object). This is close but ultimately isn't the effect i'm after
(attached image of the radial blur effect:)
i'll attach a better image when i get a chance
Use Free Transform (ctrl+t on pc). Set the transform centerpoint to the radial blur centerpoint, hold down shift to keep proportions and alt to resize all four sides at the same time, and drag the start of the blur to match the object.
If you're worried about lowering the render quality while scaling bigger you could do the radial blur with bigger resolution in a different file, but scaling blurs is relatively safe qualitywise.
Heres a screenie:
great, i actually just came back to this problem today and found a similar solution. works perfectly
Here's an interesting fact, radial blur has a different effect depend on where on the page the object is that you are using the filter on. This is because it is based form the center, and works in a circular way, hence: radial blur.
Also, out of curiosity, the attached image is or is not what you are going for?
not what i'm going for, i want it to only blur the object outwards from the center. but by default it is also blurring inwards towards the center
Hmm, despite it's tediousness, you may be best off masking. I'll put some more creative thought it into tomorrow, but that's all I got on my tired brain at the moment :]
I would think the clever use of layers and masks would resolve this. Just add the blur effect on a different layer and mask out the parts you don't want. It will probably take a bit of trial and error to get the exact effect you want, but the Radial Blur tool is a fairly blunt instrument.
i think this would be very difficult/tedious to do since some parts are blurred over the top of others...
| common-pile/stackexchange_filtered |
Creating a Wrapper .exe for launching Kite with Intel SDE for use in Sublime Text
I have an old CPU (Intel Pentium G3450 @ 3.4Ghz) and 6GB of DDR3 RAM.
I wanted to run Kite Autocomplete In Sublime Text but the installer said my PC Needs to support AVX.
Then I Found Out about "Intel SDE", It is an emulation layer which can run AVX apps on non AVX CPU !
So I Managed to Install Kite using Intel SDE with this command :- (NOTE : I have added SDE to path for easy usage)
sde -- "C:\Users\USERNAME\Downloads\KiteSetup.exe"
Although I got an error saying "Kite installation Timeout : Try Turning off Antivirus. Splash screen will close now", But I think It Installed Already.
It is showing up in Control Panel and I can Also see 1GB of Files in Kite Folder in Program Files.
So Now comes the problem, How do I make Sublime Text Launch Kite using Intel SDE ? Maybe some C++ Wrapper ?
HERE ARE THE THINGS I TRIED :-
I tried editing the kite sublime package file but couldn't decode the format.
I renamed original kited.exe to kited1.exe. Then I created a batch file with launch command and then packaged it to an exe with Bat-to-Exe tool and saved as kited.exe in Kite Folder. It Did launched kite successfully but kite doesn't seem to be Connected to Sublime Text (Note : I have already installed the plugin from package Control). It just Launches and then Terminates after some time.
Edit : -
Content of batch file is sde -- "C:\Program Files\Kite\kited1.exe"
Is the content of the batch file you pointlessly hid inside an extractable exectuable wrapper a huge secret? I don't understand how you can expect programming advice for a specific issue based upon the current content of your question. Please make sure that you've read through your question, as if you're one of us, and then all of the linked content of [ask]. After you've done that, please use the [edit] facility to make the required improvements, if you wish to receive assistance with an on topic and answerable question.
The Kite.sublime-package file is in plain ZIP format. To edit it, you can either unzip it to a temp folder, make your changes, zip it back up, and replace the original, or you can use the PackageResourceViewer plugin, which extracts it to the Packages folder for you.
@Compo there is nothing secret. Batch file just said sde -- "C:\Program Files\Kite\kited1.exe"
Highly recommend not using PackageResourceViewer to extract the package for you unless the Kite package is no longer under active development, because extracting it that way will lock you into the currently installed version forever unless you manually remove the files.
| common-pile/stackexchange_filtered |
android activity: how to avoid multi-activity because time-delay
I use remote or keyboard with android.
I have a list in XActivity and when keyPress listitem and start YActivity, and there some data need download before YActivity, so, when keyPress, there exist a time-delay, about several seconds later and then pop up one YActivity.
BUT at that seconds time-delay, person can move the focus and pressed again, another YActivity pop again.
how to avoid this.
Intent i = new Intent(this, YActivity.class);
Bundle b = new Bundle();
b.putSerializable("ID", id);
i.putExtras(b);
startActivityForResult(i, 1);
Use AsyncTask in you YActivity to load data.
"AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations"
Thanks
When you press to open the YActivity then
the process means download you are doing shall be done in background not in UI thread You can use Asynch Task OR Threads
You can disable the button which started the YActivity
Intent i = new Intent(this, YActivity.class);
Bundle b = new Bundle();
b.putSerializable("ID", id);
i.putExtras(b);
startActivityForResult(i, 1);
btn.setEnabled(false);
And also you can set a Flag(like isStartingYActivity) and check if it is begin start
if(!isStartingYActivity)
{
Intent i = new Intent(this, YActivity.class);
Bundle b = new Bundle();
b.putSerializable("ID", id);
i.putExtras(b);
startActivityForResult(i, 1);
isStartingYActivity = true;
}
As soon as the button is clicked to move to the new activity. Make the button disabled. Like this. yourButton.setEnabled(False); This will prevent from double clicking on the button. Take the user to the new activity which he wants to go to and implement Async Task in new Activity and show a progress dialog from pre execute of asynctask so that the user will know that the new activities data is getting loaded.
| common-pile/stackexchange_filtered |
Compile resx to Javascript
Is there a way to compile resx file to Javascript during build time? I found only this: Localize Strings in Javascript which is useless in my case because I have really many strings to put in javascript.
Because I will need generator to output 200 properties.
I think some of the answers in your link would allow for muliple properties.
But there are other solutions:
http://www.west-wind.com/weblog/posts/2009/Apr/02/A-Localization-Handler-to-serve-ASPNET-Resources-to-JavaScript
If you search for "convert resx json" you will find different approaches.
It is cool, but if I can do this during compilation time I can bundle this script. Anyway +1 I will explore this solution
There are tons of similar solutions out there. We explored it too for while, but now just serialize all page resources into a json object and dump it onto the page.
| common-pile/stackexchange_filtered |
gnuplot unable to read .dat file
I have been stuck with this error 'gnuplot:unable to read data.dat' error from 2 days.
I have put the file path also, but still the error is coming.I searched the internet and I am not getting it.
Thank you
void plotgraph(float *xvals, float *yvals, float *x1vals, int NUM_POINTS)
{
int NUM_COMMANDS = 4;
//char * commandsForGnuplot[] = { "set title \"Concatenated Coding+OFDM[QPSK]\"", "set ylabel 'BER'", "set xlabel 'SNR'", "plot '\C:\\Users\\shreyasn\\Documents\\Visual Studio 2013\\Projects\\Project1\\Project1\\data.temp\' with lines" };
//FILE * temp = fopen_s(&temp, "%temp%\\data.temp", "w");
//char *commandsForGnuplot[] = { "set title \"Concatenated Coding+OFDM[QPSK]\"", "set ylabel 'BER'", "set xlabel 'SNR'", "set logscale y", "set nologscale x", "plot 'data.temp' with lines title 'After coding' , \ 'data.temp1' with lines title 'Before coding'" };
// double xvals[NUM_POINTS] = {1.0, 2.0, 3.0, 4.0, 5.0};
//double yvals[NUM_POINTS] = {5.0 ,3.0, 1.0, 3.0, 5.0};
int i;
for (i = 0; i < NUM_POINTS; i++)
{
printf("time: %f decod: %f encod: %f \n", xvals[i], x1vals[i], yvals[i]); //Write the data to a temporary file
}
errno_t err;
FILE *pipe;
FILE *temp9;
if ((err = fopen_s(&temp9, "data.dat", "w+")) != 0)
printf("File not opened\n");
if (temp9 == NULL) {
printf("Error\n");
}
char * commandsForGnuplot[] = { "set title \"Concatenated Coding+OFDM[QPSK]\"", "set ylabel 'BER'", "set xlabel 'SNR'","plot '\C:\\Users\\shreyasn\\Documents\\Visual Studio 2013\\Projects\\Project1\\Project1\\data.dat\' using 1:2 with lines" };
//char * commandsForGnuplot[] = { "set title \"Concatenated Coding+OFDM[QPSK]\"", "set ylabel 'BER'", "set xlabel 'SNR'", "plot 'data.dat' with lines" };
//FILE * temp1 = fopen_s(&temp1,"data.temp1", "w");
//char *path = "C:\\Program Files (x86)\\gnuplot\\bin";
pipe = _popen("\"C:\\gnuplot\\binary\\gnuplot.exe\" -persistent", "w");
//Opens an interface that one can use to send commands as if they were typing into the
// gnuplot command line. "The -persistent" keeps the plot open even after your
// C program terminates.
//
for (i = 0; i < NUM_POINTS; i++)
{
fprintf(temp9, "%f %f \n", xvals[i], yvals[i]); //Write the data to a temporary file
//fprintf(temp1, "%lf %lf \n", xvals[i], x1vals[i]); //Write the data to a temporary file
}
fclose(temp9);
fflush(temp9);
for (i = 0; i < NUM_COMMANDS; i++)
{
fprintf(pipe, "%s \n", commandsForGnuplot[i]); //Send commands to gnuplot one by one.
}
fflush(pipe);
}
'pipe' is a system call in C, use a different name
if the file did not open, then I suspect that the program should exit, not continue with the next statements
cannot flush a file after it is closed. (and closing performs a flush anyway)
this line segment: 'char * commandsForGnuplot[]' should probably be: 'char ** commandsForGnuplot[][]' and the actual commands be formatted accordingly. I.E. { {"command1"},{"command2"}, ... };
You have a wrong backslash as first character in the file name, and you don't need to escape single quotes. It should be "plot 'C:\\Users...'".
@Christoph I did as you told still same error is appearing
@Christoph I first created that data.dat file first. Then I copied that file to where gnuplot.exe was present, then I was able to see the graph. Could you please suggest how to overcome this?
From which path did you copy the file? You write the file using a relative path and the resulting absolute path doesn't match the absolute oath you are giving to gnuplot. Either use the very same absolute path for saving and plotting, or figure out where your output file ends up. In any case it is quite cumbersome to guess what you are doing every time!
@Christoph can you please tell me how to write the file using relative path?
the following information, copied from elsewhere,
it shows how to open a pipe.
prototype:
int pipe(intfd[2]);
RETURNS: 0 success
-1 on error: and set errno
NOTES: fd[0] is set up for reading, fd[1] is set up for writing
The first integer in the array (element 0) is set up and opened for reading, while the second integer (element 1) is set up and opened for writing. Visually speaking, the output of fd1 becomes the input for fd0. Once again, all data traveling through the pipe moves through the kernel.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
main()
{
int fd[2];
pipe(fd);
.
.
}
the documentation on fopen_s states this about the mode string:
(there are other allowed mode strings, but the following seems to
be most useful)
"r+"
Opens for both reading and writing. (The file must exist.)
"w+"
Opens an empty file for both reading and writing.
If the file exists, its contents are destroyed.
So I suggest using the "r+" mode string rather than the "w+" mode string
the failure to open suggests that the user does not have
permission to overwrite the file.
Then how to get permission
| common-pile/stackexchange_filtered |
Can regular drip coffee grounds be used for pour over coffee and achieve good results?
Can you use regular drip coffee for pour over, and if you do will the coffee taste OK?
Yes, it'll be fine.
Drip brewing and pour-over coffee are essentially the same process: Pour hot water over ground coffee to extract flavor compounds, then let the infused hot water solution drip through a filter into a serving vessel. As far as the final product is concerned, it doesn't especially matter if this happens in a machine that dispenses the hot water automatically (drip brewing), or if you pour the water yourself by hand.
The only reason coffee grounds might be suitable for one but not the other would be if you use different filters for drip brewing and pourovers. For instance, if you have a drip coffee machine that takes paper filters, but a standalone metal mesh filter that you use for pourovers, you would want to use slightly coarser coffee grounds for the latter. Even in this case, though, the worst possible outcome would be that your coffee might be a little cloudy or gritty, just like if your grounds were slightly too fine (because that's exactly what's happened).
| common-pile/stackexchange_filtered |
Submit datefrom html form to controller
I want to submit a date to my controller using html form, I tried this but doesn't work:
<form action="/Home/Index" method='get'>
<input type="date" name="Choisir une date"><br>
<input type="submit" value="Submit">
<input type="reset">
</form>
Are you getting any error? Did you try putting a breakpoint in your controller method to be sure whether the request is reaching upto that point or not?
No error, when I click on submit the page is refreshed and with breakpoint date = null.
What controller? Is this an ASP.NET MVC app?
Yes it's an ASP.NET MVC app. it's works now but I have an other problem, when I choose a date and click on submit I get the new data but the date return to default value (Today in my case).
Please add name property to your input element as
<input type="date" name="date" placeholder="Choisir une date">
You should get the value for date param in your controller method now. The name property should match with your controller method parameter name.
It is an invalid HTML. It should be <input type="date" name="date" placeholder="Choisir une date">
First of all try with post method instead of get.
<form action="/Home/Index" method='get'>
<input type="date" name="ChoisirDate">
<br/>
<input type="submit" value="Submit">
<input type="reset">
</form>
And in controller
public IActionResult Index(string ChoisirDate) {
string ChoisirDateText = ChoisirDate;
Return View();
}
| common-pile/stackexchange_filtered |
interface angular usage in for loop
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
export interface User {
id: number;
name: string;
}
@Component({
selector: 'app-typeof-otcsection',
templateUrl: './typeof-otcsection.component.html',
styleUrls: ['./typeof-otcsection.component.css']
})
export class TypeofOTCSectionComponent implements OnInit {
user!: User[];
userList=any;
constructor() {}
ngOnInit(): void {
this.user={"id":0,"name":""}
}
let z=1
for (let k = 0; k < ((userarrayfromDB).length); k++) {
let user =this.user
user.id=z
user.name=userarrayfromDB[k].name
userList.push(user)
z++
}
}
So I am working on an angular project, I have made an interface called user, and using the interface I have made the object ie this.user . So suppose the userarrayfromDB length is 3 and when I am pushing the user object in userlist array , it is pushing the last array 3 times
for Example
[
{
"id": 3,
"name": "nishit"
}
],
[
{
"id": 3,
"name": "nishit"
}
],
[
{
"id": 3,
"name": "nishit"
}
]
I want the user list array like the below example
[
{
"id": 1,
"name": "test"
}
],
[
{
"id": 2,
"name": "test2"
}
],
[
{
"id": 3,
"name": "nishit"
}
]
Ok, I will try that and will let you know. Thanks
But can you explain to me why my last array only inserted 3 times
Correction for previous comment: Expect that the push user into array logic should be in a method. From your code, the logic was in the global which is incorrect. While you don't need to declare z variable for the index. Instead, user.id = k + 1 does the same job.
@Nishitbhardwaj when you do let user = this.user and then push the user variable in the array, it's always the same object reference that you are pushing, 3 times. Whenever you modify that instance once, all its references will be updated. Try let user = {...this.user}; instead.
For this particular scenario, you don't necessarily need a for loop to move some data from one array to another. You could do it all in one line like this:
this.userList = [...userarrayfromDB];
In case your userarrayfromDB contains objects of a different shape (for example, they have more properties than you need), then you can use .map to project the data in the desired form:
this.userList = userarrayfromDB.map(user => {
const result = { id: user.id, name: user.name };
// conditionally assign more properties here.
return result;
});
how can I add an if and else condition ??
What do you need to check exactly? The map handler can be expanded with curly braces and you can do whatever you need there.
let users = [[{"id":3,"name":"nishit"}],[{"id":3,"name":"nishit"}],[{"id":3,"name":"nishit"}]];
var index=1;
var usersList = users.map(record =>{
let user = record[0];
user.id=index;
user.name="test"+index;
index++;
return user;
});
console.log(usersList)
| common-pile/stackexchange_filtered |
CakePHP: Passing $this->params['form'] in a requestAction call?
How can I pass $this->params['form'] to the controller action I specify in requestAction so that I can use the variable in the same way by calling $this->params['form']?
Here is what I'm trying (but isn't working):
$this->requestAction('/reports/grid', array('params["form"]' => $this->params['form']));
$this->requestAction('/reports/grid', array('$this->params["form"]' => $this->params['form']));
$this->requestAction('/reports/grid', array('form' => $this->params['form']));
According to the 1.3 documentation, you'll need to specify each parameter you want to send off in the request in the pass or named parameter key - http://book.cakephp.org/1.3/en/view/991/requestAction
echo $this->requestAction(array('controller' => 'articles', 'action' => 'featured'), array('named' => array('limit' => 3)));
echo $this->requestAction(array('controller' => 'articles', 'action' => 'view'), array('pass' => array(5)));
So, it should be something like
$this->requestAction('/reports/grid', array('pass' => array($this->params['form'])));
Note - There are very few good reasons you would want to use requestAction. Please read up on the performance penalties if you haven't already.
Close, but not quite. Instead of pass I just had to use form, and remove the array() wrapping the parameter. Thanks for the insight :)
Could you post the solution that worked for you? It might help someone with the same problem. Thanks!
| common-pile/stackexchange_filtered |
float left causes hover on right side of menu
I am curious if there's any way to correct this behavior using css only...
Notice that when you hover over the white space to the right of the menu it causes the blur of the menu items. If you hover over the white space to the left of the menu it does not blur the menu items.
I am sure that the float: left of the #centeredmenu ul rule is causing this blur. I would like to stop the blur when you hover over the white space to the right but this rule is necessary to center the menu.
I am trying to correct this page: http://www.soaringbirdstudios.com/help
As you can see in firebug I tried to add another div below the centermenu div with a style of clear both and enclosed both divs in an enclosing div but that didn't work. I just don't have enough experience to figure this one out.
Thanks.
Please don't link to external pages and expect users to reverse-engineer them. Post an example as part of your question.
See: http://meta.stackexchange.com/questions/125997/something-in-my-web-site-or-project-doesnt-work-can-i-just-paste-a-link-to-it
I tried to fix your code, but you actually minified your CSS. Not gonna try to understand that. Don't minify CSS, seriously. The performance impact is minimal and it's just a pain in the butt. At least don't while you're in development. From what I could see though, the reason for this is that you used some weird methods for positioning your elements to the center. Relative positioning and floating... Un-float everything and remove all position stuff, and center elements normally, using text-align: center and/or margin: 0 auto;
I strongly disagree! Of course you should minify CSS, it's not a problem reading it with the proper browser's inspector tools (Chrome) - not to mention it takes about 1 min to send it through a unminify tool like: http://mrcoles.com/blog/css-unminify/ - every performance counts, saving 1kb is a lot after 10.000.000 visitors! Every bit helps for mobile devices as well.
@Diodeus sorry I wasn't aware.
Not sure if it will help your exact desired solution, but if you mean wanting to get rid of the floats, you can simply do the following:
Change:
.bmenu li {
display:inline-block;
/*float: left;*/ <-- can delete or comment out
list-style: none;
padding: 0;
position: relative;
/*right: 50%;*/ <-- can delete or comment out
margin: 100px 0 0;
font-size: 50px;
vertical-align:top; <--- added for making it pretty
}
Continue downwards with the following changes to get rid of floats completely:
delete <div style="clear:both;"></div>
#centeredmenu ul {
/*clear: left;*/ <-- can delete or comment out
/*float: left;*/ <-- can delete or comment out
list-style: none;
margin: 0;
padding: 0;
position: relative;
/*left: 50%;*/ <-- can delete or comment out
text-align: center;
}
#centeredmenu {
/*float: left;*/ <-- can delete or comment out
width: 100%;
overflow: hidden;
position: relative;
}
Any possibility you could upload the code after removing the floats? Would make it just a little easier to debug.
Did as you asked, now it blurs when hovering over both sides of the menu. Can't text indent either and logo is not showing correctly. Looks like you've created many more problems
Nah, you just misspelled a css rule that misplaced the elements. Ok good luck!
I'm looking at your solution again
| common-pile/stackexchange_filtered |
What's the main purpose of using java rmi activation system?
First of all, I am reading the java official document about rmi specification.
http://docs.oracle.com/javase/7/docs/technotes/guides/rmi/index.html
http://docs.oracle.com/javase/7/docs/platform/rmi/spec/rmi-activation2.html
The features in java rmi listed in oracle website can be easily understood except rmi activation part. I have read through the detailed document of rmi activation mechanism, but still got nothing about the useful practice in the real scenario.
Thus, these are several question which really confused me as follows:
Regarding the doc, rmid is a router which specifies the remote rmi
server and return the server information to the clients only once.
This looks like the similar function with rmiregistry which is a place for the server to register services. What's the
difference if we do not have it?
Does this mechanism include server
auto-recovery or failover functionality? In other words, I have already known that remote rmi server should be registered on RMID, if one of remote rmi server (maybe on different machine) crashed, can RMID detect this and trigger this remote rmi server bouncing?
Can the function of rmid be implemented via using the rmi API in order to run the same function in my customized standalone server instead of using JDK RMID tools. For example, tools rmiregistry could be replaced with rmi API LocateRegistry.createRegistry(regPort);
Please advise or provide the relevant material, thanks in advance.
What makes you think there's only one purpose?
sorry about the title, makes you confused, should be corrected into main purpose.
However, I read the O'Reilly Java Rmi Book. It noted that the RMI activation daemon is an RMI server, just like the RMI registry, whose sole purpose is to launch Java servers. Simply quote its words as title.
Please amend your title yourself to indicate whatever you are actually asking.
Apparently, Oracle didn't know what RMI Activation is for either, and killed it
Regarding the doc, rmid is a router which specifies the remote rmi server and return the server information to the clients only once.
No. The documentation doesn't say that. 'rmid' is a daemon that starts the remote object if it isn't already running.
This looks like the similar function with rmiregistry
No.
Does this mechanism include server auto-recovery or failover functionality?
If the JVM containing an activated remote object exits, or the activated remote object de-activates itself, rmid will restart it on demand.
Can rmid be running in the standalone server, and initialize via java API instead of rmi tools?
I don't understand the question.
Thanks for your prompt response. Due to the lack of the rmi activation doc, really sorry for serveral mess questions. I detailed the question a little bit. BTW, could you provide the detailed activation system mechanism how it works or how it make app more reliable in any other doc? There is few useful info from the official doc except standard example.
The existing documentation is more than adequate to understand how it works inside. Not that you really need to know. What actual problem are you trying to solve?
| common-pile/stackexchange_filtered |
jquery validate user has entered text into 1 of 2 textboxes
Hi I am struggling to find an answer to this, if it can be done?
I have a login form that contains 3 textboxes: UserID, Post code, Date of Birth
The user id is fine I can add a required attribute to validate, but I was wanting to validate that they had also entered data into 1 of the other 2 textboxes, so either post code or date of birth. I don't want to use asp.net custom validators as they are a pain, and was hoping that this could be done in html5/jQuery. These textboxes are on a .net user control, so not sure if that is an issue as I have had trouble with it finding the form if i use something like... $("#form1").validate
You may need to use ClientID of server controls for accessing them in javascript. You can bind javascript on click event of submit button and perform any validation.
$('#<%= submitButton.ClientID %>').click(function (){
textBox1Value = $('#<%= textBox1.ClientID %>').val();
textBox2Value = $('#<%= textBox2.ClientID %>').val();
//do validation on both textboxes here
if(!conditionFormValidated) //To prevent submit if form validation fail
return false;
});
This put me on the right path, can't post the answer yet as i am too new apparently.
You should check all three fields values in the textboxes. That should be checked on form submit. If two of them exist then you should re-initialize your validate method and invoke it.
This is how I did it, validating that 1 of 2 textboxes on a wizard control has a value.
if (!Page.IsPostBack)
{
Button btn = (Button)Wizard.FindControl("StartNavigationTemplateContainerID").FindControl("StartNextButton");
string script = "$(\"#" + btn.ClientID + "\").click(function () { if (($(\"#" + PostCode.ClientID + "\").val() == \"\" && $(\"#" + textDob.ClientID + "\").val() == \"\") || ($(\"#" + ClientId.ClientID + "\").val() == \"\" && $.browser.msie && parseInt($.browser.version, 10) < 10)) { $.jGrowl(\"<p style='padding: 3px; color: #fff;'>Please enter your Client ID and either a <em>Post code</em> or <em>Date of birth</em></p>\"); return false; } });";
Page.ClientScript.RegisterStartupScript(Page.GetType(), "ValidateLogin", script, true);
}
| common-pile/stackexchange_filtered |
how to flatten photo image which contains text only?
how can I detect the document has been folded (and possibly folded by none, once, or multiple times)
how can I correct section II so that it's turned into a rectangle?
what did you already try? do you want a completely automatic solution? Or is it feasible to click into the image and then do the correction?
Thanks for respond. I need a automatic solution.
I guess this can be achieved by:
we can assume the paper is alwasy white, and it's rectangle.
once it's folded, the number of vertice will change, thus we can probably know how many fold has been done
the vertices slit the pane into multiple ones, we can then use some transform to correct it.
sadly I'm not familiar with image processing.
| common-pile/stackexchange_filtered |
URLs not working as HTML frame src
I have the following HTML code which is not giving any output on neither Mozilla nor IE. The status bar shows connected to www.Facebook.com & www.yahoo.com but then the pages are not displayed. I've tested in Mozilla & IE.
<HTML>
<head>
<script src="scripts.js"></script>
</head>
<frameset cols="50%,50%">
<frame src="http://search.yahoo.com/search?p=gmail" />
<frame src="http://www.facebook.com/login.php" />
</frameset>
</HTML>
I hope this is a typo: <frame src=<frame src=.
Just tested that iframe in Firefox, the search.yahoo.com website works well, but facebook.com refuses to load in iframe - you get only empty page in the right side frame.
frameset tag always requires a DOCTYPE tag.
Note: If you want to validate a page containing frames, be sure the is set to either "HTML Frameset DTD" or "XHTML Frameset DTD".
P.S.: Not sure if this requirement is there or not from HTML5.
With regards to frames and HTML5: Any way of using frames in HTML5?. Frames are obsolete in HTML5.
@RoddyoftheFrozenPeas Thanks for the read. :) Will keep in mind.
This line:
<frame src=<frame src="http://search.yahoo.com/search?p=gmail" />
take away the first '<frame src='
okay sorry for that inconvenient line. But still its not working.
| common-pile/stackexchange_filtered |
WOPI host and WOPI client example
I am a bit confused about WOPI host and WOPI client.
Can anyone tell me exactly the meaning of above 2 terms. I want to know what exactly means WOPI host (either my web application or a WOPI server on Microsoft side) and same for WOPI client.
WOPI host = WOPI server = a web API that serves files to WOPI client
WOPI client = an application that is able to edit files served by WOPI host
The two communicate via MS-WOPI protocol that is described here.
Example implementations:
WOPI host - SharePoint
WOPI client - Office Web Apps (Office Online Server)
A typical scenario is that you want to enable your application to edit files in Word/Excel... In that case, you need to implement a WOPI host - an endpoint which the WOPI client (OWA) will talk to. Implementing such a host is described here.
You can take a look at existing projects on GitHub - marx-yu's implementation using HttpListener, or mine using ASP.NET Core 3.1.
thanks for the answer.
I would like to know one more thing about that Lock request,
There is nothing defined in Lock endpoint implementation document on http://wopi.readthedocs.io/projects/wopirest/en/latest/files/Lock.html
What should this request generate ?
Any random string or what ?
A random string that is within the following boundaries: http://wopi.readthedocs.io/projects/wopirest/en/latest/concepts.html#lock-length
Got it boss!! Thanks. :)
Hi Rocky, that was a very good answer. I just want to ask that Is is possible to implement WOPI host in Node.js? Thank you in anticipation.
I saw you submitted a separate question. Check out my answer there: http://stackoverflow.com/questions/39062025/wopi-host-implementation-in-nodejs/39186295#39186295
Hi, rocky, could you give me some suggestions about this (problem)[https://stackoverflow.com/questions/60540105/how-to-let-office-online-own-the-style-of-view-mode] Thanks.
@rocky is Office Web Apps free of cost?
Afaik, it's only free for viewing docs, not editing. The full licensing terms can be found here: https://learn.microsoft.com/en-us/archive/blogs/licensing/how-to-license-office-web-apps-server
For Office Online Server (a newer version of OWA), see this: https://learn.microsoft.com/en-us/officeonlineserver/office-online-server
| common-pile/stackexchange_filtered |
Using alternative for Visual Studio for cmake
Actually my computer has a low space. That's the reason for taking an alternative of Visual Studio. I am trying to use the face-recognition library in python. As we know that cmake is a C-Based language. We also need to install a compiler too. So please help me by letting me know that :
Whether there is an alternative of Visual Studio
(If yes) then what is it.
And how to install it
Thank you :)
There are lots of alternatives to Visual Studio, but first a quick clarification - Visual Studio is an IDE and it includes various compilers.
If you just need a compiler you can download the binaries from gcc.gnu.org and build on the command line.
If you want an IDE (but lighter than VS) I'd recommend CodeBlocks, which you can download from codeblocks.org.
Good luck!
Sorry for disturbing again, but i am getting confused to install the compiler from https://www.gcc.gnu.org if possible, kindly please give me the steps too please :)
It was a mistake to refer you to the gcc website - I haven't actually tried it myself and it is not not as simple as I thought. The easiest way is to use codeblocks - this will download an appropriate compiler for you as part of the installation process. Note that the compiler itself takes 0.5 GB of space.
Here is a detailed guide how to install it using codeblocks
| common-pile/stackexchange_filtered |
calculate average letters in string
I need to calculate the average number of letters in each word from the user input. But I don't know how to do that. I know I need to find the total letters, then divide.
private void button1_Click(object sender, EventArgs e)
{
var wordCount = countMethod(textBox1.Text);
MessageBox.Show(wordCount.ToString());
}
private int countMethod(string input)
{
var separators = new[] { ' ', '.' };
var count = input.Split(separators, StringSplitOptions.RemoveEmptyEntries).Length;
return count;
}
What do you mean by average letters?
The average number of letters in each word
@Sam Please edit your question to reflect that - there's a difference between an average letter (nonsensical) and an average number of letters.
For each string you receive after the split, just put the length in a list and call .Average() (LINQ) on it.
You can use the LINQ Average to do this
private double AverageWordLetter(string input)
{
var separators = new[] { ' ', '.' };
var average = input.Split(separators, StringSplitOptions.RemoveEmptyEntries)
.Select(x=>x.Length).Average();
return average;
}
You could do this.
var separators = new[] { ' ', '.' };
var words = input.Split(separators, StringSplitOptions.RemoveEmptyEntries);
decimal avg = words.Count() ==0? 0: (decimal) words.Sum(s=>s.Length)/(decimal)words.Count();
or, as @dotctor suggested (in comments) we could simply use Average extension.
var separators = new[] { ' ', '.' };
var words = input.Split(separators, StringSplitOptions.RemoveEmptyEntries);
var avg = words.Select(s=>s.Length).Average();
Or use Enuemrable.Average
Also there is no need to cast both sum and count to decimal. You can remove one of them.
| common-pile/stackexchange_filtered |
Alpha channel not working
So I am writing a basic app for the windows phone but the alpha channel doesn't seem to be showing up in any of the images I use. In Fireworks I can see the alpha channel in there.
<Image Source="Assets/Images/OnBar.png" Width="100" Height="60" Margin="280, -560, 0, 0" />
That is the xaml code used to display the image in the first place. Currently I don't have any C# code behind it so if I need to implement something on that side a point to the right direction would be appreciated. I looked around but couldn't find anything that worked or was useful. The Image itself is also white so if the alpha channel doesn't work then nothing will display. Any help is appreciated.
where to you put this image? is it on a control, like a button or something? consider making the background transparent, but anyway do tell more.
the image itself is not a button, its just a normal images placed into the window with no functionality. The only thing I can give of its location would be the fact that its located in the main grid of the window. As for the background I made it transparent through the fireworks editor but it still doesn't show like that in the actual window. Its not only this image its any image I load. I am thinking there is something I am forgetting to declare in the image parameters but can't figure out what it is.
Just tested it, it works fine with an arbitrary transparent Image. Maybe your png export format isn't compatible with xaml. Or your Imageis inside a container which isn't transparent.
But you don't forget to declare anything in Image's parameters, alpha channel is built-in and no tweakable, as far as I know.
Please provide more details and I'll edit my post.
The issue was within fireworks and not the actual code. Even thought I set the entire image to have the background an alpha channel I never went into the modify settings and set the background color to transparent.
| common-pile/stackexchange_filtered |
Image Resizing not working using s3reader
I m using Image resizer to resize the amazon images.
I m not getting any errors but i m not also able to resize my image.
I have tried to open the image url directly, it doesn't show any errors there as well.
Also i m using this on visual studio web server so the IIS is not the problem.
I m using MVC and have installed MvcRoutingShim plugin properly.
I m trying to resize the image from height = 600 to height = 100 but it doesn't work.
My Disgnostics output is as under
Image resizer diagnostic sheet 4/2/2013 11:52:23 AM
2 Issues detected:
(Warning): To potentially see additional errors here, perform an image resize request.
(Warning): NoCache is only for development usage, and cannot scale to production use.
Add DiskCache or CloudFront for production use
You are using paid bundles: Cloud Bundle
Registered plugins:
ImageResizer.Plugins.Basic.DefaultEncoder
ImageResizer.Plugins.Basic.NoCache
ImageResizer.Plugins.Basic.ClientCache
ImageResizer.Plugins.Basic.Diagnostic
ImageResizer.Plugins.Basic.SizeLimiting
ImageResizer.Plugins.MvcRoutingShim.MvcRoutingShimPlugin
ImageResizer.Plugins.S3Reader.S3Reader
Configuration:
<resizer>
<pipeline fakeExtensions=".ashx" />
<plugins>
<add name="MvcRoutingShim" />
<add name="S3Reader" buckets="refp" />
</plugins>
</resizer>
Accepted querystring keys:
quality, format, thumbnail, maxwidth, maxheight, width, height, w, h, scale, stretch, crop, cropxunits, cropyunits, page, bgcolor, rotate, flip, sourceFlip, sFlip, sRotate, borderWidth, borderColor, paddingWidth, paddingColor, ignoreicc, frame, useresizingpipeline, cache, process, margin, anchor, dpi, mode, zoom,
Accepted file extensions:
bmp, gif, exif, png, tif, tiff, tff, jpg, jpeg, jpe, jif, jfif, jfi,
Environment information:
Running Microsoft-IIS/7.5 on Microsoft Windows NT 6.1.7601 Service Pack 1 and CLR 4.0.30319.296
Trust level: Unrestricted
OS bitness: AMD64
Executing assembly: c:\windows\system32\inetsrv\w3wp.exe
IntegratedPipeline: True
Loaded assemblies:
mscorlib Assembly: <IP_ADDRESS> File: 4.0.30319.296 Info: 4.0.30319.296
System.Web Assembly: <IP_ADDRESS> File: 4.0.30319.272 Info: 4.0.30319.272
System Assembly: <IP_ADDRESS> File: 4.0.30319.1001 Info: 4.0.30319.1001
System.Core Assembly: <IP_ADDRESS> File: 4.0.30319.233 Info: 4.0.30319.233
System.Xml Assembly: <IP_ADDRESS> File: 4.0.30319.233 Info: 4.0.30319.233
System.Data.SqlXml Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Configuration Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
Microsoft.Build.Utilities.v4.0 Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Runtime.Caching Assembly: <IP_ADDRESS> File: 4.0.30319.237 Info: 4.0.30319.237
System.Web.RegularExpressions Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Data Assembly: <IP_ADDRESS> File: 4.0.30319.237 Info: 4.0.30319.237
System.Numerics Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Transactions Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.EnterpriseServices Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
Microsoft.Build.Framework Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
Microsoft.JScript Assembly: <IP_ADDRESS> File: 10.0.30319.296 Info: 10.0.30319.296
System.Web.Mvc Assembly: <IP_ADDRESS> File: 3.0.20105.0
System.Web.WebPages.Deployment Assembly: <IP_ADDRESS> File: 1.0.20105.407
System.Web.WebPages Assembly: <IP_ADDRESS> File: 1.0.20105.407
Microsoft.Web.Infrastructure Assembly: <IP_ADDRESS> File: 1.0.20105.407
System.Web.WebPages.Razor Assembly: <IP_ADDRESS> File: 1.0.20105.407
System.Web.Razor Assembly: <IP_ADDRESS> File: 1.0.20105.407
System.ComponentModel.DataAnnotations Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Data.Linq Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Web.Extensions Assembly: <IP_ADDRESS> File: 4.0.30319.272 Info: 4.0.30319.272
App_Code.2uqj4rtu Assembly: <IP_ADDRESS>
App_global.asax.eogwkngg Assembly: <IP_ADDRESS>
FluentValidation.Mvc Assembly: <IP_ADDRESS> File: <IP_ADDRESS>
EntityFramework Assembly: <IP_ADDRESS> File: 4.1.10331.0 Info: 4.1.10331.0
System.Data.Entity Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Xml.Linq Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Runtime.Serialization Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
Anonymously Hosted DynamicMethods Assembly Assembly: <IP_ADDRESS>
System.Data.OracleClient Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
FluentValidation Assembly: <IP_ADDRESS> File: <IP_ADDRESS>
Cassette Assembly: <IP_ADDRESS>74 File: <IP_ADDRESS> Info: 2.0.0
EntityFrameworkDynamicProxies-EntityFramework Assembly: <IP_ADDRESS>
System.ServiceModel.Activation Assembly: <IP_ADDRESS> File: 4.0.30319.233 Info: 4.0.30319.233
System.Runtime.DurableInstancing Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.ServiceModel Assembly: <IP_ADDRESS> File: 4.0.30319.1001 Info: 4.0.30319.1001
SMDiagnostics Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Xaml.Hosting Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
Elmah Assembly: 1.2.13605.0 File: 1.2.13605.2128
Cassette.Aspnet Assembly: <IP_ADDRESS>75 File: <IP_ADDRESS> Info: 2.0.0
Microsoft.CSharp Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Web.Services Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Drawing Assembly: <IP_ADDRESS> File: 4.0.30319.1001 Info: 4.0.30319.1001
System.IdentityModel Assembly: <IP_ADDRESS> File: 4.0.30319.1001 Info: 4.0.30319.1001
System.ServiceModel.Web Assembly: <IP_ADDRESS> File: 4.0.30319.233 Info: 4.0.30319.233
System.Activities Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.ServiceModel.Activities Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.WorkflowServices Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Data.DataSetExtensions Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Web.DynamicData Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Web.ApplicationServices Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
AjaxMin Assembly: 4.60.4609.17023
AWSSDK Assembly: <IP_ADDRESS> File: <IP_ADDRESS>
Cassette.Views Assembly: <IP_ADDRESS>75 File: <IP_ADDRESS> Info: 2.0.0
ImageResizer Assembly: <IP_ADDRESS> File: <IP_ADDRESS> Info: 3-3-3 Commit: c368317
ImageResizer.Mvc Assembly: <IP_ADDRESS> File: <IP_ADDRESS> Info: 3-3-3 Commit: c368317
ImageResizer.Plugins.S3Reader Assembly: <IP_ADDRESS> File: <IP_ADDRESS> Info: 3-3-3 Commit: c368317
librets-dotnet Assembly: <IP_ADDRESS>
LinqKit Assembly: <IP_ADDRESS> File: <IP_ADDRESS>
Newtonsoft.Json Assembly: <IP_ADDRESS> File: <IP_ADDRESS>14
System.Web.Abstractions Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Web.Helpers Assembly: <IP_ADDRESS> File: 1.0.20105.407
System.Web.Routing Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
System.Web.Mobile Assembly: <IP_ADDRESS> File: 4.0.30319.1 Info: 4.0.30319.1
The url for which i m trying to resize the image is https://s3.amazonaws.com/refp/property/802/802_1.jpeg?height=100.
Please help.
Source: http://imageresizing.net/plugins/s3reader
Please move your answer to an answer
Just change the URL from
https://s3.amazonaws.com/refp(bucketname)/property(foldername)/802(foldername)/802_1.jpeg?height=100
To
http://youraspnetserver/s3/refp(bucketname)/property(foldername)/802(foldername)/802_1.jpeg?height=100
The URL always needs to point to your .NET server, not the S3 blob, as Amazon's S3 servers are just static file servers, and can't do anything dynamic.
Thanks but i have already solved that pls have a look at the update i've made in my question. Thanks anyway.
In the future, use the "Answer Your Own Question" button to log an answer - you are not supposed to simply edit the question.
| common-pile/stackexchange_filtered |
Using external action output in outer git action step
I have this git action for my build
...
- name: Building S3 Instance
uses: charlie87041/s3-actions@main
id: s3
env:
AWS_S3_BUCKET: 'xxx'
AWS_ACCESS_KEY_ID: 'xxx'
AWS_SECRET_ACCESS_KEY: 'xxxxx'
AWS_REGION: 'xxx'
- name: Updating EC2 [Develop] instance
uses: appleboy/ssh-action@master
with:
host: ${{secrets.EC2HOST}}
key: ${{secrets.EC2KEY}}
username: xxx
envs: TESTING
script: |
cd ~/devdir
export BUCKET_USER=${{steps.s3.outputs.user_id}}
export BUCKET_USER_KEY=${{steps.s3.outputs.user_key}}
docker login
docker-compose down --remove-orphans
docker system prune -a -f
docker pull yyyy
docker-compose up -d
And this is the important function in charlie87041/s3-actions@main
generate_keys () {
RSP=$(aws iam create-access-key --user-name $USER);
BUCKET_ACCESS_ID=$(echo $RSP | jq -r '.AccessKey.AccessKeyId');
BUCKET_ACCESS_KEY=$(echo $RSP | jq -r '.AccessKey.SecretAccessKey');
echo "user_id=$BUCKET_ACCESS_ID" >> $GITHUB_OUTPUT
echo "user_key=$BUCKET_ACCESS_KEY" >> $GITHUB_OUTPUT
echo "::set-output name=BUCKET_ACCESS_KEY::$BUCKET_ACCESS_KEY"
echo "::set-output name=BUCKET_ACCESS_ID::$BUCKET_ACCESS_ID"
}
I need to update env variables in container with BUCKET_USER and BUCKET_USER_KEY, but these always return null when echo the container. How do I do this?
Not that set-output was deprecated recently (oct. 2022)
If you are using self-hosted runners make sure they are updated to version 2.297.0 or greater.
If you are using runner on github.com directly, you would need to change
echo "::set-output name=BUCKET_ACCESS_KEY::$BUCKET_ACCESS_KEY"
with
echo "BUCKET_ACCESS_KEY=$BUCKET_ACCESS_KEY" >> $GITHUB_OUTPUT
I am not sure an export within the script would work.
Using with directives, as in issue 154 might be more effective
with:
BUCKET_USER: ${{steps.s3.outputs.user_id}}
...
script: |
...
| common-pile/stackexchange_filtered |
error: incompatible types: <anonymous Callback<List<UserDataResponse>>> cannot be converted to OnNoteListener
What is the problem from this code?
I used Activity and passing it to fragment
RecyclerView OnClickListener the one i use in this coding method.
i just want to click the recyclerview to send me in to another page
Please help me right now :(
Here is my UsersAdapter
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UsersViewHolder> {
private Context mCtx;
private ArrayList<UserDataResponse> userDataResponseList = new ArrayList<>();
private OnNoteListener mOnNoteListener;
public UsersAdapter(Context mCtx, ArrayList<UserDataResponse> userDataResponseList, OnNoteListener
onNoteListener) {
this.mCtx = mCtx;
this.userDataResponseList = userDataResponseList;
this.mOnNoteListener = onNoteListener;
}
@NonNull
@Override
public UsersViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.recycle_view, parent, false);
return new UsersAdapter.UsersViewHolder(view, mOnNoteListener);
}
@Override
public void onBindViewHolder(@NonNull UsersAdapter.UsersViewHolder holder, int position) {
holder.textViewName.setText("Username: " + userDataResponseList.get(position).getRTMusername());
holder.textViewEmail.setText("Firstname: " + userDataResponseList.get(position).getRTMfirstname());
holder.textViewLastname.setText("Lastname: " + userDataResponseList.get(position).getRTMlastname());
holder.textViewDepartment.setText("Department: " + userDataResponseList.get(position).getRTMdepartment());
}
@Override
public int getItemCount() {
return userDataResponseList.size();
}
class UsersViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textViewName,textViewEmail,textViewLastname,textViewDepartment;
OnNoteListener onNoteListener;
public UsersViewHolder(@NonNull View itemView, OnNoteListener onNoteListener) {
super(itemView);
textViewName = itemView.findViewById(R.id.textViewName);
textViewEmail = itemView.findViewById(R.id.textViewEmail);
textViewLastname = itemView.findViewById(R.id.textViewLastname);
textViewDepartment = itemView.findViewById(R.id.textViewDepartment);
this.onNoteListener = onNoteListener;
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
onNoteListener.onNoteClick(getAdapterPosition());
}
}
public interface OnNoteListener{
void onNoteClick(int postion);
}
}
And here is my AdminUser.java
public class AdminUserFragment extends Fragment implements UsersAdapter.OnNoteListener {
private RecyclerView recyclerView;
private UsersAdapter adapter;
Api api;
ArrayList<String> Userdata;
ArrayList<UserDataResponse> userDataResponseArrayList = new ArrayList<>();
Redirectinglog redirectinglog;
private Handler refresherHandler = new Handler();
public AdminUserFragment() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_adminuser,container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Userdata = new ArrayList<>();
redirectinglog = new Redirectinglog(getActivity());
api = RetrofitClientInstance.GetResultAPI().create(Api.class);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
/////////////////////////////////////////////////////
refreshRunnable.run();
}
private void responseuserdata(){
Call<List<UserDataResponse>> usercall = api.getUsers();
usercall.enqueue(new Callback<List<UserDataResponse>>() {
@Override
public void onResponse(Call<List<UserDataResponse>> call, Response<List<UserDataResponse>> response) {
userDataResponseArrayList = new ArrayList<>(response.body());
for(UserDataResponse UserDataResponsetest : userDataResponseArrayList){
adapter = new UsersAdapter(getActivity(), userDataResponseArrayList, this);
recyclerView.setAdapter(adapter);
}
}
@Override
public void onFailure(Call<List<UserDataResponse>> call, Throwable t) {
Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private Runnable refreshRunnable = new Runnable() {
@Override
public void run() {
responseuserdata();
refresherHandler.postDelayed(this, 10000);
}
};
@Override
public void onNoteClick(int postion) {
}
}
What should I use?
Help me please huhuh
adapter = new UsersAdapter(getActivity(), userDataResponseArrayList, this);
Here you are passing an anonymous class instead of passing an object whose class implements onNoteListener interface. Thats why, there is a problem of compatability."this corresponds to an anonymous class because you are calling it from an anonymous class which is passed it as a parameter of Usercall.enque.
My suggestion to you would be instead of creating all that mess, you can simply set a tag in your onbindViewHolder with the position being passed and whenever user taps on the recycler view , you can check it on onClick method which you will be having if you just wire an Onclicklistener to the recycler view.You can retreive the tag value from the row in question and find out which position was clicked.Simple and easy.Comment down if you have any trouble undertsanding in what i said, i will write the code sample as well.Hope my answer helps,if it helps please mark it as accepted.Cheers.
create a view in your UserViewHolderClass as a member variable and inside the constructor of this "ViewHolderClass" write this.view = view, to assign row value to it.
//inside onBindViewholder class, write
MyViewHolder.view.setTag("position")
MyHolder.view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = view.getTag("position")// this will give you
//the position of the row which will be tapped
}
});
Also, if you will create a member value view, yo dont need to keep the other member variable in the text view,in your onCreateViewHolder, you can simplydo view.findviewid("pass id of textview, image view whatever you have in your row ans you wanna find) and get the appropriate widget present as element in your row.This is because this view will have all your text views, image views whatever you have used in row's xml file.
Okay i will wait for it
Ohhh i get it. Thank you so mucch, you are lifesaveerr
| common-pile/stackexchange_filtered |
why boolean field is not working in Hive?
I have a column in my hive table which datatype is boolean. when I tried to import data from csv, it stored as NULL.
This is my sample table :
CREATE tABLE if not exists Engineanalysis(
EngineModel String,
EnginePartNo String ,
Location String,
Position String,
InspectionReq boolean)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';
My sample data :
AB01,AS01-IT01,AIRFRAME,,0
AB02,AS01-IT02,AIRFRAME,,1
AB03,AS01-IT03,AIRFRAME,,1
AB04,AS01-IT04,AIRFRAME,,1
AB05,AS01-IT05,HEAD,,1
AB06,AS01-IT06,HEAD,,0
AB07,AS01-IT07,HEAD,,0
AB08,AS01-IT08,HEAD,,0
AB09,AS01-IT09,NOSE,,1
AB10,AS01-IT10,NOSE,,0
Result :
AB01 AS01-IT01 AIRFRAME NULL
AB02 AS01-IT02 AIRFRAME NULL
AB03 AS01-IT03 AIRFRAME NULL
AB04 AS01-IT04 AIRFRAME NULL
AB05 AS01-IT05 HEAD NULL
AB06 AS01-IT06 HEAD NULL
AB07 AS01-IT07 HEAD NULL
AB08 AS01-IT08 HEAD NULL
AB09 AS01-IT09 NOSE NULL
AB10 AS01-IT10 NOSE NULL
when loading manually :
insert into Engineanalysis select 'AB11','AS01-IT11','AIRFRAME','',0;
Result:
AB11 AS01-IT11 AIRFRAME false
can someone explain why this dissimilarity?
Boolean type needs literals representation. SQL standard defines only three values for boolean: TRUE, FALSE, and UNKNOWN(=NULL in Hive). Using integers is not standardized in SQL, though many databases supports them.
You are using LazySimpleSerDe for deserealizing table data.
LazySimpleSerDe uses this property hive.lazysimple.extended_boolean_literal to determine if it treats 'T', 't', 'F', 'f', '1', and '0' as extended, legal boolean literals, in addition to 'TRUE' and 'FALSE'. The default is false, which means only 'TRUE' and 'FALSE' are treated as legal boolean literals.
Set this property to be able to read CSV files with 1 and 0 as Booleans:
hive.lazysimple.extended_boolean_literal=true;
See this Jira HIVE-3635 Try also to set this property in the table DDL:
TBLPROPERTIES ("hive.lazysimple.extended_boolean_literal"="true")
About using other than TRUE or FALSE boolean literals in Hive query language official documentation says implicit conversion of other types to Boolean is not possible: AllowedImplicitConversions though as you can see it works.
Few tests with casting strings and integers to boolean:
hive> select cast('' as boolean);
OK
false
Time taken: 8.642 seconds, Fetched: 1 row(s)
hive> select cast('1' as boolean);
OK
true
Time taken: 4.773 seconds, Fetched: 1 row(s)
hive> select cast('f' as boolean);
OK
true
Time taken: 8.548 seconds, Fetched: 1 row(s)
hive> select cast('0' as boolean);
OK
true
Time taken: 0.851 seconds, Fetched: 1 row(s)
hive> select cast(0 as boolean);
OK
false
Time taken: 1.713 seconds, Fetched: 1 row(s)
hive> select cast(1 as boolean);
OK
true
Time taken: 4.604 seconds, Fetched: 1 row(s)
Also have a look at this Jira: HIVE-3604 and Type Conversion Functions documentation, it says: If cast(expr as boolean) Hive returns true for a non-empty string. And actually this conforms with UDFToBoolean source code.
So, better use officially allowed literals for Boolean type to make sure you have no side effects also described in this article: Hive: Booleans Are Too Confusing To Be Usable
hi @leftjin , thanks for the clear explanation. it works for me.
| common-pile/stackexchange_filtered |
Hibernate @GeneratedValue(name=???): ID gets incremented by five not by one
I am using Hibernate 4 orm and search for my twitter application. The problem is when I start persisting tweets into MariaDB table, id (primary key) gets incremented by five fold:
2
7
12
17
22
27
I tried all Generation Types which are available : SEQUENCE, IDENTITY, TABLE and AUTO. But none of this provided increment by one. I guess I am missing some configuration, otherwise it should provide increment by one.
Here is my Entity class and hibernate.cfg.xml file:
@Entity
@Indexed
@Table(name="tweets_table")
public class TweetPOJO implements Serializable{
private static final long serialVersionUID = 1123211L;
@Id
@GeneratedValue (???)
@Column(name = "raw_id" )
private int raw_id;
@Column(name = "tweet_id")
private String tweet_id;
@DateBridge(resolution=Resolution.DAY)
@Column(name = "posted_time")
private String timestamp;
@Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
@Column(name = "cleaned_text")
private String tweet_text;
@Column(name = "hashtags")
@Field(index=Index.YES, analyze=Analyze.NO, store=Store.YES)
private String hashtags;
@Column(name = "media_url")
private String media_url;
@Column(name = "media_text")
private String media_text;
@Column(name = "media_type")
private String media_type;
@Column(name = "location")
private String location;
...
...
public void setUser_frind_count(int user_frind_count) {
this.user_frind_count = user_frind_count;
}
@Override
public String toString() {
return tweet_id+" : "+tweet_text;
}
}
Here is hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer"> true </property>
<property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property>
<property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url"> jdbc:mysql://*******/clouddata </property>
<property name="hibernate.connection.username"> root </property>
<property name="hibernate.connection.password"> qwe123 </property>
<property name="connection.pool_size"> 1 </property>
<property name="hibernate.search.default.directory_provider"> filesystem </property>
<property name="hibernate.search.default.indexBase"> E:\lucene_index </property>
<!--
whether the schema will be created or just updated, every time the sessionFactory is created.
This is configured in the hibernate.hbm2ddl.auto property, which is set to update. So the schema
is only updated. If this property is set to create, then every time we run our application, the
schema will be re-created, thus deleting previous data.
-->
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="twitter_crawling_modul.TweetPOJO"/>
</session-factory>
The code which actually manipulates the object is missing, and is most likely the culprit: This usually happens when you update an object a few times before persisting it, have some exceptions caught, etc.. It is not a problem for the table (keys don't have to be continuous and in a 64 bit key space it takes a while to run out of it even if you skip a bunch). It might be a serious problem in your code though.
SHOW VARIABLES LIKE 'auto_inc%';
@NorbertvanNobelen How can I fix this problem? Can you give some suggestion?
You can try to use sequence generator
@SequenceGenerator(name = "seq", sequenceName = "seq_name", allocationSize = 1)
@GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "seq")
| common-pile/stackexchange_filtered |
How to install a package from within my application?
Possible Duplicate:
Install a ‘recommended’ package when user asks for corresponding action
I am a developer and for my application i require some packages to be installed.
So when for example the user tries to activate a feature of the programm (that requires a package ), i want to popup a messagebox asking that he needs that package in order to activate the feature..
Yes install "package name" / Cancel
So when he hits yes popup this dialog and install the packages:
Is there a way to do that? A certain command or something?
So you don't want your program to download all its dependencies at install time, only when the user reaches certain feature?
You can download synaptic source code to see how it is implemented in synaptic
@ThiagoPonte Yep exactly, when he activates a certain feature. My way of doing this until now, was to direct the user to the Ubuntu's software center page and from there he installed it. But it's kinda ugly that way...
@Tachyons and in which cc file will i see how it is implemented in synaptic? I downloaded the source, but in the common folder there are about 15 cc files..
| common-pile/stackexchange_filtered |
Debian 10 not in grub menu
I was rebooting my computer because it was being really slow. On boot, the GRUB menu wasn't showing my installation. only windows. (also my windows installation got messed up awhile ago, so I can't use that) Maybe a drive died, maybe I need to reinstall grub, but I don't know how I can access the command line if I can't even boot into linux.
Tell me if you need more info!
we need for you to tell us what is your question, so that someone here can answer it
My question is simply is there any way to get my PC to boot
think .... how do you boot linux on a PC that does not have linux installed?
Linux is installed, or, as it seems, it was until a few hours ago. (or maybe grub is just not showing it)
that's irrelevant to what i said
oh. yea I didn't think about that. Well I said in my question "but I don't know how I can access the command line if I can't even boot into linux." so what I was saying is I don't think my computer randomly decided to delete linux. I feel it's a hardware thing.
Can you boot recovery mode from grub menu? Lets see details, use ppa version with your live installer (2nd option) or any working install, not older Boot-Repair ISO:
Please copy & paste the pastebin link to the Boot-info summary report ( do not post report), do not run the auto fix till reviewed.
https://help.ubuntu.com/community/Boot-Repair
ok. I cannot boot recovery mode because linux isn't even in the grub menu. it disappeared. I'll try this boot repair thing tmr because it's getting kinda late. I'll update once I try.
Note that during this weekend, the BootHole vulnerability was published and patches for it were released, likely triggering an automatic bootloader re-installation attempt on UEFI systems. If your system boots with UEFI and needs special configuration steps (e.g. you're removed all the default Secure Boot keys and replaced them with your own), such an update may have caused this problem.
| common-pile/stackexchange_filtered |
Office 2010 and VBA show different font sizes
I have a powerpoint template created in Office 2003. When I opened the SlideMaster of the template in Office 2010, I saw that the font sizes of bulleted body are 24, 22, 20, 18, 16 for level 1, level 2, level 3, level 4, level 5 respectively. The strange thing is that when I used VBA to loop through all bulleted text, I noticed that the font sizes for bulleted text are 32, 28, 24, 20, 20 which are quite different compared to the ones viewed in the app.
If I open the template in Office 2003, PowerPoint and VBA show the same result: 32, 28, 24, 20, 20.
I'm wondering why in Office 2010 there is the difference between the app and VBA (Please see attachment)
Thank you very much for your help.
Masters and such are quite different in 2007/2010 from the way they worked in earlier versions. After opening the older format file in 2010, ignore the slide master at the top and look at the second layout (the ones that are indented under the main master). How does that compare with the original presentation?
| common-pile/stackexchange_filtered |
How do I rebind jQuery DataTable when the table is auto refreshed by background process
I have a table that I build with data coming from MySQL via PHP code and binding it to DataTable, the table and DataTable work just fine, but I have added a delete button for the table row, when I click that it calls a backend PHP which deletes the record than I am calling a new PHP to query the DB and build a new table and push it back onto the page, all works fine, EXCEPT that when the new query is formatted and pushed onto the age the dataTable is not binding at all, here is my Script.
Thanks
function aa_userDeleteSkill(in_id, in_uid) {
$.ajax( {
url: "user_delete_skill.php",
type: "get", //send it through get method
data: {
id: in_id,
uid: in_uid
},
success: function (response) {
console.log( "success -- delete: " + response );
// cleanup
if ( $.fn.DataTable.isDataTable( '#SkillsUser' ) ) {
$('#SkillsUser').DataTable().destroy();
}
$('#SkillsUser tbody').empty();
// call the rendering function
aa_userSkillRender( in_uid );
jQuery('#SkillsUser').dataTable({
"pageLength": 10,
"ordering": false,
"responsive": true,
"destroy": true,
drawCallback: function(dt) {
//console.log("draw() callback; initializing Select2's.");
//$('.experience-jquerySelect2-tag').select2({tags: true, width: "6em"});
}
});
},
error: function (xhr) {
console.log( "failed -- delete: " + xhr );
}
} );
} // end of fucntion
function aa_userSkillRender( uid ) {
// The following will prevent all future AJAX requests from being cached,
// regardless of which jQuery method you use ($.get, $.ajax, etc.)
$.ajaxSetup({
cache: false
});
// call the backend service
$("#IDuserListSkills").load("./user_render_skill.php?id=" + uid + " #IDuserListSkillsReturned",
function (responseTxt, statusTxt, xhr) {
console.log("responseTxt: " + responseTxt);
if (statusTxt == "success") {
console.log("user_render_skill.php: External content loaded successfully!");
}
if (statusTxt == "error") {
console.log("user_render_skill.php -- Error: " + xhr.status + ": " + xhr.statusText);
}
}
);
} // end of fucntion
Things would have been much simpler if you used DataTables option ajax rather than reinventing that feature yourself.
thanks for the tip, I wish the table data was that simple, however during the PHP operation, I am adding new first column where there is a delete icon, then I am adding javascrip:xxxxxx notation to that cell with a specific UID and reference_id so the delete operation can work, later on I have to add code to generate unique cell ID for each cell etc... the JSON_OBJECT MySQL and ajax feature of dataTable would have worked if I was not adding these other extra stuff to each row.
Above features can be achieved easily with DataTables options and API methods (moreover, I have posted on SO code snippets for that). Furthermore, I'm pretty sure some of those you don't even need to do to implement features you do this for.
U25lYWt5IEJhc3RhcmQg can you provide a link to the code snippets please?
If you have time and will to rebuild your app you may post separate questions to address one issue at a time and I'll be glad to answer them one by one. Otherwise, you may browse through the answers I have posted up until now and find many solutions to the problems similar to yours.
I solved my problem, my issue was I was treating the ajax and jquery.load() calls as synchronous operation and calling them in sequence, once I placed my coeds inside the call-back functions, all worked fine.
As being said ajax option would solve your issue. The fact that you've found the workaround this time doesn't mean you solved the root cause of the issue. With that you may progress to the point where you'll need some feature or big fix that'll require API methods which will not work properly in such app structure.
To see how overcomplicated your approach is, just think of such thing - in order to delete your row from both server side storage and current view it is not even necessary to load your entire dataset (without deleted line) destroy your table, and rebuild everything from scratch. You could have simply drop that line from your current view upon successful AJAX-call or, if it is really that important to refresh your table at this exact moment, invoke .ajax.reload() without destroying everything.
| common-pile/stackexchange_filtered |
Calling one R Installation from Another
I seem to be unable to compile RPostgreSQL for Windows x64, and after extensive searching, I've not been able to find a precompiled binary. To get on with my work, I've installed a 32 bit version of Postgre and have been using 32 bit R for all database ops.
I need to do much of my work in 64 bit R, so switching back and forth has become a bit painful, especially since this requires a save() and load() operation each time I need to run a query.
I'm wondering whether it is possible to call one R installation directly from another? For example, could I simply pass queries to my 32 bit R installation and retrieve the result? I think there are other times when the ability to call another R installation would be useful as well.
All I've come up with is using a system() call, either directly to pgsql or to 32-bit R, but this doesn't allow for very efficient transfer of data.
I'd very sincerely appreciate any advice or assistance!
P.S. I'd rather ask how to compile RPostgreSQL for x64, but as I understand the rules here, such a question would be inappropriate since it's not a general question (e.g. I'd need step-by-step instructions since I don't have the requisite skills).
Speaking as one of several people contributing to RPostgreSQL, we could do with a knowledgeable person dealing with Windows, 32 and 64. But yes, you may have to build PostgreSQL first.
Thanks Dirk, for RPostgreSQL and for the many other contributions you've made - they are deeply appreciated. As for compiling, the process can be very mysterious to those of us who live in interpreted languages!
see comment here: http://cran.r-project.org/bin/windows/contrib/r-release/ReadMe so install.packages('RPostgreSQL', type='source') might just work if you are set up to build R packages from source and your DB is available
Thanks mdsummer. I was finally able to install from source successfully by following those directions. Now I can load RPostgreSQL and get a db driver with dbDriver(), but R crashes whenever I try to create a connection with dbConnect(). Since it seems to compile correctly, I'm pretty much at a loss.
http://wiki.postgresql.org/wiki/64bit_Windows_port
| common-pile/stackexchange_filtered |
Finding details about an immigration from England to New Zealand / Australia
Here is a Immigration Certificate:
According to the source it says:
Departure Date: May 1919
Departure Port: England
Ship Name: Prinzessin
Destination Port: Auckland, New Zealand
I have several questions and I do not know how to go about finding answers:
Can we find the paperwork showing the date of the sailing (May 1919)?
Can we find anything out about this Prinzessin vessel?
I know that Ethel Nellie Eichler (nee Scammell) died in 1984 in Victoria, Australia. So how do we go about finding her immigration from New Zealand to Australia?
New Zealand
Australia
I think you should ask three separate questions. You can always put the background into first one and then link to that as background for subsequent questions.
Do you know for sure that Ethel Nellie Eichler resided in Australia at the time of her death, or is that merely where she happened to be when she died? Sometimes people die away from home.
@shoover The gravestone refers to her deceased sons and they too died in the Victory area; in-fact one of them was in the same cemetery as her.
Have you looked at other images for that filmstrip? Your first attempt should be to look at image 1 or thereabouts. If that doesn't help, then looking at adjacent pages of the original, working outwards should be next. I can see that there is a slot for Sailing Date but it's empty. Bear in mind that clerks would get bored writing the same stuff many times so might omit the date. I'd guess that the ship name is there to convey to people that it's the same voyage and you should interpret everything as having the same date - if you can find one.
@AdrianB38 I scoured the whole document which has multiple collations of lists. The cards in question sporadically change from date to date.
Re Ships:-
I have several URLs - this one appears to be fruitful:
"Books, boxes and Boats", which includes an option CLIP Vessel Data by Ship Name
If you search for ships starting with "Prinze" (to allow for misspellings), that brings up just one ship - Prinzessin. Selecting that gives us important information like the Official Number 143077, and basic details. The last line of details refers to the ML (Merchant Navy List) of 1920 which shows 143077 Prinzessin to have been registered at London 1919 and built at Hamburg in 1905. It appears to belong to the Union Castle line of London (column headings are visible on the previous page - page number is near to the top right). Nett tonnage 3697, gross 6387, engine horsepower 622.
Near the top left is Year - if you click on the down arrow, you see the 1919 entries for the MNL, with no Prinzessin. This suggests one possibility to be explored - that Prinzessin was handed over to the Allies at the end of WW1 as reparations.
Quite often, it then makes sense to search details of the shipping line - Union Castle's ships are accessible (sort of) from Union Castle Mail Steamship Co Register and the WW1 Managed Ships section has an entry for the Prinzessin. This entry includes a photo and the data that the ship was managed from 1921 as the French ship General Voyron. Learning point: things like the Merchant Navy List are British documents and while removal from the register may mean it's sunk or dismantled, it may also mean that it's been sold out of British service - where British probably includes British Empire.
The General Voyron name is more amenable to searching and turns up this Wikimedia link:
Category:Prinzessin (ship, 1906)
That confirms Prinzessin was seized as war reparations and indicates that she was built as Prinzessin for the Deutsche Ost-Afrika Linie, Hamburg. Whether there is much more data available, I don't know - searching for Prinzessin gives way too many answers as the word simply means Princess and even restricting it to ships doesn't help because the earlier Prinzessin Victoria Luise is regarded as the first cruise liner so has a lot of internet entries.
This answer is a stub and may be fleshed out later.
Can we find the paperwork showing the date of the sailing (May 1919)?
May 1919 is within the date range of Outward Passenger lists we can search online (BT 27, 1890-1960). See TNA's Discovery and the other research guides listed below.
Research Guides:
TNA Research Guides: All guides
TNA Research Guides: Emigration and Emigrants
TNA Research Guide: Passenger Lists
GenGuideUK: Emigration Records
GenGuideUK: New Zealand Emigration
GenGuideUK: Passenger Lists
Outward Passenger Lists:
at Findmypast: Passenger Lists Leaving UK 1890-1960
at Ancestry: UK and Ireland, Outward Passenger Lists, 1890-1960
Researching the ship
There are several Qs on GenealogySE about researching ships already. Several of the questions tagged ship are probably misleading because they are more about the individual passenger, but looking at the tag is a way to get started. Even though the questions may not be asking about ships sailing to New Zealand or Australia, or during the same time period as your question, you can use the answers as clues to what records might exist and to see the methodology used. If this is not enough to get you started on answering the question yourself, please ask a new question and say what information you would like to find, what research you have done so far, and in what way the information in the prior questions didn't help you.
Information on a ship called the "Bancroft"
Finding information on Emigration ships (UK to US) in 1841
Looking at the Military papers of Edith's husband it looks like I accidentally stumbled upon the answer!!!!
To quote:
16.5.19, Returned per S.S "PRINZESSIN" London
So, we now know that:
The date of the voyage was 16th May, 1919.
Edith was on the same ship as her husband August Eichler.
| common-pile/stackexchange_filtered |
How to display selective items in a binding list in grid control
I have implemented below code:
gridControl.DataSource = CusColumnList
CusColumnList is of type MyBindingList which inherits BindingList, in my case T is class MyColumn. The binding works well.
But now my problem comes, I don't want the data source to bind to every column in CusColumnList, I only want it binds to column whose name contains "ABC" or whose display name contains "XYZ". I tried to set
gridControl.DataSource = CusColumnList.Where(column => column.Name.Contains("ABC") || column.DisplayName.Contains("XYZ"));
But seems it does not work.
I also tried to create another bindinglist collection MyTempCusColumnList of type MyBindingList, and in the Get method of this MyTempCusColumnList, I just return every item in CusColumnList where the name or display name qualifies. But in this way, every time when CusColumnList is updated, I need to manually update MyTempCusColumnList.
I wonder whether there is a better way to archive this goal with just CusColumnList.
Thanks!
Edit : format code
You could use a filter string on a BindingSource object.
Check out the MSDN documentation on it, it's quite good: http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.filter(v=vs.100).aspx
| common-pile/stackexchange_filtered |
How to determine if day light saving is in effect for a given date and TimeZone using Javascript?
Is there any library for JavaScript which I can use to check if the day light saving is in effect for a specific time in a specific location.
For example, I would like to know for a date, say "July 1 05:30:00 UTC+0500 2009" in the time zone code, for example 110, if the day light saving is in effect. Additional information is always acceptable.
The time zone codes can be found here - http://msdn.microsoft.com/en-us/library/bb887715.aspx
Thanks for your help in advance.
Greets!
Check out this post: http://stackoverflow.com/questions/11887934/check-if-daylight-saving-time-is-in-effect-and-if-it-is-for-how-many-hours
Thanks for answering. The problem in my case is fairly simple. The time zone of the server is different from the place where I am trying to access it. I need to know if the place where the server is located has day light saving in effect for a given time. Thanks again.
Is there some reason you are using MS Dynamics CRM time zone codes? If so, why do you need a javascript answer??
You may also want to read this question about how to obtain a regular TimeZoneInfo identifier from a CRM time zone code. But still, you should do all that in .net, not in javascript.
Thanks for trying to help me. I am reading the meta data from CRM into my Javascript. The big problem - all I have is only the Time zone code. I simply need to know for a given time, if the daylight saving is in effect for the time zone from CRM. and yes, I have to do this in Javascript. Thanks again.
Javascript doesn't know anything about CRM time zone codes.
There aren't even any good libraries for JavaScript that can work with Windows time zone identifiers, like the ones you'd find when using TimeZoneInfo from .NET, or browsing through your Windows registry.
If you need to work with time zones in JavaScript, you'll need to convert to an IANA/Olson time zone identifier, and then use one of the libraries I mentioned here.
If you can work in .NET on the server, you could use this method to convert from a CRM Time Zone Id to a Windows Time Zone Id. You could then use this method to convert from Windows to IANA time zones. But if you're going to do that much work on the server anyway, I don't see why you wouldn't just do your data conversions there also.
If you're looking for a pure JavaScript solution that will work directly from the CRM time zone IDs, I'm sorry but as far as I know, that doesn't exist. You'd have to build it yourself and maintain it as timezone data changes.
This will return true or false when given a timezone as input:
function stdTimezoneOffset() {
var d = new Date();
var jan = new Date(d.getFullYear(), 0, 1);
var jul = new Date(d.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
function dst(offset) {
var d = new Date(); // create Date object for the current location
var utc = d.getTime() + (d.getTimezoneOffset() * 60000); // get UTC time in milliseconds
var nd = new Date(utc + (3600000 * offset)); // Create net Date() for city with offset
return d.getTimezoneOffset() < stdTimezoneOffset();
}
alert(dst('-5.0')); //New York
This is flawed. You are making two common mistakes. 1) you can't identify a time zone from its offset alone. -5.0 is not just for New York. 2) DST works differently all over the world. The best that this code would do is use your own local time zone's idea of DST and erroneously apply it elsewhere. You should read the "timezone != offset" section of the timezone tag wiki and also the dst tag wiki.
| common-pile/stackexchange_filtered |
Make multiple splits in CSS grid
I was wondering if it was possible to use CSS grids to do intermediate splits in columns, is this doable? Below a graphical example.
Thank you very much.
EDIT: I am using display: grid, what I am trying to achieve is something responsive that would put each cell under each other on a mobile device.
Yes, everything is possible. E.g. Column 1/Row 3 can span 2 rows. About what kind of css grid you are talking? display: grid/bootstrap grid/table grid...?
I am using display: grid, I will edit the question to explain what I want to achieve.
I just created the example you need but try to make sure that you assign proper names (instead of col-x or row-y) like navigation or sidebar for example.
I'd recommend to just double the amount of rows and assign the amount of rows twice for the left column. Especially take a look at grid-template-areas in the .grid CSS.
To change the way the grid looks on smaller devices you can apply @media queries on the .grid class to adjust the grid-* attributes.
This sample below is not the shortest nor the smartest solution for that but it's the most visual i guess.
.grid {
height: 200px;
display: grid;
grid-template-columns: 80% auto;
grid-template-rows: repeat(6, 1fr);
grid-template-areas:
"col-1-row-1 col-2-row-1-1"
"col-1-row-1 col-2-row-1-2"
"col-1-row-2 col-2-row-2-1"
"col-1-row-2 col-2-row-2-2"
"col-1-row-3 col-2-row-3-1"
"col-1-row-3 col-2-row-3-2"
}
.col-1-row-1,
.col-1-row-2,
.col-1-row-3,
.col-2-row-1-1,
.col-2-row-1-2,
.col-2-row-2-1,
.col-2-row-2-2,
.col-2-row-3-1,
.col-2-row-3-2 {
justify-self: center;
align-self: center;
}
.col-1-row-1 {
grid-area: col-1-row-1;
}
.col-1-row-2 {
grid-area: col-1-row-2;
}
.col-1-row-3 {
grid-area: col-1-row-3;
}
.col-2-row-1-1 {
grid-area: col-2-row-1-1;
}
.col-2-row-1-2 {
grid-area: col-2-row-1-2;
}
.col-2-row-2-1 {
grid-area: col-2-row-2-1;
}
.col-2-row-2-2 {
grid-area: col-2-row-2-2;
}
.col-2-row-3-1 {
grid-area: col-2-row-3-1;
}
.col-2-row-3-2 {
grid-area: col-2-row-3-2;
}
<div class="grid">
<div class="col-1-row-1">Col 1 Row 1</div>
<div class="col-1-row-2">Col 1 Row 2</div>
<div class="col-1-row-3">Col 1 Row 3</div>
<div class="col-2-row-1-1">Col 2 Row 1.1</div>
<div class="col-2-row-1-2">Col 2 Row 1.2</div>
<div class="col-2-row-2-1">Col 2 Row 2.1</div>
<div class="col-2-row-2-2">Col 2 Row 2.2</div>
<div class="col-2-row-3-1">Col 2 Row 3.1</div>
<div class="col-2-row-3-2">Col 2 Row 3.2</div>
</div>
You can just set a new html element below (for example) column2/row1 and set the style as display: grid; grid-template: auto/auto; align-self: center
| common-pile/stackexchange_filtered |
Changing color of specific tab of top menu in wordpress
I am using wordpress. I am messed up with a problem and still i am unable to find it's solution. I am trying to change color of only 1 tab in whole navigation menu !
I mean if my navigation bar include 5 tabs and i want to highlight one tab with a specific background color. But i don't have any idea to do this. Can you suggest some solution to this ? ! Thanks in advance .......
Regards,
Normally you can do this editing the css in wps stylesheet editor; I don't know what to change as that depends on the theme you are using -- you should get started searching the wordpress-forums: http://en.forums.wordpress.com/
When you create a menu in wordpress it will assign it an id and a class, like this:
<li id="menu-item-1704" class="menu-item menu-item-type-post_type menu-item-1704"><a href="http://localhost/?page_id=118">Home</a></li>
Each "menu-item" will always have a unique id number.
So then you need to add this to your css and only that particular menu item will be changed:
#menu-item-1704{background:red;}
| common-pile/stackexchange_filtered |
How to create a new function from a method, with fewer arguments?
I have two classes, ClassA and ClassB.
ClassA has three methods:
double Foo(double, ClassB);
double Bar(double (*f)(double));
double Baz(double, ClassB);
I would like to define a function Qux inside Foo, based on Baz but without the argument of type ClassB: i.e. of the kind "double Qux(double)" so that I can pass it to Bar:
double ClassA::Foo(double x, ClassB y)
{
// double Qux(double .) = Baz(., y)
Bar((*Qux))
}
Does some one have any idea?
I guess some will answer this is not the good way to do it. So just to explain the concrete situation, I am pricing financial assets using a numerical method (http://en.wikipedia.org/wiki/Simpson%27s_rule) in order to compute integrals:
ClassA: FinancialAsset
ClassB: PrincingModel
Foo: FinancialAsset.Price(date, PrincingModel)
Bar: FinancialAsset.SimpsonMethod(FunctionOneArgument)
Baz: FinancialAsset.FunctionTwoArguments(date, PrincingModel)
And I am looking for:
Qux: FunctionOneArgument(date) = FinancialAsset.FunctionTwoArguments(date, PrincingModel)
I am not sure what is the good way to address this structure. I you have a better / more c++'s way to do it, I'll take :)
Thanks
I guess you want to use lambda functions and partial applications. Depending on the version of C++ you are using, we might have different solutions.
You can't do that exactly, because your Bar function is taking a pointer to a regular function, but you can use this instead:
class A {
...
public:
double Foo(double, ClassB);
double Bar(std::function<double(double)> f);
double Baz(double, ClassB);
};
double ClassA::Foo(double x, ClassB y)
{
auto Qux = [&](double x) { Baz(x,y); };
return Bar(Qux);
}
std::function is a more general way of representing function-like objects. You can convert a regular function, a lambda, or a function object to it.
This won't compile since the capture [] is empty. Write [&] instead.
I can see a lambda there, but what is the "double Qux(double .) = Baz(., y)" thing there called?
@Losiowaty: That was left over from the original code. I've removed it now.
Ok, thanks. I thought it was something necessary though it seemed extremely non-C++'ish.
Yes sorry I forgot to comment it //
Depending on whether you have C++11 or not, you either want std::bind and std::function or boost::bind and boost::function for older C++ versions.
binding allows you to take a function and bind 0 or more of the parameters, or rearrange the parameters. Indeed something you have above would look like this:
double ClassA::Foo(double x, ClassB y)
{
boost::function<double> baz = boost::bind(this, ClassA::Baz, _1, y);
Bar(baz);
}
And Bar's signature would take a boost::function instead of a function pointer.
Note my syntax might be slightly off for binding memeber functions, have a look at the documentation for details.
see here:
http://www.boost.org/doc/libs/1_53_0/libs/bind/bind.html
Or here: http://en.cppreference.com/w/cpp/utility/functional/bind
You can do it without changing any function signatures (and C++11 or boost), but I wouldn't suggest it if you can avoid it. It's ugly, not thread-safe, and in general not very nice:
#include <iostream>
struct B
{
// some data in B
int i;
};
struct A
{
//some data in A
double d;
// the functions you defined in A
double Foo(double x, B y);
double Bar(double (*f)(double));
double Baz(double x, B y);
};
// a poor substitutes for closures
struct
{
A *a;
B *b;
} hack;
double Qux(double x2)
{
// use the stored pointer to call Baz on x2
return hack.a->Baz(x2, *hack.b);
}
double A::Foo(double x, B y)
{
// store pointers for use in Qux
hack.a = this;
hack.b = &y;
// do something with x
d += x;
double result = Bar(&Qux);
return result;
}
double A::Bar(double (*f)(double))
{
// do something with d, call the passed function
d += 1;
return f(d);
}
double A::Baz(double x, B y)
{
// do something with the passed data
return x + y.i;
}
int main()
{
A a;
a.d = 1.25;
B b;
b.i = 2;
std::cout << a.Foo(.25, b) << std::endl; // should be 4.5
return 0;
}
| common-pile/stackexchange_filtered |
How to install two versions of MySQL on MacOS (High Sierra)?
I need two separate development environments in MacOS 10.13 to accommodate clients running different versions of MySQL on their servers (5.5 and 5.7.22). I've installed MySQL 5.7.22 from a package, but need to install a different environment and binary for 5.5 which won't conflict with the other.
There was once a way to accomplish this with Homebrew, but in 1.6.8 permitting separate /version directories seems to have been deprecated (?)
Read over https://gist.github.com/benlinton/d24471729ed6c2ace731 maybe a starting point... not sure though but read and keep digging otherwise.
| common-pile/stackexchange_filtered |
Send active workbook by e-mail but changing the name
So at the moment I have a workbook that gets sent to e-mail when pressing a button, but I want to change the name of the file when e-mailing it, how can I do this?
What I have right now is this code that just sends the file with the name of the current workbook, but I want to make it send it with the username of the person who sent the e-mail too by adding Environ("UserName") to it
With OutMail
.to = "email1<EMAIL_ADDRESS> .Subject = "Your Answers " & Environ("Username")
.Body = "Your answers are here"
.Attachments.Add ActiveWorkbook.Name
.Send
End With
You must change the (active) workbook name before attaching it. Using SaveAs...
Try this approach, please. You have to change the workbook name before attaching it...
Dim fName As String
fName = ActiveWorkbook.Path & "\" & Environ("Username")
ActiveWorkbook.SaveAs fileName:=fName, FileFormat:=xlWorkbookDefault
With OutMail
.to = "email1<EMAIL_ADDRESS> .Subject = "Your Answers " & Environ("Username")
.Body = "Your answers are here"
.Attachments.Add ActiveWorkbook.Name
.Send
End With
| common-pile/stackexchange_filtered |
VBA Dynamic Range Vlookup Defined Name
world! Well, this is my first time in here, so dont be angry if I did something wrong.
I need to populate a ComboBox RowSource based on another Combobox value.
Userform with combobox
In my project there are two ComboBox that are dependent: Laboratorie and Test
They initialize with rowsources made in Defined Name with respectly all laboratories (TodosLaboratorios) and all tests (TodasAmostragens)
I have 464 lab tests and 5 laboratories. Not all laboratories can do all types of tests.
Exemple:
TEST | LABORATORIE
álcool benzilio | ALAC
n-Butano (vide álcoo n-butílico) | ALAC, ENVIRON
Clorobenzeno | ALAC, ENVIRON, SOLUTECH
I have lists in Defined Names with all tests done by an expecific lab, so if I choose a lab at my first ComboBox the other ComboBox RowSource is populated with the expecific lab tests list.
Private Sub labb1_Change()
If labb1.Value = "" Then labb1.RowSource = "todoslaboratorios"
If labb1.Value = "ALAC" Then lab1.RowSource = "labALAC"
If labb1.Value = "ENVIRON" Then lab1.RowSource = "labENVIRON"
If labb1.Value = "FIRJAN" Then lab1.RowSource = "labFIRJAN"
If labb1.Value = "SOLUTECH" Then lab1.RowSource = "labSOLUTECH"
If labb1.Value = "UNIANALISYS" Then lab1.RowSource = "labUNIANALISYS"
End Sub
I'm trying to do the inverse, as I choose an expecific test, I want to the ComboBox of laboratories be populated only with the labs that can do that test.
I have a sheet with all the labs, tests and their prices. I organized the tests/lab in this way:
tests and labs
I didn't figured out how to do a defined name dynamic range with a dynamic reference... I tried things like:
=index($t3$, match($t$1, todasamostragens, 0),
offset($t$3,match($t$1, todasamostragens, 0),0,0,5)
Am I in the right way? Can anyone help me achive my goal?
All respect for the programmers here.
I managed to solve my problem with a different approach.
I ordered the tests in one line and placed the laboratories in each column of the specific test.
Then I used .find to search that range and create an defined name.
For the tests ComboBox:
Private Sub Amostragens()
Dim teste As Variant
Dim linharange As range
Dim colunarange As range
'Dim Lrow As Long
Dim range As range
Dim rangeD As range
Set range = Worksheets("lab").range("t3:ro3")
If lab1.Value = "" Then
labb1.RowSource = "todoslaboratorios"
Exit Sub
End If
If lab1.Value <> "" Then
With range
If .Find(what:=lab1.Value) <> "" Then
Set linharange = range.Find(what:=lab1.Value).Offset(2, 0)
' Lrow = Cells.Find(what:="*", _
' AFTER:=range(linharange.Address()), _
' searchorder:=xlPrevious, _
' searchdirection:=xlNext, _
' MatchCase:=False).Row
Set colunarange = range.Find(what:=lab1.Value).Offset(6, 0)
Set rangeD = .range(linharange.Offset(-2, -19), colunarange.Offset(-2, -19))
rangeD.Name = "AmostragensLab"
End If
End With
labb1.RowSource = "AmostragensLab"
End If
End Sub
For the lab ComboBox:
Private Sub Laboratorios()
If lab1.Value = "" Then
If labb1.Value = "" Then labb1.RowSource = "todoslaboratorios"
If labb1.Value = "ALAC" Then lab1.RowSource = "labALAC"
If labb1.Value = "ENVIRON" Then lab1.RowSource = "labENVIRON"
If labb1.Value = "FIRJAN" Then lab1.RowSource = "labFIRJAN"
If labb1.Value = "SOLUTECH" Then lab1.RowSource = "labSOLUTECH"
If labb1.Value = "UNIANALISYS" Then lab1.RowSource = "labUNIANALISYS"
Exit Sub
End If
If lab1.Value <> "" Then
Exit Sub
End If
End Sub
On change:
Private Sub labb1_Change()
Laboratorios
valorlab
End Sub
Private Sub lab1_change()
Amostragens
valorlab
End Sub
I'm learning VBA and I'll appreciate sugestions to improve this code.
| common-pile/stackexchange_filtered |
How can I get rid of repetition in the for loop
for line in file2.splitlines():
for l in file1.splitlines():
if line in l:
print l
How can i get rid of the repetition?
Umm, did you just re-ask the same question?
why would you post it twice?
To be fair, it is very unlikely that a question with no upvotes that is 15 hours old will get any new answers. However it would be nice if the first question had at least been deleted first.
Or it could be edited and improved to bring it back to the front of the list. Your code probably doesn't do what you want; when you read the first line in the outer loop, the inner loop reads all the data in file2; the next time through the loop, the inner loop does nothing (there are no lines left to read). You'll need to think again.
I apologize for the duplicate question, but l'm new in the forum and I have not experience in this before.I tried to delete the first one but it was difficult since it have answers.
If I understand correctly, you wan to print duplicates.
You can do it like this:
print [line for line in file2.splitlines() if line in file1.splitlines()]
But if you want to do it in a better way, use sets:
print list(file2.splitlines() & file1.splitlines())
Wouldn't the first snippet call file1.splitlines() on each iteration of line?
Creating a dictionary out of the lines in second file would be a faster solution and it will get rid of the duplicates too:
from collections import defaultdict
second_file = open('second.txt')
second_file_dict = defaultdict(int)
first_file_dict = defaultdict(int)
for line in second_file:
second_file_dict[line.strip()] += 1
second_file.close()
first_file = open('first.txt')
for line in first_file:
if line in second_file_dict and not in first_file_dict:
print line
first_file_dict[line.strip()] += 1
first_file.close()
I tried this, but no result
@5555555555 Do you get an error?
not error, but no result
@5555555555 Hope you are opening the two files in question? Updated my answer to that effect.
It works only if I use the for loop in the second_file_dict, but this makes repetition
| common-pile/stackexchange_filtered |
Questions on Pascal's Principle
I am aware that Pascal's principle says that if a pressure acts on an enclosed liquid, the pressure will be transmitted uniformly throughout the liquid.
Can Pascal's Principle be applied to a manometer? When you apply pressure on one end, would that pressure be transmitted uniformly to the other end? When measuring difference in pressure with the manometer, is Pascal's Principle used? I mean the liquid is not really enclosed?
Normally, we apply this principle in a hydraulic press, where there are pistons which enclose the liquid, in a manometer, do you take the substance exerting the pressure (eg. gas being pumped) as the 'piston'?
What does 'enclosed' actually mean? Liquid being covered on all sides with no air? Or being unable to flow freely?
How is pressure transmitted if the liquid is not enclosed?
(Eg.) A beaker.
The term enclosed is a little misleading. Look at the diagram below:
Both containers are of equal size and contain the same amounts of the same liquid. The left liquid is contained by a beaker and a weightless, frictionless piston, the right is contained by a beaker that is simply open to air. Both sit side by side on the surface of the Earth (and thus subject to gravity).
In both cases Pascal's Principle applies and the pressure in the liquids can be measured by means of a manometer.
If we assume the pressure of the surrounding air to be $p_0$ then in the right hand case the pressure in the liquid will only depend on the height $h$ due to the weight of the liquid column, according to:
$p=p_0+\rho gh$, with $\rho$ the density of the liquid and $g$ Earth's acceleration.
In the left hand liquid the situation is very similar but we have to take into account the extra pressure exerted by the piston, which is $p_p=\frac{F}{A}$ with $F$ the force applied to the piston and $A$ the surface area of the piston.
We then get:
$p=p_0+\frac{F}{A}+\rho gh$.
So for left and right $p$ would be the same if $F=0$, despite the right not looking particularly enclosed.
The meaning of 'enclosed' becomes more apparent when we drill a hole in either container and liquid is now free to flow out of it. At that point Pascal's Principle no longer holds exactly.
Pascal's Principle applies only to static situations, where liquid is not free to escape its container (enclosure, if you prefer). But that does not mean pressure could no longer be measured with a manometer, only that the measurement would no longer correspond exactly to Pascal's Principle.
In the case of common hydraulic devices like car lifts, springing a leak renders the device useless because it no longer obeys Pascal's Principle.
Hi, would the pressure acting on the sides of the left beaker be equal to the atmospheric pressure and and the pressure exerted by the piston? If we say pressure is transmitted uniformly?
@Cr4zyM4tt: yes, that is what $p=p_0+\frac{F}{A}+\rho gh$ means. But note that the pressure on the sides varies with $h$, so the deeper part experiences slightly higher pressure. Often in hydraulic devices (car lifts e.g.) the pressure applied by the piston is much higher than the $p_0+\rho mg$ part, in which case we can say: $p=\frac{F}{A}$, approximately.
Thanks, can I say that the external pressure throughout the sides are equal? Based on Pascal's Law
@Cr4zyM4tt: what we can say is that the forces that act on both sides of the wall that makes up the container (liquid/wall/air) are the same, otherwise the wall would move (Newton). On the outside the pressure $p_0$ acts inwards, on the inside $p$ acts outwards. But $p>p_0$ and the 'deficit' is made up by the strength of the container, otherwise the wall would move, i.e. break or rupture.
Thanks Gert, I think I am confused about Pascal's law saying that pressure is transmitted uniformly throughout the liquid, what bdoes this mean? Is it pressure experienced by an object anywhere in the liquid is uniform? For example, for the beaker, is the pressure exerted on the sides the pressure transmitted by the piston and air?
@Cr4zyM4tt: take the simple case where the force applied is quite high, so $\frac{F}{A}$ is high. Assume as an approximation that $\frac{F}{A} \gg p_0+\rho gh$, then $p \approx \frac{F}{A}$. This pressure would be measured (observed) anywhere in the liquid (on the walls included). Liquids are incompressible and transmit applied pressure to anywhere inside the enclosed liquid.
| common-pile/stackexchange_filtered |
django ImageField - 'NoneType' object
This is my file
forms.py
class RegisterForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField widget=forms.PasswordInput())
username = forms.CharField(max_length=15)
email = forms.CharField(max_length=25)
avatar = forms.ImageField(required=False)
class Meta:
model = User
fields = ('username', 'email', 'password', 'password2', 'avatar')
def clean_password2(self):
password = self.cleaned_data.get("password")
password2 = self.cleaned_data.get("password2")
if not password2:
raise forms.ValidationError("error")
if password != password2:
raise forms.ValidationError("error2.")
return self.cleaned_data
def clean_avatar(self):
image = self.cleaned_data['avatar']
if image.size > 1*1024:
raise forms.ValidationError("Image file too large ( > 1kb )")
return image
and
models.py
class User(AbstractBaseUser):
username = models.CharField(max_length=15, unique = True)
email = models.CharField(max_length=25, unique = True)
reg_date = models.DateTimeField(_('reg_date'), default=timezone.now)
user_rating = models.IntegerField(default='0')
avatar = models.ImageField(upload_to='avatars', blank=True)
register.html
<form class="form" action='/auth/register/' method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<div class="form-actions">
<button type="submit" class="btn btn-info">Reg</button>
</div>
</form>
and finally
views.py
def register(request):
context = RequestContext(request)
registered = False
if request.method == 'POST':
form = RegisterForm(data=request.POST)
if form.is_valid():
user = form.save()
user.set_password(user.password)
if 'avatar' in request.FILES:
user.avatar = request.FILES['avatar']
user.save()
registered = True
else:
print form.errors
else:
form = RegisterForm()
return render_to_response('loginsys/register.html', {'form': form, 'registered': registered}, context)
I got this error:
'NoneType' object has no attribute 'size'
Request Method: POST Request URL: xxxxx/auth/register/ Django Version: 1.6.2 Exception Type: AttributeError Exception Value:
'NoneType' object has no attribute 'size'
Exception Location: /home/max/xxxxx/loginsys/forms.py in clean_avatar, line 37
loginsys/forms.py in clean_avatar
37 if image.size > 1*1024:
...
▶ Local vars
Traceback Switch to copy-and-paste view
/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
...
▶ Local vars
/home/max/xxxxx/loginsys/views.py in register
if form.is_valid():
...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/forms/forms.py in is_valid
return self.is_bound and not bool(self.errors)
...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/forms/forms.py in errors
self.full_clean()
...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/forms/forms.py in full_clean
self._clean_fields()
...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/forms/forms.py in _clean_fields
value = getattr(self, 'clean_%s' % name)()
...
▶ Local vars
/home/max/xxxxx/loginsys/forms.py in clean_avatar
if image._size > 1*1024:
...
▶ Local vars
Why object is always 'NoneType'? If I remove the function "def clean_avatar(self)", the file has been successfully save.
You should possibly re-word this question with a description of what you're trying to do and what problem you're having, at the beginning. That's a lot of meaningless code for everyone to read through, with no way of really know what it is you're trying to do.
where are you calling the clean_avatar function? show the full traceback. also, note that you must use image._size.
I created a registration form and am trying to upload an avatar. Avatar is loaded and saved, but I want to check the size picture. When testing, I always get this error.
Mihai Zamfir, I added
1) You need to validate image field through form.
form = RegisterForm(data=request.POST, files=request.FILES)
2) You need to consider that the user didn't choose an image because the image field is not required. So, in the form clean you could test it:
if image and image.size > 1*1024:
I hope I´ve helped.
| common-pile/stackexchange_filtered |
Changing node version from node@16 to node@14 on Mac OS
I‘m using brew. As I need an older version of node I
installed node@14 (brew install node@14)
unlinked the recent version (brew unlink node)
linked the old version that I want (brew link node@14)
At the end it says
If you need to have this software first in your PATH instead consider running:
echo 'export PATH="/opt/homebrew/opt/node@14/bin:$PATH"' >> ~/.zshrc
so I ran that command and then I checked the node version (node --version) and it shows (v16.13.0) so nothing changed.
How can I fix this?
Have you tried a new Terminal window?
Modifying a shell configuration does not reload that configuration. Restart the shell, usually by opening a new terminal window. Further, unless you need both of them, why didn't you just uninstall the one you didn’t need?
I just opened a new terminal window and it worked :,) thank u
zsh caches paths it used to call a binary, so if you have run the node from that Terminal tab before it will still use v16. Run hash -r to remove all cached entries or open a new Terminal tab/window.
a new window solved it
| common-pile/stackexchange_filtered |
Center Text by using middle of character as baseline
Is it possible to update the baseline in a Compose Text component to center vertically with its pivot point as the center of the Character instead of the bottom. Usecase is for a Keyboard, each key should be Centered in its own box, but some characters look off centered
'b' is centered correctly but 'c' is not, looks offset to the bottom
Can you attach your code ?
I found a solution, although i do not see anyway to do this in Android Studio, i think it might not be possible. But a solution would be to use the font as a custom font, edit the fonts .ttf file, and center each glyph manually. As far as i see in Android Studio each glyph takes up more space than the letter itself and centers itself according to that glyph and its position in the glyph. When you use "Alignment.Center" you are centering the glyph not the letter itself
| common-pile/stackexchange_filtered |
Github - Why would HTTPS stop working while SSH works fine
With no changes on my system over a weekend, on Monday I was no longer able to pull from an organizations github repos; other github repos worked fine. This was the message I got:
$ git pull
remote: Repository not found.
fatal: repository 'https://github.com/myorg/repo2.git/' not found
Another befuddling thing is that the same repos in the org worked fine from the github web interface.
I googled for answers and followed the directions for adding a new ssh key to my github profile. I then tried this command and it passed; previous to adding the new key, it failed:
$ ssh -T<EMAIL_ADDRESS>
Since I could now pass the login test, but still could not pull the remote repo. I was forced to change the origin url to use ssh.
git remote set-url origin<EMAIL_ADDRESS># Change the 'origin' remote's URL
The updated url works now, but why is the https url broken?
I am using Ubuntu.
First, passing the ssh -T test means that you have to use an ssh url anyway. It doesn't solve anything regarding the https one.
Second, a repo "not found" doesn't always mean that the repo doesn't exist anymore, but that it isn't accessible by your account.
It is possible that the composition of the teams defined in the organization has changed, and that your account is no longer part of the team allowed to modified that repo (as opposed to declare an ssh key directly within that repo admin panel).
The ssh command is given in the github docs to test your access. The reason I note it here is that is shows I have access, first to github and second to the repo using ssh. The oddity here is that https still fails to work from the command line, but the web interface works as expected. I'm assuming the web interface uses http/https.
@Mondain the web interface should be able to display the exact url it uses, no?
I'm not aware of how to find out what they use internal to the their web app. The repo urls are however selectable on the page for clone operations.
@Mondain one way would be to revert to the command line, go to the root folder of the repo, and type "git remote -v"
That just shows the remote push/fetch urls, which I've already switched over to use ssh (noted in the question above).
| common-pile/stackexchange_filtered |
Why does PHP parse some floating point numbers as weird dates?
Today is 21 September. Why do the following floating point numbers get parsed as weird dates? I realise they're converted to strings first, then parsed, but the format doesn't seem to make any kind of sense. Are these following some format I'm not aware of, or are they undefined behaviour?
I don't see an applicable format on any of:
Time Formats
Date Formats
Compound Formats
Relative Formats
var_dump(new DateTime(5.123456));
class DateTime#1 (3) {
public $date =>
string(26) "3456-09-21 05:12:00.000000"
public $timezone_type =>
int(3)
public $timezone =>
string(3) "UTC"
}
5.123456
hour: 5
minute: 12
second: 0.0
year: 3456
month: now (9)
day: now (21)
var_dump(new DateTime(5.1203047891));
class DateTime#1 (3) {
public $date =>
string(26) "7891-09-21 05:12:00.000000"
public $timezone_type =>
int(3)
public $timezone =>
string(3) "UTC"
}
5.1203047891
hour: 5
minute: 12
second: 0.0
ignored: 0304
year: 7891
month: now (9)
day: now (21)
Some other strings:
'5': Failed to parse time string
'5.': Failed to parse time string
'5.1': 2019-09-21 05:01:00.000000 5:01 am, 2019-09-21 (today)
'5.12': 2019-09-21 05:12:00.000000 5:12 am, 2019-09-21 (today)
'5.123': Failed to parse time string
'5.1234': Failed to parse time string
'5.12345': Failed to parse time string
'5.123456': 3456-09-21 05:12:00.000000 5:12 am, 3456-09-21
'5.1234567': Failed to parse time string
'5.12345678': Failed to parse time string
'5.123456789': Failed to parse time string
'5.1234567891': 7891-09-21 05:12:00.000000 5:12 am, 7891-09-21
'5.12345678912': Failed to parse time string
'5.123456789123': Failed to parse time string
'5.1234567891234': 7891-08-22 05:12:00.000000 5:12 am, 7891-08-22
'5.12345678912345': Failed to parse time string
'5.123456789123456': Failed to parse time string
'5.1234567891234567': Failed to parse time string
'5.12345678912345678': 5678-08-22 05:12:00.000000 5:12 am, 5678-08-22
'5.123456789123456789': Failed to parse time string
'5.12345678901234567': 4567-05-03 05:12:00.000000 5:12 am, 4567-05-03
'5.12345678900014567': Failed to parse time string
'5.12345678900024567': Failed to parse time string
'5.12345678900034567': 4567-01-03 05:12:00.000000 5:12 am, 4567-01-03 (3rd day of the year)
'5.12345678903654567': 4567-12-31 05:12:00.000000 5:12 am, 4567-12-31 (365th day of the year)
'5.12345678903664567': 4568-01-01 05:12:00.000000 5:12 am, 4568-01-01 (366th day(!) of a non-leap year)
'5.12345678903674567': Failed to parse time string
I've been able to predict certain parts, but it doesn't seen to follow a sensible overall format. What's going on here?
08-22 is 234th day of year
05-03 is 123rd day https://www.scp.byu.edu/docs/doychart.html
Those were ones you didn't put in, so I thought it would help. The ones that fail to parse probably don't have a valid day of year where it's looking for them.
I think we have to have a look on Date API for php
PHP doesn't document the date formats in detail, you'll probably have to read the parser source code.
@Barmar The function (not the entire class) that parses the date is 24000 lines long!
My guess is that whatever this is doing isn't really intentional, it may just be the side effects of some heuristics in the code.
@Barmar that's my guess too. Hopefully someone knows for sure!
Why does it matter? Do you really need to parse floating point numbers as dates and get predictable results? This seems like just random trivia you stumbled onto by accident, and will never come up in practice.
@Barmar Because if I submit a patch to fix this assumed bug, I could break people's production code.
Only the creator of the DateTime class code can fully answer the question. I'm just trying to explain the motivation. DateTime wants to interpret many of the possible free formats. First, the input is converted to a string.
class test{
public function __toString(){
return "2001-02-03 04:05:06";
}
}
$d = new DateTime(new test);
//object(DateTime)#2 (3) { ["date"]=> string(19) "2001-02-03 04:05:06" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" }
The method __toString used here confirms this.
If the string is empty then a date is generated from the current day and the current time. This is also the basis for missing information from the input. Then tries to recognize a time (Time Formats).
This test shows that the first attempt is to determine a time.
Look at the following tests ror a confirmation.
This is described in the manual Date Formats:
Year (and just the year) YY "1978", "2008"
'1978' can not be time, so it is parsed as a year.
var_dump(new DateTime('1978')); //"1978-09-23 09:46:43.000000"
But '2008' can represent a time. It is parsed as time 20:08.
var_dump(new DateTime('2008')); // "2019-09-23 20:08:00.000000"
The hours, minutes and seconds can be changed by:,,. or nothing to be separated.
If only one time is detected, then the current day is taken as date.
Examples (Today is 23 Sep 2019):
'04:08','0408','04.08' => "2019-09-23 04:08:00.000000"
'04.08.05','04.08:05','040805' => "2019-09-23 04:08:05.000000"
Then the date is tried to parse. The order Date / Time or Time Date in the Input does not matter. All strings parse to "2001-02-03 04:05:00.000000":
'04:05 2001-02-03'
'04.05 20010203'
'04.0520010203'
'4.0520010203'
'2001020304.05'
'20010203 04.05'
Your String: '5.123456'
The parser first analyzes 5.12 as time 05:12. The Rest is '3456' the year.
The String '5.12345678901232004' will parsed as '5.12<PHONE_NUMBER>3 2004'
5.12 as time 05:12 and 2004 as year.
var_dump(new DateTime('5.12<PHONE_NUMBER>3 2004'));
//object(DateTime)#2 (3) { ["date"]=> string(26) "2004-05-02 05:12:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" }
I have no idea how to determine the remaining string '34567890123' day 02 and month 05.
The question was not answered completely. I hope to have contributed to the understanding of the DateTime parser.
| common-pile/stackexchange_filtered |
ERROR: Could not build wheels for phik, which is required to install pyproject.toml-based projects
While running this command on command prompt:
PS D:\Mitali> pip install pandas-profiling
I am getting this error:
ERROR: Could not build wheels for phik, which is required to install pyproject.toml-based projects
The entire error looks as:
Building wheels for collected packages: phik
Building wheel for phik (pyproject.toml) ... error
ERROR: Command errored out with exit status 1:
command: 'C:\Users\HP\AppData\Local\Programs\Python\Python310\python.exe' 'C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py' build_wheel 'C:\Users\HP\AppData\Local\Temp\tmpqi_0g29r'
cwd: C:\Users\HP\AppData\Local\Temp\pip-install-prmn_pyb\phik_c27377b089f2467988f10191570c8033
Will you please share the full error, in the question?
try to do this:
pip install phik==0.11.1
pip install pandas-profiling
| common-pile/stackexchange_filtered |
Extract Text with Python from Webpages within div class
I try to get songtexts from a webpage. Below I have two versions of how I want to achieve that because with the first one I only could get the text from within the first <p> paragraph but sometimes within the div class songbook there are several <p>. With the second version I achieved that but it includes the whole html. The ".text" only works if there's only one item and not several ones (list).
I'm a bit lost here and also a newbie to Python and BeautifulSoup so I appreciate your help very much.
#Extract the songtext only and save it in file
url = urllib.request.urlopen('https://www.udo-
lindenberg.de/mit_dir_sogar_n_kind.57754.htm')
content = url.read()
soup = BeautifulSoup(content, 'lxml')
#search on page for div class block songbook and extract songtext between <p>
table = soup.find_all('div', attrs={"class":"block songbook"})
for item in table:
sys.stdout = open('output.txt','wt')
songtext = item.find('p').text
print(item.find('p').text)
#extracts the songtext with html markers
page_link = 'https://www.udo-lindenberg.de/mit_dir_sogar_n_kind.57754.htm'
page_response = requests.get(page_link, timeout=5)
page_content = BeautifulSoup(page_response.content, "html.parser")
textContent = []
for i in range(0,200):
paragraphs = soup.find_all('div', attrs={"class":"block songbook"})
textContent.append(paragraphs)
sys.stdout = open('output2.txt','wt')
print(paragraphs)
Okay I've solved it myself. I've found the mistake. The line at second version:
paragraphs = soup.find_all('div', attrs={"class":"block songbook"})
has to be changed to:
paragraphs = soup.find('div', attrs={"class":"block songbook"}).text
| common-pile/stackexchange_filtered |
For which positive integers n does there exist a prime whose digits sum to n?
Motivated by this earlier question, I thought of this problem:
Question: For which positive integers $n$ does there exist a prime whose decimal digits sum to $n$?
We can make two "easy" observations:
$1$ is not the sum of the digits of a prime.
$6,9,12,\ldots$ cannot be the sum of the digits of a prime (by the mod 3 version of Casting Out Nines). However, $3$ is the sum of the digits of $3$.
This makes me suspect that everything else is possible. Using the GAP code below, I checked that everything possible is achieved for $n \leq 71$ (although, this is not a particularly impressive feat).
Comment: I'm aware that questions along the lines of can the primes do that? can often be hard to answer (such as Goldbach's Conjecture), but hopefully some non-trivial contribution can be made to this question, possibly along the lines of "it is true assuming Conjecture X", or possibly via an algorithm for computing these primes faster.
GAP code:
DecimalDigitSum:=function(n)
if(n<10) then return n; fi;
return (n mod 10)+DecimalDigitSum(Int(n/10));
end;;
A:=List([1..1000],i->0);;
n:=1;;
while(true) do
n:=NextPrimeInt(n);
s:=DecimalDigitSum(n);
if(A[s]=0) then
Print(s," is the sum of digits of the prime ",n,"\n");
A[s]:=n;
fi;
od;
The output was:
2 is the sum of digits of the prime 2
3 is the sum of digits of the prime 3
5 is the sum of digits of the prime 5
7 is the sum of digits of the prime 7
4 is the sum of digits of the prime 13
8 is the sum of digits of the prime 17
10 is the sum of digits of the prime 19
11 is the sum of digits of the prime 29
14 is the sum of digits of the prime 59
13 is the sum of digits of the prime 67
16 is the sum of digits of the prime 79
17 is the sum of digits of the prime 89
19 is the sum of digits of the prime 199
20 is the sum of digits of the prime 389
22 is the sum of digits of the prime 499
23 is the sum of digits of the prime 599
25 is the sum of digits of the prime 997
26 is the sum of digits of the prime 1889
28 is the sum of digits of the prime 1999
29 is the sum of digits of the prime 2999
31 is the sum of digits of the prime 4999
32 is the sum of digits of the prime 6899
35 is the sum of digits of the prime 8999
34 is the sum of digits of the prime 17989
37 is the sum of digits of the prime 29989
38 is the sum of digits of the prime 39989
40 is the sum of digits of the prime 49999
41 is the sum of digits of the prime 59999
43 is the sum of digits of the prime 79999
44 is the sum of digits of the prime 98999
46 is the sum of digits of the prime 199999
47 is the sum of digits of the prime 389999
49 is the sum of digits of the prime 598999
50 is the sum of digits of the prime 599999
52 is the sum of digits of the prime 799999
53 is the sum of digits of the prime 989999
55 is the sum of digits of the prime 2998999
56 is the sum of digits of the prime 2999999
58 is the sum of digits of the prime 4999999
59 is the sum of digits of the prime 6999899
61 is the sum of digits of the prime 8989999
62 is the sum of digits of the prime 9899999
64 is the sum of digits of the prime 19999999
65 is the sum of digits of the prime 29999999
67 is the sum of digits of the prime 59899999
68 is the sum of digits of the prime 59999999
71 is the sum of digits of the prime 89999999
70 is the sum of digits of the prime 189997999
The sequence on the right is Sloane's A067523 (or A067180 if 0's are placed in the gaps), which are not particularly enlightening. The sequence on the left does not seem to be in Sloane's OEIS.
Another question that comes to my mind is: Is there any integer $n$ which is the digit sum of infinitely many distinct primes? For example if $n=2$ were to have this property, it would imply an infinitude of generalized Fermat primes of the form $10^{2^m}+1$ which goes against usual conjectures on such primes.
| common-pile/stackexchange_filtered |
How do I utilize Webclient.DownloadFile or DownloadString if the website uses SSL?
I'm writing a small utility that scrapes a webpage and emails me if the class I want has open seats. See the follow url:
Math Classes
However, I get an error everytime I execute the following code:
private void timer1_Tick(object sender, EventArgs e)
{
using (WebClient client = new WebClient())
{
//var html = client.DownloadString("https://grim.westga.edu/pls/UWGP_DAD/hwwkbull.p_us_subj_list?term_code=201108&subj=math&levl=US");
client.DownloadFile(@"https://grim.westga.edu/pls/UWGP_DAD/hwwkbull.p_us_subj_list?term_code=201108&subj=math&levl=US", @"C:\file.txt");
}
}
Any idea?
That link you posted also supports simple HTTP.
See here: http://grim.westga.edu/pls/UWGP_DAD/hwwkbull.p_us_subj_list?term_code=201108&subj=math&levl=US
Try removing your s from the url and see if that works.
Can't believe I overlooked that
| common-pile/stackexchange_filtered |
Attempting to load the view of a view controller while it is deallocating. CoreSpotlight
I integrate CoreSpotlight in my app. I want that user will find need information in spotlight search and after user will open this information in spotlight information opens in DetailViewController. I made it, spotlight works nice, but when application is opening I see this error Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (UIAlertController: 0x1245a0560) although I don't use UIAlertController. I made in AppDelegate func which call function of UITableViewController which must to open object by index. But it is not appear. Still there is an error in showData() performSegueWithIdentifier("show", sender: nil)reason: 'Receiver () has no segue with identifier 'show''. Although I add segue ( with show name) and it works when I usually select cell. Please help me.
AppDelegate
func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
if userActivity.activityType == CSSearchableItemActionType {
if let identifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
print(identifier)
checkWord = identifier // checkWord is String
let tableC = TableViewController()
tableC.showData()
return true
}
}
return false
}
func showData() {
let matchString = appDel.checkWord
if mainArray.contains(matchString) {
let ind = mainArray.indexOf(matchString)!
let indexPathMain = NSIndexPath(forItem: ind, inSection: 0)
print(indexPathMain)
self.tableView.selectRowAtIndexPath(indexPathMain, animated: true, scrollPosition: UITableViewScrollPosition.None)
performSegueWithIdentifier("show", sender: nil)
print("Show data")
}
}
If you don't implement willContinueUserActivityWithType or if it returns false, it means that iOS should handle activity. And in this case it can show UIAlertController. So to get rid this warning return true for your activity in this delegate call:
func application(application: UIApplication,
willContinueUserActivityWithType userActivityType: String) -> Bool {
return true
}
| common-pile/stackexchange_filtered |
'You rather not' construction
What would be a correct way to say this:
If you rather not wait, you can always do sth else.
or
If you'd rather not wait, you can always do sth else.
And what about the comma? Is it needed here?
The correct way would be:
If you'd rather not wait, you could always do something else.
You can use 'can' but 'could' matches tense a little more closely.
The comma should be used to separate the two clauses, yes.
| common-pile/stackexchange_filtered |
Parallax images overflowing even after CSS is overflow hidden
I have a project where I am using parallax effect. My code is exactly like this in that project:
$(window).scroll(function(){
var wScroll = $(this).scrollTop();
$('.flying-man').css({'transform':'translateY( -'+ ( wScroll- $('.flying-man').offset().top/1.2 )/150+'%)'});
});
#fun2 {
margin-top: 8%;
overflow: hidden;
}
.space-back {
background: url(https://i.sstatic.net/WgyaY.jpg) no-repeat;
background-position: center;
background-size: cover;
height: 100vh;
position: absolute;
width: 100%;
}
.flying-man {
position: absolute;
background: url(https://i.sstatic.net/LMAGK.png) no-repeat;
background-position: bottom left;
background-size: 70%;
margin-top: 50px;
width: 100%;
height: 100vh;
/*background-color: rgba(2,2,2,0.5);*/
}
section {
min-height: 100vh;
}
<section id="fun2">
<div class="space">
<div class="space-back"></div>
<div class="flying-man"></div>
</div>
</section>
<section id="speakers2">
</section>
<script
src="https://code.jquery.com/jquery-3.1.1.slim.min.js"
integrity="sha256-/SIrNqv8h6QGKDuNoLGA4iret+kyesCkHGzVUUV0shc="
crossorigin="anonymous"></script>
All I want is the second image the one having class .flying-man to be contained in the section and not overflow. I have a script that translate it from y axis (downward to upward on scroll).
You can see the problem in this image.
Please include the script you're using - it's hard to debug unless we can run your code ourselves!
added the images and js whats the problem now ? pls help
When you set display: absolute (in CSS), you take the element out of the normal document flow. An absolute element is no longer constrained by its parent, but by the whole page. I.e. If you don't use display: absolute or you make it work with more JavaScript, then you should be on your way to getting what you want.
Simply add
#fun2 {
margin-top: 8%;
overflow: hidden;
position:relative; /* <<< this */
}
otherwise overflow: hidden will have no effect
| common-pile/stackexchange_filtered |
How will changing taxonomy term affect tagged nodes
What happens when a taxonomy term is changed? Will the term just change for all nodes tagged with the original term or will the relationship be deleted?
The taxonomy term relationship is stored in the database using the term ID. So if you change that term's name, but not the ID, it should be fine. If you delete that term, the relationship will no longer exist so avoid doing that.
| common-pile/stackexchange_filtered |
Cannot return value - Expression Expected?
I'm having an issue with my return Car; I was under the impression it would return the "KEY_IMAGE" String.
KEY_IMAGE is a string which will be put inside a BitmapFactory:
byte[] logoImage = getLogoImage(IMAGEURL);
private byte[] getLogoImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
logoImage.setImageBitmap(BitmapFactory.decodeByteArray( currentAccount.accImage,
0,currentAccount.accImage.length));
My method which has an error is:
public Car getCurrentCar() {
SQLiteDatabase db = getWritableDatabase();
String sql = "SELECT " + KEY_ID + "," + KEY_IMAGE + " FROM " + TABLE_CARS + "ORDER BY RANDOM() LIMIT 1";
Cursor cursor = db.rawQuery(sql, new String[] {});
if(cursor.moveToFirst()){
Car car_current = new Car(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),cursor.getString(3));
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
db.close();
if(cursor.getCount() == 0){
return null;
} else {
return Car;
}
}
the return Car; is giving me the errors:
"Expression expected" and "cannot find symbol variable Car".
Would anyone be able to explain why I cannot return Car?
Edit:
public Car getCurrentCar() {
SQLiteDatabase db = getWritableDatabase();
String sql = "SELECT " + KEY_ID + "," + KEY_IMAGE + " FROM " + TABLE_CARS + "ORDER BY RANDOM() LIMIT 1";
Cursor cursor = db.rawQuery(sql, new String[] {});
Car car = null;
try {
if (cursor.moveToFirst()) {
car = new Car(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3));
}
}
finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
db.close();
}
return car;
}
declare car outside the if block and just before it.
remove else condition and post return car_current; there
If the cursor close throws an exception your DB will never be closed. OUght to be enclosed in individual try/catch blocks.
Cannot find symbol: variable Car
That means that the compiler can't find a variable named Car.
return Car;
Car is a class, not an object. You must return an object (or a variable).
I think that is what you meant
return car_current;
But you have to declare that variable outside the if:
Car car_current = null;
if(cursor.moveToFirst()){
car_current = new Car(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),cursor.getString(3));
}
This is Java 101.
Try it like this:
// Why not pass in a Car id?
public Car getCurrentCar() {
// Bad form here. Externalize these.
SQLiteDatabase db = getWritableDatabase();
String sql = "SELECT " + KEY_ID + "," + KEY_IMAGE + " FROM " + TABLE_CARS + "ORDER BY RANDOM() LIMIT 1";
Cursor cursor = db.rawQuery(sql, new String[] {});
Car car = null;
if(cursor.moveToFirst()) {
car = new Car(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),cursor.getString(3));
}
// Wrong - close in a finally block.
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
db.close(); // Wrong - close in a finally block.
return car;
}
Hey Duffy, thanks for your quick response. I'm having a look over what you've written. I'm not sure what you mean by why not pass in a Car id? I am querying the KEY_ID inside the sql String, or should that be done within the method? getCurrentCar(id)?
Also, should I be using try and finally together?
Exactly. I think it's better to pass that in. And yes, you should be using try and finally together. What about exceptions? I'll bet there's a SQLException thrown by some of the methods you call, but you neither catch nor include it in method signature. I'd recommend using PreparedStatement and not using Cursor. There's no need for it.
I've edited my post with the changes you suggested + I added the try and finally. Am I right in thinking the if (cursor != null) Part should be in finally?
Yes, but I wouldn't use Cursor here. I'd just write classic JDBC and use PreparedStatement.
I think you need to return car_current instead of Car. But the variable car_current is not in the scope, so you should define it outside the if statement.
Try this:
Car car_current = null;
if(cursor.moveToFirst()){
car_current = new Car(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),cursor.getString(3));
}
//after some code you could return only car_current without control
return car_current;
| common-pile/stackexchange_filtered |
File gets corrupted when transferring it via socket
My Java client sends a file to a C++ server using this code:
FileInputStream fileInputStream = new FileInputStream(path);
byte[] buffer = new byte[64*1024];
int bytesRead = 0;
while ( (bytesRead = fileInputStream.read(buffer)) != -1)
{
if (bytesRead > 0)
{
this.outToServer.write(buffer, 0, bytesRead);
}
}
My C++ server receives the bytes using this code:
vector<char> buf5(file_length);
size_t read_bytes;
do
{
read_bytes = socket.read_some(boost::asio::buffer(buf5,file_length));
file_length -= read_bytes;
}
while(read_bytes != 0);
string file(buf5.begin(), buf5.end());
And then creates the file using this code:
ofstream out_file( (some_path).c_str() );
out_file << file << endl;
out_file.close();
However, somehow the file gets corrupted during this process.
At the end of the process, both files(the one sent and the one created) have the same size.
What am I doing wrong? Any help would be appreciated!
Edit: tried to use different code for receiving the file, same result:
char buf[file_length];
size_t length = 0;
while( length < file_length )
{
length += socket.read_some(boost::asio::buffer(&buf[length], file_length - length), error);
}
string file(buf);
what do you mean by corrupted?
I'm sending a .so file. When I try to open it using "dlopen", it produces an error. "dlopen" works fine on the original file.
Have never had experience with boost::asio, but the way how you create the buffer object over the same vector in every iteration seems suspicious. Are you sure that every read does not reuse the beginning of the buffer, the remainder remaining unused?
Try to run md5sum on both files. Is it the same?
where do you obtain file_length in your first example or config_file_length in the second example?
@AndreyChernyakhovskiy look at the edit
Check if they're the same size. Make sure you're writing using binary and not ascii mode.
@Narkha edited the last code a bit... I sent it before sending the file. the file_length received is correct, and the server reads file_length amount of bytes
@user130955 Yes, but how much do you save in the output file? I bet it's not the same, due to your using string and << for binary data.
@user130955, this way it seems reasonable as to how you read the data into the buffer. But when you contruct a string from that buffer, the constructor will stop at the first zero byte it encounters; you should also pass the length. The question is, why do you need the string at all?
@AndreyChernyakhovskiy Actually I don't. I used the string to write to the file using "<<" operator, which apparently was a mistake. Anyway, thank you!
1) is it a text file?
2) if not try opening the file in binary mode before writing, also do not use << operator, instead use write or put methods
+1 For completeness, OP should use a function that fulfills UnformattedOutputFunction concept.
Thanks. Opened the file in binary mode and used "write" function, and it did the job.
In your first example the problem appears to be this line:
read_bytes = socket.read_some(boost::asio::buffer(buf5,file_length));
This results in you overwriting the first N bytes of your string and not appending multiple reads correctly.
In your second example the problem is likely:
string file(buf);
If buf contains any NUL characters then the string will be truncated. Use the same string creation as in your first example with a std::vector<char>.
If you still have problems I would recommend doing a binary diff of the source and copied files (most hex editors can do this). This should give you a better picture of exactly where the difference is and what may be causing it.
I wish I had 15 rep to vote up. I used the second example and Tejas answer and that did the job. Thank you!
| common-pile/stackexchange_filtered |
Proper Join/GroupJoin implementation
I have been trying to work with the Join and GroupJoin method. The problem seems simple. Given TableA and TableB as datamaps such that:
class MyDataContext : DataContext
{
public Table<tblA> TableA;
public Table<tblB> TableB;
}
...I am using TableA as my primary table and want to join on one field, CustomerID in TableB to retrieve [TableB].[LastName].
Should not be difficult, except that I am having difficulty getting results to work properly. TableA has records that I want regardless of a matching CustomerID in TableB. Sounds like a left join - so, reading here, I mimicked what @tvanfosson suggested:
// appropriately rewritten for my needs - so I thought...
private static IQueryable GetRecordsByView1(IQueryable<tblA> source)
{
var records = source.GroupJoin(myContext.TableB,
info => info.CustomerID,
owner => owner.CustomerID,
(info, owner) => new
{
info.CustomerID,
Owner = owner.Select(o => o.LastName).DefaultIfEmpty(),
Store = info.Store,
})
.Select(record => new
{
record.CustomerID,
record.Owner,
record.Store,
});
return records;
}
source is dynamic, such that one method builds a dynamic query:
public static void QueryStores()
{
IQueryable<tblA> source = myContext.TableA;
if (criteriaA)
source = source.Where(// something);
if (criteriaB)
source = source.Where(// something);
// after processing criteria logic, determine type of view
switch (byView)
{
case View1:
{
source = GetRecordsByView1(source);
break;
}
//other case blocks
}
myGridView.DataSource = source;
}
The problem: I am receiving the following error:
Could not format node 'OptionalValue'
for execution as SQL.
I believe it is in the following line of code:
Owner = owner.Select(o => o.LastName).DefaultIfEmpty()
What am I doing wrong here? I have to write GroupJoin as an extension method.
First...@Brian got me started on the right track. Here is the solution:
var records = source
.GroupJoin(myContext.TableB,
info => info.CustomerID,
owner => owner.CustomerID,
(info, owner) => new
{
info,
Owner = owner.Select(o => o.LastName).First()
})
.Select(record => new
{
record.info.CustomerID,
record.Owner,
record.info.Store
});
This provides me with the exact results desired...
You are correct that Owner = owner.Select(o => o.LastName).DefaultIfEmpty() is the line causing your problems. The best workaround that I have come up with is something like this:
var records = source.GroupJoin(myContext.TableB,
info => info.CustomerID,
owner => owner.CustomerID,
(info, owner) => new { info, owner }).ToList();
records.Select(x => new
{
x.info.CustomerID,
Owner = x.owner.First() == null ? new string[] {} : x.owner.Select(o => o.LastName).ToArray(),
Store = x.info.Store,
})
.Select(record => new
{
record.CustomerID,
record.Owner,
record.Store,
});
It certainly isn't ideal (you have to materialize the groupjoin with 'ToList'), and there might be a better solution, but that has worked for me. You might have to play around a bit to get it to work just right for you, but I hope this helps you along your way.
This looks promising. I did see where it looks like there is just a failure to materialize the data - I'm beginning to understand that. After removing DefaultIfEmpty(), the query goes through but the Owner result is blank. I stepped into the results and the Owner last name is in there, but buried. So I know I'm close...thanks.
Check out this left outer join example: http://msdn.microsoft.com/en-us/library/bb397895.aspx
The relevant sample:
var query = from person in people
join pet in pets on person equals pet.Owner into gj
from subpet in gj.DefaultIfEmpty()
select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) }
You can join the results into gj, then use DefaultIfEmpty to create the outer join situation, and still get the results you want.
Someone else got a similar error using DefaultIfEmpty here:
Max or Default?
http://blog.appelgren.org/2008/05/15/linq-to-sql-aggregates-and-empty-results/
HTH.
The problem is that I have to write my Join as an extension method. I cannot write as LINQ statement.
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.