source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"wordpress.stackexchange",
"0000195377.txt"
] | Q:
Chrome Version 44.0.2403.89 m is trying to force HTTPS
With the release of Chrome Version 44.0.2403.89 m, I've noticed that our site is now completely broken. All of the HTTP URLs are being redirected to HTTPS URLs, which is a problem because our site does not support HTTPS.
Please note, this is not happening in any other browser, and was working on the previous Chrome release.
I've tried to replace all of our stylesheet calls with relative links, and that has worked, but the images that are loaded in automatically or through absolute paths as well as the navigation is still broken. Please see below image for the error page that is thrown when navigating, after accepting the security warning and proceeding.
Anyone have any advice as far as updating perhaps the .htaccess file goes, or something in functions?
Thanks.
A:
Solution 1:
Enable mod_header on the server and added this rule to my appache2.conf file:
<IfModule mod_headers.c>
RequestHeader unset HTTPS
</IfModule>
Solution 2:
Or you need to add the code to fonction.php file of your current theme:
function https_chrome44fix() {
$_SERVER['HTTPS'] = false;
}
add_action('init', 'https_chrome44fix',0);
A:
This seems to be a bug that affects only Apache which is sending the user value for the header HTTPS as unprefixed header HTTPS instead of HTTP_HTTPS.
You should be able to fix that with a simple plugin:
if ( empty ( $_SERVER['SERVER_SOFTWARE'] ) )
return;
if ( FALSE === stristr( $_SERVER['SERVER_SOFTWARE'], 'apache' ) )
return;
if ( empty ( $_SERVER['HTTPS'] ) )
return;
if ( '1' === $_SERVER['HTTPS'] )
$_SERVER['HTTPS'] = FALSE;
if ( '1' === $_SERVER['HTTP_HTTPS'] )
$_SERVER['HTTP_HTTPS'] = FALSE;
|
[
"stackoverflow",
"0022616782.txt"
] | Q:
Most appropriate way to load data from internet into listview
I have a simple query but have been picking my mind around a lot lately without a straight solution.
I have a listview with loads quote data from internet. The list item is a bit complex but that is not a problem . The listview is loaded using a loader which fetches the quote data from internet, parses the json and populates the VOs. The list of VOs is set in the adapter and the notifyDataSetChanged changed is called which reloads the list through the adapter's getView
now the pattern i have used here is:
user clicks a button, we open a fragment
the fragment has LoaderCallbacks and we initiate the loader in onActivityCreated
the loader has a cached Thread Pool executor (I cant use async loaders as they essentially use linear loading not parallel across the Android API versions) which creates a download worker for each stock.
the worker hits the url and downloads the data, parses the JSON using GSON, creates an object and puts it in the loader's arraylist.
Loader uses a latch to wait till all the quotes are downloaded.
once all are done the list is loaded.
My problem is that when the listview has a lots of stocks, like 70 to 90 the quote downloading process becomes slow. ON a direct wifi network it takes about 1.5 to 2 seconds for the list to load. On mobile data networks like 2G and 3G and Hybrids it takes about 30-40 seconds to load. Profiling shows majority time spend in reading data from stream. Each quote URL hit is about 700-800 bytes and takes about 800-900ms to load. I am using HttpURLConnection to load the URLs.
I cannot use the dynamic loading pattern in list as i have menu items to filter and sort the listview. They wont make any sense if we don't have all the quote data in the list in the first place.
is there any better way to do this? I have read the things around and have tried "new async task for each row in the list when that row becomes visible on screen" but cant use it as such as that would mean lazy loading of data.
Edit to show how the Data is deserialized:
InputStream inputstreamObj = (InputStream) conn.getContent();//getInputStream();
if(inputstreamObj != null){
Reader reader = new InputStreamReader(inputstreamObj);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(List.class, new CompanyCorpAnnouncementsVODeserializer());
Gson gson = gsonBuilder.create();
retVal = gson.fromJson(reader, List.class);
}
A:
Ok I am answering it myself.
There is no plausible way to achieve this. App design methodology needs to restrict the list size to a comfortable level. In my case i am shifting focus from 1 watch list of 100-150 stocks to multiple watch lists of 30 stocks each. Since i cant drop the filtering and sorting functionality so this is the only plausible way.
Additionally need to track network state changes and adjust the executor to single threaded from caching one. Go full throttle when wi-fi is on and display dialog or toast messages when mobile net is on.
|
[
"stackoverflow",
"0014735078.txt"
] | Q:
How to handle conditional data.frame subscripts that contain NAs?
Is there a way to have conditional subscripts if the conditional vector contains NAs?
Assume i have a data.frame like this
dframe <- data.frame(a=c(1,32,4,5,8),b=c(1,2,3,4,5),d=c(NA,5,5,10,9))
dframe[dframe$d > 9,"a"] <- NA
If it was not for the NA in dframe$d this would be straight forward. I have seen %in% syntax like here to get around NAs, but do not know how to manage it for conditions.
I can see that this is somewhat of a general problem, since I am not quite sure whether I want to obtain an NA for the missing value in the condition or something else.
But I am also interested to learn how people handle this situation.
In my specific situation in would simply be helpful when NA was treated like FALSE in the condition.
A:
You were close. You had the condition and %in%. Just not the link. It is straightforward actually. Just use %in% with TRUE it'll give back all other values, where as NA will be replaced with FALSE
dframe[(dframe$d > 9) %in% TRUE, "a"] <- NA
A:
You can just restrict your indexing to the non NA values
dframe[dframe$d > 9 & !is.na(dframe$d),"a"] <- NA
|
[
"gaming.stackexchange",
"0000122674.txt"
] | Q:
How can I get rid of this black hole in my minecraft world?
I have interesting bug that I have experienced before but has gone away on its own. This one is not going away though.
I have a giant stripe or chunks missing from my desert biome, I would say probably 7 chunks long.
I'm guessing the chunks are corrupted or something, what was hoping to figure is whether it can repaired or reverted.
Here is a picture of the problem.
A:
Reload your chunks
Press F3 + A
There is no step 2
failing that...
Reload Minecraft
Close Minecraft
Reopen Minecraft
failing that...
Use MCEdit.
Backup your world
Close Minecraft
Open the world in MCEdit
Using the chunk tool, completely delete the missing chunks
Save and close MCEdit
Reopen Minecraft and it will regenerate the missing chunks
|
[
"stackoverflow",
"0004057100.txt"
] | Q:
Undefined reference to member functions
I had just thought I resolved a problem, but it seemed another one cropped up--or at least the same problem in another form. Now when I try to rebuild everything as suggested in the answer to that question, all Qt Creator shows in build issues is a one line collect2: ld returned 1 exit status
Here's some of the compile output that I think might be relevant:
Running build steps for project Othello-cmd...
Starting: "C:/Qt/2010.05/mingw/bin/mingw32-make.exe" clean -w
[snipped]
C:/Qt/2010.05/mingw/bin/mingw32-make -f Makefile.Release clean
Could Not Find C:\Users\Amos Ng\My Dropbox\School\College\2010.. Fall\CS 3A\Othello-cmd-build-desktop\debug\main.o //this was in red
mingw32-make[1]: Entering directory `C:/Users/Amos Ng/My Dropbox/School/College/2010.. Fall/CS 3A/Othello-cmd-build-desktop'
del release\main.o release\board.o release\player.o release\referee.o release\misc.o release\humanplayer.o release\computerplayer.o release\chatter.o release\chatserver.o release\location.o
mingw32-make[1]: Leaving directory `C:/Users/Amos Ng/My Dropbox/School/College/2010.. Fall/CS 3A/Othello-cmd-build-desktop'
mingw32-make: Leaving directory `C:/Users/Amos Ng/My Dropbox/School/College/2010.. Fall/CS 3A/Othello-cmd-build-desktop'
Could Not Find C:\Users\Amos Ng\My Dropbox\School\College\2010.. Fall\CS 3A\Othello-cmd-build-desktop\release\main.o
//these next 3 lines are in blue
The process "C:/Qt/2010.05/mingw/bin/mingw32-make.exe" exited normally.
Configuration unchanged, skipping qmake step.
Starting: "C:/Qt/2010.05/mingw/bin/mingw32-make.exe" -w
mingw32-make: Entering directory `C:/Users/Amos Ng/My Dropbox/School/College/2010.. Fall/CS 3A/Othello-cmd-build-desktop'
[snipped]
//A bunch of lines similar to
g++ -c -g -frtti -fexceptions -mthreads -Wall -DUNICODE -DQT_LARGEFILE_SUPPORT -DQT_DLL -DQT_CORE_LIB -DQT_THREAD_SUPPORT -I"c:\Qt\2010.05\qt\include\QtCore" -I"c:\Qt\2010.05\qt\include" -I"c:\Qt\2010.05\qt\include\ActiveQt" -I"debug" -I"\\psf\Dropbox\School\College\2010.. Fall\CS 3A\Othello-cmd" -I"." -I"c: "filepath of .o file" "filepath of .cpp file"
g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-reloc -Wl,-subsystem,console -mthreads -Wl -o debug\Othello-cmd.exe object_script.Othello-cmd.Debug -L"c:\Qt\2010.05\qt\lib" -lQtCored4
//everything's red starting here...
./debug\board.o://psf/Dropbox/School/College/2010.. Fall/CS 3A/Othello-cmd/board.cpp:29: undefined reference to `OPiece::OPiece(int)'
./debug\board.o://psf/Dropbox/School/College/2010.. Fall/CS 3A/Othello-cmd/board.cpp:39: undefined reference to `OPiece::flip()'
./debug\board.o://psf/Dropbox/School/College/2010.. Fall/CS 3A/Othello-cmd/board.cpp:76: undefined reference to `OPiece::display()'
./debug\board.o://psf/Dropbox/School/College/2010.. Fall/CS 3A/Othello-cmd/board.cpp:110: undefined reference to `OPiece::display()'
./debug\board.o://psf/Dropbox/School/College/2010.. Fall/CS 3A/Othello-cmd/board.cpp:159: undefined reference to `OPiece::OPiece(int)'
//couple more lines just like the above
collect2: ld returned 1 exit status
//...finally things are black again
mingw32-make[1]: Leaving directory `C:/Users/Amos Ng/My Dropbox/School/College/2010.. Fall/CS 3A/Othello-cmd-build-desktop'
mingw32-make: Leaving directory `C:/Users/Amos Ng/My Dropbox/School/College/2010.. Fall/CS 3A/Othello-cmd-build-desktop'
//everything's red again
mingw32-make[1]: *** [debug\Othello-cmd.exe] Error 1
mingw32-make: *** [debug] Error 2
The process "C:/Qt/2010.05/mingw/bin/mingw32-make.exe" exited with code %2.
Error while building project Othello-cmd (target: Desktop)
When executing build step 'Make'
Any ideas on what might be causing this error?
EDIT: I would also like to note that I did find "main.o" inside the debug directory...
SOLUTION (not really): I recompiled everything in Netbeans instead (on a Mac though, so maybe the linker was different...). Now the program is running fine... goodbye Qt Creator
A:
I'll try to guess. You are either using namespaces wrong (i.e. put #include directive in the body of namespace). Or you haven't deleted debug and release directories completely as you were advised.
|
[
"stackoverflow",
"0028735842.txt"
] | Q:
Aspect Oriented / Object Oriented Programming?
What is Aspect Oriented Programming? Can Aspect Oriented Programming (ASP) replace Object Oriented Programming (OOP)? Please reply with solid arguments.
A:
In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. AOP forms a basis for aspect-oriented software development. AOP includes programming methods and tools that support the modularization of concerns at the level of the source code. Aspect-oriented programming entails breaking down program logic into distinct parts (so-called concerns, cohesive areas of functionality). Nearly all programming paradigms support some level of grouping and encapsulation of concerns into separate, independent entities by providing abstractions (e.g., functions, procedures, modules, classes, methods) that can be used for implementing, abstracting and composing these concerns. Some concerns "cut across" multiple abstractions in a program, and defy these forms of implementation. These concerns are called cross-cutting concerns.
Logging exemplifies a crosscutting concern because a logging strategy necessarily affects every logged part of the system. Logging thereby crosscuts all logged classes and methods.
First of all AOP will not replace OOP. AOP extends OOP.
One shouldn't see AOP as a replacement of OOP, more as an nice add-on, that makes our code more clean, loosely-coupled and focused on the business logic. So by applying AOP you will get two major benefits:
1) The logic for each concern is now in one place, as opposed to being scattered all over the code base.
2) Classes are cleaner since they only contain code for their primary concern (or core functionality) and secondary concerns have been moved to aspects.
|
[
"stackoverflow",
"0012119992.txt"
] | Q:
File access permission denied even after setting ACL in linux
I've set ACL for an svn folder as follows
# file: www
# owner: aks
# group: users
user::rwx
group::rwx
group:users:rwx
mask::r-x
other::r-x
default:user::rwx
default:group::rwx
default:other::r-x
but despite this, when another user does an svn up, he gets
svn: Can't open file 'www/.svn/lock': Permission denied
What am i missing
A:
The use of a lock file requires write access to said lock file.
Assuming that you are using the same ACL for the lock file as well (you have listed the ACL for the parent folder instead), your ACL does not allow any user except for the owner to write to that file.
From the acl(5):
The ACL_MASK entry denotes the maximum access rights that can be granted by entries of type ACL_USER, ACL_GROUP_OBJ, or ACL_GROUP.
In essence, the ACL mask affects all named user entries and all group entries - in your case that removes write access from the users group that I assume contains the user that runs svn.
|
[
"stackoverflow",
"0022151971.txt"
] | Q:
I can not seem to get the android_id
Here is the code i am using
private String android_id = Secure.getString(this.getContentResolver(),
Secure.ANDROID_ID);
Do I need to add permission to my manifest to have access to this variable?
A:
i set android_id in onCreate now it works
private String android_id;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = getIntent();
android_id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
|
[
"stackoverflow",
"0028931660.txt"
] | Q:
Find out if a user liked specific comment
I have the following Post class:
public class Post
{
public string Id {get;set;}
public string Content {get;set;}
public IList<Comment> Comments {get;set;}
}
public class Comment
{
public int OrderNumber {get;set;} //kind of CommentId
public string AuthorId {get;set;}
public string Text {get;set;}
public IList<string> Voters {get;set;} //Ids of users who liked the post
}
There could be thousands of likes for each comment but I need to display only the quantity of them on the client so I created the following index:
Map = posts => from post in posts
select new {
Id = post.Id,
Content = post.Content,
Comments = post.Comments.Select(x =>
new CommentProjection {
AuthorId = x.AuthorId,
Text = x.Text,
VotersCount = x.VotersCount
}),
};
The problem is I need to highlight those comments that a user has already liked. Is there a way to modify above index to add this information into query results?
A:
You can do it the other way, keep track of the comments on the user, so you can show the comments they liked.
|
[
"math.stackexchange",
"0003755426.txt"
] | Q:
Showing the relative consistency of $\neg CH$ using inner models
This question showed up when I transitioned from studying constructibility and inner models of $\mathrm{ZF}$ to studying forcing. Is there a reason why we don't use inner models to show the (relative) consistency of $\neg \mathrm{CH}$ the way we use them to show the relative consistency of $\mathrm{CH}$? I have a wild guess, that is: if we could do so, the falsehood of $ \mathrm{CH}$, being a $\Pi_1$-statement, would trickle down to the minimal inner model, $\mathrm{L}$, by downward absoluteness while on the other hand we know that $ \mathrm{CH}$ holds in $\mathrm{L}$.
I'm not sure this makes sense, or even if it is true that we can't build inner models of $\mathrm{ZFC} + \neg \mathrm{CH}$. (I'm not even sure $\neg \mathrm{CH}$ is $\Pi_1$...).
A:
The problem is that it is consistent that $L$ is the only inner model, so you won't find any inner models that you can prove refute V=L (and hence CH). Things are less clear if we add large cardinal axioms so that this is no longer the case, but even if it were possible then, it would be suboptimal in terms of consistency strength.
No, $\neg$CH is not $\Pi_1.$ CH does say a certain bijection exists, but the objects it exists on ($\omega_1$ and $P(\omega)$) are $\Delta_2$ and $\Pi_1$ respectively so CH is $\Sigma_2.$ (As Hanul Jeon notes you can clinch this by observing that $\neg CH$ can be forced over $L$, so truth of CH isn’t preserved outward.)
|
[
"stackoverflow",
"0051732322.txt"
] | Q:
WPF Opening a file and updating window
I am relatively new to WPF. I am trying to open an excel file and pull the column headers and displaying it in my window as a check list. Right now I'm having issues updating the my window/checklist.
Here is what I have in the xaml
<DockPanel Grid.Column="0" Grid.Row="1" Margin="10">
<ListBox ItemsSource="{Binding TagListData}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsTagSelected}" Content="{Binding TagName}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
and here is what I have in the cs code. (Instead of reading the excel document that gets opened, I am just using a placeholder for now just to see if I'm doing this correctly.)
private Excel.Application xlApp;
private Excel.Workbook xlWorkbook;
public ObservableCollection<TagClass> TagListData { get; set; }
public MainWindow()
{
InitializeComponent();
...
TagListData = new ObservableCollection<TagClass>();
}
private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel Files|*.xls;*.xlsx;*.slxm";
if (openFileDialog.ShowDialog() == true)
{
xlApp = new Excel.Application();
xlWorkbook = xlApp.Workbooks.Open(openFileDialog.FileName);
//populate TagListData
TagListData.Add(new TagClass { IsTagSelected = true, TagName = "Tag Name 1" });
}
}
public class TagClass
{
public string TagName { get; set; }
public bool IsTagSelected { get; set; }
}
When I try top open a file to populate my checklist, nothing happens. Does anyone know what I am doing incorrectly?
I also found this which checks when an item gets updated but I want to check when the list/collection gets updated. I'm having a hard time figuring this out.. ListBox item doesn't get refresh in WPF?
Thank you
A:
It looks like you haven't set the DataContext of your window. The data context is the thing that you bind to, it doesn't just automatically hookup binding to properties that you add to the window itself.
There are many ways to fix this, the simplest (but arguably wrong) way to fix it would be to add this to the end of your constructor:
this.DataContext = this;
But this is weird. I would suggest never doing this. We normally create a new object will house the data that we want to bind to. In this case, you can set your DataContext to your TagListData, and then update the binding accordingly.
public MainWindow()
{
InitializeComponent();
...
TagListData = new ObservableCollection<TagClass>();
this.DataContext = TagListData;
}
and update the binding
<DockPanel Grid.Column="0" Grid.Row="1" Margin="10">
<ListBox ItemsSource="{Binding}"> <!-- note no Path on this binding because the data context of the window IS the collection now -->
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsTagSelected}" Content="{Binding TagName}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
If there are other things you are going to want to bind to on the Window, then setting the DataContext to the collection won't work. Instead you should create a new class that will contain the collection and all the other things you will want to bind to. Add a property of the type of this new class, and set that as your window's DataContext. When you're using the MVVM pattern, this is normally what we call the ViewModel.
|
[
"askubuntu",
"0000361477.txt"
] | Q:
Am I being served a beta release of 13.10?
Today, I followed the instructions at https://help.ubuntu.com/community/SaucyUpgrades (Ubuntu Desktops 13.04 to 13.10). When I got to step #6, the release notes popped up, and the first two lines said:
Welcome to the Ubuntu 'Saucy Salamander' development release
This is still a BETA release. Do not install it on production
machines.
Is my system trying to get outdated files, or is is safe to ignore those notes?
A:
The problem here is that the message has not been updated already. The files are the official 13.10 release but since the message still shows the previous text (when it was Beta) it shows like that to any users that tries to update.
The same thing happened with 12.10 to 13.04 and 12.04 to 12.10. If you do wait about a day (up to a week) the message should change to "Welcome to the Ubuntu 'Saucy Salamander'".
Give it time while the developers work on this "high priority" bug ;). It confused me too until I updated.
A:
13.10 is not a beta release anymore. 13.10 is a stable release. If you were on the Beta release ISOs, or are installing the Beta release ISOs, the system should still update to the latest versions in the repos, as your updates should still be applied because the repositories used are the same as the full released versions now.
This is an issue of where the community docs were just out of date.
The documentation has been updated to reflect that it is no longer a beta release.
|
[
"superuser",
"0000516363.txt"
] | Q:
What is the '' character?
An e-mail from a colleague contained the character at the end of a sentence, in a context where one might expect punctuation or a smiley.
What is this character? It has zero google results and unicodelookup.com doesn't make me wiser either.
Does it have a meaning? If not, how could someone enter such a character as a typo?
A:
According to this page it is the "Unicode Character 'FACE SAVOURING DELICIOUS FOOD' (U+1F60B)":
in general, searching for smileys and strange characters like this is better on http://duckduckgo.com which is a great search engine anyway.
UPDATE
I did some more testing following the discussion in the comments. I don't think the rendering differences depend on the font. The following is a screenshot showing the character written in different fonts in Libre Office (Linux)
This is the character as displayed on my linux box by firefox (Chromium and Opera show the same):
On my iPad, it is first displayed as a smaller (placeholder?) glyph as shown below but then resolves itself to the same image as those above:
So, I don't know how these Unicode glyphs are encoded, but they don't seem to be font dependent. I don't imagine most fonts include a specific rendering of emoticons, so there must be a shared way of displaying them that is platform/system dependent and not tied to a specific font.
A:
As seen in Segoe UI Symbol, 72 pt
A:
(Image from Mac OS X Character Viewer. I take no credit for the info in the image.)
On Mac OS X, I think Lion and above. Testing in TextEdit reveals that it is unaffected by font, as the Character Viewer appears to state in the font variation section of its entry.
Speculating on why your colleague used it, it's relatively simple to insert on Mac, using the Character Viewer/Special Characters under the emoji section (funny enough, this one's not in Messages' list of smileys). It's also easy to insert on iPad, using the Emoji "international" keyboard. There are definitely other ways to do it, and on other platforms, those are just the ways I've found to type them that aren't too hard to find. Who can't resist typing fancy colored emoticons that they found looking through random features of their system?
It might be something interesting to ask your colleague about.
This is what inspired me to make this post. Just noticed it randomly. It isn't rendered in the web page, just the tab title and the tab's hovertext. (this is on Mac 10.8 with Chrome 23)
|
[
"ru.stackoverflow",
"0001042772.txt"
] | Q:
Как открыть дизайнер формы в проекте Windows Application C++?
Всем привет.
В общем, создал проект Windows Application С++.
При запуске без ошибок создаётся красивая форма. Но проблема - нет дизайнера, как мне создавать кнопки, лейблы и т.д?
Скрин:
A:
Никак. В проектах неуправляемых приложений Windows можно разве что использовать редактор ресурсов диалоговых окон для визуального редактирования интерфейса:
В обозревателе решений Файлы ресурсов - два раза нажать по .rc файлу (если нет, создать)
В левой панели (Окно ресурсов) правой кнопкой - Добавить ресурс - Dialog
Откроется интерфейс редактора ресурсов диалоговых окон.
Подробнее о том, как это работает, см. здесь: C++ WinApi отделить UI View от кода
Но для удобной работы с GUI в режиме конструктора (как в .NET Windows Forms) в неуправляемых приложениях нужно что-то типа MFC.
|
[
"stackoverflow",
"0016898257.txt"
] | Q:
Add drop down menu on tab label
I'm interested how I can add drop down menu with options when I right click on tab label with the mouse? Are there any examples?
A:
You can use setContextMenu() on Tab to do this. The ContextMenu javadoc page has information on creating the menu - it's very similar to a standard JavaFX menu (just do contextMenu.getItems().addAll(item1, item2);, etc.
|
[
"stackoverflow",
"0038504041.txt"
] | Q:
Data Structure for Segue?
In iOS application which is the most optimized Data Structure being used for the the navigation among View Controllers and how do they work actually?
Example: In the given image 'VC.JPEG', at top we have navigation controller and forward and backward arrows are taking to next and previous screens respectively. Now at bottom of every screens,(namely A, B, C & D)we have Btn1, Btn2 and so on. When we click Btn1 it takes us from A to B, for Btn2 from B to C, for Btn3 from C to D and finally for Btn4 from D to A. So which Data structure should be best fitted for it with no extra memory requirement.
A:
Just check if the profile shown is yours and disable follow button...
|
[
"stackoverflow",
"0027784447.txt"
] | Q:
Template factory function with additional args: friendship issue
I'm working on a piece of code that looks like this:
template<typename T>
class A {
// makeA should become a friend
A() {}
};
template<typename T, typename U>
A<T> makeA(const U & u) {
(void) u;
return A<T>();
}
int main() {
makeA<double>(3);
return 0;
}
But I cannot let makeA become a friend of A. Is this possible? What is the right syntax?
A:
You could make it friend as:
template<typename T>
class A
{
template<typename TT, typename U>
friend A<TT> makeA(const U & u) ;
};
You could even define the friend function inside the class.
|
[
"stackoverflow",
"0048102955.txt"
] | Q:
HTML select option text monospace
I am trying to get select options to use monospace fonts so that they are lined up vertically when you click the drop down. I am trying to put a code left justified followed by a dash and then a description. I added the options using coded spaces so that each option has the same number of characters before the dash, but they still are not lined up. I tried courier new and monospace. I can tell it is using the fonts because they change, but they are still not lined up. Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>font test</title>
<style>
select, option{
font-family:monospace, monospace;
}
</style>
</head>
<body>
<form>
<select name=SOURCECODE>
<option value="" selected>Select a Option</option>
<option value="A">A - TEST A</option>
<option value="AB">AB - TEST AB</option>
<option value="ABC">ABC - TEST ABC</option>
<option value="ABCD">ABCD - TEST ABCD</option>
<option value="A">A - TEST A</option>
<option value="AB">AB - TEST AB</option>
<option value="ABC">ABC - TEST ABC</option>
<option value="ABCD">ABCD - TEST ABCD</option>
</select>
</form>
</body>
</html>
Is there a way to make this work?
****Note this appears to only be a problem with firefox
A:
Ok, reading throught several articles, it seems that this is a Mozilla Firefox's bug, and the font style cannot actually be set at the moment (as of 10.5.2018). I have personally tested on 59.0.2 and 60.0 on Windows 10 (x64), both have the same bug.
5 years old bug report: https://bugzilla.mozilla.org/show_bug.cgi?id=910022
11 months old bug report (for BG color): https://bugzilla.mozilla.org/show_bug.cgi?id=1376443
SO question on the same topic: CSS Font-Family Support Dropped for <SELECT> in Firefox?
I have also noticed this writting in regards to option tag:
Firefox refuses to apply background-color to option tag on a select menu.
Problem encountered since Firefox 48 and +, on Windows 7, 8.1 and 10 (all x64)
Problem not encontered on Firefox 48 and +, on Windows XP 32 bits
Solutions that would usually work (but not working in this case):
changing font-family to monospace
adding tabs (	) and <pre></pre> tags
as Kelvin Samuel noted, creating own custom Select might work (e.g. following this tutorial, see below working solution)
Working custom select from tutorial:
var x, i, j, selElmnt, a, b, c;
/*look for any elements with the class "custom-select":*/
x = document.getElementsByClassName("custom-select");
for (i = 0; i < x.length; i++) {
selElmnt = x[i].getElementsByTagName("select")[0];
/*for each element, create a new DIV that will act as the selected item:*/
a = document.createElement("DIV");
a.setAttribute("class", "select-selected");
a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
x[i].appendChild(a);
/*for each element, create a new DIV that will contain the option list:*/
b = document.createElement("DIV");
b.setAttribute("class", "select-items select-hide");
for (j = 1; j < selElmnt.length; j++) {
/*for each option in the original select element,
create a new DIV that will act as an option item:*/
c = document.createElement("DIV");
c.innerHTML = selElmnt.options[j].innerHTML;
c.addEventListener("click", function(e) {
/*when an item is clicked, update the original select box,
and the selected item:*/
var y, i, k, s, h;
s = this.parentNode.parentNode.getElementsByTagName("select")[0];
h = this.parentNode.previousSibling;
for (i = 0; i < s.length; i++) {
if (s.options[i].innerHTML == this.innerHTML) {
s.selectedIndex = i;
h.innerHTML = this.innerHTML;
y = this.parentNode.getElementsByClassName("same-as-selected");
for (k = 0; k < y.length; k++) {
y[k].removeAttribute("class");
}
this.setAttribute("class", "same-as-selected");
break;
}
}
h.click();
});
b.appendChild(c);
}
x[i].appendChild(b);
a.addEventListener("click", function(e) {
/*when the select box is clicked, close any other select boxes,
and open/close the current select box:*/
e.stopPropagation();
closeAllSelect(this);
this.nextSibling.classList.toggle("select-hide");
this.classList.toggle("select-arrow-active");
});
}
function closeAllSelect(elmnt) {
/*a function that will close all select boxes in the document,
except the current select box:*/
var x, y, i, arrNo = [];
x = document.getElementsByClassName("select-items");
y = document.getElementsByClassName("select-selected");
for (i = 0; i < y.length; i++) {
if (elmnt == y[i]) {
arrNo.push(i)
} else {
y[i].classList.remove("select-arrow-active");
}
}
for (i = 0; i < x.length; i++) {
if (arrNo.indexOf(i)) {
x[i].classList.add("select-hide");
}
}
}
/*if the user clicks anywhere outside the select box,
then close all select boxes:*/
document.addEventListener("click", closeAllSelect);
/*the container must be positioned relative:*/
.custom-select {
position: relative;
font-family: monospace;
}
.custom-select select {
display: none; /*hide original SELECT element:*/
}
.select-selected {
background-color: DodgerBlue;
}
/*style the arrow inside the select element:*/
.select-selected:after {
position: absolute;
content: "";
top: 14px;
right: 10px;
width: 0;
height: 0;
border: 6px solid transparent;
border-color: #fff transparent transparent transparent;
}
/*point the arrow upwards when the select box is open (active):*/
.select-selected.select-arrow-active:after {
border-color: transparent transparent #fff transparent;
top: 7px;
}
/*style the items (options), including the selected item:*/
.select-items div,.select-selected {
color: #ffffff;
padding: 8px 16px;
border: 1px solid transparent;
border-color: transparent transparent rgba(0, 0, 0, 0.1) transparent;
cursor: pointer;
}
/*style items (options):*/
.select-items {
position: absolute;
background-color: DodgerBlue;
top: 100%;
left: 0;
right: 0;
z-index: 99;
}
/*hide the items when the select box is closed:*/
.select-hide {
display: none;
}
.select-items div:hover, .same-as-selected {
background-color: rgba(0, 0, 0, 0.1);
}
<!--surround the select box within a "custom-select" DIV element.
Remember to set the width:-->
<div class="custom-select" style="width:200px;">
<select>
<option value="" selected>Select a Option</option>
<option value="A">A - TEST A</option>
<option value="AB">AB - TEST AB</option>
<option value="ABC">ABC - TEST ABC</option>
<option value="ABCD">ABCD - TEST ABCD</option>
<option value="A">A - TEST A</option>
<option value="AB">AB - TEST AB</option>
<option value="ABC">ABC - TEST ABC</option>
<option value="ABCD">ABCD - TEST ABCD</option>
</select>
</div>
|
[
"worldbuilding.stackexchange",
"0000051689.txt"
] | Q:
Possibility of bipedal mostly-aquatic species?
I'm trying to design a species that is largely aquatic and yet capable of walking / running (loosely) on land. I've already figured out a gill and lung type respiratory system to allow them to breathe in both air and in water, but I'm stumped on why a mostly aquatic being would have legs (or things that serve a similar function)... or ARMS for that matter.
The species is based mostly on octopi and squid. My plan was to give them the same basic features (very large eyes, beak, tentacles) but for the sake of my story they need to be able to move on land. I've also been thinking of the concept of their "legs" and "arms" having joints that deliberately dislocate to create a type of fluidity in the water so that those limbs aren't completely useless underwater, but I'm not really educated anatomically and I'm not even sure if that would work.
Tldr: basically put, how do I give squid-like mostly aquatic aliens arms and legs while remaining truthful to science?
Any ideas?
Edit: it's come to my attention that while octopi are very dexterous underwater they are rather clumsy on land and have a hard time lugging around their bodies. If I want to keep the general form of the octopi, how would I counteract this? Otherwise, I'm still searching for reasons and ideas on how to give them legs.
A:
I don't think you want bipedal. If they are octopus-like, they should not be limited to just 2 legs for locomotion. Octopuses are amazing and have no trouble moving on land for short periods (they're only limited by the fact that they can't really breathe air.) As for their limbs, octopi have no bones. They are unique, and I suggest you study the very specific and strange biology and movement of octopi--they have no joints at all, as result of having no bones.
Here's some great links:
an octopus using armor.
how they move and manipulate their limbs.
they can open jars
they are smart and can escape almost anything.
I believe that they do have fine motor control, and have very good sense of touch. If you want to give them double tentacles at the end of two for a thumb-like structure, you can, but I would say that this is really a non-problem.
|
[
"serverfault",
"0000405301.txt"
] | Q:
How to recreate samba secrets.tdb file
While trying to setup samba on an NFS server I deleted (don't ask) the /var/lib/samba/ contents and now when I try to start samba, this messages appears :
[2012/07/06 08:19:07.528973, 0] passdb/secrets.c:73(secrets_init)
Failed to open /var/lib/samba/private/secrets.tdb
[2012/07/06 08:19:07.689735, 0] passdb/secrets.c:73(secrets_init)
Failed to open /var/lib/samba/private/secrets.tdb
[2012/07/06 08:19:07.690078, 0] smbd/server.c:1240(main)
ERROR: smbd can not open secrets.tdb
So how do I recreate the secrets.tdb file and the rest of the needed files if any ?
A:
Use smbpasswd which will create the file if it doesn't exist when you add a new user
ls -l /var/lib/samba/private/secrets.tdb
ls: cannot access /var/lib/samba/private/secrets.tdb: No such file or directory
smbbpasswd iain
New SMB password:
Retype new SMB password:
ls -l /var/lib/samba/private/secrets.tdb
-rw-------. 1 root root 45056 Jul 6 07:54 /var/lib/samba/private/secrets.tdb
|
[
"stackoverflow",
"0034324052.txt"
] | Q:
Using an array in a List - OOP - Generic List
I have created a list:
List<Employee> employees = new List<Employee();
I would like to achieve this:
Employee e1 = new Employee(Job.Employee, "Name", "C Sharp", "Oracle", "SQL");
I currently have this:
Employee e1 = new Employee(Job.Employee, "Name", Skills.CSharp);
This is the code inside the Employee class
public enum Job { Employee, Supervisor, Administrator };
public enum Skills {CSharp, SQL, PHP, Javascript, Web, Python, Oracle, CPlus, Perl };
protected Job job;
protected String employeeName;
protected String employeeName;
public Job Job
{
get { return job; }
protected set { job = value; }
}
public String EmployeeName
{
get { return employeeName; }
protected set { employeeName = value; }
}
public Skills Skills
{
get {return skills; }
}
I want to be able to enter as many 'skills' as I want as currently, only one skill can be entered in the Employee e1 as I have used a enum.
How would I put an array of 'skills' in the list/constructor?
A:
You can use a params array parameter to pass variable number of Skills parameters to the constructor:
public Employee(Job job, string name, params Skills[] skills)
You will also have to modify the skills field to hold a collection of Skills instead of a single one. You can make it an array if you will not add/remove skills after the employee is created, or an IList<Skills> if you need to modify the collection.
For example:
public class Employee
{
private List<Skills> _skills; // skills stored as a private List
// to allow modification inside Employee class
public Employee(Job job, string name, params Skills[] skills)
{
_skills = new List<Skills>(skills);
...
}
public IReadOnlyList<Skills> Skills // publicly visible as a read-only list
{
get { return _skills.AsReadOnly(); }
}
...
}
A:
An alternative to passing in a Skills[], you can change your enum to be a bit-mask of the skills that an employee has:
[Flags]
enum Skills
{
None = 0,
CSharp = 1 << 0,
SQL = 1 << 1,
PHP = 1 << 2,
Javascript = 1 << 3,
...
}
Then the individual skills can be bitwise ORed together to create the skills that an individual employee has:
Employee e1 = new Employee(Job.Employee, "Name", Skills.CSharp | Skills.SQL | Skills.PHP );
Then to check if an employee has a specific skill, you can use Enum.HasFlag method, eg:
if( e1.Skills.HasFlag( Skills.CSharp ) )
|
[
"tex.stackexchange",
"0000152822.txt"
] | Q:
Goudy Old Style for LaTeX?
Is there any possibility to make use of the font "Goudy Old Style" in a LaTeX document?
I haven't found it in the font packages.
A:
Remarks
I downloaded the font as Goudy Old Style.ttf and placed it in the same directory as my .tex file.
Implementation
Typeset with xelatex
\documentclass{article}
\pagestyle{empty}% for cropping
\usepackage{fontspec}
\setmainfont{Goudy Old Style.ttf}
\begin{document}
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
1234567890
\end{document}
Output
A:
You can download the necessary files (incl. the pfb's) for use with LaTeX here (by default it uses old-style figures):
Latex type 1 font packs
Here is an example code:
documentclass[a4paper, 12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{goudy}
\pagestyle{empty}
\begin{document}
Once upon a time, a long while ago, there were four little people whose names were \textsc{Violet}, \textsc{Slingsby}, \textsc{Guy}, and \textsc{Lionel}, and they all thought they should like to see the world. So they bought a large boat to sail quite round the world by sea, and then they were to come back on the other side by land. The boat was painted blue with green spots, and the sail was yellow with red stripes; and when they set off, they only took a small Cat to steer and look after the boat, besides an elderly Quangle-Wangle, who had to cook dinner and make the tea; for which purposes they took a large kettle.
\end{document}
Installation of the font pack (a rar file): it suffices to unrar it, which gives you a ‘goudy’ directory, containing a dvips/, a fonts/ and a tex/ directories; these can be copied as they are in a local texmf directory.
However, you can make the following changes if you want a clean installation: the dvips directory contains only a dvips\config\pgy.map. Move pgy.map to fonts\map\dvips. In this same directory, you'll find a paj.map which seems to be there by error (it has nothing to see with Goudy) and can safely be deleted, as well as the dvips directory after you've moved pgy.map. Then copy the fonts/ and tex/ directories in the local texmf directory.
For further details, see the Manual font installation.
|
[
"stackoverflow",
"0033607508.txt"
] | Q:
The type signature […] lacks an accompanying binding
Why do I end up with "binding" errors in the following program?
wheels :: Int
cars :: Int
carpark wheels cars
| wheels == odd = error wheels "is not even"
| cars <= 0 = error cars "is an invalid number"
| (2*cars) >= wheels = error "the number of wheels is invalid"
| wheels >= (4*cars) = error "the number of wheels is invalid"
| otherwise = "There are " (wheels-(2 * cars)) `div` 2 "cars and " (cars - ((wheels - (2 * cars)) div 2)) "motorcycles on the parking lot"
This is the error:
aufgabe1.lhs:6:3:
The type signature for ‘wheels’ lacks an accompanying binding
aufgabe1.lhs:7:3:
The type signature for ‘cars’ lacks an accompanying binding
How can I get rid of it?
A:
What are missing bindings?
There are many problems with your program, but lets focus on the "binding" one first. You're probably accustomed to Pascal or C, where you have to specify the type of the argument at the argument:
string carpark(int wheels, int cars);
However, Haskell doesn't work like this. If you write
wheels :: Int
in your document, you're telling the compiler that the value wheels will have the type Int. The compiler now expects a definition somewhere. This definition—it's binding—is missing. The type of wheels is known, but it's not known what value wheels should be bound to.
If you were to add
wheels = 1 * 2 + 12312
the compiler wouldn't complain about that particular binding anymore.
What's the actual problem?
As I've conclused above, you want to specify the arguments' types of carpark, right? However, this concludes that you specify carpark's type:
carpark :: Int -> Int -> String
carpark wheels cars
| -- omitted
This will get rid of the "missing bindings" errors.
What's missing?
Well, after this, you will still have a non-compiling piece of software, for example error wheels "is not even" isn't valid. Have a look at error's type:
error :: String -> a
Since wheels isn't a String, this won't compile. Instead, you have to show wheels:
error (show wheels ++ " is not even")
Note that error (show wheels) " is not even" will happily compile, but won't give you the error message you're actually looking for, so beware of parenthesis and string concatenation.
Exercises
Write a function whatNumber that returns "Is Odd" if the number is odd and "Is Even" if the number is even, e.g.
whatNumber 2 == "Is Even"
Write a function whatNumberId, that returns "<x> is odd" if the number is odd and "<x> is even" if the number is even, where <x> should be the number, e.g.
whatNumberId 123 == "123 is odd"
Both exercises should help you to accomplish your original task.
|
[
"codereview.stackexchange",
"0000078468.txt"
] | Q:
Multiplying Lists
Challenge:
Given 2 lists of positive integers.
Write a program which multiplies corresponding elements in these lists
Specifications:
Your program should accept as its first argument a path to a filename.
The lists are separated with pipe char: '|' .
Numbers are separated with a space char.
The number of elements in lists are in range [1, 10].
The number of elements is the same in both lists.
Each element is a number in range [0, 99].
Solution
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MultiplyLists {
public static void main(String[] args) throws FileNotFoundException {
Scanner fileInput = (args.length > 0) ?
new Scanner(new File(args[0])) :
new Scanner(System.in)
;
while (fileInput.hasNextLine()) {
printMultipliedList(fileInput.nextLine());
}
}
private static void printMultipliedList(String line) {
String[] params = line.split("\\|");
StringBuilder multiplied = new StringBuilder();
for (int n : getMultipliedList(params[0].trim().split("\\s+"), params[1].trim().split("\\s"))) {
multiplied.append(n).append(' ');
}
multiplied.setLength(multiplied.length() - 1);
System.out.println(multiplied.toString());
}
private static List<Integer> getMultipliedList(String[] first, String[] second) {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < first.length; i++) {
result.add(
Integer.parseInt(first[i]) * Integer.parseInt(second[i])
);
}
return result;
}
}
Sample Input:
9 0 6 | 15 14 9
5 | 8
13 4 15 1 15 5 | 1 4 15 14 8 2
Sample Output:
135 0 54
40
13 16 225 14 120 10
My solution seems really convoluted, how might I improve it?
Is there anything I do here that I should try to avoid in the
future?
Is this inefficient?
A:
My solution seems really convoluted, how might I improve it?
It doesn't seem so too convoluted, but maybe that's partly because the problem itself is simple. A couple of things can be improved.
Scanner fileInput = (args.length > 0) ?
new Scanner(new File(args[0])) :
new Scanner(System.in)
;
Some issues with this snippet:
The variable is named fileInput, but it's not always a file input, sometimes it's standard input, so the name can be misleading
The spec says the first arg is a filename, so you don't actually need to support standard input at all
No need to put parens around args.length > 0
Following the spec, the line can be simplified to:
Scanner fileInput = new Scanner(new File(args[0]));
This meets the spec, but not very user-friendly.
But in the context of this question I don't think that matters.
private static void printMultipliedList(String line) {
This may sound a bit strange, but I think it's good to avoid writing code.
Every line of code is a potential bug.
Only write as much code as necessary.
The printMultipliedList(String line) method does too many things:
It splits the input, which is part of the input parsing logic
It formats and prints the output
It's good when a method does just one logical thing.
It would be better to have a cleaner separation of the input parsing and output formatting logic.
Consider refactoring it like this:
private static void parseInputAndPrintMultipliedList(String line) {
List<List<Integer>> intLists = parseIntLists(line);
List<Integer> multipliedList = getMultipliedList(intLists.get(0), intLists.get(1));
String output = formatOutput(multipliedList);
System.out.println(output);
}
Now this method contains only higher level logical steps,
and delegates all actions to other methods,
each doing just one logical thing.
See a sample implementation of the new methods I introduced at the end of this post.
Also notice that the getMultipliedList in this snippet is different from yours,
because this one takes two lists of integers, instead of string arrays.
The reason is that the original getMultipliedList method does too many things:
it does input parsing (string to int) and it multiplies lists.
for (int n : getMultipliedList(params[0].trim().split("\\s+"), params[1].trim().split("\\s"))) {
multiplied.append(n).append(' ');
}
multiplied.setLength(multiplied.length() - 1);
There are several issues:
The trimming and splitting is duplicated for params[0 and params[1]. It would be better to move this logic to a helper method
You can actually avoid trimming, if you create params like this: params = line.split("\\s*\\|\\s*")
The line in the for statement is too long. It's good to keep lines short enough to be visible without having to scroll horizontally. If you rewrite this line using the helper method I suggested earlier, it might become short enough. Or if it's still too long, then it will be better to put those values into local variables. The compiler will know to inline them, and it will improve readability.
Instead of appending ' ' to all elements and cutting off the last one, it might be slightly better to add the first item, and iterate from the 2nd until the end, and in each step do .append(' ').append(n), so you don't have to cut anything off later. But this is a very minor thing.
Is there anything I do here that I should try to avoid in the future?
To summarize what I already mentioned above:
Avoid writing code
Keep in mind the single responsibility principle, and make sure that each method does just one logical thing
Avoid duplication of logic, extract common logic to a helper method
Is this inefficient?
There are no serious efficiency problems.
There are minor inefficiencies,
but I don't think they are worth tuning:
Splitting by |, and then again splitting by visits all characters in the input twice
Multiplying the list items, and then iterating over the items for printing visits all elements twice
My suggestions make this worse, adding one more iteration due to parsing the list of strings to list of integers. But I don't think this is a problem. The time complexity of the solution remains \$O(n)\$, whether we process the list items in 3, 4, or 5 passes.
Clarity of the logic and following the single responsibility principle is more important.
Suggested implementation
Applying the suggestions about, the implementation becomes:
class MultiplyLists {
public static void main(String[] args) throws FileNotFoundException {
Scanner fileInput = new Scanner(new File(args[0]));
while (fileInput.hasNextLine()) {
parseInputAndPrintMultipliedList(fileInput.nextLine());
}
}
private static String formatOutput(List<Integer> result) {
StringBuilder builder = new StringBuilder();
Iterator<Integer> iterator = result.iterator();
builder.append(iterator.next());
while (iterator.hasNext()) {
builder.append(' ').append(iterator.next());
}
return builder.toString();
}
private static void parseInputAndPrintMultipliedList(String line) {
List<List<Integer>> intLists = parseIntLists(line);
List<Integer> multipliedList = getMultipliedList(intLists.get(0), intLists.get(1));
String output = formatOutput(multipliedList);
System.out.println(output);
}
private static List<List<Integer>> parseIntLists(String line) {
List<List<Integer>> intLists = new ArrayList<>();
for (String string : line.split("\\s*\\|\\s*")) {
intLists.add(parseIntList(string));
}
return intLists;
}
private static List<Integer> parseIntList(String input) {
List<Integer> list = new ArrayList<>();
for (String item : input.split("\\s+")) {
list.add(Integer.parseInt(item));
}
return list;
}
private static List<Integer> getMultipliedList(List<Integer> intList1, List<Integer> intList2) {
List<Integer> multipliedList = new ArrayList<>();
for (int i = 0; i < intList1.size(); i++) {
multipliedList.add(intList1.get(i) * intList2.get(i));
}
return multipliedList;
}
}
|
[
"stackoverflow",
"0022769315.txt"
] | Q:
Layout with flexbox property
In this layout, I want to place a circle (with fixed size) at the intersection of the column and a line on the bottom left corner of the page (which should be a no scroll page). The circle should look like this image.
I’ve started doing it with the flexbox property, however this was the first time I used this property and I am not getting how to do this.
Does anyone know how can I do it?
<div class="wrap">
<div class="hud1">
<div class="gps box"></div><!-- /gps -->
<div class="info box"></div><!-- /info -->
<div class="phone box"></div><!-- /phone -->
</div><!-- /hud1 -->
<div class="speed">
<div class="circle"></div>
</div>
<div class="hud2">
<div class="status box withfocus">
<h1>Estado</h1>
</div><!-- /status -->
<div class="media box withoutfocus">
<h1>Multimédia</h1>
</div><!-- /media -->
<div class="environment box withoutfocus">
<h1>Ambiente</h1>
</div><!-- /environment -->
<div class="settings box withoutfocus">
<h1>Definições</h1>
</div><!-- /settings -->
</div><!-- /hud2 -->
</div><!-- /wrap -->
Here’s the code:
http://jsfiddle.net/marisaroque/mR7nq/
EDIT:
Here’s the image:
Link
Thank you in advance!
A:
Is it like this: http://jsfiddle.net/HUmLb/embedded/result/ ?
The key is making .hud1 a one-column flex, and in the last item inserting a .hud2 row.
I still couldn't make it center vertical, but I presume it's a good start.
Let us know.
Edit
http://jsfiddle.net/ngxyW/
I put an empty box in the lower corner and fixed the wrap div to bottom left.
This is a great reading about flex display: http://css-tricks.com/snippets/css/a-guide-to-flexbox/
|
[
"electronics.stackexchange",
"0000383075.txt"
] | Q:
What the difference between pin and pn diodes i-v curve?
For my understanding there should be no big difference in i-v curve between regular p-n junction and p-i-n junction, the only difference i can think about is do to the bigger resistance of the intrinsic layer. The curve should look the same only the current will rise little bit slower, because of the resistance.
Am i right?
A:
There is indeed no big difference in IV-curve between a PIN-diode and a regular abutted PN-diode when forward biased. For wider I-regions, the current may differ slightly.
I believe the statement
the bigger resistance of the intrinsic layer
is incorrect though.
The resistivity \$\rho\$ tells us how charges move under the influence of an electric field, or
$$\vec{J} = \sigma \vec{E} = \frac{1}{\rho} \vec{E}$$
This method of carrier transport is called drift. However, diode operation also heavily depends on diffusion. The higher resistivity basically causes the depletion region to be wider as the balance between drift and diffusion tilts more towards diffusion.
PN-diode current increases as more charges have enough energy to cross the built-in potential barrier. Applying a voltage will lower that potential barrier, causing more electrons to to cross it increasing the current.
A PIN-diode has a barrier height that is the same as for a PN-diode with the same doping concentrations for P and N-regions. A PIN-diode, however, will have a barrier spread out over a longer distance. This may effect the IV-curve, but from what I have found in simulations that effect is rather small.
Other more notable differences:
A PIN-diode has a wider depletion region, so it also has a lower capacitance.
The electric field is also weaker in a PIN diode due the wider depletion region. This means that the breakdown voltage will be larger too.
|
[
"stackoverflow",
"0017533429.txt"
] | Q:
Wrap several div with other div
I have several div as following:
<div id='id1'>blabla</div>
<div id='id2'>blabla</div>
<div id='id3'>blabla</div>
<div id='id4'>blabla</div>
<div id='id5'>blabla</div>
<div id='id6'>blabla</div>
And I would like to add a new div (<div id='newdiv'>) in order to wrap the div I specify.
For example before 'id3' and after 'id5'.
So we obtain:
<div id='id1'>blabla</div>
<div id='id2'>blabla</div>
<div id='newdiv'>
<div id='id3'>blabla</div>
<div id='id4'>blabla</div>
<div id='id5'>blabla</div>
</div>
<div id='id6'>blabla</div>
Do you know jQuery code to do this?
A:
Use jQuery .wrapAll() :
$('#id3, #id4, #id5').wrapAll('<div id="newdiv" />')
Fiddle : http://jsfiddle.net/K4HVR/
A:
Probably a simple plugin to make it more flexible, reusable:
$.fn.customWrap = function (end, wrapperDivAttr) {
this.nextUntil(end).next().addBack().add(this).wrapAll($('<div/>', wrapperDivAttr));
}
$('#id3').customWrap('#id5', { id: 'newDiv'}); // call the function on the startelement, specify the end elements selector and attribute obj.
nextUntil to get all the divs until the end div, then next to select the end div as well, and addback() to add the previous elements (nextUntil ones) to the collection and then add() to select the start div as well and then wrapAll of them.
Demo
|
[
"stackoverflow",
"0024002152.txt"
] | Q:
Proper way of converting string to long int in PHP
I tried (int) "4209531264" and intval("4209531264")
but sadly all I get is 2147483647 (I realize this is because of 32 bit architecture or some php dependencies or something).
I came up with "4209531264" + 0 which returns the correct result but it is surprising to see it working since it is beyond maxint.
but the real question: is this the "right way" of converting string to long?
edit:
(float) that is.
thanks for the comments! eye opening!
A:
As long as you are not very particular about what exactly kind of value you end up with, "number" + 0 is probably the best way of converting your input because it converts to the "natural" numeric data type.
The result will be an integer if the input has no decimal part and fits (see PHP_INT_MAX) or a float if it does not.
|
[
"stackoverflow",
"0012195026.txt"
] | Q:
MEF dependency questions
Simple example.
Application A has a class library C which is used through out.
Application A uses MEF to discover and load plug in modules P1 and P2 from a plug in directory. One assembly per plug in.
P1 and P2 both have a dependency on C (The class library).
The build process will ensure the version of C used by P1 is identical to the version referenced by A.
I assume that I won't end up with multiple copies of the same assembly loaded at once? By default I end up with a copy of C in the Plugin directory as well as A's application directory.
A:
To ensure you don't end up with duplicate assemblies, you could change the Copy Local property to false of the contract (C) library in your plugin projects, that way on build, it won't be copied to the output directory.
You should be fine I think, as the CLR won't load the same assembly twice thanks to the Fusion loader rules - the first being to see if the target assembly is already loaded in the AppDomain. BUT, you have to be careful, because any code using Assembly.LoadFrom may result in exceptions occurring if it is actually finding that the assemblies have different locations on disk.
|
[
"stackoverflow",
"0051385673.txt"
] | Q:
Can't specify requirements set for OfficeApp manifest.xml
I have an Office add-in/TaskPane app.
When I try to specify the requirements set for this app in my manifest.xml, I am getting the following error from office-addin-validator:
The element OfficeApp in namespace http://schemas.microsoft.com/office/appforoffice/1.1 has invalid child element Requirements in namespace http://schemas.microsoft.com/office/appforoffice/1.1
The documentation makes it very clear that Requirements is in fact allowed in this location.
I am able to add the requirement set inside the VersionOverrides tag, and that section looks like:
<VersionOverrides xmlns="http://schemas.microsoft.com/office/taskpaneappversionoverrides" xsi:type="VersionOverridesV1_0">
<Requirements>
<bt:Sets>
<bt:Set Name="ExcelApi" MinVersion="1.1"/>
</bt:Sets>
</Requirements>
<!--- ... -->
</VersionOverrides>
However, office-addin-validator does not correctly identify that older versions of Excel are not supported.
What is the correct way to do this? I can't tell if this is a bug in the office-addin-validator tool or outdated documentation.
EDIT
Here is a failing manifest:
<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0"
xmlns:ov="http://schemas.microsoft.com/office/taskpaneappversionoverrides" xsi:type="TaskPaneApp">
<Id>999dfa02-364b-450c-a66b-b4baaae2e6f9</Id>
<Version>1.0.0.0</Version>
<ProviderName>[Provider name]</ProviderName>
<DefaultLocale>en-US</DefaultLocale>
<DisplayName DefaultValue="My Office Add-in" />
<Description DefaultValue="[Workbook Add-in description]"/>
<IconUrl DefaultValue="https://localhost:3000/assets/icon-32.png" />
<HighResolutionIconUrl DefaultValue="https://localhost:3000/assets/hi-res-icon.png"/>
<SupportUrl DefaultValue="[Insert the URL of a page that provides support information for the app]"/>
<AppDomains>
<AppDomain>AppDomain1</AppDomain>
<AppDomain>AppDomain2</AppDomain>
<AppDomain>AppDomain3</AppDomain>
</AppDomains>
<Hosts>
<Host Name="Workbook" />
</Hosts>
<DefaultSettings>
<SourceLocation DefaultValue="https://localhost:3000/index.html" />
</DefaultSettings>
<Permissions>ReadWriteDocument</Permissions>
<VersionOverrides xmlns="http://schemas.microsoft.com/office/taskpaneappversionoverrides" xsi:type="VersionOverridesV1_0">
<Hosts>
<Host xsi:type="Workbook">
<DesktopFormFactor>
<GetStarted>
<Title resid="Contoso.GetStarted.Title"/>
<Description resid="Contoso.GetStarted.Description"/>
<LearnMoreUrl resid="Contoso.GetStarted.LearnMoreUrl"/>
</GetStarted>
<FunctionFile resid="Contoso.DesktopFunctionFile.Url" />
<ExtensionPoint xsi:type="PrimaryCommandSurface">
<OfficeTab id="TabHome">
<Group id="Contoso.Group1">
<Label resid="Contoso.Group1Label" />
<Icon>
<bt:Image size="16" resid="Contoso.tpicon_16x16" />
<bt:Image size="32" resid="Contoso.tpicon_32x32" />
<bt:Image size="80" resid="Contoso.tpicon_80x80" />
</Icon>
<Control xsi:type="Button" id="Contoso.TaskpaneButton">
<Label resid="Contoso.TaskpaneButton.Label" />
<Supertip>
<Title resid="Contoso.TaskpaneButton.Label" />
<Description resid="Contoso.TaskpaneButton.Tooltip" />
</Supertip>
<Icon>
<bt:Image size="16" resid="Contoso.tpicon_16x16" />
<bt:Image size="32" resid="Contoso.tpicon_32x32" />
<bt:Image size="80" resid="Contoso.tpicon_80x80" />
</Icon>
<Action xsi:type="ShowTaskpane">
<TaskpaneId>ButtonId1</TaskpaneId>
<SourceLocation resid="Contoso.Taskpane.Url" />
</Action>
</Control>
</Group>
</OfficeTab>
</ExtensionPoint>
</DesktopFormFactor>
</Host>
</Hosts>
<Resources>
<bt:Images>
<bt:Image id="Contoso.tpicon_16x16" DefaultValue="https://localhost:3000/assets/icon-16.png" />
<bt:Image id="Contoso.tpicon_32x32" DefaultValue="https://localhost:3000/assets/icon-32.png" />
<bt:Image id="Contoso.tpicon_80x80" DefaultValue="https://localhost:3000/assets/icon-80.png" />
</bt:Images>
<bt:Urls>
<bt:Url id="Contoso.Taskpane.Url" DefaultValue="https://localhost:3000/index.html" />
<bt:Url id="Contoso.GetStarted.LearnMoreUrl" DefaultValue="https://go.microsoft.com/fwlink/?LinkId=276812" />
<bt:Url id="Contoso.DesktopFunctionFile.Url" DefaultValue="https://localhost:3000/function-file/function-file.html" />
</bt:Urls>
<bt:ShortStrings>
<bt:String id="Contoso.TaskpaneButton.Label" DefaultValue="Show Taskpane" />
<bt:String id="Contoso.Group1Label" DefaultValue="Commands Group" />
<bt:String id="Contoso.GetStarted.Title" DefaultValue="Get started with your sample add-in!" />
</bt:ShortStrings>
<bt:LongStrings>
<bt:String id="Contoso.TaskpaneButton.Tooltip" DefaultValue="Click to Show a Taskpane" />
<bt:String id="Contoso.GetStarted.Description" DefaultValue="Your sample add-in loaded succesfully. Go to the HOME tab and click the 'Show Taskpane' button to get started." />
</bt:LongStrings>
</Resources>
</VersionOverrides>
<Requirements>
<Sets DefaultMinVersion="1.1">
<Set Name="WordApi" MinVersion="1.3"/>
<Set Name="DialogApi"/>
<Set Name="ImageCoercion"/>
</Sets>
</Requirements>
</OfficeApp>
A:
The sequence of the elements is included in the scheme. It is failing because you are adding Requirements in the wrong sequence. You need to put the Requirements section immediately before the DefaultSettings section:
<Hosts>
<Host Name="Workbook" />
</Hosts>
<Requirements>
<Sets DefaultMinVersion="1.1">
<Set Name="WordApi" MinVersion="1.3"/>
<Set Name="DialogApi"/>
<Set Name="ImageCoercion"/>
</Sets>
</Requirements>
<DefaultSettings>
<SourceLocation DefaultValue="https://localhost:3000/index.html" />
</DefaultSettings>
|
[
"stackoverflow",
"0058224684.txt"
] | Q:
java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Long
I have this block of code in OrderService.java
public void deleteOrderByUserId(int userId){
List<Long> orderIds = orderDAO.getOrderIdByUserId(userId);
int deleteOrders = orderDAO.deleteOrders(orderIds);
}
This is the code in orderDAO.java
public List getOrderIdByUserId(int userId) {
StringBuilder queryStr = new StringBuilder("select distinct u.OrderId from ");
queryStr.append("User u where ");
queryStr.append("u.UserId in (:key)");
return getHibernateTemplate().getSessionFactory()
.getCurrentSession().createSQLQuery(queryStr.toString())
.setParameter("key", userId).list();
}
public int deleteOrders(List<Long> orderIds){
final String deleteOrder = "delete from Order o where o.OrderId in (:orderIds)";
final Query hibernateQuery = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(deleteOrder);
hibernateQuery.setParameterList("orderIds", orderIds);
int count = hibernateQuery.executeUpdate();
return count;
}
I'm getting an java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Long Exception while executing this step int count = hibernateQuery.executeUpdate();
What's wrong with that code and how to get rid of that exception
A:
Instead of using hibernateQuery.setParameterList("orderIds", orderIds);, I've updated it to hibernateQuery.setBigDecimal("orderIds", orderIds);
Now it's working fine.
|
[
"tor.meta.stackexchange",
"0000000010.txt"
] | Q:
Are questions about legal issues on topic?
By legal issues I'm referring specifically to
- legal issues for exit operators
- legal issues for relay operators
- legal issues for bridge operators
I'm thinking topics such as DMCA notices, logging requirements, safe-harbour provisions for ISPs etc.
A:
To play devlis advocate (and give people an opposite point of view to vote on):
I think legal questions should be okay so long as we make a few things clear:
We're not lawyers and (even if we are) can't give proper legal advice
Questions that only require "yes/no" answers are generally considered poor form
Questions should be about specific things; overly broad questions are a bad idea (in general, but I feel like this will happen a lot more with legal questions)
If anyone has any ideas for `good/bad' legal questions, please comment with some examples.
|
[
"stackoverflow",
"0026108003.txt"
] | Q:
Laravel : Response::json with index containing html
I'm trying to figure out why, when returning json array using Laravel's Response::json I get an empty object where it should return an html block.
Here's my method in the controller, which adds new record using Eloquent model:
public function add() {
$data = Input::only(array(
'title'
));
$validation = Validator::make($data, array(
'title' => 'required|min:3|alpha_num_spaces'
));
if ($validation->fails()) {
return Response::json(array(
'error' => true,
'validation' => $validation->messages()
));
}
$todo = new Todo();
$todo->title = $data['title'];
if (!$todo->save()) {
return Response::json(array(
'error' => true,
'validation' => array(
'title' => 'Record could not be added'
)
));
}
$row = View::make('partials.row', array('todo' => $todo));
return Response::json(array(
'error' => false,
'append' => $row
));
}
When everything is validated and record added to database, the last Response::json returns:
{"error":false,"append":{}}
Wheres when I just return View::make('partials.row', array('todo' => $todo)); I get the expected result, which is a table row with the new record:
<tr data-id="17">
<td>
test 8
</td>
<td>
<a href="#" class="edit">Edit</a>
</td>
<td>
<a href="#" class="delete">Delete</a>
</td>
</tr>
Is there a conflict with Response::json and html content?
A:
The solution appears to be the use of the method render():
$row = View::make('partials.row', array('todo' => $todo))->render();
|
[
"stackoverflow",
"0015613386.txt"
] | Q:
Fade out current element and fade in sibling element with the same class
I have the following markup which cannot be edited as it's generated by the server of which I do not have access. The server loads up all of the divs with the class 'contentBox', however it only shows the first one (the other three have 'display: none;' added to them).
I want to add a div with an ID of 'switchButton', so that when it is clicked it fades out the first 'contentBox' div, then fades in the second 'contentBox' div etc. (so press it again, hides second, shows third div).
I need it to loop though, so if it's pressed 4 times, it goes back to the first box.
<div id="switchButton">Click Me</div>
<div class="contentBox">Server side generated content</div>
<div class="contentBox">Server side generated content</div>
<div class="contentBox">Server side generated content</div>
<div class="contentBox">Server side generated content</div>
A:
LIVE DEMO
var c = 0; // counter
var n = $('.contentBox').length; // number of elements
// now using " ++c % n " you can loop your elements
// targeting the EQuivalent one using .eq() method. (0 indexed)
// % is called "reminder" or Modulo (AKA Modulus)
$('#switchButton').click(function(){
$('.contentBox').stop().eq( ++c%n ).fadeTo(500,1).siblings('.contentBox').fadeTo(500,0);
});
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Arithmetic_Operators
http://api.jquery.com/siblings/
http://api.jquery.com/eq/
http://api.jquery.com/fadeto/
Modulo playground
|
[
"security.stackexchange",
"0000033834.txt"
] | Q:
Any tool for scanning vulnerabilities in browser extensions?
I am scanning browser extensions of Chrome and Firefox for vulnerabilities. Is there any tool which would help me do this?
A:
There is one for Chrome, released mid-last year, called XSS ChEF. Based on some earlier work finding vulnerabilities in Chrome extensions. Unfortunately it doesn't seem to be about finding new vulnerabilities but rather an easier way of exploiting/demonstrating them once you have found one.
I haven't used it myself but based on the way it works (it's just a web server), I imagine it's possible to use it to exploit Firefox extensions too or at least to extend it to be able to access Firefox internal state once you have found a vulnerable extension.
BeEF might be a good place to start looking too.
|
[
"stackoverflow",
"0018104621.txt"
] | Q:
Switch between .bind() and .on() - dynamically
I want to do this, because I am working with third-party scripts releated to Internet Marketing. Some of them may contain jQuery library included within and it interfere with recent or latest jQuery Library that is included on my website.
Hence, I'd like to switch between .on() and .bind() dynamically upon website load with a help of variable.
For example, let's say I have global variable:
var incJS = false;
And now depending of the third-party script, I know if they have older Lib included so I'd use this.
function tpNetwork ()
{
incJS = true;
startGateway('XXXXX');
$('#fancybox-outer')
.delay(1000)
.fadeTo(300, 1);
preventGTW();
widgetStyle();
}
Now as you may see there's a function at the very bottom widgetStyle()
That function contain loads of things, but important part is following:
$(window).on('resize', function () {
if ($('.widget_wrap').length) widgetCenter_horizontal();
});
It has .on() method there. That is not supported in very old jQuery that's been used by that third-party network. I'd like to switch every single .on() with .bind() but I don't know how to, without duplicating things.
I did it like this, but it's duplicate and I believe there's easier way.
if (!incJS)
{
$(window).on('resize', function () {
if ($('.widget_wrap').length) widgetCenter_horizontal();
});
}
else
{
$(window).bind('resize', function () {
if ($('.widget_wrap').length) widgetCenter_horizontal();
});
}
Any kind of tips/help is appreciated. I am really out of any ideas and by doing researches I found nothing.
A:
What about:
$(function(){
if(!$.fn.on) $.fn.on = $.fn.bind;
});
Of course, this is excluding any delegation support.
DEMO
|
[
"aviation.stackexchange",
"0000042817.txt"
] | Q:
Can you report a crash landing on an emergency frequency even if you are not at the airport?
You see a crash landing near the airport but you're in a car, no other planes have reported the status of the plane, and Approach can no longer contact the plane. Can you report the crash on an emergency or approach frequency to the tower?
A:
If you are in a car, you probably don't have the full picture. Chances are, if the accident happened "near the airport", emergency services are probably already on the way. This is because the pilot would have been communicating with ATC, and would probably have indicated that he was in trouble before the actual accident. Even if the pilot did not have time to notify ATC, if a plane suddenly "dissapears", search and rescus will be initiated.
In any case, if will do no harm to call the normal emergency services (dial 112 or 911 in some countries). Don't overcomplicate things and try to get in touch with ATC - just dial the emergency number directly, and they will know what to do.
A:
Yes, you can. If you have an aviation handheld or a ham radio in your car, you can call the tower. FCC rules allow you to use any frequency in an emergency. The catch is that you are supposed to exhaust other means first, so if you have a cell phone you should call 911 first.
Note that this is only FCC rules. Your local jurisdiction might still arrest you for interfering with police or fire operations if you, say, were to report the crash on the local EMS repeater.
It's doubtful, though, so long as you do what you are told and are concise.
|
[
"math.stackexchange",
"0003471677.txt"
] | Q:
Compute volume of a revolved solid of equation $2ay^2=x (a−x)^2$
Find the volume of the solid of revolution generated by rotating about $y = a$ the region bounded by the loop of the given relation
$$2ay^2=x (a−x)^2$$
for $0≤x≤a$ and $a>0$.
This seems like a place for the washer method. I would do the volume from the farther edge minus the volume from the closer edge. But, how do I figure out those volumes - it is a loop?
A:
The loop circumference consists of two segments, one above and the other below the $x$-axis, given respectively below by rearranging the loop equation $2ay^2=x(x-a)^2$,
$$y_1(x)=\sqrt{\frac{x(a-x)^2}{{2a}}},\>\>\>\>\>y_2(x)=-\sqrt{\frac{x(a-x)^2}{{2a}}}$$
The segment above the $x$-axis is closer to the revoling axis $y=a$ than the segment below the $x$-axis.
The volume resulting from the loop revolving around the axis $y=a$ is a ring-like solid with the center line same as $y=a$, yet with variable widths in the $x$-direction. It can be viewed as a stack of washers along the $x$-direction over $0\le x\le a$.
For the washer at $x$ (the blue line in the diagram), its the inner and outer radii are respectively $r_1$ and $r_2$, given by
$$r_1= a - y_1(x),\>\>\>\>\>
r_2= a - y_2(x)$$
Then, the area of the washer at $x$ is
$$A(x) = \pi(r_2^2-r_1^2) =\pi \left(a+\sqrt{\frac{x(a-x)^2}{{2a}}}\right)^2-\pi\left(a-\sqrt{\frac{x(a-x)^2}{{2a}}}\right)^2=2\pi\sqrt{2ax}(a-x) $$
Then, the volume is obtained from integrating over the washer areas over $0\le x\le a$,
$$V = \int_0^a A(x)dx
= 2\pi\sqrt{2a}\int_0^a \sqrt{x}(a-x)dx$$
$$=2\pi\sqrt{2a}\cdot\frac{4a^{5/2}}{15}
=\frac{8\sqrt2}{15}\pi a^3$$
|
[
"stackoverflow",
"0036196606.txt"
] | Q:
Php add 5 working days to current date excluding weekends (sat-sun) and excluding (multiple) holidays
For delivery of our webshop, we need to calculate 5 working days from the current date in php.
Our working days are from monday to friday and we have several closing days (holidays) which cannot be included either.
I've found this script, but this doesn't include holidays.
<?php
$_POST['startdate'] = date("Y-m-d");
$_POST['numberofdays'] = 5;
$d = new DateTime( $_POST['startdate'] );
$t = $d->getTimestamp();
// loop for X days
for($i=0; $i<$_POST['numberofdays']; $i++){
// add 1 day to timestamp
$addDay = 86400;
// get what day it is next day
$nextDay = date('w', ($t+$addDay));
// if it's Saturday or Sunday get $i-1
if($nextDay == 0 || $nextDay == 6) {
$i--;
}
// modify timestamp, add 1 day
$t = $t+$addDay;
}
$d->setTimestamp($t);
echo $d->format('Y-m-d'). "\n";
?>
A:
You can use the "while statement", looping until get enough 5 days. Each time looping get & check one next day is in the holiday list or not.
Here is the the example:
$holidayDates = array(
'2016-03-26',
'2016-03-27',
'2016-03-28',
'2016-03-29',
'2016-04-05',
);
$count5WD = 0;
$temp = strtotime("2016-03-25 00:00:00"); //example as today is 2016-03-25
while($count5WD<5){
$next1WD = strtotime('+1 weekday', $temp);
$next1WDDate = date('Y-m-d', $next1WD);
if(!in_array($next1WDDate, $holidayDates)){
$count5WD++;
}
$temp = $next1WD;
}
$next5WD = date("Y-m-d", $temp);
echo $next5WD; //if today is 2016-03-25 then it will return 2016-04-06 as many days between are holidays
A:
A function based on Tinh Dang's answer:
function getFutureBusinessDay($num_business_days, $today_ymd = null, $holiday_dates_ymd = []) {
$num_business_days = min($num_business_days, 1000);
$business_day_count = 0;
$current_timestamp = empty($today_ymd) ? time() : strtotime($today_ymd);
while ($business_day_count < $num_business_days) {
$next1WD = strtotime('+1 weekday', $current_timestamp);
$next1WDDate = date('Y-m-d', $next1WD);
if (!in_array($next1WDDate, $holiday_dates_ymd)) {
$business_day_count++;
}
$current_timestamp = $next1WD;
}
return date('Y-m-d', $current_timestamp);
}
I made it limit the loop to 1000 business days. There could be no limit if desired.
|
[
"stackoverflow",
"0021366919.txt"
] | Q:
JFrame Java setColor and fillRect staying Blank?
Why am I getting a Blank screen instead of Black when I debug or run?? I've looked everywhere and tried a lot! Please help. I'm just trying to make my screen black as I am a beginner to all of this java coding. I don't believe anything is wrong with the code as I'm not getting any errors. I'm using eclipse.
package com.techon.rain;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static int width =300;
public static int height = width / 16 * 9;
public static int scale =3;
private JFrame frame;
private Thread thread;
private boolean running = false;
public Game() {
Dimension size = new Dimension(width*scale, height*scale);
setPreferredSize(size);
frame = new JFrame();
}
public synchronized void start() {
running = true;
thread = new Thread(this, "Display");
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
while(running);{
update();
render();
}
}
public void update() {
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0,0,getWidth(),getHeight());
g.dispose();
bs.show();
}
public static void main(String[] args) {
Game game = new Game();
game.frame.setResizable(false);
game.frame.setTitle("Rain");
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
}
A:
replace
public void run() {
while(running);{
update();
render();
}
by
public void run() {
while(running){
update();
render();
}
due to while(running); it is not executing other stetement inside loop.
|
[
"stackoverflow",
"0049558561.txt"
] | Q:
Nested if / else clauses in List Comprehension Syntax Error
Starting with the following list comprehension:
new_list = [re.sub(r'replace_a', 'with__b', i)
if not re.findall(r'find_pattern', i, re.M) else
re.sub(r'replace_c', r'with__d', i)
for i in old_list]
Now I would like to add an if condition after else that replaces another pattern using re.sub(). I tried with:
new_list = [re.sub(r'replace_a', 'with_b', i)
if not re.findall(r'find_pattern', i, re.M) else
(re.sub(r'replace_c', r'with_d', i)
if foo == re.match("pattern", foo))
for i in old_list]
Tried to figure out the proper way to do it with list comprehensions but had no luck.
A:
This will read much more easily as a regular for loop:
new_list = []
for i in old_list:
if not re.findall(r'find_pattern', i, re.M):
new_list.append(re.sub(r'replace_a', 'with_b', i))
elif foo == re.match("pattern", foo):
new_list.append(re.sub(r'replace_c', r'with_d', i))
# else:
# i
Your problem is that a conditional expression must always take an else clause, because it has to have some value whether or not the condition is true. With an if statement, however, you can omit the else. The above, for instance, has the ability to make new_list shorter than old_list, as not every i needs to result in a call to new_list.append. Uncommenting the else results in the same result as jpp's answer.
If you insist on using a list comprehension, then you can format it to make it more readable. Consider
new_list = [re.sub(r'replace_pattern_a', 'with_pattern_b', i)
if not re.findall(r'find_pattern', i, re.M) else
re.sub(r'replace_pattern_c', r'with_pattern_d', i)
if foo == re.match("pattern", foo) else
i
for i in old_list]
although the conditional expression really isn't designed for such nesting. This visually separates the expressions that could be added to the new list from the conditions used to make the decision, but I'm not a big fan. There are other ways to format that make different trade-offs, but IMO the regular for loop is superior.
As jpp mentions, another way to refactor is to define a generator function:
def foo(old_list):
for i in old_list:
if not re.findall(r'find_pattern', i, re.M):
yield re.sub(r'replace_a', 'with_b', i))
elif foo == re.match("pattern", foo):
yield re.sub(r'replace_c', r'with_d', i))
else:
yield i
new_list = list(foo())
which would have its pros and cons as well. (I think enumerating those is probably beyond the scope of this answer, but it does fall somewhere between the two extremes of a single list comprehension and an explicit for loop. It also comes closest to the construct I miss from my Perl days, the do statement, which is something like a lambda that doesn't take any arguments, but can contain arbitrary statements.)
|
[
"stackoverflow",
"0055664207.txt"
] | Q:
Complete stream and emit last value
How to complete stream by condition, while radiating value at which stream completed?
const MAX_VALUE = 6;
const competePredicate = data => data <= MAX_VALUE;
let imitationsOfClientConnection = of( 0, 1, 2, 3, 4, 5 );
imitationsOfClientConnection.pipe(
scan((result, current) => result + current, 0),
// <- what to write here?
).subscribe({
next: data => console.log(`You won: ${ data } points!`),
complete: () => console.log('complete')
});
Now output to console is -
You won: 0 points!
You won: 1 points!
You won: 3 points!
You won: 6 points!
You won: 10 points!
You won: 15 points!
complete
What code you need to write that output to console was this -
You won: 0 points!
You won: 1 points!
You won: 3 points!
You won: 6 points!
complete
A:
takeWhile should do the trick.
imitationsOfClientConnection.pipe(
scan((result, current) => result + current, 0),
takeWhile(total => total <= MAX_VALUE)
).subscribe(//...
https://stackblitz.com/edit/typescript-aycaxs?file=index.ts
|
[
"stackoverflow",
"0042788808.txt"
] | Q:
Loading a PDF in SfPdfViewerControl with default view mode
I'm trying to implement a PDF viewer with the Syncfusion's solution, SfPdfViewerControl. I need to have a default state for this viewer's ViewMode (fit width or height), in a Syncfusion.Windows.PdfViewer.PageViewMode's enum called _defaultDisplayType.
To do so, i'm simply doing a :
_pdfViewer.ViewMode = PageViewMode.FitWidth;
Where _pdfViewer is my instance of SfPdfViewerControl.
I'm doing it when the _pdfViewer trigger his DocumentLoaded event :
_pdfViewer.DocumentLoaded += _pdfViewer_CurrentDocumentLoaded;
And my method called looks like :
private void _pdfViewer_CurrentDocumentLoaded(object sender, DocumentLoadedEventArgs e)
{
_pdfViewer.ViewMode = _defaultDisplayType;
}
However, even though the ViewMode's property properly changes to FitWidth, the final result looks like this :
And when I try to change the ViewMode's value manually, from a button, the viewer finally sized well :
Am I doing it wrong ? I assume that I should be using some kind of setter method or command but the documentation doesn't seems to prove me wrong.
A:
We can reproduce the issue on our side. The fix for this issue will be included in our main release Essential Studio Volume 2 which is expected to be available by the end of April, 2017.
Best,
Navaneetha Kannan
|
[
"security.stackexchange",
"0000222269.txt"
] | Q:
Security of service requests on a public Wifi
I'm currently rebuilding my network infrastructure and am planning to make my NAS available trough an OpenVPN server running on my router for "outside" use (no port forwarding: NAS in private LAN, available trough the VPN).
Now I was wondering about a certain scenario:
let's say, I have mapped some of the NAS's drives as network drives via SMB/CIFS in Windows on my laptop (using the local IP address of the NAS in the LAN) or have a proprietary software of the NAS's manufacturer trying to connect to a certain service on a dedicated port.
If I were to take this notebook to an unsecured, public wifi- would this expose the local LAN IP's and/or ports in the CIFS request or the connection request coming from the proprietary software until I'm connected to my VPN (i.e. in the very moment, I'm connecting to the wifi until the VPN tunnel is up)?
Does this depend on the way such a request is implemented in the software?
A:
Note: Not exactly an answer to the question asked but side-steps the need to know for the OP.
Answer: You could block the outbound of this application with a host-based firewall for any network adapter besides the virtual adapter of your VPN.
|
[
"stackoverflow",
"0024889907.txt"
] | Q:
How to use SimpleJdbcDaoImpl accross different classes - Spring
I'm getting a null pointer when I try to access and use a SimpleJdbcDaoSupport. This is how I'm working it out:
In the main class
@Override
public void start(final Stage primaryStage) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
SimpleJdbcDaoImpl dao = ctx.getBean("simpleJdbcDaoImpl", SimpleJdbcDaoImpl.class);
In some other stage controller class
public class HomeController implements Initializable {
@Autowired
private SimpleJdbcDaoImpl simpleJdbcDaoImpl;
// Initializes the controller class.
@Override
public void initialize(URL url, ResourceBundle rb) {
// Stage and the rest called
}
@FXML
public void showNewCalendarStage() throws Exception {
System.out.println(simpleJdbcDaoImpl.getCircleCount());
}
The SimpleJdbcDaoSupport class
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
public class SimpleJdbcDaoImpl extends SimpleJdbcDaoSupport {
public int getCircleCount() {
String sql = "SELECT COUNT(*) FROM KIWI_TABLE";
return this.getJdbcTemplate().queryForInt(sql);
}
}
The spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:file:C:/WAKILI/WAKILIdb"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="simpleJdbcDaoImpl" class="wakiliproject.dao.SimpleJdbcDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation">
<value>
classpath:/hibernate.cfg.xml
</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.H2Dialect</prop>
</props>
</property>
</bean>
<context:annotation-config/>
<context:component-scan base-package="wakiliproject"/>
</beans>
The error:
Caused by: java.lang.NullPointerException
at HomeController.showNewCalendarStage(HomeController.java:283)
... 42 more
I'm trying to teach myself Spring and would like to, for example, populate a Label in another Controller class (other than the main class) with text retrieved from the database.
For simplicity, in this case, lets print some text from the database to the console. What am I doing wrong with the above code? Thank you all.
A:
In order for a Spring bean to be injected with its collaborators, it has to be managed by Spring. The HomeController is actually managed by FXML, which knows nothing about Spring annotations (@Autowired) and will ignore them. Even worse, assuming that the HomeController is under the wakiliproject package (or one of its subpackages), Spring will indeed create another instance of the HomeController that will have the @Autowired stuff injected but NOT the @FXML stuff.
Depending on how you load the controller you may be able to set the instance of the HomeController retrieved from Spring as the controller of the .fxml view. So:
Make sure Spring actually sees the HomeController (this will give you an instance of HomeController with the @Autowired stuff injected).
Load the FXML document as:
HomeController homeController = springContext.getBean(HomeController.class);
FXMLLoader fxmlLoader = new FXMLLoader(xxx.getResource("HomeController.fxml"));
fxmlLoader.setController(homeController);
try {
fxmlLoader.load();
} catch...
The above is almost pseudo-code, adapt as necessary!
If the load() is successful, the the @FXML fields of the controller will be populated too and its initialization method will be called.
Check out the VERY helpful answer to this question.
|
[
"stackoverflow",
"0012172983.txt"
] | Q:
Android linear layout not matching its parent
I am creating a listview inside a scroll view, i want the listview to match its parent. the Scroll view is matching its parent and acquiring complete screen. but the linear layout inside it is not matching its parent and acquirig the whole screen, so as the list view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/linearlayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
</ScrollView>
</LinearLayout>
A:
Yes, as njzk2 said, you can't do that. I had issues with ListViews in a scrollview
I don't use ListViews. I just use Buttons in general. They work much better.
|
[
"stackoverflow",
"0047674815.txt"
] | Q:
Is it possible to send voice notification to Google Home device
We want to send voice notifications to Google Home device from our service when we get some specific events but not sure if it is even supported/possible.
For example, we will notify the user when the cook is almost ready like:
'Hey Ender, your meal will be ready in 5 minutes. Don't forget to take it out'
There are some scripts that claim they send voice notification to Google Home device however they seem to work in the local environment which is not our case.
One of the example scripts is posted on Reddit by @S1lentAssass1n
https://github.com/GhostBassist/GooglePyNotify
Google mentions some reminder/notification in Google Home documents but I believe it is not what we what.
https://support.google.com/googlehome/answer/7387866?co=GENIE.Platform%3DAndroid&hl=en
Any idea/help would be appreciated!
A:
Notifications on the Google Assistant platform are currently in Developer Preview. You can't release an Action that supports them, yet, and they currently on work on mobile devices - not speakers such as Google Home.
This will likely change as it moves out of Developer Preview and into production, but they haven't announced a time frame for this yet.
The solution you cite from Reddit uses the Google Home as a Chromecast Audio device, so requires a (separate) local agent to cast to it. The notes about Google Home refer to the consumer feature from Google that allows you to set notices and reminders - not for other applications.
|
[
"math.stackexchange",
"0000986322.txt"
] | Q:
How to prove this sequence is convergent?
Suppose that the series $\sum_{k=1}^\infty{a_k}$ converges. Prove that
$$\lim_{n→\infty}\frac{1}{n}\sum_{k=1}^{n}ka_k=0$$
I tried to use the definition of convergence of $\sum a_k$ but I'm struggling to find $N$ such that given $\epsilon >0$, if $n>N$, then $-\epsilon<\frac{1}{n}\sum_{k=1}^{n}ka_k<\epsilon$ but I don't know how to connect them
hope somebody can help
A:
Let $s_n=a_1+\cdots+a_n\to a$. Then
$$
\sum_{k=1}^n ka_k=\sum_{k=1}^n k(s_k-s_{k-1})=\sum_{k=1}^n ks_k-\sum_{k=1}^{n-1}(k+1)s_k=ns_n-\sum_{k=1}^{n-1}s_k.
$$
Hence
$$
\frac{1}{n}\sum_{k=1}^n ka_k=s_n-\frac{n-1}{n}\cdot\frac{1}{n-1}\sum_{k=1}^{n-1}s_k\to a-a=0.
$$
We have used the fact that: If $b_n\to b$, then so does $\,\,\dfrac{b_1+\cdots+b_n}{n}$.
Note. However, it is not in general true that $na_n\to 0$.
|
[
"stackoverflow",
"0029832089.txt"
] | Q:
generate random 0 or 1 - Oracle
I need to generate a random value that can be 0 or 1. I tried this: select floor(DBMS_RANDOM.VALUE (0, 1)) from dual but there is a very very very low possibility of get value 1. Is there any chance to get this where the possibilities for 0 and 1 are similar?
A:
DBMS_RANDOM.VALUE(0,1) will never return 1. From the documentation:
low The lowest number in a range from which to generate a random
number. The number generated may be equal to low.
high The highest number below which to generate a random number. The
number generated will be less than high.
You want: floor(DBMS_RANDOM.VALUE(0,2))
A:
Try to use round instead of floor:
select round(DBMS_RANDOM.VALUE (0, 1)) from dual
A:
Use DBMS_RANDOM.RANDOM to get an integer, and mod (n,2) to get 0 (even number) or 1 (odd number)
|
[
"stackoverflow",
"0050031026.txt"
] | Q:
get object on ListView Tappedevent
I have a listview that is being populated from an SQLite DB. For that listview have constructed a method for handling when a listview element is being tapped:
xaml cell:
<ListView x:Name="CalculationListview" ItemsSource="{Binding Calculation}" HasUnevenRows="true" IsPullToRefreshEnabled="true" Refreshing="Handle_Refreshing">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell Tapped="Handle_Tapped">
<ViewCell.ContextActions>
<MenuItem Text="Delete" IsDestructive="True" Clicked="Handle_Clicked" />
</ViewCell.ContextActions>
<StackLayout>
<Label Text="{Binding Qty}">
</Label>
<Label Text="{Binding Note}">
</Label>
<Label Text="{Binding Id}">
</Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
c#
async void Handle_Tapped(object sender, System.EventArgs e)
{
var viewCellSelected = sender as MenuItem;
var calculation = viewCellSelected?.BindingContext as Calculation;
var page = new ViewSaved(calculation);
await Navigation.PushModalAsync(page);
}
As you can see, I want to retrieve the object Calculation from the given listview element and send the object to a new view named ViewSaved.
Unfortunately, my variable calculation remains null and I get an exception when I send the empty object to my new view.
I suspect that sender as MenuItem; is the issue.
A:
instead of putting the Tapped handler on the ViewCell, either use the ListView's ItemTapped or ItemSelected methods
void Handle_ItemTapped(object sender, ItemTappedEventArgs e)
{
var item = (Calculation)i.Item;
}
|
[
"stackoverflow",
"0029462496.txt"
] | Q:
Intersection of two nested lists in Python
I've a problem with the nested lists. I want to compute the lenght of the intersection of two nested lists with the python language. My lists are composed as follows:
list1 = [[1,2], [2,3], [3,4]]
list2 = [[1,2], [6,7], [4,5]]
output_list = [[1,2]]
How can i compute the intersection of the two lists?
A:
I think there are two reasonable approaches to solving this issue.
If you don't have very many items in your top level lists, you can simply check if each sub-list in one of them is present in the other:
intersection = [inner_list for inner in list1 if inner_list in list2]
The in operator will test for equality, so different list objects with the same contents be found as expected. This is not very efficient however, since a list membership test has to iterate over all of the sublists. In other words, its performance is O(len(list1)*len(list2)). If your lists are long however, it may take more time than you want it to.
A more asymptotically efficient alternative approach is to convert the inner lists to tuples and turn the top level lists into sets. You don't actually need to write any loops yourself for this, as map and the set type's & operator will take care of it all for you:
intersection_set = set(map(tuple, list1)) & set(map(tuple, list2))
If you need your result to be a list of lists, you can of course, convert the set of tuples back into a list of lists:
intersection_list = list(map(list, intersection_set))
|
[
"stackoverflow",
"0058643044.txt"
] | Q:
Getting "The parameters dictionary contains a null entry for parameter 'ID' of non-nullable type 'System.Int32' for method X" in C#
When I run this command from my view in exceptions.html
<tr ng-repeat="scbEXCEPtions in vm.scbExpData">
<td>
<button class="btn btn-alert btn-xs" ng-click="vm.DelExceptionObjRef(scbEXCEPtions.REF_ID)">
Remove
</button>
</td>
</tr>
and in my controller file exception.js, this is the method I call
vm.DelExceptionObjRef = function (refno) {
vm.viewModelHelper.apiGet('api/scbexception/RevertExceptionById/' + refno, null,
function (result) {
vm.prepareData(result.data);
},
function (result) {
toastr.error(result.data, 'Fintrak');
}, null);
}
which generates this URL when clicked on, even after setting a breakpoint on the apicontroller file, I get this error:
http://localhost:6861/api/scbEXCEPtion/RevertExceptionById/10000011943
and I have a method in my Api Controller { ScbExceptionApiController } that receives the function and method here...
[HttpGet]
[Route("RevertExceptionById/{ID}")]
public HttpResponseMessage RevertExceptionById(HttpRequestMessage request, int ID){
return GetHttpResponse(request, () => {
HttpResponseMessage response = null;
ScbException[] scbexception = _APPModuleService.RevertExceptionById(ID);
response = request.CreateResponse<ScbException[]>(HttpStatusCode.OK, scbexception);
return response;
});
}
but after execution I get this error, and I don't understand why
{"Message":"The request is invalid.","MessageDetail":"The parameters dictionary contains a null entry for parameter 'ID' of non-nullable type 'System.Int32' for method 'System.Net.Http.HttpResponseMessage RevertExceptionById(System.Net.Http.HttpRequestMessage, Int32)' in 'Fintrak.Presentation.WebClient.API.ScbExceptionApiController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."}
A:
RevertExceptionById(HttpRequestMessage request, int ID) is expecting ID as an int, which is a 32-bit integer.
The max value of a 32-bit integer is 2147483647. You're passing 10000011943 as the ID, which is exceeding this max value.
I suspect this is the reason the parameter binding for ID is failing with the given exception.
Possible solutions could be: use lower ids, or use string instead of int for the ID.
|
[
"stackoverflow",
"0031522415.txt"
] | Q:
How to access a variable in the derived class in c++?
I have a vector of several different class data types and I'm trying to print the derived class variable.
Here is the diagram of the Classes
I have the diagram implemented. I am trying to print score from the assignment class in the grading class.
The error is in the friend ostream& operator<<(ostream& os, const CourseWork& dt) function.
Here is my classes
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iomanip>
using namespace std;
/* -------------------------------------------------------- */
/* ---------------------- Grading Class ------------------- */
/* -------------------------------------------------------- */
class Grading
{
public:
string name;
int percent;
void get_raw_score();
void get_adj_score();
};
/* -------------------------------------------------------- */
/* ---------------------- Assignment Class ---------------- */
/* -------------------------------------------------------- */
class Assignment : public Grading
{
protected:
int score;
};
/* -------------------------------------------------------- */
/* ---------------------- Exam Class ---------------------- */
/* -------------------------------------------------------- */
class Exam : public Grading
{
protected:
int score;
Exam(string n, int g, int s) {
name = n;
percent = g;
score = s;
}
};
/* -------------------------------------------------------- */
/* ------------------- Project Class ---------------------- */
/* -------------------------------------------------------- */
class Project : public Assignment
{
public:
string letter_grade;
Project(string n, int g, string l_g) {
name = n;
percent = g;
letter_grade = l_g;
}
};
/* -------------------------------------------------------- */
/* ---------------------- Quiz Class ---------------------- */
/* -------------------------------------------------------- */
class Quiz : public Exam
{
public:
string letter_grade;
Quiz(string n, int g, string l_g) : Exam(n, g, score)
{
name = n;
percent = g;
letter_grade = l_g;
}
};
/* -------------------------------------------------------- */
/* ---------------------- CourseWork class ---------------- */
/* -------------------------------------------------------- */
class CourseWork {
public:
CourseWork() {}
void push_back(Quiz * a) {
work.push_back(a);
}
void push_back(Exam * a) {
work.push_back(a);
}
void push_back(Project * a) {
work.push_back(a);
}
// print the data and sort by name
void sort_name() {
for (int i = 0; i < (int)work.size(); i++)
cout<< work.at(i)->name <<endl;
}
void sort_score() {
}
friend ostream& operator<<(ostream& os, const CourseWork& dt) {
cout << "Grading" << std::setw(20) << "Percentage" << std::setw(20) << "Raw-Score" << endl;
for (int i = 0; i < (int)dt.work.size(); i++) {
// cout << dt.work.at(i)->name << std::setw(20) << dt.work.at(i)->percent << dt.work.at(i)->score <<endl;
os << dt.work.at(i)->name << std::setw(20) << dt.work.at(i)->percent << dt.work.at(i)->letter_grade;
}
return os;
}
private:
vector<Grading*> work;
};
/* -------------------------------------------------------- */
/* ---------------------- MAIN ---------------------------- */
/* -------------------------------------------------------- */
int main () {
CourseWork c;
c.push_back(new Quiz("Quiz", 5, "B-"));
c.push_back(new Quiz("Quiz", 5, "C+"));
c.push_back(new Quiz("Quiz", 5, "A"));
// c.push_back(new Exam("Midterm", 10, 50));
// c.push_back(new Exam("Final", 30, 85.5));
// c.push_back(new Project("Project", 5, "A-"));
// c.push_back(new Project("Project", 15, "B-"));
// c.push_back(new Project("Project", 15, "B-"));
// c.push_back(new Project("Demo", 10, "C"));
cout << "** Showing populated data..." << endl;
cout << c << endl << endl;;
// c.sort_name();
// c.sort_score();
return 0;
}
A:
You are storing Grading* objects in your CourseWork object:
vector< Grading* > work;
So you cannot access the members of a derived class through the pointer of the base class. You should introduce a new (pure) virtual function in your base class which shall print the parameters of the derived class.
class Grading
{
public:
virtual ~Grading() {}
virtual print() const = 0;
// ...
}
And you shall implement this in all your derived class.
Also it makes no sense to create these functions if you add the given parameters into the same verctor:
void push_back( Quiz* a )
{
work.push_back(a);
}
void push_back( Exam* a )
{
work.push_back(a);
}
void push_back( Project* a )
{
work.push_back(a);
}
You just need one function:
void push_back( Grading* a )
{
work.push_back(a);
}
Or if you really want to access the members of the derived classes then you need to cast. But use the virtual methods instead.
|
[
"networkengineering.stackexchange",
"0000041008.txt"
] | Q:
Host behavior with mask +1 and -1
Let's suppose I have a configuration:
host: 192.168.1.145/25
gateway: 192.168.1.129
network: 192.168.1.128/25
broadcast: 192.168.1.255
What happens if I add +1 bit and remove -1 bit to the mask?
1) /26
network: 192.168.1.128/26
broadcast: 192.168.1.191
Does it affect the host IP?
2) /24
network: 192.168.1.0/24
broadcast: 192.168.1.255
Does it affect the host IP?
So with this example I don't see any difference. But maybe I make something wrong? How should such type of example be done?
A:
All your assumptions are correct. Subnet mask determines subnet length. So in cases you described length of network changes, but host remains inside of the network. The difference is .145 will not need routing entry (except connected 192.168.1 one) in order to reach, say, .200 with /24 and /25 mask, but it will need route in order to reach the same .200 host with /26 mask. And similarly it'll reach .1 without routing entry with /24 mask, but not with /25 and /26.
|
[
"cs.stackexchange",
"0000097992.txt"
] | Q:
Karp hardness of testing for homomorphisms to a fixed non-bipartite graph
Description: Suppose that we are given a fixed non-bipartite graph $H$. A graph $G$ is loopless surjectively homomorphic to $H$ if there exists a loopless surjective homomorphism $\varphi:V(G)\to V(H)$ such that:
For every $u,v\in V(G)$, $(\varphi(u)=\varphi(v))\lor(uv\in E(G)\implies\varphi(u)\varphi(v)\in E(H))$.
Note that we do not allow loops and multiple edges. This is just because $H$ is a fixed simple undirected graph. So, mapping to the same vertices is good but remember to map to every vertex of $H$. This also does not put constraint on those vertices mapped to the same $H$-vertex. By standard definition, without a loop at that $H$-vertex, the set of $G$-vertices mapped to it needs to be an independent set.
We want to decide whether a given graph $G$ is loopless surjectively homomorphic to $H$. Note that for each fixed non-bipartite $H$, we have a decision problem, denoted by $\mathrm{HOMOMORPHIC}_H$.
Formally, for every fixed (i.e. not part of the input) non-bipartite graph $H$, $\mathrm{HOMOMORPHIC_H}$ is defined as below:
Input: An undirected graph $G$
Output: YES if $G$ is loopless surjectively homomorphic to $H$, otherwise NO
We want to know the computational complexity of this problem.
A:
Your question is more easily phrased as follows. You have a fixed non-bipartite, reflexive graph $H$ (reflexive = a loop on every vertex) and you want to know the complexity of deciding whether there is a surjective homomorphism (in the usual sense) from an input graph $G$ to $H$.
As far as I can see, this question is open.
The problem is trivially in P when $H$ is a clique, since every $G$ with $|V(G)|\geq|V(H)|$ has a surjective homomorphism.
Golovach et al. [1] have shown, for each four-vertex $H$, that the problem is either in P or is NP-complete (including bipartite cases, and allowing loops on any strict subset of the vertices).
I don't know of anything else with loops on all vertices.
[1] P. A. Golovach, M. Johnson, B. Martin, D. Paulusma, A. Stewart, Surjective $H$-colouring: new hardness results. ArXiv, 2017.
|
[
"stackoverflow",
"0025192915.txt"
] | Q:
What is 'a used for in Rust signatures?
I see signatures like:
fn get<'a>(&'a self, index: uint) -> &'a T
For a impl<T> Vec<T>, but I cannot find a clear explanation of the 'a part in the tutorial, the guide or the manual.
A:
A 'a is a lifetime, representing that the returned &T reference is valid for (at least) as long as the self reference. This occurs when the returned reference points to memory owned by one of the input parameters (or points into a reference stored in the input parameters), with the named lifetime informing the compiler of the exact relationship by linking the references that have an "ownership connection".
Further information:
This answer (it's old now, so the code won't compile, but the explanations still hold)
The "References and Lifetimes guide" (in particular the "named lifetime" section at the end)
|
[
"stackoverflow",
"0022041638.txt"
] | Q:
Print list as array Python
I have a list with elements like (x,y,value) how can I print that list as array where all the elements of the list with x are on the same line?
I tried this but it doesn’t work
def print_list(l,size):
for x in l:
print x[2]
My main problem is that I don't know how to print elements of the list in the same line, cause this way it prints each element in a new line.
Edit: I wasn't clear enough my list simulates an array eg for size=2 my list would have elements like this:
[0,0,value1]
[0,1,value2]
[1,0,value3]
[1,1,value3]
My functions prints it this way:
value1
value2
value3
value4
I want to modify my function in order to be printed like this:
value1 value2
value3 value4
A:
EDIT:
This should work:
def print_list(l,size):
for n in range(0, len(l), size):
values = [str(x[2]) for x in l[n:n+size]]
print(' '.join(values))
Original answer:
Using the print statement:
def print_list(l,size):
for x in l:
print x[2],
or using the print function:
from __future__ import print_function
def print_list(l,size):
for x in l:
print(x[2], end='')
Note: adding the comma after the print statement adds a space after the string you print. If you don't want the space, then it's best to use the print function.
|
[
"stackoverflow",
"0027864761.txt"
] | Q:
Using map function in swift to make MKPointAnnotations
I have an array of "place" objects with coordinates and names.
for example:
let places = [place(name: "Eiffel Tower", latitude: 48.8582, longitude: 2.2945), place(name: "Statue of Liberty", latitude: 40.6892, longitude: -74.0444), place(name: "Tower of London", latitude: 51.5081, longitude: -0.0761)]
From this array, I would like to create a new array of MKPointAnnotations using map. I know it starts like this:
let placeAnnotations = places.map{ (place -> MKPointAnnotation // but that's about all I know for sure!}
... I don't know how to set MKPointAnnotation's .coordinate and .title properties without committing some syntax error. Thank you!
A:
Yes, you're on the right track. This is the full code:
let places = [place(name: "Eiffel Tower", latitude: 48.8582, longitude: 2.2945), place(name: "Statue of Liberty", latitude: 40.6892, longitude: -74.0444), place(name: "Tower of London", latitude: 51.5081, longitude: -0.0761)]
let annotations = places.map { aPlace -> MKPointAnnotation in
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: aPlace.latitude, longitude: aPlace.longitude)
return annotation
}
println(annotations)
|
[
"sharepoint.stackexchange",
"0000185864.txt"
] | Q:
How to move a file stored in a folder of a document library into the root of that document library (Sharepoint 2013)?
There are multiple articles, tutorials, and videos on the web that show how to move a file into a folder. However I cannot find references for the opposite scenario.
How to move a file located in a folder into the root folder of the document library?
My interest is from an end-user prespective (basically doing it using the standard interface) not from a programming perspective.
A:
To do so, select a file located in a subfolder and drag&drop it onto the Document Library shortcut in the Left Pane.
I found this video from European Sharepoint Community that explains very well how to do it.
This video tutorial covers:
moving a file from the root of Document Library to a subfolder in the same Document Library,
moving a file from a subfolder in the Document Library to the root of the Document Library,
moving a file from a subfolder to a different subfolder in the same Document Library.
|
[
"stackoverflow",
"0058326612.txt"
] | Q:
Crop empty arrays (padding) from a volume
What I want to do is crop a volume to remove all irrelevant data. For example, say I have a 100x100x100 volume filled with zeros, except for a 50x50x50 volume within that is filled with ones.
How do I obtain the cropped 50x50x50 volume from the original ?
Here's the naive method I came up with.
import numpy as np
import tensorflow as tf
test=np.zeros((100,100,100)) # create an empty 100x100x100 volume
rand=np.random.rand(66,25,34) # create a 66x25x34 filled volume
test[10:76, 20:45, 30:64] = rand # partially fill the empty volume
# initialize the cropping coordinates
minx=miny=minz=0
maxx=maxy=maxz=0
maxx,maxy,maxz=np.subtract(test.shape,1)
# compute the optimal cropping coordinates
dimensions=test.shape
while(tf.reduce_max(test[minx,:,:]) == 0): # check for empty slices along the x axis
minx+=1
while(tf.reduce_max(test[:,miny,:]) == 0): # check for empty slices along the y axis
miny+=1
while(tf.reduce_max(test[:,:,minz]) == 0): # check for empty slices along the z axis
minz+=1
while(tf.reduce_max(test[maxx,:,:]) == 0):
maxx-=1
while(tf.reduce_max(test[:,maxy,:]) == 0):
maxy-=1
while(tf.reduce_max(test[:,:,maxz]) == 0):
maxz-=1
maxx,maxy,maxz=np.add((maxx,maxy,maxz),1)
crop = test[minx:maxx,miny:maxy,minz:maxz]
print(minx,miny,minz,maxx,maxy,maxz)
print(rand.shape)
print(crop.shape)
This prints:
10 20 30 76 45 64
(66, 25, 34)
(66, 25, 34)
, which is correct. However, it takes too long and is probably suboptimal. I'm looking for better ways to achieve the same thing.
NB:
The subvolume wouldn't necessarily be a cuboid, it could be any shape.
I want to keep gaps within the subvolume, only remove what's "outside" the shape to be cropped.
A:
While you wait for a sensible response (I would guess this is a builtin function in an image processing library somewhere), here's a way
y, x = np.where(np.any(test, 0))
z, _ = np.where(np.any(test, 1))
test[min(z):max(z)+1, min(y):max(y)+1, min(x):max(x)+1]
I think leaving tf out of this should up your performance.
Explanation (based on 2D array)
test = np.array([
[0, 0, 0, 0, 0, ],
[0, 0, 1, 2, 0, ],
[0, 0, 3, 0, 0, ],
[0, 0, 0, 0, 0, ],
[0, 0, 0, 0, 0, ],
])
We want to crop it to get
[[1, 2]
[3, 0]]
np.any(..., 0) this will 'iterate' over axis 0 and return True if any of the elements in the slice are truthy. I show the result of this in the comments here:
np.array([
[0, 0, 0, 0, 0, ], # False
[0, 0, 1, 2, 0, ], # True
[0, 0, 3, 0, 0, ], # True
[0, 0, 0, 0, 0, ], # False
[0, 0, 0, 0, 0, ], # False
])
i.e. it returns np.array([False, True, True, False, False])
np.any(..., 1) does the same as step 2 but over axis 1 instead of axis zero i.e.
np.array([
[0, 0, 0, 0, 0, ],
[0, 0, 1, 2, 0, ],
[0, 0, 3, 0, 0, ],
[0, 0, 0, 0, 0, ],
[0, 0, 0, 0, 0, ],
# False False True True False
])
Note that in the case of a 3D array, these steps return 2D arrays
(x,) = np.where(...) this returns the index values of the truthy values in an array. So np.where([False, True, True, False, False]) returns (array([1, 2]),). Note that this is a tuple so in the 2D case we would need to call (x,) = ... so x is just the array array([1, 2]). The syntax is nicer in the 2D case as we can use tuple-unpacking i.e x, y = ...
Note that in the 3D case, np.where can give us the value for 2 axes at a time. I chose to do x-y in one go and then z-? in the second go. The ? is either x or y, I can't be bothered to work out which and since we don't need it I throw it away in a variable named _ which by convention is a reasonable place to store junk output you don't actually want. Note I need to do z, _ = as I want the tuple-unpacking and not just z = otherwise z become the tuple with both arrays.
Well, this step is pretty much the same as what you did at the end of your answer so I assume you understand it. Simple slicing in each dimension from the first element with a value in that dimension to the last. You need the + 1 because slicing in python are not inclusive of the index after the :.
Hopefully that's clear?
|
[
"opensource.stackexchange",
"0000006879.txt"
] | Q:
May I use AGPL license in a desktop application without providing the source code?
We develop a commercial desktop application that uses an AGPL library. The lib's code is just used, not modified. Our application runs completely offline.
May we use the AGPL library without having to make our application's code open source? As I understood it, this is allowed. But still I am not sure.
Does anyone know if my conclusion is right?
A:
The GPL license family consists of three kinds of licenses:
The GPL is the most widespread variant. If you include GPL software into your software, you can only distribute the result under the terms of the GPL. Those terms include providing your source code.
The AGPL is the same as the GPL, but also requires you to offer the source if users only interact with the software over a network, i.e. your software is a webapp that wouldn't normally be distributed.
The LGPL is the same as the GPL, but relaxes its terms: under certain conditions you can link to a LGPL library without having to disclose your source.
In your case, you have a desktop app so the AGPL is equivalent to the GPL. If you want to use the AGPL code, you will have to license your application under the AGPL and offer the source code for that app.
A:
There is a lot of confusion regarding modification. You claim that "The lib's code is just used, not modified." That's a very narrow interpretation of modification. In court, integrating the library into your desktop application also counts as modification, hence you also need to open source the code of your desktop application.
As Amon indicates, your use of the AGPL corresponds with use under the GPL. The FAQ from the Free Software Foundation on gnu.org is clear:
I'd like to incorporate GPL-covered software in my proprietary
system. Can I do
this?
You cannot incorporate GPL-covered software in a proprietary system.
The goal of the GPL is to grant everyone the freedom to copy,
redistribute, understand, and modify a program. If you could
incorporate GPL-covered software into a nonfree system, it would have
the effect of making the GPL-covered software nonfree too. A system
incorporating a GPL-covered program is an extended version of that
program. The GPL says that any extended version of the program must be
released under the GPL if it is released at all. This is for two
reasons: to make sure that users who get the software get the freedom
they should have, and to encourage people to give back improvements
that they make.
However, in many cases you can distribute the GPL-covered software
alongside your proprietary system. To do this validly, you must make
sure that the free and nonfree programs communicate at arms length,
that they are not combined in a way that would make them effectively a
single program.
The difference between this and “incorporating” the GPL-covered
software is partly a matter of substance and partly form. The
substantive part is this: if the two programs are combined so that
they become effectively two parts of one program, then you can't treat
them as two separate programs. So the GPL has to cover the whole
thing.
If the two programs remain well separated, like the compiler and the
kernel, or like an editor and a shell, then you can treat them as two
separate programs—but you have to do it properly. The issue is simply
one of form: how you describe what you are doing. Why do we care about
this? Because we want to make sure the users clearly understand the
free status of the GPL-covered software in the collection.
If people were to distribute GPL-covered software calling it “part of”
a system that users know is partly proprietary, users might be
uncertain of their rights regarding the GPL-covered software. But if
they know that what they have received is a free program plus another
program, side by side, their rights will be clear.
An example: suppose that you have created an accounting app on the desktop, and that you need to create PDF invoices and PDF reports from this app. Suppose that you use an AGPL PDF library to create the PDF.
In this example, your own code defines the GUI, and it allows people to enter data that is stored in a database. When they click a button, PDF's are created using the PDF library.
That PDF library is considered being a part of the accounting app because the functionality of the library is triggered by an action of the end user in the accounting application (e.g. a PDF invoice is created when the end user clicks a button). You can't "work around" the copyleft license by saying: we separate the GUI part from the PDF generation part. It's all connected.
The difference that is explained in the FAQ is for instance: when you compile your app with a specific compiler, then that compiler doesn't have to be open source because there's a clear separation between the application and the compiler. When you run the application on an operating system, then that operating system (or specific components of that operating system, such as the code that defines visual controls) doesn't have to be open source.
To make a long story short: your conclusion was wrong, because modification has a broader meaning than you initially assumed.
Update in answer to comments asking for proof of my claims:
Note: most of the comments I refer to were removed by their author.
The example of the accounting software and the PDF invoices wasn't chosen at random. I'm the original developer of iText, an open source PDF library released as AGPL software.
In June 2015, I discovered that iText was used in a closed source module that served as an add-on to closed source accounting software. This is the first thing I did: I went to a bailiff to document the infringement (June 12, 2015):
Then I went to a lawyer, who sent a cease and desist letter:
The infringing party stalled, and came back with false arguments (similar to some arguments made in the comments).
Hence we went to court (July 8, 2015):
Our case was very clear, and it didn't take long for the court to issue a ruling (July 17, 2015):
Eventually, the infringing party accepted the ruling of the court:
These slides were taken from my JavaOne talk IANAL: What Developers should know about IP and Legal (I won a JavaOne Rockstar Award with this talk).
In the comments, I read claims that this isn't an illustrative example because creating invoices isn't an essential part of accounting software. Landsgericht Köln didn't agree with that point of view. All software using the infringing module was taken from the market because the infringing party didn't want to open source it. Notice the word v e r b o t e n in the rulling. It was forbidden to distribute software that uses iText as a whole or in part without permission of the copyright owners of iText, given the fact that the copyleft of the AGPL wasn't respected.
Actually, being an essential part isn't even a criterium. In Artifex versus Hancom, the South-Korean company Hancom used Artifex's Ghostscript to create PDF output from documents created with their office suite. Creating PDF was an optional feature that wasn't essential for the rest of the office functionality to work. However, Artifex went to court, and a Californian judge issued a ruling that the GPL could indeed be enforced even in cases where the GPL code is only used for a small feature that isn't essential in the context of the complete work.
Often you read about thought experiments that tend to work around the (A)GPL, but such thought experiments are usually based on wishful thinking. In my (real-world) experience, a judge takes into account the technical effect rather than the technical implementation.
If user A pushes a button in product X, and by doing a technical effect is triggered that results in an action in (A)GPL library Y, then product X needs to be released under the same license as library Y to user A no matter how product X is technically implemented!
If you don't understand the difference between technical effect and technical implementation, consider this: suppose that person A wants to murder person X, but he hires person B to kill person X, then person A isn't technically the murderer of person X, but the effect is the same: person X is murdered because of person A, and for a judge person A will be guilty all the same (and usually get a higher sentence than person B).
If a counter-party tells the judge that the AGPL doesn't apply when you access an AGPL library from a closed source system through a service that is open sourced under the AGPL, feel free to use the "murder" comparison in court to explain why the judge should discard the technical details of such a workaround. You'll increase your chances at winning your case. Actually, the infringing party might get a more severe sentence because of the intentional attempt to avoid compliance with the open source license.
If you do not agree with the above, please document with existing cases that went to court. Please be aware of the fact that allegations that have not been proven in court have no value whatsoever.
Personal background:
Regarding the first example: I am the original developer of iText, an AGPL PDF library, and I wrote most of the Affidavits that were used in the case documented with the screen shots above.
Regarding the second example: I was consulted by the CEO of Artifex for advice in December 2016, and by Hancom in the Summer of 2017. Eventually, the case was settled.
I have quite some firsthand experience in matters like these, and it's quite disappointing to see how many developers are interpreting the law in a way that best suits the open source user, going against the rights of the open source producer. I would expect developers to stand up for each other, and respect the rights of their fellow open source developers. In my experience however, decision makers at a company have a better understanding than the company's developers. Management usually makes much less of a problem of the dual license system that allows their company to use software under a commercial license in cases where the company can't comply with the copyleft license.
|
[
"stackoverflow",
"0029417105.txt"
] | Q:
Timestamping netstat runs?
Is there an option that allows me to print a time stamp for the system time of each run of netstat? Done some looking on the man page, but nothing seems to do the trick.
For instance, if I start a run of netstat -vI 10 at 9:30:00, I'd want:
<9:30:00> [INSERT_DATA_HERE]
<9:30:10> [INSERT_DATA_HERE]
etc.
Or is it better if I just write a script to run a 'date' command and pipe the catted output to a text file?
A:
If you are running the current Solaris version (Solaris 11.*), you can use the -T u or -T d option to get a timestamp for each statistic line.
Otherwise, with Solaris 10 and older, there is no builtin option but you can put the start timestamp and the interval in the netstat output filename that way:
netstat -v -I interface 10 > netstat-vI-10s-$(date +%FT%T).out
|
[
"stackoverflow",
"0026731308.txt"
] | Q:
pm2 installation results in error
I want to install pm2 globally to run my nodejs app. my os is ubuntu 14.04 64bit and node version 0.10.33.
when i run the command npm install pm2 -g it gives the following error
npm ERR! [email protected] preinstall: `bash ./scripts/preinstall.sh`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] preinstall script.
npm ERR! This is most likely a problem with the pm2 package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! bash ./scripts/preinstall.sh
npm ERR! You can get their info via:
npm ERR! npm owner ls pm2
npm ERR! There is likely additional logging output above.
npm ERR! System Linux 3.13.0-36-generic
npm ERR! command "/usr/local/bin/node" "/usr/local/bin/npm" "install" "pm2" "-g"
npm ERR! cwd /home/ubuntu
npm ERR! node -v v0.10.33
npm ERR! npm -v 1.4.28
npm ERR! code ELIFECYCLE
npm ERR! not ok code 0
ubuntu@ip-172-31-40-58:~$
A:
Try adding sudo
sudo npm install pm2 -g
or
sudo npm install pm2 -g --unsafe-perm
|
[
"stackoverflow",
"0054800819.txt"
] | Q:
why does "import { React } from 'react';" not work?
Can anyone explain to me why
import { React } from 'react';
breaks everything, yet
import React from 'react';
works just fine? Aren't they saying the same thing? I've tried to find an answer elsewhere in documentation and on the internet, but I can't figure it out. I think it may have something to do with Babel?
Here are my npm packages if it helps:
"dependencies": {
"moment": "^2.18.1",
"prop-types": "^15.5.10",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-router-dom": "^4.0.0",
"styled-jsx": "^3.2.1",
"uuid": "^3.2.1"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"eslint": "^4.13.1",
"eslint-loader": "^1.9.0",
"eslint-plugin-react": "^7.5.1",
"file-loader": "^1.1.6",
"html-webpack-plugin": "^2.29.0",
"react-hot-loader": "^3.0.0-beta.7",
"url-loader": "^0.6.2",
"webpack": "^3.4.0",
"webpack-dev-server": "^2.5.0"
}
A:
import React from 'react'
This essentially says "find the default export from the react module and import that as a constant that I want to call React."
import { React } from 'react'
This says "find the export from the react module which is explicitly named React, and import that here as a constant that I want to call React."
Why doesn't import { React } from 'react' work?
Because there isn't an export named React in the react package. There is only a single default export. If you do this, you'll find that React is undefined.
But it doesn't even look like I use React in my code. So, couldn't I just name it anything I want, like import Foobar from 'react'?
No, sorry. You need to import the default and name it React. This is because anytime you write JSX code like <MyComponent /> or <App />, this JSX code is transpiled and uses React.createElement(). So, you need to have access to React.
Helpful references:
ES6 syntax and usage of import
A:
According to mdn,
imports work this way
import defaultExport from "module-name";
import { export } from "module-name";
What this basically means is that if a package exports something as a default, it should be imported without the {}, and with any name you choose. When when a package exports something as a named export, it should be used with the {}.
The react package exports React as a default and each package can have only one default export.
A:
The difference is between default exports & named exports.
Default Exports
react.js
class React {
render() {
// some code...
}
}
export default React;
You can import the above file react.js in your project like
import React from "./react.js";
Named Exports
react.js
export class React {
render() {
// some code...
}
}
export const Component = () => {
// some code...
};
Then you have to import the above file react.js in your project like
import { React, Component } from "./react.js";
TL;DR - Learn about Default Exports & Named Exports from here
|
[
"dsp.stackexchange",
"0000042586.txt"
] | Q:
How to create an AR filter in Matlab
My goal is to replicate the procedure described on pages 15-16 (1461-1462) in this paper, prior to adaptive mixture ICA (AMICA): Overlearning in Marginal Distribution-Based ICA: Analysis and Solutions
Using MATLAB,
How do I estimate the AR-coefficient for a one-tap AR process?
How do I remove the AR-process from the data? (The sample rate is 1000 Hz)
Is there any basic literature, manual, or tutorial that you could recommend?
A:
Answering in reverse order,
For a tutorial, I recommend: (the all pole case is an AR model)
J. Makhoul, "Linear prediction: A tutorial review," in Proceedings of the IEEE, vol. 63, no. 4, pp. 561-580, April 1975.
doi: 10.1109/PROC.1975.9792
Abstract: This paper gives an exposition of linear prediction in the analysis of discrete signals. The signal is modeled as a linear combination of its past values and present and past values of a hypothetical input to a system whose output is the given signal. In the frequency domain, this is equivalent to modeling the signal spectrum by a pole-zero spectrum. The major part of the paper is devoted to all-pole models. The model parameters are obtained by a least squares analysis in the time domain. Two methods result, depending on whether the signal is assumed to be stationary or nonstationary. The same results are then derived in the frequency domain. The resulting spectral matching formulation allows for the modeling of selected portions of a spectrum, for arbitrary spectral shaping in the frequency domain, and for the modeling of continuous as well as discrete spectra. This also leads to a discussion of the advantages and disadvantages of the least squares error criterion. A spectral interpretation is given to the normalized minimum prediction error. Applications of the normalized error are given, including the determination of an "optimal" number of poles. The use of linear prediction in data compression is reviewed. For purposes of transmission, particular attention is given to the quantization and encoding of the reflection (or partial correlation) coefficients. Finally, a brief introduction to pole-zero modeling is given.
keywords: {Control theory;Econometrics;Frequency domain analysis;Information analysis;Predictive models;Rhythm;Signal analysis;Statistics;Time series analysis;Tutorial},
URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=1451722&isnumber=31191
How does one get rid of an AR process?
The inverse filter to an all pole filter, is a FIR filter using the AR coefficients. Inverse filtering is my guess of what that means.
Question one,
There are a number of AR estimators in Matlab's Signal Processing tool box. You can look at those, or read the above paper and roll your own. Essentially, you have to estimate the covariance of adjacent pairs of samples, and then use one of the methods detailed in the paper. The term "one tap" might be confusing, [1 a0] might correspond to one tap or two, but [1] doesn't make sense while [1 a0] does.
|
[
"stackoverflow",
"0024829055.txt"
] | Q:
VBA runtime error - 1004 when trying to format or delete cells after pasting values
I am trying to use VBA to make my life easier but I keep getting a problem which I can't work around. Basically what I want is to copy some values from several output csv files I've got, to a nice formatted excel file. Then according to some bases numbers delete values or format the cells.
However I keep getting the same error message Run-time error '1004' application-defined or object defined error. I am doing that using many output files and pasting values at the same table file but on different sheets (10.2a, 10.2b, 10.2c, ...) by having macros for each sheet. I run all the macros in one using another macro that contains all the other macros
I looked a lot in other posts but don't understand where the error comes from. Any help would be much appreciated. The code I use for one sheet is below as an example.
Sub Table_10_2a()
'
' Copy Data from one file to another
'
Dim Output As Workbook
Dim Table As Workbook
Dim i As Integer
'Open workbooks
Set Output = Workbooks.Open("O:\...\Output.csv")
Set Table = Workbooks.Open("O:\...\Table.xlsx")
'Copy paste data from output file to Table
Output.Sheets("Output1").Range("B3:E7").Copy
Table.Sheets("10.2a").Range("B11").PasteSpecial xlValues
Output.Sheets("Output1").Range("B9:E13").Copy
Table.Sheets("10.2a").Range("B17").PasteSpecial xlValues
Output.Sheets("Output1").Range("B15:E15").Copy
Table.Sheets("10.2a").Range("B23").PasteSpecial xlValues
Output.Sheets("Output1").Range("B17:E21").Copy
Table.Sheets("10.2a").Range("B26").PasteSpecial xlValues
Output.Sheets("Output1").Range("B23:E27").Copy
Table.Sheets("10.2a").Range("B32").PasteSpecial xlValues
Output.Sheets("Output1").Range("B29:E29").Copy
Table.Sheets("10.2a").Range("B38").PasteSpecial xlValues
Output.Sheets("Output1").Range("B30:E30").Copy
Table.Sheets("10.2a").Range("B40").PasteSpecial xlValues
For i = 2 To 5
'Delete cells for values below 30
If Table.Sheets("10.2a").Cells(40, i).Value < 30 Then
Table.Sheets("10.2a").Range(Cells(26, i), Cells(36, i)).ClearContents
Table.Sheets("10.2a").Cells(38, i).NumberFormat = """[""0""]"""
Table.Sheets("10.2a").Cells(40, i).NumberFormat = """[""0""]"""
End If
'Format cells for values below 50
If Table.Sheets("10.2a").Cells(40, i).Value < 50 And Table.Sheets("10.2a").Cells(40, i).Value > 30 Then
Table.Sheets("10.2a").Range(Cells(26, i), Cells(38, i)).NumberFormat = """[""0.0""]"""
Table.Sheets("10.2a").Cells(40, i).NumberFormat = """[""0""]"""
End If
Next i
'Save file
Table.Save
'Close files
Output.Close
Table.Close
End Sub
A:
This usage of Cells inside Range to build a block of cells commonly falls victim to an unqualified reference. In this case, you are using Table.Sheets("10.2a") to specify the sheet for Range but are not using the same qualifier on Cells. This means that Cells will use the default context available which varies with where the code is executing. Possibilities:
Inside a code module or ThisWorkbook, Cells refers to the ActiveSheet
Inside a Worksheet code behind, Cells refers to that Worksheet regardless of the ActiveSheet
Use Address to get around the different sheets
One approach is to follow the call to Cells with Address. This resolves the problem because Address returns the cell address without the sheet name. This is then interpreted by Range within its context which is Sheets("10.2a").
Range(Cells(26, i).Address, Cells(36, i).Address).ClearContents
Qualify the reference (generally preferred)
Another way to resolve this error is to qualify the reference by adding a sheet name before Cells: Table.Sheets("10.2a").Cells. Full line:
Range(Table.Sheets("10.2a").Cells(26, i), Table.Sheets("10.2a").Cells(36, i)).ClearContents
This type of code looks better within a With... End With block.
|
[
"stackoverflow",
"0023184277.txt"
] | Q:
Is it possible to write a file or set a setting that can not be deleted by a user in Android?
I want to, in my Android app, allow the user to set a countersign - a password of sorts, but one that is not used to log on to the app but possibly at some other point remotely. A Broadcast Receiver would watch/listen for it, and if it appeared, respond appropriately.
This would (potentially) be used by the owner of the device remotely (from another device).
However, if the person who currently had the device knew about this feature, he may be able to delete the file on which the password is stored or delete the setting that holds the value (or change it).
Is there a way to programmatically write a file or set a setting that can neither be changed or deleted, at least not without knowing the value (which will be encrypted)?
A:
For ordinary users, put the file on internal storage (e.g., getFilesDir()). They have no access to those files.
For users of rooted devices, there is no way to prevent them from deleting a file.
|
[
"stackoverflow",
"0029778347.txt"
] | Q:
How to order the display of build configurations in TeamCity?
I'm using TeamCity 9.0.2. I have one project with many configurations. Up until now, it's always seemed to order my build configurations alphabetically. Then I accidentally clicked on the x on the right and hid one of my configurations. When I unhid it, that configuration now displays at the very bottom. I would like to move it back where it was.
A:
On the right side of the header for each Project, there is a dropdown which has an option for reordering build configurations.
|
[
"stackoverflow",
"0063436437.txt"
] | Q:
Problem with saving foreign key with @OneToOne annotation. Saving as null
I have two entities (Project, OtherData) with one abstract entity. I'm using MySQL and Quarkus framework.
Problem: When I try to save Project entity field project_id remains null.
Table schemas:
On next picture there is shown, fk constraint in "project_other_data" table:
Abstract Entity:
@MappedSuperclass
public class AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
// getters and setters
}
Project Entity
@Entity
@Table(name = "projects")
public class Project extends AbstractEntity {
@NotNull
@Column(name = "name")
private String name;
@NotNull
@Column(name = "surname")
private String surname;
@Column(name = "date_create")
@JsonbDateFormat(value = "yyyy-MM-dd")
private LocalDate dateCreate;
@Column(name = "date_update")
@JsonbDateFormat(value = "yyyy-MM-dd")
private LocalDate dateUpdate;
@OneToOne(mappedBy = "project", cascade = CascadeType.ALL)
private OtherData otherData;
// getters and setters
}
OtherData Entity
@Entity
@Table(name = "project_other_data")
public class OtherData extends AbstractEntity {
@OneToOne
@JoinColumn(name = "project_id")
private Project project;
@Column(name = "days_in_year")
private Integer daysInYear;
@Column(name = "holidays_in_year")
private Integer holidaysInYear;
@Column(name = "weeks_in_year")
private Integer weeksInYear;
@Column(name = "free_saturdays")
private Integer freeSaturdays;
@Column(name = "downtime_coefficient")
private BigDecimal downtimeCoefficient;
@Column(name = "changes")
private Integer changes;
// getters and setters
}
Saving entities with code:
@Path("projects")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ProjectRest {
@Inject
ProjectService projectService;
@POST
public Response saveProject(Project project) {
return Response.ok(projectService.saveProject(project)).build();
}
}
@RequestScoped
@Transactional
public class ProjectService {
@Inject
EntityManager entityManager;
public Project saveProject(Project project) {
if (project.getId() == null) {
entityManager.persist(project);
} else {
entityManager.merge(project);
}
return project;
}
}
A:
I was able to reproduce the problem by POSTing a new Project with an embedded OtherData. The body I used for the POST:
{
"name": "John",
"surname": "Doe",
"otherData": {}
}
Point is: the database entity is also used as DTO. Thus, the field project in otherData for the request body is set to null (since no Project is passed along this would be a recursive infinite definition).
During processing the entity from the rest controller to the service to the repository, the project of otherData is never set. A quick fix is to modify ProjectService::saveProject as follows:
public Project saveProject(Project project) {
project.getOtherData().setProject(project); // This line was added
if (project.getId() == null) {
entityManager.persist(project);
} else {
entityManager.merge(project);
}
return project;
}
This will fix the database issue (the project_id will be set), but leads to the next issue. The response body cannot be serialized due to an
org.jboss.resteasy.spi.UnhandledException: javax.ws.rs.ProcessingException: RESTEASY008205: JSON Binding serialization error javax.json.bind.JsonbException: Unable to serialize property 'otherData' from com.nikitap.org_prod.entities.Project
...
Caused by: javax.json.bind.JsonbException: Recursive reference has been found in class class com.nikitap.org_prod.entities.Project.
The object structure is cyclic (project references otherData, which return references project, ...) and Jackson is unable to resolve this cycle.
To fix this issue, I would suggest to separate DTOs and database entity and explicitly map between them. In essence:
Structure the Dto-object to represent the JSON-Request and -Response you expect to receive, in a non-cyclic order
Transfer JSON-related annotations from the database entity classes to the DTO classes
In the service- or repository-layer (your choice), map the DTO to the database entites, setting all fields (including the references from project to otherData and vice-versa)
In the same layer, map database-entites back to non-cyclic DTOs
Return the DTOs from the REST endpoint
|
[
"stackoverflow",
"0059489073.txt"
] | Q:
How to not remove but handle outliers by transforming using pandas?
I have a dataframe like as shown below
dfx = pd.DataFrame({'min_temp' :[-138,36,34,38,237,339]})
As you can see below that there are three outliers in this data -138,237 and 239
What I would like to do is identify records
a) which are greater than 3 standard deviation and replace them with the valid maximum value(considering the data range).
b) which are lesser than -3 standard deviation and replace them with the valid minimum value(considering the data range).
This is what I tried but it is incorrect and not efficient
dfx.apply(lambda x: x[(x < dfx[min_temp].mean()-3*dfx[min_temp].std(), dfx[min_temp].mean()+3*dfx[min_temp].std())])
In the above example, 38 is the maximum value as it's within the 3sd limit and a valid maximum value (meaning not outlier). Similarly 36 is minimum value as it's within the -3sd
We need to use this to replace all the outliers in full dataframe.
Please note in my real data, I have more than 60 columns and 1 Million rows. I would like to do this across all the columns. Any efficient and scalable approach is helpful
I expect my output to be like this? you can see how the outliers are replaced with maximum valid value within 3sd (38 in this case)
Can you help me with this?
update after suggested solution
A:
This answer is based on the information in this good article about outlier detection. You can read about each method there.
The output of each code shows the resulting lower and upper bounds for the outlier detection.
First, let's define some sample data:
import numpy as np
df = pd.DataFrame({'col1': np.random.normal(loc=20, scale=2, size=10)})
# Insert outliers
df['col1'][0] = 40
df['col1'][1] = 0
df['col1']
Output:
0 40.000000
1 0.000000
2 19.218962
3 16.648512
4 21.444715
5 22.637459
6 21.016641
7 22.527376
8 20.502631
9 20.715458
Name: col1, dtype: float64
The Z-score method
This method is the least robust of all 3. It does not work well for small datasets (mean and standard deviation are heavily affected by outliers).
def cap_outliers(series, zscore_threshold=3, verbose=False):
'''Caps outliers to closest existing value within threshold (Z-score).'''
mean_val = series.mean()
std_val = series.std()
z_score = (series - mean_val) / std_val
outliers = abs(z_score) > zscore_threshold
series = series.copy()
series.loc[z_score > zscore_threshold] = series.loc[~outliers].max()
series.loc[z_score < -zscore_threshold] = series.loc[~outliers].min()
# For comparison purposes.
if verbose:
lbound = mean_val - zscore_threshold * std_val
ubound = mean_val + zscore_threshold * std_val
print('\n'.join(
['Capping outliers by the Z-score method:',
f' Z-score threshold: {zscore_threshold}',
f' Lower bound: {lbound}',
f' Upper bound: {ubound}\n']))
return series
cap_outliers(df['col1'], verbose=True)
Output:
Capping outliers by the Z-score method:
Z-score threshold: 3
Lower bound: -8.28385086324063
Upper bound: 49.22620154113844
0 40.000000
1 0.000000
2 19.218962
3 16.648512
4 21.444715
5 22.637459
6 21.016641
7 22.527376
8 20.502631
9 20.715458
Name: col1, dtype: float64
The Modified Z-score method
This method is much more robust than the previous one. It uses median and mad instead of mean and std.
def cap_outliers(series, zscore_threshold=3, verbose=False):
'''Caps outliers to closest existing value within threshold (Modified Z-score).'''
median_val = series.median()
mad_val = series.mad() # Median absolute deviation
z_score = (series - median_val) / mad_val
outliers = abs(z_score) > zscore_threshold
series = series.copy()
series.loc[z_score > zscore_threshold] = series.loc[~outliers].max()
series.loc[z_score < -zscore_threshold] = series.loc[~outliers].min()
# For comparison purposes.
if verbose:
lbound = median_val - zscore_threshold * mad_val
ubound = median_val + zscore_threshold * mad_val
print('\n'.join(
['Capping outliers by the Modified Z-score method:',
f' Z-score threshold: {zscore_threshold}',
f' Lower bound: {lbound}',
f' Upper bound: {ubound}\n']))
return series
cap_outliers(df['col1'], verbose=True)
Output:
Capping outliers by the Modified Z-score method:
Z-score threshold: 3
Lower bound: 5.538418022763285
Upper bound: 36.19368140628174
0 22.637459
1 16.648512
2 19.218962
3 16.648512
4 21.444715
5 22.637459
6 21.016641
7 22.527376
8 20.502631
9 20.715458
Name: col1, dtype: float64
The IQR method
This method is the most strict of all 3.
def cap_outliers(series, iqr_threshold=1.5, verbose=False):
'''Caps outliers to closest existing value within threshold (IQR).'''
Q1 = series.quantile(0.25)
Q3 = series.quantile(0.75)
IQR = Q3 - Q1
lbound = Q1 - iqr_threshold * IQR
ubound = Q3 + iqr_threshold * IQR
outliers = (series < lbound) | (series > ubound)
series = series.copy()
series.loc[series < lbound] = series.loc[~outliers].min()
series.loc[series > ubound] = series.loc[~outliers].max()
# For comparison purposes.
if verbose:
print('\n'.join(
['Capping outliers by the IQR method:',
f' IQR threshold: {iqr_threshold}',
f' Lower bound: {lbound}',
f' Upper bound: {ubound}\n']))
return series
cap_outliers(df['col1'], verbose=True)
Output:
Capping outliers by the IQR method:
IQR threshold: 1.5
Lower bound: 15.464630871041477
Upper bound: 26.331958943979345
0 22.637459
1 16.648512
2 19.218962
3 16.648512
4 21.444715
5 22.637459
6 21.016641
7 22.527376
8 20.502631
9 20.715458
Name: col1, dtype: float64
Conclusion
You should probably use the IQR method.
|
[
"stackoverflow",
"0053172732.txt"
] | Q:
Why dynamically allocated memory requires typecasting?
In C address returned by malloc() typecasts implicitly and in C++ I need to typecast explicitly. But I'm using an integer pointer which will point out to next address according to the pointer arithmetic, then why do I need to typecast memory address?
I'm actually using 'new' keyword but I need to clear my thought on this.
A:
But I'm using an integer pointer which will point out to next address according to the pointer arithmetic
Yes it will, but it's not revelant here.
malloc returns a void *.
In C, a pointer to void can be implicitly converted to a pointer to any other type.
In C++, there is no such implicit conversion (presumably to make the language a bit more safe to use).
It's as simple as that.
|
[
"stackoverflow",
"0027781242.txt"
] | Q:
Eclipse hangs on "verifying launch attributes" in large Maven projects
I am using Eclipse to develop a large Maven project (dozens of dependencies). When I try to run a unit test, I see a pause of about a minute, while the status is showing "verifying launch attributes". Observing the Eclipse's activities in Process Monitor, I see a lot of file access to various locks and jars in Maven repository. Looks like Eclipse goes over every JAR that my project depends on. As soon as that file access is done, the actual test starts.
I am aware of advice offered in "Why is Eclipse hanging at 57% with the status “Verifying launch attributes…” when launching a run configuration?", and I followed the suggested fixes. I think Eclipse is doing what it's supposed to do by going over every single JAR. My question is, how can that behavior be disabled, either in Eclipse or in Maven?
I am using Eclipse Luna on Windows 7, m2e version 1.5.0.20140606
Edit:
Below a sample of what I see in Process Monitor:
In short, we spend some 10 seconds on reasonable activity such as checking the state of Java and JAR files, and then we spend ~40 seconds locking Maven repo and reading the POM files.
Why does eclipse do that? And what do I need to change to stop it?
11:31:48.1468054 AM eclipse.exe 3736 CreateFile C:\LAS\Maven\Repository\org\drools\drools-core\6.0.1.Final\drools-core-6.0.1.Final.jar SUCCESS Desired Access: Read Attributes, Synchronize, Disposition: Open, Options: Synchronous IO Non-Alert, Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a, OpenResult: Opened
11:31:48.1469017 AM eclipse.exe 3736 QueryBasicInformationFile C:\LAS\Maven\Repository\org\drools\drools-core\6.0.1.Final\drools-core-6.0.1.Final.jar SUCCESS CreationTime: 7/21/2014 11:13:15 AM, LastAccessTime: 7/21/2014 11:13:15 AM, LastWriteTime: 7/21/2014 11:13:22 AM, ChangeTime: 7/21/2014 11:13:23 AM, FileAttributes: A
11:31:48.1469769 AM eclipse.exe 3736 CloseFile C:\LAS\Maven\Repository\org\drools\drools-core\6.0.1.Final\drools-core-6.0.1.Final.jar SUCCESS
11:31:50.0040011 AM eclipse.exe 3736 CreateFile C:\LAS\Maven\Repository\xpp3\xpp3_min\1.1.4c\xpp3_min-1.1.4c.jar SUCCESS Desired Access: Read Attributes, Disposition: Open, Options: Open Reparse Point, Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a, OpenResult: Opened
11:31:50.0040832 AM eclipse.exe 3736 QueryNetworkOpenInformationFile C:\LAS\Maven\Repository\xpp3\xpp3_min\1.1.4c\xpp3_min-1.1.4c.jar SUCCESS CreationTime: 7/21/2014 11:13:15 AM, LastAccessTime: 7/21/2014 11:13:15 AM, LastWriteTime: 7/21/2014 11:13:21 AM, ChangeTime: 7/21/2014 11:13:23 AM, AllocationSize: 28672, EndOfFile: 24956, FileAttributes: A
11:31:50.0041397 AM eclipse.exe 3736 CloseFile C:\LAS\Maven\Repository\xpp3\xpp3_min\1.1.4c\xpp3_min-1.1.4c.jar SUCCESS
(four seconds worth of this)
11:31:50.0700821 AM eclipse.exe 3736 CreateFile C:\LAS\Maven\Repository\.locks\com.lmax~disruptor~3.3.0.aetherlock SUCCESS Desired Access: Write Attributes, Synchronize, Disposition: Open, Options: Synchronous IO Non-Alert, Open Reparse Point, Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a, OpenResult: Opened
11:31:50.0701770 AM eclipse.exe 3736 SetBasicInformationFile C:\LAS\Maven\Repository\.locks\com.lmax~disruptor~3.3.0.aetherlock SUCCESS CreationTime: 0, LastAccessTime: 0, LastWriteTime: 0, ChangeTime: 0, FileAttributes: N
11:31:50.0703100 AM eclipse.exe 3736 CloseFile C:\LAS\Maven\Repository\.locks\com.lmax~disruptor~3.3.0.aetherlock SUCCESS
11:31:59.7990517 AM eclipse.exe 3736 CreateFile C:\LAS\Maven\Repository\.locks\xpp3~xpp3_min~1.1.4c.aetherlock SUCCESS Desired Access: Read Attributes, Delete, Disposition: Open, Options: Non-Directory File, Open Reparse Point, Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a, OpenResult: Opened
11:31:59.7991381 AM eclipse.exe 3736 QueryAttributeTagFile C:\LAS\Maven\Repository\.locks\xpp3~xpp3_min~1.1.4c.aetherlock SUCCESS Attributes: N, ReparseTag: 0x0
11:31:59.7991864 AM eclipse.exe 3736 SetDispositionInformationFile C:\LAS\Maven\Repository\.locks\xpp3~xpp3_min~1.1.4c.aetherlock SUCCESS Delete: True
11:31:59.7992609 AM eclipse.exe 3736 CloseFile C:\LAS\Maven\Repository\.locks\xpp3~xpp3_min~1.1.4c.aetherlock SUCCESS
(9 second worth of this)
11:31:59.8364794 AM eclipse.exe 3736 CreateFile C:\LAS\Maven\Repository\com\lmax\disruptor\3.3.0\disruptor-3.3.0-sources.jar SUCCESS Desired Access: Read Attributes, Disposition: Open, Options: Open Reparse Point, Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a, OpenResult: Opened
11:31:59.8367613 AM eclipse.exe 3736 QueryNetworkOpenInformationFile C:\LAS\Maven\Repository\com\lmax\disruptor\3.3.0\disruptor-3.3.0-sources.jar SUCCESS CreationTime: 11/18/2014 2:17:33 PM, LastAccessTime: 11/18/2014 2:17:33 PM, LastWriteTime: 11/18/2014 2:17:33 PM, ChangeTime: 11/18/2014 2:17:33 PM, AllocationSize: 81920, EndOfFile: 80291, FileAttributes: A
11:31:59.8367994 AM eclipse.exe 3736 CloseFile C:\LAS\Maven\Repository\com\lmax\disruptor\3.3.0\disruptor-3.3.0-sources.jar SUCCESS
11:32:02.0222874 AM eclipse.exe 3736 CreateFile C:\LAS\Maven\Repository\org\antlr\antlr-runtime\3.5\antlr-runtime-3.5.jar SUCCESS Desired Access: Read Attributes, Disposition: Open, Options: Open Reparse Point, Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a, OpenResult: Opened
11:32:02.0223541 AM eclipse.exe 3736 QueryNetworkOpenInformationFile C:\LAS\Maven\Repository\org\antlr\antlr-runtime\3.5\antlr-runtime-3.5.jar SUCCESS CreationTime: 7/21/2014 11:13:15 AM, LastAccessTime: 7/21/2014 11:13:15 AM, LastWriteTime: 7/21/2014 11:13:21 AM, ChangeTime: 7/21/2014 11:13:22 AM, AllocationSize: 167936, EndOfFile: 167735, FileAttributes: A
11:32:02.0223896 AM eclipse.exe 3736 CloseFile C:\LAS\Maven\Repository\org\antlr\antlr-runtime\3.5\antlr-runtime-3.5.jar SUCCESS
(3 seconds worth)
11:32:33.2963547 AM eclipse.exe 3736 CreateFile C:\LAS\Maven\Repository\.locks\commons-logging~commons-logging~1.1.aetherlock SUCCESS Desired Access: Read Attributes, Delete, Disposition: Open, Options: Non-Directory File, Open Reparse Point, Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a, OpenResult: Opened
11:32:33.2964727 AM eclipse.exe 3736 QueryAttributeTagFile C:\LAS\Maven\Repository\.locks\commons-logging~commons-logging~1.1.aetherlock SUCCESS Attributes: N, ReparseTag: 0x0
11:32:33.2965390 AM eclipse.exe 3736 SetDispositionInformationFile C:\LAS\Maven\Repository\.locks\commons-logging~commons-logging~1.1.aetherlock SUCCESS Delete: True
11:32:33.2966382 AM eclipse.exe 3736 CloseFile C:\LAS\Maven\Repository\.locks\commons-logging~commons-logging~1.1.aetherlock SUCCESS
11:32:33.2970685 AM eclipse.exe 3736 CreateFile C:\LAS\Maven\Repository\commons-logging\commons-logging\1.1\commons-logging-1.1.pom SUCCESS Desired Access: Synchronize, Disposition: Open, Options: , Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a, OpenResult: Opened
11:32:33.2971806 AM eclipse.exe 3736 QueryNameInformationFile C:\LAS\Maven\Repository\commons-logging\commons-logging\1.1\commons-logging-1.1.pom SUCCESS Name: \LAS\Maven\Repository\commons-logging\commons-logging\1.1\commons-logging-1.1.pom
11:32:33.2972430 AM eclipse.exe 3736 CloseFile C:\LAS\Maven\Repository\commons-logging\commons-logging\1.1\commons-logging-1.1.pom SUCCESS
11:32:33.2980275 AM eclipse.exe 3736 CreateFile C:\LAS\Maven\Repository\commons-logging\commons-logging\1.1\commons-logging-1.1.pom SUCCESS Desired Access: Generic Read, Disposition: Open, Options: Synchronous IO Non-Alert, Non-Directory File, Attributes: N, ShareMode: Read, Write, AllocationSize: n/a, OpenResult: Opened
11:32:33.2981528 AM eclipse.exe 3736 ReadFile C:\LAS\Maven\Repository\commons-logging\commons-logging\1.1\commons-logging-1.1.pom SUCCESS Offset: 0, Length: 4,096, Priority: Normal
11:32:33.2983145 AM eclipse.exe 3736 QueryStandardInformationFile C:\LAS\Maven\Repository\commons-logging\commons-logging\1.1\commons-logging-1.1.pom SUCCESS AllocationSize: 8,192, EndOfFile: 6,182, NumberOfLinks: 1, DeletePending: False, Directory: False
11:32:33.2983774 AM eclipse.exe 3736 ReadFile C:\LAS\Maven\Repository\commons-logging\commons-logging\1.1\commons-logging-1.1.pom SUCCESS Offset: 4,096, Length: 2,086
11:32:33.2984420 AM eclipse.exe 3736 QueryStandardInformationFile C:\LAS\Maven\Repository\commons-logging\commons-logging\1.1\commons-logging-1.1.pom SUCCESS AllocationSize: 8,192, EndOfFile: 6,182, NumberOfLinks: 1, DeletePending: False, Directory: False
11:32:33.2985057 AM eclipse.exe 3736 QueryStandardInformationFile C:\LAS\Maven\Repository\commons-logging\commons-logging\1.1\commons-logging-1.1.pom SUCCESS AllocationSize: 8,192, EndOfFile: 6,182, NumberOfLinks: 1, DeletePending: False, Directory: False
11:32:33.2987730 AM eclipse.exe 3736 CloseFile C:\LAS\Maven\Repository\commons-logging\commons-logging\1.1\commons-logging-1.1.pom SUCCESS
(30 seconds!)
A:
So far, the only thing that helps is closing a lot of projects in my workspace. When I have 30 Maven dependencies coming from my worksapce, the unit test take 30+ seconds to start. When I close those projects and forse Eclipse to go to local repository, the start of unit tests takes 5 seconds.
I see no correlation between start time and "external" dependencies. Only "internal" (in workspace and open) dependencies matter.
|
[
"stackoverflow",
"0060936911.txt"
] | Q:
Firestore Is deleting Data on Flutter when new data added
hi i am developing an app i have a listview i just created on tap method when user clicked to the item on listview it saves details to the firestore but when user clicked other item it deletes current one and adding item which is clicked i just want to keep all clicked item on firestore if you have any suggestions please let me know thanks
this is first clicked item
this is second clicked item it keeps always last clicked data]
Firestore.instance.runTransaction((Transaction transaction) async {
await transaction.set(Firestore.instance.collection("cart").document("LIihBLtbfuJ8Dy640DPd"), {
foodItem.name : {
'itemName': foodItem.name,
'imgUrl': foodItem.imageAssetPath,
'itemPrice': foodItem.price,
'quantity': '1',
}
});});
A:
As we talked in comments lately, you should use update instead of set as you want to let the old data without deletion in the same document.
Also, maybe full docs helps you to find out more problems.
|
[
"stackoverflow",
"0055312918.txt"
] | Q:
Unknown column 'sunny' in where clause
<body>
<% String name=session.getAttribute("user").toString(); %>
<br>
<%@ page import="java.sql.*" %>
<%
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection
con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/pbl","root","");
Statement st=con.createStatement();
String q="select pcode ,pname,pprice from car where us="+name;
ResultSet rs = st.executeQuery(q) ;
%>
error:
java.sql.SQLSyntaxErrorException: You have an error in your SQL
syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near 'by name' at line 1
A:
i guess the problem in this line String q="select pcode,pname,pprice from car where us="+name;
Yes, because the name (sunny, apparently) it isn't in SQL quotes, so it looks like a column reference.
NEVER use string concatenation to add values to SQL queries. Use prepared statements instead:
PreparedStatement ps = con.prepareStatement("select pcode ,pname,pprice from car where us = ?");
ps.setString(1, name);
ResultSet rs = ps.executeQuery();
That way, the information is handled as data, not as SQL (properly escaped if necessary, etc.). Things to notice there:
You use ? where the values go. You don't put ? in quotes or anything, even when you're going to use a string for the value.
You get a prepared statement by calling prepareStatement on the connection.
You don't pass a string into executeQuery. (This is important, because sadly you can pass a string into executeQuery on a PreparedStatement, which bypasses the whole point of using prepared statements; it should have been defined to cause an exception, but sadly it it wasn't.)
Let me introduce you to my friend Bobby:
|
[
"magento.stackexchange",
"0000241733.txt"
] | Q:
How to show Qty left in Magento 2 Listing page?
I need to show Qty left message with qty of product in product detail page with below condition.
If the available stock is less than 'Notify for Quantity Below' parameter of each product.
And can we show same message in product detail page More Information tab?
I have set Only X left Threshold as 15 in Store -> Configuration->Catalog->Inventory
I need to show That Qty left message message only if it is less than this value.
How this can be checked and show.
Please anyone suggest me in this?
A:
Create a block class to your custom module named Vendor_Module to below path:
app/code/Vendor/Module/Block/Product.php
and add the below content to it:
<?php
namespace Vendor\Module\Block;
class Product extends \Magento\Framework\View\Element\Template
{
protected $_scopeConfig;
protected $_stockInterface;
protected $_productRepository;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\CatalogInventory\Api\StockStateInterface $stockInterface,
\Magento\Catalog\Model\ProductRepository $productRepository
){
$this->_scopeConfig = $scopeConfig;
$this->_stockInterface = $stockInterface;
$this->_productRepository = $productRepository;
parent::__construct($context);
}
public function getStockMessage($productId){
$_product = $this->getProductById($productId);
$_stock = $this->getStock($_product);
if($_stock <= $this->getThresoldQty()){
return __('Only %1 left', $_stock);
}
return '';
}
public function getProductById($id)
{
return $this->_productRepository->getById($id);
}
public function getStock($_product)
{
return $this->_stockInterface->getStockQty($_product->getId(), $_product->getStore()->getWebsiteId());
}
public function getThresoldQty(){
return $this->_scopeConfig->getValue('cataloginventory/options/stock_threshold_qty', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
}
}
Now add the below code to top of your list.phtml
$blockObj = $block->getLayout()->createBlock('Vendor\Module\Block\Product');
Then call the below block inside your foreach loop:
<?php echo $blockObj->getStockMessage($_product->getId()); ?>
You can use the thing in your product details page.
|
[
"stackoverflow",
"0002505041.txt"
] | Q:
Best library to parse HTML with Python 3 and example?
I'm new to Python completely and am using Python 3.1 on Windows (pywin). I need to parse some HTML, to essentially extra values between specific HTML tags and am confused at my array of options, and everything I find is suited for Python 2.x. I've read raves about Beautiful Soup, HTML5Lib and lxml, but I cannot figure out how to install any of these on Windows.
Questions:
What HTML parser do you recommend?
How do I install it? (Be gentle, I'm completely new to Python and remember I'm on Windows)
Do you have a simple example on how to use the recommended library to snag HTML from a specific URL and return the value out of say something like this:
<div class="foo"><table><tr><td>foo</td></tr></table><a class="link" href='/blahblah'>Link</a></div>
(say we want to return "/blahblah")
A:
Web-scraping in Python 3 is currently very poorly supported; all the decent libraries work only with Python 2. If you must web scrape in Python, use Python 2.
Although Beautiful Soup is oft recommended (every question regarding web scraping with Python in Stack Overflow suggests it), it's not as good for Python 3 as it is for Python 2; I couldn't even install it as the installation code was still Python 2.
As for adequate and simple-to-install solutions for Python 3, you can try the library's HTML parser, although quite barebones, it comes with Python 3.
A:
If your HTML is well formed, you have many options, such as sax and dom. If it is not well formed you need a fault tolerant parser such as Beautiful soup, element tidy, or lxml's HTML parser. No parser is perfect, when presented with a variety of broken HTML, sometimes I have to try more then one. Lxml and Elementree use a mostly compatible api that is more of a standard than Beautiful soup.
In my opinion, lxml is the best module for working with xml documents, but the ElementTree included with python is still pretty good. In the past I have used Beautiful soup to convert HTML to xml and construct ElementTree for processing the data.
A:
BeautifulSoup, with its version 3.1.0.1 (January 2009) also work with Python 3.x.
I do not have have direct experience with BeautifulSoup under Py3k (although this soon should change...). I just read, however, that Version 3.1.0 of Beautiful Soup does significantly worse on real-world HTML than its previous versions, so I may try and wait if possible (i.e. stay with Python 2.6 a bit longer).
|
[
"stackoverflow",
"0041298289.txt"
] | Q:
Spring Boot @Autowired with Kotlin in @Service is always null
Currently I try to rewrite my Java Spring Boot Application with Kotlin. I encountered a problem that in all of my classes which are annotated with @Service the dependency injection is not working correctly (all instances are null). Here is an example:
@Service
@Transactional
open class UserServiceController @Autowired constructor(val dsl: DSLContext, val teamService: TeamService) {
//dsl and teamService are null in all methods
}
Doing the same in Java works without any problems:
@Service
@Transactional
public class UserServiceController
{
private DSLContext dsl;
private TeamService teamService;
@Autowired
public UserServiceController(DSLContext dsl,
TeamService teamService)
{
this.dsl = dsl;
this.teamService = teamService;
}
If I annotate the component with @Component in Kotlin everything works fine:
@Component
open class UserServiceController @Autowired constructor(val dsl: DSLContext, val teamService: TeamService) {
//dsl and teamService are injected properly
}
Google provided many different approaches for Kotlin and @Autowired which I tried but all resulted in the same NullPointerException
I would like to know what the difference between Kotlin and Java is and how I can fix this?
A:
I just bumped into exactly same issue - injection worked well, but after adding @Transactional annotation all the autowired fields are null.
My code:
@Service
@Transactional
open class MyDAO(val jdbcTemplate: JdbcTemplate) {
fun update(sql: String): Int {
return jdbcTemplate.update(sql)
}
}
The problem here is that the methods are final by default in Kotlin, so Spring is unable to create proxy for the class:
o.s.aop.framework.CglibAopProxy: Unable to proxy method [public final int org.mycompany.MyDAO.update(...
"Opening" the method fixes the issue:
Fixed code:
@Service
@Transactional
open class MyDAO(val jdbcTemplate: JdbcTemplate) {
open fun update(sql: String): Int {
return jdbcTemplate.update(sql)
}
}
A:
Which Spring Boot version do you use? Since 1.4 Spring Boot is based on Spring Framework 4.3 and since then you should be able to use constructor injection without any @Autowired annotation at all. Have you tried that?
It would look like this and works for me:
@Service
class UserServiceController(val dsl: DSLContext, val teamService: TeamService) {
// your class members
}
|
[
"stackoverflow",
"0028551376.txt"
] | Q:
Avoid loading of invisible tiles when using multiple tile layers in Leaflet
I am using Leaflet with two tile layers. The first one, I will call it basement tile layer, provides tiles for whole world. The second one overlays the basement tile layer in a specific region defined by bounce option. I will call this one overlaying tile layer. In code this looks like the following:
var map = L.map('map');
// OpenstreetMap tile layer as basement
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// overlaying tile layer for specific region defined by bounds
L.tileLayer('http://{s}.examples.com/overlay/{z}/{x}/{y}.png', {
bounds: L.latLngBounds(L.latLng(59.321966, 18.05943), L.latLng(59.328469, 18.076167));
}).addTo(map);
The overlaying tile layer are not transparent. So for the bounds region only the tiles of overlaying tile layer are visible. Tiles provided by basement tile layer are not needed. But I didn't find a way to prevent Leaflet from loading these unnecessary tiles yet. I would be glad for any hint.
I thought about using tile events to interrupt loading of tiles which aren't needed. But as far as documented tile events can not manipulate tile loading.
Here is a JSFiddle demonstrating the behavior. As you see e.g. tile 14/4825/6155.png is loaded from openstreetmap.org even so it's invisible.
In my use case another think makes it more complicated: Overlaying map has strict borders cause it's generated by historic map sheet. So tiles are transparent at the borders of overlaying map. In these regions tiles of basement map has to be loaded.
A:
Thanks to @FrankPhillips hints in comment I figured out that I could overwrite _isValidTile method from L.GridLayer to achieve the functionality. I could add a hole option as a opposite to bounce option.
L.ExtendedTileLayer = L.TileLayer.extend({
_isValidTile: function (coords) {
var crs = this._map.options.crs;
if (!crs.infinite) {
// don't load tile if it's out of bounds and not wrapped
/*
* this._globalTileRange is not defined
* not quite sure why
*/
var globalTileRange = this._map.getPixelWorldBounds( coords.z );
var bounds = globalTileRange;
if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
(!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
}
var tileBounds = this._tileCoordsToBounds(coords);
// don't load tile if it doesn't intersect the bounds in options
if (this.options.bounds &&
! L.latLngBounds(this.options.bounds).intersects(tileBounds)) {
return false;
}
// don't load tile if it does intersect the hole in options
if (this.options.hole &&
L.latLngBounds(this.options.hole).intersects(tileBounds)) {
return false;
}
return true;
},
});
var map = L.map('map', {
center: [40.777838, -73.968654],
zoom: 14
});
new L.ExtendedTileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
hole: L.latLngBounds(
L.latLng(40.791853, -73.967128),
L.latLng(40.781455, -73.955713)
)
}).addTo(map);
L.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>.',
bounds: L.latLngBounds(
L.latLng(40.791853, -73.967128),
L.latLng(40.781455, -73.955713)
)
}).addTo(map);
I updated JSFiddle to show it working.
_isValidTile is mostly just copyed from Leaflet original. I had to reimplement this._globalTileRange since is was undefined. Code is only working for leaflet-src.js, since _isValidTime is uglifyed in production build.
|
[
"mathematica.stackexchange",
"0000051688.txt"
] | Q:
Problem evaluating a complicated integral
Apologies for stating my problem poorly in the first instance, thank you for the help in narrowing down the issue.
Problem
For those interested, it's for the exact unbiased inverse of the generalized Anscombe Transform, as given in this paper: http://dx.doi.org/10.1109/TIP.2012.2202675.
I'm trying to integrate, for a given value of $y$ and $\sigma$, the function
$$
\int_{-\infty}^{+\infty} f_{\sigma}\left ( z \right ) \sum_{k=0}^{\infty}\left ( \frac{y^{k}\mathrm{e}^{-y}}{k!\sqrt{2\pi \sigma^{2}}} \mathrm{e}^{-\frac{\left ( z-k \right )^{2}}{2\sigma^{2}}} \right ) \mathrm{d}z
$$
where
$$
f_{\sigma}\left ( z \right ) = \left\{\begin{matrix}
2\sqrt{z+\frac{3}{8}+\sigma^{2}}, & z > -\frac{3}{8}-\sigma^{2}\\
0, & z \leq -\frac{3}{8}-\sigma^{2}
\end{matrix}\right.
$$
which gives the equation in the reference below:
$$
\int_{-\infty}^{+\infty} 2\sqrt{z+\frac{3}{8}+\sigma ^{2}}\sum_{k=0}^{\infty}\left ( \frac{y^{k}\mathrm{e}^{-y}}{k!\sqrt{2\pi \sigma^{2}}} \mathrm{e}^{-\frac{\left ( z-k \right )^{2}}{2\sigma^{2}}} \right ) \mathrm{d}z
$$
In the reference, the values of the above function are tabulated, presumably in Matlab, for $\sigma \in \left \{ 0.01,...,50 \right \}$ and $y \in \left \{0,...,200 \right \}$. The authors have made this table available for download, but I want to do it myself.
However, I can't get it to work - Mathematica won't evaluate it:
func[z_, y_, sig_] :=
Piecewise[{{2 Sqrt[z + 3/8 + sig^2],z > -3/8 - sig^2}},0.]*
Sum[((y^k )* Exp[-y])/(k! * Sqrt[2 \[Pi] sig^2]) *
Exp[-((z - k)^2) / (2 sig^2)], {k, 0, Infinity}]
NIntegrate[func[z, 5, 2], {z, -Infinity, Infinity}]
Have I made a mistake somewhere? Or misunderstood the integral/problem as given?
Update
A suggestion is to replace the infinite sum with an upper limit of ~50 as it converges quickly. This does allow Mathematica to now evaluate the integral.
A:
It cannot be real, since zunder the radical goes to minus infinity. Anyway, if you only need a numerical table, why do not you do something like this:
f[y_, sig_, n_] :=
NIntegrate[
2 Sqrt[z + 3/8 + sig^2]*
Sum[((y^k)*Exp[-y])/(k!*Sqrt[2 \[Pi] sig^2])*
Exp[-((z - k)^2)/(2 sig^2)], {k, 0,
n}], {z, -\[Infinity], \[Infinity]}]
Here nis the number of terms in the sum. It converges rather fast. To check it let us do the following:
f[5, 2, #] & /@ {10, 100, 1000}
(* {5.92884 + 0.000418281 I, 6.03812 + 0.000418544 I,
6.03812 + 0.000418544 I} *)
The result is complex, which is to be expected, and not related to the number of terms in the sum.
|
[
"stackoverflow",
"0048837546.txt"
] | Q:
How to get a depth image from sparse depth data?
I am currently working on a problem where I have created an uint16 image of type CV_16UC1 based on Velodyne data where lets say 98% of the pixels are black (value 0) and the remaining pixels have the metric depth information (distance to that point). These pixels correspond to the velodyne points from the cloud.
cv::Mat depthMat = cv::Mat::zeros(frame.size(), CV_16UC1);
depthMat = ... //here the matrice is filled
If I try to display this image I get this:
On the image you can see that the brightest(white) pixels correspond to the pixels with biggest depth.From this I need to get a denser depth image or smth that would resemble a proper depth image like in the example shown on this video:
https://www.youtube.com/watch?v=4yZ4JGgLE0I
This would require proper interpolation and extrapolation of those points (the pixels of the 2D image) and it is here is where I am stuck. I am a beginner when it comes to interpolation techniques. Does anyone know how this can be done or at least can point me to a working solution or example algorithm for creating a depth map from sparse data?
I tried the following from the Kinect examples but it did not change the output:
depthMat.convertTo(depthf, CV_8UC1, 255.0/65535);
const unsigned char noDepth = 255;
cv::Mat small_depthf, temp, temp2;
cv::resize(depthf, small_depthf, cv::Size(), 0.01, 0.01);
cv::inpaint(small_depthf, (small_depthf == noDepth), temp, 5.0, cv::INPAINT_TELEA);
cv::resize(temp, temp2, depthf.size());
temp2.copyTo(depthf, (depthf == noDepth));
cv::imshow("window",depthf);
cv::waitKey(3);
A:
I managed to get the desired output(something that resembles a depth image) by simply using dilation on the sparse depth image:
cv::Mat result;
dilate(depthMat, result, cv::Mat(), cv::Point(-1, -1), 10, 1, 1);
|
[
"stackoverflow",
"0009216191.txt"
] | Q:
Automatically update field in SQL Server table 15 seconds after insert
I have a bit of an odd situation, and I'm struggling with populating a field in a table. I should also mention I'm pretty new to SQL Server.
What is in use: I'm working in a SQL Server 2008 database. There are two tables of concern, PO_APPROVAL_LOG, and PO_HDR.
The process that is being performed here is the creation of a new purchase order. In some cases it requires a manager approval to create the PO. I'm using a winform (C#) that authenticates the manager against Active Directory, if the manager is a member of a certain group, PO is approved.
My situation: there is a 3rd party application in use, and I'm writing some validation code (mentioned above) which executes before the save event can occur in the application. If certain criteria is met, my validation code returns back TRUE and allows the application to proceed with the save. When the save is kicked off, a handful of tables in the database are inserted into, including PO_HDR. I cannot change the order which events occur, I can only write these validation rules. The application will not continue until it receives a specific object back from my code which has a SUCCESS property set to TRUE or FALSE.
The problem I'm having is related to logging the PO approval into the PO_APPROVAL_LOG table. Right now, the PO_APPROVAL_LOG table is inserted into when the manager would submit their credentials. This occurs before PO_HDR is populated. I need to include the PO_HDR.PO_NUMBER, in order to do that, I need to wait until after PO_HDR populates, and grab the PO_NUMBER value, and update the corresponding PO_APPROVAL_LOG entry. Very few POs actually need approval, the PO_APPROVAL_LOG table shouldn't see a lot of action.
I cannot create a trigger on the PO_HDR table.
For the sake of experimentation, I played with creating an AFTER INSERT trigger on PO_APPROVA_LOG that used a waitfor delay to see if I could fetch the PO_NUMBER after PO_HDR had a chance to populate. (Yes, I do know waitfor delay in a trigger is a terrible idea, it was just to experiment in a play database). This didn't work, as the application didn't get a response from my validation code of TRUE until after the insert and subsequent trigger execution finished.
My question: Could a SQL Agent job be a possible solution? It would need to run every minute or two. One of my concerns is, would this be very taxing on the database? If the job ran and determined if a procedure should be called to update the log table (found one or more NULL PO_NUMBER values in PO_APPROVAL_LOG), perhaps that could work.
Any other advice? This has been giving me trouble for a while.
If any of that is unclear, please ask! Thanks!
A:
There is no way to do it in sql, try to perform this from your code.
|
[
"stackoverflow",
"0033477429.txt"
] | Q:
JavaFX TextField focusProperty lost on touchScrollEvent
I am showing a Keyboard if the user clicks into a my extended TextField with the code shown below. When scrolling with a mouse you don't loose the focus to the TextField, but when scrolling by touch the focus is lost - and keyboard dispears of course. Is there a way to get the same behavior on touchScroll as on mouseScroll? I don't want the keyboard to disapear if the user is scrolling with touch!
focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(final ObservableValue<? extends Boolean> observable, final Boolean oldValue,
final Boolean newValue) {
KeyboardUtils.INSTANCE.setVisible(newValue);
}
});
A:
This is pretty basic sir, when you are scrolling with a Touchscroll you definitely Touch a scrollable Pane area, and that Pane requestFocus()by the touch, so your TextField will loose its focus.
so to solve it you send focus back to your TextField if you detect a touch either by using the Scrolling listener of that Pane or Node or go for setOnTouchStationary() or setOnTouchReleased(), to help tweak the visibility of your keyboard instead of lying on focus of your TextField.
EDIT
Try this
Node lastFocusedNode =null; // lastly known node to have focus
//now every node or child in your ScrollPane or Scrollable parent
//that you care about will have a focusable listener-including
// your textfield
textField.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(
ObservableValue<? extends Boolean> observable,
Boolean oldValue, Boolean newValue) {
if(!newValue){//if they loose focus
lastFocusedNode = textField;
//if they loose focus attach them to lastFocusedNode
}
}
});
//the above saves you iterations
then when your ScrollPane/scrollable Node Receives focus you set them to the lastFocusedNode since its just going to allow scrolling.
sp.focusedProperty().addListener(new InvalidationListener() {
@Override
public void invalidated(Observable observable) {
if (lastFocusedNode != null) {
lastFocusedNode.requestFocus();
}
}
});
the above assumes your ScrollPane will just not do anything consuming aside from scrolling..
if you ScrollPane/scrollable parent is not going with that assumption then
you go with this approach-detect when the user scrolls after touching your content area of your Scrollable Node-this works only if user attempts to scroll after touching.
//approach loaded
final InvalidationListener lis = new InvalidationListener() {
@Override
public void invalidated(Observable observable) {
//here it is changing
if(sp.isFocused())
lastFocusedNode.requestFocus();//take the focus away
}
};
using the above invalidation listener you set it on the hvalueProperty() and vvalueProperty() or your ScrollPane - which Scrollable parent are you using?
sp.hvalueProperty().addListener(lis);
sp.vvalueProperty().addListener(lis);
then you are done. any of the above solution will cause No problemo
EDIT 2
from what i know TouchEvent is for Touch enabled computers, so maybe go with MouseEvent and you can detect Pane.setOnMousePressed(); etc etcc
Hope it helps
|
[
"stackoverflow",
"0058342691.txt"
] | Q:
Unpacking a first-class module constrained by a type variable
I'm trying to write a function that basically looks like this:
module type M = sig
type t
val doStuff : t -> unit
end
let f : 'a. 'a -> (module M with type t = 'a) -> unit
= fun value (module MSomething) -> MSomething.doStuff value
That is, a function that takes any type of value, and an associated module containing one or more functions that can operate on this value. Unfortunately the above will have the compiler complaining that
The type of this packed module contains variables
However, I've found that I can still get this to work if I wrap it in a GADT that 1) makes 'a an existential and 2) provides a converter from another parameterized type variable to the existential:
type 'b gadt =
GADT: ('b -> 'a) * (module M with type t = 'a) -> 'b gadt
let f value (GADT (convert, (module MSomething))) =
MSomething.doStuff (convert value)
The GADT itself isn't a nuisance1, but I'd very much like to avoid the convert function since it doesn't serve any purpose other than to help the compiler out. Is this possible somehow?
Full example/MCVE
module type M = sig
type t
val doStuff : t -> unit
end
module MInt = struct
type t = int
let doStuff = print_int
end
let f : 'a. 'a -> (module M with type t = 'a) -> unit
= fun value (module MSomething) -> MSomething.doStuff value
let () = f 42 (module MInt : M with type t = int)
let () = print_newline ()
1 I actually want the GADT because I need the module to be parameterized by a different existential so I can put differently typed modules together in a list. But for simplicity's sake I've omitted that from the first example above.
A:
With first class modules (like for any local module) you should reach for locally abstract types and not explicit polymorphic annotations:
let f (type a) (value:a) (module M: M with type t = a) = M.doStuff value
works just fine.
|
[
"stackoverflow",
"0003241237.txt"
] | Q:
Specify two icon sizes in iPhone4/iPad app
The iPad and iPhone4 both are armv7 (not 6), and I'm curious to know how to specify two separate icon sizes given that the target architecture is exactly the same. Specifying two in a typical universal app is simple, however I'm not sure how to do this. I can't find it in the documentation, although it may be! (Sorry if it is; and I'm sorry if this was asked before!)
Thanks!
Kyle
A:
In order to specify two different sizes for the iPhone4 and iPad, refer to iTunesConnect Developer Guide. It lists the image sizes you need in order to do so (both should be included in your binary).
What you're looking for is under the Requirements section beginning on page 6.
Hope this helps...
A:
Here is a better more detailed link.
Application Icons
When specifying icon files using the
CFBundleIconFiles key, it is best to
omit the filename extensions of your
image files. If you include a filename
extension, you must explicitly add all
of your image files (including any
high-resolution variants) to the
array. When you omit the filename
extension, the system automatically
detects high-resolution variants of
your file using the base filename you
provide.
|
[
"stackoverflow",
"0033613806.txt"
] | Q:
Merge two, unequal, two-dimensional arrays
I have two arrays:
$addresses = array(array('address' => 'Address1', 'housenumber' => 22, 'zipcode' => '1234 AB', 'city' => 'Amsterdam', 'country' => 'Netherlands'),
array('address' => 'Address2', 'housenumber' => 62, 'zipcode' => '1234 AC', 'city' => 'Rotterdam', 'country' => 'Netherlands'),
array('address' => 'Address3', 'housenumber' => 63, 'zipcode' => '1234 AD', 'city' => 'Eindhoven', 'country' => 'Netherlands'));
$tasks = array(array('task_action' => 'pick up', 'note' => 'Some note 1'),
array('task_action' => 'deliver', 'note' => 'Some note 2'),
array('task_action' => 'pick up', 'note' => 'Some note 3'));
This is what I want to achieve:
$NewArray = array(array('address' => 'Address 1', 'housenumber' => 22, 'zipcode' => '1234 AB', 'city' => 'Amsterdam', 'country' => 'Nederland', 'task_action' => 'pick up', 'note' => 'Some note'),
array('address' => 'Address 2', 'housenumber' => 62, 'zipcode' => '1234 AC', 'city' => 'Rotterdam', 'country' => 'Nederland', 'task_action' => 'deliver', 'note' => 'Some note 2'),
array('address' => 'Address 3', 'housenumber' => 63, 'zipcode' => '1234 AD', 'city' => 'Eindhoven', 'country' => 'Nederland', 'task_action' => 'pick up', 'note' => 'Some note 3'));
I tried things like:
for ($x = 0; $x < count($addresses); $x++) {
for ($x = 0; $x < count($tasks); $x++) {
$addresses[$x][] = $tasks[$x];
}
}
Can someone provide me a little help on this?
A:
You could look at this as a multi-dimensional array, but really it's a list of entries.
You have a list of addresses and a list of tasks, and you want to combine them:
foreach ($addresses as $index => $_) {
$addresses[$index] = array_merge($addresses[$index], $tasks[$index]);
}
|
[
"stackoverflow",
"0061198221.txt"
] | Q:
how to settext button in bottom sheet dialog fragment?
i have one class for bottomsheetdialog fragment.I looked at many places but I'm confused.i want to change text of button in bottom sheet.i get this error 'android.view.View android.view.View.findViewById(int)' on a null object reference.
here are my codes;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
bottomSheetFragment=new BottomSheetFragment();
View viewDialog=bottomSheetFragment.getView();
assert viewDialog != null;
MaterialButton btn_titresim=viewDialog.findViewById(R.id.btn_titresim);
btn_titresim.setText("text");
}
}
Another class for BottomSheetDialogFragment
public class BottomSheetFragment extends BottomSheetDialogFragment {
public BottomSheetFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Objects.requireNonNull(getDialog()).setOnShowListener(dialog -> {
BottomSheetDialog d = (BottomSheetDialog) dialog;
View bottomSheetInternal =
d.findViewById(com.google.android.material.R.id.design_bottom_sheet);
assert bottomSheetInternal != null;
BottomSheetBehavior.from(bottomSheetInternal).setState(BottomSheetBehavior.STATE_EXPANDED);
});
return inflater.inflate(R.layout.layout_popup, container, false);
}
}
A:
You can solve this by having a listener interface in your fragment that returns the BottomSheet fragment's View back to your activity, so you can then access the BottomSheetDialogFragmentunderlying views normally by findViewById() method.
Here I decided to use the Singleton pattern for the BottomSheetDialogFragment to set a listener instance from the activity.
So in your fragment add a listener; it's named below FragmentListener, call the listener callback in onCreateView() or in onViewCreated()
public class BottomSheetFragment extends BottomSheetDialogFragment {
public BottomSheetFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
interface FragmentListener {
void getView(View view);
}
static FragmentListener mFragmentListener;
public static BottomSheetFragment newInstance(FragmentListener listener) {
mFragmentListener = listener;
return new BottomSheetFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Objects.requireNonNull(getDialog()).setOnShowListener(dialog -> {
BottomSheetDialog d = (BottomSheetDialog) dialog;
View bottomSheetInternal =
d.findViewById(com.google.android.material.R.id.design_bottom_sheet);
assert bottomSheetInternal != null;
BottomSheetBehavior.from(bottomSheetInternal).setState(BottomSheetBehavior.STATE_EXPANDED);
});
View view = inflater.inflate(R.layout.layout_popup, container, false);
// Trigger the listener callback to return the view back to the activity
// mFragmentListener.getView(view); // Not working in all devices
return inflater.inflate(R.layout.layout_popup, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
// Trigger the listener callback to return the view back to the activity
mFragmentListener.getView(view);
}
}
implement the listener by your activity, and change the text in your callback, and instantiate the BottomSheetDialogFragment using the singleton pattern instead.
public class MainActivity extends AppCompatActivity implements BottomSheetFragment.FragmentListener {
@Override
protected void onCreate(final Bundle savedInstanceState) {
bottomSheetFragment = BottomSheetFragment.newInstance(this);
}
@Override
public void getView(View view) {
// Setting the text
((MaterialButton) view.findViewById(R.id.btn_titresim)).setText("text");
}
}
Wish that solves your problem
|
[
"stackoverflow",
"0021667087.txt"
] | Q:
Bootstrap 3 and Simple Form display issue with form inputs
Recent upgrade to Bootstrap 3 on a Rails app. SimpleForm text box and also other form inputs are too large - they are erroneously full-page in length. The app does have responsive design, and the form input boxes do resize.
I'd like to limit the form input size to 50% instead of full page.
I did add this initializer gist https://gist.github.com/tokenvolt/6599141 but it did not seem to have an effect.
I am unfamiliar with the Bootstrap3/Simpleform2.1.1 conflicts.
I adjusted the width to 50% in the application.css.scss, but that did not make a clean change
/* forms */
input, textarea, select, .uneditable-input {
border: 1px solid #bbb;
width: 100%;
padding: 10px;
margin-bottom: 15px;
@include box_sizing;
}
A:
By length do you mean width? If you don't want the form to be too wide you could divide the page into columns and then put the form into a smaller column.
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<%= simple_form-for...
</div>
</div>
Bootstrap uses a gridsystem that divides the page into 12 columns. if you just put the form on, it will take up all 12 columns (the whole page) so you need to specify how many columns you want the form to take up. Here's a post that really helped me understand the new gridsystem: http://blog.jetstrap.com/2013/08/bootstrap-3-grids-explained/
|
[
"stackoverflow",
"0038325120.txt"
] | Q:
How to solve "Neither Jetty ALPN nor OpenSSL via netty-tcnative were properly configured"?
I'm trying to create a Dataflow job in order to insert rows in BigTable, but while I'm testing the Dataflow job locally I get the following error:
Exception in thread "main" com.google.cloud.dataflow.sdk.Pipeline$PipelineExecutionException: java.lang.IllegalStateException: Neither Jetty ALPN nor OpenSSL via netty-tcnative were properly configured.
at com.google.cloud.dataflow.sdk.Pipeline.run(Pipeline.java:186)
Bellow you can find my Main code:
CloudBigtableOptions options =
PipelineOptionsFactory.fromArgs(args).withValidation().create().as(CloudBigtableOptions.class);
options.setProject("xxxxxxxxx");
options.setBigtableProjectId("xxxxxxxxx");
options.setBigtableInstanceId("xxxxxxxxx");
options.setBigtableTableId("xxxxxxxxx");
options.setZone("europe-west1-b");
options.setRunner(DirectPipelineRunner.class);
CloudBigtableTableConfiguration config =
CloudBigtableTableConfiguration.fromCBTOptions(options);
Pipeline p = Pipeline.create(options);
CloudBigtableIO.initializeForWrite(p);
FixedWindows window = FixedWindows.of(Duration.standardMinutes(1));
p
.apply(Create.of("Hello"))
.apply(Window.into(window))
.apply(ParDo.of(MUTATION_TRANSFORM))
.apply(CloudBigtableIO.writeToTable(config));
p.run();
Another try has been with the following code:
CloudBigtableTableConfiguration config =
new CloudBigtableTableConfiguration.Builder()
.withProjectId("xxxxxxxxx")
.withInstanceId("xxxxxxxxx")
.withTableId("xxxxxxxxx")
.build();
Pipeline p = Pipeline.create(options);
CloudBigtableIO.initializeForWrite(p);
FixedWindows window = FixedWindows.of(Duration.standardMinutes(1));
p
.apply(Create.of("Hello"))
.apply(Window.into(window))
.apply(ParDo.of(MUTATION_TRANSFORM))
.apply(CloudBigtableIO.writeToTable(config));
p.run();
But I got the same error.
Am I doing something wrong?
EDIT:
Full error:
Exception in thread "main" com.google.cloud.dataflow.sdk.Pipeline$PipelineExecutionException: java.lang.IllegalStateException: Neither Jetty ALPN nor OpenSSL via netty-tcnative were properly configured.
at com.google.cloud.dataflow.sdk.Pipeline.run(Pipeline.java:186)
at HubCache.main(HubCache.java:75)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.IllegalStateException: Neither Jetty ALPN nor OpenSSL via netty-tcnative were properly configured.
at com.google.bigtable.repackaged.com.google.cloud.grpc.BigtableSession.<init>(BigtableSession.java:236)
at org.apache.hadoop.hbase.client.AbstractBigtableConnection.<init>(AbstractBigtableConnection.java:123)
at org.apache.hadoop.hbase.client.AbstractBigtableConnection.<init>(AbstractBigtableConnection.java:91)
at com.google.cloud.bigtable.hbase1_0.BigtableConnection.<init>(BigtableConnection.java:33)
at com.google.cloud.bigtable.dataflow.CloudBigtableConnectionPool$1.<init>(CloudBigtableConnectionPool.java:72)
at com.google.cloud.bigtable.dataflow.CloudBigtableConnectionPool.createConnection(CloudBigtableConnectionPool.java:72)
at com.google.cloud.bigtable.dataflow.CloudBigtableConnectionPool.getConnection(CloudBigtableConnectionPool.java:64)
at com.google.cloud.bigtable.dataflow.CloudBigtableConnectionPool.getConnection(CloudBigtableConnectionPool.java:57)
at com.google.cloud.bigtable.dataflow.AbstractCloudBigtableTableDoFn.getConnection(AbstractCloudBigtableTableDoFn.java:96)
at com.google.cloud.bigtable.dataflow.CloudBigtableIO$CloudBigtableSingleTableBufferedWriteFn.getBufferedMutator(CloudBigtableIO.java:941)
at com.google.cloud.bigtable.dataflow.CloudBigtableIO$CloudBigtableSingleTableBufferedWriteFn.processElement(CloudBigtableIO.java:966)
pom.xml:
<dependencies>
<dependency>
<groupId>com.google.cloud.dataflow</groupId>
<artifactId>google-cloud-dataflow-java-sdk-all</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>com.google.cloud.bigtable</groupId>
<artifactId>bigtable-hbase-dataflow</artifactId>
<version>LATEST</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>LATEST</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.netty/netty-tcnative-boringssl-static -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-tcnative-boringssl-static</artifactId>
<version>1.1.33.Fork13</version>
<classifier>${os.detected.classifier}</classifier>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<extensions>
<!-- Use os-maven-plugin to initialize the "os.detected" properties -->
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.4.0.Final</version>
</extension>
</extensions>
</build>
A:
We've just released the 0.9.1 client that paired with Netty tcnative-boringssl-static we use Fork19 as shown in the connector examples and pardo hello example no longer require using os.detected.
A:
Problem was that the extension os-maven-plugin, to initialize the "os.detected" properties, didn't initialize the property correctly.
I've done a test setting the property corrrectly and the test has been executed without problems.
|
[
"stats.stackexchange",
"0000257888.txt"
] | Q:
Performing Bayesian prediction in practice when an explicit expression for the likelihood is not available
I have a numerical code which, given an input vector $\mathbf{x}$ and parameter vector $\boldsymbol{\theta}$, gives me an output $l=f(\mathbf{x},\boldsymbol{\theta})$. I assume the statistical model
$y=f(\mathbf{x},\boldsymbol{\theta})+\epsilon$
where $\epsilon\sim\mathcal{N}(0,\sigma)$. I have a random sample $D=\{\mathbf{x}_i,y_i\}$ and I would like to:
calibrate the parameters using Bayesian inference, i.e., compute $p(\boldsymbol{\theta}|D)$
use $p(\boldsymbol{\theta}|D)$ to perform output predictions with associated credible intervals.
I know how to proceed in theory, but I'm not sure about the fiddly bits. So, as always
$p(\boldsymbol{\theta}|D)=\frac{p(D|\boldsymbol{\theta})p(\boldsymbol{\theta})}{\int p(D|\boldsymbol{\theta})p(\boldsymbol{\theta})d\boldsymbol{\theta}}$
The likelihood should be:
$p(D|\boldsymbol{\theta})=\frac{1}{\sqrt{2\pi}^N\sigma^N}\prod_{i=1}^N \exp{\left(-\frac{(y_i-{f_i(\mathbf{x}_i,\boldsymbol{\theta}))^2}}{2\sigma^2}\right)}$
Since the code is a black box, I don't have an explicit expression for $p(D|\boldsymbol{\theta})$, but I can compute this expression for any given $\boldsymbol{\theta}$. I know $p(\boldsymbol{\theta})$ (I choose it). The hard part is computing
$\int p(D|\boldsymbol{\theta})p(\boldsymbol{\theta})d\boldsymbol{\theta}$
I can imagine two approaches:
if the number of parameters $d$ is small enough, then numerical quadrature may be sufficient
otherwise, I think I should use an MCMC code. Suppose I have one available: the algorithm asks me in input the unnormalized target distribution (see for example here), which would be (correct me if I'm wrong) $p(D|\boldsymbol{\theta})p(\boldsymbol{\theta})$. The problem is that I don't have an explicit expression to pass to the algorithm: I can only evaluate it for given $\boldsymbol{\theta}$. So is the only solution to write my own MCMC? If so, I'll ask another question for details on how to do this.
Anyway, suppose I managed to compute $\int p(D|\boldsymbol{\theta})p(\boldsymbol{\theta})d\boldsymbol{\theta}$ one way or another. Now I have an "expression" for $p(\boldsymbol{\theta}|D)$, meaning that I can compute
$p(\boldsymbol{\theta}|D)$ for any given $\boldsymbol{\theta}$. If I could sample from this distribution, then I think I could perform prediction this way: I choose a new input vector $\mathbf{x}^*$ where I want my
prediction. I draw a sample of size $m$ $\{\boldsymbol{\theta}^{(1)},\dots,\boldsymbol{\theta}^{(m)}\}$ from $p(\boldsymbol{\theta}|D)$. I then compute the size $m$ sample
$\{y^{(1)}=f(\mathbf{x}^*,\boldsymbol{\theta}^{(1)}), \dots,y^{(m)}=f(\mathbf{x}^*,\boldsymbol{\theta}^{(m)})\}$
This would be my prediction at $\mathbf{x}^*$. Right? The problem is how to sample from $p(\boldsymbol{\theta}|D)$.
What approaches are available to do this?
PS if $\sigma$ is unknown, I think I can still apply the same approach by just including it in $\boldsymbol{\theta}$. Correct?
A:
The problem you have described, integrating $\int p(D|\boldsymbol{\theta})p(\boldsymbol{\theta})d\boldsymbol{\theta}$, is the driver of the notorious computational difficulties of Bayesian analysis. MCMC seeks to avoid evaluating this integral directly by sampling from the joint posterior $p(\boldsymbol{\theta}|D)$. As jaradniemi says, MCMC is not the only solution, but it is far and away the most common solution among Bayesian practitioners these days. A few other approaches in no particular order: importance sampling, quadrature, grid approximation, rejection sampling.
There are also various approximations for the posterior distribution, like fitting a multivariate normal (sometimes you'll see this kind of approximation justified through the so called "Bayesian CLT") or using variational bayes. The approximations have the advantage of speed, but it's often difficult to assess their accuracy without doing the full inference through some other method.
Assuming whatever method you use yields a sample $\{\boldsymbol{\theta}^{(1)},\dots,\boldsymbol{\theta}^{(m)}\}, \ i=1,\ldots,m$ from the joint posterior (as you would get from MCMC, for example), to handle a new input $\boldsymbol{x}^*$, you would draw $\{y^{(1)}, \ldots, y^{(m)}\}$ from $y^{(i)} \sim \operatorname{\mathcal{N}}\left( f(\boldsymbol{x}^*, \boldsymbol{\theta^{(i)}}),\sigma \right)$. This would give you the posterior preditive distribution for $y$ corresponding with the input vector $\boldsymbol{x^*}$. If desired, you could take whatever summary statistic you wanted from this distribution -- the mean, median, another quantile, etc.
Edit showing an example of grid approximation
Grid approximation is a simple idea where you evaluate an un-normalized distribution across a grid of points, and then gather samples from the grid points. For it to work well, you must have a fine enough grid. Here's 1-dimensional example from a normal distribution using R. As you can see, it's easy to extend to multiple dimensions, but the computation gets expensive quickly as the number of dimensions grows. For example, if you have 3-dimensions, even if your grid is only $1000$ points in each dimension, you need $1000^3$ grid points.
mu.truth <- 0
sd.truth <- 1.5
x.grid <- seq(-10, 10, length.out=10000)
some.constant <- 8585 # Totally arbitrary, just to illustrate we don't need a normalized density to use grid approximation
q.dens <- dnorm(x.grid, mean=mu.truth, sd=sd.truth)/some.constant
normalized.dens <- q.dens/sum(q.dens) # R's sample function does this automatically, but just to be explicit...
y.sample <- sample(x.grid, 1000, replace=TRUE, prob=normalized.dens) # Gives us a sample from N(mu.truth, sd.truth^2)
# Visualize how well the approximation did
hist(y.sample, freq=FALSE)
lines(x.grid, dnorm(x.grid, mean=mu.truth, sd=sd.truth), col="blue")
As you can see, this results in a relatively representative sample from the un-normalized pdf.
|
[
"ell.stackexchange",
"0000112095.txt"
] | Q:
Getting deeper meaning getting stronger
Imagine there is a couple who's love is getting more solid and strong as time passes. They have lived e.g 20 years and in spite of other's expectation they fall in love more and more. I was wondering if someone could let me know if in English the way I am trying to say the sentence below sounds natural:
Their love will get deeper (meaning gets stronger) as time passes.
A:
Your example using
will get deeper
only talks about the future of their love without accounting for the past, which your question frames as a deepening process also.
A couple of ways to say this
They became more deeply in love as time passed.
Their love grew deeper as time passed.
often love is described as growing over time (as opposed to getting), both these sentences refer to past and future sates of their love.
"Deeper" also has the meaning of "stronger" in learning.
deeper understanding = stronger understanding (and includes more detailed understanding)
|
[
"physics.stackexchange",
"0000311241.txt"
] | Q:
The difference between Type I strings and Type II strings
I understand Type II strings but i do not understand the difference between Type I and Type II strings. Can anyone explain this to me?
A:
Type II superstring theory starts from the assumption that small perturbations of the vacuum state result only in orientable closed[*] strings.
By contrast, Type I superstring theory starts from the assumption that perturbations near the vacuum state can be either open or closed strings, but both must be non-orientable.
Another difference is that while Type II theories have two 10-dimensional supersymmetry generators, Type I theories have only one. This difference is a consequence of the non-orientability of Type I strings. Assuming the strings are non-orientable means forcing the positive and negative chiral components of the worldsheet spinors to be dependent on each other. They are both determined by the same set of modes, not two different sets of modes as in Type II.
For Type I superstring theory, anomaly cancellation requires the gauge group to be SO(32).
[*] Type II does include open strings. However, they don't show up in the vacuum perturbation theory--they are only there in connection with non-perturbative effects (D-branes).
|
[
"stackoverflow",
"0059635094.txt"
] | Q:
Using forked ProgressMonitorDialog in synchronized block
I am using a jface ProgressMonitorDialog to cache some data. This is being done in a synchronized block in order to not run into concurrency problems.
Strangely though, the synchronized block does not work if I am calling the ProgressMonitorDialog#run with the parameter fork=true.
Can someone explain to me what is happening here?
Output:
start synchronization Thread[main,5,main]
start synchronization Thread[main,5,main]
finished synchronization Thread[main,5,main]
finished synchronization Thread[main,5,main]
Code:
private void test() {
Shell shell = new Shell();
SyncTest st = new SyncTest(shell);
shell.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
st.doSmth();
}
});
shell.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
st.doSmth();
}
});
}
private static class SyncTest {
private static final Object LOCK = new Object();
private Shell shell;
public SyncTest(Shell shell) {
this.shell = shell;
}
public void doSmth() {
synchronized (LOCK) {
System.out.println("start synchronization " + Thread.currentThread().toString());
try {
ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);
pmd.run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
Thread.sleep(1000);
}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
System.out.println("finished synchronization " + Thread.currentThread().toString());
}
}
}
A:
You are using Display.asyncExec to put both the doSmth calls in to the list of runables that will be run in the UI thread as soon as Display.readAndDispatch is called.
So the first call to doSmth runs and enters the synchronized block.
It then calls pmd.run with fork true. This runs the runnable in a separate thread and also calls Display.readAndDispatch repeatedly to keep the UI thread responsive.
These Display.readAndDispatch calls will pick up the second call to doSmth - but you are still inside the synchronized block and still on the same UI thread so synchronized does not block and you get the observed result.
If you want to run code in the background use a Job and specify a 'scheduling rule' to prevent any conflicting second job from running at the same time. If you have setUser(true) in the job it will display a progress dialog.
|
[
"stackoverflow",
"0043689697.txt"
] | Q:
Simple List filter & Search filter with dc.js?
Would someone be able to give an example of how to create a list box filter with dc.js? as well as a search box filter?
I'm trying to create a dashboard with dc.js and instead of filtering through all distinct values using a bar chart, I'm trying to make a listbox with buttons. Is this easy to do?
Similarly, what would be the simplest way to create a search box to filter the data?
Any guidance would be much appreciated!
A:
List box
Sometimes the names of UI elements are ambiguous, but I think you're referring to a select widget, which is available in dc.js 2.1+ as dc.selectMenu.
Demo
Search box
Pull Request #936 implements this. Please try it out and leave your review on the PR.
It's available with the current latest dc.js in this branch.
|
[
"stackoverflow",
"0042235759.txt"
] | Q:
jQuery color animate not syncing across multiple elements
I'm having trouble syncing a color change animation using jQuery. For some reason, the font color inside a button element only changes when every other color change has finished processing. Here is the code:
$(".jumbotron-fluid, .btn").animate({
backgroundColor: colors[seed]["background"]
});
$(".container").animate({
backgroundColor: colors[seed]["container"]
});
$("p, blockquote footer, .btn, a:link, a:visited, a:hover, a:active, a").animate({
color: colors[seed]["font"]
});
Here is a link to a CodePen that shows this project in action: http://codepen.io/christianflorez/full/OWdYRm/
When clicking on the "Get a new quote" button, every time the font color in the button changes to white, it doesn't change in sync with the rest of the DOM. Anyone know why this might be happening? I've tried testing the code across multiple browsers and the same issue appears. Thanks everyone for your help.
A:
The queueparameter of animate is set true as default. As you animate .btn twice, the second animation is fired after the end of first. Change queue to false for the first .btn animate. codepen link
$(".jumbotron-fluid, .btn").animate({
backgroundColor: colors[seed]["background"]
},{queue:false}
);
$(".container").animate({
backgroundColor: colors[seed]["container"]
}
);
$("p, blockquote footer, .btn, a:link, a:visited, a:hover, a:active, a").animate({
color: colors[seed]["font"]
}
);
|
[
"stackoverflow",
"0016967482.txt"
] | Q:
hibernate one to many query using mappings
I have 3 classes with the corresponding relationship parent child on them:
//SigTcContraloriaObjetivos, SigTcContraloriaIniciativas, SigTcContraloriaAcciones
<class dynamic-insert="false" dynamic-update="true" mutable="true" name="org.citi.tablero.contraloria.planes.model.db.hibernate.dto.SigTcContraloriaObjetivos" optimistic-lock="version" polymorphism="implicit" select-before-update="false" table="SIG_TC_CONTRALORIA_OBJETIVOS">
<id column="ID_OBJETIVO" name="idObjetivo">
<generator class="sequence">
<param name="sequence">SEQ_SIG_CONTRALORIA_OBJETIVOS</param>
</generator>
</id>
<property column="DESCRIPCION" name="descripcion"/>
<set name="children" inverse="false" cascade="all" lazy="false">
<key column="ID_OBJETIVO"/>
<one-to-many class="SigTcContraloriaIniciativas"/>
</set>
</class>
<class dynamic-insert="false" dynamic-update="true" mutable="true" name="org.citi.tablero.contraloria.planes.model.db.hibernate.dto.SigTcContraloriaIniciativas" optimistic-lock="version" polymorphism="implicit" select-before-update="false" table="SIG_TC_CONTRALORIA_INICIATIVAS">
<id column="ID_INICIATIVA" name="idIniciativa">
<generator class="sequence">
<param name="sequence">SEQ_SIG_CONTRALORIA_INICIATIVA</param>
</generator>
</id>
<property column="DESCRIPCION" name="descripcion"/>
<property column="ID_OBJETIVO" name="idObjetivo" />
<set name="children" inverse="false" cascade="all" lazy="false">
<key column="ID_INICIATIVA"/>
<one-to-many class="SigTcContraloriaAcciones"/>
</set>
</class>
<class dynamic-insert="false" dynamic-update="true" mutable="true" name="org.citi.tablero.contraloria.planes.model.db.hibernate.dto.SigTcContraloriaAcciones" optimistic-lock="version" polymorphism="implicit" select-before-update="false" table="SIG_TC_CONTRALORIA_ACCIONES">
<id column="ID_ACCION" name="idAccion">
<generator class="sequence">
<param name="sequence">SEQ_SIG_CONTRALORIA_ACCIONES</param>
</generator>
</id>
<property column="DESCRIPCION" name="descripcion"/>
<property column="ID_INICIATIVA" name="idIniciativa" />
<property column="ID_ORGANIZACION" name="idOrganizacion" />
</class>
I need a way to select one SigTcContraloriaIniciativa with the associated SigTcContraloriaObjetivo and with the associated SigTcContraloriaAccion
This is the query im using:
String sql = "select distinct p from SigTcContraloriaObjetivos p join p.children c join c.children b where and b.idOrganizacion = 8";
(In the database i only have one SigTcContraloriaAccion with idOrganizacion= 8, so my expected result is one SigTcContraloriaObjetivos with the corresponding SigTcContraloriaIniciativas with the corresponding SigTcContraloriaAccion im selecting)
My problem is when I execute query.list() it returns me one SigTcContraloriaObjetivos (as expected), two SigTcContraloriaIniciativas(Not expected, i only expect one), and two SigTcContraloriasAcciones (only one expected) for each SigTcContraloriaIniciativas
UPDATE:
This is the image of the tables:
A:
I think your query is returning the correct result but that you do not understand it.
As you have stated, the correct SigTcContraloriaObjetivos object is being returned. What you get back is the object and ALL its associations (assuming fetch type is EAGER). Those associations are NOT filtered based upon your query though.
I think you are expecting:
SigTcContraloriaObjetivos (ID=1)
----- SigTcContraloriaIniciativas (ID=1)
----- SigTcContraloriaAcciones (ID=5)
JPA/Hibernate does not work that way. The result of such a query will always be the object(s) that meet the criteria and those object(s) will contain all their associated objects.
|
[
"stackoverflow",
"0051190519.txt"
] | Q:
Javascript NaN large integer error
So I was calculating last ten digit of the series :
1^1 + 2^2 + 3^3 + ... + 1000^1000
But I keep getting NaN as a result.
Code:
function myFunction() {
var i, x, a, sum = 0; {
for (i = 1; i <= 1000; i++) {
var a = Math.pow(i, i);
sum += a;
}
var x = sum;
var y = x % 10000000000;
}
document.getElementById("demo").innerHTML = y;
}
<p>Click the button to demontrate </p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
A:
You have an Infinity value - try the code below :
function myFunction() {
var i, x, a, sum = 0; {
for (i = 1; i <= 1000; i++) {
var a = Math.pow(i, i);
if(a!=Infinity)sum += a;
}
var x = sum;
var y = x % 10000000000;
document.getElementById("demo").innerHTML = y;
}
|
[
"salesforce.stackexchange",
"0000291789.txt"
] | Q:
Is it possible to dynamically create LWC from aura component?
We can't dynamically create LWC like aura does. We can embed LWC in aura, is it possible to dynamically create LWC using $A.createcomponent within aura component?
A:
No. If you want to "dynamically" create an LWC you actually have to dynamically create an Aura component that statically wraps the LWC component.
|
[
"stackoverflow",
"0007549179.txt"
] | Q:
SignalR + posting a message to a Hub via an action method
I am using the hub- feature of SignalR (https://github.com/SignalR/SignalR) to publish messages to all subscribed clients:
public class NewsFeedHub : Hub
public void Send(string channel, string content)
{
Clients[channel].addMessage(content);
}
This works fine when calling "Send" via Javascript, but I would also like the web application to publish messages (from within an ASP.NET MVC action method). I already tried instantiating a new object ob NewsFeedHub and calling the Send method, but this results in an error (as the underlying "Connection" of the Hub is not set). Is there a way to use the Hub without a connection?
A:
Please note that the SignalR API has changed multiple times since this question was asked. There is a chance that some answers will become out of date. This does not mean that they should be down-voted as they were correct at the time of writing
There is another updated answer for this, as seen in the SignalR Wiki
c#
Public ActionResult MyControllerMethod()
{
var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.methodInJavascript("hello world");
// or
context.Clients.Group("groupname").methodInJavascript("hello world");
}
vb.net
Public Function MyControllerMethod() As ActionResult
Dim context = GlobalHost.ConnectionManager.GetHubContext(Of MyHub)()
context.Clients.All.methodInJavascript("hello world")
'' or
context.Clients.Group("groupname").methodInJavascript("hello world")
End Function
Update
This code has been updated. Follow http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server for changes.
If you are using DI container
If you are using a DI container to wire up your hubs, get IConnectionManager from your container, and call GetHubContext on that connectionManager.
A:
2018 February, Short and simple solution
For solving this I usually design my hubs in the following way:
public class NewsFeedHub : Hub
{
private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<NewsFeedHub>();
// Call this from JS: hub.client.send(channel, content)
public void Send(string channel, string content)
{
Clients.Group(channel).addMessage(content);
}
// Call this from C#: NewsFeedHub.Static_Send(channel, content)
public static void Static_Send(string channel, string content)
{
hubContext.Clients.Group(channel).addMessage(content);
}
}
So it's easy to call from Javascript and from back-end code as well. The two methods are resulting in the same event at the client.
A:
update 2012: This answer is old, too! SignalR's public API is in constant flux, it seems. Tim B James has the new, proper API usage as of July 2012.
update 2019 Don't use this answer anymore. New versions of SignalR that work on AspNetCore should refer to the accepted answer by Tim B James, or other up-voted answers. I'm leaving this answer here for history's sake.
The currently accepted answer from Mike is old, and no longer works with the latest version of SignalR.
Here's an updated version that shows how to post a message to a hub from an MVC controller action:
public ActionResult MyControllerMethod()
{
// Important: .Resolve is an extension method inside SignalR.Infrastructure namespace.
var connectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
var clients = connectionManager.GetClients<MyHub>();
// Broadcast to all clients.
clients.MethodOnTheJavascript("Good news!");
// Broadcast only to clients in a group.
clients["someGroupName"].MethodOnTheJavascript("Hello, some group!");
// Broadcast only to a particular client.
clients["someConnectionId"].MethodOnTheJavascript("Hello, particular client!");
}
|
[
"hinduism.stackexchange",
"0000028668.txt"
] | Q:
Anyone know significance of 18 in path to God?
We have Mahabharata lasting upto - 18 days
Bhagavad Gita - 18 chapters
Puranas - 18 Puranas
Ayyapan - 18 steps
Siddhas - primarily 18 siddhars
Is there a significance in 18? Probably 18 steps we need to take towards supreme Godhead?
A:
Numbers 18, 108, 1008, 10008 are all multiples of 9 which is a mystic
number. All multiples of 9 added together ultimately become number 9.
This can be verified (16x9=144; 1+4+4=9). The mystic number 9 is
arrived as follows: The universe is constituted of the three factors -
time, space and causation. The universe is constituted of the three
Gunas (ingredients) - sattva, rajas and tamas. The universe is
constituted of the three functions - creation, preservation and
destruction. This three times three making nine has made nine a mystic
number. The number nine exhausts the definition of the phenomenal
universe.
Twice nine or eighteen makes the Mahabharata scheme complete. The
eighteen Parvas define in detail the career of man on earth. The
eighteen chapters in the Gita make Yoga philosophy complete. The
eighteen day war makes the warrior's exploits complete. Eighteen are
the divisions of the armies of the contending parties -Pandavas and
Kauravas with one having seven and the other eleven divisions. Thus
all the available human forces mobilized were eighteen in number.
The Mahabharata is thus an exposition of the human possibilities and
achievements graded into eighteen, the first multiple of nine. The
higher multiples of nine signify further ranging into divine regions.
REF:Swami Chidbhavananda in his commentary on the Gitas
|
[
"stackoverflow",
"0002450695.txt"
] | Q:
SQL Server concurrency and generated sequence
I need a sequence of numbers for an application, and I am hoping to leverage the abilities of SQL Server to do it. I have created the following table and procedure (in SQL Server 2005):
CREATE TABLE sequences (
seq_name varchar(50) NOT NULL,
seq_value int NOT NULL
)
CREATE PROCEDURE nextval
@seq_name varchar(50)
AS
BEGIN
DECLARE @seq_value INT
SET @seq_value = -1
UPDATE sequences
SET @seq_value = seq_value = seq_value + 1
WHERE seq_name = @seq_name
RETURN @seq_value
END
I am a little concerned that without locking the table/row another request could happen concurrently and end up returning the same number to another thread or client. This would be very bad obviously. Is this design safe in this regard? Is there something I can add that would add the necessary locking to make it safe?
Note: I am aware of IDENTITY inserts in SQL Server - and that is not what I am looking for this in particular case. Specifically, I don't want to be inserting/deleting rows. This is basically to have a central table that manages the sequential number generator for a bunch of sequences.
A:
The UPDATE will lock the row exclusively so your concurrency concerns are not founded. But use of @variable assignment in UPDATE statements is relying on undefined behavior. It's true, it will work, but rather rely on defined behavior: use the OUTPUT clause.
CREATE PROCEDURE nextval
@seq_name varchar(50)
, @seq_value INT output
AS
BEGIN
DECLARE @ot TABLE (seq_value INT)
UPDATE sequences
SET seq_value = seq_value + 1
OUTPUT INSERTED.seq_value INTO @ot
WHERE seq_name = @seq_name
SELECT @seq_value = seq_value FROM @ot;
END
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.