qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
67,057,864 | I'm trying to use [lcapy's](https://www.google.com/search?q=lcapy&oq=lcapy&aqs=chrome..69i57j35i39j35i19i39j69i59j69i60l4.1424j0j7&sourceid=chrome&ie=UTF-8) python library to draw some electrical circuits in google colab. Unfortunately, I'm always getting an error:
`RuntimeError: pdflatex is not installed`
Even though I did `pip install pdflatex`
I couldn't find anything related to this error in lcapy's docs.
the notebook can be found [here](https://colab.research.google.com/drive/1KLpNLekwXLnP8xUfAUeGn1g42vugFA2N?usp=sharing) | 2021/04/12 | [
"https://Stackoverflow.com/questions/67057864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9943255/"
] | I experienced a similar issue/error trying to render PDFs from latex output generated by pandas in google colab recently. The error I got was complaining about a file ([Error Code 2](https://stackoverflow.com/questions/6758514/python-exit-codes/6758687)), listed 'pdflatex' as the missing file, but I confirmed the install had completed as you reported. This led me to realize there were missing LaTex dependencies that were generating the error; the traceback seemed a bit misleading to me. Here is the solution that worked for me:
First, install components and dependencies in colab notebook:
```python
!pip install folium==0.2.1
!pip install pdflatex
!sudo apt-get install texlive-latex-recommended
!sudo apt install texlive-latex-extra
!sudo apt install dvipng
```
In my first attempt, There was an error buried in the install of `pdflatex` with an incompatible version of `folium 0.8.x`, so the first command rolls it back to the compatible version from the error trace. Probably not totally necessary to roll back folium, but I haven't tested.
The latex install commands were shamelessly lifted from [this answer for latex-equations-do-not-render-in-google-colaboratory-when-using-matplotlib](https://stackoverflow.com/questions/55746749/latex-equations-do-not-render-in-google-colaboratory-when-using-matplotlib), where they offer a bit more explanation. The whole install process produced quite a bit of output and took some time.
After completed, I was able to generate a pdf file from my LaTex string similar to the [example from the package docs](https://pypi.org/project/pdflatex/):
```python
import pdflatex as ptex
pdfl = ptex.PDFLaTeX.from_texfile(r'/content/my_tex_string_file.tex')
pdf, log, completed_process = pdfl.create_pdf()
with open('testPDF.pdf', 'wb') as pdfout:
pdfout.write(pdf)
```
`my_tex_string_file.tex` was generated from pandas in my test case, and I added a preamble manually (string concatenation) to include the correct latex packages for my desired output, but a quick look through the github page for [lcapy](https://github.com/mph-/lcapy) shows the same approach may work for lcapy as well. | I ran into the same issue myself and after verifying pdflatex is installed with `!pdflatex -help`, I looked into Lcapy's code. The easiest workaround I found is to comment out line 73 of system.py. I only need schematic tools, so this solution is adequate for me. If you need a proper solution, all the relevant functions are in the same file and it seems that `import pdflatex` is unnecessary as the library searches for the binary. |
11,338,420 | **ERROR**
```
Unable to cast the type 'System.Nullable`1' to type 'System.Object'.
LINQ to Entities only supports casting Entity Data Model primitive types.
```
This is the error I am getting.
**Controller** -
```
public ActionResult FixturesAll()
{
teamMgr = new TeamManager();
fixtureMgr = new FixtureManager();
var team = teamMgr.GetTeams();
var viewModel = new TeamIndexViewModel()
{
Teams = team.ToList(),
NumberOfTeams = team.Count()
};
var fixtures = from fixtures in Oritia_entities.Fixtures
where fixtures.SeasonId == seasionID
select new FixtureModel
{
Team1 = "",
Team2 = "",
Winners = (fixtures.TeamWon+""),
FirstBattingTeam = (fixtures.FirstBattingTeam+""),
SecondBattingTeam = (fixtures.SecondBattingTeam+""),
Team1Score = fixtures.Team1Score + "",
Team1Wickets = fixtures.Team1Wickets + "",
Team2Score = fixtures.Team2Score + "",
Team2Wickets = fixtures.Team2Wickets + ""
};
ViewData["Fixtures"] = fixtures;
return View(viewModel);
}
```
**Partial View**
```
<%@ Control Language="C#" Inherits=
"System.Web.Mvc.ViewUserControl<IEnumerable<DataAccess.FixtureModel>>" %>
<table>
<% foreach (var item in ViewData["Fixtures"]
as IEnumerable<DataAccess.FixtureModel>) // Here I am getting the error
{ %>
<tr>
<td>
<%: item.Team1 %>
</td>
<td>
<%: item.Team2 %>
</td>
</tr>
</table>
```
**View**
```
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<FunBox.ViewModels.TeamIndexViewModel>" %>
<ul>
<% foreach (string team in Model.Teams)
{ %>
<li><a href="<%: team.ToString() %>/">
<%: team.ToString() %></a> </li>
<% } %>
</ul>
<div>
<% Html.RenderPartial("FixturesAll",ViewData["Fixtures"]); %>
</div>
```
**Complex Classes**
```
public class TeamIndexViewModel
{
public int NumberOfTeams { get; set; }
public List<String> Teams { get; set; }
}
public class FixtureModel
{
public string Team1 { get; set; }
public string Team2 { get; set; }
public string Winners { get; set; }
public string Team1Score { get; set; }
public string Team1Wickets { get; set; }
public string Team2Score { get; set; }
public string Team2Wickets { get; set; }
public string FirstBattingTeam { get; set; }
public string SecondBattingTeam { get; set; }
}
```
**Output of sp\_help Fixtures**
```
Id bigint (pk)
TeamID1 bigint
TeamID2 bigint
TeamWon bigint
Date datetime
SeasonId bigint
ManOfTheMatch bigint
FirstBattingTeam bigint
SecondBattingTeam bigint
ResultDescription nvarchar
Team1Score bigint
Team2Score bigint
Team1Wickets bigint
Team2Wickets bigint
```
This is my overall structure and I am getting the above error.I googled but i didn't get an exact solution for this. Any help is highly appreciated.
*Thanks all for helping me and my special thanks to [**Jon Skeet**](https://stackoverflow.com/users/22656/jon-skeet) for giving the idea*
Please see my updated query
```
var data = from fixtures in Oritia_entities.Fixtures
join t1 in Oritia_entities.Teams on new { ID = fixtures.TeamID1 } equals new { ID = t1.ID }
join t2 in Oritia_entities.Teams on new { ID = fixtures.TeamID2 } equals new { ID = t2.ID }
where fixtures.SeasonId == seasionID
select new FixtureModel
{
Team1 = t1.TeamName,
Team2 = t2.TeamName,
Winners = SqlFunctions.StringConvert((double)(fixtures.TeamWon ?? 1)),
FirstBattingTeam = SqlFunctions.StringConvert((double)(fixtures.FirstBattingTeam ?? 1)),
SecondBattingTeam = SqlFunctions.StringConvert((double)(fixtures.SecondBattingTeam ?? 1)),
Team1Score = SqlFunctions.StringConvert((double)(fixtures.Team1Score ?? 1)),
Team1Wickets = SqlFunctions.StringConvert((double)(fixtures.Team1Wickets ?? 1)),
Team2Score = SqlFunctions.StringConvert((double)(fixtures.Team2Score ?? 1)),
Team2Wickets = SqlFunctions.StringConvert((double)(fixtures.Team2Wickets ?? 1))
};
```
I used [SqlFunctions.StringConvert](http://msdn.microsoft.com/en-us/library/dd487158.aspx) for converstion to string and nows it working. Thanks all. | 2012/07/05 | [
"https://Stackoverflow.com/questions/11338420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438624/"
] | Instead of:
```
<% foreach (var item in ViewData["Fixtures"] as IEnumerable<DataAccess.FixtureModel>)
```
try:
```
<% foreach (var item in Model)
```
Also try to eagerly load your entities using the `.ToList()` method:
```
ViewData["Fixtures"] = fixtures.ToList();
```
Also you might consider using view models instead of `ViewData`. It will make your code much cleaner and you will no longer rely on *magic strings*.
---
UPDATE:
Try this:
```
var fixtures = Oritia_entities
.Fixtures
.Where(f => f.SeasonId == seasionID)
.ToList()
.Select(f => new FixtureModel
{
Team1 = "",
Team2 = "",
Winners = (f.TeamWon+""),
FirstBattingTeam = (f.FirstBattingTeam+""),
SecondBattingTeam = (f.SecondBattingTeam+""),
Team1Score = f.Team1Score + "",
Team1Wickets = f.Team1Wickets + "",
Team2Score = f.Team2Score + "",
Team2Wickets = f.Team2Wickets + ""
});
``` | Give this a shot... (although id tweak the try catch a bit, if you end up using it. i wouldn't recommend suppressing an error and not doing anything about it/allow it to die a silent death ;P)
```
public string NullableObjectToString(object obj)
{
try
{
if (obj == null)
return "";
return (obj ?? string.Empty).ToString();
}
catch (Exception)
{
return "";
}
}
```
Then
```
var fixtures = from fixtures in Oritia_entities.Fixtures
where fixtures.SeasonId == seasionID
select new FixtureModel
{
Winners = NullableObjectToString(fixtures.TeamWon),
FirstBattingTeam = NullableObjectToString(fixtures.FirstBattingTeam) // ..... you get the idea
}
``` |
204,696 | My question is in regards to MySQL, but I also wonder how this affects other databases. I have several fields that are `varchar(255)` but my coworker insists if they were `varchar(30)` -- or any smaller size -- then queries would run faster. I'm not so sure, but if it's so I'll admit to it. | 2008/10/15 | [
"https://Stackoverflow.com/questions/204696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28240/"
] | It depends on the query and the data, but you're probably optimizing too soon to even be worried.
For SELECT queries, the statement itself will run just as fast within MySQL, and as long as the data doesn't get larger than it would be at the smaller sized field then it will transmit as fast. If the smaller field forces you to store the information in a smaller space (would you use the extra 225 chars?), then you will get fast transmission to other programs.
For INSERT queries the size of the field isn't an issue, but using variable length fields will slow the process done. INSERTs with fixed length rows are notably faster (at least in MySQL 5.0 and earlier).
Generally, use the size you need for the data. If you don't know if you need 255 chars or 30 chars you're probably optimizing too soon. Are large data fields causing a bottleneck? Is you program suffering from database performance problems at all? Find your bottlenecks first, solve the problem with them second. I'd guess the difference in time you're looking at here is unimportant to whatever problem you are trying to solve. | If you're only ever using the first 30 characters, then there won't be a difference between a varchar(30) and a varchar(255) (although there would be a difference with varchar(1000), which would take an extra byte).
Of course, if you end up using more than 30 characters, it will be slower as you have more data to pass to the client, and your indexes will be larger. |
34,672,248 | I'm trying to configure [Let's Encrypt certificates](https://letsencrypt.org/) on a server that is publically accessible. Originally, the server was hiding behind a router, but I have since forwarded ports 80 and 443.
The certificate seems to have completed a majority of the install process, but fails with the message: `Failed to connect to host for DVSNI challenge`.
Full stack trace:
```
Updating letsencrypt and virtual environment dependencies......
Requesting root privileges to run with virtualenv: sudo /bin/letsencrypt certonly --standalone -d example.net -d www.example.net
Failed authorization procedure. example.net (tls-sni-01): urn:acme:error:connection :: The server could not connect to the client to verify the domain :: Failed to connect to host for DVSNI challenge
IMPORTANT NOTES:
- The following 'urn:acme:error:connection' errors were reported by
the server:
Domains: example.net
Error: The server could not connect to the client to verify the
domain
```
Any support would be greatly appreciated!
I looked around elsewhere for a solution and haven't had much luck. Most other similar situations were resolved by forwarding port 443, but I am certain this port is already forwarded and open, albeit no service is currently running on it.
It shouldn't make a difference, but I'm trying to configure this certificate for use with Node JS on a Raspberry Pi. | 2016/01/08 | [
"https://Stackoverflow.com/questions/34672248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944335/"
] | I finally figured out what was going on. I discovered that the `--manual` flag steps through the authentication process interactively.
Each phase in the process will display a prompt similar to the following:
```
Make sure your web server displays the following content at
http://www.example.net/.well-known/acme-challenge/twJCKQm9SbPEapgHpyU5TdAR1ErRaiCyxEB5zhhw0w8 before continuing:
twJCKQm9SbPEapgHpyU5TdAR1ErRaiCyxEB5zhhw0w8.t7J7DDTbktMGCCu2KREoIHv1zwkvwGfJTAkJrnELb4U
If you don't have HTTP server configured, you can run the following
command on the target server (as root):
mkdir -p /tmp/letsencrypt/public_html/.well-known/acme-challenge
cd /tmp/letsencrypt/public_html
printf "%s" twJCKQm9SbPEapgHpyU5TdAR1ErRaiCyxEB5zhhw0w8.t7J7DDTbktMGCCu2KREoIHv1zwkvwGfJTAkJrnELb4U > .well-known/acme-challenge/twJCKQm9SbPEapgHpyU5TdAR1ErRaiCyxEB5zhhw0w8
# run only once per server:
$(command -v python2 || command -v python2.7 || command -v python2.6) -c \
"import BaseHTTPServer, SimpleHTTPServer; \
s = BaseHTTPServer.HTTPServer(('', 80), SimpleHTTPServer.SimpleHTTPRequestHandler); \
s.serve_forever()"
Press ENTER to continue
```
As I discovered, the process, despite being run as root itself, did not have the privileges to start the challenge server itself. Surely, this might be a bug in the API.
Running the script in the prompt directly produces the following error:
```
$(command -v python2 || command -v python2.7 || command -v python2.6) -c \
> "import BaseHTTPServer, SimpleHTTPServer; \
> s = BaseHTTPServer.HTTPServer(('', 80), SimpleHTTPServer.SimpleHTTPRequestHandler); \
> s.serve_forever()"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python2.7/SocketServer.py", line 419, in __init__
self.server_bind()
File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
SocketServer.TCPServer.server_bind(self)
File "/usr/lib/python2.7/SocketServer.py", line 430, in server_bind
self.socket.bind(self.server_address)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 13] Permission denied
```
But running it as root (as the prompt itself stated) started the server correctly and could be monitored as the external server queried it to complete the challenge:
```
sudo $(command -v python2 || command -v python2.7 || command -v python2.6) -c "import BaseHTTPServer, SimpleHTTPServer; \
s = BaseHTTPServer.HTTPServer(('', 80), SimpleHTTPServer.SimpleHTTPRequestHandler); \
s.serve_forever()"
66.133.109.36 - - [08/Jan/2016 21:25:10] "GET /.well-known/acme-challenge/SZ88SorxBGXBtSZCTn4FX2g7u5XjnPFOOV3f5S5DuXB HTTP/1.1" 200 -
66.133.109.36 - - [08/Jan/2016 21:25:10] "GET /.well-known/acme-challenge/twJCKQm9SbPEapgHpyU5TdAR1ErRaiCyxEB5zhhw0w8 HTTP/1.1" 200 -
```
This error took awhile to diagnose as many things could have prevented the challenges from failing and the servers spawned were failing silently in the background. | If you're using Cloudflare DNS in front of your site, remember to have the DNS A, AAAA records point directly to your site, temporarily until renewal finishes. |
19,630,886 | I am developing an app that targets for tablets only not for phones.
Is this code is enough to acheive my goal? Is there any way to test it or google play sorts it's by itself and present to users?
Below is the code I have tried. But I don't know how to test it?
```
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="18" />
<supports-screens
android:largeScreens="true"
android:normalScreens="false"
android:smallScreens="false"
android:requiresSmallestWidthDp="600"
android:xlargeScreens="true" />
```
Is `android:anyDensity="true"` should be given along with support screen tag? Or just leave that attribute. I want to work my application on all range of tablets.
Any help in this case is highly appreciable. Thanks in advance. | 2013/10/28 | [
"https://Stackoverflow.com/questions/19630886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1277837/"
] | Seems oke, should work as far as I know.
Think about what you define as a tablet. What makes your app less suitable for a 6" phone, than for a 7" tablet?
You can't really test this until you upload it in the Google play Store. These filters in the manifest.xml are used by the Google Play Store, not actually when installing an app. They just make sure somebody doesn't find the app on his tablet and the install button won't work on the website.
You could test it by just uploading your APK but not publishing I think. It will give you a list of devices that are supported with the current settings. | You can use a trick here...
**1)** Create an startup activity, which only verifies screen size in its on create an starts actual activity in success scenario. like,
```
// In onCreate of startup activity
if (isTablet()) {
startActivity(new Intent(StartupActivity.this, MainActivity.class));
this.finish(); // don't forget to kill startup activity after starting main activity.
} else {
setContentView(R.layout.startup);
}
```
This is the critical point. In else case you should set layout to this activity which ideally can have a label with you message like "Device not supported." and a button to close application.
**2)** Ideally, you should place all your string resources in **res/values-large/strings.xml** if you want to support only tablets. So here is the trick, Just add following item in your string resources...
```
<string name="is_supported_screen">true</string>
```
And now create a new string resource file at **res/values/strings.xml** which will contain the same string item but with **false** value like...
```
<string name="is_supported_screen">false</string>
```
**NOTE:** make sure this string resource file must contain atleast all the resources used in StarupActivity e.g. activity title, device not supported message, close app button text etc.
**3)** Finally write a method in your StartupActivity like,
```
private boolean isTablet() {
if (Boolean.parseBoolean(context.getResources().getString(R.string.is_supported_screen))) {
return true;
} else {
return false;
}
}
```
And its done...:)
Actually what happens here is, for devices with large screens like tablets, will load string resource from **res/values-large/strings.xml** and will found `true` and in the case of other device, android will load resources from **res/values/strings.xml** and it will found `false` int the method `isTablet()` for value of `R.string.is_supported_screen`.
And finally, Your main activity will be started if app is installed in tablet and will show message of device not supported will be displayed.
**I would like to emphasize that this is a trick, so you need to follow all the steps carefully. Any mistake and you will not get desired results.** |
48,823,158 | i want to build a project and failed because it requires root permission. When i change the user to root as "sudo -s", it prompted `[sudo] password for ubuntu`. As ec2 doesn't offer ubuntu password, it login with pem file. How can I login as root and create files? Thanks! | 2018/02/16 | [
"https://Stackoverflow.com/questions/48823158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5772775/"
] | I fixed this by doing using "sudo" for a Ubuntu AWS EC2 SSH Login:
```
$ sudo passwd ubuntu
```
Instead of prompting me for:
```
"(current) UNIX password:"
```
It prompts now for:
```
"Enter new UNIX password:"
```
I hope this fixes some problems with ec2 ubuntu users! | I was surprised as well, when AWS ec2 ubuntu prompted me for a password.
```
[sudo] password for ubuntu:
```
In the end I just hit `return` without inserting anything and it worked. |
53,076,457 | I make a button, put it in a div, center align the div and button, however the button aligns itself from its far left side which makes it appear off center. Is there a way to make it align from wherever its actual center is?
```css
.btndiv{
width: 80%;
height: 500px;
margin: 0 auto;
text-align: center;
}
.testbutton{
position: absolute;
bottom: 0px;
width: 30%;
height: 50px;
}
```
```html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style3.css">
</head>
<body>
<div class="btndiv">
<button class=" testbutton"> A button </button>
</div>
</body>
</html>
``` | 2018/10/31 | [
"https://Stackoverflow.com/questions/53076457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10583888/"
] | For aligning element, its always recommended to use "grid", example in snippet:
```css
.grid-container {
display: grid;
grid-template-columns: auto auto auto;
}
.grid-item {
background-color: rgba(255, 255, 255, 0.3);
border: 1px solid rgba(0, 0, 0, 0.1);
padding: 10px;
font-size: 10px;
text-align: center;
}
```
```html
<html>
<body>
<div class="grid-container">
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"><button class=" testbutton"> A Button </button>
</div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
</div>
</body>
</html>
``` | Add below css and you're done...
```
.testbutton {
left: 0;
right: 0;
margin: auto;
}
```
Also, If you want to center align it vertically add below css
```
.testbutton {
left: 0;
right: 0;
top:0;
bottom:0;
margin: auto;
}
```
```css
.btndiv{
width: 80%;
height: 500px;
margin: 0 auto;
text-align: center;
}
.testbutton {
left: 0;
right: 0;
margin: auto;
}
.testbutton{
position: absolute;
bottom: 0px;
width: 30%;
height: 50px;
}
```
```html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style3.css">
</head>
<body>
<div class="btndiv">
<button class=" testbutton"> A button </button>
</div>
</body>
</html>
``` |
16,191,626 | * Our windows store application is especially for our customers.
* It requires user credential to login.
* It doesn't have any sign up page.
* New users cannot access our application(They should be our customer.)
* For new users, Admin will create an account and share them to the
user.
* At the first time, user is requested to change password.
This is how our customer access our application
We submitted our free business app to the windows store.
But it is rejected with the reason saying "*Apps that require users to sign in must either specify upfront in app description the type of access user must have and how to get it or **provide a mechanism for new users to sign up for services from within the app**. At a minimum this could be a link in the app to the website where the user can create a new account and sign up for services. Your app did not appear to provide this information to the user.*"
We do not have such a page. How can we proceed for resubmission?
Whether we need to provide description like "Our application can be accessible to our customers only"
or
provide support email address and saying like "Contact our support team/admin to create new account"
or
any suggestions? | 2013/04/24 | [
"https://Stackoverflow.com/questions/16191626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2315398/"
] | `%.*%`
This will match
1) a %
2) any number of any characters
3) a %
And since it will match greedily rather than lazily, it will match the widest %...% it can, rather than stop at the first.
For example, the lazy version of this would be %.\*?% (putting ? after a \* makes it lazy) and it would close after the first, not last %. | `/%.+?%/` should do the trick.
See greedyness of regex expressions.
`[^%]` stops at the first `%`. But you want to include all characters between the two `%`s. |
7,622 | I want to gather the Edid information of the monitor.
I can get it from the `xorg.0.log` file when I run `X` with the `-logverbose` option.
But the problem is that If I switch the monitor (unplug the current monitor and then plug-in another monitor), then there is no way to get this information.
Is there any way to get the EDID dynamically (at runtime)?
Or any utility/tool which will inform me as soon as monitor is connected and disconnected?
I am using the LFS-6.4. | 2011/02/18 | [
"https://unix.stackexchange.com/questions/7622",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/4843/"
] | After more searching, it looks like the easiest way to do this is with `\_s`. So for example:
```
/hello\_sworld
``` | The way I know of is not hard, but it's a little tedious. Replace every space in your search query with the following:
```
[ \t\n]\+
```
(Note the space after the `[`.) This is regular expression matching syntax. Broken down, it means:
* `[...]` means match any one of the list of characters inside the brackets.
* `\t` is Tab
* `\n` is Newline
* `...\+` means match one or more of the preceding.
For more info on regular expressions, you can ask vim:
```
:help regexp
:help usr_27
``` |
8,088 | What is the largest number of pieces in a set for LEGO, Nanoblock, or any other brand?
I recently bought a 6800-piece LOZ Block set (Chinese Nanoblock knockoff). I was wondering if there are sets in any block size or brand that have more pieces than that. | 2016/10/01 | [
"https://bricks.stackexchange.com/questions/8088",
"https://bricks.stackexchange.com",
"https://bricks.stackexchange.com/users/7751/"
] | Brickset has a query for sets with most pieces: [brickset.com/sets/query-45](http://brickset.com/sets/query-45)
Top of the list is Taj Mahal with 5922 pieces. | There is a 11,800 nanoblock building Neuschwanstein Castle. |
409,529 | This particular example relates to Django in Python, but should apply to any language supporting exceptions:
```
try:
object = ModelClass.objects.get(search=value)
except DoesNotExist:
pass
if object:
# do stuff
```
The Django model class provides a simple method *get* which allows me to search for *one and only one* object from the database, if it finds more or less it raises an exception. If can find zero or more with an alternative *filter* method, which returns a list:
```
objects = ModelClass.objects.filter(search=value)
if len(objects) == 1:
object = objects[0]
# do stuff
```
**Am I overly averse to exceptions?** To me the exception seems a little wasteful, at a guess, a quarter-to-a-half of the time will be 'exceptional'. I'd much prefer a function that returns *None* on failure. Would I be better to use Django's *filter* method and process the list myself? | 2009/01/03 | [
"https://Stackoverflow.com/questions/409529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42974/"
] | Believe it or not, this actually is an issue that is a bit different in each language. In Python, exceptions are regularly thrown for events that aren't exceptional by the language itself. Thus I think that the "you should only throw exceptions under exceptional circumstances" rule doesn't quite apply. I think the results you'll get on this forum will be slanted towards that point of view though, considering the high number of .Net programmers (see [this question](https://stackoverflow.com/questions/351400/why-are-net-programmers-so-afraid-of-exceptions)) for more info on that).
At a very minimum, I'd better not catch anyone who sticks to that rule ever using a generator or a for loop in Python (both of which involve throwing exceptions for non-exceptional circumstances). | I agree with the other answer but I wanted to add that exception passing like this is going to give you a very noticeable performance hit. Highly recommended that you check to see if the result exists (if that's what filter does) instead of passing on exceptions.
---
Edit:
In response to request for numbers on this, I ran this simple test...
```
import time
def timethis(func, list, num):
st=time.time()
for i in xrange(0,1000000):
try:
func(list,num)
except:
pass
et = time.time()
print "Took %gs" % (et-st)
def check(list, num):
if num < len(list):
return list[num]
else:
return None
a=[1]
timethis(check, a, 1)
timethis(lambda x,y:x[y], a, 1)
```
And the output was..
```
Took 0.772558s
Took 3.4512s
```
HTH. |
62,487,263 | I'm trying to pass data from my ag-Grid to a form in a new component by clicking on the row.
I could get the data from the row by clicking on the cell via **onCellClicked** . But i don't know how to pass it to my other component now.
here is my 2 interfaces :
[](https://i.stack.imgur.com/TMH8O.png)
[](https://i.stack.imgur.com/i5bLq.png)
and here is my code :
**ag-Grid.ts :**
```
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Grid, GridApi } from 'ag-grid-community';
import { AgGridAngular } from 'ag-grid-angular';
import { DealsService } from '../services/deals.service';
import * as moment from 'moment';
import { RouterLinkRendererComponent } from '../router-link-renderer/router-link-renderer.component';
@Component({
selector: 'app-deals',
templateUrl: './deals.component.html',
styleUrls: ['./deals.component.scss']
})
export class DealsComponent implements OnInit {
showNav = true;
private gridApi;
gridOptions = {
rowHeight :90,
headerHeight:60,
defaultColDef: {
sortable: true
},
}
columnDefs = [
{
headerName: 'Deal',
field:'DEALID',
cellRendererFramework: RouterLinkRendererComponent,
cellRendererParams: {
inRouterLink: '/Repo'
},
width:300,
resizable:true,
onCellClicked: this.makeCellClicked.bind(this),
filter: 'agNumberColumnFilter',
},
{
headerName:'Block',
field:'BLOCKID',
width:200,
resizable:true,
filter: 'agNumberColumnFilter',
columnGroupShow:'open',
},
],
},
];
rowData : any;
constructor(private service:DealsService) {}
onGridReady(params) {
this.gridApi = params.api;
}
getDropDownlist(){
this.service.getDealsList().subscribe(data => this.rowData = data);
}
makeCellClicked(event) {
console.log(event.data);
}
ngOnInit() {
this.service.getDealsList().subscribe(data => {
this.rowData = data;
});
}
}
```
I'm blocked and i do really appreciate your help guys.
Thank you! | 2020/06/20 | [
"https://Stackoverflow.com/questions/62487263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13095163/"
] | You need to convert your index to datetime
```
df.index=pd.to_datetime(df.index)
``` | ```
import pandas as pd
df.index = df.index.astype('datetime64[ns]')
df_train = df[(df.index > '2017-01-01') & (df.index < '2020-04-01')]
df_test = df[df.index > '2020-04-01']
``` |
4,065 | At our University, we have in the first semester a very difficult C Introductory Course, that consists of presenting a shortened version of the language specification: What are for/while loops, if clause, what is a pointer and so on.
But they never show how good C code in a more complicated application should look. What version control is, what [Valgrind](https://valgrind.org) is (a gnu tool for detecting memory leaks) and so on.
For the many new (about 60%) to programming or C, the group projects are quite a knockout (about 40%).
Some motivated students and I decided to offer a "best practices" session before the first assignment is handed out and after the lecture has finished.
For the students to have a better chance of finishing this course successfully.
Our selected Chapters are these:
* how to compile (clang and gcc and their flags and warnings)
* valgrind
* make
* coding style
+ best practices -> how to allocate memory, typedefs, file operations
+ basic program flow, some simple patterns
* git
* pitfalls specific to this course and C in general
* how to ask the right question (and in turn how to google their problems)
* how to use the manpage
Are there points missing? Is there something that we shouldn't do?
In short, how to improve the content. We are planning on 3 Sessions with around 3 hours each. | 2017/12/21 | [
"https://cseducators.stackexchange.com/questions/4065",
"https://cseducators.stackexchange.com",
"https://cseducators.stackexchange.com/users/1868/"
] | Too much, too fast
------------------
"First semester". If I parse correctly, you say 60% students are **new to programming**.
You say "The following points knock them out: they don't know how to test, they don't know how to check for memory leaks, they have no concept of encapsulating". And you say "group assignments".
Taken together, it looks like this course is "introductory" only in this sense it will introduce part of students to the idea that this university doesn't want to teach them (programming or even teach them how to learn programming), but it wants to filter them out.
You cannot change that fact. You cannot help everyone, you can help some.
Either you want:
* to help programmers to become better
* to help some non-programmers to become programmers (will work 10% of the time in your setting)
* to help all non-programmers to learn a bit, but probably not enough to let them pass
Presently your mini-course is a big mish-mash. Come on: someone needs to be informed how to google stuff? Really? And the next minute you talk about git? To help who, in what way...? Don't waste everyone's time, narrow it down:
* to help programmers to become better
+ valgrind
+ coding style
- best practices -> how to allocate memory, typedefs, file operations
- basic program flow, some simple patterns
+ git
+ pitfalls in general
* to help some non-programmers to become programmers (will work 10% of the time in your setting)
+ you want to give them ready-made stuff; their heads are bound to explode, the more boilerplate you give them, the less the explosion
- make
* boilerplate gcc flags included, etc
- pitfalls specific to this course
- the rest will come later (i.e. someday they will decide they need to improve on memory handling - but not today for sure, someday they will decide to migrate version control out of their Facebook - not today)
* to help all non-programmers to learn a bit, but probably not enough to let them pass
+ "how to google their problems"
+ "how to use the manpage" | if they are new to programming start with flip-flops. I usually refer to Lombardi's "This year, we are going to start from the beginning. This, gentleman, is a football". It makes it funnier when they are British.
You can delete this answer as I don't have comment permissions.
```
debian
eclipse-cdt
svn/git
cmake
jenkins
unit test
```
250,000 lines of code is more reasonable than 800. Also, if you need to add a comment to code it means that the code is unintelligible.
Edit:
As requested in the comment. I think starting with a brief introduction to electrical engineering and discreet mathematics is appropriate in an introductory programming course. The list above is not complete or accurate, but it's something that can be setup in a day and increases the productivity of other programming tasks that are part of your lesson.
Also, implementing strcpy is a good task for anyone from an arts background. |
47,964,186 | Say you have a function `f:integers -> integers`, one should be able to lift this function to act on sets of integers.
I.e. `f:sets of integers -> sets of integers`, by `f({a,b,...}) = {f(a),f(b),...}`
How can one do this succinctly in python? That is, not involving iterables (loops), potentially something more native and order-independent.
I would expect `f({a,b,...})` to be the syntax, but it's not. Maybe something like `act(f,{a,b,...})`? | 2017/12/24 | [
"https://Stackoverflow.com/questions/47964186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9137341/"
] | You can pass multiple arguments as well , like this:
```
def square(*args) :
l = []
for i in args:
l.append(i**2)
return l
```
It'll return like:
```
>>>> square(1,2,3,4)
>>>> [1,2,9,16]
>>>> square(1)
>>>> [1]
>>>> square(1,6)
>>>> [1,36]
``` | ```
from funcy import curry
def lift(fn):
return curry(map)(fn)
``` |
448,136 | Out of interest, I'm looking for the word describing the usual cap of detergent for manual dish-washing. It consists of two parts which can be moved relatively to each other in vertical orientation so that pull up opens the bottle and pushing down closes it. The bottle is then turned upside-down and the detergent can be dosed.
A soap dispenser [for liquid soap] is different from what I'm searching since it requires a push (usually vertical) to press out the next portion.
That being said, I'm only speculating that a specific word for it exists. I'd use dish-washing detergent cap if I'd be force to make a choice.
I stumbled over this before asking a question on chemistry.SE about the condensation rate of detergent in a bottle with such a cap, i.e. an example sentence is "What would be an appropriate estimate for the condensation rate of dish-washing detergent in a bottle closed with a X" (I'll clarify the context in the chemistry.SE question, of course). I'm aware that it's not necessary to know the word to ask the question there. | 2018/05/28 | [
"https://english.stackexchange.com/questions/448136",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/137985/"
] | [](https://i.stack.imgur.com/kXtwL.jpg)
According to [numerous sources](https://www.google.de/search?q=push-pull%20cap&rlz=1C9BKJA_enDE701DE701&hl=de&prmd=sivn&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjLkYmYlqnbAhVIMJoKHa9pCuEQ_AUIEigC&biw=1024&bih=748), a cap of this design is a *push pull cap*, without a hyphen. | Generally call it **push / pull cap** |
17,175 | Most recipes that call for Bisquick have volume measurements, but I've read it's better to measure most dry ingredients by mass (not to mention more convenient and less messy). So what is the proper conversion factor for Bisquick (i.e. it's density)?
I assume it's close to that of flour, but [different types of flours have different densities](http://www.traditionaloven.com/conversions_of_measures/flour_volume_weight.html) and I wasn't sure which one to use or which one the Bisquick manufacturers assume when developing their recipes. | 2011/08/27 | [
"https://cooking.stackexchange.com/questions/17175",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/6328/"
] | My recipes with buisquick work just fine and I generally find that 4 cups of buisquick weigh 500 g. | I sifted the bisquick and them measured very carefully one cup--on my electronic scale (caliberated of course) the weight was 4 ounces. I repeated this three times with the same results. |
239,826 | I'm trying to settle a debate with my girlfriend. She says "how quicker" is incorrect and you should always use "how much quicker".
Which of these is [more?] correct?
>
> See how quicker the cars flow into the city than out of the city.
>
>
>
Or
>
> See how much quicker the cars flow into the city than out of the city.
>
>
>
I can't find a definitive source. But Googling indicates the former is less common (5,300 results) than the latter (320,000 results). But most of the hits for "how quicker" are in Google Books, especially texts from the early 20th century.
Could this just be an archaism? Has the grammar changed? I'm assuming those old books were lectored. | 2015/04/16 | [
"https://english.stackexchange.com/questions/239826",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/2929/"
] | The correct sentence is definitely:
* "See how much quicker the cars flow into the city..."
Unfortunately the presence of a structure on teh intarweb doesn't mean it is correct, and in this case most of the hits for "how quicker" are for constructs like "See how quicker response can help you...", which is an entirely different construct. | Actually, I'm afraid both of you are wrong. The correct version is "See how much more quickly the cars flow into the city than out of the city."
The base word is "quick" - fast, or speedy. The normal adjectival construction uses "-er", and the normal adverbial construction is "-ly".
So "quicker" is an adjective, and "quickly" is an adverb (and both already exist).
The word being modified is "flow", a verb, so the adverb "quickly" should be used.
However, of the two choices presented, your girlfriend's is closer to correct. In careless speech, the adjective is often used, since the next possible subject is "cars". In this case, "how quicker the cars" is not remotely likely, but "how much quicker the cars" is at least close. |
46,266,458 | I was wondering when I worked on a project if I could achieve this, but assuming it does not seem currently possible to get this behavior without any change of structure (I would really like to keep the hover inside its own class declaration), to you, what would be the cleanest solution ?
**LESS**
```
@blue: blue;
@blue-darker: darken(@blue, 20%);
.text-blue {
color: @blue;
/* something like that */
&:hover when (element_reference == hyperlink) {
color: @blue-darker;
}
}
```
**CSS**
```
.text-blue {
color: blue;
}
/* something like that */
a.text-blue:hover {
color: #000099;
}
```
**HTML**
```
<p class="text-blue">Text in blue with no hover effect</p>
<a class="text-blue" href="#">Link in blue with hover effect</a>
``` | 2017/09/17 | [
"https://Stackoverflow.com/questions/46266458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2480215/"
] | This should do what you want:
```
.text-blue {
color: @blue;
a&:hover {
color: @blue-darker;
}
}
```
[Fiddle](http://jsfiddle.net/d39f2ps5/) | I would use a `:link` CSS pseudoclass, because `<a>` without `href` is not treated as a hyperlink. See at <https://jsfiddle.net/jsqdom1s/>
```
.text-blue {
color: @blue;
a&:link:hover {
color: @blue-darker;
}
}
``` |
25,730,192 | I'm looking for a script that can extract the line with the highest latency hop from a traceroute. Ideally it would look at the max or avg of the 3 values by line. How can I so that?
This is what I tried so far:
```
traceroute www.google.com | awk '{printf "%s\t%s\n", $2, $3+$4+$5; }' | sort -rgk2 | head -n1
traceroute -w10 www.google.com | awk '{printf "%s\t%s\n", $2, ($3+$4+$5)/3; }' | sort -rgk2 | head -n1
```
It seemed a step in the right direction, except some of the values coming back from a traceroute are \*, so both the sum and the average provide a wrong value.
**Update**
Got one step further:
```
traceroute www.cnn.com | awk '{count = 0;sum = 0;for (i=3; i<6; i++){ if ($i != "*") {sum += $i;count++;}}; printf "%s\t%s\t%s\t%s\n", $2, count, sum, sum/count }' | sort -rgk2
```
now need to intercept if I dont' have a column 4,5. Sometimes traceroute only provides 3 stars like this:
```
17 207.88.13.153 235.649ms 234.864ms 239.316ms
18 * * *
``` | 2014/09/08 | [
"https://Stackoverflow.com/questions/25730192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131021/"
] | Try:
```
$ traceroute 8.8.8.8 | awk ' BEGIN { FPAT="[0-9]+\\.[0-9]{3} ms" }
/[\\* ]{3}/ {next}
NR>1 {
for (i=1;i<4;i++) {gsub("*","5000.00 ms",$i)}
av = (gensub(" ms","",1,$1) + gensub(" ms","",1,$2) + gensub(" ms","",1,$3))/3
if (av > worst) {
ln = $0
worst = av
}
}
ND { print "Highest:", ln, " Average:", worst, "ms"}'
```
which gives:
```
Highest: 6 72.14.242.166 (72.14.242.166) 7.383 ms 72.14.232.134 (72.14.232.134) 7.865 ms 7.768 ms Average: 7.672 ms
```
If there are three asterix (asteri?) `* * *` the script assumes that the hop isn't responding with the IGMP response and ignores it completely. If there are one or two `*` in a line, it gives them the value of 5.0 seconds. | Stephan, you could try and use pchar a derivative of pathchar. It should be in the Ubuntu repository.
I takes a while to run though so you need some patience. It will show you throughput and that will be much better than latency for determining the bottleneck.
<http://www.caida.org/tools/taxonomy/perftaxonomy.xml>
Here is an example:
```
rayd@raydHPEliteBook8440p ~ sudo pchar anddroiddevs.com
pchar to anddroiddevs.com (31.221.38.104) using UDP/IPv4
Using raw socket input
Packet size increments from 32 to 1500 by 32
46 test(s) per repetition
32 repetition(s) per hop
0: 192.168.0.20 (raydHPEliteBook8440p.local)
Partial loss: 0 / 1472 (0%)
Partial char: rtt = 6.553065 ms, (b = 0.000913 ms/B), r2 = 0.241811
stddev rtt = 0.196989, stddev b = 0.000244
Partial queueing: avg = 0.012648 ms (13848 bytes)
Hop char: rtt = 6.553065 ms, bw = 8759.575088 Kbps
Hop queueing: avg = 0.012648 ms (13848 bytes)
1: 80.5.69.1 (cpc2-glfd6-2-0-gw.6-2.cable.virginm.net)
``` |
12,885,037 | I'm trying to extract a string from an url. The URL can either be:
```
http://page.de/s/project.html?id=1
```
or
```
http://page.de/s/project.html?id=1/#/s/project.html?id=x
```
I need to extract the last `?id=-value` but I can't get it to go. This is what I have:
```
url_snip = key.replace("?id=","")
```
which only works for the first URL.
**Question:**
Is there a `regexp` or method to get the last id value no matter whats the URL?
Thanks! | 2012/10/14 | [
"https://Stackoverflow.com/questions/12885037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536768/"
] | You can use `enumerate` function, which accepts a list (`orig_list`) and return list of pairs, in which first element is index of item in `orig_list` and second element - that item from `orig_list`.
Example:
```
orig_list = numpy.array([0.0, 35., 2., 44., numpy.pi, numpy.sqrt(2.)])
filter_func = lambda (idx, value): value<4.
filtered_pairs = filter(filter_func, enumerate(orig_list))
result = map(lambda (idx, value): idx, filtered_pairs)
```
You also can replace id extractor with stdlib function `itemgetter` (module operator):
```
from operator import itemgetter
orig_list = numpy.array([0.0, 35., 2., 44., numpy.pi, numpy.sqrt(2.)])
filter_func = lambda (idx, value): value<4.
result = map(itemgetter(0), filter(filter_func, enumerate(orig_list)))
``` | ```
>>> def some_sort_of_f(data, condition = lambda x: x<4.):
rez=[]
for i in range(len(data)):
if condition(data[i]):
rez.append(i)
return rez
>>> data = [0.0, 35., 2., 44.]
>>> some_sort_of_f(data)
[0, 2]
>>>
``` |
19,626,893 | I'm using VS 2013 RTM Ultimate, and when I try to add a Controller to my MVC 5 project I get the following error:
"There was an error running the selected code generator: 'The Parameter searchFolders does not contain any entries. Provide at least one folder to search files.'
None of the scaffolders work basically, all giving the same error... Tried rebuidling / clean etc and still get error.
**Update Oct 28:**
Looks like it is a problem with having T4Scaffolding installed. Looks like they are working on a fix. | 2013/10/28 | [
"https://Stackoverflow.com/questions/19626893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/469736/"
] | If you have recently installed a package with T4Scaffolding dependency (ex. MVCMailer uses T4Scaffolding.Core),
then you can uninstall T4Scaffolding.Core and restart VS 2013. Notice that MvcMailer which caused this in my case, won't work in 2013. Best is to check your references or packages for suspects.
**From comments:**
Uninstalling it didn't seem to work for me, so ***I deleted packages/T4Scaffolding* from the disk\*** and then it worked. **(*by Jared Thirsk*)** | My solution was to open VS installer, then go to modify and install .net framework templates |
20,607,296 | I need to check if a parameter (either string or int or float) is a "large" integer. By "large integer" I mean that it doesn't have decimal places and can exceed `PHP_INT_MAX`. It's used as msec timestamp, internally represented as float.
`ctype_digit` comes to mind but enforces string type. `is_int` as secondary check is limited to `PHP_INT_MAX` range and `is_numeric` will accept floats with decimal places which is what I don't want.
Is it safe to rely on something like this or is there a better method:
```
if (is_numeric($val) && $val == floor($val)) {
return (double) $val;
}
else ...
``` | 2013/12/16 | [
"https://Stackoverflow.com/questions/20607296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608395/"
] | I recommend the binary calculator as it does not care about length and max bytes. It converts your "integer" to a binary string and does all calculations that way.
BC math lib is the only reliable way to do RSA key generation/encryption in PHP, and so it can easy handle your requirement:
```
$userNumber = '1233333333333333333333333333333333333333312412412412';
if (bccomp($userNumber, PHP_INT_MAX, 0) === 1) {
// $userNumber is greater than INT MAX
}
```
Third parameter is the number of floating digits. | ```
function isInteger($var)
{
if (is_int($var)) {
return true;
} elseif (is_numeric($var)) {
// will throw warning
if (!gmp_init($var)) {
return false;
} elseif (gmp_cmp($var, PHP_INT_MAX) >0) {
return true;
} else {
return floor($var) == $var;
}
}
return false;
}
``` |
4,041,469 | I need to simplify $z^2+i=0$ and find all solutions for $z$. I have seen that the solutions to $z=\sqrt{i}=\left(\frac{1}{\sqrt{2}}+i\frac{1}{\sqrt{2}}\right)$ and $\left(-\frac{1}{\sqrt{2}}-i\frac{1}{\sqrt{2}}\right)$. I was hoping to find a similar solution for $z=\sqrt{-i}\,$ but my attempt gives me $z=\pm i^{\frac{3}{2}}$
$$z=re^{i\theta} \,\,\& \,\, e^{i\pi}=-1 $$
then,
$$(re^{i\theta})^2=-i\\r^2e^{i2\theta}=ie^{i\pi+k(2\pi)}$$ where $k\in\mathbb{Z}$.
So, we have $\begin{cases} r^2=i \,\,\,\therefore r=\sqrt{i}\\ \theta=k\pi
\end{cases}$
Then, $$z\_k=\sqrt{i} \, e^{i\left(\frac{\pi}{2}+k\pi\right)}$$
$$z\_0=\sqrt{i}\left(\cos\frac{\pi}{2}+i\sin\frac{\pi}{2}\right)=i^\frac{3}{2}\\
z\_1=\sqrt{i}\left(\cos(\frac{\pi}{2}+1)+i(\sin\frac{\pi}{2}+1)\right)=-i^\frac{3}{2}$$
I realized that this is literally the same as just solving $z=\sqrt{-i}=i\sqrt{i}=i^\frac{3}{2}$, however, I was hoping to find a solution of the form $x+iy$. I am not sure how to go about this problem a different way. | 2021/02/27 | [
"https://math.stackexchange.com/questions/4041469",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/864339/"
] | Here it is another solution for the sake of curiosity.
Let $z = x + yi$, where $x,y \in \mathbb{R}$. Then we have the following equation:
\begin{align\*}
z^{2} + i = 0 & \Longleftrightarrow (x+yi)^{2} = x^{2} - y^{2} + 2xyi = -i\\\\
& \Longleftrightarrow
\begin{cases}
x^{2} - y^{2} = 0\\\\
2xy = -1
\end{cases}\\\\
& \Longleftrightarrow
\begin{cases}
x = -y\\\\
2y^{2} = 1\\
\end{cases}\\\\
& \Longleftrightarrow
\begin{cases}
x = -\dfrac{1}{\sqrt{2}}\\\\
y = +\dfrac{1}{\sqrt{2}}
\end{cases};
\begin{cases}
x = +\dfrac{1}{\sqrt{2}}\\\\
y = -\dfrac{1}{\sqrt{2}}
\end{cases}
\end{align\*}
Hopefully this helps! | >
> I was hoping to find a similar solution for z=−i−−√ but my attempt gives me z=±i32
>
>
>
I don't see why.
$z = x+yi$ and $z^2 = (x^2 -y^2) + 2xyi = -i$ so $x^2-y^2 = 1$ and $2xy = -1$ so $x^2 =y^2$ and $x = \pm |y|$ but $2xy =-1$ is negative os $x = -y$ and so $2xy=-1\implies -2y^2 = 1\implies y =\pm \frac 1{\sqrt 2}$ and $x = \mp \frac 1{\sqrt 2}$. and $z = \pm \frac 1{\sqrt 2} \mp \frac 1{\sqrt 2} i$.
Which shouldn't *surprise* us as if $(\pm \frac 1{\sqrt 2} \pm \frac 1{\sqrt 2} i)^2 = i$ then $i(\pm \frac 1{\sqrt 2} \pm \frac 1{\sqrt 2} i) = \pm \frac 1{\sqrt 2}i \mp \frac 1{\sqrt 2} =\mp \frac 1{\sqrt 2} \pm \frac 1{\sqrt 2}$ when squared should be $i^2\*i = -i$.
===
Using polar coordidates $-i = 0 + (-1)i = \cos \frac {3\pi}2 +\sin(\frac {3\pi}2)i = e^{(\frac {3\pi}2 + 2k\pi)i}$ and so the square roots of $-i$ are
$e^{(\frac {3\pi}4 + k\pi)i} = \cos(\begin{cases}\frac {3\pi}4\\\frac {7\pi}4\end{cases})+\sin(\cos(\begin{cases}\frac {3\pi}4\\\frac {7\pi}4\end{cases}))i =\pm \frac 1{\sqrt 2} \mp \frac 1{\sqrt 2}i$ |
211,515 | I have an API that returns a JSON formatted array of users within a given pair of lat/ long bounds.
I'm using this data to plot a number of markers on a map, based on the location of each user.
I also want to render a HTML list on each client request so that I can show the list of plotted users alongside the map.
What is the best way to get the list HTML to the client?
To me it seems like an incorrect solution to return the HTML for the user list *within* the initial API call (response.html, or something), although this feels like I'm shoe-horning functionality into an otherwise clean API response.
I also don't want to make two API calls (one for the initial data and one for the HTML), for obvious reasons (overhead).
Finally, I don't want to generate the HTML client-side (in JavaScript), as I already have a class to do this for me server-side.
What options does that leave me with?
Thanks | 2013/09/14 | [
"https://softwareengineering.stackexchange.com/questions/211515",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/80183/"
] | Return the data for the list and use client side templating to convert it into HTML.
```
GET http://yourwebserver.com/users.json
[{ name: 'foo'}]
```
using a [Mustache.js](http://mustache.github.io/) template like this
```
Mustache.render('<ul>{{#.}}<li>{{name}}</li>{{/.}}</ul>', data)
```
With this aproach you have a simple interface, reduce data transfer, and make the template static therefore cachable. | REST is a vary adaptive architecture (as I am sure you realize).
The answer to your question I think has more to do with you as a programmer than anything else. For example, there is nothing wrong with the following API call
```
GET http://yourapi.com/users.json
GET http://yourapi.com/users.html
```
These are two different representations of the same resource. Perfectly acceptable in a REST API.
I do however see your point about keeping the API 'clean'. I have a REST API which only outputs json, but I then need to have a client which converts the json to HTML. This could either be another web server or could be done through javascript.
On re-reading your question I can see that you want both a json response and a HTML response with the same API call. The only way you are really going to achieve this is as mentioned in the comments above: use an ajax request to GET the json, and then manipulate the page as required with javascript (i.e. use javascript to update the marker data from json, and the users list) |
9,580,218 | A have an azure webrole with a test page and a service in that role.
After publishing the role it doesn't start automatically, only at first use.
So if the role is shut down for some reason the first usage after that is quite slow.
Is there a way to make webroles start automatically right after they are deployed (either first time, or after a migration)? | 2012/03/06 | [
"https://Stackoverflow.com/questions/9580218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1143406/"
] | Check out the [auto start feature of IIS 7.5](http://www.techbubbles.com/aspnet/auto-start-web-applications-in-aspnet-40/). Make sure you set osFamily="2" for the webrole so that it uses the Windows 2008 R2 OS.
Edit: We're still stuck on osFamily="1" for technical reasons, so we haven't been able to implement auto start functionality yet. However, here are the steps that would be required to setup auto start:
1. Create your own auto start provider that implements the [IProcessHostPreloadClient interface](http://msdn.microsoft.com/en-us/library/system.web.hosting.iprocesshostpreloadclient.aspx). There used to be a default provider called the [Application Warm-Up Module](http://www.iis.net/download/applicationwarmup), but it's not available for download anymore. You can use .Net Reflector to view the contents of the Microsoft.ApplicationServer.Hosting.AutoStart.ApplicationServerAutoStartProvider.dll as an example implementation. This dll is included in Windows *Server* (not Azure) AppFabric.
2. The next step is to specify the correct settings in your applicationHost.config. Some variation of the code listed [here](http://blogs.technet.com/b/meamcs/archive/2011/05/12/writing-an-iis-7-5-auto-start-provider.aspx) can be entered in your RoleEntryPoint class so that it's called when your Azure Role fires up.
Please let the community know if you successfully create your own auto start provider. At this point, there isn't a lot of information about implementing [IProcessHostPreloadClient](http://msdn.microsoft.com/en-us/library/system.web.hosting.iprocesshostpreloadclient.aspx) on the internet. | A role is typically restarted about once a month, for OS maintenance of either the Guest or the underlying Host OS. What you're more likely to see is AppPool timeout due to inactivity, which will exhibit the same type of initial-hit delay. The default timeout is 20 minutes. You can change the timeout via elevated startup script, with something like:
```
%windir%\system32\inetsrv\appcmd set config -section:applicationPools -applicationPoolDefaults.processModel.idleTimeout:00:00:00
```
I discussed this in [another SO question](https://stackoverflow.com/a/9305417/272109) as well. |
11,755,248 | I'm trying to authenticate a user using AJAX wrapped with jQuery to call a PHP script that queries a MySQL database. I'm NOT familiar with *any* of those technologies but I (sorta) managed to get them working individually, but I can't get the jQuery, AJAX and HTML to work properly.
**[Edit:]** I followed [Trinh Hoang Nhu's](https://stackoverflow.com/users/533738/trinh-hoang-nhu) [advice](https://stackoverflow.com/questions/11755248/authenicating-user-using-jquery-ajax-not-working#comment-15607048) and added a `return false;` statement to disable the Submit button. All previous errors fixed, I can't get the object returned by the AJAX right.
HTML
----
Here's the HTML snippet I use:
```
<form id="form" method='post'>
<label>Username:</label>
<input id="user" name="user" type="text" maxlength="30" required /> <br />
<label>Password:</label>
<input id="pass" name="pass" type="password" maxlength="30" required /> <br />
<input id="url" name="url" type="text" value="<?php echo $_GET['url'] ?>" hidden />
<input name="submit" type="submit" value="I'm done">
</form>
```
jQuery/AJAX
-----------
Here's my jquery code for using AJAX to authenticate a user (sorry if the indenting is messed up because of the tabs):
```
function changeMessage(message) {
document.getElementById("message").innerHTML = message; }
$(document).ready(function() {
$("#form").submit(function() {
changeMessage("Checking");
//check the username exists or not from ajax
$.post("/stufftothink/php/AJAX/login.php",
{user: $("#user").val(), pass: $("#pass").val(), url: $("#url") },
function(result) {
//if failed
if (result === 'false') {
changeMessage("Invalid username or password. Check for typos and try again");
$("#pass").val(""); }
//if authenticated
else {
changeMessage("Authenticated");
window.location.href = result; }
} );
//to disable the submit button
return false;
} );
} )
```
PHP
---
And here's my PHP script that gets called:
```
<?php
ob_start();
session_start();
$user = $_POST['user'];
$pass = md5($_POST['pass']);
mysql_connect('localhost', 'root', '');
mysql_select_db('stufftothink');
$query = "select * from users where user = '$user' and pass = '$pass'";
$result = mysql_query($query);
$i = 0;
while ($row = mysql_fetch_array($result)) {
$i = 1; }
if ($i == 1) {
$_SESSION['user'] = $user;
$invalid_urls = array('register.php', 'login.php');
$url = $_REQUEST['url']; //not sure whether _GET or _POST
if (in_array($url, $invalid_urls)) {
echo '/stufftothink/profile.php'; }
else {
echo '/stufftothink/'.$url; }
}
else {
echo 'false'; }
mysql_close();
?>
```
Edit
----
I've been getting a lot of downvotes on this question. I had accidentally submitted the question without the explanation filled in. I went back to edit it, but when I came back, there were already 4 downvotes. It had barely been a couple of minutes. Am I doing something wrong, or were the first 5 minutes the problem? | 2012/08/01 | [
"https://Stackoverflow.com/questions/11755248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1292652/"
] | First if you want to submit form using ajax, you must `return false` from your submit function. Otherwise your browser will handle it and redirect you to another page.
If you want to return an object from PHP, you must convert it to json using `json_encode`,
for example:
```
//PHP
$return = array("url" => "http://www.google.com");
echo json_encode($return);
//would echo something like {"url":"http://www.google.com"}
//JS
$.post(url, data, function(data){
alert(data.url);
});
``` | You have no ending `;`'s on functions.
Should be:
```
function changeMessage(message) {
document.getElementById("message").innerHTML = message;
};
$(document).ready(function() {
$("#form").submit(function() {
changeMessage("Checking");
//check the username exists or not from ajax
$.post("/stufftothink/php/AJAX/login.php",
{user: $("#user").val(), pass:$("#pass").val() },
function(result) {
//if failed
if (result === 'false') {
changeMessage("Invalid username or password. Check for typos and try again");
$("#pass").val("");
}
//if authenticated
else {
changeMessage("Authenticatred");
window.location.href = "/stufftothink/" + result;
}
});
});
});
```
Not sure if that'll fix it, but it's the only thing that jumps out at me. |
7,127,308 | I have webservice(WCF) and MembershipProvider/RoleProvider to check credentials.
When service called - various methods call providers to get user, get login name by Id, get Id by login name and so on. End result - When looking in Profiler - I can see lot of chat.
I can easily incorporate caching into MembershipProvider and RoleProvider's so it will cache user's and won't hit DB every time.
User list is not big. I don't think it will ever be more than 100-200.
On one hand - I know SQL Server does cache small tables and designed to take care of those selects. OTOH - I SEE it in profiler :) And memory on web server side will be occupied. Plus, lookups on web server still need to be done (CPU/Memory).
I guess I want to hear about your experience and should I even worry about this stuff? I placed tags "strategically" so hopefully both DBA and developers will give me some input :) | 2011/08/19 | [
"https://Stackoverflow.com/questions/7127308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/509600/"
] | Absolutely, avoiding a round trip to the DB server pays off. Is not only the memory cache issue. Running a query, even a trivial one, is quite a complex process:
* the connection has to be opened and authenticated. It gets amortized with connection pooling, true, but even a pooled connection still requires one extra roundtrip for [`sp_reset_connection`](https://stackoverflow.com/questions/596365/what-does-sp-reset-connection-do) at open time.
* request has to be composed and sent to the server
* a task needs to be allocated for the request and a worker has to pick up the task. workers are very precious resource in SQL Server, as there are [so few of them](http://msdn.microsoft.com/en-us/library/ms187024.aspx).
* SQL has to parse your query. At the very very best it can skip the parsing but still needs to hash the input text, see [Dynamically created SQL vs Parameters in SQL Server](https://stackoverflow.com/questions/1608522/dynamically-created-sql-vs-parameters-in-sql-server/1608856#1608856)
* query has to be executed, locks acquired, pages in memory looked up. Locking is especially expensive because it may conflict with other operation and has to wait. Using [snapshot isolation](http://msdn.microsoft.com/en-us/library/tcbchxcb%28v=vs.80%29.aspx) can help to some (large) extent.
* the result has to be marshaled back to client.
* client has to parse the response metadata.
* client has to process the response.
An local in memory lookup will win most times. Even a remote cache lookup like [memcached](http://memcached.org/) will win over a DB query, no matter how trivial the query. So why not always cache locally? Because of the one of the most hard problems in CS: cache coherency and invalidation. It is a problem that is *way* harder than you think it is right now, no matter how hard you think it is ;). You may look at SQL Server's own active cache invalidation solution, [Query Notifications](http://msdn.microsoft.com/en-us/library/ms130764.aspx), which works pretty well for fairly static result sets. I have a LINQ integration with Query Notification project myself, [LinqToCache](http://code.google.com/p/linqtocache/). | Depends. What happens when you want to delete or disable a user's account and have the change take effect immediately?
You need to make sure that all modifications to user accounts are always reflected in the cache on all of your web servers. But ultimately, it is quite likely that avoiding the network IO (which is what would really slow you down), while not noticeable to an individual, would make a slight difference over hitting the DB each time.
Chances are though, it isn't worth it. |
6,830,116 | I just started learning Ruby coming from Java. In Java you would use packages for a bigger projects. Is there anything equivalent to that in Ruby? Or what is the best way to achieve a package like setting?
The way I'm doing it right now is 'load'ing all the needed class into my new Ruby file. Isn't there a way to tell my current Ruby class to use all other Ruby classes in the same folder?
Cheers,
Mike | 2011/07/26 | [
"https://Stackoverflow.com/questions/6830116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/863451/"
] | There's three kinds of package loading in Ruby:
* Explicitly loading a library with `require`
* Implicitly loading a library using `autoload`
* Importing a library with `gem`
The `require` method is the most direct and has the effect of loading in and executing that particular file. Since that file may go on to `require` others, as a matter of convenience, you may end up loading in quite a lot at once.
The `autoload` method declares a module that will be loaded if you reference a given symbol. This is a common method to avoid loading things that you don't need, but making them automatically available if you do. Most large libraries use this method of loading to avoid dumping every single class into memory at once.
The `gem` approach is a more formalized way of packaging up a library. Although it is uncommon for applications to be split up into one or more gems, it is possible and provides some advantages. There's no obligation to publish a `gem` as open-source, you can keep it private and distribute it through your own channels, either a private web site or `git` repository, for instance, or simply copy and install the `.gem` file as required.
That being said, if you want to make a library that automatically loads a bunch of things, you might take this approach:
```
# lib/example.rb
Dir.glob(File.expand_path('example/**/*.rb', File.dirname(__FILE__))).each do |file|
require file
end
```
This would load all the `.rb` files in `lib/example` when you call `require 'example'`. | You probably want to use `require` rather than load, since it should take care of circular references.
If you want to grab all the files in a given folder, that's easy enough:
```
Dir.foreach("lib"){|x| require x}
```
Your other option is to have a file that manually requires everything, and have your other files require that.
You should also look at wrapping the code in your libraries with a `module` block, to give them their own namespaces.
That said: rightly or wrongly, I tend to feel that this is the one area -- perhaps the only one -- where Ruby is less powerful than Python, say, or Java. |
73,600,074 | I want to start by saying that I am a teacher and have very little experience coding. I only have a cursory understanding of how to manipulate cell values in pre-existing code. I created a spreadsheet for my school district to help teachers streamline the creation of student progress reports. On the .xlsm file I used the following code to auto-populate tab names based on the contents of cell "b1" in the same tab. I found this code on a forum. It worked well for a few years, but suddenly this year the code does not work. The code fails and displays the message box delineated in the vba code that the source cell contains illegal characters:
```
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
Set Target = Range("b1")
If Target = "" Then Exit Sub
On Error GoTo Badname
ActiveSheet.Name = Left(Target, 31)
Exit Sub
Badname:
MsgBox "Please revise the entry in b1." & Chr(13) _
& "It appears to contain one or more " & Chr(13) _
& "illegal characters." & Chr(13)
Range("b1").Activate
End Sub
```
Can this code be fixed? Does excel offer other means to auto-populate tab names from cell values? In case it matters, the cell that I am using as the source for the tab name contains the formula `='class list'!B5`. It pulls the desired source text from a different tab and the goal is to have the text that is transferred via the formula to be the source of the tab's name. Is there a way to modify the VBA code to pull the value directly from the source tab? I could understand if it is the formula in "b1" that is causing the problem? But it is a mystery to me why, after working for several previous years, the problem is only now manifesting...
One other issue with this VBA code is that it required the user to interact with the cells in the tab before the VBA code would run and change the tab name. Could the code be made to change the tab name as soon as the source cell value changes? Though not strictly necessary this would be a big quality of life improvement.
Thank you so much for your consideration,
Eric | 2022/09/04 | [
"https://Stackoverflow.com/questions/73600074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19916353/"
] | >
> Is there a way to add/download that branch and add it to my repository, so that I can try it out?
>
>
>
Sure! First, add a [remote](https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes) to your local repository pointing at the fork. E.g., if you repository was named `example` and I had forked it, you would run:
```
git remote add larsks https://github.com/larsks/example
```
That command creates a remote named `larsks` pointing at my fork (you can name the remote anything you want, but I usually use the github username). Now, update the local cache for that remote:
```
git remote update
```
And now you can see branches in that fork and check them out locally. To access my `main` branch, you would run:
```
git checkout larsks/main
```
Or to access my `feature1` branch:
```
git checkout larsks/feature1
```
Etc. Note that the above commands will put you in a "detached head" state; to check out a local branch based on one of those branches you might run something like:
```
git checkout -b feature1 larsks/feature1
``` | TL;DR
=====
* run `git remote add`
* run `git fetch`
* profit!
Long
====
The bottom line is that you need to copy their *commits*. You do not need to copy their "branch" unless, by the word "branch", you mean "the set of commits in question".
>
> ... without having to clone the repository
>
>
>
The act of copying commits *is* "cloning". Or is it? The word isn't all that well defined: when we clone a repository, we copy all of its commits—or at least, all of the ones we want to copy: those that we care about and are new to us.
The `git clone` *command*, on the other hand, means:
* make a new empty repository;
* add a *remote* (a short name by which we'll contact some other Git repository, probably repeatedly, in the future);
* copy their commits; and
* create an initial branch name, since working without a branch name is no fun.
(Git doesn't actually *need* any branch names at all, but see "no fun".) So you don't want to run `git clone`, because you don't want step 1 here: you want to use your existing repository. But you do want steps 2 and 3, and then you may or may not want a variation on the last step.
Fortunately, we have:
* `git remote add`: this is how we add a *remote* to a repository, and in fact, `git clone` essentially uses `git remote add` to set up `origin` so that you can run `git fetch origin`; and
* `git fetch *remote*`: this is how we copy some other repository's commits, or at least, those that we find interesting and are new to us.
The `git pull` command, if you use it—I recommend *avoiding* it, especially if you're new to Git—consists of running `git fetch` followed by running a second Git command, to do something with the just-fetched commits if any. Split this up into the two separate commands so that you will learn and understand each of the two steps, and thereby profit (see the TL;DR section).
The `git fetch` command calls up one specific remote, using the URL saved during `git remote add`. Your Git software and their Git software—"they" being whoever answers at that URL—converse, to figure out which commits you have and which ones they have. Then your Git software downloads the *new-to-you* commits. When we run `git clone`, *all* the commits are new to us, so we get them all, but when we run `git fetch`, we get a much more limited set, which goes a lot faster.
Once you have *more than one remote*, things get a little trickier than when you have just one. The `git fetch` command needs to know *which remote to use*. If you run it without any arguments, it guesses. If all else fails it just guesses `origin`, which is the standard First Name For A Remote.
Running `git remote update` tells your Git software to run `git fetch` to *all* remotes. More precisely, it fetches from a defined set of remotes, or a group, but the default here is "all". You can do the same with `git fetch --all`: the `--all` here means *all remotes*.
As for branch names: Git uses these to help you (and Git) find your own commits. When you fetch from some *other* repository, Git creates or updates names in your own repository that I call *remote-tracking names*. These are not branch names—even though Git calls them *remote-tracking branch names*, they don't work the way branch names work. But you'll want one if you're going to make any new commits of your own.
When you run, e.g.:
```
git checkout foobranch # or git switch foobranch
```
and there is no branch named `foobranch` in *your* set of branches, your own Git software would—and will if you add `--no-guess` here—complain that there is no `foobranch`, and just fail. But if you let Git use `--guess`, which is the default setting, your Git will scan your *remote-tracking names*, to look for `origin/foobranch` and—if there's a `remote2`—`remote2/foobranch` and so on. **If it finds exactly one match** it will "guess" that you meant *create a new branch with name `foobranch` using the commit found by the remote-tracking name*.
Once you have *two* remotes, this guess mode stops working so well. Just be aware of this. |
1,828,999 | How can I solve
$$\begin{cases}
\sin^2(y\_1) = \frac{1}{2}\sin^2(\frac{y\_1+y\_2}{2})\\
\sin^2(y\_2) = \frac{1}{2}(\sin^2(\frac{y\_1+y\_2}{2})+1)
\end{cases}$$
where $$\space y\_1,y\_2 \in [0,\frac{\pi}{2}] $$
Thanks a lot! | 2016/06/16 | [
"https://math.stackexchange.com/questions/1828999",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/348263/"
] | $\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle}
\newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
\newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
\newcommand{\dd}{\mathrm{d}}
\newcommand{\ds}[1]{\displaystyle{#1}}
\newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
\newcommand{\half}{{1 \over 2}}
\newcommand{\ic}{\mathrm{i}}
\newcommand{\iff}{\Leftrightarrow}
\newcommand{\imp}{\Longrightarrow}
\newcommand{\ol}[1]{\overline{#1}}
\newcommand{\pars}[1]{\left(\,{#1}\,\right)}
\newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
\newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
\newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
\newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\color{#f00}{I} & =
\int\_{0}^{\infty}\expo{-2x}\ln\pars{1 + \expo{-x} \over 1 - \expo{-x}}\,\dd x =
2\int\_{0}^{\infty}\expo{-2x}\,\mathrm{arctanh}\pars{\expo{-x}}\,\dd x
\\[3mm] & =
2\int\_{0}^{\infty}\expo{-2x}\,
\sum\_{n = 0}^{\infty}{\expo{-\pars{2n + 1}x} \over 2n + 1}\,\dd x =
2\sum\_{n = 0}^{\infty}{1 \over 2n + 1}
\int\_{0}^{\infty}\expo{-\pars{2n + 3}x}\,\dd x
\\[3mm] & =
\half\sum\_{n = 0}^{\infty}{1 \over \pars{n + 3/2}\pars{n + 1/2}} =
\half\sum\_{n = 0}^{\infty}\pars{{1 \over n + 1/2} - {1 \over n + 3/2}} =
\half\,{1 \over 0 + 1/2} = \color{#f00}{1}
\end{align} | It only comes down to basic high school math$$I=\int\_0^1x\ln\left(\frac{1+x}{1-x}\right)dx=\int\_0^1x\ln(1+x)dx-\int\_0^1x\ln(1-x)$$For the first integral we substitute $u=1+x$ and for the second integral we substitute $v=1-x$ $$=\int\_1^2(x-1)\ln{x}\space dx-\int\_0^1(1-x)\ln x\space dx=\int\_0^2(x-1)\ln x\space dx$$
The only thing left to do is integrate by parts
$$I=\left(\frac{x^2}{2}-x\right)\ln x\Bigg|\_0^2-\int\_0^2\left(\frac{x^2}{2}-x\right)\frac{1}{x}dx=\int\_0^2\left(1-\frac{x}{2}\right)dx=\left(x-\frac{x^2}{4}\right)\Bigg|\_0^2=1$$ |
35,333,336 | I would like to add a shadow effect to my UITextField currently what I'm achieving is this:
[](https://i.stack.imgur.com/kjYUh.png)
As you can see the shadow is not rounded in the corners. My code:
```
mNickname.layer.borderWidth = 1
mNickname.layer.borderColor = UIColor.whiteColor().CGColor
mNickname.layer.cornerRadius = 3
mNickname.layer.masksToBounds = false
mNickname.layer.shadowRadius = 3.0
mNickname.layer.shadowColor = UIColor.blackColor().CGColor
mNickname.layer.shadowOffset = CGSizeMake(1.0, 1.0)
mNickname.layer.shadowOpacity = 1.0
``` | 2016/02/11 | [
"https://Stackoverflow.com/questions/35333336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4760175/"
] | try this, code is in objective C, but same for swift
```
self.textField.layer.shadowColor = [[UIColor blackColor] CGColor];
self.textField.layer.shadowOffset = CGSizeMake(0.0, 1.0);
self.textField.layer.shadowOpacity = 1;
self.textField.layer.shadowRadius = 0.0;
``` | Try to change shadowOpacity to 0.5
Also, could you send full customisation of this textField? |
49,447,175 | Need assistance on a macro which tries to download the extract from SAP system but stops exactly in a place where it need to download. But the same problem doesn't arise when manually done.
Below are the steps which we follow in SAP system:
* In first step, Enter the TCode: ZFIS and do the below selection (Finance New GL >> Line Item Reports >> Cognos Download)
* Enter the required details and execute
* The result needs to be saved in a folder path in txt format
* The problem occurs when it reaches the yellow line code
* Manual saving doesn’t cause any trouble but when try to Run it with coding then the below error appears. Not sure why...
We tried all the possibilities (i.e. checked with our IT dept and tried to install new version of SAP system) but still we are unable to find a solution.
Lastly, I am here to see if I can find a solution for the same.
Attaching the VBA code for your reference:
```
Sub CognosUpload()
Dim SAPApplication
Dim SAPConnection
Dim SAPSession
Dim SAPGuiAuto
Dim StoringPath As Variant
Dim fso As Scripting.FileSystemObject
Dim ts As Scripting.TextStream
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
CurYear = Format(DateSerial(Year(Date), Month(Date) - 1, 1), "YYYY")
Period = Format(DateSerial(Year(Date), Month(Date) - 1, 1), "MM")
MsgBox ("Please select a folder to save all the SAP Extracts.")
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
StoringPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
StoringPath = StoringPath
If StoringPath = "" Then Exit Sub
LastSelectedRow = Cells(Rows.Count, 3).End(xlUp).Row
For i = 3 To LastSelectedRow
If LastSelectedRow = 1 Then
SelectedCode = Cells(3, 3).Value
Else
SelectedCode = Cells(i, 3).Value
End If
With Range("PLANTCODES")
Set Fn = .Cells.Find(What:=SelectedCode, LookIn:=xlValues)
j = Fn.Address
End With
CodeforFilename = Range(j).Offset(0, 1).Value
'ChooseFilename = InputBox("Enter the desired name for the file")
If Not IsObject(SAPApplication) Then
Set SAPGuiAuto = GetObject("SAPGUI")
Set SAPApplication = SAPGuiAuto.GetScriptingEngine
End If
If Not IsObject(SAPConnection) Then
Set SAPConnection = SAPApplication.Children(0)
End If
If Not IsObject(SAPSession) Then
Set SAPSession = SAPConnection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject SAPSession, "on"
WScript.ConnectObject SAPApplication, "on"
End If
SAPSession.findById("wnd[0]").maximize
SAPSession.findById("wnd[0]/tbar[0]/okcd").Text = "/nZFIS"
SAPSession.findById("wnd[0]").sendVKey 0
SAPSession.findById("wnd[0]/usr/lbl[5,3]").SetFocus
SAPSession.findById("wnd[0]/usr/lbl[5,3]").caretPosition = 0
SAPSession.findById("wnd[0]").sendVKey 2
SAPSession.findById("wnd[0]/usr/lbl[9,11]").SetFocus
SAPSession.findById("wnd[0]/usr/lbl[9,11]").caretPosition = 0
SAPSession.findById("wnd[0]").sendVKey 2
SAPSession.findById("wnd[0]/usr/lbl[16,14]").SetFocus
SAPSession.findById("wnd[0]/usr/lbl[16,14]").caretPosition = 4
SAPSession.findById("wnd[0]").sendVKey 2
SAPSession.findById("wnd[0]/tbar[1]/btn[17]").press
SAPSession.findById("wnd[1]/usr/txtV-LOW").Text = "GSA"
SAPSession.findById("wnd[1]/usr/txtENAME-LOW").Text = ""
SAPSession.findById("wnd[1]/usr/txtV-LOW").caretPosition = 7
SAPSession.findById("wnd[1]/tbar[0]/btn[8]").press
SAPSession.findById("wnd[0]/usr/txtP_YEAR").Text = CurYear
SAPSession.findById("wnd[0]/usr/txtP_PERIO").Text = Period
SAPSession.findById("wnd[0]/usr/txtP_PERIO").SetFocus
SAPSession.findById("wnd[0]/usr/txtP_PERIO").caretPosition = 2
SAPSession.findById("wnd[0]/usr/btn%_S_BUKRS_%_APP_%-VALU_PUSH").press
SAPSession.findById("wnd[1]/tbar[0]/btn[16]").press
ThisWorkbook.Sheets(1).Select
Cells(i, 3).Copy
SAPSession.findById("wnd[1]/tbar[0]/btn[24]").press
SAPSession.findById("wnd[1]/tbar[0]/btn[8]").press
SAPSession.findById("wnd[0]/tbar[1]/btn[8]").press
SAPSession.findById("wnd[0]/tbar[1]/btn[45]").press
SAPSession.findById("wnd[1]/tbar[0]/btn[0]").press
SAPSession.findById("wnd[1]/usr/ctxtDY_PATH").Text = StoringPath
SAPSession.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = SelectedCode & ".txt"
SAPSession.findById("wnd[1]/usr/ctxtDY_FILENAME").caretPosition = 9
**SAPSession.findById("wnd[1]/tbar[0]/btn[0]").press**
Sheets(2).Select
InputFolder = (StoringPath & SelectedCode & ".txt")
Set fso = New Scripting.FileSystemObject
Set ts = fso.OpenTextFile(InputFolder)
'Sheets(1).Activate
Range("A:I").Clear
Range("A1").Select
Call ClearTextToColumns
Do Until ts.AtEndOfStream
ActiveCell.Value = ts.ReadLine
ActiveCell.Offset(1, 0).Select
Loop
Columns("A:A").TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="|", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), _
TrailingMinusNumbers:=True
'Range("A:A").Delete shift:=xlToLeft
ts.Close
Set fso = Nothing
Rows("1:1").Delete Shift:=xlUp
Rows("2:2").Delete Shift:=xlUp
Rows("1:1").Font.Bold = True
Columns("A:A").Delete Shift:=xlLeft
Columns("A:G").EntireColumn.AutoFit
If Range("A3").Value = "" Then GoTo Listmsg
MyFileName = "Congnos Download for " & CodeforFilename
sFname = StoringPath & MyFileName & ".csv"
lFnum = FreeFile
'ActiveSheet.UsedRange.Rows
Open sFname For Output As lFnum
'Loop through the rows'
For Each rRow In Sheets("CSV Extract").UsedRange.Rows
'Loop through the cells in the rows'
For Each rCell In rRow.Cells
If rCell.Column = 5 Or rCell.Column = 6 Then
If rCell.Row = 1 Or rCell.Row = 2 Then
sOutput = sOutput & rCell.Value & ";"
Else
sOutput = sOutput & Trim(Round(rCell.Value)) & ";"
End If
Else
sOutput = sOutput & rCell.Value & ";"
End If
Next rCell
'remove the last comma'
sOutput = Left(sOutput, Len(sOutput) - 1)
'write to the file and reinitialize the variables'
Print #lFnum, sOutput
sOutput = ""
Next rRow
'Close the file'
Close lFnum
Sheets(1).Select
Listmsg:
Sheets(1).Select
Next i
Sheets(1).Select
Range("B3").Select
MsgBox "CSV file has been created for you, now you can upload the file in Cognos."
ResetSettings:
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
End Sub
Sub ClearTextToColumns()
On Error Resume Next
If IsEmpty(Range("A1")) Then Range("A1") = "XYZZY"
Range("A1").TextToColumns Destination:=Range("A1"), _
DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=False, _
Comma:=False, _
Space:=False, _
Other:=False, _
OtherChar:=""
If Range("A1") = "XYZZY" Then Range("A1") = ""
If Err.Number <> 0 Then MsgBox Err.Description
End Sub
``` | 2018/03/23 | [
"https://Stackoverflow.com/questions/49447175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8746502/"
] | To check the issue:
1. Go to Visual studio `Preferences >> SDK Location >> Android`
2. Select the Locations tab
Here you will see the Location targeted for each, we are facing issue with JDK.
3. Click on the folder selector so to navigate to the current location been pointed.
4. In my case it was pointing to `"usr/"` folder
5. Check the `"libexec"` folder inside `"usr/"` folder and look for `"Java_Home"`
6. Execute the file `"Java_Home"`, it will give you the location it is pointing toin the terminal window.
In my case it was pointing to `"/Library/Java/JavaVirtualMachines/jdk-10.jdk/Contents/Home"`
Now we know the location our VS is pointing to and we need to change this to required one. in my case `"JDk 1.8"`
7. Click on the folder selector again and navigate to the folder `"/Library/Java/JavaVirtualMachines"`
8. Here navigate to the desired JDK till `"Contents/Home"`.
Make sure once you select and come back to VS the green tick is all set. | Reinstall [JDK 1.8](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html). [MS Instructions](https://learn.microsoft.com/en-us/xamarin/android/troubleshooting/questions/update-jdk?tabs=windows)
[](https://i.stack.imgur.com/eAhNG.png)
Visual Studio was pointed to JDK 1.8 but for some reason it was no good.
[](https://i.stack.imgur.com/JLjQf.png)
**WARNING** - make sure to fix the path to your jdk in visual studio. For me what I installed was a different version of 1.8 than the one I had previously. If Visual studio is still using the old jdk path it won't work. This should be obvious but for me it wasn't.
```
C:\Program Files\Java\jdk1.8.0_192 <-- old path. visual studio still thought this was good. good, that is, until build time.
C:\Program Files\Java\jdk1.8.0_201 <-- new path. from the install of JDK 1.8 that I did today. Tools > Options > Xamarin > Android Settings > Java Development Kit Location needs to be pointing to this.
``` |
886,508 | I'm trying to find the integral of $y = x\sin^2 (x^2)$. Can someone help please? I've tried converting it to $x(\frac{1}{2} -\frac{1}{2}\cos(2x^2))$ and using integration by parts but it doesn't seem to help.
Thanks. | 2014/08/03 | [
"https://math.stackexchange.com/questions/886508",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/167774/"
] | Hint: First let $u=x^{2}$ and notice that $\sin^{2}(u)=\frac{1-\cos(2u)}{2}$ | 1) $x \sin^2(x^2)dx = \frac{1}{2}\sin^2(x^2)d x^2$
2) $\sin^2 t = \frac{1 - \cos 2t}{2}$ |
26,742 | Reading [this article](http://www.douglasadams.com/dna/19990901-00-a.html) by the fantastic Douglas Adams I came across this interesting quote:
>
> ‘[I]nteractivity’ is one of those neologisms that Mr Humphrys likes to dangle between a pair of verbal tweezers, but the reason we suddenly need such a word is that during this century we have for the first time been dominated by non-interactive forms of entertainment: cinema, radio, recorded music and television... We didn’t need a special word for interactivity in the same way that we don’t (yet) need a special word for people with only one head.
>
>
>
This got me thinking — not just about what that word might be (unikef? monocap?), but also how new words are constructed.
My two first thoughts above were that the word would be constructed from either Greek or Latin roots (mono and uni, respectively), and I assume that most newly constructed words would follow a similar structure. That is - they would take previously prescribed pieces of a language (classical or otherwise) and shape those pieces to fit the needs of the new word.
But which language would be more likely? Greek? Or Latin? Or, since the concept of having to describe someone with only one head antedates both of these languages by so much, would it be inappropriate for a new word to have a classical root?
I would appreciate it if any readers who do have multiple heads could let us know authoritatively how you refer to us one-headed folks. | 2011/05/24 | [
"https://english.stackexchange.com/questions/26742",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/3320/"
] | I wish I had come sooner. You see, my good reptilian sister was to put your race in its place, but, alas, she was slain by a sacrilegious buffoon:

As a classicist, I'd begin with what words the Ancients used themselves. The following two are (most probably) the only options in both languages—that is, *Lewis & Short* and *Liddell, Scott, Jones* have only these words.
Greek: **[μονοκέφαλος](http://www.perseus.tufts.edu/hopper/text?doc=Perseus:text:1999.04.0057:entry=monoke/falos)**
* From this, correct formations would be *monocephalic*, *monocephalous*, and ?*monocephalus*. The latter is not used in English, I think, but only in medicine or biology, which use Latin in those cases, not English (they'd be italicized). The first one being the most common and analogous to most other existing *-cephal-* words, I'd pick ***monocephalic***.
Latin: ***[uniceps](http://www.perseus.tufts.edu/hopper/text?doc=Perseus:text:1999.04.0059:entry=uniceps)***
* From this, correct formations would be *unicapital* and *unicipitous*. Because neither form exists so far in either the Oxford English Dictionary or Google Ngrams, I'd simply stick with *monocephalic* to describe your pathetic race.
---
New words based on a word from another language normally follow the way in which older English words from the same stem/root have been formed. Whenever English first adopts a foreign stem, it is converted into an English stem to make appropriate derivations from. This is to some degree an arbitrary process, and there are often several methods by which it may come about; in most cases, one or more of those become established soon after the word is first adopted, and new words based on the same stem are from then on expected to follow the pattern. If a new stem to be converted is similar to a stem that has already been converted, formation usually proceeds analogously as far as possible.
It is generally preferred that a compound word be made from stems that all come from the same language, though hybrids may be necessary if no single language can provide all parts, or if the language that is used in related words cannot provide them. It should first be checked whether a compound already exists in the language of origin, in which case that should be adopted as a whole; only if such does not exist should one create a new compound. | How about something like "unicapital".
From **unus** *L. one* + **capitis** *L. head*
>
> The unicapital inhabitants of the Sol System consume comparatively few facial tissues.
>
>
> |
34,770,255 | I am new to Gherkin and BDD.
We are doing BDD regression tests with Squish.
Our application is very complex - similar to a flight simulator.
Now I ask myself how to write the tests in Gherkin.
As we have a large number of variables as preconditions to a certain situation I would normally put a lot of
```
Given some precondition
And some other precondition
```
into my tests.
My natural feeling is that I should avoid this because it would make things unnecessarily complex.
Is there a rule of thumb for how many preconditions there should be?
Should I try to reduce it to only one? | 2016/01/13 | [
"https://Stackoverflow.com/questions/34770255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Gherkin is a Business Readable, Domain Specific Language created especially for behavior descriptions.
Gherkin serves two purposes: serving as your project’s documentation and automated tests. Gherkin’s grammar is defined in the Treetop grammar that is part of the Cucumber codebase.
To understand Gherkin in a better way, please take a look at simple scenario mentioned below:
```
Feature: As a existing facebook user, I am able to post a birthday greeting on any other existing user's facebook page
Scenario: Verify that Joe Joseph can post a birthday greeting on Sam Joseph's facebook page
Given Joe Joseph is an existing facebook user
Given Sam Joseph is an existing facebook user
Given Joe Joseph is on login page of facebook
Given Joe Joseph logs into his facebook account
When Joe Joseph opens Sam Joseph's facebook page
And Joe Joseph writes "Happy Birthday Sam" on Sam Joseph's facebook page
And Joe Joseph clicks on Post button
Then Joe Joseph verifies that "Happy Birthday Sam" is successfully posted on Sam Joseph's facebook page
```
In the above scenario, all the statements that starts with "Given" are my preconditions.
So, as far as precondictions are concerned, you can use as many preconditions which is required for the test. | Gherkin is the language that Cucumber understands. It is a Business Readable, Domain Specific Language that lets you describe software’s behaviour without detailing how that behaviour is implemented [More here](https://github.com/cucumber/cucumber/wiki/Gherkin)
From above statement my understanding is. You don't need to add precondition every time as who is using scenario knows how to write and understand Gherkin language.
Here is example:
```
When I take login as system admin
And I click on new user
And I enter new user details
Then new user is created successful
```
Here I don't need to mention where I am and other precondition like URL opened or not ?
First precondition is URL opened or not.
```
Given I opened URL "http://www.stackoverflow.com"
And I enter system admin details
And I click on new user
When I enter new user details
Then new user is created successfully
```
Second Condition New User Details form have all the required field. This can be separate scenario.
Goal is tell business and team that we are testing this scenario. It is not test case. You don't need to create tons of document for testing purpose. |
30,967 | In sentences like "He taught them so that they would understand," if the speaker is certain that "they understand," could we use the normal past tense as *Les enseñaron para que entendieron* instead of *entendieran*? | 2019/07/15 | [
"https://spanish.stackexchange.com/questions/30967",
"https://spanish.stackexchange.com",
"https://spanish.stackexchange.com/users/23295/"
] | No, you cannot.
You base things off of whether something has already happened at the particular moment in the narrative sequence. He taught them at moment X so that they would learn at some point *after* moment X. Because the very nature of the preposition *para* obligates such an ordering, it's impossible to use indicative after *para que*. As well, *para que* also hits another case for subjunctive: volition/desire. He does it *in order that* they understand (as you learn, you'll notice that many times, often times several of the reasons for subjunctive might apply simultaneously).
Now, your thinking isn't entirely off. If the preposition had been, for instance, *después de*, then you'd see a difference:
* Después de que les enseñó, entendían.
No subjunctive. The understanding comes after the teaching, so we know the teaching has occured.
* Después de que les enseñe, entenderán.
Subjunctive because in this case, he has not yet taught them, and thus they still do not (yet) understand. | "para que", just like other purpose linkers like "a fin de que / con el objeto/propósito de que", needs to be followed by subjunctive because, at the time when the main action is/was performed, the result is/was not known:
* Les enseño para que entiendan. (I teach you that you will understand.)
* Les enseñé para que entendieran. (I taught you so that you would understand.) |
58,243 | Given any unsigned 16 bit integer, convert its *decimal form* (i.e., base-10) number into a 4x4 ASCII grid of its bits, with the most-significant bit (MSB) at the top left, least-significant bit (LSB) at bottom right, read across and then down (like English text).
Examples
--------
### Input: 4242
```
+---+---+---+---+
| | | | # |
+---+---+---+---+
| | | | |
+---+---+---+---+
| # | | | # |
+---+---+---+---+
| | | # | |
+---+---+---+---+
```
### Input: 33825
```
+---+---+---+---+
| # | | | |
+---+---+---+---+
| | # | | |
+---+---+---+---+
| | | # | |
+---+---+---+---+
| | | | # |
+---+---+---+---+
```
Specific Requirements
---------------------
1. Input *must* be in decimal (base-10), however you may convert to binary any way you wish (including using language built-ins, if available).
2. Output table format must match *exactly*. This means you must use the specific ASCII characters (`-`, `+`, and `|`) for the table grid lines as shown, each cell's interior is 3 characters, and *true* bits are represented by `#` while *false* is represented by a space ().
3. Leading or trailing whitespace is *not permitted.* Final newline is *required*.
4. Bit order must match the examples as described.
Allowances
----------
1. Input must be a base-10 number on the command line, standard input, or user input, but *must not* be hard-coded into your source code.
May the clearest shortest code win! :-) | 2015/09/18 | [
"https://codegolf.stackexchange.com/questions/58243",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/45116/"
] | GNU sed + dc, 116
=================
Score includes +1 for `-r` flags to `sed`:
```
s/.*/dc -e2o&p/e
:
s/^.{,15}$/0&/;t
s/./| & /g
s/.{16}/\n+---+---+---+---+\n&|/g
y/01/ #/
s/\n([-+]+)(.*)/\1\2\n\1/
```
Test output:
```
$ { echo 4242 ; echo 33825 ; } | sed -rf 16bitgrid.sed
+---+---+---+---+
| | | | # |
+---+---+---+---+
| | | | |
+---+---+---+---+
| # | | | # |
+---+---+---+---+
| | | # | |
+---+---+---+---+
+---+---+---+---+
| # | | | |
+---+---+---+---+
| | # | | |
+---+---+---+---+
| | | # | |
+---+---+---+---+
| | | | # |
+---+---+---+---+
$
```
---
Alternatively:
Pure sed, 146
=============
You might think it's cheating to use `sed`'s GNU extension to eval a `dc` command. In that case, we can do this a little differently, according to [this meta-answer](http://meta.codegolf.stackexchange.com/a/5349/11259). Of course the question clearly states that input *must* be in base 10, but here I'm attempting to claim that we can override that for `sed` answers and use unary (base 1) instead.
```
:
s/11/</g
s/<([ #]*)$/< \1/
s/1/#/
y/</1/
t
:a
s/^.{,15}$/0&/;ta
s/./| & /g
s/.{16}/\n+---+---+---+---+\n&|/g
y/01/ #/
s/\n([-+]+)(.*)/\1\2\n\1/
```
### Test output
Using `printf` to generate the necessary unary string:
```
$ printf "%33825s" | tr ' ' 1 | sed -rf 16bitgrid.sed
+---+---+---+---+
| # | | | |
+---+---+---+---+
| | # | | |
+---+---+---+---+
| | | # | |
+---+---+---+---+
| | | | # |
+---+---+---+---+
$
``` | [Vyxal](https://github.com/Vyxal/Vyxal), 31 bytes
=================================================
```
\+3-4*\|?b16∆Z\#*2↳ʁ+4ẇṠv"fǏvǏ⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJcXCszLTQqXFx8P2IxNuKIhlpcXCMqMuKGs8qBKzThuofhuaB2XCJmx492x4/igYsiLCIiLCI0MjQyIl0=)
```
? # Input
b # To binary
16∆Z # Pad to length 16 with 0s
\#* # That many #s, for each bit
2↳ʁ # Pad to length 2 with spaces and mirror
\| + # Prepend | to each
4ẇṠ # Divide into rows and stringify each
v"f # Interleave with...
\+3- # "+---"
4* # Repeated four times
Ǐ # Append the first line
vǏ # For each line, append the firstt character
⁋ # Join the result by newlines
``` |
1,255,917 | I newly installed Ubuntu 20.04 in Lenovo i3 PC, but the Snap Store application is not shown in the application menu.
When I check on Ubuntu store it is shown that the Snap Store is already installed. | 2020/07/03 | [
"https://askubuntu.com/questions/1255917",
"https://askubuntu.com",
"https://askubuntu.com/users/1101669/"
] | The '*Ubuntu Software*' application that you find pre-installed in your system is the Snap Store *itself*. Ubuntu shipped the Snap Store as the default software store application on 20.04 (source: [this OMG! Ubuntu article](https://www.omgubuntu.co.uk/2020/02/ubuntu-snap-store-transition)).
You can verify this by running the command `snap-store` in a Terminal window. It would launch the Ubuntu Software application. | Launch the Snap Store from the terminal instead. Open the terminal and type:
```
snap run snap-store
```
Alternatively you can search for "snap store" in the Software app, click it to bring up the Snap Store information screen, and launch the Snap Store by clicking the `Launch` button. |
2,705,607 | I have a dictionary in C# like
```
Dictionary<Person, int>
```
and I want to sort that dictionary *in place* with respect to keys (a field in class Person). How can I do it? Every available help on the internet is that of lists with no particular example of in place sorting of Dictionary. Any help would be highly appreciated! | 2010/04/24 | [
"https://Stackoverflow.com/questions/2705607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/302047/"
] | You can't sort a `Dictionary<TKey, TValue>` - it's inherently unordered. (Or rather, the order in which entries are retrieved is implementation-specific. You shouldn't rely on it working the same way between versions, as ordering isn't part of its designed functionality.)
You *can* use [`SortedList<TKey, TValue>`](http://msdn.microsoft.com/en-us/library/ms132319.aspx) or [`SortedDictionary<TKey, TValue>`](http://msdn.microsoft.com/en-us/library/f7fta44c(v=VS.100).aspx), both of which sort by the key (in a configurable way, if you pass an `IEqualityComparer<T>` into the constructor) - might those be of use to you?
Pay little attention to the word "list" in the name `SortedList` - it's still a dictionary in that it maps keys to values. It's *implemented* using a list internally, effectively - so instead of looking up by hash code, it does a binary search. `SortedDictionary` is similarly based on binary searches, but via a tree instead of a list. | Due to this answers high search placing I thought the LINQ **OrderBy** solution is worth showing:
```
class Person
{
public Person(string firstname, string lastname)
{
FirstName = firstname;
LastName = lastname;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
static void Main(string[] args)
{
Dictionary<Person, int> People = new Dictionary<Person, int>();
People.Add(new Person("John", "Doe"), 1);
People.Add(new Person("Mary", "Poe"), 2);
People.Add(new Person("Richard", "Roe"), 3);
People.Add(new Person("Anne", "Roe"), 4);
People.Add(new Person("Mark", "Moe"), 5);
People.Add(new Person("Larry", "Loe"), 6);
People.Add(new Person("Jane", "Doe"), 7);
foreach (KeyValuePair<Person, int> person in People.OrderBy(i => i.Key.LastName))
{
Debug.WriteLine(person.Key.LastName + ", " + person.Key.FirstName + " - Id: " + person.Value.ToString());
}
}
```
Output:
```
Doe, John - Id: 1
Doe, Jane - Id: 7
Loe, Larry - Id: 6
Moe, Mark - Id: 5
Poe, Mary - Id: 2
Roe, Richard - Id: 3
Roe, Anne - Id: 4
```
In this example it would make sense to also use **ThenBy** for first names:
```
foreach (KeyValuePair<Person, int> person in People.OrderBy(i => i.Key.LastName).ThenBy(i => i.Key.FirstName))
```
Then the output is:
```
Doe, Jane - Id: 7
Doe, John - Id: 1
Loe, Larry - Id: 6
Moe, Mark - Id: 5
Poe, Mary - Id: 2
Roe, Anne - Id: 4
Roe, Richard - Id: 3
```
LINQ also has the **OrderByDescending** and **ThenByDescending** for those that need it. |
59,989,280 | We have a situation in oracle SQL.
```
select x from A where x=10;
```
so if `10` exists in the column, value will be displayed `10`. but if it doesn't exists I want to display `null`. I tried `NVL` but it is not returning anything as data is not displaying.
Could you please help me to resolve this. | 2020/01/30 | [
"https://Stackoverflow.com/questions/59989280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you want to return multiple rows from the original `SELECT` then you can use `UNION ALL` to add a row when the value does not exist:
```sql
SELECT x
FROM A
WHERE x = 10
UNION ALL
SELECT NULL
FROM DUAL
WHERE NOT EXISTS (
SELECT x
FROM A
WHERE x = 10
)
```
If your table is:
```sql
CREATE TABLE a ( x ) AS
SELECT 10 FROM DUAL UNION ALL
SELECT 10 FROM DUAL UNION ALL
SELECT 10 FROM DUAL;
```
Then the query will output:
>
>
> ```
>
> | X |
> | -: |
> | 10 |
> | 10 |
> | 10 |
>
> ```
>
>
Then if you `DELETE FROM a;` and repeat the query, it will output:
>
>
> ```
>
> | X |
> | ---: |
> | *null* |
>
> ```
>
>
*db<>fiddle [here](https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=e7d9429506b034b7de16ac873b9d958d)* | Try this:
```
select max(x)
from A
where x = 10; --this will return null if no data
```
And then you can do a NVL:
```
select nvl(max(x), 0)
from A
where x = 10; --this will return 0 if no data
``` |
745,095 | For a second order ODE
y''+10y'+ 21y=0
which was reduced to this quadratic expression
x^2+10x+21=0
* is there any way to tell whether the expression is bounded that is y(x) is either periodic or has a limit 0 as x tends to infinity?
\*Does periodic means having only complex solutions? | 2014/04/08 | [
"https://math.stackexchange.com/questions/745095",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/133532/"
] | To answer the second part, in the differential equation
$$
ay''(x)+by'(x)+cy(x)=0
$$
you would need $b=0$ and $ac>0$ to get periodic solutions. With complex, but not purely imaginary eigenvalues you get oscillating solutions where the amplitude changes with an exponential function. | Suppose that you want to solve the quadratic equation, $ax^2 + bx + c = 0$. The quadratic formula gives the two roots as
$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
Now, take a look at the surd, $\sqrt{b^2 - 4ac}$. If $b^2 - 4ac$ was negative, then the roots would be complex, because the square root of a negative real number is imaginary.
Intuitively, if $b^2 - 4ac$ is positive, then there will be two distinct real roots. If $b^2 - 4ac$ is zero, then both roots will be the same.
This $b^2 - 4ac$ is what we call the discriminant of the quadratic equation. |
2,893,435 | This is an excercise from Spivak's Calculus.
Show that if $x^n=y^n$ and $n$ is odd, then $x=y$. Hint: first explain why it suffices to consider only the case x and y greater than 0, then show that x smaller than y or greater y are both impossible.
I try to prove this by using induction. The base case $n=1$ is correct. Assume that $n=2k+1$ is true, prove that $n=2k+3$ is also true. But now I don't know how to proceed. | 2018/08/24 | [
"https://math.stackexchange.com/questions/2893435",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/456122/"
] | It seems unlikely that induction is a good approach here.
If $x$ and $y$ have opposite signes, then obviously you can't have $x^n=y^n$. Now, let us assume that $x,y\geqslant0$. The case in which $x,y\leqslant0$ is similar. Note that$$x^n-y^n=(x-y)(x^{n-1}+x^{n-2}y+\cdots+xy^{n-1}).$$So, if $x^n=y^n$, then $x=y$ or $x^{n-1}+x^{n-2}y+\cdots+xy^{n-1}=0$. But the last equality cannot hold, unless $x=y=0$ (in which case $x=y$), since $x,y\geqslant0$.
And if $x,y\leqslant0$,\begin{align}x^n=y^n&\implies(-x)^n=(-y)^n\\&\implies-x=-y\\&\implies x=y.\end{align} | For fun:
$n \in \mathbb{Z^+}$, odd .
1) $x=y=0$ is a solution.
2) Let $(x,y) \not =(0,0)$.
$x^n-y^n=0$;
$(\frac{x}{y})^n =1$, implies
$\frac{x}{y}=1$,
since $n \in \mathbb{Z^+}$, $n$ odd. |
4,019,609 | I just made a Linq-to-SQL .dbml file in Visual Studio 2010.
I'm getting the following 2 errors, a total of 60 times in total, mostly the first.
1. The type or namespace name 'Linq'
does not exist in the namespace 'System.Data'
2. The type or namespace
name 'EntitySet' could not be found
I've found various similar questions here and on other sites, all of which seem to say that some extra assembly needs to be added.
I've added every one suggested, the problem persists. Another odd thing is that VS2010 itself doesn't underline the errors in the editor screen, but it does show them in the error log.
Anyways, I've seen all the existing topics and applied their solutions, the problem persists.
Some technical details:
* I'm running Windows 7 32-bit.
* I still have Visual Studio 2008 SP1
installed. I just installed VS2010
when it came out and didn't remove
the older one.
* I'm running MSSQL server 2008 R2.
And here's the assemblies listed in my web.config file:
```
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.DataSetExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.Entity.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.Services.Client, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.Services.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.SqlXml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
``` | 2010/10/25 | [
"https://Stackoverflow.com/questions/4019609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80907/"
] | I've been having the same problem on exactly the same config except for my Windows 7 is 64-bit. Got it solved by doing `[project name] -> References -> Add reference -> System.Data.Linq` Why do you add references by hand? | You can try following:
Add reference to **System.Data.Linq** (Right click on References folder | Select Add Reference | Select .Net tab(Is default selected) | select **System.Data.Linq** reference | click OK.
I hope this will help you or someone else. |
982,214 | I want my (ExtJS) toolbar buttons **not** to grab the focus on the web page when they are clicked, but to do their "thing" while leaving the focus unchanged by the click. How do I do that? | 2009/06/11 | [
"https://Stackoverflow.com/questions/982214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121200/"
] | I don't think there's an easy way to do what you want to do because it's the browser's default behaviour.
You could of course blur() the button as soon as it is clicked, but that would simply unselect everything. To have the previously active object regain focus, you'd have to create a "memory" of sorts by adding a blur handler for every element to keep track of which element had/lost focus last (store the id of the element in a global and update it when an element loses focus). | Maybe you should try to use `stateful` and state change properties for form fields or whatever to get focus back? |
4,274,114 | If A = $\begin{bmatrix} 1 & -1 \\ 0 & -2 \end{bmatrix}$, set B = {X ∈ $M\_2(\mathbb{R})$∣AX + $X^\intercal$A = 0}
Find a homogeneous system that will give all the elements of B.
My attempt:
AX + $X^\intercal$A = 0
AX = $-$ ($X^\intercal$A)
($\cfrac{1}{A}$) AX = $-$ ($X^\intercal$A)$(\cfrac{1}{A})$
X = $-$ $X^\intercal$
This would mean that all skew-symmetric matrices would satisfy the conditions.
However, I tried plugging in random skew-symmetric matrices but AX + $X^\intercal$A woouldn't equate to 0.
I may have erred in my solution: I just don't know where. | 2021/10/11 | [
"https://math.stackexchange.com/questions/4274114",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/834929/"
] | Your step when apply inverse both side is not correct because you are multiplying from the left and from the right, use instead
$$\begin{bmatrix} 1 & -1 \\ 0 & -2 \end{bmatrix} \begin{bmatrix} a& b \\ c& d \end{bmatrix}=- \begin{bmatrix} a& c \\ b& d \end{bmatrix} \begin{bmatrix} 1 & -1 \\ 0 & -2 \end{bmatrix} $$
that is
* $a-c=-a$
* $b-d=a+2c$
* $-2c=-b$
* $-2d=b+2d$ | You cannot infer from the step $AX=-(X^TA)$ that $A^{-1}AX=-(X^TA)A^{-1}$.
When two square matrices are equal, say $X=Y$, you can left-multiply both sides by a matrix $M$ to get another equality $MX=MY$, or you can right-multiply both sides by $M$ to get $XM=YM$. However, you cannot infer that $MX=YM$, because matrix multiplication in general is not commutative. |
922,774 | I've a method that I want to be able to accept either a single string (a path, but not necessarily one that exists on the machine running the code) or a list/tuple of strings.
Given that strings act as lists of characters, how can I tell which kind the method has received?
I'd like to be able to accept either standard or unicode strings for a single entry, and either lists or tuples for multiple, so isinstance doesn't seem to be the answer unless I'm missing a clever trick with it (like taking advantage of common ancestor classes?).
Python version is 2.5 | 2009/05/28 | [
"https://Stackoverflow.com/questions/922774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68457/"
] | You can check if a variable is a string or unicode string with
* Python 3:
```
isinstance(some_object, str)
```
* Python 2:
```
isinstance(some_object, basestring)
```
This will return `True` for both strings and unicode strings
As you are using python 2.5, you could do something like this:
```
if isinstance(some_object, basestring):
...
elif all(isinstance(item, basestring) for item in some_object): # check iterable for stringness of all items. Will raise TypeError if some_object is not iterable
...
else:
raise TypeError # or something along that line
```
Stringness is probably not a word, but I hope you get the idea | Check the type with isinstance(arg, basestring) |
25,313,784 | I would like to list the chars used in a string (sorted) with a function like this one :
```
def foobar(string):
return ????
string = 'what a nice day'
print foobar(string)
```
This should print the string `acdehintwy`
What would be the foobar() function?
I tried OrderedDict.fromkeys(items) but I can't sort it afterwards... | 2014/08/14 | [
"https://Stackoverflow.com/questions/25313784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3942297/"
] | ```
s='what a nice day'
print ("".join(set(s.replace(" ",""))))
acedihntwy
```
A [set](https://docs.python.org/2/library/sets.html) will remove the duplicates and `s.replace(" ","")` will remove the spaces
```
def foobar(s):
return "".join(set(s.replace(" ","")))
In [4]: foobar("what a nice day")
Out[4]: 'acedihntwy'
``` | Use a [set](https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset).
```
>>> mystring = 'what a nice day'
>>> chars = sorted(set(mystring.replace(" ", "")))
>>> print(chars)
['a', 'c', 'd', 'e', 'h', 'i', 'n', 't', 'w', 'y']
>>> "".join(chars)
'acdehintwy'
``` |
5,448,545 | Consider:
```
http://example.com/page.html?returnurl=%2Fadmin
```
For `js` within `page.html`, how can it retrieve `GET` parameters?
For the above simple example, `func('returnurl')` should be `/admin`.
But it should also work for complex query strings... | 2011/03/27 | [
"https://Stackoverflow.com/questions/5448545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641151/"
] | I do it like this (to retrieve a specific get-parameter, here 'parameterName'):
```
var parameterValue = decodeURIComponent(window.location.search.match(/(\?|&)parameterName\=([^&]*)/)[2]);
``` | I have created a simple JavaScript function to access GET parameters from URL.
Just include this JavaScript source and you can access `get` parameters.
E.g.: in <http://example.com/index.php?language=french>, the `language` variable can be accessed as `$_GET["language"]`. Similarly, a list of all parameters will be stored in a variable `$_GET_Params` as an array. Both the JavaScript and HTML are provided in the following code snippet:
```html
<!DOCTYPE html>
<html>
<body>
<!-- This script is required -->
<script>
function $_GET() {
// Get the Full href of the page e.g. http://www.google.com/files/script.php?v=1.8.7&country=india
var href = window.location.href;
// Get the protocol e.g. http
var protocol = window.location.protocol + "//";
// Get the host name e.g. www.google.com
var hostname = window.location.hostname;
// Get the pathname e.g. /files/script.php
var pathname = window.location.pathname;
// Remove protocol part
var queries = href.replace(protocol, '');
// Remove host part
queries = queries.replace(hostname, '');
// Remove pathname part
queries = queries.replace(pathname, '');
// Presently, what is left in the variable queries is : ?v=1.8.7&country=india
// Perform query functions if present
if (queries != "" && queries != "?") {
// Remove question mark '?'
queries = queries.slice(1);
// Split all the different queries
queries = queries.split("&");
// Get the number of queries
var length = queries.length;
// Declare global variables to store keys and elements
$_GET_Params = new Array();
$_GET = {};
// Perform functions per query
for (var i = 0; i < length; i++) {
// Get the present query
var key = queries[i];
// Split the query and the value
key = key.split("=");
// Assign value to the $_GET variable
$_GET[key[0]] = [key[1]];
// Assign value to the $_GET_Params variable
$_GET_Params[i] = key[0];
}
}
}
// Execute the function
$_GET();
</script>
<h1>GET Parameters</h1>
<h2>Try to insert some get parameter and access it through JavaScript</h2>
</body>
</html>
``` |
3,980,773 | I'm building a new database for a web-based application and find that I am frequently having to decide between flexibility of the model and meaningful foreign keys to enforce referential integrity.
There are a couple of aspects of the design that lead me towards writing triggers to do what FKs would normally do:
1. Parts of the model use the [Class Table Inheritance Pattern](http://martinfowler.com/eaaCatalog/classTableInheritance.html) and some of the data tables have an ObjectID whose underlying type should be restricted to a subset of object types. This is pretty easy to do in a trigger, but impossible in a FK without further complicating the data model.
2. The database has a very flexible reference data model that allows end users to customize their instance of the database (each client will have their own database) with new fields as well as extending the list of predefined values for common fields. At first, I had a hundred little tables with exactly the same schema (ID, Name) but have since consolidated them all into a single table (FieldID, ID, Name). Again, this would be pretty straightforward to check in a trigger, but impossible in a FK
Some other details:
* As mentioned above, each client will have their own copy of the database
* The size of each database is not likely to very big. Probably somewhere in the 10 - 50 GB range
* MS SQL 2008
Does this idea sound reasonable? Or are there some huge pitfalls that I'm not thinking about? The reason I would be creating foreign keys is to enforce data integrity and prevent orphaned rows. As long as that end is accomplished the means shouldn't matter, right?
**EDIT**: I feel like I should clarify that I am not intending to perform ALL referential integrity checks with triggers. When I can, I will use a foreign key. There are a just a couple of areas in my model where I can't. I appreciate the thoughtful answers so far. | 2010/10/20 | [
"https://Stackoverflow.com/questions/3980773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86265/"
] | From your description, it seems to me the triggers will get more and more complex over time, and will end up being a nightmare to maintain.
I have had to maintain this kind of "ObjectId" data schema in my career, and my experience with it has always been negative. The maintenance becomes very painful over time, and it becomes very complicated to perform meaningful queries. Essentially what you would be doing would be abandoning a "real" relational model for a sort of metadata model.
It may seem counterintuitive, but maintaining a properly normalized relational model, even one with many tables, is (generally) easier than maintaining a metadata model.
All that said, if I were going to go the "ObjectId" route, I would consider enforcing integrity in my application layer and not using triggers. The downside would be that it would make it possible to get bad data in the system (logical bugs or people typing in data manually through SSMS). However the maintenance would likely be more manageable. | Using triggers to implement a more complex referential integrity rule is ok, but can be confusing to new developers so make sure it's well documented internally.
Having clients customize their database structure is asking for trouble though. It's very likely to cause maintenance problems down the road. A better option is to create a universal structure that can hold any data, such as a table of key/value pairs. |
3,987,683 | How do I install a specific version of a formula in homebrew? For example, postgresql-8.4.4 instead of the latest 9.0. | 2010/10/21 | [
"https://Stackoverflow.com/questions/3987683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62612/"
] | Homebrew changed recently. Things that used to work do not work anymore. The easiest way I found to work (January 2021), was to:
* Find the `.rb` file for my software (first go to [Formulas](https://github.com/Homebrew/homebrew-core/tree/master/Formula), find the one I need and then click "History"; for CMake, this is at <https://github.com/Homebrew/homebrew-core/commits/master/Formula/cmake.rb>)
+ Pick the desired version among the revisions, e.g. [3.18.4](https://github.com/Homebrew/homebrew-core/commit/2bf16397f163187ae5ac8be41ca7af25b5b2e2cc#diff-c385976f09457894270c14463d4c0d0e21d0083de7e0663683f42b4d1d21638a), click three dots in the top right corner of the `.rb` file diff ([...](https://github.com/Homebrew/homebrew-core/blob/2bf16397f163187ae5ac8be41ca7af25b5b2e2cc/Formula/cmake.rb)) and then click [Raw](https://raw.githubusercontent.com/Homebrew/homebrew-core/2bf16397f163187ae5ac8be41ca7af25b5b2e2cc/Formula/cmake.rb). Copy the URL.
* Unlink the old version `brew unlink cmake`
* Installing directly from the git URL does not work anymore (`brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/2bf16397f163187ae5ac8be41ca7af25b5b2e2cc/Formula/cmake.rb` will fail)
+ Instead, download it and install from a local file `curl -O https://raw.githubusercontent.com/Homebrew/homebrew-core/2bf16397f163187ae5ac8be41ca7af25b5b2e2cc/Formula/cmake.rb && brew install ./cmake.rb`
Voila! You can delete the downloaded `.rb` file now. | On the newest version of homebrew (0.9.5 as of this writing) there will be a specific recipe for the version of the homebrew keg you want to install. Example:
```sh
$ brew search mongodb
mongodb mongodb24 mongodb26
```
Then just do `brew install mongodb26` like normal.
In the case that you had already installed the latest version, make sure to unlink the latest version and link the desired version: `brew unlink mongodb && brew link mongodb26`. |
4,962,269 | This is my homework which is due tomorrow and I have been trying to do it for the past 5 hours, but I can't figure it out. I understand what I have to do, but I just don't know where to start. If you could help me to just get started or to give some advice it would be great. Can i just have the answer I cant figure it out iv tried everything
>
> It has to Return an array of int, of size 27, consisting of character counts from the String s.
>
>
> * The count of the number of 'a' or 'A' characters must be in position 0 of the array,
> * the count of the number of 'b' or 'B' characters must be in position 1 of the array,
> * the count of the number of 'z' or 'Z' characters must be in position 25 of the array, and
> * the count of all other characters must be in position 26 of the array.
>
>
> for example
>
>
> * if s is "", then all entries in the array must be 0.
> * if s is "a", then all entries in the array must be 0 except for entry 0, which must be 1.
> * if s is "Baaa!", then all entries in the array must be 0 except for:
> + entry 0, which must be 3,
> + entry 1, which must be 1, and
> + entry 26, which must be 1.
>
>
> The only methods you may call on the String s are charAt(int) and length().
>
>
>
---
Thanks iv read everything you guys have said and its helped me alot in understanding the problem and what i need to do. Im still stuck however but im slowly getting this.
Thanks again! | 2011/02/10 | [
"https://Stackoverflow.com/questions/4962269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612052/"
] | 1. Create an array of 27 elements. [Official trail on Arrays](http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)
2. Iterate through all characters of the string, using for instance an ordinary for loop ([Official trail on the `for` statement](http://download.oracle.com/javase/tutorial/java/nutsandbolts/for.html)) and the [`String.charAt`](http://download.oracle.com/javase/6/docs/api/java/lang/String.html#charAt%28int%29).
3. Find the index corresponding to the character using something like `Character.toUpperCase(currentChar) - 'A'` for ordinary characters.
4. Increment the corresponding entry in the array, using something like `charSums[index]++`. | So, basically you are trying to count the numbers of occurrence of alphabets in a String.
The returning array is size 27 because there are 26 alphabets + 1 cell of non-alphabet characters.
What you need to do is simple,
1) create array of size 27 (no need for special initialization since java initialize int array to 0s for you),
2) iterate through the string using lenght() method
3)at each iteration use the chartAt() method to get the character and increment the count in the correct cell of array you created in step 1.
Hint: consider what will 'b'-'a' and 'z'-'a' return. |
2,665,056 | How do I parameterise $x^2-y^2+z^2=0$ where $y\in [0,1]$
?
Here's my thought process right now, but I'm not sure:
$x^2-y^2+z^2=0$
$x^2+z^2=y^2$
Let $y=u$
Then can you just parametrise it like you would a circle? | 2018/02/24 | [
"https://math.stackexchange.com/questions/2665056",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/499701/"
] | Yes, so $(x,y,z)=(u\cos t, u, u\sin t)$ is a parametrization, where $u\in[0,1]$ and $t\in[0,2\pi)$. Since it is a surface, we have two parameters, $u$ and $t$. | $y=\sin t$, $ t \in [0,π/2].$
Then $x^2+z^2 = \sin^2 t$ ;
$x=\sin t \cos s$; $z= \sin t \sin s$,
where $s \in [0,2π).$ |
45,989,509 | I want to insert a syncfusion linearlayout listview, but for some reason it's not displaying any items/data, and I'm not getting any errors at the same time, I tried changing binding syntax and a couple things, but I cannot seem to get it right.
This is my xaml:
```
<syncfusion:SfListView x:Name="listView"
ItemTemplate="{Binding Source={local2:BandInfoRepository}, Path=BandInfo, Mode=TwoWay}"
ItemSize="100"
AbsoluteLayout.LayoutBounds="1,1,1,1"
AbsoluteLayout.LayoutFlags="All" >
<syncfusion:SfListView.ItemTemplate>
<DataTemplate>
<Grid RowSpacing="0" Padding="0,12,8,0" ColumnSpacing="0" Margin="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="1" />
</Grid.RowDefinitions>
<Grid RowSpacing="0" Padding="8,0,8,10">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Image Source="{Binding Path=BandImage}"
Grid.Column="0"
Grid.Row="0"
HeightRequest="80"
WidthRequest="70"
HorizontalOptions="Start"
VerticalOptions="Start"
/>
<StackLayout Orientation="Vertical"
Padding="5,-5,0,0"
VerticalOptions="Start"
Grid.Row="0"
Grid.Column="1">
<Label Text="{Binding Path=BandName}"
FontAttributes="Bold"
FontSize="16"
BackgroundColor="Green"
TextColor="#000000" />
<Label Text="{Binding Path=BandDescription}"
Opacity="0.54"
BackgroundColor="Olive"
TextColor="#000000"
FontSize="13" />
</StackLayout>
</Grid>
<BoxView Grid.Row="1"
HeightRequest="1"
Opacity="0.75"
BackgroundColor="#CECECE" />
</Grid>
</DataTemplate>
</syncfusion:SfListView.ItemTemplate>
</syncfusion:SfListView>
```
And this is the class where I'm getting the data from:
```
public class BandInfo : INotifyPropertyChanged
{
private string bandName;
private string bandDesc;
private ImageSource _bandImage;
public string BandName
{
get { return bandName; }
set
{
bandName = value;
OnPropertyChanged("BandName");
}
}
public string BandDescription
{
get { return bandDesc; }
set
{
bandDesc = value;
OnPropertyChanged("BandDescription");
}
}
public ImageSource BandImage
{
get { return _bandImage; }
set
{
_bandImage = value;
OnPropertyChanged("BandImage");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
```
And just in case, this is how I'm filling the collection (BandInfoRepository.cs):
```
public class BandInfoRepository
{
private ObservableCollection<BandInfo> bandInfo;
public ObservableCollection<BandInfo> BandInfo
{
get { return bandInfo; }
set { this.bandInfo = value; }
}
public BandInfoRepository()
{
GenerateBookInfo();
}
internal void GenerateBookInfo()
{
string[] BandNames = new string[] {
"Nirvana",
"Metallica",
"Frank Sinatra"
};
string[] BandDescriptions = new string[] {
"Description",
"Description",
"Description"
};
bandInfo = new ObservableCollection<BandInfo>();
for (int i = 0; i < BandNames.Count(); i++)
{
var band = new BandInfo()
{
BandName = BandNames[i],
BandDescription = BandDescriptions[i],
BandImage = ImageSource.FromResource("Lim.Images.Image" + i + ".png")
};
bandInfo.Add(band);
}
}
}
```
I hope you guys can help me out as I've been stuck with this for a while now. Thanks in advance. | 2017/08/31 | [
"https://Stackoverflow.com/questions/45989509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7560262/"
] | You can do that with a classic loop:
```
let input = [("Ann", 1), ("Bob", 2)]
var guests: [Guest] = []
for each in input {
guests.append(Guest(name: each.0, age: each.1))
}
```
However, it can be done more concisely (and with avoidance of `var`) using functional techniques:
`let guests = [("Ann", 1), ("Bob", 2)].map { Guest(name: $0.0, age: $0.1) }`
EDIT: Dictionary-based solution (Swift 4; for Swift 3 version just use the classic loop)
```
let input = [("Ann", 1), ("Bob", 2)]
let guests = Dictionary(uniqueKeysWithValues: input.map {
($0.0, Guest(name: $0.0, age: $0.1))
})
```
Or, if it's possible for two guests to have the same name:
```
let guests = Dictionary(input.map { ($0.0, Guest(name: $0.0, age: $0.1)) }) { first, second in
// put code here to choose which of two conflicting guests to return
return first
}
```
With the dictionary, you can just do:
```
if let annsAge = guests["Ann"]?.age {
// do something with the value
}
``` | ```
//MARK: Call method to create multiple instances
createInstance([("Ann", 1), ("Bob", 2)])
func createInstance(_ input: Array<Guest>) {
for each in input {
guests.append(Guest(name: each.0, age: each.1))
}
}
``` |
26,183,703 | I'm stuck on making a loop. I'd like to input the first key in the Teacher1 dict and it's corresponding value into my payload dictionary and run my code on the payload dict. Then the next item in the students dict would be inputted into the payload dict and run till I go through all the values in the students dict. Thanks for your time!
```
Teacher1 = {'Username1': 'Pass1', 'Username2: 'Pass2...}
Payload = {'User_id': 'Username1', : 'Password': 'Pass1' }
``` | 2014/10/03 | [
"https://Stackoverflow.com/questions/26183703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2785334/"
] | You can just loop over the keys of the dictionary
```
payload = {}
for user_id in teacher1:
payload['User_id'] = user_id
payload['Password'] = teacher1[user_id]
# Do some processing with payload here
``` | You can do something like this:
```
for k, v in Teacher1.items():
Payload = {}
Payload['User_id'] = k
Payload['Password'] = v
# do payload processing
``` |
16,942,580 | I am trying to scroll into view so that the very last item in a vertical listivew is always showing, but ListView.ScrollIntoView() never works.
I have tried:
```
button1_Click(object sender, EventArgs e)
{
activities.Add(new Activities()
{
Time = DateTime.Now,
Message = message
});
ActivityList.ItemsSource = activities;
// Go to bottom of ListView.
ActivityList.SelectedIndex = ActivityList.Items.Count;
ActivityList.ScrollIntoView(ActivityList.SelectedIndex);
}
```
I have also tried:
`ActivityList.ScrollIntoView(ActivityList.Items.Count)`, and `ActivityList.ScrollIntoView(ActivityList.Items.Count + 1);` but nothing is working.
Please help. This is really annoying. And the documentation [isn't very helpful](http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.scrollintoview.aspx) in this case. | 2013/06/05 | [
"https://Stackoverflow.com/questions/16942580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/152598/"
] | The problem with `ActivityList.ScrollIntoView(ActivityList.Items[ActivityList.Items.Count - 1]);`
and similiar "solutions", at least from what I'm experiencing, is that when the ListBox contains the same item more than once, it jumps to the first it finds, i.e. lowest index. So, it doesn't care about the index of the item you input, it just looks for that item and picks the first.
I haven't yet found a solution to this, but the approach I'm taking right now is to Insert instead of Add items. In the original posters case I think that would result in:
```
activities.Insert(0, new Activities()
{
Time = DateTime.Now,
Message = message
});
```
or possibly:
```
ActivityList.Items.Insert(0, new Activities()
{
Time = DateTime.Now,
Message = message
});
```
Which causes every new entry to be inserted in the top, and thus ScrollIntoView doesn't even need to be called. | The problem I faced was similar. I was adding programatically to a ListBox and needed the last item added to be visible. After tying various methods I found the following to be the simplest and the best
```
lstbox.Items.MoveCurrentToLast();
lstbox.ScrollIntoView(lstbox.Items.CurrentItem);
``` |
6,558 | I am trying to get back in shape and started running. After a few runs (treadmill at the gym) both my knees are really hurting.
* Is this due to a lack of stretching?
* Is this overcompensating for weakness in other muscles ?
What would i be doing that would make my knees hurt. I have run in the past and never had this specific pain.
Also, is there any recommendation to heal from this. I have stopped running for 3 days and my knees still hurt even when walking or going up stairs, etc.
If it is weakness in other leg muscles I would appreciate any exercise suggestions | 2012/05/26 | [
"https://fitness.stackexchange.com/questions/6558",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/751/"
] | When your knees hurt after running, it's usually an indication that your thigh/hip muscles are not strong enough, and your knees are bearing the brunt. You have to systematically strengthen your various leg muscles. Here's what has helped me (non-exhaustive list but covers the major categories)
* [For the glutes](http://www.bodyresults.com/e2gluteusMedius.asp)
* [Walt Reynold's ITB special](http://onemillionruns.blogspot.com/2006/10/walt-reynolds-itb-special.html) (really important - do it before it hits)
* [For the Achilles tendon](http://www.buzzle.com/articles/achilles-tendonitis-exercises.html)
* [For quads, hamstrings, shins](http://www.roadrunnersports.com/rrs/content/content.jsp?contentId=300140)
* [For calves](http://physicaltherapy.about.com/od/strengtheningexercises/p/Toeraises.htm)
* Squats
* Weighted legs raises (side and straight up)
* Toe raises and dips (standing on steps)
And specifically for knees
* [Some Yoga poses](http://www.runnersworld.com/article/0,7120,s6-241-285--13106-0,00.html?cm_mmc=training-_-2009_04_21-_-training-_-INJURY%20PREVENTION:%20What%20Knees%20Need)
Hope this helps. | Your running gait matters too. If unsure, you can get a physiotherapist or trainer (one that specialise in that) to assess your gait.
Stretching does not really help. Some research out there suggests that stretching does not actually prevent injuries. It is better to do dynamic warm up - jumping jacks, slow jogs for 5-10mins.
You can try some active recovery - walking, swimming. Look out for inflammation. It your knee is swollen, apply ice and seek professional help.
Train the muscles mentioned excellently above. Our muscles act as force absorbers and work to both propel our body forward (concentric action of muscles) and also to prevent us from falling down (eccentric action of muscles). Shin splint may be a common occurrence if you haven’t been training and jumped right back into it, too fast and too intense. |
237,639 | Background: 600-ish years into the future. Humanity finally managed to make Earth uninhabitable and now lives in space. Some humans shed their flesh bodies and are now reduced to brains, their "bodies" being space ships.
I am looking for a futuristic, but still science-based explanation which allows such a spaceship to use an acceleration of around 50g for long periods of time (up to 20 hours), and 100g for a few seconds, in extreme cases, without obviously turning the brain it hosts into mush.
My imagination created some sort of rotating sphere filled with an electrically-permeable gel, which turns slowly, with the brain inside it, acting as a cushion, but I am not fully satisfied. Any other ideas?
EDIT: I was asked to provide constraints.
1. The device which protects the brain in the spaceship should be rather small, no more than twice the size of a human head.
2. The space ship is fusion-powered, therefore plenty of power available, but we need to limit the amount of power the device would use, or make the power usage exponentially higher, the higher the protected volume would be.
3. „Magical” Forcefields, non-inertial systems or exotic matter usage („MumboJumbonium”, to quote someone) are to be avoided.
4. Inertial dampeners are OK, as long as there's some drawback attached to them (see constraint 2 as an example) and they have some background explanation (they work and can be used because...?)
5. Acceleration in real space/time is a prerequisite. Propulsion methods which avoid acceleration are not allowed in this context. | 2022/11/04 | [
"https://worldbuilding.stackexchange.com/questions/237639",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/99331/"
] | The gel the brain is stored in reinforces the brain. It seeps into the brain and makes its internal structure sturdier, which makes the whole brain more resistant to acceleration.
This could be done by nanites which builds stabilizing micro-structure within the brain which greatly enhance its structural integrity. Or it could be done purely biochemically by an agent which reacts with the cell walls of the neurons and hardens them with a protective shell. Neither of that must affect the natural processes of the neurons and their ability to form synapses, so the natural thinking processes of the human remain unaffected. | **Store the Brain as Energy**
[](https://i.stack.imgur.com/OHTyv.jpg)
Before the ship accelerates, the brain or the entire person is scanned, and the data is absorbed into the transporter pattern buffer. The buffer is a mechanical system built to be much more resilient to strong acceleration than a squishy meatbag.
When the spaceship comes to speed, the brain or entire person is reconstituted as if nothing happened. From their point of view the ship instantly jumped to top speed and all the clocks jumped forward a few hours.
Bonus points for hijinks! |
33,618,681 | No, I can't use generic Collections. What I am trying to do is pretty simple actually. In php I would do something like this
```
$foo = [];
$foo[] = 1;
```
What I have in C# is this
```
var foo = new int [10];
// yeah that's pretty much it
```
Now I can do something like `foo[foo.length - 1] = 1` but that obviously wont work. Another option is `foo[foo.Count(x => x.HasValue)] = 1` along with a nullable int during declaration. But there *has* to be a simpler way around this trivial task.
This is homework and I don't want to explain to my teacher (and possibly the entire class) what `foo[foo.Count(x => x.HasValue)] = 1` is and why it works etc. | 2015/11/09 | [
"https://Stackoverflow.com/questions/33618681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433905/"
] | The simplest way is to create a new class that holds the index of the inserted item:
```
public class PushPopIntArray
{
private int[] _vals = new int[10];
private int _nextIndex = 0;
public void Push(int val)
{
if (_nextIndex >= _vals.Length)
throw new InvalidOperationException("No more values left to push");
_vals[_nextIndex] = val;
_nextIndex++;
}
public int Pop()
{
if (_nextIndex <= 0)
throw new InvalidOperationException("No more values left to pop");
_nextIndex--;
return _vals[_nextIndex];
}
}
```
You could add overloads to get the entire array, or to index directly into it if you wanted. You could also add overloads or constructors to create different sized arrays, etc. | `foo[foo.Length]` won't work because foo.Length index is outside the array.
Last item is at index `foo.Length - 1`
After that an array is a fixed size structure if you expect it to work the same as in php you're just plainly wrong |
28,009,942 | This time I'm proving function calling other. `vars.c`:
```
int pure0 ()
{
return 0;
}
int get0(int* arr)
{
int z = pure0();
return 0;
}
```
My proof start - `verif_vars.v`:
```
Require Import floyd.proofauto.
Require Import vars.
Local Open Scope logic.
Local Open Scope Z.
Definition get0_spec :=
DECLARE _get0
WITH sh : share, arr : Z->val, varr : val
PRE [_arr OF (tptr tint)]
PROP ()
LOCAL (`(eq varr) (eval_id _arr);
`isptr (eval_id _arr))
SEP (`(array_at tint sh arr 0 100) (eval_id _arr))
POST [tint] `(array_at tint sh arr 0 100 varr).
Definition pure0_spec :=
DECLARE _pure0
WITH sh : share
PRE []
PROP ()
LOCAL ()
SEP ()
POST [tint] local(`(eq (Vint (Int.repr 0))) retval).
Definition Vprog : varspecs := nil.
Definition Gprog : funspecs := get0_spec :: pure0_spec ::nil.
Lemma body_pure0: semax_body Vprog Gprog f_pure0 pure0_spec.
Proof.
start_function.
forward.
Qed.
Lemma body_get0: semax_body Vprog Gprog f_get0 get0_spec.
Proof.
start_function.
name arrarg _arr.
forward_call (sh).
entailer!.
```
Which induces the goal:
```
2 subgoals, subgoal 1 (ID 566)
Espec : OracleKind
sh : share
arr : Z -> val
varr : val
Delta := abbreviate : tycontext
POSTCONDITION := abbreviate : ret_assert
MORE_COMMANDS := abbreviate : statement
Struct_env := abbreviate : type_id_env.type_id_env
arrarg : name _arr
============================
Forall (closed_wrt_vars (eq _z')) [`(array_at tint sh arr 0 100 varr)]
subgoal 2 (ID 567) is:
DO_THE_after_call_TACTIC_NOW
```
I suppose it states, that the function call does not alter `arr` contents, which is quite obvious for me.
What can I do with this goal? Which tactic applies here, and what exactly means the statement? Should I enrich the `pure0` spec to somehow point out, that it does not modify anything? | 2015/01/18 | [
"https://Stackoverflow.com/questions/28009942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1234026/"
] | FIRST: When writing VST/Verifiable-C questions, please indicate which version of VST you are using. It appears you are using 1.4.
SECOND: I am not sure this answers all your questions, but,
"closed\_wrt\_vars S P" says that the lifted assertion P is closed with respect to all the variables in the set S. That is, S is a set of C-language identifiers that may stand for nonaddressable local variables ("temps", not "vars"). P is an assertion of the form "environ->mpred", and "closed" means that if you change the "environ" to have different values for any of the variables in set S, then the truth of P will not change.
"Forall" is Coq's standard library predicate to apply a predicate to a list. So,
```
Forall (closed_wrt_vars (eq _z')) [`(array_at tint sh arr 0 100 varr)]
```
means, let the set S be the singleton set containing just the variable \_z'.
We assert here that all the predicates in the list are closed w.r.t. S.
There's exactly one predicate in the list, and it's "trivially lifted",
that is, for any predicate (P: mpred), the lifted predicate
```
`(P)
```
is equivalent to (fun rho:environ => P). Trivially, then, `P doesn't
care what you do to rho, including changing the value of \_z'.
The "auto with closed" (or just to be sure, "auto 50 with closed")
should take care of this, and you indicate that it does take care of it.
So I assume that the rest of your question was, "what's going on here?",
and I hope I answered it. | By the way (unrelated to your question), the precondition
``isptr (eval_id _arr)` for get0 is probably unnecessary.
It is implied already by ``(array_at tint sh arr 0 100) (eval_id _arr))`.
Furthermore, suppose you did want the ``isptr (eval_id _arr)` in your precondition; you might consider writing it as,
```
PROP (isptr varr)
LOCAL (`(eq varr) (eval_id _arr))
SEP (`(array_at tint sh arr 0 100 varr))
```
which is (in some ways) simpler and more "canonical". |
3,229,833 | I am developing a Java Application that uses Hibernate and is connected to an Oracle instance. Another client is looking to use the same application, but requires it run on MS SQL Server. I would like to avoid making changes to the existing annotations and instead create a package of xml files that we can drop in depending on the environment.
One way to do this is using JPA XML configuration to override the existing class annotations. However, JPA does not support generic generators, which is a requirement due to the structure of our legacy database. The other way that I am looking into is to use Hibernate XML configs to remap entire classes and have access to the `generator` xml tag. This solution has some issues though:
* Hibernate does not allow you to selectively override entity members
* Hibernate does not allow you to re-map the same class (e.g. `org.hibernate.AnnotationException: Use of the same entity name twice`)
Does anyone have any experience with overriding annotations using Hibernate XML Configuration files or is JPA the only way to go?
### Update with an Example
In Oracle, Sequences are used to generate unique IDs when inserting new records into the database. An id would then be annotated in the following manner:
```
@Id
@GeneratedValue(generator="EXAMPLE_ID_GEN", strategy=GenerationType.SEQUENCE)
@SequenceGenerator(name="EXAMPLE_ID_GEN", sequenceName="SEQ_EXAMPLE_ID")
@Column(name = "EXAMPLE_ID")
public String getExampleId() {
return this.exampleId;
}
```
However, MS SQL Server does not have the concept of Sequences (Ideological differences). Therefore, you could use a table generator to simulate sequences.
```
@Id
@GeneratedValue(generator="EXAMPLE_ID_GEN", strategy=GenerationType.TABLE)
@TableGenerator(name="EXAMPLE_ID_GEN", tableName="SEQUENCE", valueColumnName="VALUE", pkColumnName="SEQUENCE", pkColumnValue="EXAMPLE_ID")
public String getExampleId() {
return this.exampleId;
}
```
Two different configurations for two different types of databases. Keep in mind that this is a legacy database and that we aren't going to rewrite our application to support SQL Server identities, the native id generator for SQL Server (which would also require a different annotation).
To alleviate this, I have looked into using Hibernate's `@GenericGenerator` and point it to a class of my own creation that models `org.hibernate.id.SequenceGenerator` (or something similar) and also customize the structure of the table by extending `org.hibernate.id.TableStructure`.
Back to my original question - is any of this possible with an XML override?
### How I Solved this Problem
So, in the end, I found that JPA and Hibernate did not provide the out-of-box functionality that I was looking for. Instead, I created a custom generator that checked the database dialect and set the TableStructure appropriately. As I explored all options, I ended up using Hibernate's `@GenericGenerator` annotation. This is an example of the Id generation annotation:
```
@Id
@GeneratedValue(generator="EXAMPLE_ID_GEN")
@GenericGenerator(name = "EXAMPLE_ID_GEN", strategy="com.my.package.CustomIdGenerator", parameters = {
@Parameter(name = "parameter_name", value="parameter_value")
})
public String getExampleId() {
return this.exampleId;
}
```
This solution necessitates that each Hibernate entity be modified with the new Id generator. | 2010/07/12 | [
"https://Stackoverflow.com/questions/3229833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203583/"
] | I think that if you don't use `AnnotationConfiguration` when configuring your `SessionFactory`, the annotations will be omitted.
So, use `Configuration`. | In my case:
Rack and Slot are entities having custom ID Generators. I am using unidirectional one-to-one mapping. Dimension table will hold the data with a Autogenerated Custom ID as foreign key for multiple tables (Rack and Slot for example here).
And my [schema](http://i.stack.imgur.com/oQKHJ.png) looks like this : Rack ------> Dimension <-----------Slot
where Dimension will hold the data for Rack and Slot table with Generated ID.
Here the concern is that when i am saving the data like this:-
```
Rack rack = new Rack(params);
Dimension dim = new Dimension(params);
rack.setDimension(dim);
session.save(rack);
```
Data is being saved successfully with same Autogenerated ID in Rack and Dimension Tables.
But when I am saving the data for Slot table :
```
Slot Slot = new Slot(params);
Dimension dim = new Dimension(params);
slot.setDimension(dim);
session.save(slot);
```
it is showing error message as:-
```
attempted to assign id from null one-to-one property: rack
```
Can I pass the dynamic property name as "slot" when saving the data for Slot and Dimension and "rack" when saving the data for Rack and Dimension.
---
```
@GenericGenerator(name = "foreign", strategy = "foreign", parameters = {
@Parameter(name = "property", value = "slot"),
@Parameter(name = "property", value = "rack")})
```
Rack.java
```
@Entity
@Table(name="tablename")
@GenericGenerator(name = "customseq", strategy = "CustomIdGenerator")
public class Rack {
@Id
@GeneratedValue(generator = "customseq")
@Column(name = "uni_id")
private String id;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private Dimension dimension;
// Getters and Setters
}
```
Slot.java
```
@Entity
@Table(name="tablename")
@GenericGenerator(name = "customseq", strategy = "CustomIdGenerator")
public class Rack {
@Id
@GeneratedValue(generator = "customseq")
@Column(name = "uni_id")
private String id;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private Dimension dimension;
// Getters and Setters
}
```
Dimension.java
```
public class Dimension implements Serializable{
@Id
@Column(name = "systemid")
@GeneratedValue(generator = "foreign")
@GenericGenerator(name = "foreign", strategy = "foreign", parameters = {
@Parameter(name = "property", value = "slot"),
@Parameter(name = "property", value = "rack")})
private String systemid;
@OneToOne(mappedBy = "dimension", fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
private Rack rack;
@OneToOne(mappedBy = "dimension", fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
private Slot slot;
// Getters and Setters
}
``` |
2,717,954 | When i press a button in my app, I need to return to the last activity.
Any ideas? | 2010/04/27 | [
"https://Stackoverflow.com/questions/2717954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/269671/"
] | This is for a situation where the same fragment may sometimes be the only fragment in an activity, and sometimes part of a multi-fragment activity, for example on a tablet where two fragments are visible at the same time.
```
/**
* Method that can be used by a fragment that has been started by MainFragment to terminate
* itself. There is some controversy as to whether a fragment should remove itself from the back
* stack, or if that is a violation of the Android design specs for fragments. See here:
* http://stackoverflow.com/questions/5901298/how-to-get-a-fragment-to-remove-itself-i-e-its-equivalent-of-finish
*/
public static void fragmentImplementCancel(Fragment fragment) {
FragmentActivity fragmentActivity = fragment.getActivity();
FragmentManager fragmentManager = fragmentActivity.getSupportFragmentManager();
if (fragmentManager.getBackStackEntryCount() == 1) {
fragmentManager.popBackStack();
}
else {
fragmentActivity.finish();
}
}
```
This code can be called to implement a Cancel button, for example.
```
if (theButton.getId() == R.id.btnStatusCancel) {
StaticMethods.fragmentImplementCancel(this);
}
``` | You can spoof a up button call on back button press:
```
@Override
public void onBackPressed() {
onNavigateUp();
}
``` |
25,905,540 | For some reason, I can't use the `Tkinter` or `tkinter` module.
After running the following command in the python shell
```
import Tkinter
```
or
```
import tkinter
```
I got this error
>
> ModuleNotFoundError: No module named 'Tkinter'
>
>
>
or
>
> ModuleNotFoundError: No module named 'tkinter'
>
>
>
What could be the reason for and how can we solve it? | 2014/09/18 | [
"https://Stackoverflow.com/questions/25905540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4021630/"
] | On CentOS7, to get this working with Python2, I had to do:
```
yum -y install tkinter
```
Noting this here because I thought that there would be a pip package, but instead, one needs to actually install an rpm. | We can use 2 types of methods for importing libraries
1. work with `import library`
2. work with `from library import *`
You can load tkinter using these ways:
1. `from tkinter import*`
2. `import tkinter` |
34,579,657 | The last `for` loop of my program isn't running. I have realised this is because the arrays are ending up as `null`, therefore it is skipping this part. I am not sure what I am doing wrong when splitting the text as this seems to be making everything go to `null`. Still unsure.
```
String[] splituptext;
for (int loop = 0; loop<temparray.length; loop++) {
splituptext = temparray[loop].split(":");
int score, min;
try {
score = Integer.parseInt(splituptext[1]);
min = Integer.parseInt(splituptext[2]);
} catch(NumberFormatException e) {
System.out.println("Error");
return;
}
splituptext[0] = game[loop];
score = scores[loop];
min = mins[loop];
}
for (int x = 0; x < numofgames; x++) {
System.out.println(playername);
System.out.println(game[x]);
System.out.println(scores[x]);
System.out.println(mins[x]);
}
``` | 2016/01/03 | [
"https://Stackoverflow.com/questions/34579657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5678721/"
] | Regex ranges don't do what you think they do. A `[x-y]` range contains all characters in ascii from `x` to `y`.
Therefore `[0-255]` matches characters from `0` to `2` (aka `0`, `1` and `2`) and `5` or in short - `[0125]`.
---
To match a number from `0` to `255`, you could do:
```
\d\d?|1\d\d|2([0-4]\d|5[0-5])
```
The idea:
* `\d\d?` - one or two digit numbers
* `1\d\d` - numbers from `100` to `199`
* `2[0-4]\d` - numbers from `200` to `249`.
* `25[0-5]` - numbers from `250` to `255`
---
To match an entire IP, you could do:
```
^((\d\d?|1\d\d|2([0-4]\d|5[0-5]))\.){3}(\d\d?|1\d\d|2([0-4]\d|5[0-5]))$
``` | Here is a regex variation (based on [ndn](https://stackoverflow.com/users/2423164/ndn)'s [answer above](https://stackoverflow.com/a/34579651/3832970)) that will check if *the entire input text* is a valid IP:
```
^(?:(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))\.){3}(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))$
```
See [regex demo](https://regex101.com/r/bQ6lA8/1)
Here is a solution that can be used to *extract* valid IPs from larger text:
```
\b(?:(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))\.){3}(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))\b
```
See [another demo](https://regex101.com/r/bQ6lA8/2)
*Explanation*:
* `^` - start of string (replace with `\b` word boundary if you need not match at the beginning of string only)
* `(?:(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))\.){3}` - 3 occurrences of
+ `(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))` - 1- or 2-digit sequence, or a `1xx` number (`1\d{2}`) or a range of integer numbers in-between 200-255 range (thanks to `2(?:[0-4]\d|5[0-5])`)
+ `\.` - a literal period
* `(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))` - see above (just the last part of the IP address)
* `$` - end of string (replace with `\b` if you just need a whole word match).
*NOTE*: In JS, you can use the literal notation to declare these regexps, e.g.:
```
/\b(?:(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))\.){3}(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))\b/g
/^(?:(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))\.){3}(?:\d{1,2}|1\d{2}|2(?:[0-4]\d|5[0-5]))$/
``` |
3,986 | Overview
========
Yesterday I posted the following question [Please make [storage] and [image-storage] synonyms of [online-storage]](https://webapps.meta.stackexchange.com/questions/3982/please-make-storage-and-image-storage-synonyms-of-online-storage). At this time, it received two comments mentioning that [online-storage](https://webapps.stackexchange.com/questions/tagged/online-storage "show questions tagged 'online-storage'") is a meta-tag, so I'm wondering if there any tag in Web Applications that is not about a specific web app or web app feature, besides bookmarklets and browsers features which are directly related to web application like Greasemonkey scripts that is not a meta-tag.
At this time it looks to me that most tags in Web Applications site should use the name of a web application or a prefix to related it to a web application to make it be able to be used alone and make it means the same for different people as it's required by the [tags help article](https://webapps.stackexchange.com/help/tagging) but could be exceptions like *things* that are commonly used by different web apps.
Which are those tags and why they aren't a meta-tag in the context of Web Applications?
Proposal: Add one answer for each of this tags and explain why it's not a meta-tag.
Related meta questions
----------------------
[Let's clean up some meta tags](https://webapps.meta.stackexchange.com/questions/2696/lets-clean-up-some-meta-tags)
Examples of tags that are specific to web applications
------------------------------------------------------
[facebook](https://webapps.stackexchange.com/questions/tagged/facebook "show questions tagged 'facebook'")
[gmail](https://webapps.stackexchange.com/questions/tagged/gmail "show questions tagged 'gmail'")
[google-spreadsheets](https://webapps.stackexchange.com/questions/tagged/google-spreadsheets "show questions tagged 'google-spreadsheets'")
[google-drive](https://webapps.stackexchange.com/questions/tagged/google-drive "show questions tagged 'google-drive'")
[trello](https://webapps.stackexchange.com/questions/tagged/trello "show questions tagged 'trello'")
[twitter](https://webapps.stackexchange.com/questions/tagged/twitter "show questions tagged 'twitter'")
[youtube](https://webapps.stackexchange.com/questions/tagged/youtube "show questions tagged 'youtube'")
Examples of tags that are specific to a web application feature
---------------------------------------------------------------
### Gmail
[gmail-filters](https://webapps.stackexchange.com/questions/tagged/gmail-filters "show questions tagged 'gmail-filters'")
[gmail-labels](https://webapps.stackexchange.com/questions/tagged/gmail-labels "show questions tagged 'gmail-labels'")
[gmail-search](https://webapps.stackexchange.com/questions/tagged/gmail-search "show questions tagged 'gmail-search'")
### Facebook
[facebook-groups](https://webapps.stackexchange.com/questions/tagged/facebook-groups "show questions tagged 'facebook-groups'")
[facebook-pages](https://webapps.stackexchange.com/questions/tagged/facebook-pages "show questions tagged 'facebook-pages'")
[facebook-timeline](https://webapps.stackexchange.com/questions/tagged/facebook-timeline "show questions tagged 'facebook-timeline'")
Examples of tags that are not specific to web application
---------------------------------------------------------
[collaboration](https://webapps.stackexchange.com/questions/tagged/collaboration "show questions tagged 'collaboration'")
[dns](https://webapps.stackexchange.com/questions/tagged/dns "show questions tagged 'dns'")
[domain](https://webapps.stackexchange.com/questions/tagged/domain "show questions tagged 'domain'")
[email](https://webapps.stackexchange.com/questions/tagged/email "show questions tagged 'email'")
[export](https://webapps.stackexchange.com/questions/tagged/export "show questions tagged 'export'")
[formulas](https://webapps.stackexchange.com/questions/tagged/formulas "show questions tagged 'formulas'")
[hosting](https://webapps.stackexchange.com/questions/tagged/hosting "show questions tagged 'hosting'")
[import](https://webapps.stackexchange.com/questions/tagged/import "show questions tagged 'import'")
[ip-address](https://webapps.stackexchange.com/questions/tagged/ip-address "show questions tagged 'ip-address'")
[links](https://webapps.stackexchange.com/questions/tagged/links "show questions tagged 'links'")
[offline](https://webapps.stackexchange.com/questions/tagged/offline "show questions tagged 'offline'")
[sharing](https://webapps.stackexchange.com/questions/tagged/sharing "show questions tagged 'sharing'")
[search](https://webapps.stackexchange.com/questions/tagged/search "show questions tagged 'search'")
[sorting](https://webapps.stackexchange.com/questions/tagged/sorting "show questions tagged 'sorting'")
[statistics](https://webapps.stackexchange.com/questions/tagged/statistics "show questions tagged 'statistics'")
[url](https://webapps.stackexchange.com/questions/tagged/url "show questions tagged 'url'")
[url-shortening](https://webapps.stackexchange.com/questions/tagged/url-shortening "show questions tagged 'url-shortening'")
[video](https://webapps.stackexchange.com/questions/tagged/video "show questions tagged 'video'")
[website](https://webapps.stackexchange.com/questions/tagged/website "show questions tagged 'website'")
Examples of tags that could be ok as suggested by ale on their answer
---------------------------------------------------------------------
[security](https://webapps.stackexchange.com/questions/tagged/security "show questions tagged 'security'")
[rss](https://webapps.stackexchange.com/questions/tagged/rss "show questions tagged 'rss'")
[spam-prevention](https://webapps.stackexchange.com/questions/tagged/spam-prevention "show questions tagged 'spam-prevention'")
Examples of tags related to bookmarklets or browsers features that could be directly related to web applications
----------------------------------------------------------------------------------------------------------------
[bookmarklet](https://webapps.stackexchange.com/questions/tagged/bookmarklet "show questions tagged 'bookmarklet'")
[bookmarklet-rec](https://webapps.stackexchange.com/questions/tagged/bookmarklet-rec "show questions tagged 'bookmarklet-rec'")
[userscripts](https://webapps.stackexchange.com/questions/tagged/userscripts "show questions tagged 'userscripts'")
Examples of tags about *things* that are commonly used in web applications and could not be meta-tags
-----------------------------------------------------------------------------------------------------
* [html](https://webapps.stackexchange.com/questions/tagged/html "show questions tagged 'html'")
* [html5](https://webapps.stackexchange.com/questions/tagged/html5 "show questions tagged 'html5'")
* [javascript](https://webapps.stackexchange.com/questions/tagged/javascript "show questions tagged 'javascript'")
--- | 2016/03/15 | [
"https://webapps.meta.stackexchange.com/questions/3986",
"https://webapps.meta.stackexchange.com",
"https://webapps.meta.stackexchange.com/users/88163/"
] | I don't think we can come up with a definitive list. It'd be as hard to come up with a list of tags that *aren't* meta-tags.
I think there are some non-application-specific tags that are okay, even if they could possibly be considered meta-tags.
* [privacy](https://webapps.stackexchange.com/questions/tagged/privacy "show questions tagged 'privacy'")
* [security](https://webapps.stackexchange.com/questions/tagged/security "show questions tagged 'security'")
* [spam-prevention](https://webapps.stackexchange.com/questions/tagged/spam-prevention "show questions tagged 'spam-prevention'")
While these don't have much context without being attached to a particular web app, I think they'll be attractive to people who are interested in such things, and there *are* people who are experts on such topics who could answer a lot of our questions.
That's by no means an exhaustive list, of course.
That's why it seems that we would need to discuss each one individually and come to a consensus. Some, like those I've been posting lately, seem obvious *to me*. But I put them up for discussion because someone may have a different take.
---
Let's look at why we have tags at all: They're to help categorize questions so that they're easier to find. "Easier" for who? For the people who have knowledge and can answer questions. Tags aren't much use to Askers; they probably got here through a Google search. It's for Answerers that we have the tags.
There are too many questions here for anyone to read *every* question that comes through, and this is a pretty low-volume site. So we have tags to help Answerers find questions they can answer. For instance, I know a little bit about Facebook (ugh), many of the Google apps, Dropbox, plus a few more. Questions on those topics I can probably answer, so I have a set of favorite tags (or wildcards) so I can find those questions easily.
So, when we look at the utility of a tag, we should really be asking ourselves: "Is this tag something that someone with knowledge would look for?" Who in the world would come to a site about Web applications looking to answer questions about [subscriptions](https://webapps.stackexchange.com/questions/tagged/subscriptions "show questions tagged 'subscriptions'")? A specific *type* of subscription, perhaps, but then it's far more likely they'll be looking for questions tagged with the app(s) they know about. | Hacking tags
============
I'm using "hacking" here to refer to the activity of explore the limits of web applications and to find not too easy to figure out how tos which result in a "hack" or "clever solution"
Below there are a list of tags that could be "hacking tools" grouped in four categories, including the numbers of question tagged for each one.
Is there one or several missing tags missing?
Basic tools
-----------
* [css](https://webapps.stackexchange.com/questions/tagged/css "show questions tagged 'css'"): 23
* [html](https://webapps.stackexchange.com/questions/tagged/html "show questions tagged 'html'"): 74
* [html5](https://webapps.stackexchange.com/questions/tagged/html5 "show questions tagged 'html5'"): 32
* [javascript](https://webapps.stackexchange.com/questions/tagged/javascript "show questions tagged 'javascript'"): 43
Intermediate tools
------------------
* [bookmarklet](https://webapps.stackexchange.com/questions/tagged/bookmarklet "show questions tagged 'bookmarklet'"): 22
* [userscripts](https://webapps.stackexchange.com/questions/tagged/userscripts "show questions tagged 'userscripts'"): 10
* [formulas](https://webapps.stackexchange.com/questions/tagged/formulas "show questions tagged 'formulas'"): 119
Advanced tools
--------------
* ~~[google-apps-script](https://webapps.stackexchange.com/questions/tagged/google-apps-script "show questions tagged 'google-apps-script'"): 351~~
* [google-api](https://webapps.stackexchange.com/questions/tagged/google-api "show questions tagged 'google-api'"): 24
* [twitter-api](https://webapps.stackexchange.com/questions/tagged/twitter-api "show questions tagged 'twitter-api'"): 21
* [google-chart-api](https://webapps.stackexchange.com/questions/tagged/google-chart-api "show questions tagged 'google-chart-api'"): 6
Browser extensions
------------------
* [extensions](https://webapps.stackexchange.com/questions/tagged/extensions "show questions tagged 'extensions'"): 6
* [browser-addons](https://webapps.stackexchange.com/questions/tagged/browser-addons "show questions tagged 'browser-addons'"): 10
* [firefox-extensions](https://webapps.stackexchange.com/questions/tagged/firefox-extensions "show questions tagged 'firefox-extensions'"): 17
* [google-chrome-extensions](https://webapps.stackexchange.com/questions/tagged/google-chrome-extensions "show questions tagged 'google-chrome-extensions'"): 46
Infrastructure
--------------
* [dns](https://webapps.stackexchange.com/questions/tagged/dns "show questions tagged 'dns'")
* [ip-address](https://webapps.stackexchange.com/questions/tagged/ip-address "show questions tagged 'ip-address'")
Related
=======
<https://webapps.meta.stackexchange.com/questions/3994/please-make-extensions-a-synonym-of-browser-addons>
REMARKS
I strike through [google-apps-script](https://webapps.stackexchange.com/questions/tagged/google-apps-script "show questions tagged 'google-apps-script'") as it's web application, not just a tool. |
14,797,401 | I want to pass raw html from view to controller. Iam trying to do it with jquery ajax request. Everything is ok until object with raw html passes to controller. What is my mistake?
Here is my model, controller and jquery.
Thank you.
Model
```
public class NewsEditionModel
{
public string Title { get; set; }
public string SubTitle { get; set; }
public string Text { get; set; }
}
```
Controller
```
public ActionResult AddText(NewsEditionModel obj)
{
var news = new News();
try
{
news.Text = obj.Text;
news.PublishDate = DateTime.Now;
news.Title = obj.Title;
var repository = new Repository();
var success = repository.AddNews(news, User.Identity.Name);
return Json(new {data = success});
}
catch (Exception)
{
return View("Error");
}
}
```
Jquery
```
function submitForm() {
var text = ste.getContent();
var title = $('#title').val();
var obj1 = JSON.stringify({ Text: text, Title: title, SubTitle: "" });
var obj = $.parseJSON(obj1);
$.ajax({
type: "POST",
dataType: "json",
content: "application/json",
data: {obj: obj},
url: '@Url.Action("AddText", "News")',
success: function (res) {
}
});
}
``` | 2013/02/10 | [
"https://Stackoverflow.com/questions/14797401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765751/"
] | Just add `<ValidateInput(False)> _` to your contoller post req. | You can use this example
```
$.ajax({
url: '@Url.Action("AddText", "News")',
data: {obj: JSON.stringify({ Text: text, Title: title, SubTitle: "" })},
contentType: 'application/json',
dataType: 'json',
success: function (data) { alert(data); }
});
``` |
26,182,824 | Can you please tell me if it is possible to have a 2D array with two day types. I am new to C#.
For example: `array[double][string]`
I have radius of flowers alone with their name as follows:
```
4.7,Iris-setosa
4.6,Iris-setosa
7,Iris-versicolor
6.4,Iris-versicolor
6.9,Iris-versicolor
5.5,Iris-versicolor
6.5,Iris-versicolor
6.3,Iris-virginica
5.8,Iris-virginica
```
I would like to put these in to a 2D array and sort it according to the first `double` index. Please let me know if this is possible with an example. | 2014/10/03 | [
"https://Stackoverflow.com/questions/26182824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1255576/"
] | As comments have said, you likely want a simple class for this:
```
public class Flower {
public double Radius { get; set; }
public string Name { get; set; }
}
var l = new List<Flower>();
l.Add(new Flower() { Radius = 4.7, Name = "Iris-setosa" });
l.Add(new Flower() { Radius = 4.6, Name = "Iris-setosa" });
/* ... */
Flower[] sorted = l.OrderBy(f => f.Radius).ToArray();
```
You could get away with an array of `KeyValuePair<int, string>`, but I don't see much reason to go that route unless you're just looking for something quick and dirty. | If you don't want to create a class for some reason you can also use [Anonymous Types](http://msdn.microsoft.com/en-us/library/bb397696.aspx), so for your case it will be something like:
```
var a1 = new[] {
new {Radius = 4.7, Name = "Iris-setosa"},
new {Radius = 4.6, Name = "Iris-setosa"}
};
``` |
831,102 | Is there a VB6 equivalent to the C/C++ 'continue' keyword?
In C/C++, the command 'continue' starts the next iteration of the loop.
Of course, other equivalents exist. I could put the remaining code of the loop in an if-statement. Alternatively, I could use a goto. (Ugh!) | 2009/05/06 | [
"https://Stackoverflow.com/questions/831102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91769/"
] | There is no equivalent in VB6, but later versions of VB do introduce this keyword. This article has a more in-depth explanation: <http://vbnotebookfor.net/2007/06/04/the-continue-statement/>
Perhaps you can restructure your code to either add an if statement or have the loop just call a function that you can return from. | I´m an idiot :P thanks MarkJ
```
For index As Integer = 1 To 10
If index=9 Then
Continue For
End If
'some cool code'
Next
```
No sorry only for .net.
I think you have to use goto, I know it looks ‘cleaner’ to use a continue but there is nothing wrong with going the if route.
wrong.
```
Continue:
For index As Integer = 1 To 10
If index=9 Then
GoTo Continue
End If
'some cool code'
Next
```
corrected(?)
```
For index = 1 To 10
If index=9 Then
GoTo Continue
End If
'some cool code'
Continue:
Next
```
hate vb |
5,855,505 | I have a custom Adapter that renders some items in a ListView. I need to show an icon on the ListView's items, if the item's text is ellipsized, and hide it if there's enough room for the text to finish. I have access to the button in getView method of my adapter (where I set the text) but the ellipses are not added immediately upon setting the text.
Is there any way I can do this?
Here's my TextView markup:
```
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:singleLine="true"
android:id="@+id/list_item_description"/>
``` | 2011/05/02 | [
"https://Stackoverflow.com/questions/5855505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54538/"
] | >
> [public int getEllipsisCount (int line)](http://developer.android.com/reference/android/text/StaticLayout.html#getEllipsisCount%28int%29):
>
>
> Returns the number of characters to be ellipsized away, or 0 if no ellipsis is to take place.
>
>
>
So, simply call :
```
if(textview1.getLayout().getEllipsisCount() > 0) {
// Do anything here..
}
```
Since the getLayout() cant be called before the layout is set, use ViewTreeObserver to find when the textview is loaded:
```
ViewTreeObserver vto = textview.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Layout l = textview.getLayout();
if ( l != null){
int lines = l.getLineCount();
if ( lines > 0)
if ( l.getEllipsisCount(lines-1) > 0)
Log.d(TAG, "Text is ellipsized");
}
}
});
```
And finally do not forget to remove **removeOnGlobalLayoutListener** when you need it nomore. | You can either set your text to marque.
add this in your code might help.....
```
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
android:freezesText="true"
android:marqueeRepeatLimit="marquee_forever"
```
You can also put a horizontal scrollview for you code....
```
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/list_item_description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:ellipsize="end"
android:gravity="center_vertical"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</HorizontalScrollView>
``` |
37,272,814 | ```
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("abcde").password("123456").roles("USER");
}
```
and i am getting an error in the last line, it says that
```
The type org.springframework.security.authentication.AuthenticationManager cannot be resolved. It is indirectly referenced from required .class files
```
I have looked for a solution and cannot find a way to fix it. | 2016/05/17 | [
"https://Stackoverflow.com/questions/37272814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4505897/"
] | Add spring-security-core.jar to the Build Path of the project. If you are using Eclipse, right click on project --> Properties --> Java Build Path --> Libraries --> click Add jars or Add external jars and point to the jar file.
Also, do clean build. | If you use gradle, it's more easy check if you have these libraries ... compile
* spring-security-web
* spring-security-config
* spring-security-taglibs
* spring-security-ldap
* spring-boot-starter-ws
* spring-security-core |
886,744 | I want to install JDK 1.5 and 1.6 on XP, is it possible? how to do it
Also, I am using Eclipse how to setup using different JDK for different projects?
thanks. | 2009/05/20 | [
"https://Stackoverflow.com/questions/886744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103340/"
] | I have solved this by creating batch files for different Java versions.
1. I have installed the Java versions I need to have
2. Whenever, I need to use Java I run the appropriate batch file and set the environment variables to work with that Java version.
**Java 8.bat**
```
@echo off
echo Setting JAVA_HOME
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_121
echo setting PATH
set PATH=%JAVA_HOME%\bin;%PATH%
echo Display java version
java -version
```
**Java 10.bat**
```
@echo off
echo Setting JAVA_HOME
set JAVA_HOME=C:\Program Files\Java\jdk-10.0.2
echo setting PATH
set PATH=%JAVA_HOME%\bin;%PATH%
echo Display java version
java -version
``` | There was a big mess with different incompatible JDK and JRE from 90s when Java was created and still this problem exists.
The main rule is when you type in console:
`java -version`
and
`javac -version`
the result should be the same then you sure both JRE and JDK (JSDK) are compatible, so when you compile you can rut it without any problems.
`JAVA_HOME` and `PATH` are essential for many console applications
and some GUI tools might use those variables as well but often is possible to alter default settings in GUI application instead of messing with environment variables. Also `CLASSPATH` still sometimes are used as well, however better use ANT as compiler than javac directly.
You can install multiple JDK and JRE but each one should to have its own separate folder, the default should be usually ok.
Worth mentioning that every JDK have JRE included and it instal in separate folder and as separate APP in **Windows Control Panel -> Applications** to be more confusing, so basically developer will never have to download and install JRE. Do not use Java update application which might cause problems after update some apps might not work, just do it manually. |
84,605 | For some time you could see pictures someone sent you via Hangouts in an album called "Hangouts". This vanished somehow.
When you open a picture from Hangouts on the Computer, you can still see in the URL that there is some kind of album. The URL is in the form `https://plus.google.com/u/0/photos/albums/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX` and you can even browse this album.
How can I get to this album from Google Plus or Google Photos? | 2015/09/18 | [
"https://webapps.stackexchange.com/questions/84605",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/98286/"
] | It appears this has been deprecated. If you want to download all of the images that have ever been shared with you over hangouts, you need to use Google Takeout.
* Visit <https://takeout.google.com/settings/takeout>
* Deselect all
* Select Hangouts
* Hit the download button
Google will send you a .zip link with all of the images. | **Viewing Photos shared with you**
On <https://get.google.com/albumarchive/> you can only see photos that were shared **by you**. To see the album of pictures shared **with you** by a specific person, perform the following steps:
1. Navigate to the Person’s G+ Profile (by clicking on the person’s icon in Hangouts)
2. Select "About" button in the profile’s header
3. Scroll down to "You & Person" and click "See all photos"
4. Select the "Photos from Hangouts" album |
30,987,883 | How do I install PHP 7 (PHP next generation) on Ubuntu?
I wanted to install PHP 7 on a clean install of Ubuntu to see what issues I would face.
Here’s the official (yet meager guide):
<https://wiki.php.net/phpng> | 2015/06/22 | [
"https://Stackoverflow.com/questions/30987883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4323201/"
] | Ondřej Surý has a PPA at <https://launchpad.net/~ondrej/+archive/ubuntu/php>
```
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt-get install php7.0
```
Using the PPA is certainly easier than building from source!
A note for people with PHP 5.x already installed; `apt-get` complained a bit when I tried to install install php7.0 on a box with PHP 5 on it, but after I did `apt-get remove php5` to get rid of my existing PHP 5.6 install and then explicitly did `sudo apt-get install php7.0-common` I was able to get the `sudo apt-get install php7.0` to go through. Don't know why this was necessary; if somebody who understands Apt better than I do would like to edit in some better instructions (or provide a better answer altogether and ask me to delete this one) then feel free. | You could install a control panel that supports Ubuntu and PHP 7. For example, ServerPilot [supports Ubuntu](https://serverpilot.io/community/articles/ubuntu-control-panel.html) and [installs PHP 7](https://serverpilot.io/blog/2015/08/20/php-7.0-available-on-all-servers.html). |
46,519 | This is what I get with `\textbar`:

This is what I want it to look like:
 | 2012/03/02 | [
"https://tex.stackexchange.com/questions/46519",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/9610/"
] | Use a `\rule`
```
\documentclass{article}
\newcommand{\lpipe}{\rule[-0.4ex]{0.41pt}{2.3ex}}
\begin{document}
Wintersemester 2011 \lpipe\ 2012
\end{document}
```

The optional argument takes a vertical lift, the first mandatory argument takes the line width and the second the height. You may adjust the values to fit your needs (and font settings)
Update
------
```
\documentclass{article}
\newcommand{\lpipe}{\smash{\rule[-0.4ex]{0.41pt}{42ex}}}
\begin{document}
Some text to fill the lines and see the \verb+\baselineskip+ increasing.
Now let's type the \lpipe\ pipe. And some more filler text. And some more
filler text. And some more filler text. And some more filler text. More
filler text. And some more filler text. And some more filler text. More
filler text. And some more filler text. And some more filler text.
\bigskip
H\lpipe H\\
H \lpipe\ H
\end{document}
```
Update 2
--------
I added `\smash` to the definition of `\lpipe` to make it not affect the line height. But I think that the line should be only as heigh as possible without increasing the line (even without `\smash`). Otherwise it will hardly fit to the used font.
To illustrate this I took this picture

which is the result of this code
```
\documentclass{article}
\newcommand{\lpipe}{\rule[-0.4ex]{0.41pt}{2.3ex}}
\newcommand{\badlpipe}{\smash{\rule[-0.4ex]{0.41pt}{3.2ex}}}
\begin{document}
Some text to fill the lines and see the \verb+\baselineskip+ increasing.
Now let's type the \lpipe\ pipe. And some more filler text. And some more
filler text. And some more filler text. And some more filler text. More
filler text. And some more filler text. And some more filler text. More
filler text. And \badlpipe\ some more filler text. And some more filler text.
\end{document}
```
The `\badlpipe` is a litte to long to not affect the line height, so I used `\smash`. But one can easily see that this is very bad style and looks not good … | Here is an alternative:
```
\documentclass{standalone}
\begin{document}
Wintersemester 2012 $\mid$ 2013
\end{document}
```
 |
62,413,459 | I'm altering the fabcar version of hyperledger fabric and wrote some functions. When I executed, I got an error mentioned below (command mentioned below is of shell script)
```
$ peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --tls --cafile $ORDERER_CA -C $CHANNEL_NAME -n cloud $PEER_CONN_PARMS --isInit -c '{"function":"uploadData","Args":["DATA1","ID12345","/home/samplefile___pdf","3"]}'
Error: endorsement failure during invoke. response: status:500 message:"error in simulation: transaction returned with failure: Function uploadData not found in contract SmartContract"
```
Below is the chaincode (abstractly mentioned)
```
type SmartContract struct {
contractapi.Contract
}
type Data struct {
Owner string `json:"owner"`
File string `json:"file"`
FileChunkNumber string `json:"filechunknumber"`
SHA256 string `json:"sha256"`
}
// Uploads new data to the world state with given details
func (s *SmartContract) uploadData(ctx contractapi.TransactionContextInterface, args []string) error {
/*...*/
}
```
I don't get where to alter the changes | 2020/06/16 | [
"https://Stackoverflow.com/questions/62413459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13747617/"
] | I think the problem in your case is in the variable type you are using to display the information. I am not sure how you are using `json_decode` in your PHP code, but if you are using `$post['title']` then your answer is converted to a PHP associative array.
So, when you are doing your foreach, instead of using `stdClass` you should be using the array like this:
```php
<?php foreach ( $post['categories'] as $nameCategory) { ?>
<a href="<?php echo $nameCategory['slug']?>"><?php echo $nameCategory['text']; ?></a>
<?php } ?>
```
If you do a `print_r($post)` or `var_dump($post)` you should see the variable types you are using.
Also, when using an array as an object you should be getting an error message from PHP so you should check your php.ini configuration to see if your error messages are disabled or in its case are being saved to a log file. | Your data structure as displayed seems to be JSON. But since you can get some values out of it, I will not bother about it. The reason you are not getting the right value is most likely wrong targeting. This particular set of data is nested inside another 'array' so to speak; simply reach it using the right name like:
```
echo $post['categories']['slug'];
echo $post['categories']['text'];
``` |
10,643,116 | Is that even possible? I have two ObservableCollections. I want to bind and populate a listbox with one of them. For example let's say that we have 2 buttons - one for Twitter and one for Facebook. Clicking on a Facebook button it will populate listbox with friend's names from facebook observable collection and it will bind it. Clicking on Twitter it will populate listbox with Twitter followers and populate listbox and bind it.
How to choose which collection will be populated in listbox? | 2012/05/17 | [
"https://Stackoverflow.com/questions/10643116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1401931/"
] | I would just use one observable collection and fill based on the users choice. You could also fill it with the names from both sources and have a filter to filter out one or the other (apparently you need a wrapper object where you can indicate whether the name is a facebook friend or twitter follower).
**Edit**: Here is some quick code example of how you can do it:
```
public interface ISocialContact
{
string Name { get; }
}
public class FacebookContact : ISocialContact
{
public string Name { get; set; }
public string FacebookPage { get; set; }
}
public class TwitterContact : ISocialContact
{
public string Name { get; set; }
public string TwitterAccount { get; set; }
}
```
Then in your data context:
```
public ObservableCollection<ISocialContact> Contacts { get; set; }
...
Contacts = new ObservableCollection<ISocialContact> {
new FacebookContact { Name = "Face", FacebookPage = "book" },
new TwitterContact { Name = "Twit", TwitterAccount = "ter" }
};
```
And in your xaml:
```
<Grid>
<Grid.Resources>
<DataTemplate DataType="{x:Type local:FacebookContact}">
<TextBlock Text="{Binding FacebookPage}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:TwitterContact}">
<TextBlock Text="{Binding TwitterAccount}"/>
</DataTemplate>
</Grid.Resources>
<ListBox ItemsSource="{Binding Contacts}" Width="100" Height="100"/>
</Grid>
```
This will apply the appropriate template to each object in your collection. So you can have collection with just facebook contacts or just twitter contacts or mixed.
Also note: You do not need the common interface. It will also work if you just make your `ObservableCollection` of type `object`. But given that they are being displayed by the same app in the same list box indicates that you can find some kind of common base and either can create a comon interface or base class. | In your ViewModel, create a property that exposes one or the other ObservableCollection, and swap it out when the button is clicked:
```
private ObservableCollection<string> _twitterFriendList;
private ObservableCollection<string> _facebookFriendList;
private ObservableCollection<string> _selectedFriendList;
public ObservableCollection<string> SelectedFriendList
{
get { return _selectedFriendList; }
set
{
if (value != _selectedFriendList)
{
_selectedFriendList = value;
RaisePropertyChanged("SelectedFriendList");
}
}
}
void TwitterButton_Click(object sender, RoutedEventArgs e)
{
SelectedFriendList = _twitterFriendList;
}
void FacebookButton_Click(object sender, RoutedEventArgs e)
{
SelectedFriendList = _facebookFriendList;
}
```
Then in your XAML you can just bind to the property:
```
<ListBox ItemsSource="{Binding SelectedFriendList}"/>
``` |
281,794 | I have a lot of `.csv` files that I need to plot. However, the numeric data comes, sometimes, among quotes or just as numbers (without the quotes).
For example
```
a,b,c,d
"1","4","5","1"
"2","3","1","5"
"3","5","6","1"
4,1,4,9
5,3,4,7
```
My question is if there is an option in `pgfplots` to pre-process the data and remove the quotes if they are present. Or it is too much trouble to do it from here (LaTeX and friends) and I should generate outside scripts to pre-process the data.
```
\documentclass{article}
\usepackage{pgfplots}
\usepackage{filecontents}
\begin{filecontents*}{data.csv}
a,b,c,d
"1","4","5","1"
"2","3","1","5"
"3","5","6","1"
4,1,4,9
5,3,4,7
\end{filecontents*}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot table [x=a, y=c, col sep=comma] {data.csv};
\end{axis}
\end{tikzpicture}
\end{document}
``` | 2015/12/06 | [
"https://tex.stackexchange.com/questions/281794",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/7561/"
] | If you're not tied to `pgfplots`, [`dataplot`](http://ctan.org/pkg/datatool) can handle quotes in the CSV file. It's far more limited that `pgfplots` and if your real data is a lot larger than the data provided in your MWE it may not cope so well. However, I thought I may as well add this as a possible alternative in case it's useful.
Since `dataplot` uses `datatool` you need to first load the data before you can plot it:
```
\documentclass{article}
\usepackage{dataplot}
\usepackage{filecontents}
\begin{filecontents*}{data.csv}
a,b,c,d
"1","4","5","1"
"2","3","1","5"
"3","5","6","1"
4,1,4,9
5,3,4,7
\end{filecontents*}
\DTLloaddb{data}{data.csv}
\begin{document}
\DTLplot{data}{x=a,y=c}
\end{document}
```
You can change the default appearance using extra keys and various commands. For example:
```
\documentclass{article}
\usepackage{dataplot}
\usepackage{filecontents}
\begin{filecontents*}{data.csv}
a,b,c,d
"1","4","5","1"
"2","3","1","5"
"3","5","6","1"
4,1,4,9
5,3,4,7
\end{filecontents*}
\DTLloaddb{data}{data.csv}
\begin{document}
\setcounter{DTLplotroundXvar}{0}% round x tic values to 0 dp
\setcounter{DTLplotroundYvar}{0}% round y tic values to 0 dp
\DTLplot{data}{colors={blue},% line colours
x=a,% column for x values
y=c,% column for y values
box,% box around plot
style=both,% lines and markers
marks={\pgfuseplotmark{*}},% filled circle markers
minx=0,% minimum value on x-axis
maxx=6,% minimum value on x-axis
miny=0,% minimum value on x-axis
maxy=8,% maximum value on x-axis
xticgap=1,% gap between tic marks on x-axis
yticgap=2,% gap between tic marks on y-axis
axes=both% both axes
}
\end{document}
```
This produces:
[](https://i.stack.imgur.com/94n8u.png) | Dangerous method: set `\catcode`"=9`; safer method: remove the quotes.
```
\documentclass{article}
\usepackage{pgfplots}
\usepackage{filecontents}
\begin{filecontents*}{\jobname.csv}
a,b,c,d
"1","4","5","1"
"2","3","1","5"
"3","5","6","1"
4,1,4,9
5,3,4,7
\end{filecontents*}
\begin{filecontents*}{\jobname-noquote.csv}
a,b,c,d
1,4,5,1
2,3,1,5
3,5,6,1
4,1,4,9
5,3,4,7
\end{filecontents*}
\begin{document}
\begin{tikzpicture}
\begin{axis}\catcode`"=9
\addplot table [x=a, y=c, col sep=comma] {\jobname.csv};
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}
\addplot table [x=a, y=c, col sep=comma] {\jobname-noquote.csv};
\end{axis}
\end{tikzpicture}
\end{document}
```
[](https://i.stack.imgur.com/RBgDv.png)
Thanks to Christian Feuersänger! We can use the key `ignore chars`, section 2.1 of the manual of `pgfplotstable`.
```
\documentclass{article}
\usepackage{pgfplots}
\usepackage{filecontents}
\begin{filecontents*}{\jobname.csv}
a,b,c,d
"1","4","5","1"
"2","3","1","5"
"3","5","6","1"
4,1,4,9
5,3,4,7
\end{filecontents*}
\begin{filecontents*}{\jobname-noquote.csv}
a,b,c,d
1,4,5,1
2,3,1,5
3,5,6,1
4,1,4,9
5,3,4,7
\end{filecontents*}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot table [x=a, y=c, col sep=comma,ignore chars={"}] {\jobname.csv};
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}
\addplot table [x=a, y=c, col sep=comma] {\jobname-noquote.csv};
\end{axis}
\end{tikzpicture}
\end{document}
``` |
484,742 | Is there any way to improve code completion in notepad++?
Currently it supports some kind of "static" code completion and it requires to make a list of instructions and they parameters in xml file or it works on a list of words in open document. I`m looking for something that can read \*.h files and make that list automatically and also use variables and functions from current file. | 2009/01/27 | [
"https://Stackoverflow.com/questions/484742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58877/"
] | You have some code completion sections to look at [here](http://cybernetnews.com/2008/06/16/notepad-50-can-auto-complete-code/). But i would mainly suggest you change to an IDE for the programming language because Notepad++ doesn't have any of the benefits you find in a Real IDE. ( Maybe because it's a text-editor and not an IDE ). | Not possible without creating your own plugin.
It might be faster to develop a script that parses your .h files and creates an auto-complete language file for notepad++.
Although a plugin that parsed your include files (for any language) and added them to the auto-complete would be very nice. |
39,622,173 | I just upgraded to MacOS Sierra, and I realized that I can't seem to run the "ssh -X" command in the Terminal anymore. It used to launch xterm windows, but now it's like I didn't even put the -X option anymore. It was working absolutely fine right before I updated. Other than going from OS X Yosemite to MacOS Sierra, I didn't change anything else in the setup.
EDIT:
As suggested, this is what I found in the debug logs that might be causing this problem.
```
debug1: No xauth program.
Warning: untrusted X11 forwarding setup failed: xauth key data not generated
``` | 2016/09/21 | [
"https://Stackoverflow.com/questions/39622173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5035553/"
] | Just upgraded my macbook from El Capitan to Sierra. Simply reinstalling Xquartz has done the trick for me, using ssh -X [linux server] | I spent the whole day looking for solution only to realize that the recent Sierra does not ship with XQuartz installed <https://support.apple.com/en-gb/HT201341>. Upon install (<https://www.xquartz.org/>) all works. |
121,089 | I recently started teaching activities in an American institution.
I have had a couple of students asking for extensions for problem sets / project deadlines for medical or family reasons, which is obviously acceptable. More unexpectedly, other students asked for extensions because they also had problem sets, quizzes and projects due for other classes during the same period (end of semester). Note that there is a buffer period between classes and exams, so we are not talking about conflicts with finals here.
I studied in a different country, in a notoriously work-intensive institution, so the idea that having homework for class X would somehow be an excuse to turn in homework late for class Y simply never occurred to me. I feel that no class should have priority over other classes - if it was the case, differences in credits would reflect that (my class is not a "small one" with little credit). Yes, sometimes students have a lot of work - but is it not part of real life too? On the other hand, the fact that students made these requests so openly makes me think that it might be normal here in the US, and I wouldn't want to be more strict than the local standards.
Is there any kind of norm regarding what is considered as an acceptable reason to ask for an extension? | 2018/12/05 | [
"https://academia.stackexchange.com/questions/121089",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/97206/"
] | Asking if there is a norm for what is “acceptable” assumes that students care about such norms, but sadly some don’t, and will always try to push the boundaries of what is acceptable. It is up to you to set limits, and this is not especially difficult, and certainly not considered unreasonable in the (U.S., large public university) environment I am familiar with.
I suggest that the next time you start teaching a new class, you include a statement in your course syllabus saying “Deadline extensions for course assignments will not be given except in exceptional, justifiable circumstances”, or something to that effect. Then if students ask, all you need to do is point them to the policy. Problem solved.
As for this semester, assuming you have not had such a written policy that students were expected to have read, it might be reasonable to be a bit more merciful if you are so inclined. But you would still be perfectly within your rights and common sense not to give extensions even then. | I would recommend against the practice in general, but with a variation. It is good to tell students at the beginning what happens if deadlines are missed and to stick to those rules except for emergency situations.
You can certainly publish in your course materials the consequences of being late. My own practice would suggest about a 5% (half a grade) penalty for missing the deadline with a limit on how late it can be and still be accepted.
One thing you want to guard against is those few students who want to be late so as to get some feedback from peers before completing their assignment. The penalty will help with this, but also will make the consequences clear.
Some folks even give a small bonus for early completion. This helps get some students moving earlier, which is good for them in general.
Another possible solution is to permit re-work and regrading after the deadline with the rules stating that only a portion of the points lost initially can be regained. This means that some students will submit incomplete work on the deadline and use the feedback you give to improve the work. This can be very helpful to some students and works well if the number of students isn't too big. It isn't as hard to do for the instructor if students doing re-work turn in the old with it (in a folder) so that it is easy to see why points were lost. For some courses, such as computer programming, having the students also mark their changes in the new work makes regrading very quick and easy.
But, whatever your rules, publish them and make them clear at the start of the course. In particular, don't assume that the very strict rules you grew up with are understood generally, or even that they are the best rules. Think about your teaching goals and how to accomplish them. |
401,385 | I calculated the value of $\theta$ to be $53^{\circ}$ for (ii) by using the principle of moments ($6\sin\theta r 2 = 2.4 r$ ) as the disc is in equilibrium. Nothing wrong so far.
For (iii), I calculated the horizontal component of $\:\rm 6 N$ force ($6\cos 53^{\circ}= 3.6\:\rm N$) and since it is the only force that hasn't been cancelled, I deduced it must be the force (in opposite direction) of the pin on the disc.
But the answer is $6 \:\rm N.$
Isn't the vertical component of the force responsible for the anti-clockwise torque which is being cancelled by the clockwise torque? If so, why do I have to include it for my answer to (iii)?
Is it because despite being the cause of the anti-clockwise torque which has been cancelled, the force itself isn't cancelled and requires an opposing force ? But again, if this force is cancelled, how can it exert any torque? I'm confused.
I've just been introduced to this topic so I'd like to apologize if I'm missing out something very simple. Thanks in advance :).
[](https://i.stack.imgur.com/jGfFg.png) | 2018/04/22 | [
"https://physics.stackexchange.com/questions/401385",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/193438/"
] | Some history: In the pre-Wilsonian interpretation of quantum field theory, renormalisability of theories was considered an essential requirement. That is, you should be able to remove all ultraviolet divergences of the theory (that occur in perturbation theory) by absorbing them in a finite number of parameters in the lagrangian. If you could not do that, then the theory was called "non-renormalisable" and considered pathological. The renormalisability criteria placed strong constraints of the theory, determining which finite number of interactions were allowed. The standard model is renormalisable.
One effect of the renormalization process was that coupling constants became scale (energy) dependent, and such running coupling constants were understood to be physical. eg asymptotic freedom is the result of the QCD coupling constant becoming weak at large energies.
Wilson's goal and approach in condensed matter was different. He was interested in studying the behaviour of complicated theories near the second order phase transition where the correlation length becomes very large, that is when the theory is essentially scale invariant. That means that you could study the system via an *effective theory* near the phase transition point without worrying about the underlying microscopic degrees of freedom. In this approach you write down a simple field theory with the desired symmetries and you use a cut-off $\Lambda$ in all calculations since your theory is only an approximation at low energies $E \ll \Lambda$ (long distance scales).
So in the Wilsonian approach there are no ultraviolet divergences. But it also meant that you had to include many more interactions in your lagrangian. The coupling constants also became $\Lambda$ dependent and you had a running of the couplings here too. In practice, in the limit $E/\Lambda \to 0$, only a finite number of couplings are important: the ones that are "marginal" and "relevant". The ones that are "irrelevant" are the ones that a particle physicist would have labelled as "non-renormalisable".
So it was initially a different philosophy and approach in high-energy physics and condensed matter, but gradually high-energy physicists understood that the Wilsonian perspective of effective field theories is applicable to their studies of quantum field theory.
In the modern perspective, the standard model is believed to be a low-energy approximation of some as yet unknown theory. Although the current model is renormalisable, it is believed that "non-renormaliable = irrelevant" interactions would become important at higher energies, and they would represent new processes. So you can write down what the next possible interaction could be (eg to give neutrinos small masses) and make some predictions.
Such an effective field theory approach is also useful when you want to make low energy predictions from your high energy theories.
So, in summary, the Wilsonian perspective of quantum field theories and the renormalisation group is important because it gives them a very physical and intuitive meaning.
Now, some comments about "conformal field theories". A bigger symmetry than just scale invariance is "conformal invariance". In two dimensional space conformal invariance results in an infinite dimensional symmetry group which places strong constraints on a theory and allows many exact results to be obtained in condensed matter systems. It is also important in string theory as the world sheet is two dimensional. Conformal symmetry is less powerful in higher dimensions as the symmetry group is finite and the symmetry is typically broken by quantum effects through the generation of mass scales. | I'm not sure if this will directly answer your question, but perhaps it will be helpful. I will simply quote a few sections from the beginning of *Conformal Field Theory* by Phillipe Francesco, picking only those which relate to high energy particle physics (CFT's are very important in understanding quantum critical points in condensed matter systems).
>
> Scattering experiments failed to detect a
> characteristic length scale when probing the proton deeply with
> inelastically scattered electrons. This supported the idea that the
> proton is a composite object made of point-like constituents, the
> quarks. . .
>
>
> In other words, in this deep-inelastic range, the internal dynamics of
> the proton does not provide its own length scale $\ell$ that could justify
> a separate dependence of the structure functions on the dimensionless
> variables $\ell^2\nu$ and $\ell^2 q^2$. In the context of quantum chromodynamics (QCD,
> the modem theory of strong interactions), this reflects the asymptotic
> freedom of the theory, namely, the quasi-free character of the quarks
> when probed at very small length scales.
>
>
> Of course, the quark-gluon
> system underlying the scaling phenomena of deep inelastic scattering
> is thoroughly quantum-mechanical, just like systems undergoing
> quantum-critical phenomena. However, scale invariance manifests itself
> at short distances in QCD, whereas it emerges at long distances in
> quantum systems like the Heisenberg spin chain.
>
>
>
In regards to String Theory:
>
> The first-quantized formulation
> of string theory involves fields (representing the physical
> shape of the string) that reside on the world-sheet. From the point of
> view of field theory, this constitutes a two-dimensional system,
> endowed with reparametrization invariance on the world-sheet,
> meaning that the precise coordinate system used on the world-sheet has
> no physical consequence. . . This reparametrization
> invariance is tantamount to conformal invariance. Conformal invariance
> of the world-sheet theory is essential for preventing the appearance
> of ghosts (states leading to negative probabilities in quantum
> mechanics). The various string models that have been elaborated
> basically differ in the specific content of this conformally invariant
> two-dimensional field theory (including boundary conditions). A
> classification of conformally invariant theories in two dimensions
> gives a perspective on the variety of consistent first-quantized
> string theories that can be constructed . . .
>
>
> string scattering amplitudes were expressed in terms of correlation
> functions of a conformal field theory defined on the plane (tree
> amplitudes), on the torus (one-loop amplitudes), or on some
> higher-genus Riemann surface.
>
>
>
And further regarding the operator product expansion (OPE) and conformal bootstrap:
>
> The modem study of conformal invariance in two dimensions was
> initiated by Belavin, Polyakov, and Zamolodchikov, in their
> fundamental 1984 paper. These authors combined the representation
> theory of the Virasoro algebra . . with the idea of an algebra of local operators and
> showed how to construct completely solvable conformal theories:
> the so-called minimal models. An intense activity at the border of
> mathematical physics and statistical mechanics followed this initial
> envoi and the minimal models were identified with various
> two-dimensional statistical systems at their critical point. More
> solvable models were found by including additional symmetries or
> extensions of conformal symmetry in the construction of conformal
> theories.
>
>
> A striking feature of the work of Belavin, Polyakov, and
> Zamolodchikov . . . regarding conformal theories is the minor role
> played (if at all) by the Lagrangian or Hamiltonian formalism.
> Rather, the dynamical principle invoked in these studies is the
> associativity of the operator algebra, also known as the bootstrap
> hypothesis. . . The key ingredient
> of this approach is the assumption that the product of local
> quantum operators can always be expressed as a linear combination of
> well-defined local operators . . . This is the operator product expansion,
> initially put forward by Wilson . . . The dynamical principle of the
> bootstrap approach is the associativity of this algebra. In practice,
> a successful application of the bootstrap approach is hopeless, unless
> the number of local fields is finite. This is precisely the case in
> minimal conformal field theories. . .
>
>
> Following the pioneering work of Belavin, Polyakov, and Zamolodchikov,
> conformal field theory has rapidly developed along many directions.
> The work of Zamolodchikov has strongly influenced many of these
> developments: conformal field theories with Lie algebra symmetry (with
> Knizhnik), theories with higher- spin fields—the W-algebras—or with
> fractional statistics—parafermions (with Fateev), vicinity of the
> critical point, etc. These developments, and their offspring, still
> constitute active fields of research today and make conformal field
> theory one of the most active areas of research in mathematical
> physics.
>
>
> |
64,877,282 | ```
def encode_units(x):
if x <= 0:
return 0
if x >= 1:
return 1
basket_sets = mybasket.applymap(encode_units)
```
I am getting the type error in this. I am trying to do a basket analysis where I want to convert all positive value to 1 and 0 to 0 only. | 2020/11/17 | [
"https://Stackoverflow.com/questions/64877282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14653676/"
] | The 401 Unauthorized response is usually emitted as an `error` notification from the Angular `HttpClient`. So you'd need to use RxJS [`catchError`](https://rxjs.dev/api/operators/catchError) operator to catch the error and redirect. You could then emit [`NEVER`](https://rxjs.dev/api/index/const/NEVER) constant so that nothing emits after the redirect and keep the observable alive, or emit [`EMPTY`](https://rxjs.dev/api/index/const/EMPTY) constant to complete the observable.
Try the following
```js
import { throwError, NEVER } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
export class ApiService {
constructor(private http: HttpClient) { }
public get<T>(
path: string,
params: HttpParams = new HttpParams(),
headers: HttpHeaders = new HttpHeaders()
): Observable<T> {
return this.getBodyOfResponseOrRedirect(
this.http.get<T>(path, {headers, params, observe: 'response'}));
}
private getBodyOfResponseOrRedirect<T>(
responseObservable: Observable<HttpResponse<T>>
): Observable<T> {
return responseObservable.pipe(
catchError(error => {
if (!!error.status && error.status === 401) {
window.location.href = 'https://custom-url';
return NEVER; // <-- never emit after the redirect
}
return throwError(error); // <-- pass on the error if it isn't 401
}),
map(response => response.body)
);
}
}
``` | @Michael D solution was super helpfull. Based on his comment I implemented the following http interceptor :
```
@Injectable()
export class HttpResponseInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(error => {
if (!!error.status && error.status === 401) {
window.location.href = 'url';
return NEVER;
}
return throwError(error);
}));
}
}
``` |
16,104,707 | I have one affiliate account and I need to make a `soap` call to get data. I got ready code from one site and I tried to apply it, but I'm getting `500(internal server error)`. My code is given below.
```
public void getdata()
{
var _url = "http://secure.directtrack.com/api/soap_affiliate.php";
var _action = "http://secure.directtrack.com/api/soap_affiliate.php/dailyStatsInfo";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(@"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/1999/XMLSchema""><SOAP-ENV:Body xmlns=""http://soapinterop.org//"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""> <q1:Execute xmlns:q1=""http://secure.directtrack.com/api/soap_affiliate.php/dailyStatsInfo""><client xsi:type=""xsd:string"">MyClientNAme</client><add_code xsi:type=""xsd:string"">MyCode</add_code><password xsi:type=""xsd:string"">MyPassword</password><program_id xsi:type=""xsd:int"">161</program_id></q1:Execute></SOAP-ENV:Body></SOAP-ENV:Envelope>");
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
```
What is the problem? Thanks in advance. | 2013/04/19 | [
"https://Stackoverflow.com/questions/16104707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1562231/"
] | I went through this as well, I can even tell where you got this code :)
so check it out
```
webRequest.Headers.Add("SOAPAction", action);
```
is the issue
simply use
```
webRequest.Headers.Add("SOAP:Action");
``` | You should try using reflection in order to send data to a web service. Try using something like this:
```
Uri mexAddress = new Uri(URL);
// For MEX endpoints use a MEX address and a
// mexMode of .MetadataExchange
MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;
var binding = new WSHttpBinding(SecurityMode.None);
binding.MaxReceivedMessageSize = Int32.MaxValue;
XmlDictionaryReaderQuotas readerQuotas = new XmlDictionaryReaderQuotas();
readerQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas = readerQuotas;
//SS Get Service Type and set this type to either Galba and Powersale
string contractName = "";
string operationName = "RegisterMerchant";
object[] operationParameters;// = new object[] { 1, 2 };
// Get the metadata file from the service.
//MetadataExchangeClient mexClient = new MetadataExchangeClient(mexAddress, mexMode);
MetadataExchangeClient mexClient = new MetadataExchangeClient(binding);
mexClient.ResolveMetadataReferences = true;
MetadataSet metaSet = mexClient.GetMetadata(mexAddress, mexMode);
// Import all contracts and endpoints
WsdlImporter importer = new WsdlImporter(metaSet);
Collection<ContractDescription> contracts = importer.ImportAllContracts();
ServiceEndpointCollection allEndpoints = importer.ImportAllEndpoints();
// Generate type information for each contract
ServiceContractGenerator generator = new ServiceContractGenerator();
var endpointsForContracts = new Dictionary<string, IEnumerable<ServiceEndpoint>>();
foreach (ContractDescription contract in contracts)
{
generator.GenerateServiceContractType(contract);
// Keep a list of each contract's endpoints
endpointsForContracts[contract.Name] = allEndpoints.Where(se => se.Contract.Name == contract.Name).ToList();
}
if (generator.Errors.Count != 0) { throw new Exception("There were errors during code compilation."); }
// Generate a code file for the contracts
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BracingStyle = "C";
CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#");
// Compile the code file to an in-memory assembly
// Don't forget to add all WCF-related assemblies as references
CompilerParameters compilerParameters = new CompilerParameters(
new string[] { "System.dll", "System.ServiceModel.dll", "System.Runtime.Serialization.dll" });
compilerParameters.GenerateInMemory = true;
CompilerResults results = codeDomProvider.CompileAssemblyFromDom(compilerParameters, generator.TargetCompileUnit);
if (results.Errors.Count > 0)
{
throw new Exception("There were errors during generated code compilation");
}
else
{
// Find the proxy type that was generated for the specified contract
// (identified by a class that implements
// the contract and ICommunicationbject)
Type[] types = results.CompiledAssembly.GetTypes();
Type clientProxyType = types
.First(t => t.IsClass && t.GetInterface(contractName) != null && t.GetInterface(typeof(ICommunicationObject).Name) != null);
// Get the first service endpoint for the contract
ServiceEndpoint se = endpointsForContracts[contractName].First();
// Create an instance of the proxy
// Pass the endpoint's binding and address as parameters
// to the ctor
object instance = results.CompiledAssembly.CreateInstance(
clientProxyType.Name,
false,
System.Reflection.BindingFlags.CreateInstance,
null,
new object[] { se.Binding, se.Address },
CultureInfo.CurrentCulture, null);
Type parameterType = types.First(t => t.IsClass && t.Name=="Method()");
Object o = Activator.CreateInstance(parameterType);
FieldInfo[] props = parameterType.GetFields();
FieldInfo fi = parameterType.GetField("NewMerchantDetail");
//PropertyInfo pi = parameterType.GetProperty("NewMerchantDetail");
Type p1Type = fi.FieldType;
//Pass in the values here!!!
Object o1 = Activator.CreateInstance(p1Type);
PropertyInfo pi1 = p1Type.GetProperty("MerchantID");//7
pi1.SetValue(o1, vendingClient.VendingClientID, null);
pi1 = p1Type.GetProperty("FirstName");// John
pi1.SetValue(o1, vendingClient.DescriptiveName, null);
fi.SetValue(o, o1, BindingFlags.Default, null, null);
operationParameters = new object[] { o1 };
// Get the operation's method, invoke it, and get the return value
object retVal = instance.GetType().GetMethod(operationName).
Invoke(instance, operationParameters);
```
I used this code for distributing data instead of having to insert into each individual database.
Hope it helps! |
31,715,557 | I am stuck with jquery wherein I am trying to add dynamic html elements (on click of +) which should also get removed on clicking on (-).
Each element should have unique name and id say "name\_1","name\_2"...
But it doesn't seem to going my way.
Here is my code:
```js
$(document).ready(function() {
var maxField = 10;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = $('.field_wrapper1').html();
var x = 1;
$('.add_button').click(function() {
if (x < maxField) {
x++;
$('.field_wrapper').append('<div class="field_wrapper1" style = "display:none;margin:20px;"><div><strong>*Upload New Contract Copy :</strong><input type="text" name="text_1" id = "text_1" value="" maxlength="50"/><strong><font color="#ff0000">* </font>Upload New Contract Copy :</strong><input type="file" name="pdf_1" id="pdf_1" accept="application/pdf" /><a href="javascript:void(0);" class="remove_button" title="Remove field"><img src="http://www.allintravellocal.com/images/minus_img.jpg"/></a><label for="contract_copy_pdf" class="err" id="err_lbl_contract_copy_pdf"></label></div></div>');
}
});
$(wrapper).delegate('.remove_button', 'click', function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
```
```html
<div class="field_wrapper">
<div>
<strong><font color='#ff0000'>* </font>Upload New Contract Copy :</strong>
<input type="text" name="contract_copy_text_1" id="contract_copy_text_1" value="" maxlength="50" />
<strong><font color='#ff0000'>* </font>Upload New Contract Copy :</strong>
<input type="file" name="contract_copy_pdf_1" id="contract_copy_pdf_1" accept="application/pdf" /> (*.pdf)
<a href="javascript:void(0);" class="add_button" title="Add field">
<img src="http://www.allintravellocal.com/images/plus_img.jpg" />
</a>
<label for="contract_copy_pdf" class="err" id="err_lbl_contract_copy_pdf"></label>
</div>
</div>
```
Here is my fiddle :
[Demo](http://jsfiddle.net/hLtqe0d8/1/) | 2015/07/30 | [
"https://Stackoverflow.com/questions/31715557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4014347/"
] | You need to "import" the first file in the second.
Be warned that this will litterally include the first, so any code in the first will be executed as if it were litterally in the place of the line.
The syntax is:
```
# if /path/to/file exists, then include it
[ -f /path/to/file ] && . /path/to/file
```
Note `bash` also support the keyword `source` (ie: `source /path/to/file`) but it is not POSIX compliant and might not work in other shell like `ash`, `dash`, `posh`. | If you don't want to do an explicit sourcing of your script file as [bufh suggests](https://stackoverflow.com/a/31715558/520162): I put my often used functions in my `.bashrc` which gets always sourced thus having the functions always available.
As bufh pointed out in a comment *always* is not really always but limited to interactive shells. So, if you're planning to use the scripts from an interactive session, you could put it into the `.bashrc`, otherwise go for explicit sourcing. |
47,709 | Below is my first attempt to write the sheet music for the song "My Way" by Sinatra:
[](https://i.stack.imgur.com/FsAjj.jpg)
Then I googled and compared with what I found in the internet, for example this one:
[](https://i.stack.imgur.com/lBkWQ.png)
So my questions are:
1. Why does it start the first tab at the second note? How was I suppose to know that? Is that usually the case?
2. I was confused because although I wanted to assume the time signature was 4/4, my first tab had only 3 beats. Later I realized that there is a pause adding up to 4 beats. How can I "hear the pause" to write the sheet music?
3. How to determine the key and the scale of this song? So that I can know whether that first C sharp in the first line is an accidental or just part of the scale?
Thanks! | 2016/08/04 | [
"https://music.stackexchange.com/questions/47709",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/32396/"
] | By pentascale I'm assuming you mean the first five notes of a regular major or minor scale? Not a pentatonic scale, right?
If you're just playing five-note patterns like C-D-E-F-G, C#-D#-E#-F#-G# and so on, you might well be playing every pattern starting with right-hand thumb and left-hand pinkie, and then playing each successive note with the next finger, using five fingers to play five notes.
However, at some point in the future you'll want to do more than five notes, so you'll need to turn during the scale so you don't run out of fingers. So I'd suggest you practise your five note patterns using conventional scale fingerings. That way you won't have to unlearn a load of stuff when you play more than five notes.
Scale exercises like this are really important but you need to develop the skills in a way that you can build on them subsequently, rather than it being something you have to abandon because you can't build on it. | **EDIT: The OP has clarified his/her intent, illustrating that s/he is asking about the first five pitches of a diatonic scale, *not* the pentatonic scale. But I will leave this up, I think, in case it helps future readers.**
**Meanwhile, I suggest the author go ahead and start learning the major/minor scales in their entirety; it's only two extra notes :-) Furthermore, s/he will create better fingering habits in the context of the entire scale than with just the first five pitches.**
If you "eventually want to play hands together" but you don't yet know the scales, I would kill two birds with one stone and go ahead and start playing them with both hands together, deriving each scale as you go.
Your two-hand abilities on the scale will quickly start to improve, and you'll notice very soon that you just "know" the pentatonic scales without really having to think about them.
(Quick note: I think you just made a little typo, but I want to clarify that the pattern of the pentatonic scale is actually `START - 1 - 1 - **1 1/2** - 1 - END`.)
One practice tip might be to focus on the pentatonic scales that have the same contour on the keyboard. For instance, the F, C, and G pentatonic scales have no black notes, thus their contours and fingerings are the same. (If you know the circle of fifths, you'll see that these tonics are adjacent to each other on the circle; this will hold true for other sets as well.) |
149,304 | Well, it's the whole question. I installed 9.1 before, but I need older version now and I haven't yet found out how to do that. | 2012/06/11 | [
"https://askubuntu.com/questions/149304",
"https://askubuntu.com",
"https://askubuntu.com/users/66793/"
] | If you want to install PostgreSQL 8.4 in ubuntu in specific version like ubuntu 12 then Follow the steps:
* Create the file /etc/apt/sources.list.d/pgdg.list, and add a line for the repository :
`sudo sh -c 'echo "deb <http://apt.postgresql.org/pub/repos/apt/> precise-pgdg main"> /etc/apt/sources.list.d/pgdg.list'`
* Import the repository signing key, and update the package lists :
`wget --quiet -O - <https://www.postgresql.org/media/keys/ACCC4CF8.asc> | \
sudo apt-key add -
sudo apt-get update`
`sudo apt-get install postgresql-8.4` | It's 2019 and (at least with my actual Ubuntu 16 config) PG versions prior to 9.3 are not available to instal with `apt-get`. I've followed the instructions provided in this [site](https://erpnani.blogspot.com/2016/03/install-postgresql-84-from-its-official.html) and now I have PG 10.10 and 8.4 installed. Required steps are (extracted from the previous link):
**1**. Create and edit the PostgreSQL repository by running the command below:
`~$ sudo vi /etc/apt/sources.list.d/pgdg.list`
Press I on keyboard and add the below line into the file:
`deb http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg main`
Press Esc on keyboard and followed by :wq to save the file.
**2**. Download & import the repository key:
`~$ wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -`
**3**. Update your system:
`~$ sudo apt-get update`
**4**. Now you’re able to install PostgreSQL via below command:
`~$ sudo apt-get install postgresql-8.4 pgadmin3`
**NOTE**: I've omitted pgadmin3 because I had it installed before.
**NOTE 2**: The link doesn't mention but if you have another PG version installed, remember you'll have to change port in one of your installations:
```
~$ sudo updatedb
~$ locate postgresql.conf
/etc/postgresql/10/main/postgresql.conf
/etc/postgresql/8.4/main/postgresql.conf
~$ cp /etc/postgresql/8.4/main/postgresql.conf /etc/postgresql/8.4/main/postgresql.conf_yyyymmdd
~$ sudo vi /etc/postgresql/8.4/main/postgresql.conf
```
Find the entry that says:
`port = 5433` and change port number to new value. Save file (:wq) and restart your postgres. |
207,717 | What could exist buried in the earth that is sugary and can be used to sweeten food? It should be relatively common, and at a depth where it is only accessible to peoples specialized for digging (specifically, the people described in [this question](https://worldbuilding.stackexchange.com/questions/205889/what-weapons-would-fossorial-people-use)). Also, the sweet thing should be something that might have come to be on Earth | 2021/07/24 | [
"https://worldbuilding.stackexchange.com/questions/207717",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/75161/"
] | A lot of tubers grow underground, and some need some digging to be reached, like [yam](https://en.wikipedia.org/wiki/Yam_(vegetable)#Harvesting)
>
> Yams in West Africa are typically harvested by hand using sticks, spades, or diggers. Wood-based tools are preferred to metallic tools as they are less likely to damage the fragile tubers; however, wood tools need frequent replacement. Yam harvesting is labor-intensive and physically demanding. Tuber harvesting involves standing, bending, squatting, and sometimes sitting on the ground depending on the size of mound, size of tuber, or depth of tuber penetration. Care must be taken to avoid damage to the tuber, because damaged tubers do not store well and spoil rapidly. Some farmers use staking and mixed cropping, a practice that complicates harvesting in some cases.
>
>
> In forested areas, tubers grow in areas where other tree roots are present. Harvesting the tuber then involves the additional step of freeing them from other roots. This often causes tuber damage.
>
>
>
Generally speaking tubers are rich in carbohydrates, because they are the energy storage of the plant producing them, therefore in principle all of them are either sweet or have the potential to be sweet. Something like a sweet potato.
So, you are looking for something which is an interbreed of a sweet potato for the sweetness and yam for the challenging harvest. | If you want the ultimate sugar rush then maybe grow sugar beet [wikipedia link](https://en.wikipedia.org/wiki/Sugar_beet).
20% sugar. |
51,779,919 | So, I have a code like this:
```
#!/bin/bash
awk -v ip="10.0.7.1" -v no="8" -v line='#BalancerMember "ajp://" ip ":8009" route=node" no " loadfactor=1 keepalive=on ttl=300 max=400 timeout=300 retry=60' '
/ProxySet lbmethod=byrequests/{
print " " line ORS $0
next
}
1' /tmp/000-site.conf > /tmp/000-site.conf.tmp && mv /tmp/000-site.conf.tmp /tmp/000-site.conf
```
So, I'm unable to use the awk variable `ip` and `no` inside an awk variable `line`. | 2018/08/10 | [
"https://Stackoverflow.com/questions/51779919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5851645/"
] | tl;dr
=====
If you want 8 AM on first day of July at UTC…
```
OffsetDateTime.of(
2018 , 7 , 1 , // Date (year, month 1-12 is Jan-Dec, day-of-month)
8 , 0 , 0 , 0 , // Time (hour, minute, second, nano)
ZoneOffset.UTC // Offset-from-UTC (0 = UTC)
) // Returns a `OffsetDateTime` object.
.format( // Generates a `String` object with text representing the value of the `OffsetDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSZ" , Locale.US )
) // Returns a `String` object.
```
>
> 2018-07-01T08:00:00.000+0000
>
>
>
Avoid legacy date-time classes
==============================
Never use `Calendar` or `Date` classes. They were completely supplanted by the modern *java.time* classes such as [`OffsetDateTime`](https://docs.oracle.com/javase/10/docs/api/java/time/OffsetDateTime.html). You are mixing the legacy classes with the modern, and that makes no sense.
java.time
=========
Your Question is not clear about what are your inputs and what are your outputs versus your expectations.
If you goal is 8 AM on July 1 in UTC:
```
LocalDate ld = LocalDate.of( 2018 , Month.JULY , 1 ) ;
LocalTime lt = LocalTime.of( 8 , 0 ) ;
OffsetDateTime odt = OffsetDateTime.of( ld , lt , ZoneOffset.UTC ) ;
```
>
> odt.toString(): 2018-07-01T08:00Z
>
>
>
That string format complies with [ISO 8061](https://en.wikipedia.org/wiki/ISO_8601) standard. If your destination refuses that input and accepts only `2018-07-01T08:00:00.000+0000`, then we must defining a formatting pattern.
```
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSZ" , Locale.US );
String output = odt.format( f );
```
>
> 2018-07-01T08:00:00.000+0000
>
>
>
---
About *java.time*
=================
The [*java.time*](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old [legacy](https://en.wikipedia.org/wiki/Legacy_system) date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), & [`SimpleDateFormat`](http://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html).
The [*Joda-Time*](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes.
To learn more, see the [*Oracle Tutorial*](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Specification is [JSR 310](https://jcp.org/en/jsr/detail?id=310).
You may exchange *java.time* objects directly with your database. Use a [JDBC driver](https://en.wikipedia.org/wiki/JDBC_driver) compliant with [JDBC 4.2](http://openjdk.java.net/jeps/170) or later. No need for strings, no need for `java.sql.*` classes.
Where to obtain the java.time classes?
* [**Java SE 8**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8), [**Java SE 9**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9), [**Java SE 10**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10), [**Java SE 11**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_11), and later - Part of the standard Java API with a bundled implementation.
+ Java 9 adds some minor features and fixes.
* [**Java SE 6**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6) and [**Java SE 7**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7)
+ Much of the java.time functionality is back-ported to Java 6 & 7 in [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/).
* [**Android**](https://en.wikipedia.org/wiki/Android_(operating_system))
+ Later versions of Android bundle implementations of the *java.time* classes.
+ For earlier Android (<26), the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project adapts [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) (mentioned above). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706).
The [**ThreeTen-Extra**](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as [`Interval`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html). | You can do it like so,
```
offsetDateTime.atZoneSameInstant(ZoneId.of("Asia/Kolkata"))
```
**Update**
If you need an instance of `OffsetDateTime` here it is.
```
offsetDateTime.atZoneSameInstant(ZoneId.of("Asia/Kolkata")).toOffsetDateTime();
``` |
3,195,440 | I wonder what is the properties of Product Pi Notation? I can't found anywhere about the properties.
First of all, i have:
$X=\beta\alpha\\
X^2=\beta^2\alpha(\alpha + 1) \\
X^3=\beta^3\alpha(\alpha + 1)(\alpha + 2) \\
. \\
. \\
. \\
\text{And so forth.}
$
My question is. I want to write this form into Pi Notation (If it's possible):
We know that the pattern for $X^n$ is the following:
$X^n=\beta^n\alpha(\alpha + 1)(\alpha + 2)\cdots (\alpha+(n-1))$
And with the Product Pi, is the following true?
$X^n=\beta^{n}\displaystyle\prod\_{k=0}^{n-1}\left(\alpha + k\right)\quad,n=1, 2, 3,\ldots$
If it's wrong, please to tell me what is the right one? Please help, Thanks.^ | 2019/04/21 | [
"https://math.stackexchange.com/questions/3195440",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/664855/"
] | In the category of rings with unity (with a $1$), morphisms are required to take the unity to the unity. In the case at hand, unless the morphism is trivial, the kernel will not be a ring with unity that embeds as a ring with unity.
Consider for example the case of $R=\mathbb{Z}\times\mathbb{Z}$, and the morphism $R\to\mathbb{Z}$ obtained by mapping $(a,b)$ to $a$. This is a ring-with-unit morphism.
The kernel of the map is the ideal $I=\{(0,b)\mid b\in\mathbb{Z}\}$. Now, as an abstract ring, $I$ is a ring with unity: the element $(0,1)$ is a unity for $I$. (In fact, $I$ is isomorphic as a ring-with-unity to $\mathbb{Z}$).
Thus, in this case, the kernel is in fact in the category: it is a ring with unity. However, the embedding $I\hookrightarrow R$ is **not** a morphism in the category of rings-with-unity, because the unit of $I$, $(0,1)$, is *not* mapped to the unit of $R$. Thus, the embedding is not a morphism in this category.
That’s Jacobson’s point: even if the kernel happens to, abstractly and by happenstance, be a ring with unity, you will almost never have that the embedding of the kernel into the ring is a morphism in the category. The slight error in your argument is that it is possible for the kernel to be a ring-with-unity, abstractly, even if it is not a **sub**ring-with-unity (which would require the unity of the ideal to be the same as the unity of the whole ring, in which case you are correct that the ideal would have to be the whole ring).
Note that this issue does not show up in the category of rings/rngs, where you do not require rings to have a unity and you do not require morphisms to map $1$ to $1$ even when the two rings do. In that category, the same proof shows that a morphism is monic if and only if it is one-to-one. | It may be possible for an ideal of a ring to be a ring with a different one. For instance, we can make a ring out of finite sums of the variables $\{X\_n | n \in \mathbb{N} \}$ where multiplication is given by $X\_n X\_m = X\_{max(n,m)}$ and extending linearly. The one of this ring is $X\_0$.
Then, consider the ideal given by sums of variables $\{X\_n | n > 0 \}$. This by itself is a ring (in fact, it's isomorphic to the original ring) but it has a different one given by $X\_1$.
Therefore, even in the very special case where the ideal is a unital ring, like this one, the inclusion need not be a unital ring homomorphism. |
132,015 | I have a paper that was a published in a conference proceedings. This paper was extended and turned into a journal paper. However, some things like figures from the motivation section or the experimental setup (used same metrics) are the same. The journal paper was reviewed, and one reviewer raised some concerns about a possible overlap with the conference paper. At the moment I'm preparing a response to his comments, and would like to present a percentage of the overlap. Is there a method to calculate the overlap with a previous publication? Are there any common guidelines that are used when presenting an overlap with a previous publication? | 2019/06/17 | [
"https://academia.stackexchange.com/questions/132015",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/36841/"
] | Your problem is that you need to show your paper is sufficiently original to merit publication. Calculating a measure of overlap will not help you achieve that goal. Instead, you need to:
* Clarify the original aspects of the paper. For example, you might write in the paper "Previously we showed [minor progress]" and then "but we did not solve [major problem in the field]" and finally "in this work we achieve [important step towards goal]"
* Justify to the editor why some overlap is necessary. For example, "This paper is about x, which is well known to experts but may be unfamiliar to some readers of this journal. Therefore, we repeat our introduction to x from our conference paper."
* Remove unnecessary overlap.
The editor will be looking for meaning, not quantity. Don't invent metrics where they are not needed. | You should be able to list the major points in both papers.
If the lists are mostly identical then the second paper is too similar to the first, if the points are substantially different then the second does not overlap but takes the topic forward. |
11,614,274 | I am developing a JQuery mobile web app and I am having some problems with the format after executing
$('#someId').replaceWith(php var);
The problem, I think, is that as this is executed before the JQuery Mobile libraries are loaded I get a crappy format when I replace.
Can anyone think on something that could help?
Thank you very much!
UPDATE:
I'm quite new to PHP. What I want to do is to have several variables with the div html code in a way that when I click any button I don't have to refresh the page, just to refresh the div. This data is comming from an external database, so I need to do it with php... any ideas?? | 2012/07/23 | [
"https://Stackoverflow.com/questions/11614274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1033507/"
] | I know this is an old question, but it turned up when I was searching for the same.
Here is my solution to add a compressed (zip) attachment using [System.IO.Compression.ZipArchive (requires .NET 4.5 or higher)](http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive(v=vs.110).aspx) [based on the answer of acraig5075]:
```
byte[] report = GetSomeReportAsByteArray();
string fileName = "file.txt";
using (MemoryStream memoryStream = new MemoryStream())
{
using (ZipArchive zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Update))
{
ZipArchiveEntry zipArchiveEntry = zipArchive.CreateEntry(fileName);
using (StreamWriter streamWriter = new StreamWriter(zipArchiveEntry.Open()))
{
streamWriter.Write(Encoding.Default.GetString(report));
}
}
MemoryStream attachmentStream = new MemoryStream(memoryStream.ToArray());
Attachment attachment = new Attachment(attachmentStream, fileName + ".zip", MediaTypeNames.Application.Zip);
mail.Attachments.Add(attachment);
}
``` | You're not creating a valid zip file, you're just creating a compressed stream and writing it to a file that has a `*.zip` extension. You should use a .NET zip library instead of `DeflateStream`.
You can use something like [DotNetZip Library](http://dotnetzip.codeplex.com/):
>
> DotNetZip is an easy-to-use, FAST, FREE class library and toolset for
> manipulating zip files or folders. Zip and Unzip is easy: with
> DotNetZip, .NET applications written in VB, C# - any .NET language -
> can easily create, read, extract, or update zip files. For Mono or MS
> .NET.
>
>
>
If you have constraints and cannot use an external library, you could try to use `GZipStream` and add the attachment with an extension of `*.gz` which would be supported by common compression tools.
As useful information for future reference, .NET 4.5 will *finally* introduce native support for zip archiving through the [`ZipArchive`](http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive%28VS.110%29.aspx) class. |
146,120 | At the following circuit I want to find what it does and basically its transfer function. I've searched a lot but I didn't find any circuit like this. Since it does not match any of the basic types of op amp circuits (inverting or non-inverting amplifier) I don't know where to start from. Finally, anyone knows what's the name of this circuit? Please note that this is not homework.

Following Lorenzo Donati's method I got to this point for the transfer function:
 | 2015/01/01 | [
"https://electronics.stackexchange.com/questions/146120",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/40047/"
] | You can determine the transfer function \$H(s)\$ of the circuit reasoning on the following circuit:

and thinking of \$V\_1\$ and \$V\_2\$ as two independent inputs. Since the circuit is linear superimposition applies, and the output (in the s-domain) of the circuit when \$V\_2\$ is off is simply that of an inverting amplifier (\$R\_3\$ shorts the non inverting input to ground, assuming an ideal op-amp):
\$ V\_{out1} = - \dfrac{R\_2}{R\_1} V\_1 \$
Analogously, when \$V\_1\$ is off, the circuit acts as a non-inverting amplifier whose input is filtered by the series \$C-R\_3\$. Thus applying the non-inverting amp gain formula and the voltage divider formula you get:
\$ V\_{out2} = \left(1 + \dfrac{R\_2}{R\_1} \right)\dfrac{R\_3}{R\_3 + \frac{1}{C s}} V\_2 \$
The full response is the sum of the two above:
\$ V\_{out} = V\_{out1} + V\_{out2} =
- \dfrac{R\_2}{R\_1} V\_1 +
\left(1 + \dfrac{R\_2}{R\_1} \right)\dfrac{R\_3}{R\_3 + \frac{1}{C s}} V\_2 \$
Your circuit is like the one I posted, but with \$V\_1 = V\_2\$, therefore the full response becomes:
\$ V\_{out} = V\_{in} \cdot \left[
- \dfrac{R\_2}{R\_1} + \left(1 + \dfrac{R\_2}{R\_1} \right)\dfrac{R\_3}{R\_3 + \frac{1}{C s}}
\right] \$
from which you get:
\$ H(s) = \dfrac{V\_{out}}{V\_{in}} =
- \dfrac{R\_2}{R\_1} + \left(1 + \dfrac{R\_2}{R\_1} \right)\dfrac{R\_3}{R\_3 + \frac{1}{C s}} \$
This simplifies, after a bit of algebra, into:
\$H(s) = \dfrac{s - \frac{R\_2}{R\_1 R\_3 C}}{s + \frac{1}{R\_3 C}} \$
Which shows that the circuit acts as an active filter with a 1st order frequency response.
Such a topology is used, for example, to create [all-pass filters](http://en.wikipedia.org/wiki/All-pass_filter) if \$R\_2 = R\_1\$.
**EDIT**
The derivation of the final form of H(s) follows:
\$ H(s)
= - \dfrac{R\_2}{R\_1} + \left(1 + \dfrac{R\_2}{R\_1} \right)\dfrac{R\_3}{R\_3 + \frac{1}{C s}}
= - \dfrac{R\_2}{R\_1} + \dfrac{R\_1 + R\_2}{R\_1} \dfrac{R\_3 C s}{R\_3 C s + 1} = \$
\$
= - \dfrac{R\_2}{R\_1} + \dfrac{(R\_1 + R\_2)R\_3 C s}{R\_1(R\_3 C s + 1)}
= \dfrac{-R\_2(R\_3 C s + 1) + (R\_1 + R\_2)R\_3 C s}{R\_1(R\_3 C s + 1)}
\$
\$
= \dfrac{-R\_2 R\_3 C s - R\_2 + R\_1 R\_3 C s + R\_2 R\_3 C s}{R\_1(R\_3 C s + 1)}
= \dfrac{- R\_2 + R\_1 R\_3 C s }{R\_1(R\_3 C s + 1)}
= \dfrac{R\_1 R\_3 C s - R\_2 }{R\_1 R\_3 C s + R\_1}
\$
dividing numerator and denominator by \$R\_1 R\_3 C \$ we get:
\$ H(s)
= \dfrac{s - \frac{R\_2}{R\_1 R\_3 C}}{s + \frac{R\_1}{R\_1 R\_3 C}}
= \dfrac{s - \frac{R\_2}{R\_1 R\_3 C}}{s + \frac{1}{R\_3 C}}
\$ | Remember, ideal op amps follow two basic rules:
1. No current flows into either input.
2. Negative feedback forces the voltage at each input to be equal.
Let's start with a qualitative approach. Since there's one capacitor, we can divide the frequency response of this circuit into three regions -- low-frequency \$(Z\_C \gg R\_3)\$, mid-frequency \$(Z\_C \approx R\_3)\$, and high-frequency \$(Z\_C \ll R\_3)\$.
At DC, the capacitor acts like an open circuit, so the non-inverting input is tied to ground. In this case, the negative feedback is a simple inverting amplifier.
At high frequency, the capacitor acts like a short circuit, so the non-inverting input is tied directly to \$V\_{in}\$. It's harder to see, but in this case the negative feedback gives you a voltage follower.
At mid-frequency, the frequency response transitions from inverting input to voltage follower. We expect the gain to go from R2/R1 to 1 and the phase to go from 180 to 0. This is where we have to derive the transfer function using the op amp rules. \$V\_+\$ is pretty easy -- C and R3 form a low-pass filter:
$$V\_+ = V\_{in}\frac{R\_3}{R\_3 + \frac{1}{sC}} = V\_{in}\frac{1}{1 + \frac{1}{sR\_3C}}$$
\$V\_-\$ is a little trickier, but it's mostly the same as deriving an inverting amplifier:
$$\frac{V\_{in} - V\_-}{R\_1} = \frac{V\_- - V\_{out}}{R\_2}$$
$$(R\_1 + R\_2)V\_- = R\_1V\_{out} + R\_2V\_{in}$$
Now we connect our two equations with:
$$V\_+ = V\_-$$
$$V\_{in}\frac{1}{1 + \frac{1}{sR\_3C}}(R\_1 + R\_2) = R\_1V\_{out} + R\_2V\_{in}$$
From here, it's just a matter of algebra. It's up to you how you want to express the result, but one way that's easy to understand is:
$$\frac{V\_{out}}{V\_{in}} = (DC\ gain) + (AC\ gain)\*(frequency\ response)$$
(Note that Lorenzo's form is probably more common in signal processing, but I like this one for educational purposes.) Here's my derivation:
$$V\_{in}\frac{R\_1 + R\_2}{1 + \frac{1}{sR\_3C}} = R\_1V\_{out} + R\_2V\_{in}$$
$$V\_{out} = -\frac{R\_2}{R\_1}V\_{in} + \frac{V\_{in}}{R\_1}\frac{R\_1 + R\_2}{1 + \frac{1}{sR\_3C}}$$
$$V\_{out} = -\frac{R\_2}{R\_1}V\_{in} + V\_{in}\frac{1 + \frac{R\_2}{R\_1}}{1 + \frac{1}{sR\_3C}}$$
$$\frac{V\_{out}}{V\_{in}} = -\frac{R\_2}{R\_1} + (\frac{R\_2}{R\_1} + 1)\frac{1}{1 + \frac{1}{sR\_3C}}$$
When s -> 0, the gain becomes:
$$\frac{V\_{out}}{V\_{in}} = -\frac{R\_2}{R\_1} + (\frac{R\_2}{R\_1} + 1)\*0 = -\frac{R\_2}{R\_1}$$
When s -> infinity, the gain becomes:
$$\frac{V\_{out}}{V\_{in}} = -\frac{R\_2}{R\_1} + (\frac{R\_2}{R\_1} + 1)\*1 = 1$$
That's the behavior we expected to begin with, which is a good sign that I did the algebra correctly. :-) You can also check with Excel or some other tool vs. what you get in CircuitLab. Doing a frequency response simulation in CircuitLab is probably the easiest way to get started with an unfamiliar filter circuit. |
3,922,761 | I'm confident with solving this question in cylindrical coordinates (for which there are few answers) but I'm doubtful about cartesian coordinates and can't seem to figure out the limits. $z$ needs to be the outer integral in the below question:
[](https://i.stack.imgur.com/X1FbI.png)
[](https://i.stack.imgur.com/OaN7M.png)
Right now, I've figured that:
1. $z$ must vary from $-1$ to $1$ (since it describes the radius of the cylinder).
2. If we make $x$ the inner integral and dependent on $y$ we could say that it varies from $-2y^2$ to $(1-2y^2)$ (obtained by substituting the cylinder equation and adding in $a=0$ & $a=1$
3. I'm not sure how to evaluate the middle integral and how exactly there are 2 regions over which we must integrate. | 2020/11/25 | [
"https://math.stackexchange.com/questions/3922761",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/694570/"
] | Here is a simple proof that works when $ n $ is even :
Let $ n\in 2\mathbb{N}^{\*} :$
\begin{aligned} \sum\_{k=0}^{n}{B\_{k}\binom{n}{k}\frac{2^{k}}{n-k+1}}&=2^{n°1}\sum\_{k=0}^{n}{B\_{k}\binom{n}{k}\int\_{0}^{\frac{1}{2}}{x^{n-k}\,\mathrm{d}x}}\\&=2^{n+1}\int\_{0}^{\frac{1}{2}}{B\_{n}\left(x\right)\mathrm{d}x} \end{aligned}
Using the substitution $ \left\lbrace\begin{aligned}y&=1-x\\ \mathrm{d}y &=-\,\mathrm{d}x\end{aligned}\right.$, we get : $$ \int\_{0}^{\frac{1}{2}}{B\_{n}\left(x\right)\mathrm{d}x}=\int\_{\frac{1}{2}}^{1}{B\_{n}\left(1-x\right)\mathrm{d}x}=\left(-1\right)^{n}\int\_{\frac{1}{2}}^{1}{B\_{n}\left(x\right)\mathrm{d}x}=\int\_{\frac{1}{2}}^{1}{B\_{n}\left(x\right)\mathrm{d}x} $$
Thus : $$ \int\_{0}^{\frac{1}{2}}{B\_{n}\left(x\right)\mathrm{d}x}=\frac{1}{2}\int\_{0}^{1}{B\_{n}\left(x\right)\mathrm{d}x} = 0 $$
That means $$ \sum\_{k=0}^{n}{B\_{k}\binom{n}{k}\frac{2^{k}}{n-k+1}}=0 $$
Now let's try to get the general result using a different method.
Denoting $ \left(\forall n\in\mathbb{N}\right),\ u\_{n}=\sum\limits\_{k=0}^{n}{B\_{k}\binom{n}{k}\frac{2^{k}}{n-k+1}} $ we can observe that if $ x $ is such that $ \left|x\right|<2\pi $, $ \sum\limits\_{n\geq 0}{\frac{B\_{n}}{n!}x^{n}} $ and $ \sum\limits\_{n\geq 0}{\frac{2^{-n}}{\left(n+1\right)!}x^{n}} $ both converge. Thus the series $ \sum\limits\_{n\geq 0}{\frac{u\_{n}}{2^{n}n!}x^{n}} $ also converges and we have : \begin{aligned} \sum\_{n=0}^{+\infty}{\frac{u\_{n}}{2^{n}n!}x^{n}}&=\left(\sum\_{n=0}^{+\infty}{\frac{B\_{n}}{n!}x^{n}}\right)\left(\sum\_{n=0}^{+\infty}{\frac{2^{-n}}{\left(n+1\right)!}x^{n}}\right)\\ &=\frac{x}{\mathrm{e}^{x}-1}\times\frac{\mathrm{e}^{\frac{x}{2}}-1}{\frac{x}{2}}\\ &=\frac{1}{\sinh{\left(\frac{x}{2}\right)}}-\frac{2}{\mathrm{e}^{x}-1}\\ &=\frac{2}{x}-\sum\_{n=1}^{+\infty}{B\_{2n}\frac{2\left(1-2^{1-2n}\right)}{\left(2n\right)!}x^{2n-1}}-\frac{2}{x}\sum\_{n=0}^{+\infty}{\frac{B\_{n}}{n!}x^{n}}\\ &=1-\sum\_{n=1}^{+\infty}{B\_{2n}\frac{4\left(1-2^{-2n}\right)}{\left(2n\right)!}x^{2n-1}}\end{aligned}
From that formula we get the following : $$\fbox{$\begin{array}{rcl}\begin{aligned} u\_{0} &=1\\ \left(\forall n\geq 1\right),\ u\_{2n} &= 0\\ \left(\forall n\geq 1\right),\ u\_{2n-1}&=B\_{2n}\frac{1-2^{2n}}{n} \end{aligned} \end{array}$}$$
From these expressions you can get expressions for the sum $ \sum\limits\_{k=1}^{n}{B\_{k}^{+}\binom{n}{k}\frac{2^{k}}{n-k+1}} $ : $$ \fbox{$\begin{array}{rcl}\left(\forall n\in\mathbb{N}^{\*}\right),\ \displaystyle\sum\_{k=1}^{n}{B\_{k}^{+}\binom{n}{k}\frac{2^{k}}{n-k+1}}=\frac{2n+1}{n+1} + u\_{n} \end{array}$}$$ | We seek to show that for $m$ even
$$\sum\_{q=1}^m 2^q B^+\_q {m\choose q} \frac{1}{m-q+1} = \frac{2m+1}{m+1}$$
or alternatively for $m$ even
$$\sum\_{q=1}^m 2^q B^+\_q {m+1\choose q} = 2m+1$$
where
$$B^+\_q = q! [z^q] \frac{z}{1-\exp(-z)}.$$
We get for the LHS
$$-B^+\_0 - 2^{m+1} B^+\_{m+1}
+ \sum\_{q=0}^{m+1} 2^q B^+\_q {m+1\choose q}
\\ = - 1 - 2^{m+1} B^+\_{m+1} +
(m+1)! [z^{m+1}] \exp(z) \frac{2z}{1-\exp(-2z)}
\\ = - 1 - (m+1)! [z^{m+1}] \frac{2z}{1-\exp(-2z)}
\\ + (m+1)! [z^{m+1}] \exp(z) \frac{2z}{1-\exp(-2z)}
\\ = - 1 + (m+1)! [z^{m+1}]
\frac{2z (\exp(z)-1)}{1-\exp(-z)^2}
\\ = - 1 + (m+1)! [z^{m+1}]
\frac{2z \exp(z) (1-\exp(-z))}{1-\exp(-z)^2}
\\ = - 1 + (m+1)! [z^{m+1}]
\frac{2z \exp(z)}{1+\exp(-z)}
\\ = - 1 + (m+1)! [z^{m+1}]
\left(\frac{2z \exp(z) + 2z}{1+\exp(-z)}
- \frac{2z}{1+\exp(-z)} \right)
\\ = - 1 + (m+1)! [z^{m+1}]
\left(2z \exp(z)
- \frac{2z}{1+\exp(-z)} \right)
\\ = - 1 + 2 (m+1)! [z^{m}]
\left(\exp(z)
- \frac{1}{1+\exp(-z)} \right)
\\ = - 1 + 2 (m+1)! \frac{1}{m!}
- 2 (m+1)! [z^{m}] \frac{1}{1+\exp(-z)}
\\ = 2m+1 - 2 (m+1)! [z^{m}] \frac{1}{1+\exp(-z)}.$$
We observe that this evaluates to zero when $m=0$ as claimed and
henceforth assume $m\ge 1.$ Continuing,
$$2m+1 - 2 (m+1)!
[z^{m}]
\left( \frac{1/2-\exp(-z)/2}{1+\exp(-z)} + \frac{1}{2}\right).$$
Now note that with $f(z) = \frac{1/2-\exp(-z)/2}{1+\exp(-z)}$ we have
$$f(-z) = \frac{1/2-\exp(z)/2}{1+\exp(z)}
= \frac{\exp(-z)/2-1/2}{\exp(-z)+1}
= - f(z)$$
so the function $f(z)$ is odd and hence the even order coefficients of
its Taylor series vanish. Since the constant $1/2$ does not contribute
to $[z^m]$ when $m \ge 1$ that leaves just $2m+1$ and we have the
desired result. For the odd order coefficients we have to evaluate the
remaining coefficient extractor.
$$2 (m+1)! [z^{m}] \frac{1}{1+\exp(-z)}
= 2 (m+1)! (-1)^m [z^{m}] \frac{1}{1+\exp(z)}
\\ = 2 (m+1)! (-1)^m [z^{m}] \frac{1}{2+\exp(z)-1}
\\ = (m+1)! (-1)^m [z^{m}] \frac{1}{1+(\exp(z)-1)/2}
\\ = (m+1)! (-1)^m [z^{m}]
\sum\_{q=0}^m (-1)^q 2^{-q} (\exp(z)-1)^q
\\ = (m+1) (-1)^m
\sum\_{q=0}^m (-1)^q 2^{-q} q! {m\brace q}.$$
We thus obtain the closed form
$$\bbox[5px,border:2px solid #00A000]{
2m+1 - [[m \;\text{odd}]]
(m+1) (-1)^m
\sum\_{q=1}^m (-1)^q 2^{-q} q! {m\brace q}.}$$
The Iverson bracket is not essential here as the sum evaluates to zero
anyway when $m$ is even. This yields for the original as proposed by
OP that it is
$$\bbox[5px,border:2px solid #00A000]{
\frac{2m+1}{m+1} - [[m \;\text{odd}]]
(-1)^m \sum\_{q=1}^m (-1)^q 2^{-q} q! {m\brace q}.}$$ |
351,948 | >
> (a) A computer network consists of six computers. Each computer is directly connected
> to at least one of the other computers. Show that there are at least two computers in
> the network that are directly connected to the same number of other computers.
>
>
> (b) Find the least number of cables required to connect eight computers to four printers
> to guarantee that four computers can directly access four different printers. Justify
> your answer.
>
>
> | 2013/04/05 | [
"https://math.stackexchange.com/questions/351948",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/63102/"
] | HINTS:
1. Pick any one of the six computers; to how many others can it be connected? We’re told that it’s connected to at least one, and there are only five others, so it must be connected to $1,2,3,4$, or $5$ other computers. The same is true of each of the six. That’s how many different possibilities?
2. This problem is very poorly worded. It could mean that there are at least four computers, each of which can access all four printers; that there is some set of four computers that altogether can access all four printers; or that no matter what four computers you pick, those four can access all four printers. I suspect, however, that the last of these is intended, since the first two are trivial. The best way to attack it is probably to ask yourself how many cables you can install **without** meeting the requirement. For instance, is you connect each of the eight computers to the same three printers, you’ve used $8\cdot3=24$ cables, and **no** set of four computers can access all four printers. How much worse can you do? How many more cables can you install and still have at least one set of four computers that can reach at most three of the printers? | (a) There are six computers, and each computer connected to at least one of the other five computers, this means the possible connection for each computer is: 1, 2, 3, 4, 5, by using the Pigeon and Pigeonhole Principle, let these 5 possible connections be the Pigeonholes, and let the six computers be the Pigeons, therefore there are must at least two computers have same number of connections.
(b) First, think of the worse case, there are 8 computers and 4 printers, so the worst case would be all 8 computers have access to 3 printers, but non of them have access to 4 printers, that is $8\times3=24$ cables. Now, since each computer has access to 3 printers, then you can just add 4 cables, so that there must be 4 computers have access to all 4 printers. Thus, the number of cables that guarantee 4 computers have direct access to all 4 printers is $24+4=28$ |
18,507 | I have 4 years of work experience as Network consultant. I have worked in a team and also led a team of 3. However, I have never worked as a Project Manager. Can I go for the PMP certification or not? | 2016/06/17 | [
"https://pm.stackexchange.com/questions/18507",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/23815/"
] | A PMP certification requires you to have at least 4500 hours (if you have a 4-year degree) to 7500 hours (if you have a secondary degree) of experience in leading a project (Source: [PMI](https://www.pmi.org/certifications/types/project-management-pmp)). That doesn't mean that you can't start preparing for the exam now though, because you also need 35 hours of training. My advise is to get practical experience first, but simultaneously further educate yourself on project management, so when you have collected enough hours and feel like you want to do a certificate, you can do so immediately. | Management is all about meeting customer expectations and run a business successfully.
Consider yourself on a junction where you see many roads that lead to your destination. As long as you know which road you have to take to reach your destination faster/safely/hassle free journey, you are on a right path.
Certifications help you to gain theoretical knowledge on management skills (like it helps you to decide which road to take) like
* What is a project
* Processes to execute a project
* handle risks/mitigation plans and many aspects of projects for the successful completion of project on-time without compromising on quality
Whereas real time experience helps you to improve your skills.
Now it is upto individual's interest to decide whether to go for certifications to gain theoretical knowledge or gain practical experience as and whenever an opportunity knocks your door. |
16,714,567 | I think I do not quite understand how F# infers types in sequence expressions and why types are not correctly recognized even if I specify the type of the elements directly from "seq".
In the following F# code we have a base class A and two derived classes, B and C:
```
type A(x) =
member a.X = x
type B(x) =
inherit A(x)
type C(x) =
inherit A(x)
```
If I try to "yield" their instances in a simple sequence expressions, I get two errors:
```
// Doesn't work, but it makes sense.
let testSeq = seq {
yield A(0)
yield B(1) // Error, expected type: A
yield C(2) // Error, expected type: A
}
```
That can make sense, since it may not be so trivial to infer "common" types (interfaces, I think, can make that work far harder). However, those errors can be fixed with a safe cast:
```
// Works fine :)
let testSeqWithCast = seq {
yield A(0)
yield B(1) :> A
yield C(2) :> A
}
```
What if I do not want to use casts? I tried to specify the sequence type directly from "seq", but things do not seem to work:
```
// Should work, I think...
let testGenSeq = seq<A> {
yield A(0)
yield B(1) // Error, expected type: A
yield C(2)
}
```
So, my question is: is there a way to avoid casts? If not, is there a reason why even specifying the type doesn't make the code work?
I tried digging through following links:
<http://msdn.microsoft.com/en-us/library/dd233209.aspx>
<http://lorgonblog.wordpress.com/2009/10/25/overview-of-type-inference-in-f/>
But I found nothing useful...
Thank you in advance for any kind of answer you can give :) | 2013/05/23 | [
"https://Stackoverflow.com/questions/16714567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1880086/"
] | In order to understand the cause of your confusion you should not go anywhere further, than the first statement of [the link](http://msdn.microsoft.com/en-us/library/dd233209.aspx) you referred to :
>
> A sequence is a logical series of elements **all of one type**.
>
>
>
You can return a sequence of **only one, the same** type like `seq<A>`, or `seq<obj>`. The OOP-ish fact that types `B` and `C` are inherited from `A` is not relevant. The following may help: all your instances are also inherited from `obj`, but in order to make from them a `seq<obj>` you should explicitly cast:
```
// Works fine
let testSeq = seq<obj> {
yield A(0) :> obj
yield B(1) :> obj
yield C(2) :> obj
}
```
or just `box` them like below:
```
// Works fine too
let testSeq = seq {
yield box (A(0))
yield box (B(1))
yield box (C(2))
}
```
**EDIT**: For understanding the reasoning behind explicit casting in F# the following (simplistic) consideration may help. Type inference does not do guessing; unless it can derive `seq` type deterministically, or have it explicitly declared, it will complain.
If you just do
```
let testSeq = seq {
yield A(0)
yield B(1)
yield C(2)
}
```
compiler is presented with indeterminism - `testSeq` can be either `seq<A>`, or `seq<obj>`, so it complains. When you do
```
let testSeq = seq {
yield A(0)
yield upcast B(1)
yield upcast C(2)
}
```
it infers `testSeq` as `seq<A>` based on type of the first member and upcasts B and C to `A` without complaining. Similarly, if you do
```
let testSeq = seq {
yield box A(0)
yield upcast B(1)
yield upcast C(2)
}
```
it will infer `testSeq` as `seq<obj>` based on the type of the first member upcasting this time second and third members to `obj`, not `A`. | This is just a summary of all answers my question has received, so that future readers can save their time by reading this (and decide whether or not reading other answers to get a better insight).
The short answer to my question, as pointed out by @Gene Belitski, is no, it's not possible to avoid casts in the scenario I described. First of all, the documentation itself states that:
>
> A sequence is a logical series of elements **all of one type**.
>
>
>
Moreover, in a situation like the next one:
```
type Base(x) =
member b.X = x
type Derived1(x) =
inherit Base(x)
type Derived2(x) =
inherit Base(x)
```
We surely have that an instance of `Derived1` or of `Derived2` is also an instance of `Base`, but it is also true that those instances are also instances of `obj`. Therefore, in the following example:
```
let testSeq = seq {
yield Base(0)
yield Derived1(1) // Base or obj?
yield Derived2(2) // Base or obj?
}
```
We have that, as explained by @Gene Belitski, the compiler cannot choose the right ancestor between `Base` and `obj`. Such decision can be helped with casts, as in the following code:
```
let testBaseSeq = seq<Base> {
yield Base(0)
yield upcast Derived1(1)
yield upcast Derived2(2)
}
let testObjSeq = seq<obj> {
yield Base(0) :> obj
yield Derived1(1) :> obj
yield Derived2(2) :> obj
}
```
However, there's more to explain. As @kvb states, the reason this can't work without casts is that we are implicitly mixing generics, inheritance, and type inference, which may not work together as well as expected. The snippet in which `testSeq` appears is automagically transformed in:
```
let testSeq = Seq.append (Seq.singleton (Base(0)))
(Seq.append (Seq.singleton (Derived1(1)))
(Seq.singleton (Derived2(2))))
```
The issue lies in `Seq.singleton`, where an *automatic upcast* would be needed (like in `Seq.singleton (Derived1(1))`) but it cannot be done since `Seq.singleton` is generic. If the signature of `Seq.singleton` had been, for example, `Base -> Base seq`, then everything would have worked.
@Marcus proposes a solution to my question which boils down to define my own *sequence builder*. I tried writing the following builder:
```
type gsec<'a>() =
member x.Yield(item: 'a) = Seq.singleton item
member x.Combine(left, right) = Seq.append left right
member x.Delay(fn: unit -> seq<'a>) = fn()
```
And the simple example I posted seems to be working fine:
```
type AnotherType(y) =
member at.Y = y
let baseSeq = new gsec<Base>()
let result = baseSeq {
yield Base(1) // Ok
yield Derived1(2) // Ok
yield Derived2(3) // Ok
yield AnotherType(4) // Error, as it should
yield 5 // Error, as it should
}
```
I also tried extending the custom builder so that it supported more complex constructs like `for` and `while`, but I failed trying writing the while handler. That may be a useful research direction, if someone is interested in.
Thanks to everyone who answered :) |
37,887,520 | I have a list of "home appliances" and i want to model a database to save them in a table. There are different device types with different properties/columns.
Example :
User "mike" has a "TV (size inch ,energy consumption)", "fridge(min. tempreture,height,width)".
A user has a list of "home appliances".
I don't know how i could model this in a nice way. In the end, i just want to query the db : which appliances ( and their properties ) does the user have ? | 2016/06/17 | [
"https://Stackoverflow.com/questions/37887520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928621/"
] | This is a classic problem in data modeling and database design. It goes by different names than the one you used, "abstraction". In ER modeling, it tends to be called "generalization/specialization". In object modeling, it tends to be called "class/subclass" modeling, or "inheritance".
When it comes to designing SQL tables to match up with these models, there are several techniques that might help you. In the early years, SQL had no general facilities to help with this situation, in spite of the fact that it occurs over and over again in the real world. Two techniques that come to mind are "single table inheritance" and "class table inheritance".
Single table inheritance stuffs all the data for the class and the subclasses into one table. It's good for the simplest situations. Your case looks a little more complicated than that, to me.
Class table inheritance provides one table for class data and a separate table for each subclass. The answer from Jorge Campos looks like this. In connection with class table, there is a technique called "shared primary key". The subclass tables don't have an id field of their own. Instead, the foreign key that references the class table is used as the primary key of the subclass table. This makes joins simple, easy, and fast. It also enforces the one-to-one nature of the subclass relationship.
A quick search on these buzzwords should give you lots of descriptive examples. I particularly like the way Fowler presents these concepts. Or you could start with the info tab on these three tags:
[single-table-inheritance](/questions/tagged/single-table-inheritance "show questions tagged 'single-table-inheritance'") [class-table-inheritance](/questions/tagged/class-table-inheritance "show questions tagged 'class-table-inheritance'") [shared-primary-key](/questions/tagged/shared-primary-key "show questions tagged 'shared-primary-key'") | You could create a model like:
```
user (id, name)
1, bob
2, mark
...
device (id, name)
1, TV
2, Fridge
...
attributes (id, name)
1, size inch
2, energy consumption
3, min temperature
4, height
...
device_has_attribute (id_device, id_attribute, value)
1, 1, 2.7inches (you decide the unit or it could be another table)
1, 2, 220v
2, 1, 6.7ft
2, 3, 30F
...
home_appliance (id, name)
1, Kitchen
2, Living room
...
home_appliance_device (id_home_appliance, id_device )
1, 1
2, 1
2, 2
...
user_home_appliance (id_user, id_home_appliance)
1, 1
1, 2
2, 2
...
```
I recommend you to add the value unit as another table it would be
```
unit (id, name, acronym)
device_has_attribute (id_device, id_attribute, value, id_unit)
``` |
51,690,369 | A part of my program checks the current data with a specified date to see if it is before that date. If it is, I want to throw a `TooEarlyException`.
My `TooEarlyException` class(note that it currently is checked, but I am trying to decide if it should be checked or unchecked):
```java
public class TooEarlyException extends Exception {
private int dayDifference;
private String message = null;
public TooEarlyException(int dayDifference) {
this.dayDifference = dayDifference;
}
public TooEarlyException() {
super();
}
public TooEarlyException(String message) {
super(message);
this.message = message;
}
public TooEarlyException(Throwable cause) {
super(cause);
}
public int getDayDifference() {
return dayDifference;
}
@Override
public String toString() {
return message;
}
@Override
public String getMessage() {
return message;
}
}
```
Here is my code that checks the dates and throws the exception if necessary(assume that `today` and `dateSpecified` are `Date` objects):
```
public void checkDate() throws TooEarlyException{
//Do Calendar and Date stuff to get required dates
...
//If current Date is greater than 4 weeks before the event
if(today.before(dateSpecified)) {
//Get difference of dates in milliseconds
long difInMs = dateSpecified.getTime() - today.getTime();
//Convert milliseconds to days(multiply by 8,640,000^-1 ms*s*min*h*days)
int dayDifference = (int)difInMs/8640000;
//Throw exception
throw new TooEarlyException(dayDifference);
} else { //Date restriction met
//Format date Strings
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
System.out.printf("Today Date: %s%n", df.format(today));
System.out.printf("Event Date(Actual): %s%n", df.format(eventDateActual));
System.out.printf("Event Date(4 Weeks Prior): %s%n", df.format(dateSpecified));
}
}
```
How I call `checkDate`:
```
try {
checkDate();
} catch(TooEarlyException e) {
System.out.printf("Need to wait %d days", e.getDayDifference());
e.printStackTrace();
System.exit(1);
}
```
In [this](https://stackoverflow.com/a/19061110/4450564) post, [Gili](https://stackoverflow.com/users/14731/gili) says:
>
> **Checked Exceptions** should be used for **predictable**, but **unpreventable** errors that are **reasonable to recover from**.
>
>
>
My question with this is in my case, this error would be considered predictable but unpreventable, but not recoverable from, as my program needs to be run within 28 days of a specified date(this is because the API I am using has a restriction that in order to get data for an event, it must within 4 weeks before the event starts). Essentially, if this error happens, I intentionally want the program not to be able to run.
**Should I make this a checked exception, or an unchecked exception**, keeping in mind that the program should not run if the Date restriction isn't met? | 2018/08/04 | [
"https://Stackoverflow.com/questions/51690369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4450564/"
] | If this is something that shouldn't happen and you want to catch it just in case, then it should be RuntimeException. Otherwise, checked (expected) exception. | You shouldn't use Exception at all in this example.
1. You are using Exception for flow control and you catch it immediately and handle it in the same method. Thus is a bad practice.
Using if statement can easily achieve the flow control in your example.
2. Your quote is out of context. Gili has explained what he meant by predicable and unpreventable, it doesn't apply to your case.
: The caller did everything within their power to validate the input parameters, but some condition outside their control has caused the operation to fail.
**Update**
Since OP has changed the code, it seems more arguable between checked and runtime exception.
But remembering one rule in **Effective Java** that when you decide between checked and runtime exception, always asked yourself one question: what do you expect the caller to do? Can he do better than just ignore or log the exception and exit?
You new code looks exactly like this, so if you cannot change your code to use if statement, you should use Runtime Exception, instead of Checked. |
678,293 | I am working on a web app and I decided (after reading many post on SO) to store the actual images in the file system and to store the metadata in the DB.
Should I store a relative path or an absolute path.
I can think of some advantages for each of the choices.
**Absolute:**
*Pros:*
It is obvious where the file is even to other apps reading the DB
Can put the photos anywhere on the drive (would require an handler)
*Cons:*
Need to convert the absoulte path to a relative path for use in the site or create a handler
If I migrate to another server I may have to change all the paths
**Relative:**
*Pros:*
Simply add the link to the html and it works
*Cons:*
If I change the app root I have to move the pictures or change all the paths
Have to put the pictures in a public directory (Or I gain nothing over the absolute path)
Ok these are some of things going on in my head right now.
I can't decide. | 2009/03/24 | [
"https://Stackoverflow.com/questions/678293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72453/"
] | I would store a relative path in the database. This gives you the greatest flexibility. Loading images is a simple matter of prepending an "IMAGE\_ROOT" variable (which should probably be configurable) to get the filesystem path. This is important because you might want to move where the images are stored (put them on a faster drive, for example). Then it is simply changing the configurable IMAGE\_ROOT.
When putting a reference to the image into a page, I'd put the full URL. Again, this is simply adding a URL\_ROOT to the relative path. This gives you the advantage of being able to easily switch servers if you find load requires dedicated servers for serving images. | If you're using SQL Server 2008, you can solve this problem neatly with the new [FILESTREAM data type](http://technet.microsoft.com/en-us/library/bb933993.aspx). |
42,021,255 | I am clicking on an image in recycleview and uploading new image to the server.If the image uploads successfully then it should reflects in recycleview. I am using this code:
```
private void get_cardview_data(String response) {
r_View_StudentInfo.setHasFixedSize(true);
recyclerViewlayoutManager = new GridLayoutManager(this, 3);
r_View_StudentInfo.setLayoutManager(recyclerViewlayoutManager);
try {
JSONArray jsonArray=new JSONArray(response);
if(jsonArray.length()>0){
for(int n = 0; n < jsonArray.length(); n++) {
getDataAdapter_studentInfo = new GetDataAdapter_StudentInfo();
JSONObject jsonObject = null;
jsonObject = jsonArray.getJSONObject(n);
image= jsonObject.getString("pic_url");
if(image.equals("")){
getDataAdapter_studentInfo.setImageUrl(Config.NULL_IMAGE);
}
else {
getDataAdapter_studentInfo.setImageUrl(Config.SET_IMAGE+dbname+"/"+image);
}
getDataAdapter_studentInfo.setId(jsonObject.getInt(Config.JSON_ID)); getDataAdapter_studentInfo.setSname(jsonObject.getString(Config.JSON_SNAME));
getDataAdapter_studentInfo.setRollno(jsonObject.getString(Config.JSON_ROLLNO));
getDataAdapter_studentInfo.setPname(jsonObject.getString(Config.JSON_PNAME));
getDataAdapter_studentInfo.setPmobile(jsonObject.getString(Config.JSON_PMOBILE));
getDataAdapter_studentInfos.add(getDataAdapter_studentInfo);
recyclerViewadapter = new RecyclerViewAdapter_StudentInfo(getDataAdapter_studentInfos, (Context) this);
// getDataAdapter_studentInfos.clear();
r_View_StudentInfo.setAdapter(recyclerViewadapter);
r_View_StudentInfo.getAdapter().notifyDataSetChanged();
text_nodata.setVisibility(View.GONE);
}
}
else{
text_nodata.setVisibility(View.VISIBLE);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
```
But this is not reloading. If I close the app and then start it will be showing uploaded images.Please help me to resolve.
```
public class RecyclerViewAdapter_StudentInfo extends RecyclerView.Adapter<RecyclerViewAdapter_StudentInfo.ViewHolder> {
ImageLoader imageLoader;
Context context;
List<GetDataAdapter_StudentInfo> getDataAdapter_studentInfos;
public RecyclerViewAdapter_StudentInfo(List<GetDataAdapter_StudentInfo> getDataAdapter, Context context){
super();
this.getDataAdapter_studentInfos = getDataAdapter;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items_student_info, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
GetDataAdapter_StudentInfo getDataAdapter_document = getDataAdapter_studentInfos.get(position);
try {
imageLoader = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader.get(getDataAdapter_document.getImageUrl(),
ImageLoader.getImageListener(
holder.imageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
R.drawable.profile_image //Error image if requested image dose not found on server.
)
);
holder.imageView.setImageUrl(getDataAdapter_document.getImageUrl(), imageLoader);
}catch (Exception e){ }
holder.textView1.setText(String.valueOf(getDataAdapter_document.getId()));
holder.textView2.setText(getDataAdapter_document.getSname());
holder.textView3.setText(getDataAdapter_document.getRollno());
holder.textView4.setText(getDataAdapter_document.getPname());
holder.textView5.setText(getDataAdapter_document.getPmobile());
// holder.imageView.setImageResource(getDataAdapter_document.getImageUrl());
}
public void refreshEvents(List<GetDataAdapter_StudentInfo> getDataAdapter_studentInfos) {
this.getDataAdapter_studentInfos.clear();
this.getDataAdapter_studentInfos.addAll(getDataAdapter_studentInfos);
notifyDataSetChanged();
}
@Override
public int getItemCount() {
return getDataAdapter_studentInfos.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView textView1,textView2,textView3,textView4,textView5;
public NetworkImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView)itemView.findViewById(R.id.student_image);
textView1 = (TextView) itemView.findViewById(R.id.textView1) ;
textView2 = (TextView) itemView.findViewById(R.id.textView2) ;
textView3 = (TextView) itemView.findViewById(R.id.textView3) ;
textView4 = (TextView) itemView.findViewById(R.id.textView4) ;
textView5 = (TextView) itemView.findViewById(R.id.textView5) ;
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
GetDataAdapter_StudentInfo getDataAdapterDocument = getDataAdapter_studentInfos.get(getAdapterPosition());
Intent intent=new Intent(context,StudentInfo_CardClick.class);
intent.putExtra("student_pic", getDataAdapterDocument.getImageUrl());
intent.putExtra("stud_name", getDataAdapterDocument.getSname());
intent.putExtra("stud_rollno", getDataAdapterDocument.getRollno());
intent.putExtra("stud_id", String.valueOf(getDataAdapterDocument.getId()));
intent.putExtra("stud_pname", getDataAdapterDocument.getPname());
intent.putExtra("stud_pmobile", getDataAdapterDocument.getPmobile());
context.startActivity(intent);
}
});
}
}
}
private void selected_section_id() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.C_SEND_SECTION_ID,
new Response.Listener<String>() {
@Override
public void onResponse(String response)
{
//Toast.makeText(Dashboard.this,response,Toast.LENGTH_LONG).show();
// getDataAdapter_studentInfos.clear();
get_cardview_data(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Dashboard.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(Config.C_DB_NAME_D,dbname);
params.put(Config.C_AC_YEAR_ID_SEC,ac_yearid);
params.put(Config.C_CLASS_ID,value_class);
params.put(Config.C_SECTION_ID,value_section);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Dashboard.this);
requestQueue.add(stringRequest);
}
``` | 2017/02/03 | [
"https://Stackoverflow.com/questions/42021255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6873553/"
] | First, you need to [`explode()`](http://php.net/manual/en/function.explode.php) string to get an array of IDs. Then use the correct syntax for [`whereIn()`](https://laravel.com/docs/5.4/queries#where-clauses):
```
->whereIn('id', explode(',', $vlsalesitemid))
``` | ```
$vlsalesitemid="11,12,13,";
$val_array = explode(',', $vlsalesitemid);
$query=DB::table('st_temp_sales')->where('brand_id', $brandid)
->whereIn('your_id', $val_array)->get();
return $query;
``` |
13,373,249 | I'm trying to extract the time from a string using bash, and I'm having a hard time figuring it out.
My string is like this:
```
US/Central - 10:26 PM (CST)
```
And I want to extract the `10:26` part.
Anybody knows of a way of doing this only with bash - without using sed, awk, etc?
Like, in PHP I would use - not the best way, but it works - something like:
```
preg_match( ""(\d{2}\:\d{2}) PM \(CST\)"", "US/Central - 10:26 PM (CST)", $matches );
```
Thanks for any help, even if the answer uses sed or awk | 2012/11/14 | [
"https://Stackoverflow.com/questions/13373249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1741861/"
] | ```
echo "US/Central - 10:26 PM (CST)" | sed -n "s/^.*-\s*\(\S*\).*$/\1/p"
-n suppress printing
s substitute
^.* anything at the beginning
- up until the dash
\s* any space characters (any whitespace character)
\( start capture group
\S* any non-space characters
\) end capture group
.*$ anything at the end
\1 substitute 1st capture group for everything on line
p print it
``` | Quick 'n dirty, regex-free, low-robustness chop-chop technique
```
string="US/Central - 10:26 PM (CST)"
etime="${string% [AP]M*}"
etime="${etime#* - }"
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.