qid
int64 10
74.7M
| question
stringlengths 15
26.2k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 27
28.1k
| response_k
stringlengths 23
26.8k
|
---|---|---|---|---|---|
26,155 | (Related: [Warfare without Metal](https://worldbuilding.stackexchange.com/q/11042/9498))
In my setting, metals (including common metals such as tin and iron) are a rare commodity. Because of this, humans have to make weapons such as firearms (guns) with other resources.
In order to get to the level of technology that we are at today, humans have discovered how to create and manipulate [buckminsterfullerene](https://en.wikipedia.org/wiki/Buckminsterfullerene "Wikipedia page") (aka buckyballs) in order to make electronics such as computers.
Guns are still made by propelling a bullet with an explosion (as they are today), so brittle materials like wood won't work.
You must assume:
* Guns still use bullets, which means the bullets must also have a safe casing.
* Humans are as advanced as they are today, so you may use any material that isn't rare.
* The "no metal" rule applies to common metals like tin, iron, copper, etc, which means all of those count as rare.
* Humans are the only species, and Earth is the only planet.
In short, **what could guns and bullets be made out of if metal couldn't be used?** | 2015/09/22 | [
"https://worldbuilding.stackexchange.com/questions/26155",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/9498/"
] | For single shot "zip gun" type weapons, almost any material can do. Indeed, with the restrictions given, it is difficult to imagine a firearm in the sense that we know today as being possible.
To make a modern "repeating" firearm, the challenge is multifold. The chamber needs to contain high pressures and high temperature gasses. The cartridge case is made of brass in modern weapons since it can expand slightly during firing to create a seal in the chamber, and its ejection helps remove a lot of heat from the chamber and weapon. It also helps that the metallic cartridge also mechanically protects the round and propellant in storage and in the magazine as well. Polymer cartridges have been experimented with (Notably the [LSAT](https://infogalactic.com/info/Lightweight_Small_Arms_Technologies) program), and caseless cartridges have also been developed (notably for the [HK G-11](https://infogalactic.com/info/Heckler_%26_Koch_G11) rifle program), but with limited success to date.
[![enter image description here](https://i.stack.imgur.com/YDnBH.jpg)](https://i.stack.imgur.com/YDnBH.jpg)
*LSAT cased telescoped polymer ammunition as developed for a machine-gun*
[![enter image description here](https://i.stack.imgur.com/4TWZv.jpg)](https://i.stack.imgur.com/4TWZv.jpg)
*HK G-11 with 50 round magazine and caseless ammunition*
The next challenge is to have a barrel which can handle the severe forces imparted by having a high speed projectile passing through it, along with heat buildup and mechanical strength to deal with soldiers bashing it in the field. Ceramic barrels might have some of the properties desired, but ceramic/metal composites seem to have the sorts of material properties to make an "ideal" barrel. Lacking metals, a ceramic barrel with a high strength material "wound" around it should have most of the properties desired, at the expense of a complex manufacturing process. The [Carl Gustave](https://infogalactic.com/info/Carl_Gustav_recoilless_rifle) M-3 has this on a larger scale in an 84mm recoilless rifle, but the rifled liner is still steel.
So the short version is firearms the way we understand them are going to be exceedingly difficult to make without metal. There are some possible substitutes, however.
Rocket projectiles have been around since ancient China. Using cardboard tubes filled with gunpowder attached to an arrow provides a simple yet effective projectile weapon, which can be fired from a crossbow like weapon individually or from a multiple rocket launcher to bombard an area with arrows
[![enter image description here](https://i.stack.imgur.com/8wmFY.jpg)](https://i.stack.imgur.com/8wmFY.jpg)
*Take that!*
A more modern variation was the [Gyrojet](https://infogalactic.com/info/Gyrojet) rocket pistol and carbine, using a .45 cal projectile powered by a tiny solid filled rocket motor. Oddly enough it was quite safe at point blank range (you could stop the projectile by putting your thumb over the barrel), but became increasingly dangerous as the rocket built up velocity. Accuracy was ensured by having the rocket exhausts angles slightly to impart a rotation on the projectile as it was in flight.
[![enter image description here](https://i.stack.imgur.com/R3CNf.jpg)](https://i.stack.imgur.com/R3CNf.jpg)
*Gyrojet ammunition*
[![enter image description here](https://i.stack.imgur.com/knNQ7.jpg)](https://i.stack.imgur.com/knNQ7.jpg)
*Gyrojet Mk 2 pistol*
[![enter image description here](https://i.stack.imgur.com/wWSfQ.jpg)](https://i.stack.imgur.com/wWSfQ.jpg)
*Gyrojet rocket carbines*
The pressures inside the weapons are much lower than a conventional firearm, and they can be made of virtually any material (the historic ones used aluminum, but in principle even a plastic barrel would do). Polymer and ceramic could conceivably make a modern Gyrojet, should anyone be interested in reviving this, or for the purposes of your story set in the "modern" age.
Edit to add: <https://www.youtube.com/watch?v=VdW8Trh_MGg>
This video shows a successful firing of a Mk2 pistol, and you can see the rocket spinning the round. | The answer would depend heavily on how gun like you want your non-metal guns to be. The Hwacha (the MythBusters did an episode on It) looks like a good starting point for a non metal gun, reducing the size of the arrows, and developing an automatic reloading system. It might look something like the Gyrojet guns developed in the 1960s. |
45,524,174 | I want my app to invoke a lambda function. The lambda function should create an instance of a lambda function, make the instance a sort of a cron job which runs every hour for upto N times (N = 1000), and pass event keys to the lambda function.
The pseudocode for the lambda function which does the bulk of the work is:
* newLamdaFunc = create from another lambda function
* set a trigger for newLambdaFunc (make it a cron job)
* newLambdaFunc.event.someKey = someValue
Is the above logic possible from within a lambda function? What should be the alternate logic if the above is not possible to do? | 2017/08/05 | [
"https://Stackoverflow.com/questions/45524174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/558972/"
] | This
```
var my_var = <?php echo json_encode($title); ?>;
```
evaluates to:
```
var my_var = sometitle;
```
and *sometitle* is probably not defined. You want it to be a string:
```
var my_var = "<?php echo json_encode($title); ?>";
``` | That is because `my_var` is not being treated as a placeholder for a `string`. Instead, my\_var is being treated as a place holder for another variable named `<?php echo json_encode($title); ?>`. Make the following change and everything should work:
```
var my_var = "<?php echo json_encode($title); ?>";
var url = "//localhost/wordpress/"
url += my_var
url += ".tsv"
d3.tsv( url, function(d) {
d.frequency = +d.frequency;
return d;
}, function(error, data) {
if (error) throw error;
x.domain(data.map(function(d) { return d.letter; }));
y.domain([0, d3.max(data, function(d) { return d.frequency; })]);
``` |
10,144,462 | I'm by no means a java programmer, so this may seem pretty basic.
Which of these are 'better' when you want to keep your code lines short.
```
String str = "First part of a string.";
str += " Second part of string.";
```
or
```
String str = "First part of string." +
" Second part of string."
```
I guess my question is do both the += and + make a new String object? If they do then neither really are better, it would just be a matter of preference. The example I gave would be a good example of real world use. I don't want a comparison of doing a concatenation 3 times to 1000 times with either method.
Thanks | 2012/04/13 | [
"https://Stackoverflow.com/questions/10144462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/799858/"
] | I prefer the 2nd method. The reason is that the compiler will likely combine the result of the concatenation into a single string at compile time while the 1st method may be done at run-time (depending on the actual implemention.) It's a small thing unless you're doing something millions of times, however. | Following Java's coding conventions:
```
String str = "First part of string. "
+ "Second part of string.";
```
Make sure the '+' operator begins the next line this improves readability.
Using this style allows for readable and efficient code.
<https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#248>
Hope this helps!
Happy coding,
Brady |
8,611,816 | In my Show User page, I want to add a link to an external website with some values saved in the table passed as parameters.
I got the first part working right, that's simple.
```
<%= link_to "Outside Site", "http://outsidesite.com/create" %>
```
But I also want to pass some paramaters which are saved in the database, like `@user.email`, `@user.first_name`, etc.
So basically the final link will look like:
<http://outsidesite.com/create?email=user@email.com&firstname=userfirstname> etc etc.
What would be the best way to do this? | 2011/12/23 | [
"https://Stackoverflow.com/questions/8611816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053709/"
] | You can write the helper method such as url patern. You can check the code bellow:
```
def generate_url(url, params = {})
uri = URI(url)
uri.query = params.to_query
uri.to_s
end
```
After that, you can call the helper method like:
```
generate_url("YOUR-URL-ADDR-HERE", :param1 => "first", :param2 => "second")
```
I hope you find this useful. | Because rails don't know how the website want it's paramteres, I think you must do it with string concatenation. At least, you can write a helper to do this for you but will just become a string concatenation in the end. |
19,574,643 | I've been struggling for a while with this one. I have a Rails4/Devise 3.1 app with two users in the system:
1. Graduates
2. Employers
and one devise User who can be either a Graduate or Employer via a polymorphic `:profile` association. I have Graduates sign up via `/graduate/sign_up` path and employers via `/employer/sign_up` path both of which route to the same `/views/devise/registrations/new.html.erb` view (since their signup form is pretty much the same - email and password). Everything works fine, except when there is a validation error, `RegistrationsController#create.respond_with resource` always redirects both user types to `/users` path and I need to redirect them back to where they originally came from, e.g. `/graduate/sign_up` or `/employer/sign_up` respectively. I've tried replacing `respond_with` with `redirect_to`, but I end up loosing the resource object with associated error messages. Any idea guys on how this can be done?
These are my models:
```
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :profile, polymorphic: true
end
class Graduate < ActiveRecord::Base
has_one :user, as: :profile
end
class Employer < ActiveRecord::Base
has_one :user, as: :profile
end
```
Registrations controller:
```
class RegistrationsController < Devise::RegistrationsController
def create
build_resource sign_up_params
user_type = params[:user][:user_type]
# This gets set to either 'Graduate' or 'Employer'
child_class_name = user_type.downcase.camelize
resource.profile = child_class_name.constantize.new
if resource.save
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_navigational_format?
sign_up(resource_name, resource)
respond_with resource, :location => after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords(resource)
respond_with resource
end
end
end
```
Registration view (same for both, graduates and employers):
```
<h2>Sign up</h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :email %><br />
<%= f.email_field :email, :autofocus => true %></div>
<div><%= f.label :password %><br />
<%= f.password_field :password %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></div>
<%= hidden_field resource_name, :user_type, value: params[:user][:user_type] %>
<div><%= f.submit "Sign up" %></div>
<% end %>
<%= render "devise/shared/links" %>
```
These are my routes:
```
devise_for :users, :controllers => { :registrations => 'registrations' }
devise_scope :user do
match 'graduate/sign_up', to: 'registrations#new', user: { user_type: 'graduate' }, via: [:get]
match 'employer/sign_up', to: 'registrations#new', user: { user_type: 'employer' }, via: [:get]
end
root to: 'home#index'
```
Output of rake routes;
```
$ rake routes
Prefix Verb URI Pattern Controller#Action
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
user_password POST /users/password(.:format) devise/passwords#create
new_user_password GET /users/password/new(.:format) devise/passwords#new
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
PATCH /users/password(.:format) devise/passwords#update
PUT /users/password(.:format) devise/passwords#update
cancel_user_registration GET /users/cancel(.:format) registrations#cancel
user_registration POST /users(.:format) registrations#create
new_user_registration GET /users/sign_up(.:format) registrations#new
edit_user_registration GET /users/edit(.:format) registrations#edit
PATCH /users(.:format) registrations#update
PUT /users(.:format) registrations#update
DELETE /users(.:format) registrations#destroy
graduate_sign_up GET /graduate/sign_up(.:format) registrations#new {:user=>{:user_type=>"graduate"}}
employer_sign_up GET /employer/sign_up(.:format) registrations#new {:user=>{:user_type=>"employer"}}
root GET /
``` | 2013/10/24 | [
"https://Stackoverflow.com/questions/19574643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2619188/"
] | [Apparently](http://bendyworks.com/blog/respond-with-an-explanation), the `:location` parameter is ignored if you have an existing template called, well, in this case, #index. I still don't understand why Devise redirects to #index or #show when the resource has errors on it.
I'll update this answer as I find out more. | Calling `respond_with` will render the default action of that resource. This I believe is the `index` action (/users/) and thus the cause for the redirect.
I think what you want to do is render the `new` action instead. Try the following:
```
if resource.save
...
else
clean_up_passwords(resource)
render :action => 'new'
end
``` |
7,893,128 | I have a char array that is really used as a byte array and not for storing text. In the array, there are two specific bytes that represent a numeric value that I need to store into an unsigned int value. The code below explains the setup.
```
char* bytes = bytes[2];
bytes[0] = 0x0C; // For the sake of this example, I'm
bytes[1] = 0x88; // assigning random values to the char array.
unsigned int val = ???; // This needs to be the actual numeric
// value of the two bytes in the char array.
// In other words, the value should equal 0x0C88;
```
I can not figure out how to do this. I would assume it would involve some casting and recasting of the pointers, but I can not get this to work. How can I accomplish my end goal?
**UPDATE**
Thank you Martin B for the quick response, however this doesn't work. Specifically, in my case the two bytes are `0x00` and `0xbc`. Obviously what I want is `0x000000bc`. But what I'm getting in my unsigned int is `0xffffffbc`.
The code that was posted by Martin was my actual, original code and works fine so long as all of the bytes are less than 128 (.i.e. positive signed char values.) | 2011/10/25 | [
"https://Stackoverflow.com/questions/7893128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/469319/"
] | ```
unsigned int val = (unsigned char)bytes[0] << CHAR_BIT | (unsigned char)bytes[1];
```
This if `sizeof(unsigned int) >= 2 * sizeof(unsigned char)` (not something guaranteed by the C standard)
Now... The interesting things here is surely the order of operators (in many years still I can remember only `+, -, * and /`... Shame on me :-), so I always put as many brackets I can). `[]` is king. Second is the `(cast)`. Third is the `<<` and fourth is the `|` (if you use the `+` instead of the `|`, remember that `+` is more importan than `<<` so you'll need brakets)
We don't need to upcast to `(unsigned integer)` the two `(unsigned char)` because there is the [integral promotion](http://msdn.microsoft.com/en-us/library/fc9te331.aspx) that will do it for us for one, and for the other it should be an automatic [Arithmetic Conversion](http://msdn.microsoft.com/en-us/library/09ka8bxx.aspx).
I'll add that if you want less headaches:
```
unsigned int val = (unsigned char)bytes[0] << CHAR_BIT;
val |= (unsigned char)bytes[1];
``` | ```
unsigned int val = bytes[0] << 8 + bytes[1];
``` |
25,946,407 | In ios8 delegate methods of UIActionSheet calling multiple times
```
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
```
I have checked in ipad 2 with IOS 8 | 2014/09/20 | [
"https://Stackoverflow.com/questions/25946407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2401215/"
] | Its a bug of the ios 8..
As the @rob said `UIActionSheet` is deprecated in iOS 8. (UIActionSheetDelegate is also deprecated.)
To create and manage action sheets in iOS 8 and later, use `UIAlertController` | If you want to continue using the existing API, there is a bit of behavior that lets you know when to run your code and when to ignore the delegate call - the `buttonIndex`.
The first time the delegate methods are called, they are always passed the correct `buttonIndex`. The second time through, however, they are called with a `buttonIndex` of the cancel button. |
27,877,498 | I have 2 columns in my table in sql server β [Occurrence Time (NT)] and [Clearance Time(NT)] having the format yyyy-mm-dd hh:mm:ss and a third column [Outage Duration] with the format hh:mm:ss
[Identifier] | [Occurrence Time(NT)] | [Clearance Time(NT)] | [Outage Duration]
4 | 2014-12-28 15:06:33.000 | 2014-12-28 15:18:18.000 | 00:11:45.000
Outage duration is calculated as the difference of [Occurrence Time (NT)] and [Clearance Time(NT)]
Currently my code to do this is as follows :
```
select distinct a.[Identifier]
,a.[Occurrence Time(NT)]
,a.[Clearance Time(NT)]
,cast((cast(a.[Clearance Time(NT)] as datetime) - cast(a.[Occurrence Time(NT)]as datetime)) as time )
as [Outage Duration]
from final_report_2 a
```
The cast is just a failsafe as both the columns are already datetime. This code works for all cases where [Occurrence Time (NT)] and [Clearance Time(NT)] fall on the same day i.e. the outage is within 24 hours
For e.g in above row no. 4 both have 28th as the day and thus the outage is calculated correctly.
But the outage duration is wrongly calculated in case of different days.
2678 | 2014-12-28 12:50:04.000 | 2014-12-31 23:59:59.000 | 11:09:55.000
In row 2678 the time should be 83:09:55 instead of 11:09:55.
So I need to factor in the difference of the days as well and then calculate the [Outage duration] in hh:mm:ss format.
One of the possible ways to do this is as follows :
(23:59:59 β 12:50:04) + 00:00:01 + ((31-28-1)\*24):00:00 + 23:59:59
where the first part calculates the time of the first day , then the second part calculates the no. of whole days in between the [Occurrence Time (NT)] and [Clearance Time(NT)] and multiplies it by 24 and the final part represents the time of the final day.
How can I implement the above in sql server ? Can it be done using DATEPART or DATEADD functions? | 2015/01/10 | [
"https://Stackoverflow.com/questions/27877498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4440075/"
] | you need to use `datediff` function.
First find the `difference` in `seconds` between the two dates.
```
select Datediff(SECOND, [Clearance Time(NT)], [Occurrence Time(NT)])
```
Now convert the `seconds` to `hh:mm:ss` using this code.
```
DECLARE @TimeinSecond INT
SET @TimeinSecond = 86399 -- Change the seconds
SELECT RIGHT('0' + CAST(@TimeinSecond / 3600 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST((@TimeinSecond / 60) % 60 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST(@TimeinSecond % 60 AS VARCHAR),2)
```
Change your query something like this.
```
SELECT DISTINCT a.[Identifier],
a.[Occurrence Time(NT)],
a.[Clearance Time(NT)],
RIGHT('0' + Cast(Datediff(SECOND, [Clearance Time(NT)],[Occurrence Time(NT)]) / 3600 AS VARCHAR), 2)
+ ':'
+ RIGHT('0' + Cast((Datediff(SECOND, [Clearance Time(NT)],[Occurrence Time(NT)]) / 60) % 60 AS VARCHAR), 2)
+ ':'
+ RIGHT('0' + Cast(Datediff(SECOND, [Clearance Time(NT)],[Occurrence Time(NT)]) % 60 AS VARCHAR), 2) [Outage Duration]
FROM final_report_2 a
```
**Reference:** conversion of `seconds` to `hh:mm:ss` referred from this **[link](http://blog.sqlauthority.com/2014/08/17/sql-server-convert-seconds-to-hour-minute-seconds-format/)** | Good old SQL DATEDIFF.
Here's the duration function I use. All wrapped up in a UDF.
```
CREATE FUNCTION fDuration(@DtStart DATETIME, @DtEnd DATETIME)
RETURNS VARCHAR(10)
AS
BEGIN
RETURN (
SELECT
CONVERT(VARCHAR(10), t.Hours) + ':' +
RIGHT('00' + CONVERT(VARCHAR(10), t.Minutes), 2) + ':' +
RIGHT('00' + CONVERT(VARCHAR(10), t.Seconds - (t.Hours * 60 * 60) - (t.Minutes) * 60), 2) as Value
FROM (
SELECT
t.Hours,
ABS(t.Seconds / 60 - (t.Hours * 60)) as Minutes,
t.Seconds
FROM (
SELECT
DATEDIFF(SECOND, @DtStart, @DtEnd) as Seconds,
DATEDIFF(SECOND, @DtStart, @DtEnd)/60/60 AS Hours) t
) t)
END
```
USAGE:
```
SELECT dbo.fDuration('2014-12-28 12:50:04.000', '2014-12-31 23:59:59.000')
```
RETURNS :
```
83:09:55
```
In your case, you can modify your query like this
```
SELECT DISTINCT a.[Identifier],
a.[Occurrence Time(NT)],
a.[Clearance Time(NT)],
dbo.fDuration(a.[Occurrence Time(NT)], a.[Clearance Time(NT)]) as [Outage Duration]
FROM final_report_2 a
```
Or even add [Outage Duration] as a Computed field in final\_report\_2 with formula
```
dbo.fDuration([Occurrence Time(NT)],[Clearance Time(NT)])
```
Then it becomes a simple select...
```
SELECT DISTINCT a.[Identifier],
a.[Occurrence Time(NT)],
a.[Clearance Time(NT)],
a.[Outage Duration]
FROM final_report_2 a
```
Note
Hours are not prefixed with a '0'. This allows for negative durations.
Hope that helps |
475,970 | How can I specify a multiline commit message for mercurial on the command line?
```
hg commit -m "* add foo\n* fix bar"
```
does not work. The log shows:
```
changeset: 13:f2c6526e5911
tag: tip
date: Fri Jan 23 23:22:36 2009 +0100
files: foobar.cpp
description:
* add foo\n*fix bar
``` | 2009/01/24 | [
"https://Stackoverflow.com/questions/475970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/52986/"
] | I know, there is already a solution for linux users, but I needed another solution for windows command line, so I was looking for it...
And I found one:
<https://www.mercurial-scm.org/pipermail/mercurial/2011-November/040855.html>
```
hg commit -l filename.txt
```
I hope, it's useful for someone out there ,)
[EDIT]
oO - it has already been added to the help
>
> -l --logfile FILE read commit message from file
>
>
> | In bash (since version 2.0):
```
hg commit -m $'foo\nbar'
```
(I.e. put a **dollar sign** before an opening single quote to make it parse escape sequences (like `\n)` within the string β note that it doesn't work with double quotes.) |
28,577,178 | I'm trying to check modulo of a number against a tuple of numbers, if the modulo is equals to one of the values in the tuple I want to return True else return False.
This is what I had tried so far:
```
def check(y):
k = (2, 5, 8, 10, 13, 16, 19, 21, 24, 27, 29)
for i in range(0, len(k)):
if k[i] == y % 30:
return True
else:
return False
def main():
print(check(1439))
main()
```
It always returns false. | 2015/02/18 | [
"https://Stackoverflow.com/questions/28577178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84199/"
] | It always returns false because this code:
```
for i in range(0, len(k)):
if k[i] == y % 30:
return True
else:
return False
```
returns true or false based only on the *first* item in the array, because it returns in *both* possible code paths. Either `k[0] == y % 30` and it returns true, or `k[0] != y % 30` and it returns false.
If you want to use this loop-based solution, you need to check *every* item in the array, returning true immediately if it matches, otherwise returning false *only* after the list is exhausted, something like (using the `for n in k` variant of the loop since the index is irrelevant here):
```
for n in k:
if n == y % 30:
return True
return False
```
The full program is thus:
```
def check(y):
k = (2, 5, 8, 10, 13, 16, 19, 21, 24, 27, 29)
for n in k:
if n == y % 30:
return True
return False
def main():
print(check(1439))
print(check(36))
main()
```
with the first call producing true as `1439 % 30 == 29` (in the list) but the second giving false because `36 % 30 == 6` (not in the list).
Of course, there's a far more Pythonic way to achieve this:
```
def check(y):
k = (2, 5, 8, 10, 13, 16, 19, 21, 24, 27, 29)
return any (x == y % 30 for x in k)
```
That basically finds any element in `k` for which that element is equal to `y % 30`. See [this link](https://docs.python.org/3/library/functions.html#any) for more information on the Python `any` operation, and you'll see instantly the equivalent code given is remarkably similar to your loop:
```
def any(iterable):
for element in iterable:
if element:
return True
return False
```
But, of course, it turns out to be unnecessary to use `any` in this particular case as `y % 30` is effectively a *fixed* value in the context of searching through the list. Instead, you can opt for the much simpler:
```
def check(y):
k = (2, 5, 8, 10, 13, 16, 19, 21, 24, 27, 29)
return (y % 30) in k
```
leaving the `any` variant for more complex comparisons not easily doable, such as only checking even numbers from the list:
```
def check(y):
k = (2, 5, 8, 10, 13, 16, 19, 21, 24, 27, 29)
return any (x == y % 30 for x in k if x % 2 == 0)
``` | You can accomplish this with a generator expression inside `any()`:
```py
def check(y):
return any(n == y % 30 for n in k)
```
This builds an iterator of booleans that is true for all elements of k that are divisors of `y`. |
53,355 | Assuming the following:
* Operating arbitrary software in a completely read only environment is impractical. (While some software will operate RO without issue, it can be nigh impossible for other software, particularly if source code is not available as is sometimes the case)
* Rebuilding any machine in place is trivial and takes a negligible timespan with whatever method is being used, be it prebuilt images or via configuration management tools rebuilding them or any other combination or alternative.
* Destroying a host will not cause any downtime or service degradation.
Is there any reliable way to estimate how long an OS/Host should be allowed to 'live' before recycling it?
Ideally a way that avoids 'unnecessarily' excessive recycling which regardless of how efficient it is, will be adding overheads and performance penalties which would be best avoided as much as possible. | 2014/03/14 | [
"https://security.stackexchange.com/questions/53355",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/41980/"
] | You have a non-question right here.
Let's look at your second and third assumptions. Rebuilding a machine has negligible cost with zero downtime. The logical conclusion in this ideal world is rebuilding after any instruction is executed. After all, it has zero cost.
Then you say,
>
> Ideally a way that avoids 'unnecessarily' excessive recycling which regardless of how efficient it is, will be adding overheads and performance penalties which would be best avoided as much as possible.
>
>
>
You say the costs are negligible, so why will I want to avoid it?
In the real world, while rebuilding can be highly automated, it does have costs. It takes time to spin up a new VM. While there are very solid failover mechanisms out there, they are costly and there probably *will* be a noticeable impact on performance even if downtime is avoided. So the correct answer is "rebuild only when there is a problem." | It strikes me that this question is very similar to "How often should I change my password?".
There is possibly some benefit to a regular password change / machine rebuild, in that any compromises will be destroyed. However, unless you have invested a huge amount of capital into automation, there will be a non-trivial marginal cost for each password change / machine rebuild (I don't think your second or third assumptions can ever be true).
I agree with Terry essentially: do it when an event has made it necessary, not because you're adhering to a schedule.
A strong password is inherently strong regardless of the passage of time; similarly, a well-hardened system doesn't need to be rebuilt just because X months have passed since the last one. |
9,928,877 | I'm trying to create a windows phone app with lots of texts like this text here under, but it either gets chopped or gets only on 1 line. I have tried different solutions of scrollable textblock and etc but nothing seems to work. The text I want to post in the app is around 30000 characters long. | 2012/03/29 | [
"https://Stackoverflow.com/questions/9928877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111704/"
] | You have to set the [TextWrapping property](http://msdn.microsoft.com/en-us/library/system.windows.controls.textblock.textwrapping%28v=vs.95%29.aspx) to `wrap`.
```
<TextBlock TextWrapping="Wrap"/>
```
Also make sure you don't constrain the TextBlock in terms of height. | I created a RSS reader page within the wp application which solved my issue of text being chopped. My intent with this app was to integrate some info about my clients company.
Regards Joel |
2,339,280 | I am working the iphone/ipad 3.2 SDK and have created a subdirectory named "Docs" under the default Resources directory "Resources-iPad". If I place "file.pdf" directly in the resources directory and make this call, all works well:
```
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(),CFSTR("file.pdf"), NULL, NULL);
```
If I put "file.pdf" in the "Docs" subdirectory and per the Apple docs try this, the call returns NULL:
```
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(),CFSTR("file.pdf"), NULL, CFSTR("Docs");
```
What have I done incorrectly? | 2010/02/26 | [
"https://Stackoverflow.com/questions/2339280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81524/"
] | The information on core data memory management is good info and technically the answer by Arthur Kalliokoski is a good answer re: the difference between a leek and object allocation. My particular problem here is related to an apparently known bug with setBackgroundImage on a button in the simulator, it creates a memory 'leak' in that it doesn't release ever release the memory for the UIImage. | You can have a continuously growing program without necessarily leaking memory. Suppose you read words from the input and store them in dynamically allocated blocks of memory in a linked list. As you read more words, the list keeps growing, but all the memory is still reachable via the list, so there is no memory leak. |
8,407,025 | I'm getting a parameter and getting a specific product from a stored procedure. This stored procedure is returning many columns (I think around 15-20). Unfortunately, some of these values may be null and this of course produces an error when I try to put them in a variable. Is there a simple way to check and see if these values are `NULL` so that it doesn't throw an exception or do I need to put an `if` statement before each assignment? If it helps, here is my code:
```
public List<Product> ReadSpecificProductDetails(string productAndURLID)
{
ConfigureDataAccess();
myCommand = new SqlCommand("[dbo].[GetSpecificProductDetails]", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
//myCommand.Parameters.Add(productAndURLID);
//myCommand.Parameters.Add(new SqlParameter("@ProductID", SqlDbType.SmallInt));
myCommand.Parameters.AddWithValue("@ProductID", Convert.ToInt16(productAndURLID));
try
{
try
{
myConnection.Open();
myReader = myCommand.ExecuteReader();
}
catch (SqlException exception)
{
exception.Data.Add("cstring", myConfiguration);
throw;
}
catch (InvalidOperationException ex)
{
ex.Data.Add("cStatus", myConnection.State);
throw;
}
//Create a 'Product' list to store the records in
while (myReader.Read())
{
int productID = Convert.ToInt16(myReader["ProductID"]);
string productName = (string)myReader["Name"];
string productNumber = (string)myReader["ProductNumber"];
//int quantitySum = Convert.ToInt16(myReader["QuantitySum"]);
string productColor = (string)myReader["Color"];
int productSafetyStockLevel = Convert.ToInt16(myReader["SafetyStockLevel"]);
int productReorderPoint = Convert.ToInt16(myReader["ReorderPoint"]);
decimal productStandardCost = Convert.ToDecimal(myReader["StandardCost"]);
decimal productListPrice = Convert.ToDecimal(myReader["ListPrice"]);
string productSize = (string)myReader["Size"];
decimal productWeight = Convert.ToDecimal(myReader["Weight"]);
int productDaysToManufacture = Convert.ToInt16(myReader["DaysToManufacture"]);
string productCategoryName = (string)myReader["PC.Name"];
string productSubCategoryName = (string)myReader["PS.Name"];
string productModelName = (string)myReader["PM.Name"];
DateTime productSellStartDate = Convert.ToDateTime(myReader["Sell_Start_Date"]);
DateTime productSellEndDate = Convert.ToDateTime(myReader["Sell_End_Date"]);
DateTime productDiscontinuedDate = Convert.ToDateTime(myReader["Discontinued_Date"]);
Product p = new Product(productID, productName, productNumber, productColor, productSafetyStockLevel, productReorderPoint, productStandardCost,
productListPrice, productSize, productWeight, productDaysToManufacture, productCategoryName, productSubCategoryName, productModelName, productSellStartDate,
productSellEndDate, productDiscontinuedDate);
myProducts.Add(p);
}
}
finally
{
myReader.Close();
myConnection.Close();
}
return myProducts;
}
``` | 2011/12/06 | [
"https://Stackoverflow.com/questions/8407025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1078251/"
] | ```
int? x = dt.Field<int?>( "Field" );
```
Or
```
int y = dt.Field<int?>( "Field" ) ?? 0;
```
[C# DBNull and nullable Types - cleanest form of conversion](https://stackoverflow.com/questions/1706405/c-sharp-dbnull-and-nullable-types-cleanest-form-of-conversion)
The top is probably your best approach. You currently have some non nullable types you are populating. So if you want to be able to represent them as null use the top approach. Otherwise you can use the other option to give a default value. | Peform a check for DBNULL for the field you may suspect is a null value. In this case all of them.
```
if (! DBNull.Value.Equals(row[fieldName]))
return (string) row[fieldName] + " ";
else
return String.Empty;
```
What you can do is create a function that has several overloads for int, string, and DateTime parameters that checks for null
So it would look something like this:
```
public string CheckNull(string value)
{
if (! DBNull.Value.Equals(value))
return value;
else
return String.Empty;
}
```
This way you would only have to do something like
```
object.stringProperty = (string)CheckNull(row["columnName"]);
``` |
4,091,458 | I love JOCL, Java bindings for OpenCL. I would like to run Cuda-memcheck on an executable from Java, but whenever I make Java applications, they are always just JAR files that point to a Main-Class. Is there a way to create a .exe file like C++ does and feed that to Cuda-memcheck? | 2010/11/03 | [
"https://Stackoverflow.com/questions/4091458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1202394/"
] | While [Jon has answered](https://stackoverflow.com/a/4091497/4751173) the question on making the list immutable, I would like to also point out that even if the list is immutable, its contained objects are not automatically immutable.
Even if you make the list immutable (for instance by copying its contents into a `ReadOnlyCollection<T>`), *you can still manipulate properties of the contained objects, if they are not of an immutable type*. As soon as you pass out references to the objects contained in the list, calling code can manipulate those objects.
Let's take an example:
```
class Person
{
public string Name { get; set; }
}
class Group
{
private readonly IEnumerable<Person> _persons;
public Group(IEnumerable<Person> persons)
{
_persons = new ReadOnlyCollection<Person>(persons.ToList());
}
public IEnumerable<Person> Persons
{
get
{
foreach (var person in _persons)
{
yield return person;
}
}
}
}
```
Then we have the following code:
```
List<Person> persons = new List<Person>( new[]{new Person { Name = "Fredrik MΓΆrk" }});
Group smallGroup = new Group(persons);
Console.WriteLine("First iteration");
foreach (var person in smallGroup.Persons)
{
Console.WriteLine(person.Name);
person.Name += " [altered]";
}
Console.WriteLine("Second loop");
foreach (var person in smallGroup.Persons)
{
Console.WriteLine(person.Name); // prints "Fredrik MΓΆrk [altered]"
}
```
As you can see, even though we have make the *list* effectively immutable, \*`Person` is not an immutable type. Since the `Persons` property of the `Group` class passes out references to the actual `Person` objects, the calling code can easily manipulate the object.
One way to protect yourself against this is to expose the collection as an `IEnumerable<T>` using `yield return` and some cloning mechanism to make sure that you don't pass out the original object references. For example, you can alter the `Person` class into this:
```
class Person
{
public string Name { get; set; }
// we add a copy method that returns a shallow copy...
public Person Copy()
{
return (Person)this.MemberwiseClone();
}
}
class Group
{
private readonly IEnumerable<Person> _persons;
public Group(IEnumerable<Person> persons)
{
_persons = new ReadOnlyCollection<Person>(persons.ToList());
}
public IEnumerable<Person> Persons
{
get
{
foreach (var person in _persons)
{
// ...and here we return a copy instead of the contained object
yield return person.Copy();
}
}
}
}
```
Now, the program above will *not* alter the name of the `Person` instance inside the list, but its own copy. However, note that we now have what can be called **shallow immutability**: if `Person` in turn would have members that are not immutable, the same problem exists for those objects, and so on...
Eric Lippert wrote a 10-part series of blog post on the topic in 2007. The first part is here: [Immutability in C# Part One: Kinds of Immutability](https://ericlippert.com/2007/11/13/immutability-in-c-part-one-kinds-of-immutability/). | AFAIK, because of the less complex structure, the rule would be: If you need to increase or decrease the size of the collection, use list, if not and you are only using it for enumeration, use array.
I don't think constant vs regular variable makes much of a different in the instantiation of the object. |
54,972,875 | Suppose I have a string
```
String str =" Hello, @John how's going on"
```
Now I want to know., how to highlight the word `@John` and wanna make it clickable from Textview | 2019/03/03 | [
"https://Stackoverflow.com/questions/54972875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8469107/"
] | You can use `clickable span` in a `spannable` string like the following :-
```
SpannableString ss = new SpannableString(" Hello, @John how's going on");
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View textView) {
//perform click operation
}
@Override
public void updateDrawState(TextPaint ds) {
}
};
ss.setSpan(clickableSpan, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
yourTv.setText(ss);
yourTv.setMovementMethod(LinkMovementMethod.getInstance());
yourTv.setHighlightColor(Color.TRANSPARENT);
```
>
> startIndex - is the index of **J** of word **John** in the full string
>
>
> endIndex - is the index of **n** of the word **John** in the full string.
>
>
>
&& the **onclick** method will be triggered once john is clicked..
**Edit**
*To extract the username John* u can split the string and get it like this snippet :-
```
String username = yourString.split("@")[1].split(" ")[0]; // this will extract john
``` | This will also work with multible mentions.
```js
var str = "Hello, @John how's going on. Greedings to @Bob.";
var regex = /[@]\S[^. ]*/g;
var matches = str.match(regex)
var split = str.split(regex);
for(var i = 0; i<matches.length;i++){
document.body.appendChild(document.createTextNode(split[i]));
var a = document.createElement('a');
a.appendChild(document.createTextNode(matches[i]));
a.title = "my title text";//text you can see onHover
a.href = "http://example.com/users/"+matches[i].split('@')[1];//link to user
document.body.appendChild(a);
}
document.body.appendChild(document.createTextNode(split[split.length-1]));
``` |
18,754,420 | I learned that when constructing an object, `super()` will be called, whether you write it in the constructor or not. But I noticed that in some code, the `super()` method is called explicitly. Should I be calling `super()` implicitly or explicitly in a constructor? What's the difference? | 2013/09/12 | [
"https://Stackoverflow.com/questions/18754420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2749891/"
] | Had a hard time with this myself. In foundation 5, solution is below. Referenced from: <https://github.com/zurb/foundation/issues/4468>
```
$(document).foundation({
joyride: {
post_ride_callback : function () {
alert('yay');
}
}
}).foundation('joyride', 'start');
``` | You need to explicitly either blankety declare foundation on the whole document first or call joyride on the document first then call start + your config... not sure why it's set up this way as it's very confusing but here it is:
```
var config = {
nubPosition : 'auto',
postRideCallback : function() {
alert('done');
}
$(document).foundation('joyride').foundation('joyride','start',config);
```
please vote this up if it works. |
126,413 | I currently work for a medium-large (~500 employees) Italian company as a Linux developer. I work in a team of 8 people, most of them are really awesome and really friendly, the day life is good and so is the comfort that the company offers.
To reach the office I have to drive around 75km per day, on alternating weeks (I share the car with a colleague), so around 750km per month just to go to and from work. My salary is ~15% less than the Italian average for the position I cover.
A couple of days per month I also work for another company, way smaller (around 10 employees) which is 10km away from my place. There I work with a guy that is a consultant for the first company. We work quite well together. The office is often almost empty since more than half of the team work in a different city.
Recently the new company asked me to join them as a full-time developer, with a salary that is almost double my current one.
I don't know exactly what to do and what I should take into account to choose what to do.
I feel guilty leaving my current team knowing the difficulties we are facing right now (mostly because the team is too small for the amount of work).
(Of course I can earn more money and gain more free time in the new job.)
Should I have concern for my previous workplace, when considering a new job?
Some extra info: I've worked at the first company since January 2018 and I'm almost 23 years old. | 2019/01/14 | [
"https://workplace.stackexchange.com/questions/126413",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/97910/"
] | Many people I know have felt exactly as you do, leaving both better and significantly worse employers than yours. I felt the same, when I left my first employer. I confused the personal loyalty I felt to my team, my manager and the company with my duty as an employee. Of course you feel loyal, you've worked there for a year and you've grown immensely! However, you cannot be responsible for the work you leave behind. It is your manager's job to ensure that the team can cope with the loss of any one member. That is not your cross to bear. That said, which option provides you with more room to grow, in ways you would like to grow?
You might not yet know which professional growth your new employer can offer you, while you do know what skills you can develop and projects you can complete with the old employer. Many of us are a little risk averse. How does that factor into your current feelings?
There is (or will be) more to life than a job. A pay rise early in your career can be a huge boost to your financial prospects. Working closer to home means more time to invest in you, family and friends - or in your career. That is a level of freedom that your current job may not be able to offer you. Don't compare the jobs in isolation. Instead, weigh the possibilities offered by the jobs (including the freedom to do work that you like, in a team that you like). | **No you should not be concerned about your future-ex company.**
This is business, not college and **you're working to make money, not friends**.
Most workplaces guilt trip you into thinking that you somehow owe them anything. Truth is: you don't. As a worker you are creating revenue for the company (despite them paying you!) and they need you more than you need them anyway. Do not think for a single second that your employer will be concerned when it's time to fire you and treat as they would you: professionally and rationally.
Now whether you should take the offer that doubles your salary is a different altogether, and only you can decide if the overall offer (salary, bonuses, perks, work environment, colleagues...) is better or not than your current one. But keep in mind that emotional ties to your current employer is never a valid reason make a decision about your career. |
25,656,375 | How don't i apply css of jquery mobile to specific elements?
Isn't there any way to do this without modifying the css file of jquery mobile?
plz help me. | 2014/09/04 | [
"https://Stackoverflow.com/questions/25656375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2503508/"
] | By default, jQuery `$.ajax` will submit your request as form data. If you open your browser debugger while the request is sent, you would see this request data:
```
system[]:31
system[]:32
system[]:33
system[]:34
system[]:35
system[]:36
system[]:37
system[]:38
system[]:39
system[]:42
system[]:43
```
PHP understands that this is an array and reads it in as an array by default. **You should not wrap it in an `array()` tag.**
You can assign the array to your own variable as such: **`$system = $_POST['system'];`**
However, your work isn't quite done there. `$system` is now an **array of strings**. Here is a `var_dump` of `$system`:
```
array(11) {
[0]=>
string(2) "31"
[1]=>
string(2) "32"
[2]=>
string(2) "33"
[3]=>
string(2) "34"
[4]=>
string(2) "35"
[5]=>
string(2) "36"
[6]=>
string(2) "37"
[7]=>
string(2) "38"
[8]=>
string(2) "39"
[9]=>
string(2) "42"
[10]=>
string(2) "43"
}
```
Use this to convert it to an **array of integers**:
`$system = array_map('intval', $system);` | I awarded the answer to `@Barmar` as his solution solved the original OP. I still had a problem with getting the JS arrays across to the PHP array due to using `system = $(this).attr('data-system')`. Changing the code to the following fixed that issue:
```
$('#sub_category_box_systems').on('click', '.sub_category_link', function() {
system = $(this).attr('data-system').split(",");
});
``` |
3,448,952 | What's wrong with this code? Why doesn't it show value?
```
<script>
$(document).ready(function()
{
$('#radio_div').change(function(event){
var value = $("input[@name='rdio']:checked").val();
$('#update_text').html('Radio value:' + value);
});
});
</script>
</head>
<body>
<div id="radio_div">
<input type="radio" name="rdio" value="a" />
<input type="radio" name="rdio" value="b" />
<input type="radio" name="rdio" value="c" />
</div>
<div id="update_text">Please push radio button</div>
``` | 2010/08/10 | [
"https://Stackoverflow.com/questions/3448952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415459/"
] | You're adding a `change` handler to a `<div>` element.
Since `<div>` elements never generate `change` events, your code doesn't work.
Instead, you should add the `change` handler to the `input` elements *inside* the `<div>` element, like this:
```
$('#radio_div :radio').change(...)
```
(The [`:radio` selector](http://api.jquery.com/radio-selector/) matches radio inputs) | Try this :
```
$('#radio_div input:radio').click(function() {
if($(this).is(':checked')) {
$(this).val(); // $(this).attr('value');
}
});
``` |
10,305,047 | ```
ImageIcon backpackImageIcon = new ImageIcon("images/gui/button_backpack.png");
JButton backpackButton = new JButton();
backpackButton.setBounds(660,686,33,33);
backpackButton.setBorderPainted(false);
backpackButton.setFocusPainted(false);
backpackButton.setVisible(true);
backpackButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("B"), "backpackButtonPress");
backpackButton.getActionMap().put("backpackButtonPress", ClassBackpackButton);
backpackButton.setAction(ClassBackpackButton);
backpackButton.setIcon(backpackImageIcon);
backpackButton.setToolTipText("Backpack[B]");
panel.add(backpackButton);
```
I have multiple buttons set up this exact way. What I was hoping to be able to do was to have them darken 10% on hover and maybe 20% on click. I tried to look around for how to do this but had no luck(only found javascript stuff). Sorry if this has been asked before and thanks for any help.
\*\* ***EDIT*** \*\*
I have tried to do this but it just turns the image blank:
```
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(new File("images/gui/button_backpack.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedImage darkerBackpackBufferedImage = new BufferedImage(32, 32, BufferedImage.TYPE_BYTE_INDEXED);
RescaleOp op = new RescaleOp(1.3f, 0, null);
darkerBackpackBufferedImage = op.filter(bufferedImage, null);
ImageIcon darkerBackpackImageIcon = new ImageIcon((Image) darkerBackpackBufferedImage);
backpackButton.setRolloverIcon((ImageIcon) darkerBackpackImageIcon);
```
\*\* ***EDIT*** \*\* with solution
here is the modified shiftColor function that I went with for anyone reading this above... good luck :)
```
public BufferedImage shiftColor(BufferedImage img, int rShift, int gShift, int bShift) {
Color tmpCol;
int tmpRed, tmpGreen, tmpBlue;
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
tmpCol=new Color(img.getRGB(x,y));
tmpRed = (tmpCol.getRed()-rShift < 0) ? 0 : tmpCol.getRed()-rShift; //if shifted color is less than 0 change to 0
tmpGreen = (tmpCol.getGreen()-gShift < 0) ? 0 : tmpCol.getGreen()-gShift; //if shifted color is less than 0 change to 0
tmpBlue = (tmpCol.getBlue()-bShift < 0) ? 0 : tmpCol.getBlue()-bShift; //if shifted color is less than 0 change to 0
tmpCol=new Color(tmpRed, tmpGreen, tmpBlue);
img.setRGB(x,y,tmpCol.getRGB());
}
}
return img;
}
``` | 2012/04/24 | [
"https://Stackoverflow.com/questions/10305047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572286/"
] | This function will return a BufferedImage with a color offset (ie. lighter/darker)
```
public BufferedImage shiftColor(BufferedImage img, int rShift, int gShift,int bShift) {
Color tmpCol;
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
tmpCol=new Color(img.getRGB(x,y));
tmpCol=new Color(tmpCol.getRed()-rShift,tmpCol.getGreen()-gShift,tmpCol.getBlue()-bShift);
img.setRGB(x,y,tmpCol.getRGB());
}
}
return img;
}
```
Even though this will work, I still recommend creating both the light and dark image in an image editor (ie. Photoshop) and loading both at startup. The above code will be process intensive and will slow your apps runtime. | Check out this [tutorial](http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html). You are probably interested in mouseEntered. As instead of changing the color of the backpack in Java consider 2 images, one of a light backpack and another of a dark backpack. Change them when you hover over the button.
```
public class MouseEventDemo implements MouseListener {
ImageIcon backpackImageIcon = new ImageIcon("images/gui/button_backpack.png");
JButton backpackButton = new JButton();
backpackButton.setBounds(660,686,33,33);
backpackButton.setBorderPainted(false);
backpackButton.setFocusPainted(false);
backpackButton.setVisible(true);
backpackButton.addMouseListener(this);
addMouseListener(this);
backpackButton.setIcon(backpackImageIcon);
backpackButton.setToolTipText("Backpack[B]");
panel.add(backpackButton);
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
//set button color to dark color
}
public void mouseExited(MouseEvent e) {
//set button color to light color
}
public void mouseClicked(MouseEvent e) {}
}
``` |
44,234,876 | I am new to spark and scala. I want to read a directory containing json files. The file has attribute called "EVENT\_NAME" which can have 20 different values. I need to separate the events, depending upon the attribute value. i.e. EVENT\_NAME=event\_A events together. Write these in hive external table structure like: /apps/hive/warehouse/db/event\_A/dt=date/hour=hr
Here I have 20 different tables for all the event types and data related to each event should go to respective table.
I have managed to write some code but need help to write my data correctly.
```
{
import org.apache.spark.sql._
import sqlContext._
val path = "/source/data/path"
val trafficRep = sc.textFile(path)
val trafficRepDf = sqlContext.read.json(trafficRep)
trafficRepDf.registerTempTable("trafficRepDf")
trafficRepDf.write.partitionBy("EVENT_NAME").save("/apps/hive/warehouse/db/sample")
}
```
The last line creates a partitioned output but is not how exactly I need it. Please suggest how can I get it correct or any other piece of code to do it. | 2017/05/29 | [
"https://Stackoverflow.com/questions/44234876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1728716/"
] | I'm assuming you mean you'd like to save the data into separate directories, without using Spark/Hive's `{column}={value}` format.
You won't be able to use Spark's `partitionBy`, as Spark partitioning forces you to use that format.
Instead, you have to break your `DataFrame` into its component partitions, and save them one by one, like so:
```
{
import org.apache.spark.sql._
import sqlContext._
val path = "/source/data/path"
val trafficRep = sc.textFile(path)
val trafficRepDf = sqlContext.read.json(trafficRep)
val eventNames = trafficRepDf.select($"EVENT_NAME").distinct().collect() // Or if you already know what all 20 values are, just hardcode them.
for (eventName <- eventNames) {
val trafficRepByEventDf = trafficRepDef.where($"EVENT_NAME" === eventName)
trafficRepByEventDf.write.save(s"/apps/hive/warehouse/db/sample/${eventName}")
}
}
``` | <https://spark.apache.org/docs/latest/sql-programming-guide.html#upgrading-from-spark-sql-16-to-20>
>
> Dataset and DataFrame API `registerTempTable` has been deprecated and replaced by `createOrReplaceTempView`
>
>
>
<https://spark.apache.org/docs/2.1.1/api/scala/index.html#org.apache.spark.sql.DataFrameWriter@saveAsTable(tableName:String):Unit> |
32,423,408 | I am trying and failing to save a grid of ggplots as a .png on my hard drive and would appreciate some help troubleshooting my code.
Here's an example that reproduces my error using public data on Lego Star Wars sets:
```
library(dplyr)
library(ggplot2)
library(grid)
library(gridExtra)
# Load the Lego data and subset it to Lego Star Wars sets
Lego <- read.csv("https://raw.githubusercontent.com/seankross/lego/master/data-tidy/legosets.csv", stringsAsFactors=FALSE)
Lego.SW <- filter(Lego, Theme=="Star Wars")
# Make a list with the ggplot objects to plot
lego_plot_list = list()
lego_plot_list[[1]] = ggplot(tally(group_by(Lego.SW, Year)), aes(x=Year, y=n)) + geom_line() + theme_bw() + ylab("Number of sets released")
lego_plot_list[[2]] = ggplot(Lego.SW, aes(Pieces)) + geom_histogram(binwidth=10) + theme_bw() + ylab("Number of sets")
lego_plot_list[[3]] = ggplot(Lego.SW, aes(USD_MSRP)) + geom_histogram(binwidth=10) + theme_bw() + xlab("Price (USD)") + ylab("Number of sets")
lego_plot_list[[4]] = ggplot(Lego.SW, aes(x=Pieces, y=USD_MSRP)) + geom_point() + theme_bw() + xlab("Number of pieces") + ylab("Price")
# Make the plots
lego.grid = marrangeGrob(lego_plot_list, nrow=2, ncol=2, top="")
lego.grid # show in terminal to make sure we're getting what we want
ggsave("legostarwars.png", lego.grid)
```
And here's the error I get at the end of that process, whether or not I previously display `lego.grid` in the terminal:
```
Error in ggsave("legostarwars.png", lego.grid) :
plot should be a ggplot2 plot
```
I *think* my code follows the example given in the `arrangeGrob()` documentation, and I didn't see a different solution in related questions. Apologies if I overlooked something and this is a duplicate.
In case it's relevant, here's my session info:
```
R version 3.2.1 (2015-06-18)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 8 x64 (build 9200)
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] grid stats graphics grDevices utils datasets methods base
other attached packages:
[1] dplyr_0.4.2 gridExtra_2.0.0 ggplot2_1.0.1
loaded via a namespace (and not attached):
[1] Rcpp_0.12.0 assertthat_0.1 digest_0.6.8 MASS_7.3-43 R6_2.1.0 plyr_1.8.3 DBI_0.3.1 gtable_0.1.2 magrittr_1.5
[10] scales_0.2.5 stringi_0.5-5 lazyeval_0.1.10 reshape2_1.4.1 labeling_0.3 proto_0.3-10 tools_3.2.1 stringr_1.0.0 munsell_0.4.2
[19] parallel_3.2.1 colorspace_1.2-6
``` | 2015/09/06 | [
"https://Stackoverflow.com/questions/32423408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1708299/"
] | If you're saving to a single png file, you probably don't mean to use `marrangeGrob()` (**m**ultiple pages), but `arrangeGrob()`.
The error you see is due to a check in `ggplot2::ggsave`, which should disappear in the next release. In the meantime you can either call `png()` explicitly, or install the dev version of ggplot2. | Using the devel version of `dplyr/ggplot2` in `R 3.2.2`, it worked for me.
```
lego.grid <- marrangeGrob(lego_plot_list, nrow=2, ncol=2, top="")
grid.newpage()#from @baptiste's comments
ggsave("legostarwars.png", lego.grid)
#Saving 7 x 6.99 in image
```
[![enter image description here](https://i.stack.imgur.com/RcN2c.png)](https://i.stack.imgur.com/RcN2c.png)
```
sessionInfo()
R version 3.2.2 (2015-08-14)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 14.04.2 LTS
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] grid stats graphics grDevices utils datasets methods
[8] base
other attached packages:
[1] lazyeval_0.1.10.9000 gridExtra_2.0.0 ggplot2_1.0.1.9003
[4] data.table_1.9.5 dplyr_0.4.3.9000 overflow_0.2-1
[7] stringr_1.0.0 reshape2_1.4.1
loaded via a namespace (and not attached):
[1] Rcpp_0.12.0 assertthat_0.1 chron_2.3-45 plyr_1.8.2
[5] R6_2.0.1 gtable_0.1.2 DBI_0.3.1 magrittr_1.5
[9] scales_0.3.0 stringi_0.5-1 labeling_0.3 tools_3.2.2
[13] munsell_0.4.2 parallel_3.2.2 colorspace_1.2-6
``` |
51,266,104 | In **C++ Primer 5th**, it says that the default implementation of `stack` and `queue` is `deque`.
I'm wondering why they don't use `list`? Stack and Queue doesn't support random access, always operate on both ends, therefore `list` should be the most intuitive way to implement them, and `deque`, which support random access (with constant time) is somehow not necessary.
Could anyone explain the reason behind this implementation? | 2018/07/10 | [
"https://Stackoverflow.com/questions/51266104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6861219/"
] | With `std::list` as underlying container each `std::stack::push` does a memory allocation. Whereas `std::deque` allocates memory in chunks and can reuse its spare capacity to avoid the memory allocation.
With small elements the storage overhead of list nodes can also become significant. E.g. `std::list<int>` node size is 24 bytes (on a 64-bit system), with only 4 bytes occupied by the element - at least 83% storage overhead. | the main reason is because deque is faster than the list in average for front and back insertions and deletions
deque is faster because memory is allocated by chunks were as list need allocation on each elements and allocation are costly operations.
[benchmark](https://baptiste-wicht.com/posts/2017/05/cpp-containers-benchmark-vector-list-deque-plf-colony.html) |
19,445,534 | Is it possible to create an application that could be executed on `iOS 5` devices with the new `Xcode 5`? On the software update page, within the app store, there is an `Xcode 5` update available, but i am wondering if it would be a wise thing to do to update to Xcode 5.
My major concern is whether i could still create applications targeting iOS 5, and if i could still work on old projects targeting `iOS 5`.
I have searched through SO but seems there is not much related resources yet. Please shed some light on this. Thanks! | 2013/10/18 | [
"https://Stackoverflow.com/questions/19445534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2893866/"
] | in xcode5 **Preference** you can download the `simulator` for iOS 5.0, iOS 5.1, iOS 6.0, iOS 6.1 like below image from Xcode Download preference:
![enter image description here](https://i.stack.imgur.com/mTeAF.png)
After set Deployment Target:-
![enter image description here](https://i.stack.imgur.com/whNMH.png)
here you getting option for testing which simulatore:-
![enter image description here](https://i.stack.imgur.com/bAqLR.png) | Yes , you can create and test your application on iOS 5.0 simulator too in Xcode 5.
They would just be created with the iOS 7.0 SDK as the base SDK |
15,612,279 | Is there any way to print the first N words of a file? I've tried cut but it reads a document line-by-line. The only solution I came up with is:
```
sed ':a;N;$!ba;s/\n/Ξ΄/g' file | cut -d " " -f -20 | sed 's/Ξ΄/\n/g'
```
Essentially, replacing newlines with a character that doesn't not exist in the file, applying "cut" with space as delimiter and then restoring the newlines.
Is there any better solution? | 2013/03/25 | [
"https://Stackoverflow.com/questions/15612279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1651270/"
] | You could use `awk` to print the first n words:
```bsh
$ awk 'NR<=8{print;next}{exit}' RS='[[:blank:]]+|\n' file
```
This would print the first 8 words. Each word is output on a separate line, are you looking to keep the original format of the file?
**Edit:**
The following will preserve the original format of the file:
```bsh
awk -v n=8 'n==c{exit}n-c>=NF{print;c+=NF;next}{for(i=1;i<=n-c;i++)printf "%s ",$i;print x;exit}' file
```
**Demo:**
```bsh
$ cat file
one two
thre four five six
seven 8 9
10
$ awk -v n=8 'n==c{exit}n-c>=NF{print;c+=NF;next}{for(i=1;i<=n-c;i++)printf "%s ",$i;print x;exit}' file
one two
thre four five six
seven 8
```
A small caveat: if the last line printed doesn't use a single space as a separator this line will lose it's formatting.
```bsh
$ cat file
one two
thre four five six
seven 8 9
10
# the 8th word fell on 3rd line: this line will be formatted with single spaces
$ awk -v n=8 'n==c{exit}n-c>=NF{print;c+=NF;next}{for(i=1;i<=n-c;i++)printf "%s ",$i;print x;exit}' file
one two
thre four five six
seven 8
``` | Why not try turning your words into lines, and then just using `head -n 20` instead?
For example:
```
for i in `cat somefile`; do echo $i; done | head -n 20
```
It's not elegant, but it does have considerably less line-noise regex. |
313,384 | I'm working on a somewhat simple game. Currently trying to implement the game logic for moving the pieces around.
Logic is something like this:
```
does player have pieces in inventory?
if yes:
did they try to move it to an empty location
if yes: ...
if no: ...
if no:
...
```
As you can see it's a bunch of nested if-else statements. My question is how could one refactor the code (or perhaps even approach the design) to avoid large nested blocks of if-else statements.
My game is not chess, but if you take chess for example, how should you approach the design as to avoid conditionals where the game logic is quite complex.
From the very brief search I've done polymorphism seems to be one(1)
(1) <https://stackoverflow.com/questions/7264145/if-less-programming-basically-without-conditionals> | 2016/03/21 | [
"https://softwareengineering.stackexchange.com/questions/313384",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/201143/"
] | I advocate for the middle path. There's nothing wrong with if statements but deep nesting is something you want to avoid. As a rule of thumb, if you get to the third level of nesting, you should probably restructure the code. The first and most basic approach is to create new methods. So in your example, you'd have the top level if and then call methods that handle the second level. This is a perfectly fine approach but you might run into new issues. The main problem is if you have a bunch of calculations that you have to use in all the layers of nesting. Resist the temptation to move them to a higher-scope (like the object) simply to avoid passing parameters. That way lies madness.
The second approach is to use polymorphism. A good example create a class for each chess piece. They would each implement a method (or methods) determining their legal moves. You avoid having a big if statement saying something like if queen ..., if king ... if pawn ... Going even deeper, get a handle on the Strategy pattern. It's one of the best examples of effective OO design and highly relevant to games. | you could make use of OOP to solve this.
```
var piece = GetPiece(..);
if (piece != null)
{
board.Move(piece,location);
}
else
{
//do something
}
```
Now the first line, `piece != null` handles the
>
> does player have pieces in inventory?
>
>
>
The `board.Move(piece,location)` would have the logic to see
>
> did they try to move it to an empty location.
>
>
>
Obviously piece has it's logic such as movement pattern. |
62,115,591 | As Async Storage is deprecated what other way is there to store a variable locally??
I have a React Native ios App with a Notification Centre.
Each time the user enters the Notification Centre a Cognito access Token was generated. To avoid excess of token generation the Tokens were saved through Async storage and their expiry was checked.
Now is there some other local storage in React Native that i can use?? | 2020/05/31 | [
"https://Stackoverflow.com/questions/62115591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13246365/"
] | **AsyncStorage is deprecated so use below package**
Get library With Yarn:
```
yarn add @react-native-async-storage/async-storage
```
**Once done, import the header**
```
import AsyncStorage from '@react-native-async-storage/async-storage';
```
**For store a value**
```
const storeData = async (value) => {
try {
await AsyncStorage.setItem('@storage_Key', value)
} catch (e) {
// saving error
}
}
```
**Get a Value**
```
const getData = async () => {
try {
const value = await AsyncStorage.getItem('@storage_Key')
if(value !== null) {
// value previously stored
}
} catch(e) {
// error reading value
}
}
```
For more: [offical link](https://react-native-async-storage.github.io/async-storage/docs/usage) | Async storage from `react-native` library is deprecated, they split it from react-native core into a community library.
You can always use Async Storage from this [library](https://github.com/react-native-community/async-storage)
Just follow installation steps from [docs](https://react-native-community.github.io/async-storage/docs/install). And you can import `AsyncStorage` like this
```
import AsyncStorage from '@react-native-community/async-storage';
``` |
44,183,784 | I would like to ask you if the current schema design on a HBase table is correct for the following scenario:
I receive 10 million events per day each having a unix epoch timestamp and an id. I will have to group by day, so that I can easily scan for those events that happened on a specific day.
**Current design**:
Events timestamp is converted to a format "MM-YYYY\_DD" string as key and each id of an event that occurred on that day is stored in the row. This will result in up to 10 million columns in one row.
As far as I understand HBase there is a lock on writing on a single row. Resulting in having many locks when importing a single day and decreasing performance.
Maybe this would be a **better design?**: Use the unix epoch timestamp as a row's key resulting in many rows with several thousand columns (several events may occurring on the same second, because my timestamp has a max. resolution of one second).
When scanning one can calculate the start and end time in unix epoch and do the scan. | 2017/05/25 | [
"https://Stackoverflow.com/questions/44183784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7804338/"
] | ```
#include <iostream>
enum Direction { UP, UP_RIGHT, RIGHT, DOWN_RIGHT, DOWN, DOWN_LEFT, LEFT, UP_LEFT };
Direction GetDirectionForAngle(int angle)
{
const Direction slices[] = { RIGHT, UP_RIGHT, UP, UP, UP_LEFT, LEFT, LEFT, DOWN_LEFT, DOWN, DOWN, DOWN_RIGHT, RIGHT };
return slices[(((angle % 360) + 360) % 360) / 30];
}
int main()
{
// This is just a test case that covers all the possible directions
for (int i = 15; i < 360; i += 30)
std::cout << GetDirectionForAngle(i) << ' ';
return 0;
}
```
This is how I would do it. (As per my previous comment). | ```
switch (this->_car.getAbsoluteAngle() / 30) // integer division
{
case 0:
case 11: this->_car.edir = Car::EDirection::RIGHT; break;
case 1: this->_car.edir = Car::EDirection::UP_RIGHT; break;
...
case 10: this->_car.edir = Car::EDirection::DOWN_RIGHT; break;
}
``` |
3,743,726 | >
> How to efficiently perform matrix inversion more than once $\left(A^TA + \mu I \right)^{-1}$ if $\mu \in \mathbb{R}$ is changing but $A \in \mathbb{R}^{n \times m}$ is fixed?
>
>
>
>
> Or do I need to invert the whole matrix in every update of $\mu$?
>
>
> | 2020/07/03 | [
"https://math.stackexchange.com/questions/3743726",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/602319/"
] | Do you need to have the matrix in explicit form, or are you happy for it to be factored? If the latter, then note that adding a constant to the diagonal of a matrix leaves the eigenvectors unchanged and shifts all the eigenvalues by that constant. That's easy to see since if A*x*=$\lambda$*x*, then (A+$\mu$I)*x* = ($\lambda+\mu$)x. If you've done the eigendecomposition, then the new inverse is just V $(\Lambda + \mu I)^{-1}$ V$^T$. Since the thing being inverted is diagonal, this is very fast. | To invert any matrix $\bf X$ you can reformulate it into
"Find the matrix which if multiplied by $\bf X$ gets closest to $\bf I$".
To solve that problem, we can set up the following equation system.
$$\min\_{\bf v}\|{\bf M\_{R(X)}} {\bf v} - \text{vec}({\bf I})\|\_2^2$$
where $\text{vec}({\bf I})$ is vectorization of the identity matrix, $\bf v$ is vectorization of ${\bf X}^{-1}$ which we are solving for and $\bf M\_{R(X)}$ represents multiplication (from the right) by matrix $\bf X$. If no inverse exists, then this should still find a closest approximation to an inverse in the 2-norm sense.
This will be a linear least squares problem that should converge in worst case same number of iterations as matrix size.
But, if we run some iterative solver and have a good initial guess, then it can go much faster than that.
Information on how to construct $\bf M\_{R(X)}$ should exist at the wikipedia entry for [Kronecker Product](https://en.wikipedia.org/wiki/Kronecker_product#Matrix_equations).
If you look at this:
$$({\bf B^T\otimes A})\text{vec}({\bf X}) = \text{vec}({\bf AXB}) = \text{vec}({\bf C})$$
We can rewrite it: $$({\bf B^T\otimes A})\underset{\bf v}{\underbrace{\text{vec}({\bf X})}}-\underset{\text{vec}({\bf I})}{\underbrace{\text{vec}({\bf C})}} = {\bf 0}$$
Maybe now it becomes clearer what $\bf M\_{R(X)}$ should be.
---
**Edit**:
If we combine this with an iterative Krylov subspace solver, we are allowed to choose an initial "guess" for the solution to the equation system.
So let us assume we have found one solution $X\_1 = (A^TA + \mu\_1 I)^{-1}$.
We can now use $X\_1$ as initial guess when solving for $X\_2 = (A^TA+\mu\_2 I)^{-1}$ |
59,308 | I would like to remove a wall in my walk-out basement but I don't know how to interpret this architectural blueprint. Based on this blueprint, is the wall bearing load or not? I have highlighted the wall in question in the pictures below.
[![enter image description here](https://i.stack.imgur.com/8vFJJ.jpg)](https://i.stack.imgur.com/8vFJJ.jpg)
Click for larger view
[![enter image description here](https://i.stack.imgur.com/qgCVi.jpg)](https://i.stack.imgur.com/qgCVi.jpg)
Click for larger view | 2015/02/10 | [
"https://diy.stackexchange.com/questions/59308",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/7085/"
] | EDIT: On second look, the drawing actually tells us. There's a note box to the right: TYP BEARING WALL 2x4 stud 16" O.C. on Continuous footing. The dashed line around the wall indicates the footing.
ORIGINAL:
If I'm reading the drawing correctly, **IT DEFINITELY IS**.
For the sake of this discussion, north is the top of the drawing.
There appears to be a beam running E-W from the post to the East wall. There are no notes on the west wall talking about a beam pocket. This leads me to believe that the dark line following the same path as the beam is simply a dimension line, not a continuation of the beam. So the beam does not extend westward towards the area you want to deal with.
This makes the total span in the area you're looking at 36 feet. Far too long for 2 x 12's,
which means the wall you want to remove is definitely supporting the joists.
Even if the beam does continue, I would take great care. 20 feet is about the max for a joist span. This job calls for a professional engineer to assess the situation.
The solution is probably to dig a footer where the doorway is now, and put up a steel post and raise another short steel or paralam beam where the wall is.
This involves building temporary stud walls on either side of the existing wall to support the load while you're working. You'll need to find a contractor who has done this type of work before. | Everything Chris said is true...but Iβm not sure if the note box gives us information about mentioned wall or different one.It't hard to tell from the drawing, at least for me...I don't know the standards in your country, and if house is built according to regulations, but bearing walls should be either vertical or horizontal (I mean one or another direction on the drawing) so maybe you can compare these two "types" and see which is bearing.Also,keep in mind that maybe it is not the wall which is bearing weight, but only his upper part, beam and the rest of the wall isn't load bearing. I would like to provide you with more helpful information but just from the drawing I can't. |
3,047,195 | How to show that $\langle \textbf {a,b} \rangle = \|\textbf {a}\| \|\textbf {b}\| \cos \theta$ where $\langle \cdot , \cdot \rangle$ denotes the usual real inner product or dot product on $\Bbb R^2$, $\| \cdot \|$ is the usual or Euclidean norm on $\Bbb R^2$ and $\theta$ is the angle between the vectors $\textbf {a}$ and $\textbf {b}$ in $\Bbb R^2$.
I have proved this result when $\theta$ is acute. How do I prove this result for obtuse or reflex angles? I didn't find any proof in the online sources which prove the above fact for obtuse or reflex angles. Would somebody help me in this regard?
Thank you very much.
**EDIT** $:$
Assume that $\theta$ is acute. WLOG by proper choice of coordinate axes we may assume that both $\textbf {a}$ and $\textbf {b}$ lie on the first quadrant. Let $\textbf {a} = (x,y)$ and $\textbf {b} = (z,w)$. Let $\textbf {a}$ and $\textbf {b}$ make angles $\theta\_1$ and $\theta\_2$ respectively with the positive direction of $x$-axis and also assume that $\theta\_1 > \theta\_2$. Then $\theta = \theta\_1 - \theta\_2$. Also $\tan \theta\_1 = \frac {y} {x}$ and $\tan {\theta\_2} = \frac {w} {z}$. Then
$$\tan \theta = \frac {\tan \theta\_1 - \tan \theta\_2} {1 + \tan \theta\_1 \tan \theta\_2}.$$
Putting the values of $\tan \theta\_1$ and $\tan \theta\_2$ and then simplifying we get
$$\tan \theta = \frac {yz-xw} {xz+yw}.$$ Since $\theta$ is acute so
$$\cos \theta = \frac {1} {\sqrt {1+{\tan}^2 \theta}} = \frac {xz+yw} {\sqrt {x^2+y^2} \sqrt {z^2+w^2}} = \frac {\langle \textbf {a , b} \rangle} {\|\textbf {a} \| \| \textbf {b} \|}.$$ | 2018/12/20 | [
"https://math.stackexchange.com/questions/3047195",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/543867/"
] | If you have a valid proof for the case when the order of $a$ is two, $o(a)=2$, then I'm pretty sure that you're done with the question β because the order of $a$ doesn't really matter here. The order of $z=xax^{-1}$ is equal to the order of $a$; so, just as you said, by uniqueness it implies that $xax^{-1}=a$, and you're done. | What you want to show is that $\forall x \in G, x.a.x^{-1} = a$. The thing you miss is probably that $(x.a.x^{-1})^k = x.a^k.x^{-1}$ for any integer $k$. If you write the product down, you will see that all the intermediate $x^{-1}.x$ terms cancel each other $(x.a.x^{-1})^n = (x.a.x^{-1})(x.a.x^{-1})\ldots(x.a.x^{-1})$
For a more rigorous proof you can do it by induction.
From here you have $(x.a.x^{-1})^n = x.a^n.x^{-1} = x.x^{-1} =1$. This means that $x.a.x^{-1}$ has an order $m$ that divises $n$.
Now, we just need to show that $m=n$. For that, one can see that $1 = (x.a.x^{-1})^m = x.a^m.x^{-1}$ which implies $a^m=1$. By definition of the order of an element we can deduce $m=n$ since the order is the smallest positive integer that verifies this property.
We proved that $x.a.x^{-1}$ is of order $n$ which implies, by uniqueness of an element of such order, that $x.a.x^{-1} = a$ which is what we wanted. |
27,022,915 | I have the following code that draws an image to a canvas and gets the pixel data:
```
var canvas=$('#canvas'),
ctx=canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
var data=ctx.getImageData(0, 0, canvas.width, canvas.height);
```
This pulls `RGBA` values which I need to store into an array that I'll be able to access using X/Y coordinates. The image drawn to the canvas is a black/white image - so it would check whether a pixel is black or white at `X`,`Y` - like:
```
imageArray[x][y]
```
I can't figure out how to loop the pixel data and save it to a `2d` array so I'd be able to call it by coordinates. | 2014/11/19 | [
"https://Stackoverflow.com/questions/27022915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1020936/"
] | What you can do is loop through the entire image data array and extract the values you need:
Each pixel takes up four spaces in the array for its rgba values, so we can loop through the total number of pixels and grab four values from the array each time.
You can get the y value (or row the pixel is on) by dividing the current index by the height and the x (or column pixel is on) by using the y value to subtract the rows from the current index, leaving the x.
```
var pixels = imageData.data;
var w = imageData.width;
var h = imageData.height;
var l = w * h;
for (var i = 0; i < l; i++) {
// get color of pixel
var r = pixels[i*4]; // Red
var g = pixels[i*4+1]; // Green
var b = pixels[i*4+2]; // Blue
var a = pixels[i*4+3]; // Alpha
// get the position of pixel
var y = parseInt(i / w, 10);
var x = i - y * w;
}
``` | `ctx.getImageData` returns an object that contains a `.data` property.
That data property is an array that already contains all the pixel colors that you're looking for.
```
// get the imageData object
var imageData=ctx.getImageData(0, 0, canvas.width, canvas.height);
// get the pixel color data array
var data=imageData.data;
```
The `data` array is a long array containing the red, green, blue & alpha (opacity) values for each pixel on the canvas. The `data` array is shaped like this:
```
// top left pixel [0,0]
data[0]: Red value for pixel [0,0],
data[1]: Green value for pixel [0,0],
data[2]: Blue value for pixel [0,0],
data[3]: Alpha value for pixel [0,0],
// next pixel rightward [1,0]
data[4]: Red value for pixel [1,0],
data[5]: Green value for pixel [1,0],
data[6]: Blue value for pixel [1,0],
data[7]: Alpha value for pixel [1,0],
// and so on for each pixel on the canvas
...
```
You can get position of any [x,y] pixel within `data` like this:
```
// the data[] array position for pixel [x,y]
var n = y * canvas.width + x;
```
And then you can fetch that pixel's red, green, blue & alpha values like this:
```
var red=data[n];
var green=data[n+1];
var blue=data[n+2];
var alpha=data[n+3];
``` |
4,938,397 | I would like to dynamically add properties to a ExpandoObject at runtime. So for example to add a string property call NewProp I would like to write something like
```
var x = new ExpandoObject();
x.AddProperty("NewProp", System.String);
```
Is this easily possible? | 2011/02/08 | [
"https://Stackoverflow.com/questions/4938397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27294/"
] | Here is a sample helper class which converts an Object and returns an Expando with all public properties of the given object.
```
public static class dynamicHelper
{
public static ExpandoObject convertToExpando(object obj)
{
//Get Properties Using Reflections
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = obj.GetType().GetProperties(flags);
//Add Them to a new Expando
ExpandoObject expando = new ExpandoObject();
foreach (PropertyInfo property in properties)
{
AddProperty(expando, property.Name, property.GetValue(obj));
}
return expando;
}
public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
{
//Take use of the IDictionary implementation
var expandoDict = expando as IDictionary<String, object>;
if (expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
else
expandoDict.Add(propertyName, propertyValue);
}
}
```
Usage:
```
//Create Dynamic Object
dynamic expandoObj= dynamicHelper.convertToExpando(myObject);
//Add Custom Properties
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");
``` | This is the best solution I've found. But be careful with that. Use exception handling because it might not work on all of the cases
```
public static dynamic ToDynamic(this object obj)
{
return JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(obj));
}
``` |
31,096 | I'm trying to find out how much memory my own .Net server process is using (for monitoring and logging purposes).
I'm using:
```
Process.GetCurrentProcess().PrivateMemorySize64
```
However, the Process object has several different properties that let me read the memory space used:
Paged, NonPaged, PagedSystem, NonPagedSystem, Private, Virtual, WorkingSet
and then the "peaks": which i'm guessing just store the maximum values these last ones ever took.
Reading through the MSDN definition of each property hasn't proved too helpful for me. I have to admit my knowledge regarding how memory is managed (as far as paging and virtual goes) is very limited.
So my question is obviously "which one should I use?", and I know the answer is "it depends".
This process will basically hold a bunch of lists in memory of things that are going on, while other processes communicate with it and query it for stuff. I'm expecting the server where this will run on to require lots of RAM, and so i'm querying this data over time to be able to estimate RAM requirements when compared to the sizes of the lists it keeps inside.
So... Which one should I use and why? | 2008/08/27 | [
"https://Stackoverflow.com/questions/31096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] | Is this a fair description? I'd like to share this with my team so please let me know if it is incorrect (or incomplete):
There are several ways in C# to ask how much memory my process is using.
* Allocated memory can be managed (by the CLR) or unmanaged.
* Allocated memory can be virtual (stored on disk) or loaded (into RAM pages)
* Allocated memory can be private (used only by the process) or shared (e.g. belonging to a DLL that other processes are referencing).
Given the above, here are some ways to measure memory usage in C#:
1) Process.VirtualMemorySize64(): returns all the memory used by a process - managed or unmanaged, virtual or loaded, private or shared.
2) Process.PrivateMemorySize64(): returns all the private memory used by a process - managed or unmanaged, virtual or loaded.
3) Process.WorkingSet64(): returns all the private, loaded memory used by a process - managed or unmanaged
4) GC.GetTotalMemory(): returns the amount of managed memory being watched by the garbage collector. | Working set isn't a good property to use. From what I gather, it includes everything the process can touch, even libraries shared by several processes, so you're seeing double-counted bytes in that counter. Private memory is a much better counter to look at. |
182,663 | I wrote the `TOTAL_FREQUENCY` values manually. But I want to automatically write this values with a script. Namely, I want to write sum of column 3 to all of the the column 5 rows. How can I do it with a script?
[![enter image description here](https://i.stack.imgur.com/l0i3J.jpg)](https://i.stack.imgur.com/l0i3J.jpg) | 2016/02/29 | [
"https://gis.stackexchange.com/questions/182663",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/68219/"
] | The following Python script (created by Terry Giles and mentioned in this [ESRI forum](http://forums.esri.com/Thread.asp?c=93&f=1728&t=241385)) allows you to sum the values of a field and paste the sum in another field. The script is designed to work in the **Toolbox** so that when you run it, you can enter the *Layer name, Field name* and *output*:
```
#args to pass in:
##1 = input FC or table
##2 = field to sum up
##3 = field to write sum into
import arcpy, sys
intable = sys.argv[1]
field = sys.argv[2]
# Create search cursor
rows = arcpy.SearchCursor(intable)
row = rows.Next()
x = 0.0
# Enter while loop for each feature/row
while row:
x += row.getvalue(field)
print x
row = rows.next()
#note value can be rounded depending on field type
gp.calculatefield(intable,sys.argv[3],float(x),"PYTHON")
```
---
*Disclaimer: I am not an ArcGIS user therefore cannot confirm if this still works as this script was first posted way back in 2007.* | It seems OP seeking field calculator expression. Here is one:
```
def getTotal(name,field):
mxd = arcpy.mapping.MapDocument("CURRENT")
lr=arcpy.mapping.ListTableViews(mxd,name)[0]
tbl=[row[0] for row in arcpy.da.TableToNumPyArray(lr,field)]
return sum(tbl)
```
=======================================
```
getTotal( "frekans","frequency")
``` |
378,484 | I need to add a description on my Account every time an Opportunity's stage is changed.
I tried the following and getting NULL pointer exception.
```java
public class opportunityTriggerHandler {
public static void oppStgChangeDetails(List<Opportunity> oppList, map<Id, Opportunity> oldmap, boolean isInsert, boolean isUpdate){
List<Account> accsToUpdate = New List<Account>();
for(Opportunity opp:oppList){
if(isInsert || (isUpdate && opp.stageName <> oldmap.get(opp.Id).stageName)){
opp.Account.Description = opp.Account.Description + 'Prev Stage: ' + oldmap.get(opp.Id).stageName
+ 'New Stage: ' + opp.StageName;
accsToUpdate.add(opp.Account);
}
}
update accsToUpdate;
}
}
``` | 2022/06/15 | [
"https://salesforce.stackexchange.com/questions/378484",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/104956/"
] | Let's rewrite this to be cleaner and use `getInstance()` properly
```
public class UpdateOpportunity{
public static void checkOpportunityStage(List<Opportunity> opportunityList){
List<Task> taskList = new List<Task>();
Task_Settings__mdt TaskDomain = Task_Settings__mdt
.getInstance('Manage_Product_Service'); // Must be developerName of MDT row
for(Opportunity opp:opportunityList){ // no need to check for empty
if(opp.StageName == 'Closed Won'){
taskList.add(new Task(
Subject = taskDomain.Subject__c, // field in MDT w/ subjectName
WhatId = opp.Id));
}
}
insert taskList; // no need to check for empty, won't burn DML
}
}
```
**Key points**
* `getInstance(val)` returns a single row based on its [DeveloperName](https://developer.salesforce.com/docs/atlas.en-us.232.0.apexref.meta/apexref/apex_methods_system_custom_metadata_types.htm#apex_System_CustomMetadataType_getinstance_devName) column
* If you have dynamic subjects based on some condition in the `Opportunity`, you'll need to fetch all relevant `MDT` rows (SOQL or multiple `getInstance()` and assign to `Task.Subject` accordingly
* Avoid testing for empty lists if the ensuing code either just falls through (a for loop) or is DML of a collection (DML of empty lists does not count against limits). This makes methods more compact.
* Learn to use the new Sobject method with field value setting style. Makes code easier to read | You need to put this statement to set the subject
```
task1.Subject = TaskDomain.FieldName__c;
``` |
21,646,179 | When I tried
```
$ sudo apt-get install python-matplotlib
```
I got the following error:
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package python-matplotlib
```
How to `install` it? | 2014/02/08 | [
"https://Stackoverflow.com/questions/21646179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3151082/"
] | One "cleaner" way to install matplotlib is to go through pip:
```
sudo apt-get install python-pip
sudo pip install matplotlib
```
It will also ensure that you'll get the most up to date stable version and will be easier to maintain when an upgrade is pushed to pypi.
If the build process complains about missing headers files just install the missing lib with:
```
sudo apt-get install libfreetype6-dev libpng-dev
```
Warning: it can take a lot of time to fully build as one dependency of matplotlib is numpy which is quite a project in terms of c extension. | type the following commands in terminal:
```
$ wget https://github.com/matplotlib/matplotlib/zipball/master
$ unzip master
$ cd matplotlib-matplotlib-bb3ea55
$ sudo python2.7 setup.py build
$ sudo python2.7 setup.py install
```
If the `unzip` command doesn't work properly, extract the files manually. `$ cd matplotlib-matplotlib-bb3ea55` should be the proper directory (however the last seven characters may be different). |
154,427 | Boot now freezes the system at the "Ubuntu purple screen" with the 5 dots under it. I cannot even CTRL-ALT-F1 to get to an alternate console. Have to push reset button on computer to reboot.
After the 12.04 update crash, the system would boot, but I had no icons and no launch bar and errors about missing dependencies. CTRL-ALT-F1 and ran apt-get -f install and it appeared to get the missing packages. I followed with a apt-get update; apt-get upgrade. It appeared to install all of the remaining 12.04 update packages. Rebooted to same blank screen - no icons, but got a compiz error. In console I tried "unity --reset" rebooted ... Nothing ... It's dead in the water. Tried to boot into Recovery Mode - black screen - I cannot even CTRL-ALT-Del - have to push reboot button.
Fortunately, I have Mint on another partition and I can access the broken 12.04 partition.
Ideas? I can back up all of my folders using Mint, but I would *hate* to have to do a new install. | 2012/06/22 | [
"https://askubuntu.com/questions/154427",
"https://askubuntu.com",
"https://askubuntu.com/users/72433/"
] | You can boot into recovery mode. Choosing From Boot Menu. From there you can backup your data or try to update again. | I had this same exact problem. Just burn 12.4 on a disk, run in Live DVD mode (try Ubuntu), backup your files, and then boot the DVD again and try the option that will say "Upgrade 12.4 into 12.4". If it doesn't work, then just do a clean installation. |
2,543,313 | ```
market_l="${echo $1 | awk '{print tolower($0)}'}"
echo $market_l
```
when i execute this its giving me an error below:
```
./test: market_l="${echo $1 | awk '{print tolower($0)}'}": The specified substitution is not valid for this command.
``` | 2010/03/30 | [
"https://Stackoverflow.com/questions/2543313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134713/"
] | Did you mean to use the `$()` operator instead of `${}`? | you should use `$()` to assign output to a variable. not `${}`
```
market_l="$(echo $1 | awk '{print tolower($0)}')"
```
or you can do it with ksh
```
#!/bin/ksh
typeset -l market_l
market_l="$1"
echo $market_l
```
Other ways to change case besides `awk`, fyi
```
$ echo "$1"|tr [A-Z] [a-z]
$ echo "$1"|sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'
``` |
21,775,709 | I want to set a **tinyint** field as autoincrement, but table constructor dont let me do it. But he lets to **int** and **bigint** types. Whats the problem?
Here is the screenshot: <http://gyazo.com/ce8d345ee94bf26e833fe16133b5eee5.png>
The first row "ΠΠ΄Π΅Π½ΡΠΈΡΠΈΠΊΠ°ΡΠΈΡ" is an **Identity** field in English. | 2014/02/14 | [
"https://Stackoverflow.com/questions/21775709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2932802/"
] | SQL Server Compact only support int and bigint with IDENTITY | First of all, why do you use TinyInt? TinyInt has a range from -128 to +127, so is is not very well suited for auto\_increment columns. |
32,633,799 | I want to execute a code block only on devices running with an OS older than `iOS8`. I can't do:
```
if #available(iOS 8.0, *) == false {
doFoo()
}
```
The solution I'm using for now is:
```
if #available(iOS 8.0, *) { } else {
doFoo()
}
```
, but it feels clunky. Is there another way to negate the `#available` statement elegantly with Swift ? | 2015/09/17 | [
"https://Stackoverflow.com/questions/32633799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1173513/"
] | I use a `guard` for this:
```
guard #available(iOS 8.0, *) else {
// Code for earlier OS
}
```
There's slight potential for awkwardness since `guard` is required to exit the scope, of course. But that's easy to sidestep by putting the whole thing into its own function or method:
```
func makeABox()
{
let boxSize = .large
self.fixupOnPreOS8()
self.drawBox(sized: boxSize)
}
func fixupOnPreOS8()
{
guard #available(iOS 8, *) else {
// Fix up
return
}
}
```
which is really easy to remove when you drop support for the earlier system. | **Swift 5.6, Xcode 13.3 Beta**
```
if #unavailable(iOS 13, *) {
// below iOS 13
} else {
// iOS 13 and above
}
```
**Swift 5.5 and earlier**
a simple way to check is by using `#available` with a `guard` statement
```
guard #available(iOS 13, *) else {
// code for earlier versions than iOS 13
return
}
```
another way is to use if/else
```
if #available(iOS 13, *) {} else {
// code for earlier versions than iOS 13
}
``` |
43,208,196 | I have some radio button which I put in radio button group.
So, how can I get the radio button index value or selected index value when I going to click on a particular radio button.
Here is my code
```
bg=new ButtonGroup();
for(i=0;i<8;i++){
rbt =new RadioButton();
rbt.setName("rbt"+i);
radioList.add(rbt);
}
for(int i=0;i<radioList.size();i++){
radioList.get(i).addPointerPressedListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
for(int i=0;i<radioList.size();i++){
Log.p("================"+bg.getSelectedIndex);
}
}
});
}
```
In the above code I am getting the previously selected value not the current. value
Thanks in Advance | 2017/04/04 | [
"https://Stackoverflow.com/questions/43208196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7136032/"
] | see snippet below or **[jsfiddle](https://jsfiddle.net/b74a3kbs/5/)**
it will work regardless how many cols you have or rows
first ( on big screen ) all rows have `margin-bottom` except the last one
then on medium screen , the rows won't have any margin and the cols will all have margin-bottom except the **last col** from the **last row**
```css
.row {
margin-bottom:30px;
}
.row:last-child{
margin-bottom:0;
}
.row [class*="col-"] {
border:1px solid red;
}
@media only screen and (max-width: 768px) {
.row {
margin:0
}
.row [class*="col-"] {
margin-bottom:30px;
}
.row:last-child [class*="col-"]:last-child{
margin-bottom:0;
}
}
```
```html
<body>
<h1 class="display-3">
hey
</h1>
<div class="container">
<div class="row">
<div class="col-md-4 col-lg-4">
col 1
</div>
<div class="col-md-4 col-lg-4">
col 2
</div>
<div class="col-md-4 col-lg-4">
col 3
</div>
</div>
<div class="row">
<div class="col-md-4 col-lg-4">
col 4
</div>
<div class="col-md-4 col-lg-4">
col 5
</div>
<div class="col-md-4 col-lg-4">
col 6
</div>
</div>
</div>
</body>
``` | Use Gutters in row: <https://getbootstrap.com/docs/5.0/layout/gutters/>
```
<div class="row gy-2">
...
</div>
``` |
21,304,282 | I'm writing a script that takes an output file from another platform (that sadly doesn't produce CSV output, instead it's around 7 lines per record), grabbing the lines that have the values I'm interested in (using `select-string`) and then scanning the `MatchInfo` array, extracting the exact text and building an array as I go, to export to CSV when finished.
My problem is that the original file has around 94000 lines of text, and the matchinfo object still has around 23500 records in it, so it takes a while, especially building the array, so I thought I'd throw in a `Write-Progress` but the overhead in doing so is quite horrific, it increases the elapsed time x8 vs not having the progress bar.
Here's an example entry from the original file:
```
CREATE TRANCODE MPF OF TXOLID
AGENDA = T4XCLCSHINAG
,ANY_SC_LIST = NONE ,EVERY_SC_LIST = NONE
,SECURITY_CATEGORY = NONE ,FUNCTION = 14
,TRANCODE_VALUE = "MPF"
,TRANCODE_FUNCTION_MNEMONIC = NONE
,INSTALLATION_DATA = NONE
;
```
Now, for each of these, I only care about the values of `AGENDA` and `TRANCODE_VALUE`, so having read the file in using `Get-Content`, I then use `Select-String` as the most efficient way I know to filter out the rest of the lines in the file:
```
rv Start,Filtered,count,CSV
Write-Host "Reading Mainframe Extract File"
$Start = gc K:\TRANCODES.txt
Write-Host ("Read Complete : " + $Start.Count + " records found")
Write-Host "Filtering records for AGENDA/TRANCODE information"
$Filtered = $Start|Select-String -Pattern "AGENDA","TRANCODE_VALUE"
Write-Host ([String]($Filtered.Count/2) + " AGENDA/TRANCODE pairs found")
```
This leaves me with an object of type `Microsoft.PowerShell.Commands.MatchInfo` with contents like:
```
AGENDA = T4XCLCSHINAG
,TRANCODE_VALUE = "MPF"
AGENDA = T4XCLCSHINAG
,TRANCODE_VALUE = "MP"
```
Now that Select-String only took around 9 seconds, so no real need for a progress bar there.
However, the next step, grabbing the actual values (after the `=`) and putting in an array takes over 30 seconds, so I figured a `Write-Progress` is helpful to the user and at least shows that something is actually happening, but, the addition of the progress bar seriously extends the elapsed time, see the following output from `Measure-Command`:
```
Measure-Command{$Filtered|foreach {If ($_.ToString() -Match 'AGENDA'){$obj = $null;
$obj = New-Object System.Object;
$obj | Add-Member -type NoteProperty -name AGENDA -Value $_.ToString().SubString(27)}
If ($_.ToString() -Match 'TRANCODE_VALUE'){$obj | Add-Member -type NoteProperty -name TRANCODE -Value ($_.ToString().SubString(28)).Replace('"','');
$CSV += $obj;
$obj = $null}
<#$count++
Write-Progress `
-Activity "Building table of values from filter results" `
-Status ("Processed " + $count + " of " + $Filtered.Count + " records") `
-Id 1 `
-PercentComplete ([int]($count/$Filtered.Count *100))#>
}}
TotalSeconds : 32.7902523
```
So that's 717.2308630680085 records/sec
```
Measure-Command{$Filtered|foreach {If ($_.ToString() -Match 'AGENDA'){$obj = $null;
$obj = New-Object System.Object;
$obj | Add-Member -type NoteProperty -name AGENDA -Value $_.ToString().SubString(27)}
If ($_.ToString() -Match 'TRANCODE_VALUE'){$obj | Add-Member -type NoteProperty -name TRANCODE -Value ($_.ToString().SubString(28)).Replace('"','');
$CSV += $obj;
$obj = $null}
$count++
Write-Progress `
-Activity "Building table of values from filter results" `
-Status ("Processed " + $count + " of " + $Filtered.Count + " records") `
-Id 1 `
-PercentComplete ([int]($count/$Filtered.Count *100))
}}
TotalSeconds : 261.3469632
```
Now only a paltry 89.98660799693897 records/sec
Any ideas how to improve the efficiency?
Here's the full script as-is:
```
rv Start,Filtered,count,CSV
Write-Host "Reading Mainframe Extract File"
$Start = gc K:\TRANCODES.txt
Write-Host ("Read Complete : " + $Start.Count + " records found")
Write-Host "Filtering records for AGENDA/TRANCODE information"
$Filtered = $Start|Select-String -Pattern "AGENDA","TRANCODE_VALUE"
Write-Host ([String]($Filtered.Count/2) + " AGENDA/TRANCODE pairs found")
Write-Host "Building table from the filter results"
[int]$count = 0
$CSV = @()
$Filtered|foreach {If ($_.ToString() -Match 'AGENDA'){$obj = $null;
$obj = New-Object System.Object;
$obj | Add-Member -type NoteProperty -name AGENDA -Value $_.ToString().SubString(27)}
If ($_.ToString() -Match 'TRANCODE_VALUE'){$obj | Add-Member -type NoteProperty -name TRANCODE -Value ($_.ToString().SubString(28)).Replace('"','');
$CSV += $obj;
$obj = $null}
$count++
Write-Progress `
-Activity "Building table of values from filter results" `
-Status ("Processed " + $count + " of " + $Filtered.Count + " records") `
-Id 1 `
-PercentComplete ([int]($count/$Filtered.Count *100))
}
Write-Progress `
-Activity "Building table of values from filter results" `
-Status ("Table built : " + $CSV.Count + " rows created") `
-Id 1 `
-Completed
Write-Host ("Table built : " + $CSV.Count + " rows created")
Write-Host "Sorting and Exporting table to CSV file"
$CSV|Select TRANCODE,AGENDA|Sort TRANCODE |Export-CSV -notype K:\TRANCODES.CSV
```
Here's output from script with the `write-progress` commented out:
```
Reading Mainframe Extract File
Read Complete : 94082 records found
Filtering records for AGENDA/TRANCODE information
11759 AGENDA/TRANCODE pairs found
Building table from the filter results
Table built : 11759 rows created
Sorting and Exporting table to CSV file
TotalSeconds : 75.2279182
```
**EDIT:**
I've adopted a modified version of the answer from @RomanKuzmin, so the appropriate code section now looks like:
```
Write-Host "Building table from the filter results"
[int]$count = 0
$CSV = @()
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$Filtered|foreach {If ($_.ToString() -Match 'AGENDA'){$obj = $null;
$obj = New-Object System.Object;
$obj | Add-Member -type NoteProperty -name AGENDA -Value $_.ToString().SubString(27)}
If ($_.ToString() -Match 'TRANCODE_VALUE'){$obj | Add-Member -type NoteProperty -name TRANCODE -Value ($_.ToString().SubString(28)).Replace('"','');
$CSV += $obj;
$obj = $null}
$count++
If ($sw.Elapsed.TotalMilliseconds -ge 500) {
Write-Progress `
-Activity "Building table of values from filter results" `
-Status ("Processed " + $count + " of " + $Filtered.Count + " records") `
-Id 1 `
-PercentComplete ([int]($count/$Filtered.Count *100));
$sw.Reset();
$sw.Start()}
}
Write-Progress `
-Activity "Building table of values from filter results" `
-Status ("Table built : " + $CSV.Count + " rows created") `
-Id 1 `
-Completed
```
And running the entire script through `Measure-Command` gives elapsed time of 75.2279182 seconds with no `write-progress` and with the modified `write-progress` using @RomanKuzmin suggestion, 76.525382 seconds - not bad at all!! :-) | 2014/01/23 | [
"https://Stackoverflow.com/questions/21304282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1868534/"
] | I hope this helps someone else.
I spent a day on a similar problem: Progress bar was very very slow.
My problem however was rooted in the fact that I had made the screenbuffer for the powershell console extremely wide (9999 instead of the default 120).
This caused Write-Progress to be slowed to the extreme every time it had to update the gui progress bar. | I completely removed my old answer for sake of efficiency, Although modulus checks are efficient enough, they do take time, especially if doing a modulus 20 against say 5 million - this adds a decent amount of overhead.
For loops, all I do is something simple as follows
---which is similar to the stop watch method, is reset your progress check with each write-progress:
```
$totalDone=0
$finalCount = $objects.count
$progressUpdate = [math]::floor($finalCount / 100)
$progressCheck = $progressUpdate+1
foreach ($object in $objects) {
<<do something with $object>>
$totalDone+=1
If ($progressCheck -gt $progressUpdate){
write-progress -activity "$totalDone out of $finalCount completed" -PercentComplete $(($totalDone / $finalCount) * 100)
$progressCheck = 0
}
$progressCheck += 1
}
```
The reason I set `$progressCheck` to `$progressUpdate+1` is because it will run the first time through the loop.
This method will run a progress update every 1% of completion. If you want more or less, just update the division from 100 to your prefered number. 200 would mean an update every 0.5% and 50 would mean every 2% |
169,219 | In my medieval-fantasy world, thereβs a secret civilization with modern technology.
A βpowerfulβ dragon accidentally came across them and they became good allies. The dragon was introduced to the concept of aircraft and it wasnβt long until she decided to ride one.
The dragon shrunk into a more humanoid form, with the appropriate limbs and digits.
The dragon loved to fly in a fighter plane, so much so that she refuses to fly under her own power as much as before.
Why would this be so? | 2020/02/21 | [
"https://worldbuilding.stackexchange.com/questions/169219",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/72381/"
] | Convenience and speed.
Unless your dragon has some magical powers helping it along, there is no way she ever could achieve the same speeds as a fighter plane.
Also, who doesn't prefer driving a car over walking? If it can be easier, then why not use the possibility?
Now how she will afford the fuel is another question. We all know how stingy dragons can be about parting with their hoard. | I'd say that the best reason is that she can't fly properly anymore for some reason, and flying an airplane is the closest she can get. Maybe she has something like a torn wing that didn't heal properly, so she can't fly very well naturally anymore. If she were injured helping someone from the secret civilization, this could be why she was given an airplane in the first place. |
3,295,783 | If you are not developing for an Apple platform, are there reasons to choose Objective-C? I know of GNUstep (which I do not find visually pleasing), but what else is there?
If you want to develop for multiple platforms, including OS X or iOS but also Linux or Windows, when might Objective-C be a good choice? | 2010/07/21 | [
"https://Stackoverflow.com/questions/3295783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/397408/"
] | Outside Apple, The only major Objective-C environment is GNUSTEP/Windowmaker.
It's a shame, since Objective-C is a much nicer and saner language than C++. | There is [The Cocotron](http://www.cocotron.org/)
[Clozure Common Lisp (CCL)](http://openmcl.clozure.com/) on 32-bit Windows platforms now includes experimental support for the Cocoa frameworks using the Cocotron open source project. |
50,961,544 | While i am working with open vino to convert .pb file into inference format using model optimizer, i am continuously facing "graph contains a cycle error".
And we have used TensorFlow Object Detection Models and SSD Inception V2 to generate .pb file.
```
[ ERROR ] -------------------------------------------------
[ ERROR ] ----------------- INTERNAL ERROR ----------------
[ ERROR ] Unexpected exception happened.
[ ERROR ] Please contact Model Optimizer developers and forward the following information:
[ ERROR ] Graph contains a cycle.
[ ERROR ] Traceback (most recent call last):
File "/opt/intel/computer_vision_sdk_2018.1.265/deployment_tools/model_optimizer/mo/main.py", line 222, in main
return driver(argv)
File "/opt/intel/computer_vision_sdk_2018.1.265/deployment_tools/model_optimizer/mo/main.py", line 190, in driver
mean_scale_values=mean_scale)
File "/opt/intel/computer_vision_sdk_2018.1.265/deployment_tools/model_optimizer/mo/pipeline/tf.py", line 141, in tf2nx
partial_infer(graph)
File "/opt/intel/computer_vision_sdk_2018.1.265/deployment_tools/model_optimizer/mo/middle/passes/infer.py", line 55, in partial_infer
nodes = nx.topological_sort(graph)
File "/opt/intel/computer_vision_sdk_2018.1.265/deployment_tools/model_optimizer/venv/lib64/python3.5/site-packages/networkx/algorithms/dag.py", line 157, in topological_sort
raise nx.NetworkXUnfeasible("Graph contains a cycle.")
networkx.exception.NetworkXUnfeasible: Graph contains a cycle.
[ ERROR ] ---------------- END OF BUG REPORT --------------
[ ERROR ] -------------------------------------------------
``` | 2018/06/21 | [
"https://Stackoverflow.com/questions/50961544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9428127/"
] | **@+id/name** When you create a `new id`
**"@id/"** When you `link to existing id`
**Use-case example 1:**
Let's say you created your own resource in XML:
```
<resources>
<item name="plusIcon" type="id"/>
</resources>
```
Now you can use this resource at multiple places without creating a new resource using **@+id**. Say `layout_one.xml`:
```
<TextView android:id="@id/plusIcon"/>
```
Same resource in `layout_two.xml`:
```
<TextView android:id="@id/plusIcon"/>
```
**Use-case example 2:**
There are a number of other ID resources that are offered by the Android framework. If you want to referencing an Android resource ID in that case you can use @android you don't need to create your own new resource ID | Defining the constraints within a **RelativeLayout** might be a good example.
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Top"/>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Bottom"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/textView3"
android:layout_below="@id/textView1"
android:text="Center"/>
</RelativeLayout>
```
On the last TextView **android:layout\_above** and **android:layout\_below** don't require the plus symbol because textView1 and textView2 are already defined IDs. |
13,500,741 | Good evening! I have a web app with login-logout, where you can buy or sell some products. My queries are stored in a java class, called `DBManager`, which has just static methods that are called from servlets (I can't use JSP because in this project we can't use them, the professor gives us this constraint).
So here's the problem: I used to manage connection with `ServletContextListener`. In `contextInitialized` I set up connection, and in `contextDestroyed` I shutdown it. The attribute "Connection" is stored using `ServletContext.setAttribute(Connection)`.
How can i get this parameter through the java class (not servlet) `DBManager`? I must get the object using `getServletContext()` inside a servlet and than passing it as an attribute, or there's a shortcut to avoid that? | 2012/11/21 | [
"https://Stackoverflow.com/questions/13500741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1392008/"
] | Instead of arbitrary getting the connection, you could change your class to receive a connection. That allows you to pass any instance of connection (what happens if you need to get data from another database?).
Also, imagine that the code will be ported to desktop. With this approach you can reuse your [DAO](http://en.wikipedia.org/wiki/Data_access_object) without any changes.
```
class DBManager {
private Connection connection;
public DBManager(Connection connection) {
this.connection = connection;
}
//methods that will use the connection
}
``` | In your `HttpServlet` `doPost` or `doGet` methods you can call `getServletContext()`.
```
ServletContext sc = getServletContext();
DataSource ds = (DataSource) sc.getAttribute("ds");
Connection conn = ds.getConnection();
```
>
> A servlet can bind an object attribute into the context by name. Any attribute bound into a context is available to any other servlet that is part of the same Web application.
>
>
> Context attributes are LOCAL to the JVM in which they were created. This prevents ServletContext attributes from being a shared memory store in a distributed container. When information needs to be shared between servlets running in a distributed environment, the information should be placed into a session, stored in a database, or set in an Enterprise JavaBeans component.
>
>
> |
311,206 | >
> Let $f$ be a fixed nonzero linear functional on an $n$-dimensional vector space $V$ and
> $H=\{\alpha \in V:f(\alpha)=0\}$. Then $H$ is a subspace of $V$ and its dimension is $n-1$.
>
>
>
I have shown that $H$ is a subspace of $V$. Do you have an idea how to show that its dimension is $n-1$? Thanks a lot. | 2013/02/22 | [
"https://math.stackexchange.com/questions/311206",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/52337/"
] | $\dim (\ker(f))+ \dim(\operatorname{Im}(f)) = \dim V=n$ your $H=\ker(f)$ and $\dim(\operatorname{Im}(f))=1$ | Here a complete proof. Suppose that $f:V\rightarrow F$ nonzero linear functional on an n-dimensional vector space $V$ over a field $F$.
We know that $f(V)=\operatorname{Im}(f)$ is a subspace of $F$ so $0\leq\dim\, \operatorname{Im}(f)\leq \dim F =1$. But $\dim\, \operatorname{Im}(f)\neq 0$ because $f$ is a nonzero linear functional so $\dim\, \operatorname{Im}(f)=1$ and then $Im(f)=F$ i.e. $f$ is surjective. Now by rankβnullity theorem we have as jim did:
$$\dim (\ker(f))+ \dim(\operatorname{Im}(f)) = \dim V=n$$ with $H=\ker(f)$ so $\dim H=n-1$. |
283 | ```
void removeForbiddenChar(string* s)
{
string::iterator it;
for (it = s->begin() ; it < s->end() ; ++it){
switch(*it){
case '/':case '\\':case ':':case '?':case '"':case '<':case '>':case '|':
*it = ' ';
}
}
}
```
I used this function to remove a string that has any of the following character: \, /, :, ?, ", <, >, |. This is for a file's name. This program runs fine. It simply change a character of the string to a blank when the respective character is the forbidden character. However, I have a feeling against this use of switch statement. I simply exploit the case syntax here, but this, somehow nags me. I just don't like it. Anybody else got a better suggestion of a better implementation in this case? | 2011/01/27 | [
"https://codereview.stackexchange.com/questions/283",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/530/"
] | One thing that I would change about your function (in addition to Jonathan's recommendation of using a string to store the forbidden characters), is the argument type of `removeForbiddenChar` to `string&` instead of `string*`. It is generally considered good practice in C++ to use references over pointers where possible (see for example [this entry](http://www.parashift.com/c++-faq-lite/references.html#faq-8.6) in the C++ faq-lite).
One further, minor cosmetic change I'd recommend is renaming the function to `removeForbiddenChars` (plural) as that is more descriptive of what it does. | Solution with no conditional branching.
Swapping space for time optimization.
Simplified algorithm:
```
void removeForbiddenChar(string* s)
{
for (string::iterator it = s->begin() ; it < s->end() ; ++it)
{
// replace element with their counterpart in the map
// This replaces forbidden characters with space.
(*it) = charMap[*it];
}
}
```
Or the C++0x version:
```
void removeForbiddenChar(std::string* s)
{
std::transform(s->begin(), s->end(), [](char c) => {return charMap[c];});
}
```
Just need the data:
```
char charMap[] =
// The majority of characters in this array
// map the poistion to the same character code.
// charMap['A'] == 'A'
// For forbidden characters a space is in the position
// charMap['<'] == ' '
// Note: \xxx is an octal escape sequence
"\000\001\002\003\004\005\006\007"
"\010\011\012\013\014\015\016\017"
"\020\021\022\023\024\025\026\027"
"\030\031\032\033\034\035\036\037"
"\040\041 \043\044\045\046\047" // replaced \042(") with space
"\050\051\052\053\054\055\056 " // replaced \057(/) with space
"\060\061\062\063\064\065\066\067"
"\070\071 \073 \075 " // replaced \072(:)\074(<)\076(>)\077(?) with space
"\100\101\102\103\104\105\106\107"
"\110\111\112\113\114\115\116\117"
"\120\121\122\123\124\125\126\127"
"\130\131\132\133 \135\136\137" // replaced \134(\)
"\140\141\142\143\144\145\146\147"
"\150\151\152\153\154\155\156\157"
"\160\161\162\163\164\165\166\167"
"\170\171\172\173\174\175\176\177"
"\200\201\202\203\204\205\206\207"
"\210\211\212\213\214\215\216\217"
"\220\221\222\223\224\225\226\227"
"\230\231\232\233\234\235\236\237"
"\240\241\242\243\244\245\246\247"
"\250\251\252\253\254\255\256\257"
"\260\261\262\263\264\265\266\267"
"\270\271\272\273\274\275\276\277"
"\300\301\302\303\304\305\306\307"
"\310\311\312\313\314\315\316\317"
"\320\321\322\323\324\325\326\327"
"\330\331\332\333\334\335\336\337"
"\340\341\342\343\344\345\346\347"
"\350\351\352\353\354\355\356\357"
"\360\361\362\363\364\365\366\367"
"\370\371\372\373\374\375\376\377";
``` |
2,446,175 | I have a block of text which occasionally has a really long word/web address which breaks out of my site's layout.
What is the best way to go through this block of text and shorten the words?
**EXAMPLE:**
this is some text and this a long word appears like this
```
fkdfjdksodifjdisosdidjsosdifosdfiosdfoisjdfoijsdfoijsdfoijsdfoijsdfoijsdfoisjdfoisdjfoisdfjosdifjosdifjosdifjosdifjosdifjsodifjosdifjosidjfosdifjsdoiofsij and i need that to either wrap in ALL browsers or trim the word.
``` | 2010/03/15 | [
"https://Stackoverflow.com/questions/2446175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/175562/"
] | You need **[wordwrap](http://php.net/manual/en/function.wordwrap.php)** function i suppose. | Based on @JonnyLitt's answer, here's my take on the problem:
```
<?php
function insertSoftBreak($string, $interval=20, $breakChr='­') {
$splitString = explode(' ', $string);
foreach($splitString as $key => $val) {
if(strlen($val)>$interval) {
$splitString[$key] = wordwrap($val, $interval, $breakChr, true);
}
}
return implode(' ', $splitString);
}
$string = 'Hello, My name is fwwfdfhhhfhhhfrhgrhffwfweronwefbwuecfbryhfbqpibcqpbfefpibcyhpihbasdcbiasdfayifvbpbfawfgawg, because that is my name.';
echo insertSoftBreak($string);
?>
```
Breaking the string up in space-seperated values, check the length of each individual 'word' (words include symbols like dot, comma, or question mark). For each word, check if the length is longer than `$interval` characters, and if so, insert a `­` (soft hyphen) every `$interval`'th character.
I've chosen soft hyphens because they seem to be relatively well-supported across browsers, and they usually don't show unless the word actually wraps at that position.
I'm not aware of any other usable (and well supported) HTML entities that could be used instead (`‌` does not seem to work in FF 3.6, at least), so if crossbrowser support for `­` turns out lacking, a pure CSS or Javascript-based solution would be best. |
25,642,244 | I'm mostly coding in Perl and struggle now with a regex in Java. I have this:
```
// String dbfPath = "/result_feature/Monocytes-CD14+_H3K4me3_ENCODE_UW_bwa_samse"
// rs.getString = "Monocytes-CD14+_H3K4me3_ENCODE_UW_bwa_samse"
if(! dbfPath.matches(".*" + rs.getString("rs_name") + "/*"))
```
My problem is that the rs\_name contains wildcards (+). I tried putting [] around, but then I have an illegal range (-).
How can I avoid the returning string being interpreted?
Thanks! | 2014/09/03 | [
"https://Stackoverflow.com/questions/25642244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1520203/"
] | Wrap your `rs.getString()` inside a `Pattern.quote`:
```
Pattern.quote(rs.getString("rs_name"))
```
>
> Returns a literal pattern String for the specified String.
>
>
> | You could add '\Q' & '\E' in your string direclty.
```
\Q Nothing, but quotes all characters until \E
\E Nothing, but ends quoting started by \Q
if(! dbfPath.matches(".*\\Q" + rs.getString("rs_name") + "\\E/*"))
```
One thing, you should make sure your string doesn't contain '\E', if yes, the safe way is using Pattern.quote() methods. |
16,249 | Example:
>
> The **cat** was lying on a cat bed, barely visible under
> the blankets, an IV wrapped around one of her front legs. Judging by
> the triangular shape of her head, her black nose ears and ears, she seemed
> to be a Siamese. Not that I was an expert at identifying cats; I only
> recognized this kind because one of them
> clawed into my neck when I was a child. It hurt like hell. And the cat got stuck so
> firmly Mom had to call the firefighters so they could come and pull it
> away with a crowbar. Seems like I wasn't very popular with animals at the time.
>
>
> We stared at the **Siamese** in silence for a while. The dogs, cats, and
> rabbits in the cages also contributed to this silence, making the
> place feel more like an animal morgue than an animal hospital. The
> only sound was the steady beeping of the **cat's** heart monitor.
>
>
> "So," I said, stroking the **cat's** paw, "did you guys find out the
> problem?"
>
>
> Takeshi sat at the examination table behind him. "We tested for infection,
> kidney failure, stomach ulcer, intestinal cancerβthe common diseases
> that'd make a cat stop eating. We found nothing."
>
>
> "Maybe its an, uh, psychological issue?"
>
>
> "Psychological issue?" Takeshi repeated, scratching the back of his
> hood. "Well, the owner of the **Siamese** moved into a new apartment recently."
>
>
> "What's that have to do with anything?"
>
>
>
I did this to have variation. I didn't want to repeat the *Siamese* or *cat* too much. Is this alternation annoying? Should I just stick with one of the words? | 2015/02/17 | [
"https://writers.stackexchange.com/questions/16249",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/1544/"
] | What you're talking about are [epithets](http://dictionary.reference.com/browse/epithet), and depending on who you talk to, they are either a necessary tool of writing or the bane of existence.
When overdone, epithets can make a simple conversation between two people feel like an orgy. If Bob, Frank, the blond, the redhead, the plumber, and the lawyer are all referred to in the same scene, it's hard to keep things straight. There's nothing wrong with repeating names when clarity is required. In your case, however, there are places where it's unambiguous who you're discussing, so you don't necessarily need references at all. Consider this:
>
> The cat was barely visible under the blankets she was wrapped in, an IV line taped to one of her front legs. Judging by the triangular shape of her head and her black nose ears and ears, she seemed to be a Siamese. Not that I was an expert at identifying cats; I only recognized this kind because one of them clawed into my neck when I was a child. It hurt like hell. And it had dug in so firmly that Mom had to call the firefighters so they could come and pull it away with a crowbar. Seems like I wasn't very popular with animals at the time.
>
>
> We stared at the poor thing in silence for a while. The dogs, cats, and rabbits in the other cages were strangely quiet as well, making the place feel more like an animal morgue than an animal hospital. The only sound was the steady beeping of the heart monitor.
>
>
> "So," I said, stroking the cat's paw, "did you guys find out the problem?"
>
>
> Takeshi sat at the examination table behind him. "We tested for infection, kidney failure, stomach ulcer, intestinal cancerβthe common diseases that'd make a cat stop eating. We found nothing."
>
>
> "Maybe it's a, uh, psychological issue?"
>
>
> "Psychological issue?" Takeshi repeated, scratching the back of his hood. "Well, her owner moved into a new apartment recently."
>
>
> "What's that have to do with anything?"
>
>
> | While it's a good idea to vary your descriptions occasionally for variety, in this instance, *Siamese* is not just a way to refer to *the cat,* but a way to differentiate this cat from *other* cats.
If the scene were in someone's living room, then *Siamese* would help you identify that cat as opposed to the tabby, tuxedo, and tortie cats also lying on the couch.
Here, you're pretty much talking about one cat, so I would treat "cat" more like "plumber" or "lawyer" in Roger's excellent answer, and use the cat's name as the variable instead.
The only place I would use it in your example is here:
>
> "So," I said, stroking **Sheba's** paw, "did you guys find out the problem?"
>
>
> |
60,503,529 | I want to use a `<select>` to be able to choose between several values, or choose none.
My component is this one :
```
<select @bind="SelectedValue">
<option value="null">Null</option>
@for (int i = 0; i < 10; i++)
{
<option value="@i">Value : @i </option>
}
</select>
<hr />
@if (SelectedValue.HasValue)
{
<p>The selected value is : @SelectedValue.Value</p>
}
else
{
<p>the value is null</p>
}
@code {
private int? SelectedValue = null;
}
```
I can bind the `<select>` value to an `int` object, but I can't bind the `null` value. Is there a special syntax I should use, or is it just not supported ? | 2020/03/03 | [
"https://Stackoverflow.com/questions/60503529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/704012/"
] | Why don't you just use -1 instead of null?
```
<select @bind="SelectedValue">
<option value="-1">Null</option>
@for (int i = 0; i < 10; i++)
{
<option value="@i">Value : @i </option>
}
</select>
<hr />
@if (SelectedValue>-1)
{
<p>The selected value is : @SelectedValue.Value</p>
}
else
{
<p>the value is null</p>
}
@code {
private int? SelectedValue = -1;
}
``` | >
> As a workaround, make a second property to translate.
>
>
> Also, you can't use an empty string instead of 'null', although you
> can use a different string. If you use an empty string then the Text
> property, rather than the Value property is passed as the selected
> Value.
>
>
>
```
//On Entity
public int? ProductID { get; set; }
/// <summary>
/// Only used to bind to select
/// </summary>
public string ProductIDAsString
{
get => ProductID?.ToString()?? "null";
set => ProductID = value == "null" ? null :(int?)int.Parse(value);
}
//In component
<label>Product</label>
<select @bind="@Model.ProductIDAsString" >
<option value="null">None</option>
@foreach (var product in AvailableProducts)
{
<option value="@product.ProductID">@product.Label</option>
}
</select>
``` |
16,751 | In Mac Lane, there is a definition of an arrow between adjunctions
called a map of adjunctions. In detail, if a functor $F:X\to A$ is left
adjoint to $G:A\to X$ and similarly $F':X'\to A'$ is left adjoint to
$G':A'\to X'$, then a map from the first adjunction to the second is a
pair of functors $K:A\to A'$ and $L:X\to X'$ such that $KF=F'L$,
$LG=G'K$, and $L\eta=\eta'L$, where $\eta$
and $\eta'$ are the units of the first and second adjunction. (The
last condition makes sense because of the first two conditions; also,
there are equivalent conditions in terms of the co-units, or in terms
of the natural bijections of hom-sets).
As far as I can see, after the definition, maps of adjunctions do not
appear anywhere in Mac Lane. Googling, I found this definition also
in the [unapologetic mathematician](http://unapologetic.wordpress.com/2007/07/30/transformations-of-adjoints/),
again with the motivation of being an arrow between adjunctions.
But what is the motivation for defining arrows between adjunctions
in the first place? I find it hard to believe that the only
motivation to define such arrows is, well, to define such arrows...
So my question is: What is the motivation for defining a map of
adjunctions? Where are such maps used?
Besides the unapologetic mathematician, the only places on the web
where I found the term ''map of adjunctions'' were sporadic papers,
from which I was not able to get an answer to my question (perhaps
''map of adjunctions'' is non-standard terminology and I should have
searched with a different name?).
I came to think about this when reading [Emerton's first answer
to a question about completions of metric spaces](https://mathoverflow.net/questions/11622/what-is-the-right-universal-property-of-the-completion-of-a-metric-space).
In that question, $X$ is metric spaces with isometric embeddings, $A$
is complete metric spaces with isometric embeddings, $X'$ is metric
spaces with uniformly continuous maps, $A'$ is complete metric
spaces with uniformly continuous maps, and $G$ and $G'$ are the
inclusions. Now, if I understand the implications of Emerton's answer
correctly, then it
is possible to choose left adjoints $F$ and $F'$ to $G$ and $G'$ such
that the (non-full) inclusions $A\to A'$ and $X\to X'$ form a map of
adjunctions. This made me think whether the fact that we have a map
of adjunctions has any added value. Then I realized that I do not
even know what was the motivation for those maps in the first place.
[EDIT: Corrected a typo pointed out by Theo Johnson-Freyd (thanks!)] | 2010/03/01 | [
"https://mathoverflow.net/questions/16751",
"https://mathoverflow.net",
"https://mathoverflow.net/users/2734/"
] | One of the applications of adjoint functors is to compose them to get a monad (or comonad, depending on the order in which you compose them). A map of adjoint functors gives rise to a map of monads. So one might ask: what are maps of monads good for? Many algebraic categories (such as abelian groups, rings, modules) can be described as categories of algebras over a monad, others (for example in Arakelov geometry) are most easily described in such a way. A map of monads then gives functors between the categories of algebras over these objects.
Here is a concrete example from topology: Let $E$ be a connective generalized multiplicative homology theory, and let $H = H(-;\pi\_0E)$ be ordinary homology with coefficients in $\pi\_0E$. There exists a map $E \to H$ inducing an isomorphism on $\pi\_0$. For a spectrum $X$, the functor $\underline{E}\colon X \mapsto E \wedge X$ gives rise to a monad, and similarly for $H$, thus we get a morphism of monads $\underline{E} \to \underline{H}$. The completion $X\hat{{}\_E}$ of a spectrum $X$ at $E$ is defined to be the totalization of the cosimplicial spaces obtained by iteratively applying $\underline{E}$ to $X$. The monad map gives a natural map $X\hat{{}\_E} \to X\hat{{}\_H}$ which turns out to be an equivalence for connective $X$. | The 2-category of categories, adjunctions, and conjugate natural transformations (i.e., maps of adjunctions between the same categories) is used in an approach to modal type theory in [Adjoint Logic with a 2-Category of Modes](http://dlicata.web.wesleyan.edu/pubs/ls15adjoint/ls15adjoint.pdf).
The general 2-categorical account of the double category of categories, adjunctions and maps of adjunctions is given by [mates](https://ncatlab.org/nlab/show/mate). |
21,691,409 | I'm relatively new to programming, so when someone suggested that building an array of structs (each containing n attributes of a particular "item") was faster than building n arrays of attributes, I found that I didn't know enough about arrays to argue one way or the other.
I read this:
[how do arrays work internally in c/c++](https://stackoverflow.com/questions/19370231/how-do-arrays-work-internally-in-c-c)
and
[Basic Arrays Tutorial](http://www.augustcouncil.com/~tgibson/tutorial/arr.html)
But I still don't really understand how a C program retrieves a particular value from an array by index.
It seems pretty clear that data elements of the array are stored adjacent in memory, and that the array name points to the first element.
Are C programs smart enough to do the arithmetic based on data-type and index to figure out the exact memory address of the target data, or does the program have to somehow iterate over every intermediary piece of data before it gets there (as in the linkedlist data structure)?
More fundamentally, if a program asks for a piece of information by its memory address, how does the machine find it? | 2014/02/11 | [
"https://Stackoverflow.com/questions/21691409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2127595/"
] | Let's take a simpler example. Let's say you have a array `int test[10]` which is stored like this at address 1000:
>
> 1|2|3|4|5|6|7|8|9|10
>
>
>
The complier knows that, for example, an int is 4 bytes. The array access formula is this:
>
> baseaddr + sizeof(type) \* index
>
>
>
The size of a struct is just the sum of the sizes of its elements plus any padding added by the compiler. So the size of this struct:
```
struct test {
int i;
char c;
}
```
Might be 5. It also might not be, because of padding.
As for your last question, very shortly (this is very complicated) the MMU uses the page table to translate the virtual address to a physical address, which is then requested, which if it's in cache, is returned, and otherwise is fetched from main memory. | so here is the whole trick, array elements are adjacent in memory.
when you declare an array for example: `int A[10];`
the variable `A` is a pointer to the first element in the array.
now comes the indexing part, whenever you do `A[i]` it is exactly as if you were doing `*(A+i)`.
the index is just an offset to the beginning address of the array, also keep in mind that in pointer arithmetic the offset is multiplied by the size of the data type of the array.
to get a better understanding of this write a little code, declare an array and print the address of it and then of each element in the array.
and notice how the offset is always the same and equal to the size of the data type of your array on your machine. |
137,241 | I quoted the next code snippet from `config.status` generated by `configure`.
```
if test ! -f "$as_myself"; then
{ { echo "$as_me:$LINENO: error: cannot find myself; rerun with an absolute path" >&5
echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2;}
{ (exit 1); exit 1; }; }
fi
```
In the code snippet, what does `{ (exit 1); exit 1; };` do? What's the purpose of only doing `exit` in a subshell? | 2014/06/15 | [
"https://unix.stackexchange.com/questions/137241",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/64173/"
] | Executing `(exit 1);` is the simplest way of triggering an `ERR` trap. It will also trigger immediate exit if `set -e` is in effect. (Triggering the error condition requires a command to fail; `exit` with a failure value in a subshell causes the subshell to fail.)
`exit 1;` will do neither of those things.
So `{(exit 1); exit 1;}` can be used to first produce the `ERR` trap, which might do something useful for debugging purposes, and then terminate the script with an error indication.
But that's not what is going on in `autoconf` files. `autoconf` scripts rely on the `EXIT` trap in order to clean up temporary files created during the run. Most shells, including `bash` will set the status from the value provided in the `exit` command before calling the `EXIT` trap. That could allow the `EXIT` trap to detect whether it was invoked from an error or from normal termination, and it also allows it to ensure that the exit status is correctly set at the end of the trap operation.
However, apparently some shells do not co-operate. Here's a quote from the [`autoconf` manual](http://www.gnu.org/software/autoconf/manual/autoconf-2.64/html_node/Limitations-of-Builtins.html):
>
> Some shell scripts, such as those generated by `autoconf`, use a trap to clean up before exiting. If the last shell command exited with nonzero status, the trap also exits with nonzero status so that the invoker can tell that an error occurred.
>
>
> Unfortunately, in some shells, such as Solaris `/bin/sh`, an exit trap ignores the exit command's argument. In these shells, a trap cannot determine whether it was invoked by plain exit or by exit 1. Instead of calling exit directly, use the `AC_MSG_ERROR` macro that has a workaround for this problem.
>
>
>
The workaround is to make sure that `$?` has the exit status *before* the `exit` command is executed, so that it will definitely have that value when the `EXIT` trap is executed. And, indeed, it is the `AC_MSG_ERROR` macro which inserts that curious code, complete with redundant braces. | There is no purpose for this as far as I can see, there is nothing that can be achieved directly by starting a subshell and then immediately exiting.
Things like this are most likely a side effect of automatically generating code - in some cases there may be other commands executed in the subshell where having the `exit 1` makes sense. Ultimately there is a good chance that the generation code is somehow simplified by allowing it to insert some statements that don't have any function in some cases rather and generating 'clean code' every single time is more complex. Either that or the code which generated the above is just poorly written :)
The liberal use of `{...}` is another example of this, most of them are redundant, but it is easier to write code that inserts them in every case (maybe in some you want to redirect the output/input of the block) rather than to distinguish the ones where they are not needed and omit them. |
13,436,520 | Recently I am writing some micro-benchmark code, so I have to print out the JVM behaviors along with my benchmark information. I use
```
-XX:+PrintCompilation
-XX:+PrintGCDetails
```
and other options to get the JVM status. For benchmark information, I simply use `System.out.print()` method. Because I need to know the order of the message I printed and the JVM output.
I can get good result when I just print them out in the console, although the JVM output sometimes tear my messages up, but since they are in different threads, it is understandable and acceptable.
When I need to do some batch benchmarks, I'd like to ***`redirect the output into a file`*** with `pipe (> in Linux system)`, and use python to get the result from the file and analyse it.
Here is the problem:
**`The JVM output always overlapped with the messages I printed in the Java application.`** It ruined the completion of the messages.
Any idea how to deal with this situation? I need **`both the JVM output and application output in the same place in order to preserve the sequence because it is important. And they do not overlap on each other so I don't lose anything.`** | 2012/11/18 | [
"https://Stackoverflow.com/questions/13436520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1643467/"
] | For `-XX:+PrintCompilation`, you could use `-XX:+UnlockDiagnosticVMOptions -XX:+LogCompilation` flags instead to get a "verbose" output in separate "hotspot.log" file. This file is in XML format and contains both the information from `-XX:+PrintCompilation` and the cause of such compilations. The file path can be changed via `-XX:LogFile=<new_hotspot_log>`. Reference: <https://wiki.openjdk.java.net/display/HotSpot/LogCompilation+overview>
For `-XX:+PrintGCDetails`, you could use `-Xloggc:<gc_log>` to redirect the GC output to the specified file. Reference: `java -X` | First, I'd try what @barracel noted about using System.out.println().
I don't know much about Java, but you could also write out all of your debug messages to stderr and leave stdout for the JVM. This may prevent the pollution of stdout that's apparently happening when multiple threads write to the same file descriptor. |
1,435,138 | Well it should work in IE, I know IE doesnt support content property anything other that? | 2009/09/16 | [
"https://Stackoverflow.com/questions/1435138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116489/"
] | The only option is the the [`content`](http://www.w3.org/TR/CSS21/generate.html#content) property:
>
> The content property is used with the
> `:before` and `:after` pseudo-elements, to
> insert generated content.
>
>
>
But as you point out, this is part of CSS 3 and is not supported by IE. In the meantime you will need to compensate by using JavaScript. | It is quite possible to solve this without Javascript, using a combination of HTML and CSS. The trick is to duplicate the content added by the CSS in the HTML an IE-specific conditional comment (not shown by other browsers) and use the `display` CSS selector to toggle when that element is shown. [According to MSDN](http://msdn.microsoft.com/en-us/library/cc351024%28v=vs.85%29.aspx), IE 8+ supports CSS `:after` and `content:`, so only IE 7 and below need to use a conditional comment.
Here is an example:
```
<style type="test/css" media="screen">
.printonly { display: inline; }
</style>
<style type="text/css" media="print">
#maintitle:after { content:" \2014 Site Title";} /* for IE8+ and Other Browsers. sidenote: Can't use &mdash directly in generated content, so using escape code */
.printonly { display:inline } /* For IE <= 7 */
</style>
<h1 id="maintitle">Page Title
<!--[if lte IE 7]><span class="printonly">— Site Title</span><![endif]-->
</h1>
``` |
198,143 | I'm looking for a way to get the list of all plugins listed in the [WordPress.org Plugin Directory](https://wordpress.org/plugins/).
There is one other post I've [found on StackOverflow](https://wordpress.stackexchange.com/questions/95836/list-of-all-existing-wordpress-plugins) regarding this which recommends [using the subversion repository.](http://plugins.svn.wordpress.org/)
I'd like to do something that organizes them by number of downloads.
I think this is probably possible using the WordPress.org API, but I'm not positive. My attempts thus far have failed. Any ideas? | 2015/08/10 | [
"https://wordpress.stackexchange.com/questions/198143",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43881/"
] | You can start with something like this:
```
https://api.wordpress.org/plugins/info/1.2/?action=query_plugins&request[page]=1&request[per_page]=400
```
I think it's self-explanatory. | good day dear Davemackey - hello Michael Field
its been a long time that this has been asked - but anyway.. here my little idea that i can come up with..
Not the best answer but I tried to solve my own problem the best way I could.
Getting a list of plugins
=========================
This will **not** return ALL plugins but it will return the **top rated** ones:
```
$plugins = plugins_api('query_plugins', array(
'per_page' => 100,
'browse' => 'top-rated',
'fields' =>
array(
'short_description' => false,
'description' => false,
'sections' => false,
'tested' => false,
'requires' => false,
'rating' => false,
'ratings' => false,
'downloaded' => false,
'downloadlink' => false,
'last_updated' => false,
'added' => false,
'tags' => false,
'compatibility' => false,
'homepage' => false,
'versions' => false,
'donate_link' => false,
'reviews' => false,
'banners' => false,
'icons' => false,
'active_installs' => false,
'group' => false,
'contributors' => false
)));
```
Save the data as JSON
=====================
Since the data that we get is huge and it will be bad for performance, we try to get the `name` and the `slug` out of the array and then we write it in a JSON file:
```
$plugins_json = '{' . PHP_EOL;
// Get only the name and the slug
foreach ($plugins as $plugin) {
foreach ($plugin as $key => $p) {
if ($p->name != null) {
// Let's beautify the JSON
$plugins_json .= ' "'. $p->name . '": {' . PHP_EOL;
$plugins_json .= ' "slug": "' . $p->slug . '"' . PHP_EOL;
end($plugin);
$plugins_json .= ($key !== key($plugin)) ? ' },' . PHP_EOL : ' }' . PHP_EOL;
}
}
}
$plugins_json .= '}';
file_put_contents('plugins.json', $plugins_json);
```
Now we have a slim JSON file with only the data that we need.
To keep updating the JSON file, we run that script to create a JSON file every 24 hours by setting up a Cron Job. |
48,630 | I have a computer running TightVNC server. It is on my home network. The computer it is installed on has a locally static ip address 192.168.1.100. I am able to connect to this vnc server from my home network fine, but unable to connect from outside my network (using the IP address that I see at [www.whatismyip.com](http://www.whatismyip.com)).
I have forwarded port 5900 (and 5800) to ip address 192.168.1.100. But if I use [canyouseeme.org](http://canyouseeme.org/) I am unable to see that port.
I am running Windows 7.
Any suggestions? | 2009/09/29 | [
"https://superuser.com/questions/48630",
"https://superuser.com",
"https://superuser.com/users/8610/"
] | I would double check that you have forwarded the port as that is all you should need to do.
If there is a problem, try changing the default port in case your ISP is blocking it.
Lastly, you may want to double check that you have forwarded the correct protocol, I can't remember if it is TCP or UDP that is needed, but if you have one - try the other (or both!) | I'm betting (could be wrong) that you probably actually need to forward 5901/5801. Doesn't VNC add the display number to the port you select? The first display number is 1. Been awhile since I messed with VNC but just a thought. |
3,156,744 | I have a problem when I try to do a git svn rebase on my repository. It displays :
```
Checksum mismatch: code/app/meta_appli/app_info.py
expected: d9cefed5d1a630273aa3742f7f414c83
got: 4eb5f3506698bdcb64347b5237ada19f
```
I searched a lot but haven't found a way to solve this problem.
If anybody knows, please share your knowledge.
Thanks in advance. | 2010/07/01 | [
"https://Stackoverflow.com/questions/3156744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/119190/"
] | [This solution](http://www.victoriakirst.com/?p=903) was the only one that worked for me:
>
> See what was the revision number of the last change on the file:
>
>
> `git svn log chrome/test/functional/search_engines.py`
>
>
> Reset svn to be closest parent before that revision:
>
>
> `git svn reset -r62248 -p`
>
>
> Do a `git svn fetch`!
>
>
> Dance at your success.
>
>
> | In our practice the error "Checksum mismatch:" on .shtml files in git svn clone ... command was caused by the setup of the front-end Apache server to interpret the.shtml files (from SVN) as Server-Side Includes (SSI) and thus produce live content instead of just providing the stored file content. Disabling SSI in Apache's /etc/httpd.conf file for the period of migration by commenting out the
```
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml
```
directives solved the problem.
Anyway, the migration of the repository could exclude some paths and files happens with:
```
git svn clone <URL> --ignore-paths=<regex>
```
clause. It makes sense to check the environment of the SVN server process if those files have special interpretation like SSI (and the .php and .py files) and disable it. |
18,603,181 | In C# I use strategy pattern with dictionary like this:
```
namespace NowListeningParserTool.Classes
{
using System.Collections.Generic;
public class WebsiteDictionary
{
private readonly Dictionary<string, WebsiteParser> _website = new Dictionary<string, WebsiteParser>();
public WebsiteDictionary()
{
_website.Add("YouTube", new YoutubeWebsiteParser());
_website.Add("977 Music", new NineNineSevenMusicWebsiteParser());
_website.Add("Grooveshark", new GroovesharkWebsiteParser());
_website.Add("Sky.FM", new SkyfmWebsiteParser());
_website.Add("iHeart", new IheartWebsiteParser());
_website.Add("Live365", new LiveThreeSixFiveWebsiteParser());
_website.Add("Pandora", new PandoraWebsiteParser());
_website.Add("Spotify", new SpotifyWebsiteParser());
}
public string GetArtistAndTitle(string website, string browser, string stringToParse)
{
return _website[website].GetArtistAndTitle(browser, stringToParse, website);
}
public string GetWebsiteLogoUri(string website)
{
return _website[website].WebsiteLogoUri;
}
}
}
```
WebsiteParser is abstract class.
What would be the syntax for this in JavaScript? For example I have multiple IF statements in JavaScript:
```
function getWebsite() {
if (document.URL.indexOf('grooveshark.com') >= 0) return getTrackGrooveshark();
if (document.URL.indexOf('977music.com') >= 0) return getTrack977Music();
if (document.URL.indexOf('sky.fm/play') >= 0) return getTrackSkyFm();
if (document.URL.indexOf('iheart.com') >= 0) return getTrackIHeart();
if (document.URL.indexOf('live365.com') >= 0) return getTrackLive365();
if (document.URL.indexOf('youtube.com') >= 0) return getTrackYoutube();
if (document.URL.indexOf('pandora.com') >= 0) return getTrackPandora();
if (document.URL.indexOf('spotify.com') >= 0) return getTrackSpotify();
}
```
...that I really don't like, and would like to use the same approach as I did in C# for eliminating these ugly IFs.
Cheers. | 2013/09/03 | [
"https://Stackoverflow.com/questions/18603181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395676/"
] | Option 1: Returns the content from the executed function.
```
function getWebsite() {
var websites = [
['grooveshark.com',getTrackGrooveshark],
['977music.com',getTrack977Music],
['sky.fm/play',getTrackSkyFm],
['iheart.com',getTrackIHeart],
['live365.com',getTrackLive365],
['youtube.com',getTrackYoutube],
['pandora.com',getTrackPandora],
['spotify.com',getTrackSpotify]
],
url = document.URL,
ret;
$.each(websites,function(i,v){
if(url.indexOf(v[0]) !== -1){
ret = v[1]();
return false;
}
});
return ret;
}
```
Option 2: Invoke the function.. Return Nothing
```
function getWebsite() {
var websites = [
['grooveshark.com',getTrackGrooveshark],
['977music.com',getTrack977Music],
['sky.fm/play',getTrackSkyFm],
['iheart.com',getTrackIHeart],
['live365.com',getTrackLive365],
['youtube.com',getTrackYoutube],
['pandora.com',getTrackPandora],
['spotify.com',getTrackSpotify]
],
url = document.URL;
$.each(websites,function(i,v){
if(url.indexOf(v[0]) !== -1){
v[1](); //Executes the function
return false; //Breaks the Each loop.
}
});
}
``` | I think this is really a matter of using a simple JavaScript object. Basically you can reference any property of an object in a similar fashion as you are doing in C#, but I think in a much simpler way. Of course that is my opinion :) I like to structure my modules in a self instantiating manner, like jQuery, so there may be more here than you need in the simplest form. I am also going to assume your parsers are global methods for the example's sake, but you should avoid doing that in real practice. Sorry for any typos as I am doing this in the WYSIWYG editor here.
Here goes:
(function () {
```
"use strict";
var WebsiteDictionary = function () {
return new WebsiteDictionary.fn.init();
};
WebsiteDictionary.fn = WebsiteDictionary.prototype = {
constructor: WebsiteDictionary,
init: function () {
this._website["YouTube"] = YoutubeWebsiteParser();
this._website["977Music"] = NineNineSevenMusicWebsiteParser();
this._website["Grooveshark"] = GroovesharkWebsiteParser();
this._website["SkyFM"] = SkyfmWebsiteParser();
this._website["iHeart"] = IheartWebsiteParser();
this._website["Live365"] = LiveThreeSixFiveWebsiteParser();
this._website["Pandora"] = PandoraWebsiteParser();
this._website["Spotify"] = SpotifyWebsiteParser();
return this;
},
_website: {},
GetArtistAndTitle: function(website, browser, stringToParse)
{
return this._website[website].GetArtistAndTitle(browser, stringToParse, website);
}
GetWebsiteLogoUri: function(website)
{
return this._website[website].WebsiteLogoUri;
}
};
// Give the init function the love2DevApp prototype for later instantiation
WebsiteDictionary.fn.init.prototype = WebsiteDictionary.fn;
return (window.WebsiteDictionary= WebsiteDictionary);
```
}());
I believe this is called an associative array, but don't quote me on that. Basically every member/property of a JavaScript object is accessible in a similar fashion as you access the Dictionary properties in C#. So the member's name is the dictionary key. I also edited the names so they can be valid JavaScript names.
I hope this helps. I think this is a pretty nifty little JavaScript technique. If you review some high profile JavaScript libraries, like jQuery you see this being used a lot. |
46,787,432 | I am creating an array in Javascript where the product id is used for the key. As the key is numeric, the array is filling gaps with null.
So for example, if I had only two products and their ids were 5 and 7, I would do something like:
```
var arr = []
arr[5] = 'my first product';
arr[7] = 'my second product';
```
This array is then passed to a PHP script but upon printing the array, I get the following;
```
Array (
[0] = null
[1] = null
[2] = null
[3] = null
[4] = null
[5] = My first product
[6] = null
[7] = My second product
)
```
my ID numbers are actually 6 digits long, so when looping over the array, there are 100,000 iterations, even if I actually only have two products.
How can I create the array so the null values are not entered? I thought of making the key a string instead but as the array is build dynamically, I am not sure how to do that.
```
var arr = [];
for(var i=0; i<products.length; i++)
{
array[products[i].id] = products[i].name;
}
```
Thanks | 2017/10/17 | [
"https://Stackoverflow.com/questions/46787432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/857903/"
] | For iterating the array, you could use [`Array#forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach), which skips sparse items.
```js
var array = [];
array[5] = 'my first product';
array[7] = 'my second product';
array.forEach(function (a, i) {
console.log(i, a);
});
```
For better organisation, you could use an object, with direct access with the given id.
```
{
5: 'my first product',
7: 'my second product'
}
``` | >
> Forcing javascript key integer fills array with null
>
>
>
You are declaring an empty array and then setting values into 6th and 8th element in the array. That leaves the values of other elements as null.
If you don't intend to `push` items into array, i.e. use objects. Something like,
```
var obj = {};
obj[5] = "my first product";
obj[7] = "my second product";
```
This means the object created is:
>
> obj = {"5":"my first product","7":"my second product"}
>
>
> |
63,666,195 | I am a very new user here so, apologies in advance if I break any rule. Here is the problem I am facing and need suggestions please.
I have a Chrome extension which works with Gmail & consumes APIs from my web server running on nginx through Phusion Passenger server of Rails application.
My Nginx version is nginx version: nginx/1.15.8 and Phusion Passenger version is Phusion Passenger Enterprise 6.0.1
I had the CORS settings in nginx as follows:
```
####### CORS Management ##########
add_header 'Access-Control-Allow-Origin' 'https://mail.google.com,https://*.gmail.com';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, HEAD';
add_header Referrer-Policy "no-referrer";
add_header Pragma "no-cache";
##################################
```
This used to work until Chrome 84, however, with the latest update of Chrome 85, it has started throwing CORS errors as follows:
########## Error started appearing in Chrome 85 ############
Access to fetch at 'https://my-site.com/' from origin 'https://mail.google.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
##########################################
After this, I updated the CORS settings to wide open as per the suggestions/reference from various sources and blogs and now updated CORS setting looks like this:
UPDATED CORS Settings in Nginx
```
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' $http_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type' always;
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8' always;
add_header 'Content-Length' 0 always;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' $http_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type' always;
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' $http_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type' always;
}
}
```
############################################
After updating this setting in Nginx, the CORS error has gone but now I am getting 401 Unauthorized error from server when the extension makes API call.
I tried tweaking all the methods but couldn't fix it up. Is there something which I am missing or doing differently?
Please help! | 2020/08/31 | [
"https://Stackoverflow.com/questions/63666195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13319628/"
] | I got the same issue following Cosmos DB SQL API getting started guide.
The fix was to specify `ConnectionMode = ConnectionMode.Gateway`
```
var cosmosClient = new CosmosClient(EndpointUrl, AuthorizationKey, new CosmosClientOptions() { AllowBulkExecution = true, ConnectionMode = ConnectionMode.Gateway });
``` | Please ensure below points are taken care in .NET SDK:
* Initialize a singleton DocumentClient
* Use Direct connectivity and TCP protocol (ConnectionMode.Direct and ConnectionProtocol.Tcp)
* Use 100s of Tasks in parallel (depends on your hardware)
* Increase the MaxConnectionLimit in the DocumentClient constructor to a high value, say 1000 connections
* Turn gcServer on
* Make sure your collection has the appropriate provisioned throughput (and a good partition key)
You can now use the bulk executor library directly for bulk operations - <https://learn.microsoft.com/en-us/azure/cosmos-db/bulk-executor-dot-net> |
13,727,089 | I am trying to update the metadata on the multimedia image in C# using Tridion's TOM.NET API like this
```cs
componentMM.LoadXML(localComponent.GetXML(XMLReadFilter.XMLReadALL));
// make changes to the component mm multimedia text;
localComponent.UpdateXML(componentMM.InnerXML);
localComponent.Save(True)
```
While this works for other components, it is failing for Multimedia images.
```xml
<?xml version="1.0"?>
<tcm:Error xmlns:tcm="http://www.tridion.com/ContentManager/5.0"
ErrorCode="80040345" Category="19" Source="Kernel" Severity="2">
<tcm:Line ErrorCode="80040345" Cause="false" MessageID="16137"><![CDATA[
Unable to save Component (tcm:33-32599).
]]><tcm:Token>RESID_4574</tcm:Token>
<tcm:Token>RESID_4418</tcm:Token>
<tcm:Token>tcm:33-32599</tcm:Token>
</tcm:Line>
<tcm:Line ErrorCode="80040345" Cause="true" MessageID="15747"><![CDATA[
Unexpected element: MultimediaFileSize
]]><tcm:Token>MultimediaFileSize</tcm:Token>
</tcm:Line>
<tcm:Details>
<tcm:CallStack>
<tcm:Location>ComponentBL.CheckMultiMediaProperties</tcm:Location>
<tcm:Location>ComponentBL.CheckMultiMediaProperties</tcm:Location>
<tcm:Location>ComponentBL.Update</tcm:Location>
<tcm:Location>XMLState.Save</tcm:Location>
<tcm:Location>Component.Save</tcm:Location>
</tcm:CallStack>
</tcm:Details>
</tcm:Error>
```
Can you please let me know what am I doing wrong here? | 2012/12/05 | [
"https://Stackoverflow.com/questions/13727089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373140/"
] | Include only the tcm:Metadata node in your update?
Specifically, it is complaining about you specifying the size of the mm file, which you shouldn't, that's a system property. Clean up the XML you receive from Tridion to remove that property (it might then complain about another property, just do what it asks you to).
EDIT: Reading the error messages is a great skill to have... | When you do this you need to only save the modified metadata data (not the entire XML). Try removing all of the child nodes except tcm:Metadata from the XML structure before calling `.UpdateXML()`
Perhaps you could paste your sample XML if you need further assistance. |
18,683,338 | is it possible to get metadata of an OData service in JSON format?
When I try to use `format=json` , it doesn't work. Here is what I tried:
```
http://odata.informea.org/services/odata.svc/$metadata/?format=json
``` | 2013/09/08 | [
"https://Stackoverflow.com/questions/18683338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/668082/"
] | The `$metadata` document is in the CSDL format, which currently only has an XML representation. (As a side note, if you do want to request the json format for a different kind of OData payload, make sure the `format` query token has a `$` in front of it: `$format=json`.)
So, no it is not possible. You can, however, get the service document in JSON, which is a subset of the $metadata document:
```
http://odata.informea.org/services/odata.svc?$format=json
```
This won't have type information, but it will list the available entry points of the service (i.e., the entity sets). | I agreed with the previous answer. This isn't supported by the specification but some OData frameworks / libraries are about to implement this feature.
I think about Olingo. This is could be helpful for you if you also implement the server side. See this issue in the Olingo JIRA for more details:
* **OLINGO-570** - <https://issues.apache.org/jira/browse/OLINGO-570>
Hope it helps you,
Thierry |
445,739 | I have lines that look like this
```
123-456-789 12.34.56 example
```
I want to select the 12, add 2 to it, then print the whole line as is. So the result should be :
```
123-456-789 14.34.56 example
```
I have this awk expression :
```
awk 'BEGIN {FS="[ .]"}{$2=$2+2}{print}'
```
But it gives me
```
123-456-789 14 34 56 example
```
The dots are gone and replaced by spaces. | 2018/05/24 | [
"https://unix.stackexchange.com/questions/445739",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/292395/"
] | Trying to "*restore*" a complex/compound field separator will likely break some values and the consistency of the whole record.
Instead, use the following approach:
```
awk '{ n = substr($2, 1, index($2, ".")); sub(/[^.]+\./, n + 2 ".", $2) }1' file
```
The output:
```
123-456-789 14.34.56 example
```
---
The above command will use whitespace(s) as default field separator and perform all the needed processing on the 2nd field `$2` only. | Use `split` function in your `awk` script that allows capturing the field separator:
```
awk '{split($0,a,"[- .]",sep); a[4]+=2; for(i in a) printf "%s%s",a[i], sep[i]; printf "\n"}' file
```
Alternatively, you can make use of `RS` and `RT` variables
```
awk -v RS='[- .]' 'NR==4{$1+=2} {printf "%s%s",$0,RT}' file <<< '123-456-789 12.34.56 example'
```
Note that last one would only work for a single line. |
1,521,071 | How do I shift an array of items up by 4 places in Javascript?
I have the following string array:
```
var array1 = ["t0","t1","t2","t3","t4","t5"];
```
I need a function convert "array1" to result in:
```
// Note how "t0" moves to the fourth position for example
var array2 = ["t3","t4","t5","t0","t1","t2"];
```
Thanks in advance. | 2009/10/05 | [
"https://Stackoverflow.com/questions/1521071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184481/"
] | ```
array1 = array1.concat(array1.splice(0,3));
```
run the following in Firebug to verify
```
var array1 = ["t0","t1","t2","t3","t4","t5"];
console.log(array1);
array1 = array1.concat(array1.splice(0,3));
console.log(array1);
```
results in
```
["t0", "t1", "t2", "t3", "t4", "t5"]
["t3", "t4", "t5", "t0", "t1", "t2"]
``` | One more way would be this:
```
var array2 = array1.slice(0);
for (var i = 0; i < 3; i++) {
array2.push(array2.shift());
}
``` |
151,933 | Setting Overview
----------------
My world suffers from an abundance of a particular type of energy. This energy can be safely absorbed and utilized by living cells, enabling, for example, a dragon's flight and fiery breath or a human's ability to manipulate his environment through "magic."
However, this energy also amplifies the effects of electricity, such as lightning or computer circuitry. In the latter case, unshielded components tend to fail spectacularly in short order.
To balance this extra energy, I've ruled that iron can absorb immense amounts of it, which causes the metal to heat. The more it absorbs, the more it heats up. The disruptive, raw energy is safely converted into heat energy.
Brief History
-------------
When humans first arrived on this world by spaceship, they brought with them advanced, electricity-based technology. These devices were quickly adapted to the new world's environment and the humans started terraforming the world.
The planet's indigenous flying and fire-breathing species didn't take kindly to this and banded together to end the technological threat to their world. A single AI managed to escape the onslaught by tunneling deep underground, where it has remained for several thousand years formulating a revenge plan.
The Problem
-----------
The AI has devised a plan to end the reign of the raw energy, but it needs to be able to act on the surface. To do this, it has decided to construct semi-autonomous machines to go forth and do its bidding. These machines, of course, have to be protected from the raw energy, so they will be constructed using copious amounts of iron (to absorb the offending energy) and copper (to redistribute the heat from the iron into a heat sink).
Unfortunately, this means the machines have this giant heat sink taking up space, and that is inefficient.
Can the machines be engineered in such a way to re-use the energy stored in their heat sink, such as granting them a fire breath akin to the dragons they're going to be fighting, or are heat sinks a one-way trip for energy?
---
About the tags: I had in mind designing these machines to mimic real animal designs. This particular story was heavily influenced by playing *Horizon: Zero Dawn*. The [creature-design](/questions/tagged/creature-design "show questions tagged 'creature-design'") tag is intended to reflect this concept. | 2019/07/30 | [
"https://worldbuilding.stackexchange.com/questions/151933",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/6986/"
] | **Energy Absorption Mechanism + constant movement**
This is a dumb idea but hey, worth a shot. The idea is that these machines must have some initial energy stored within them to allow them to get to perform certain tasks as directed by the AI. Obviously the dragons and whatnot will try to fight them back, so instead of just containing this energy within a massive heat sink, just use the energy as fuel by absorbing it using technology to absorb the kinetic and thermal energy of the so-called 'raw energy' you mentioned the dragons using. Of course, I'm assuming that the 'raw energy' you described has these properties.
You already mention iron and copper to be used for channeling this energy into the heat sink, but why not turn the tables - why not use the raw energy to power your electric technology? We know that energy in all its forms can be transformed into a different type of energy (GPE to KE, Thermal to KE, Chemical to KE, etc.) so perhaps your AI is advanced enough to figure out how to use the raw energy, or RE, into Thermal or Kinetic energy!
Now this means that it's still possible to destroy one of these machines by overloading it with energy. In this case, to mitigate this problem we can make sure this machine works harder and uses more of its energy, and perhaps convert stored energy to into raw energy blasts (if that works on the dragons). Literally fighting fire with fire.
We can complicate this further by making the more operational/technical robots (like the ones re-starting terraforming or whatnot) would have high heat sinks, whereas combat robots would have low ones as they'll be more equipped to fight back anyway. If they are left with any excess energy, it can be passed on to the operational robots.
Edit: I mentioned piezoelectric materials - I messed up. From this [pdf](https://iopscience.iop.org/article/10.1088/1742-6596/662/1/012031/pdf), we can see a comprehensive research paper done about how a battery's energy can be derived from using mechanical energy derived from piezoelectric components in and around the battery, effectively making a battery charge itself. That would likely exacerbate your problem as your problem has to do with getting rid of excess energy, not making more.
The reason I kept my answer generic was because I didn't know what raw energy was (still don't technically) as it exists in the universe you built. More information about RE and its limitations would be helpful. | >
> However, this energy also amplifies the effects of electricity, such as lightning or computer circuitry. In the latter case, unshielded components tend to fail spectacularly in short order.
>
>
>
This is marvellous news. Now for every watt of energy used, many more watts of power become available.
If anything the problem here is that your electronics would be too effective. So, your AI should build its autonomous drones on the assumption they can produce a fraction of their normal power. This energy field will make up the shortfall.
As a result, the AI can use a standard template model, but use weaker components and get the same result. These new versions will be lighter and more efficient.
The AI might even use a large lump of iron as a means of generating power, similar to how Radio Thermoisotope Generators power satellites using the heat of plutonium and other radioactive decaying materials
So the TLDR, this is not a problem, but a huge advantage.
If this advantage is not to your liking though, the AI could use copper and aluminum instead, and avoid iron in most components. There are plenty of ferrous and conductive materials that aren't iron. Some of our most advanced electronics relies on Silicon, copper, Gallium Nitride, and various rare elements, Iron isn't necessary |
1,310,890 | $$\lim\_{x\to\infty}\left(\sin{\frac 1x}+\cos{\frac 1x}\right)^x$$
It is about the $(\to1)^{(\to\infty)}$ situation. Can we find its limit using the formula $\lim\_{x\to\infty}(1+\frac 1x)^x=e$? If yes, then how? | 2015/06/03 | [
"https://math.stackexchange.com/questions/1310890",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/245612/"
] | Put $y=\dfrac{1}{x} \to \displaystyle \lim\_{x\to \infty}\ln(f(x))=\displaystyle \lim\_{y\to 0}\dfrac{\ln\left(\sin y+\cos y\right)}{y}=\displaystyle \lim\_{y\to 0} \dfrac{\cos y - \sin y}{\sin y+ \cos y}=1\to \displaystyle \lim\_{x \to \infty} f(x) = e$. | Set $1/x=h$ to get
$$\lim\_{x\to\infty}\left(\sin\frac1x+\cos\frac1x\right)^x=\lim\_{h\to 0^+}\left(\sin h+\cos h\right)^{\frac1h}$$
Now $(\sin h+\cos h)^2=1+2\sin h\cdot\cos h=1+\sin2h$
$$\lim\_{h\to 0^+}\left(\sin h+\cos h\right)^{\frac1h}=\lim\_{h\to 0^+}\left[\left(\sin h+\cos h\right)^2\right]^{\frac1{2h}}$$
$$=\left[\lim\_{h\to 0^+}\left(1+\sin2h\right)^{\dfrac1{\sin2h}}\right]^{\lim\_{h\to 0^+}\dfrac{\sin2h}{2h}}$$
Now for the inner limit, use $\lim\_{ y\to0}(1+y)^{\dfrac1y}=\lim\_{m\to\infty}\left(1+\dfrac1m\right)^m=e$
How about the limit in the exponent? |
323,482 | Setting:
* Longitudinal data on outcome Yi,t of a group of individuals, i={1,...,N}, over time, t={1,...,T}
* On this group, a sequence of RCTs (r={1,...,R}) staggered over time is applied.
* Each RCT is measuring the effect of a specific treatment and treats a small percentage of the population.
* Once an individual is treated in a certain round (r=x) then he is no longer eligible for other future RCTs (rounds).
I am trying to measure the specific impact of each treatment (eq 1), as well as the average impact of the treatments (eq 2).
1. Yi,t,r = ALPHAr*TREATEDi,r + BETAr*(TREATEDi,r\*I\_POST\_TREATMENTt,r)
2. Yi,t = ALPHA\*TREATEDi + BETA \*(TREATEDi \*I\_POST\_TREATMENTt)
The control group of that same round (r=x) on the other hand may be "contaminated" by being treated in a future RCT. Because trials treat a small percentage of the population each round (without replacement), and there aren't that many rounds, a significant proportion of the control group remains untreated over the entire period.
What is the correct statistical procedure to adopt here?
Is there a technical term for this sort of setting?
Any relevant literature I should look at?
EDIT: To try to collect me inputs, I cross posted on Stata List [here](http://www.statalist.org/forums/forum/general-stata-discussion/general/1427618-proper-statistical-procedure-for-repeated-rcts-on-the-same-group-without-replacement) | 2018/01/17 | [
"https://stats.stackexchange.com/questions/323482",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/64472/"
] | You could do a chi-square test of goodness of fit.
This is explained on this page: <http://stattrek.org/chi-square-test/goodness-of-fit.aspx?Tutorial=AP>
So, let's see what your expected value is. There's always 0 days after a marketing event, but there may seldom be 5 days after a marketing event (if the marketing events often occur 3 days apart). So, we might end up with an uneven number of possible days since event. The number of days can be percentaged and applied to the data so we get an expected number of the 102 calls (I wanted to use a number different than 100, for clarity).
[![enter image description here](https://i.stack.imgur.com/1jpiM.jpg)](https://i.stack.imgur.com/1jpiM.jpg)
Since the days data are ordinal (4 days is longer than 3 days, etc.) you could also use a Kolmogorov-Smirnov one-sample test. | Categorizing your data (2<=x<=4) needs some theory to support it. Is there a marketing theory that says calls in this region are optimal? If so, you could do a multiple regression analysis with planned contrasts. |
1,896,468 | I am working on a project which needs to insert the member birthday's into MySQL database. But i am confused. Actually i am using it like that:
int(10)
So i change the format e.g. "27/06/1960" to unix time using PHP and use the function date() to show the birthday. Is there any better solution? and is there any good resource you recommend to read about "DATE, DATETIME, TIMESTAMP"?
Thanks. | 2009/12/13 | [
"https://Stackoverflow.com/questions/1896468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180685/"
] | The fastest way to find out when somebody birthday is would be to use 2 or 3 separate INT columns and probably an addition column to store the whole thing as a DATETIME. While you don't normally use ints nor multiple columns to represent date, keep in mind if you have a lot of rows in this table, doing something like
```
SELECT * FROM people WHERE birthday LIKE '%-12-24';
```
is not very efficient. It works fine in smaller datasets but become slow if we start getting into large datasets (depends on your hardware). Sometimes you need to store data in unusual ways to keep your system efficient, the tiny amount of HD space you waste by having up to 4 sets of date columns (month, day, year, and store the whole thing as a datestamp) pays off in speed.
By doing this you can simply do:
```
SELECT * FROM people WHERE birth_month=12 AND birth_day=24
``` | Use a DATE column. MySQL expects input as "YYYY-MM-DD" and outputs values like that.
A date that was not (yet) provided by user may be encoded as a NULL column. Though you may not need the extra bit that the "NULL" requires, you may even write the special value "0000-00-00" for that. |
26,449,109 | I am trying to develop a simple mode for codemirror.
This mode will colour paragraphs alternatively in blue and green. A separation between paragraph is an empty line or a line containing only spaces.
Here is a version of the code that works, but with the big issue that empty lines are not detected:
```
CodeMirror.defineMode("rt", function() {
return {
startState: function() {return {state1: true};},
token: function(stream, state) {
if (stream.match(/\s\s*/)!=null){ # this fails to detect empty lines
state.state1 = !state.state1;
}
stream.skipToEnd();
if (state.state1) { return "status1"; }
return "status2";
}
};
});
```
if I apply it to the following text:
```
line 1
line 2 # the next line is just a backspace and is not detected
line 3
line 4 # the next line is a few spaces followed by a backspace, it is detected
line 5
line 6
```
it colors from line 1 to line 4 in one color and line 5 to line 6 in another, which is expected.
I am trying to find a way to update my code so that it detects the empty line between line 2 and line 3. Any way to do this ? | 2014/10/19 | [
"https://Stackoverflow.com/questions/26449109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1484601/"
] | ```
/url\(([^"']+?)\)|'([^'"]+?)'\)|"([^'"]+?)"\)/g
```
Try this.Grab the captures.See demo.
<http://regex101.com/r/qQ3kG7/1> | Try this:
```
var results = str.match(/url\(['"]?[^\s'")]+['"]?\)/g)
.map(function(s) {
return s.match(/url\(['"]?([^\s'")]+)['"]?\)/)[1];
});
```
[Demo](http://jsfiddle.net/yw3n2aaw/) |
338,405 | I have a layer file which I use as reference for symbology for future layers. It is based on unique values, however there is over 100 unique values, and each one have their own icon.
If I apply this symbology to a small layer, its legend or symbology table will have over 100 items, even if the layer only uses 3-4 symbols.
Is there a way to remove all icons that are not been used in that layer?
ArcGIS Pro has a button called Add Unlisted value, and I'm looking for the exact opposite: remove all unlisted values. | 2019/10/10 | [
"https://gis.stackexchange.com/questions/338405",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/150721/"
] | In ArcGIS Pro, try checking the "Only show features visible in the map extent" box, which can be found under Feature Display Options menu. This will make it so that only things that appear in the current map extent are displayed in your legend.
<https://pro.arcgis.com/en/pro-app/help/layouts/work-with-legend-items.htm> | In layout view, click on the legend item. This opens the Format Legend Item area where there is an to "Only show features visible in the map extent". |
17,727,101 | I have the following code:
```
g = lambda a, b, c: sum(a, b, c)
print g([4,6,7])
```
How do I get the lambda function to expand the list into 3 values? | 2013/07/18 | [
"https://Stackoverflow.com/questions/17727101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2089675/"
] | Expand the list t0 3 values can be done by this:
```
g(*[4,6,7])
```
But the `sum` won't work in your way.
Or you can write this way:
```
>>> g = lambda *arg: sum(arg)
>>> print g(4, 5, 6)
15
>>>
```
Or just make your lambda accept a list:
```
g = lambda alist: sum(alist)
print g([4,6,7])
``` | If your lambda expects to have a list/tuple of fixed length passed in, but wants to expand the values in that list/tuple into separate parameter variables, the following will work.
```
g = lambda (a, b, c): a + b + c
g([4, 6, 7])
```
Note the parentheses around the parameter list.
This "feature" works in Python 2.x, but was removed in Python 3 |
4,289,629 | Is it normal for methods with a question mark to return something that's truthy (for example, a number) to indicate that something is true, or should `true` itself be returned?
Are there any examples of truthiness being used in the Ruby standard library or by Rails, for example?
**Background:** Someone wrote a `String#int?` method in [an answer to a separate question](https://stackoverflow.com/questions/4282273/does-ruby-1-9-2-have-an-is-a-function/4282449#4282449), which returned an integer to represent true, and `nil` to represent false. Another user was surprised at not returning a boolean. | 2010/11/27 | [
"https://Stackoverflow.com/questions/4289629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38765/"
] | It is *usual* for methods ending with `?` to return either `true` or `false` but it is not systematic and no core method will assume it.
An example in the core classes is `Numeric#nonzero?` which *never* returns `true` or `false`.
```
42.nonzero? # => 42
```
The library `Set` has `add?` and `delete?` too. I wish `Enumerable#one?` returned `nil` or `false` to distinguish cases where the count is zero from when it is greater than one.
A similar example are the comparison operators (`<`, `>`, ...), which usually return only `true` or `false`. Here again exceptions exist for `Module`'s operators that will return `nil` instead when the two modules are not related:
```
Array > Enumerable # => false
Array > Fixnum # => nil
``` | I renamed the method in question to remove the `?`, which was really not important to the question being answered. Scanning through the core functions that end in ?s, the only ones I spotted that returned data or nil were the `add?` and `delete?` methods on Set. |
12,283,436 | I'm working on a wikipedia reader where I want the user to be able to share the article he is reading to a friend using NFC. I dont want to be able to open these intents or anything fancy like that, just allow the friend to open up the url in the browser of his choice. I'm using a webview so getting ahold of the url won't be hard.
I've been searching the internet for some kind of example that is this easy but I haven't found anything simple enough. Do any of you have any recommendations for tutorials or examples? | 2012/09/05 | [
"https://Stackoverflow.com/questions/12283436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1468731/"
] | It's really easy. To share something via Android Beam, you have to create a so-called NDEF message. An NDEF message contains one or more records, which have a specific type (e.g. URI, text, MIME type, etc.) and contain the data you want to share.
Add this piece of code somewhere in the Activity that shows the URL you want to share and make sure it is called whenever the URL changes:
```
NfcAdapter nfc = NfcAdapter.getDefaultAdapter(this);// (only need to do this once)
if (nfc != null) { // in case there is no NFC
// create an NDEF message containing the current URL:
NdefRecord rec = NdefRecord.createUri(url); // url: current URL (String or Uri)
NdefMessage ndef = new NdefMessage(rec);
// make it available via Android Beam:
nfc.setNdefPushMessage(ndef);
}
``` | You should look at UriRecord or AbsoluteUriRecord, or even you can try an Android Application Record if you can find the one which launches the browser(?). And you should look into beam - there is a project boilerplate in the download sections [here](http://code.google.com/p/nfc-eclipse-plugin/) (shameless plug) :-) You might want to experiment with getting the desired effect using a tag first. |
39,578 | I want to get 2 columns from another list and merge these columns. But when I am trying to do this via Lookup, they are not shown under "Add a column to show each of these additional fields".
But when I tried a simple text one (not lookup) it is shown.
Is there anyway to show a column which a kind of lookup field? | 2012/06/27 | [
"https://sharepoint.stackexchange.com/questions/39578",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/9035/"
] | It was very annoying not be able lookup currency column,
however I found this workaround that worked in SP 2013.
1. Create calculated column of type "Single Line"
2. Use formula to format text as currency `=TEXT([Price],"$0.00;($0.00)")`
3. Now this new column can be referenced as secondary column and visible in the list. | I found a work around for this, what you do is use a wf to move the column into a text field. Go the origional list that has the information you'd like to look up. Creat a new text column and give it a name similar to the one you would like to dupilicate. Then create a WF to auto-populate that column into a text field. You can then look that column up in any other list. |
19,487 | I am planning to test a filesystem.
What all should i consider to do. or how to accomplish the same.
Are there are any tools to test a filesystem or any reliable references?
Purpose: Planning to shift from ext3 to EFS. | 2009/06/04 | [
"https://serverfault.com/questions/19487",
"https://serverfault.com",
"https://serverfault.com/users/360512/"
] | Don't just test for speed, also consider reliability. Try to, e.g., power down disks on a busy filesystem and see what's left.
The quality of the repair and recovery tools available is also important, and very hard to test discretely. Block structure may e.g. inhibit tools that try to salvage data in raw mode from a unsalvageable filesystem.
For more hints on testing a filesystem under very harsh beatings you may be interesting what the ZFS guys did: [One](https://web.archive.org/web/20130526102119/https://blogs.oracle.com/bill/entry/zfs_and_the_all_singing) [Two](https://github.com/openzfs/openzfs/tree/master/usr/src/test/) | While [bonnie++](http://www.coker.com.au/bonnie++/) is primarily focused on bench-marking performance it does work above the filesystem. It performs some tests that give different results per-filesystem. I suspect you are probably interested in the change in performance related to EFS as well, so you may want to try that at least as one of your tests. |
322,291 | How to stop the Tomcat 6.0 server ?
Under bin direcctory it has got only 4 files namely
bootstrap, tomcat6 , tomcat6w , tomcat-juli
Under TaskManager also , Windows Processes also , there is nothing related to tomcat
How can we stop the server instance now (I need to stop it as i modified some web.xml file ) | 2011/10/17 | [
"https://serverfault.com/questions/322291",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | Depends on how you started it.
If you started it by `startup.bat`, just use `shutdown.bat` which reside in the very same folder.
If it's started as Windows service (why have you by the way installed it as a Windows service if your intent is apparently to develop with it, not to run in production?), then you should restart the Windows service by service manager (start > run > services.msc). | If tomcat 6 on windows is started as a service with a diffeernt name, you have to copy tomcat6w.exe to servicenamew.exe. Then it will find it. Don't forget the w. For example, i have a tomcat6 that runs as "talend\_tac". I had to copy tomcat6w to talend\_tacw.exe, then it would control the service. |
65,005,506 | How to execute the form submit in Button click using ICommand
How to pass parameter in ICommand execute
```
@using System.Windows.Input
<button @onclick="buttonClick"> Blazor Button</button>
@code {
private ICommand _command;
public ICommand Command
{
get => _command;
set => _command = value;
}
private void buttonClick()
{
this.Command?.Execute(null);
}
}
``` | 2020/11/25 | [
"https://Stackoverflow.com/questions/65005506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8204457/"
] | You can use `Row.fromSeq`:
```
val m = Map("com.project.name" -> "A", "com.project.age" -> "23")
val row = Row.fromSeq(m.toSeq)
```
or alternatively `Row(m.toSeq:_*)`
both giving `[(com.project.name,A),(com.project.age,23)]` | You can convert map into the dataframe as follows :
```
import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._
val input : Map[String,String] = Map("com.project.name" -> "A", "com.project.age" -> "23")
val df = input.tail
.foldLeft(Seq(input.head._2).toDF(input.head._1))((acc,curr) =>
acc.withColumn(curr._1,lit(curr._2)))
```
Now if you want to get the Row from the Dataframe you can get as follows :
```
val row = df.first
```
And if you want to see the names of the column you can get that as follows :
```
val columns = df.columns
``` |
60,292,616 | I am try to installing Chaincode, follow the tutorial of hyperledger. But when I try to run the command
`peer chaincode install -p chaincodedev/chaincode/sacc -n mycc -v 0`
The terminal gives error message
>
> Error: error getting chaincode deployment spec for mycc: error getting chaincode package bytes: failed to calculate dependencies: incomplete package: github.com/hyperledger/fabric-chaincode-go/shim
>
>
>
I see some other people got similar issue, but there is no answer yet. I am new to these stuffs, so any suggestions can be helpful. | 2020/02/19 | [
"https://Stackoverflow.com/questions/60292616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10514498/"
] | I solved it today:
After loging into CLI contaier execute the following command (import the shim package). This will import the package into cli container where the chaincode will be compiled.
go get github.com/hyperledger/fabric-chaincode-go/shim
then execute
peer chaincode install -p chaincodedev/chaincode/sacc -n mycc -v 0
It will work cheers. | In my case the reason was incorrect path. CLI container work dir has already `chaincodedev` part of the path
```
cli:
...
working_dir: /opt/gopath/src/chaincodedev
```
You can do following to validate if this is true in your case
```
docker exec -it cli bash
pwd
```
You have to see `/opt/gopath/src/chaincodedev`.
So all I needed to do is just remove `chaincodedev` from command path
```
peer chaincode install -p chaincode/sacc -n mycc -v 0
``` |
31,436 | Do you know any good GUI for pacman and arch? Where I could view packages installed and possible to install? And of course do anything as in pacman. | 2012/02/11 | [
"https://unix.stackexchange.com/questions/31436",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/1924/"
] | I think "PackageKit" is the best choise for Gtk's desktop, So for QT you can use "Appset-qt". | pacmanxg ... <https://bbs.archlinux.org/viewtopic.php?id=125872> |
2,661,065 | I'm looking for a good sorted list for java. Googling around give me some hints about using TreeSet/TreeMap. But these components is lack of one thing: random access to an element in the set.
For example, I want to access nth element in the sorted set, but with TreeSet, I must iterate over other n-1 elements before I can get there. It would be a waste since I would have upto several thousands elements in my Set.
Basically, I'm looking for some thing similar to a sorted list in .NET, with ability to add element fast, remove element fast, and have random access to any element in the list.
Has this kind of sorted list implemented somewhere?
Thanks.
**Edited**
My interest in SortedList grows out of this problems:
I need to maintains a list of many thousands object (and can grow up to many hundred of thousands). These objects will be persisted to database. I want to randomly select few dozens of element from the whole list. So, I tried to maintain a separated on-memory list that contains the primary keys (Long numbers) of all objects. I need to add/remove keys from the list when object is added / removed from database. I'm using an ArrayList right now but I'm afraid ArrayList would not suit it when the number of records grows. (Imagine you have to iterate over several hundred thousands of elements every time an object is removed from database). Back to the time when I did .NET programming, then I would use a sorted List (List is a .NET class that once Sorted property set to true, will maintain order of its element, and provide binary search that help remove/insert element very quick). I'm hoping that I can find some thing similar from java BCL but unluckily, I didn't find a good match. | 2010/04/18 | [
"https://Stackoverflow.com/questions/2661065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/244000/"
] | SortedList decorator from Java Happy Libraries can be used to decorate TreeList from Apache Collections. That would produce a new list which performance is compareable to TreeSet.
<https://sourceforge.net/p/happy-guys/wiki/Sorted%20List/> | What about using a `HashMap`? Insertion, deletion, and retrieval are all O(1) operations. If you wanted to sort everything, you could grab a List of the values in the Map and run them through an O(n log n) sorting algorithm.
**edit**
A quick search has found [LinkedHashMap](http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedHashMap.html), which maintains insertion order of your keys. It's not an exact solution, but it's pretty close. |
19,594,231 | we want to publish an update of our app. Is it possible to rename the app after the update? let's say the app is called **myApp** and I want it to be called **myApp 2** after the update... can it be done? | 2013/10/25 | [
"https://Stackoverflow.com/questions/19594231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862909/"
] | *In Build Setting*, You can change **Product Name**.
![enter image description here](https://i.stack.imgur.com/aOyJS.png) | For changing the apps name see <https://developer.apple.com/library/ios/qa/qa1625/_index.html>
However, the directory for the app's data will change as well. If you want to move some data, you can find the directory used by the simulator e.g. with:
NSString \*homeDir = NSHomeDirectory(); NSLog(@"%@",homeDir);
before and after renaming and use 'Go to Folder' in finder to get there. |
2,807,502 | I have [this](http://pastebin.org/219615) ASP.NET page with ASP.NET UpdatePanel and jQueryUI droppable and sortable components. The page works fine in all browsers, but doesn't in Internet Explorer (IE8 tested).
After I try to call ASP.NET AJAX event (by pressing my asp.net button inside the UpdatePanel) my sortable list stops working properly inside IE browser and the browser throws the following error:
>
> Message: Unspecified error.
> Line: 145
> Char: 186
> Code: 0 URI: <http://code.jquery.com/jquery-1.4.2.min.js>
>
>
>
I found out that the problem is caused by the code on line 66:
```
$("#droppable").droppable();
```
If I comment it out, the sortable list works fine after ajax postbacks. But it doesn't make sense.
Does anyone know what could be wrong?
Thanks.
P.S. I am using jQueryUI **1.8.1** and jQuery **1.4.2** | 2010/05/11 | [
"https://Stackoverflow.com/questions/2807502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136666/"
] | I believe this is a bug in JQuery - I think there is a fix where you redefine the offset function to work under IE:
<http://dev.jqueryui.com/ticket/4918>
Cheers | The solution
```html
<%@ Page Language="C#" AutoEventWireup="true" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style type="text/css">
#sortable
{
list-style-type: none;
margin: 0;
padding: 0;
border: solid 1px #999999;
}
#sortable li
{
margin: 0.3em 0.3em 0.3em 0.3em;
padding-left: 1.5em;
font-size: 1em;
height: auto;
border: dotted 1px #999999;
background-color: #dddddd;
}
#sortable li:hover
{
background-color: #aaaaaa;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="srptManager">
<Scripts>
<asp:ScriptReference Path="http://code.jquery.com/jquery-1.4.2.min.js" />
<asp:ScriptReference Path="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js" />
</Scripts>
</asp:ScriptManager>
<asp:UpdatePanel ID="updPanel" runat="server">
<ContentTemplate>
<ul id="sortable">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
<div id="droppable" style="background-color: black">
Drop Here</div>
<asp:Button runat="server" ID="btnAjaxRefresh" Text="Go" />
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
// *******Solution Here*******
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
jqueryStuff();
}
}
function BeginRequestHandler(sender, args) {
$("#sortable").sortable("destroy");
$("#droppable").droppable("destroy");
}
function jqueryStuff() {
$(document).ready(function() {
$("#sortable").disableSelection();
$("#sortable").sortable();
// ******Problem at this line******
$("#droppable").droppable();
});
}
jqueryStuff();
</script>
</form>
</body>
</html>
``` |
55,096,252 | Assume we have a dataset like:
```
a: 1,2,3,5,6
b: 4,1,2
c: 1,4
```
Now we want to transform this dataset to:
```
1: a,b,c
2: a,b
3: a
4: b,c
5: a
6: a
```
This transform could be done by a dictionary but is there a way to do this more efficiently
Currently I do as below:
```
uFile = open("t/u.txt","r")
uDic = dict()
for cnt1, line in enumerate(uFile):
lineAr = line.strip().split(' ')
for item in lineAr:
if item not in uDic.keys():
uDic[item] = []
uDic[item].append(cnt1)
```
And then save the output. | 2019/03/11 | [
"https://Stackoverflow.com/questions/55096252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4716337/"
] | Use defaultdict for this:
```
from collections import defaultdict
d = {'a': [1, 2, 3, 5, 6], 'b': [4, 1, 2], 'c': [1, 4]}
o = defaultdict(list)
for k, v in d.items():
for vv in v:
o[vv].append(k)
print(dict(o))
{1: ['a', 'b', 'c'],
2: ['a', 'b'],
3: ['a'],
5: ['a'],
6: ['a'],
4: ['b', 'c']}
``` | I would go with a simpler way as following:
```
In [2]: d
Out[2]: {'a': [1, 2, 3, 5, 6], 'b': [4, 1, 2], 'c': [1, 4]}
In [3]: dd = {}
In [4]: for k,v in d.items():
...: for e in v:
...: val = dd.get(str(e), [])
...: dd[str(e)] = val + [k]
...:
In [5]: dd
Out[5]:
{'1': ['a', 'b', 'c'],
'2': ['a', 'b'],
'3': ['a'],
'5': ['a'],
'6': ['a'],
'4': ['b', 'c']}
```
This link may help to understand why the keys are turned into `strings`:
[why-must-dictionary-keys-be-immutable](https://docs.python.org/3/faq/design.html#why-must-dictionary-keys-be-immutable) |
35,278,621 | I am using the Facebook Javascript SDK to enforce that users who access my site must be logged into Facebook. I'm using the function *StatusChangeCallback* to redirect visitors to a Facebook login page if they aren't logged into Facebook. I have copied a snippet of my script below, which is in the Head tag of my web page.
This works fine, except that I notice that my page loads momentarily before the script redirects the visitors to a login page. That means that visitors can click the "Stop" button and bypass this redirect functionality.
**Is there a way to prevent the page from loading until after my Facebook login script has completed?**
```
<script>
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
if (response.status === 'connected') {
//Continue loading the page
} else if (response.status === 'not_authorized') {
window.location.href = "facebook.html";
} else {
window.location.href = "facebook.html";
}
}
``` | 2016/02/08 | [
"https://Stackoverflow.com/questions/35278621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5900211/"
] | I don't know if a generator itself can be recursive.
Will M [proved me wrong](https://stackoverflow.com/a/35279624/1187415)!
Here is a possible implementation for a pre-order traversal, using a stack for the child nodes which still have to be enumerated:
```
extension XMLNode : SequenceType {
public func generate() -> AnyGenerator<XMLNode> {
var stack : [XMLNode] = [self]
return anyGenerator {
if let next = stack.first {
stack.removeAtIndex(0)
stack.insertContentsOf(next.childNodes, at: 0)
return next
}
return nil
}
}
}
```
For a level-order traversal, replace
```
stack.insertContentsOf(next.childNodes, at: 0)
```
by
```
stack.appendContentsOf(next.childNodes)
``` | While Martin's answer is certainly more concise, it has the downside of making a lot of using a lot of array/insert operations and is not particularly usable in lazy sequence operations. This alternative should work in those environments, I've used something similar for `UIView` hierarchies.
```
public typealias Generator = AnyGenerator<XMLNode>
public func generate() -> AnyGenerator<XMLNode> {
var childGenerator = childNodes.generate()
var subGenerator : AnyGenerator<XMLNode>?
var returnedSelf = false
return anyGenerator {
if !returnedSelf {
returnedSelf = true
return self
}
if let subGenerator = subGenerator,
let next = subGenerator.next() {
return next
}
if let child = childGenerator.next() {
subGenerator = child.generate()
return subGenerator!.next()
}
return nil
}
}
```
Note that this is preorder iteration, you can move the `if !returnedSelf` block around for post order. |
56,109,891 | I made a GUI with Tkinter in python 3. Is it possible to close the window and have the application stays in the Windows System Tray?
Is there any lib or command within Tkinter for this. | 2019/05/13 | [
"https://Stackoverflow.com/questions/56109891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11490650/"
] | If your controller path is `/App/Http/Controllers/API`, you need to adjust it's namespace :
```php
namespace App\Http\Controllers\API;
```
If your controller path is `/App/Http/Controllers`, you need to adjust your routes:
```php
Route::post('login', 'UserController@login');
``` | **1**. Copy the existing functions of your controller and delete it.
**2**. Recreate your controller but this time specifying the location of were you want to place it, in the Controllers directory. e.g.
php artisan make:controller NameOfYourSubFolder\YourControllersName
**3**. Paste you functions. |
16,990,782 | I'm very new to GAE/Java/Maven and coming from a .net background, is eager to try it out.
I've installed the Google App Engine plugin for eclipse 4.2. I created an application using the Google plugin, and everything went according to plan. It works nicely. I can develop, test on local server and deploy to the cloud without any hassles.
Problem comes in when I would like to use Maven as well - Then you need to create a 'Mavern project' based on some archetype. I've followed the tutorial at: <https://developers.google.com/appengine/docs/java/tools/maven>, and started to create the 'guestbook' application.
All went according to plan. I can run the dev server from the command line and test the application in a browser. Only problem is - this is where the tutorial ends.
I have no idea how to deploy this to the Google Cloud from the command line. You can't use the Google plugin anymore either since it just doesn't recognize the application as an 'AppEngine' app.
Can someone please help me out here? Thanks | 2013/06/07 | [
"https://Stackoverflow.com/questions/16990782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The best way is to use *Maven Goals* from the command line. From the Google Documentation for [Deploying a Java App](https://cloud.google.com/appengine/docs/standard/java/tools/uploadinganapp):
>
> If you are using the App Engine SDK-based Maven plugin, use the
> command:
>
>
>
> ```
> mvn appengine:update
>
> ```
>
> If you are using the Cloud SDK-based Maven plugin, use the command:
>
>
>
> ```
> mvn appengine:deploy
>
> ```
>
>
The Cloud SDK-based plugin is more current and you should ideally be using it (which means using `mvn appengine:deploy`).
[Documentation for mvn appengine:deploy](https://cloud.google.com/appengine/docs/flexible/java/maven-reference#appenginedeploy) | I tried to follow the document and use maven for upload new code, the command run without error and can run at local but it does not affect the app on google cloud. I went to dashboard of the project, I found under tab versions there are some instance include the new one. At this tab I found I made a mistake with app version, in my case I have 3 version. I migrate traffic to the lasted one, and everything work fine. |
6,256,552 | I have found only
<http://ispras.linux-foundation.org/index.php/API_Sanity_Autotest>
because it is listed on Wikipedia. Is there any other Sanity suite for C++? | 2011/06/06 | [
"https://Stackoverflow.com/questions/6256552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/48465/"
] | The simplest way to check this is with a [regular expression](http://www.regular-expressions.info/):
```
function(str){
return /^[A-Z]/.test(str);
}
```
returns `true` when the input string starts with a capital, false otherwise. (This particular regular expression - the bits between the // characters - is saying, 'match the start of the string followed by any single character in the range A-Z'.)
In terms of your HTML above, we'll need the contents of the validate() function to determine where the regex match needs to go. | This will check to see if the username entered starts with a capital letter, and is followed by 5 - 24 alphanumeric characters.
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
function validate() {
var the_input = document.getElementById('userName').value;
if (!the_input.match(/^[A-Z]([A-Z]|[a-z]|[0-9]){5,24}$/)) {
alert('Your username must begin with a capital letter, and contain between 6 and 25 alphanumeric characters.');
return false;
} else {
alert('Welcome!');
return true;
}
}
</script>
</head>
<body>
<form action="http://www.cknuckles.com/cgi/echo.cgi" method="get" name="logOn">
User Name:<br />
<input type="text" name="userName" id="userName" size="25" /><br />
Password:<br />
<input type="password" name="pw" size="25" /><br />
<input type="submit" value="Log In" onclick="return validate();"/>
</form>
</body>
</html>
```
As an aside, it should be noted that this will not work if the user has javascript turned off - you may wish to have some server-side validation instead (or in addition) as a fail-safe. |
45,098,535 | I have 2 views.
1)MyMenuRestaurent.axml 2) ImageAndSubTitle.axml
code for MyMenuRestaurent.axml
```
<LinearLayout>
<ListView>
</ListView>
</LinearLayout>
```
Code For Image And Sub Title
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/lightgray">
<ScrollView
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1"
android:backgroundTint="#ff81d4fa">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dip">
</LinearLayout>
<TextView
android:id="@+id/Text1"
android:text="Demo Item Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/blue"
android:textSize="20dip" />
<TextView
android:id="@+id/Text2"
android:text="Demo Price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14dip"
android:textColor="@color/blue" />
</TableLayout>
</ScrollView>
</LinearLayout>
```
I have listview clickable. when click on one item detail of individual item is opened. but if i add scroll view (click) is not working. because scroll view block click on element. i want to make click on item along with scroll view. | 2017/07/14 | [
"https://Stackoverflow.com/questions/45098535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8187944/"
] | It's likely `docker run` did work, but since you did not specify any command to run, the container stopped working just after starting. With `docker ps -a` you should see some exited ubuntu containers.
If you run the container as daemon (`-d`) and tell it to wait for interactive input (`-it`) it should stay running. Hence `docker run -d -it ubuntu` should do what you want. | I did not understand the question correctly. What you want to do is bash connection maybe parameter to execute is incorrect
```
sudo docker run -t -i /bin/bash ubuntu
```
Go for it |
9,299,717 | I am trying to run some javascript (toggleClass) only if the clicked menu link has a submenu. Is this possible? Thanks in advance for your help.
```
$('#nav a').click(function () {
if (???) {
$(this).toggleClass('sf-js-enabled');
}
});
``` | 2012/02/15 | [
"https://Stackoverflow.com/questions/9299717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1149767/"
] | ```
$('#nav a').click(function () {
// Proceed only if children with your submenu class are present
if ($(this).find('.submenuClass').length > 0) {
$(this).toggleClass('sf-js-enabled');
}
})
``` | Try this.
```
$('#nav a').click(function () {
if ($(this).find('submenuSelector').length) {
$(this).toggleClass('sf-js-enabled');
}
})
```
Alternatively you can use `has(selector)` method which reduces the set of matched elements to those that have a descendant that matches the selector or DOM element.
```
$('#nav a').click(function () {
//Do other suff here
if ($(this).has('submenuSelector').length) {
$(this).toggleClass('sf-js-enabled');
}
})
``` |
20,506,612 | I am reading "Python programming for the absolute beginner" and in there there is this piece of code:
```
@property
def mood(self):
unhappiness = self.hunger + self.boredom
if unhappiness < 5:
m = "happy"
elif 5 <= unhappiness <= 10:
m = "okay"
elif 11 <= unhappiness <= 15:
m = "frustrated"
else:
m = "mad"
return m
```
All it does is calculate on-the-fly and return the calculation. It doesn't provide access to a private attribute or any attribute of the class. Is this better as property rather than method? | 2013/12/10 | [
"https://Stackoverflow.com/questions/20506612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2870783/"
] | It's just a matter of taste.
A property is used where an access is rather cheap, such as just querying a "private" attribute, or a simple calculation.
A method is used where a rather "complicated" process takes place and this process is the main thing.
People are used to using getter and setter methods, but the tendency is used for useing properties more and more.
Take, as an example, the `Serial` class of `pyserial`. It has - as a heritage - methods such as `getBaudRate()` and `setBaudRate()`, but recommends to use `baudrate` as a reading and writing property for querying and setting the baud rate. | It's essentially a preference. It allows you to type `object.property` rather than `object.property()`.
So when should you use which? You have to use context to decide. If the method you have returns a value based upon properties of the object, it saves you the time of creating a variable and setting it equal to some generator method (example: `property = object.generateProperty()`. Doesn't it make more sense to just skip this step, and make `generateProperty()` a property of its own?
This is the general concept as I understand it. |
7,727,142 | Can anyone tell me what this is:
```
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js ie ie6" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="no-js ie ie7" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="no-js ie ie8" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js iframe" lang="en"> <!--<![endif]-->
```
I have seen this on so many pages but there is no JavaScript link on some of the pages to support the document declaration. | 2011/10/11 | [
"https://Stackoverflow.com/questions/7727142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/596952/"
] | Those are only checks for compatibility with older browsers
`<!DOCTYPE html>` usually refers to HTML5, browsers below IE9 don't support HTML5 at all, so tweaks are needed. That's why there are HTML if-clauses that check if you use IE and which version. The HTML element gets a special class for that browser version so that CSS can see if it's IE and in which version (e.g. for fixing the box model of IE6)
The no-js class probably gets removed by JavaScript so that CSS can access specific elements only if JavaScript is on/off | You should use this as your Doctype: `<!DOCTYPE html>`
The rest is not relevant for the doctype, and is IE-specific. |
68,612,455 | I've been experimenting with for loops, mostly with a condition 'less than or equal'. However, I wanted to make the condition of a for loop so that the number in the initialization is bigger than that one in the condition. When I ran the code, it didn't work. And when I added the bigger than or equal operator, it crashed; here's the code:
```
//loop n1
for (let i = 0; i > 4; i++) {
console.log(i);
}
//loop n2
for (let i = 0; i >= 4; i++) {
console.log(i);
//loop n3
for (let i = 0; i = 4; i++) {
console.log(i);
```
None of these worked, and the last one crashed. I don't get it; according to my logic, loop n3 should have stopped when "i" is equal to 4, but no, it crashed. And loop n1 should've stopped when "i" is more than 4.
Can anybody explain this to me?
Thanks | 2021/08/01 | [
"https://Stackoverflow.com/questions/68612455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15453757/"
] | ```
for will run while condition is true
// will exit right away, i is smaller then 4
for (let i = 0; i > 4; i++) {
console.log(i);
}
// will exit right away, i is smaller then 4
for (let i = 0; i >= 4; i++) {
console.log(i);
}
// will exit right away, i is smaller then 4
for (let i = 0; i === 4; i++) {
console.log(i);
}
``` | The issue you're encountering is that the condition needs to resolve to "*true*" in order for the loop to continue. Let's run through your examples...
For the first one, you start with **i** is equal to zero (**0**), and then test for **i** being greater than four (**4**). Well, zero (**0**) is less than four (**4**). That immediately fails and the loop does not execute.
For the second one, again you start with **i** equal to zero (**0**), and your condition of **i** being greater than or equal to four (**4**) still fails.
In your third example, it's still pretty much the same as the previous two because zero (**0**) is not equal to four (**4**).
For your **for** loops to successfully execute, the condition statement has to return "*true*" for at least the first value that your iterator (in this case the variable **i**) is set to. If you want to try a loop that works, for the first two examples you can change the "greater than" (***> / >=***) to "less than" (***< / <=***) and then it will run. Or, if you change the value of **i** to be four (**4**) or greater than four, and change your incrementing statement from "*i++*" to "*i--*", that would also allow it to run. For your final example, something like that would be far better off being done as an **if** statement instead of a **for** loop. |
2,934,832 | I have a page in which there are multiple hrefs. i want to find out which href is clicked and based on that href click I want to show and hide a div? | 2010/05/29 | [
"https://Stackoverflow.com/questions/2934832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/324831/"
] | I'm going to assume you have control over the href's here and you want to have the simplest markup possible, in that case you can do something like this:
```
<a href="#div1">Toggle Div 1</a>
<a href="#div2">Toggle Div 2</a>
<div id="div1" class="toggleDiv">Div 1 Content</div>
<div id="div2" class="toggleDiv">Div 2 Content</div>
```
Then to open/toggle a div based on the `href`, or more specifically the `hash` property, you can do this:
```
$("a").click(function() {
$(".toggleDiv").not(this.hash).hide();
$(this.hash).toggle('fast');
});βββ
```
This toggles the corresponding `<div>` with the matching `ID == href` minus the hash and hides the other `<div>` elements if that's what you're after...you do this by just giving them a common class and hide all those except the one related to the current link.
[You can view a demo here](http://jsfiddle.net/aYEUG/) to see if it's what you're after. | This should give you something to start with:
```
$('a').click(function()
{
var href = this.href;
// Show/hide your div.
return false;
});
```
Just implement your logic in the `click` handler function. |
191,835 | I was reviewing an application for a grant and found out that one of the applicants has included a publication on his CV that does not exist in the journal. It was supposedly published several years ago. I counterchecked the list of publications of that particular journal, including the issue and volume, but it's non-existent. I also googled the title and checked the Google Scholar account of the applicant -- the paper could not be found.
Is this an academic offense? How can I investigate further, and what should I do if I am ultimately unable to find any proof of this paper's existence? | 2022/12/21 | [
"https://academia.stackexchange.com/questions/191835",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/78095/"
] | You only really have a few options, if the granting institution is "typical".
1. Your best option is to contact the person coordinating the review with your concern (in the NIH hierarchy, that may be a program officer or scientific review officer).
2. You can ignore the issue.
3. You can hold hold on to the issue, saving it for synchronous discussion if the review panel functions that way (I suspect anyone else on the panel would be miffed that you didn't raise the issue with the review officer if you did that, and the review officer would probably not be happy either)
FWIW, if a grant reviewer contacted me [the applicant] in any way about the review of one of my grants during the review period, I would immediately contact the Scientific Review Officer for the study section, and maybe (after reading up on the rules) the study section chair. I'd probably request that the reviewer be placed in conflict for the grant, which means (for the NIH, anyway) that the reviewer would not even be allowed to be in the room for the review, let alone submit anything in writing that the rest of the panel had access to. I suspect that request would be honored. I also suspect that, at the very least, the panel administrators would explain the error of their ways to the reviewer involved (at the very least).
Sitting on top of this analysis is the realization that many people in the room are looking for an excuse to assign a grant an unfundable score (not that I approve of that), and raising this issue during the review may well poison the grant for funding. | For clarification, you may consider asking the applicant directly. There might be a silly explanation that avoids all confusion.
Of course, depending on the answer of the applicant, you may take the necessary steps.
Claiming something that doesn't exist is of course a very serious academic offense. That is why you should not hesitate asking applicants in case you have doubts or things do not add up. Something polite along the lines "We were checking your CV and we were wondering where we can find your such-and-such publication."
Edit: I answered without looking at the comments. I still believe that directly contacting the author, either personally or through some other channels of the university (e.g. secretary) is possibly the only course of action that can clarify things at this point. |
2,205,128 | I am trying to create HTTP connection using AsyncTask class.
Is it possible to create HTTP connection ?
Can you suggest sample source code ?
Thanks in advance. | 2010/02/05 | [
"https://Stackoverflow.com/questions/2205128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164589/"
] | As an inner class inside your activity :
```
public final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
private HttpClient mHc = new DefaultHttpClient();
@Override
protected String doInBackground(String... params) {
publishProgress(true);
// Do the usual httpclient thing to get the result
return result;
}
@Override
protected void onProgressUpdate(Boolean... progress) {
// line below coupled with
// getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS)
// before setContentView
// will show the wait animation on the top-right corner
MyActivity.this.setProgressBarIndeterminateVisibility(progress[0]);
}
@Override
protected void onPostExecute(String result) {
publishProgress(false);
// Do something with result in your activity
}
}
```
Then somewhere in your activity :
```
new HttpTask().execute(someParams...);
``` | i think this may help u...
<http://androidbeginner.blogspot.com/2010/01/communication-with-httprequest.html>
Atul yadav |