source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0049811773.txt"
] | Q:
Xamarin Forms Android AppCompatActivity Toolbar background color is not changing
In my Xamarin Forms Android Project I need to change the ToolBar Title color and background color I have tried with many workarounds suggested in Google but unfortunately I am unable to find the correct solution to me
What I Need is
What I am getting Now is
by using below codes
MainActivity.cs
[Activity(Label = "Sample.Droid", Icon = "@mipmap/icon_launcher", Theme = "@style/MyTheme")]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
styles.xml
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<style name="MyTheme" parent="MyTheme.Base">
</style>
<style name="MyTheme.Base" parent="Theme.AppCompat.NoActionBar">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="colorPrimary">#cc66ff</item>
<item name="colorPrimaryDark">#1976D2</item>
<item name="colorAccent">#FF4081</item>
</style>
Toolbar.axml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#cc66ff"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
What I have tried
I have tried to change the android:background in Toolbar.xaml but it doesn't have any impact on it;it is always displaying Dark background in Toolbar
and also I tried with this below code too in MainActivity.cs this hides the title in the Toolbar
var toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
anyone please guide me to resolve this issue and make me get what I need Thanks in advance
A:
In you app class (PCL), add these to change the back button's color:
NavigationPage naviPage = new NavigationPage( new App13.MainPage());
MainPage = naviPage;
naviPage.BarBackgroundColor = Color.FromHex("#cc66ff");
I have made a demo for you.
Update:
From here, like @MarlonRibeiro has said, you can use drawerArrowStyle to change the back button's color to white(I have updated my project on github):
<style name="MainTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="@style/Widget.AppCompat.DrawerArrowToggle">
<item name="color">#FFFFFF</item>
</style>
|
[
"stackoverflow",
"0031402582.txt"
] | Q:
Splitting an array into x arrays
I have an array:
arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I want to split arr1 into x slices, where each slice is as full and equal as possible.
arr2 = arr1.foo(3)
# => [1, 2, 3, 4][5, 6, 7][8, 9, 10]
each_slice does the opposite of what I want, separating the array into groups of x elements instead.
arr2 = arr1.each_slice(3)
# => [1, 2, 3][4, 5, 6][7, 8, 9][10]
If possible, I want to do this without using rails-specific methods like in_groups.
A:
class Array
def in_groups(n)
len, rem = count.divmod(n)
(0...n).map { | i | (i < rem) ? self[(len+1) * i, len + 1] : self[len * i + rem, len] }
end
end
A:
Another approach:
def in_groups(array, n)
a = array.dup
n.downto(1).map { |i| a.pop(a.size / i) }.reverse
end
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
in_groups(arr, 1) #=> [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
in_groups(arr, 2) #=> [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
in_groups(arr, 3) #=> [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
in_groups(arr, 4) #=> [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10]]
in_groups(arr, 5) #=> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
A:
You could use recursion:
def in_groups(arr, n)
return [arr] if n == 1
len = arr.size/n
[arr[0,len]].concat in_groups(arr[len..-1], n-1)
end
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
in_groups(arr, 1) #=> [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
in_groups(arr, 2) #=> [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
in_groups(arr, 3) #=> [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
in_groups(arr, 4) #=> [[1, 2], [3, 4], [5, 6, 7], [8, 9, 10]]
in_groups(arr, 5) #=> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
in_groups(arr, 9) #=> [[1], [2], [3], [4], [5], [6], [7], [8], [9, 10]]
in_groups(arr, 10) #=> [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
in_groups(arr, 11) #=> [[], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
Edit 1: For largest groups first, tack on .reverse or replace the antepenultimate line with:
len = (arr.size.to_f/n).ceil
Edit 2: the following is a slight variant of @undur's answer, possibly easier to follow for those with brain types "B" and "C":
class Array
def in_groups(n)
size_small, nbr_large = count.divmod(n)
size_large, nbr_small = size_small+1, n-nbr_large
nbr_for_large = nbr_large * size_large
self[0, nbr_for_large].each_slice(size_large).to_a.concat(
self[nbr_for_large..-1].each_slice(size_small).to_a)
end
end
(1..10).to_a.in_groups(3)
#=> [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
|
[
"stackoverflow",
"0041899282.txt"
] | Q:
Getting matplotlib backends for python 3.6
I installed ipython and matplotlib with pip (9.0.1) under python 3.6 (in Xubuntu 16.04), but no images are showing when I try to plot something.
starting ipython with ipython3 --matplotlib qt gives the following error:
ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5,
or PySide package to be installed, but it was not found.
I tried to install these with pip, but it fails:
$ pip3.6 install PySide
Collecting PySide
Downloading PySide-1.2.4.tar.gz (9.3MB)
100% |████████████████████████████████| 9.3MB 12.8MB/s
Complete output from command python setup.py egg_info:
only these python versions are supported: [(2, 6), (2, 7), (3, 2), (3, 3), (3, 4)]
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-bzzpzy5q/PySide/
$ pip3.6 install PyQT
Collecting PyQT
Could not find a version that satisfies the requirement PyQT (from versions: )
No matching distribution found for PyQT
$ pip3.6 install PyQT4
Collecting PyQT4
Could not find a version that satisfies the requirement PyQT4 (from versions: )
No matching distribution found for PyQT4
$ pip3.6 install PyQT5
Collecting PyQT5
Could not find a version that satisfies the requirement PyQT5 (from versions: )
No matching distribution found for PyQT5
If I try ipython3 --matplotlib gtk, the error is:
ImportError: Gtk* backend requires pygtk to be installed.
But:
$ pip3.6 install pygtk
Collecting pygtk
Could not find a version that satisfies the requirement pygtk (from versions: )
No matching distribution found for pygtk
I seem to understand that something called PyGobject or PyGI replaced pygtk for python 3. And indeed, ipython3 --matplotlib gtk3 results in:
ImportError: Gtk3 backend requires pygobject to be installed.
But:
$ pip3.6 install pygobject
Collecting pygobject
Could not find a version that satisfies the requirement pygobject (from versions: )
No matching distribution found for pygobject
$ pip3.6 install PyGObject
Collecting PyGObject
Could not find a version that satisfies the requirement PyGObject (from versions: )
No matching distribution found for PyGObject
Finally, pip3.6 install PyGI succeeds!
But matplotlib still complains about GTK things not being installed.
What else should I try?
A:
Getting the Tk backend to work
As @ImportanceOfBeingErnest suggested, at least one backend should be available: the Tk based one.
This is true provided the Tk development libraries were available when python was compiled. This was not the case for me (I suppose a pre-compiled python distribution should be Tk-enabled).
When I tried to start ipython with Tk as matplotlib backend (ipython3 --matplotlib tk), I had an error message similar to the following one:
import _tkinter # If this fails your Python may not be configured for Tk
ImportError: No module named _tkinter
A comment to the following answer explains how to get the Tk development libraries in Ubuntu: apt install tk-dev.
After doing this and recompiling python 3.6, an ipython3 --matplotlib tk session started without errors and could display graphics.
Setting the default backend choice
The matplotlib documentation gives an example of configuration file, which I downloaded as ~/.config/matplotlib/matplotlibrc. In that file I set backend : TkAgg.
Other backends
The comments in the above-mentioned configuration file mention the existence of yet another GUI backend based on WX, which, like PyGTK and PyQT, doesn't seem to be installable using pip for python 3.6 as of january 2017 (at least in Linux):
$ pip3.6 install wxpython
Collecting wxpython
Could not find a version that satisfies the requirement wxpython (from versions: )
No matching distribution found for wxpython
|
[
"stackoverflow",
"0039380544.txt"
] | Q:
Is using a HashMap the simplest solution for storing an Object that has an ID?
I have a class in some code, ChatChannel (some unneccessary code omitted), that I'm having a bit of trouble with.
public class ChatChannel {
private static HashMap<String, ChatChannel> registeredChannels = new HashMap<>(); // ChannelID, ChatChannel Object
public static void registerChannel(ChatChannel channel) {
registeredChannels.put(channel.getId(), channel);
}
public static ChatChannel getChannelById(String id) {
return registeredChannels.getOrDefault(id, null);
}
/** The actual ChatChannel item is defined BELOW THIS LINE **/
private String name;
private String id;
public ChatChannel(String name, String id) {
this.name = name;
this.id = id;
}
public static String getId() {
return id;
}
}
Essentially, this class will allow me to separate messages sent by users into "channels." Users may only receive messages in joined channels, and may only send a message to their active channel. Channels should be accessible using their ID (for example, global).
However, my problem is I don't know whether I should use a HashMap or Collection in order to keep the code light and simple. Ideally, I'd like to be able to reference any ChatChannel by its id at any point in the code, so I don't need to constantly pass around these ChatChannels. What, if any, would the performance gain of using HashMap (and external IDs) be? Would it be roughly equal to using a Collection and then iterating through it using my getId() method? If so, which is considered "proper" Java?
A:
To answer the stated question "Should I be using a HashMap or Collection for performance?" — you can't and won't use a "Collection" in this sense because a Collection is an abstract concept, represented in Java as an interface.
A Collection could be a List, or a Map, or a Set, among other things. You can write a method that, for example, accepts (any kind of) a Collection and performs an operation on everything in the Collection, but in your case here you must decide on what kind of collection to use in your implementation.
Since you're retrieving a channel given an identifier String, a Map is a useful choice because it is a key-to-value mapping; you don't have to iterate through it to find the element that has the desired key.
You should generally declare things generically, then instantiate them with a specific implementation. That is, when working with it in your code you don't care what sort of Map it is, just that it's a Map. The actual map that you allocate could be a HashMap or a LinkedHashMap or a TreeMap — since maintaining the insertion order or keeping things sorted doesn't seem to matter here, the plain HashMap appears appropriate.
private static Map<String, ChatChannel> registeredChannels = new HashMap<>();
// ^^^ generic declarat | specific implementation ^^^^
You might also know something about how many channels there are likely to be, or at least the size of the starting set of channels, so you may also consider the initialCapacity and the loadFactor parameters to the constructor, for example
// Allocate with room for 10 initial channels, expand the map size when 75% full
private static Map<String, ChatChannel> registeredChannels =
new HashMap<>(10, 0.75);
|
[
"stackoverflow",
"0062500289.txt"
] | Q:
Get random points at edges of a square in python
Question
Given a plotting window, how does one generate random points at the perimeter of a square (perimeter of the plotting window)?
Background and attempt
I found a similar question with regards to a rectangle in javascript.
I managed to write a program to generate random points within limits but the question is regarding how one could find random points with the condition that they are at the edge of the plot (either x is equal to 5 or -5 ,or y is equal to 5 or -5 in this case).
import numpy as np
import matplotlib.pyplot as plt
# Parameters
n = 6 # number of points
a = 5 # upper bound
b = -5 # lower bound
# Random coordinates [b,a) uniform distributed
coordy = (b - a) * np.random.random_sample((n,)) + a # generate random y
coordx = (b - a) * np.random.random_sample((n,)) + a # generate random x
# Create limits (x,y)=((-5,5),(-5,5))
plt.xlim((b,a))
plt.ylim((b,a))
# Plot points
for i in range(n):
plt.plot(coordx[i],coordy[i],'ro')
plt.show()
Summary
So to summarize, my question is how do I generate random coordinates given that they are at the edge of the plot/canvas. Any advice or help will be appreciated.
A:
Here is what you can do:
from random import choice
import matplotlib.pyplot as plt
from numpy.random import random_sample
n = 6
a = 5
b = -5
plt.xlim((b,a))
plt.ylim((b,a))
for i in range(n):
r = (b - a) * random_sample() + a
random_point = choice([(choice([a,b]), r),(r, choice([a,b]))])
plt.scatter(random_point[0],random_point[1])
plt.show()
Output:
|
[
"stackoverflow",
"0013255127.txt"
] | Q:
Moving and resizing shell with mouse (custom titlebar)
I want to create custom titlebar so I have to write code that will allow user to resize and move shell (I am using SWT), but I have got problem with
a) capturing mouse up
b) resizing
shell.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(final MouseEvent arg0) {
move=true;
oldx=arg0.x;
oldy=arg0.y;
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
while (move) {
shell.setLocation(MouseInfo.getPointerInfo().getLocation().x-oldx, MouseInfo.getPointerInfo().getLocation().y-oldy);
}
}
});
}
@Override
public void mouseUp(MouseEvent arg0) {
move=false;
}
});
Moving shell is working but it doesn't capture mouse up event. Also I don't know how to make resizing. I have tried
shell.setSize(MouseInfo.getPointerInfo().getLocation().x-shell.getBounds().x, MouseInfo.getPointerInfo().getLocation().y-shell.getBounds().y);
but it doesn't work.
A:
Your problem is that you are expecting event #2 (mouseDown) to fire, before event #1 (mouseUp) has finished firing. SWT processes events one at a time. You need #2 to fire to finish operations in #1, which will never happen because #2 will not run. This is a deadlock situation. You would need to move the window as the mouse moves, not based on the mouseDown event. Take a look a this example.
|
[
"ja.stackoverflow",
"0000051099.txt"
] | Q:
LANフラットケーブルのラベリング
ラックサーバのLANフラットケーブルのラベリングをやることになったんですが
みなさんどうしてますか?
直接書き込む?
丸型ケーブル用のラベルを巻く
(実際やってみましたが当然うまく巻けません)
プログラムではなくNWの質問で申し訳ないですが
よろしくお願いします。
A:
ラベル付けをする目的に関しては、ファイバータグが使えると思います。
https://www.sanwa.co.jp/product/syohin.asp?code=CA-TAG111
ラックマウントサーバーのケーブルは、物理的な損傷を防ぐために丈夫なモノをお勧めしたいです。
ケーブルの自重で破損しないよう、ケーブルフィンガー等で横に流すこともご検討ください。
|
[
"stackoverflow",
"0020965830.txt"
] | Q:
Autocomplete Not Working in DurandalJS Modal View
I am using the DurandalJS framework for my PHP web application. I am exploiting DurandalJS framework features for showing modal views.
I have a homepage, home.html which contains a link to a page called, autocomplete.html. When this link is clicked, it opens the autocomplete.html page inside a modal view (a feature provided by DurandalJS).
I am also using the jQuery-UI autocomplete feature to create an autocomplete for a textbox. When a user types anything into the textbox, he gets a list of suggestions based on the characters he enters through the keyboard.
The problem here is that the autocomplete feature works if the autocomplete.html page is run independently in the browser. However, this feature doesn't run when the page is shown in the modal i.e. by running (navigating) the project through the DurandalJS framework.
Can anyone please tell me where exactly am I going wrong? Replies at the earliest will be highly appreciated.
The source code for my project is given below. Please note that the order in which I have provided the source code is in the same order in which the DurandalJS navigation call stack is executed. The flow of my application is, index.php >>> main.js >>> shell.js >>> shell.html >>> home.js >>> home.html >>> autocomplete.js >>> autocomplete.html.
The autocomplete.js >>> autocomplete.html call stack is executed when the user clicks on the Go to Autocomplete link on the home.html page.
main.js
require.config({
paths: {
'text': 'durandal/amd/text'
}
});
define(function (require) {
var app = require('durandal/app'),
viewLocator = require('durandal/viewLocator'),
system = require('durandal/system'),
router = require('durandal/plugins/router');
//>>excludeStart("build", true);
system.debug(true);
//>>excludeEnd("build");
app.start().then(function () {
//The following statement is to help DurandalJS to find files only according to their names.
//Replace 'viewmodels' in the moduleId with 'views' to locate the view.
//Look for partial views in a 'views' folder in the root.
viewLocator.useConvention();
//configure routing
router.useConvention();
router.mapNav("pages/home");
router.mapNav("pages/autocomplete");
app.adaptToDevice();
//Show the app by setting the root view model for our application with a transition.
app.setRoot('viewmodels/shell', 'entrance');
});
});
shell.js
define(function (require) {
var router = require('durandal/plugins/router');
return {
router: router,
activate: function () {
return router.activate('pages/home');
}
};
});
shell.html
<br />
<br />
<br />
<br />
<div class="container-fluid page-host">
<!--ko compose: {
model: router.activeItem, //wiring the router
afterCompose: router.afterCompose, //wiring the router
transition:'entrance', //use the 'entrance' transition when switching views
cacheViews:true //telling composition to keep views in the dom, and reuse them (only a good idea with singleton view models)
}--><!--/ko-->
</div>
home.js
// JavaScript Document
//This file loads the respective page's ViewModel (<Page>.js) and displays the View (<page>.html)
define(function (require) {
self.app = require('durandal/app');
return {
movies: ko.observable(),
activate: function() {
var self = this;
//The following code in the function creates a modal view for the autocomplete page
self.viewAutoCompleteModal = function(AutoComplete, element) {
app.showModal("viewmodels/pages/autocomplete");
};
}
};
});
home.html
<div id="applicationHost">
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<div class="container">
<a class="brand">
<span>My application</span>
</a>
</div>
</div>
</div>
</div>
<!--The following lines of code create href links for the My Application pages and directs the DurandalJS to the respective pages. The data-bind attribute calls the view<Page>Modal functions (which create a Modal view) which is defined in the ViewModel (<Page>.js file)-->
<br />
<br />
<a href="#/pages/autocomplete" data-bind="click: viewAutoCompleteModal">Go to Autocomplete</a>
autocomplete.js
// JavaScript Document
define(function (require) {
var router = require('durandal/plugins/router');
var moviesRepository = require("repositories/moviesRepository");
return {
activate: function (context) {
}
};
});
autocomplete.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<title>jQuery-UI Autocomplete Demo</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://localhost/rockontechnologies/Scripts/Script1.10.3/jquery-1.9.1.js"></script>
<script src="http://localhost/rockontechnologies/Scripts/Script1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="modal-footer">
<ul class="btn-group">
<button class="btn" data-bind="click: closeModal">Exit</button>
</ul>
</div>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
For help on DurandalJS, I have referred to:
http://durandaljs.com/
For help on Autocomplete, I have referred to: [http://jqueryui.com/autocomplete/][3]
Thank you in advance.
A:
ive answered a similar question here which will help you.
But your autocomplete.html is wrong and will not work when composed by Durandal. You need to convert that to a durandal style html page.
Add your script tags to your host page. In Hot Towel this is managed by bundles so im not entirely sure where you add these if using PHP.
Remove the HTML, SCRIPT, META etc... Just leave the pure HTML markup.
e.g:
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
Then in your autocomplete.js file, add an attached method or if using Durandal < 2.0.0 you add a viewAttached method.
define(function (require) {
var router = require('durandal/plugins/router');
var moviesRepository = require("repositories/moviesRepository");
return {
activate: function (context) {
},
attached: function (view) {
var $tagInput = $(view).find('#tags');
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$tagInput.autocomplete({
source: availableTags
});
}
};
});
Let me know if you are still having issues and ill be pleased to help.
|
[
"sharepoint.stackexchange",
"0000071958.txt"
] | Q:
Why, on occasion, does executeQueryAsync() fail to execute success OR failure method?
My intent is to dynamically create a grouping of EditControlBlock (List Item Menu) custom actions for two different list view pages.
Upon loading the Active page, all custom actions are destroyed, and only those necessary for the Active view of this particular library are recreated. Meaning, only items marked as active appear in this list view, so I want the custom actions available to be only those relating to an active item.
The same would happen on the Inactive page but only custom actions related to Inactive items would appear in this list.
The issue I'm facing is that quite often, executeQueryAsync fails to run either success or failure functions as the method call suggests it should. The query is executed and the request seems to go off into infinity never to return (I know, I know not quite).
I've verified this erratic through a number of page-reloads. Every time the page reloads the code is executed again, with the desired result to see all the Active custom actions added to the ECB.
About 50% of the time I see all of them. The other 50% of the time I see between 3 and 7 of the items I've attempted to add.
This code is in a script linked to the master page:
function createTendersCustomActions(action) {
var siteUrl = L_Menu_BaseUrl;
var context = new SP.ClientContext.get_current();
this.listRef = context.get_web().get_lists().getByTitle('Tenders');
var collUserCustomAction = listRef.get_userCustomActions();
var oUserCustomAction = collUserCustomAction.add();
oUserCustomAction.set_location('EditControlBlock');
oUserCustomAction.set_sequence(action.sequence);
oUserCustomAction.set_title(action.title);
oUserCustomAction.set_url('javascript:alert(' + action.workflow +')');
oUserCustomAction.update();
context.load(listRef, 'Title' ,'UserCustomActions');
context.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
function onQuerySucceeded() {
console.log('Custom action ' + action.title + ' created for ' + this.listRef.get_title());
}
function onQueryFailed(sender, args) {
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
}
function deleteTendersCustomActions() {
var siteUrl = L_Menu_BaseUrl;
var context = new SP.ClientContext.get_current();
this.listRef = context.get_web().get_lists().getByTitle('Tenders');
this.collUserCustomActions = listRef.get_userCustomActions();
//delete all Custom Actions
collUserCustomActions.clear();
context.load(collUserCustomActions);
context.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
function onQuerySucceeded() {
}
function onQueryFailed(sender, args) {
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
}
var tendersCustomActions_Active =
[
{ "workflow" : "Assign To", "title" : "Assign To", "sequence" : "0" },
{ "workflow" : "Log Check In", "title" : "Log Check In", "sequence" : "1" },
{ "workflow" : "Log Check Out", "title" : "Log Check Out", "sequence" : "2" },
{ "workflow" : "Mark as Issued", "title" : "Issue", "sequence" : "3" },
{ "workflow" : "Mark as Closed", "title" : "Mark as closed", "sequence" : "4" },
{ "workflow" : "Make Inactive", "title" : "Make Inactive", "sequence" : "5" },
{ "workflow" : "Mark as Cancelled", "title" : "Cancel", "sequence" : "6" },
{ "workflow" : "Mark as On Hold", "title" : "Mark as On Hold", "sequence" : "7" },
];
var tendersCustomActions_Inactive =
[
{ "workflow" : "Make Active", "title" : "Assign To", "sequence" : "0" },
];
function addTendersCustomItems_Active() {
for (var i = 0; i < tendersCustomActions_Active.length-1; i = i+1) {
createTendersCustomActions(tendersCustomActions_Active[i]);
}
}
function addTendersCustomItems_Inactive() {
for (var i = 0; i < tendersCustomActions_Inactive.length-1; i = i+1) {
createTendersCustomActions(tendersCustomActions_Inactive[i]);
}
}
And in the webpage in a hidden WebPart; executes every time this particular page loads:
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(deleteTendersCustomActions, "sp.js");
ExecuteOrDelayUntilScriptLoaded(addTendersCustomItems_Active, "sp.js");
</script>
I have read multiple cases of similar sort of behavior and yet I have also heard of others successfully using the SharePoint JavaScript Object Model to execute multiple asynchronous queries without a hitch.
I should let it be known I'm using IE8, the current standard in the organization.
I've been told, by a SharePoint system admin here, that using JavaScript to work with SharePoint objects is unreliable and is not to be trusted.
This might be so, but I would really like to know: What explains this erratic behavior? Is the server configured to throttle the queries coming through the JavaScript object model? Are the requests getting lost within network traffic?
A:
Think about what you're doing: You are deleting and re-provisioning a list custom action, asynchronously, at the same time you are loading a page that will consume that custom action. I would expect unpredictable things to happen. Put this in a production environment with lots of concurrent users, each deleting and re-provisioning custom actions on the list, and you have a "hot mess".
There's a much easier way to accomplish what you're trying to do, and it will be much more functional.
So you have a list, and I'll assume there is a status field which can have values of 'Active' or "Inactive'. You want to call a certain function on Active items (let's call it ActiveFunc() ) and another function on Inactive items ( InactiveFunc() ).
SharePoint has a JavaScript 'hook' that will enable to you to dynamically inject items into the ECB when it is called. Jan Tielens has written an excellent blog series that goes into great detail on this functionality. The posts were written when SharePoint 2007 was still new, but this code works just fine in 2010 and 2013.
You'll want to call a function called Custom_AddListMenuItems (for a doc lib, it's Custom_AddDocLibMenuItems ) ,check which view you are on, and add the right ECB entry (Here we are checking the URL via window.location for the view name):
function Custom_AddListMenuItems(m, ctx) {
if (ctx.ListTitle == 'Tenders' && window.location.href.indexOf('ActiveTenders') > 0) {
CAMOpt(m, "Call Active Func", "javascript:ActiveFunc();", "");
}
if (ctx.ListTitle == 'Tenders' && window.location.href.indexOf('InactiveTenders') > 0) {
CAMOpt(m, "Call Inactive Func", "javascript:InactiveFunc();", "");
}
}
The exact syntax is a little arcane but Jan's posts explain the nuts and bolts of what's going on. So now we have code checking which view we are on and adding the right ECB entry.
But wait - we can do better than that.
Since we are writing JavaScript to dynamically add these entries into the ECB, we can take it a step further and just check the status field itself rather than the view's URL. Doing this we can have the proper functionality in any view no matter what combination of statuses it may contain - even views that haven't been created yet.
To do this just write a simple query to check the status and adjust your code appropriately:
function Custom_AddListMenuItems(m, ctx) {
if (ctx.ListTitle == 'Tenders' ) {
$.ajax({
async: false,
url: L_Menu_BaseUrl + "/_vti_bin/listdata.svc/Tenders(" + currentItemID + ")?$select=StatusValue",
dataType: "json",
success: function(data) {
switch(data.d.StatusValue)
{
case "Active":
CAMOpt(m, "Call Active Func", "javascript:ActiveFunc();", "");
break;
case "Inactive":
CAMOpt(m, "Call Inactive Func", "javascript:InactiveFunc();", "");
break;
default:
//some other status, do nothing
break;
}
},
error: function(data) {
//error, do something
}
});
}
}
A couple of points to clarify here:
I'm using jQuery to call the REST interface to query the current item's status. It's important to set async = false because otherwise the function would return and build the default ECB before your code had a chance to return.
The REST interface treats Choice columns a little funny. My Status column's value was called StatusValue in the web service results. Check ListData.svc in the browser to verify your values.
That currentItemID variable is a SharePoint variable available in ECB code. Jan Tielens goes into more detail on this on his blog.
One last point - NEVER, EVER take JavaScript advice from a system administrator! :)
|
[
"stackoverflow",
"0046501734.txt"
] | Q:
Cant connect to my proxied elasticsearch node
I'm having issues with connecting from my Go client to my es node.
I have elasticsearch behind an nginx proxy that sets basic auth.
All settings are default in ES besides memory.
Via browser it works wonderfully, but not via this client:
https://github.com/olivere/elastic
I read the docs and it says it uses the /_nodes/http api to connect. Now this is probably where I did something wrong because the response from that api looks like this:
{
"_nodes" : {
"total" : 1,
"successful" : 1,
"failed" : 0
},
"cluster_name" : "elasticsearch",
"nodes" : {
"u6TqFjAvRBa3_4FndfKh4w" : {
"name" : "u6TqFjA",
"transport_address" : "127.0.0.1:9300",
"host" : "127.0.0.1",
"ip" : "127.0.0.1",
"version" : "5.6.2",
"build_hash" : "57e20f3",
"roles" : [
"master",
"data",
"ingest"
],
"http" : {
"bound_address" : [
"[::1]:9200",
"127.0.0.1:9200"
],
"publish_address" : "127.0.0.1:9200",
"max_content_length_in_bytes" : 104857600
}
}
}
}
I'm guessing I have to set the IPs to my actual IP/domain (my domain is like es01.somedomain.com)
So how do i correctly configure elastisearch so that my go client can connect?
My config files for nginx look similar to this: https://www.elastic.co/blog/playing-http-tricks-nginx
Edit: I found a temporary solution by setting elastic.SetSniff(false) in the Options for the client, but I think that means I can't scale ES horizontally. So still looking for an alternative.
A:
You are looking for the HTTP options, specifically http.publish_host and http.publish_port, which should be set to the publicly reachable address and port of the Nginx server proxying the ES node.
Note that with Elasticsearch listening on 127.0.0.1:9300 for the transport, you won't be able to form a cluster with nodes on other hosts. The transport can be configured similarly with the transport options.
|
[
"pt.stackoverflow",
"0000198099.txt"
] | Q:
Ordenação de itens com angular
Estou trabalhando em um sistema que requer paginação dos dados, mas antes eu gostaria de ordenar o json que recebo na ordem dos nomes dos usuários.
O JSON está no formato:
[["22","Aiolinhos","23","[email protected]","Administradores","SIM"],["20","Aiorinhos","21","[email protected]","Administradores","SIM"],["6","Aldebas","7","[email protected]","Administradores","SIM"],["12","Caminhus","13","[email protected]","Administradores","SIM"],["18","Ditinho","19","[email protected]","Administradores","SIM"],["3","Dohkinho","3","[email protected]","Administradores","SIM"],["8","Kanonzinho","9","[email protected]","Administradores","SIM"],["14","Milinho","15","[email protected]","Administradores","SIM"],["4","Muzinho","4","[email protected]","Administradores","SIM"],["2","Saguinha","2","[email protected]","Administradores","SIM"],["1","Shakinha","1","[email protected]","Administradores","SIM"],["16","Shionzinho","17","[email protected]","Administradores","SIM"],["10","Shurinha","11","[email protected]","Administradores","SIM"]]
E os trechos em html+angular que criei para mostrar esses dados para o usuário são:
<div class="container">
<div class="jumbotron">
<div class="row">
<div class="col-xs-12 text-right">
<button type="button" class="btn btn-secondary" ng-click="create()">Novo</button>
</div>
</div>
<table class="table table-hover">
<thead>
<tr>
<td ng-repeat="header in headers track by $index">{{header}}</td>
<td ng-if="headers.length">Editar / Remover</td>
</tr>
</thead>
<tr ng-repeat="row in rows | orderBy:order track by $index">
<td ng-repeat="cell in row track by $index" ng-if="!$first">{{cell}}</td>
<td ng-if="row.length"><button type="button" class="btn btn-secondary glyphicon glyphicon-pencil" ng-click="edit(row)"></button>
<button type="button" class="btn btn-danger glyphicon glyphicon-trash" ng-click="delete(row)"></button></td>
</tr>
</table>
</div>
</div>
controller:function($scope,$routeParams,$location,crudservice){
$scope.headers = [];
$scope.rows = [[]];
$scope.modelPath = $routeParams.model;
$scope.order = 0;
crudservice.model = {};
crudservice.listModel($routeParams.model).then(function(response){
if(response.data.status == 1){
var data = response.data;
console.log(JSON.parse(data.headers));
console.log(JSON.parse(data.rows));
$scope.headers = JSON.parse(data.headers);
$scope.rows = JSON.parse(data.rows);
}
});
Mas ocorre que a tabela não mostra algumas linhas, além das células Nome, E-mail, Grupo, Ativos e Editar/Remover estarem em locais que não deveriam:
Alguma suposição do porquê isso estar acontecendo?
A:
Todos os itens que não estão aparecendo possuem os valores da primeira e da terceira coluna iguais:
["3","Dohkinho","3","[email protected]","Administradores","SIM"],
["4","Muzinho","4","[email protected]","Administradores","SIM"],
["2","Saguinha","2","[email protected]","Administradores","SIM"],
["1","Shakinha","1","[email protected]","Administradores","SIM"]
Entretanto seu código deveria ser funcional, como demonstrado no exemplo (funcional) a seguir:
angular.module('myApp', [])
.controller('myController', function($scope){
$scope.rows = [["22","Aiolinhos","23","[email protected]","Administradores","SIM"],["20","Aiorinhos","21","[email protected]","Administradores","SIM"],["6","Aldebas","7","[email protected]","Administradores","SIM"],["12","Caminhus","13","[email protected]","Administradores","SIM"],["18","Ditinho","19","[email protected]","Administradores","SIM"],["3","Dohkinho","3","[email protected]","Administradores","SIM"],["8","Kanonzinho","9","[email protected]","Administradores","SIM"],["14","Milinho","15","[email protected]","Administradores","SIM"],["4","Muzinho","4","[email protected]","Administradores","SIM"],["2","Saguinha","2","[email protected]","Administradores","SIM"],["1","Shakinha","1","[email protected]","Administradores","SIM"],["16","Shionzinho","17","[email protected]","Administradores","SIM"],["10","Shurinha","11","[email protected]","Administradores","SIM"]];
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div ng-app="myApp">
<div ng-controller="myController">
<div class="container">
<div class="jumbotron">
<table class="table table-hover">
<tr ng-repeat="row in rows | orderBy:order track by $index">
<td ng-repeat="cell in row track by $index" ng-if="!$first">{{cell}}</td>
<td ng-if="row.length">
<button type="button" class="btn btn-secondary glyphicon glyphicon-pencil" ng-click="edit(row)"></button>
<button type="button" class="btn btn-danger glyphicon glyphicon-trash" ng-click="delete(row)"></button>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
A minha suspeita é que a sua fonte esteja de alguma forma manipulando o array de arrays, criando um map inválido.
|
[
"math.stackexchange",
"0001992296.txt"
] | Q:
Proving that $\mathbb{R}/ \sim $ is homeomorphic to $S^1$
The relation $\sim$ is as follows: $x \sim y$ if $x-y \in \mathbb{Z}$ and I can't really figure out what are the classes of equivalence from that relation. Help please.
A:
The class of $x$ is simply $\xi (x) = [x]=x+\mathbb Z = \{ x+n : n\in\mathbb Z\}$. The map $\xi : {\Bbb R} \mapsto {\Bbb R}/{\Bbb Z}$ associates to $x$ its class. Perhaps more important, a set $A$ in the quotient is open iff $\xi^{-1}(A)$ is open in ${\Bbb R}$.
You may then show that $\cos$ and $\sin$ (of the reals) gives rise to a well-defined continuous bijective function $$\phi\in {\Bbb R}/{\Bbb Z}\mapsto (\cos 2\pi \phi,\sin 2\pi \phi) \in S^1\subset {\Bbb R}^2$$
which provides the wanted homeomorphism.
A:
Hint: Remember $S^1 = \{\exp{i 2\pi s} : s \in [0, 1)\}$
Define $\Theta : S^1 \rightarrow \mathbb{R}/\sim$ as $\Theta(\exp{i2\pi s}) = \{s + k : k \in \mathbb{Z}\}$ and show that $\Theta$ is an homeomorphism.
|
[
"stackoverflow",
"0020982084.txt"
] | Q:
Output image src with SimpleXML hidden characters
I'm using SimpleXML to read nodes, and I echo out the image file name. Using foreach, I print them out:
assets/project_Guide2Big1.jpg
assets/project_Guide2Big2.jpg
assets/project_Guide2Big3.jpg
assets/project_Guide2Big4.jpg
assets/project_Guide2Big5.jpg
I inserted these values into my img tags, but the images don't appear except for the first one.
I copy "assets/project_Guide2Big1.jpg" into the browser. I see the image, but when I copy "assets/project_Guide2Big2.jpg", the address changes to this
asset/%E2%80%8BprojectGuide2Big2.jpg.
It looks like some urlencoding(?). I tried to decode, but my images still aren't working. This is so wierd.
Were does the %E2%80%8B come from?
A:
That looks suspiciously like a UTF-8 character sequence representing some Unicode character which you didn't expect to be there.
Using this online converter, we can see that the sequence of UTF-8 bytes E2 80 8B represent the Unicode codepoint U+200B, which is a "Zero Width Space".
So somehow, your source XML includes an invisible character after the slash. When echoed to the screen, it is completely invisible - even when viewing source, since the source is still just text. But when you try to load the URL, that character is outside the valid range for URLs, so gets automatically encoded by the browser.
You might be wondering what the point of a zero-width space is, but consider automatic word-wrap functions - they may look for a space to break on, but a URL contains no spaces. So inserting a zero-width space makes the text look the same, but allows it to wrap at that specific point. Another character useful for this is the "soft hyphen", which has the beautifully apt entity name of ­ - as a friend of mine put it, "the soft hyphen is shy, and may not appear". :)
|
[
"stackoverflow",
"0053522743.txt"
] | Q:
Different member function definition according to compile-time condition
As per this answer, I've been using
template <typename T,
typename = typename enable_if<bool_verfier<T>()>::type> >
classMember(const T& arg);
As the function signature for several class members, where bool_verifier<T>() is a templated function that asserts that a particular class T fulfills certain requirements, with return type constexpr bool. This ensures a particular overload of classMember(const T& arg) is only used for particular argument types, but it is not possible to do this when there are multiple overloads with the same prototype/argument signature, because the compiler won't allow it:
// ...
template <typename T, typename = typename enable_if<bool_verfier<T>()>::type> >
classMember(const T& arg);
template <typename T, typename = typename enable_if<!(bool_verfier<T>())>::type>>
classMember(const T& arg);
// ...
which causes the following compilation error:
‘template<class T, class> void myClass::classMember<T>(const T&)’
cannot be overloaded with
‘template<class T, class> void std::myClass<T>::classMember(const T&)’
If I need classMember to have different definitions according to whether or not bool_verifier<T>() returns true, what would be the correct syntax/member declaration? Alternatively, is there a way to call bool_verifier<T> from an #if precompiler conditional statement?
A:
Alternatively, is there a way to call bool_verifier<T> from an #if precompiler conditional statement?
Nope. The preprocessor runs before anything else, and doesn't have knowledge of C++ at all.
You probably need to disambiguate between the two overloads with an extra template parameter (or by changing where enable_if appears), as default template parameter values are not part of the signature. The following works for me:
struct foo
{
template <typename T, typename = std::enable_if_t<bool_verifier<T>{}>>
void a();
template <typename T, typename = std::enable_if_t<!bool_verifier<T>{}>, typename = void>
void a();
};
live godbolt.org link
|
[
"stackoverflow",
"0052324897.txt"
] | Q:
How I can catch output of gitlab-runner in bash
Why when I write into terminal
#!/bin/bash
out=`gitlab-runner list`
echo "list: ${out}"
out variable is still empty and output of the command always display in terminal? Install Gitlab Runner
How I can catch this output?
A:
gitlab-runner list outputs the list on stderr, thus you would not catch it as output to stdout.
see Bash how do you capture stderr to a variable?
and change your script to:
#!/bin/bash
out="$(gitlab-runner list 2>&1)"
echo "list: ${out}"
|
[
"stackoverflow",
"0011021420.txt"
] | Q:
VB.NET Brackets () {} [] <>
Can someone please fill in the blanks for me, including a brief description of use and perhaps a code snippet? I'm well aware of the top two in particular, but a little hazy on the last one especially:
() - Used for calling a function, object instantiation, passing parameters, etc.
{} - Used for defining and adding elements to arrays or sets.
[] - Used for forcing an object to be treated as a type rather than keyword.
<> - Used for... ?
For Example, I see stuff like this all the time, but still not quite sure what the brackets means...
<TemplateContainer(GetType(TemplateItem))> _
Public Property MessageTemplate As ITemplate
A:
VB.net uses parentheses for, among other things, arithmetic groupings and function parameters (both of which use parentheses in C#), as well as array subscripts and default-property parameters (both of which use brackets in C#), (indexers), etc. It also uses (Of ... ) to enclose a list of types (which would be enclosed in < ... > in C#, with no "Of" keyword.
Braces are used for array or set initialization expressions, and are also used when defining a generic type with multiple constraints (e.g. (Of Foo As {IEnumerable, IDisposable, Class})). Note that the latter usage is only permitted in constraints; it is alas not possible to e.g. Dim MyThing As {IEnumerable, IDisposable, Class}).
Braces are now also used for the New With {} construct:
Dim p = New Person With {.Name = "John Smith", .Age = 27}
Dim anon = New With {.Name = "Jack Smythe", .Age = 23}
Square brackets are used to enclose identifiers whose spelling would match that of a reserved word. For example, if a class defined a method called Not (perhaps the class was written in a language without a keyword Not), one could use such a method within VB by enclosing its name in square brackets (e.g. someVariable = [Not](5)). In the absence of the square brackets, the above expression would set someVariable to -6 (the result of applying the vb.net Not operator to the value 5).
Angle brackets, as noted elsewhere, are used for attributes. Note that in many cases, attributes are placed on the line above the thing they affect (so as to avoid pushing the affected variable past the right edge of the screen). In older versions of vb, such usage requires the use of a line-continuation mark (trailing underscore).
Angle brackets are also used for XML Literals and XML Axis Properties:
Dim xml = <simpleTag><anotherTag>text</anotherTag></simpleTag>
Console.WriteLine(xml.<anotherTag>.First.Value)
A:
In this case it's used for the Attribute declaration. It can also be used in XML Literals as follows:
<TestMethod>
Public Sub ThisIsATest()
If 1 <> 0 Then
Dim foo = <root>
<child>this is some XML</child>
</root>
End If
End Sub
A:
In VB.Net, <> is used to enclose Attributes.
|
[
"stackoverflow",
"0058439692.txt"
] | Q:
Convert physical addresses to Geographic locations Latitude and Longitude
I Have read a CSV file (that have addresses of customers) and assign the data into DataFrame table.
Description of the csv file (or the DataFrame table)
DataFrame contains several rows and 5 columns
Database example
Address1 Address3 Post_Code City_Name Full_Address
10000009 37 RUE DE LA GARE L-7535 MERSCH 37 RUE DE LA GARE,L-7535, MERSCH
10000009 37 RUE DE LA GARE L-7535 MERSCH 37 RUE DE LA GARE,L-7535, MERSCH
10000009 37 RUE DE LA GARE L-7535 MERSCH 37 RUE DE LA GARE,L-7535, MERSCH
10001998 RUE EDWARD STEICHEN L-1855 LUXEMBOURG RUE EDWARD STEICHEN,L-1855,LUXEMBOURG
11000051 9 RUE DU BRILL L-3898 FOETZ 9 RUE DU BRILL,L-3898 ,FOETZ
I have written a code (Geocode with Python) inorder to convert physical addresses to Geographic locations → Latitude and Longitude, but the code keep showing several errors
So far I have written this code :
The code is
import pandas as pd
from geopy.geocoders import Nominatim
from geopy.extra.rate_limiter import RateLimiter
# Read the CSV, by the way the csv file contains 43 columns
ERP_Data = pd.read_csv("test.csv")
# Extracting the address information into a new DataFrame
Address_info= ERP_Data[['Address1','Address3','Post_Code','City_Name']].copy()
# Adding a new column called (Full_Address) that concatenate address columns into one
# for example Karlaplan 13,115 20,STOCKHOLM,Stockholms län, Sweden
Address_info['Full_Address'] = Address_info[Address_info.columns[1:]].apply(
lambda x: ','.join(x.dropna().astype(str)), axis=1)
locator = Nominatim(user_agent="myGeocoder") # holds the Geocoding service, Nominatim
# 1 - conveneint function to delay between geocoding calls
geocode = RateLimiter(locator.geocode, min_delay_seconds=1)
# 2- create location column
Address_info['location'] = Address_info['Full_Address'].apply(geocode)
# 3 - create longitude, laatitude and altitude from location column (returns tuple)
Address_info['point'] = Address_info['location'].apply(lambda loc: tuple(loc.point) if loc else None)
# 4 - split point column into latitude, longitude and altitude columns
Address_info[['latitude', 'longitude', 'altitude']] = pd.DataFrame(Address_info['point'].tolist(), index=Address_info.index)
# using Folium to map out the points we created
folium_map = folium.Map(location=[49.61167,6.13], zoom_start=12,)
An example of the full output error is :
RateLimiter caught an error, retrying (0/2 tries). Called with (*('44 AVENUE JOHN FITZGERALD KENNEDY,L-1855,LUXEMBOURG',), **{}).
Traceback (most recent call last):
File "e:\Anaconda3\lib\urllib\request.py", line 1317, in do_open
encode_chunked=req.has_header('Transfer-encoding'))
File "e:\Anaconda3\lib\http\client.py", line 1244, in request
self._send_request(method, url, body, headers, encode_chunked)
File "e:\Anaconda3\lib\http\client.py", line 1290, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "e:\Anaconda3\lib\http\client.py", line 1239, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "e:\Anaconda3\lib\http\client.py", line 1026, in _send_output
self.send(msg)
File "e:\Anaconda3\lib\http\client.py", line 966, in send
self.connect()
File "e:\Anaconda3\lib\http\client.py", line 1414, in connect
server_hostname=server_hostname)
File "e:\Anaconda3\lib\ssl.py", line 423, in wrap_socket
session=session
File "e:\Anaconda3\lib\ssl.py", line 870, in _create
self.do_handshake()
File "e:\Anaconda3\lib\ssl.py", line 1139, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1059: The handshake operation timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "e:\Anaconda3\lib\site-packages\geopy\geocoders\base.py", line 355, in _call_geocoder
page = requester(req, timeout=timeout, **kwargs)
File "e:\Anaconda3\lib\urllib\request.py", line 525, in open
response = self._open(req, data)
File "e:\Anaconda3\lib\urllib\request.py", line 543, in _open
'_open', req)
File "e:\Anaconda3\lib\urllib\request.py", line 503, in _call_chain
result = func(*args)
File "e:\Anaconda3\lib\urllib\request.py", line 1360, in https_open
context=self._context, check_hostname=self._check_hostname)
File "e:\Anaconda3\lib\urllib\request.py", line 1319, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error _ssl.c:1059: The handshake operation timed out>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "e:\Anaconda3\lib\site-packages\geopy\extra\rate_limiter.py", line 126, in __call__
return self.func(*args, **kwargs)
File "e:\Anaconda3\lib\site-packages\geopy\geocoders\osm.py", line 387, in geocode
self._call_geocoder(url, timeout=timeout), exactly_one
File "e:\Anaconda3\lib\site-packages\geopy\geocoders\base.py", line 378, in _call_geocoder
raise GeocoderTimedOut('Service timed out')
geopy.exc.GeocoderTimedOut: Service timed out
Expected output is
Address1 Address3 Post_Code City_Name Full_Address Latitude Longitude
10000009 37 RUE DE LA GARE L-7535 MERSCH 37 RUE DE LA GARE,L-7535, MERSCH 49.7508296 6.1085476
10000009 37 RUE DE LA GARE L-7535 MERSCH 37 RUE DE LA GARE,L-7535, MERSCH 49.7508296 6.1085476
10000009 37 RUE DE LA GARE L-7535 MERSCH 37 RUE DE LA GARE,L-7535, MERSCH 49.7508296 6.1085476
10001998 RUE EDWARD STEICHEN L-1855 LUXEMBOURG RUE EDWARD STEICHEN,L-1855,LUXEMBOURG 49.6302147 6.1713374
11000051 9 RUE DU BRILL L-3898 FOETZ 9 RUE DU BRILL,L-3898 ,FOETZ 49.5217917 6.0101385
A:
I've updated your code:
Added: Address_info = Address_info.apply(lambda x: x.str.strip(), axis=1)
Removes whitespace before and after str
Added a function with try-except, to handle the lookup
from geopy.exc import GeocoderTimedOut, GeocoderQuotaExceeded
import time
ERP_Data = pd.read_csv("test.csv")
# Extracting the address information into a new DataFrame
Address_info= ERP_Data[['Address1','Address3','Post_Code','City_Name']].copy()
# Clean existing whitespace from the ends of the strings
Address_info = Address_info.apply(lambda x: x.str.strip(), axis=1) # ← added
# Adding a new column called (Full_Address) that concatenate address columns into one
# for example Karlaplan 13,115 20,STOCKHOLM,Stockholms län, Sweden
Address_info['Full_Address'] = Address_info[Address_info.columns[1:]].apply(lambda x: ','.join(x.dropna().astype(str)), axis=1)
locator = Nominatim(user_agent="myGeocoder") # holds the Geocoding service, Nominatim
# 1 - convenient function to delay between geocoding calls
# geocode = RateLimiter(locator.geocode, min_delay_seconds=1)
def geocode_me(location):
time.sleep(1.1)
try:
return locator.geocode(location)
except (GeocoderTimedOut, GeocoderQuotaExceeded) as e:
if GeocoderQuotaExceeded:
print(e)
else:
print(f'Location not found: {e}')
return None
# 2- create location column
Address_info['location'] = Address_info['Full_Address'].apply(lambda x: geocode_me(x)) # ← note the change here
# 3 - create longitude, latitude and altitude from location column (returns tuple)
Address_info['point'] = Address_info['location'].apply(lambda loc: tuple(loc.point) if loc else None)
# 4 - split point column into latitude, longitude and altitude columns
Address_info[['latitude', 'longitude', 'altitude']] = pd.DataFrame(Address_info['point'].tolist(), index=Address_info.index)
Output:
Address1 Address3 Post_Code City_Name Full_Address location point latitude longitude altitude
10000009 37 RUE DE LA GARE L-7535 MERSCH 37 RUE DE LA GARE,L-7535,MERSCH (Rue de la Gare, Mersch, Canton Mersch, 7535, Lëtzebuerg, (49.7508296, 6.1085476)) (49.7508296, 6.1085476, 0.0) 49.750830 6.108548 0.0
10000009 37 RUE DE LA GARE L-7535 MERSCH 37 RUE DE LA GARE,L-7535,MERSCH (Rue de la Gare, Mersch, Canton Mersch, 7535, Lëtzebuerg, (49.7508296, 6.1085476)) (49.7508296, 6.1085476, 0.0) 49.750830 6.108548 0.0
10000009 37 RUE DE LA GARE L-7535 MERSCH 37 RUE DE LA GARE,L-7535,MERSCH (Rue de la Gare, Mersch, Canton Mersch, 7535, Lëtzebuerg, (49.7508296, 6.1085476)) (49.7508296, 6.1085476, 0.0) 49.750830 6.108548 0.0
10001998 RUE EDWARD STEICHEN L-1855 LUXEMBOURG RUE EDWARD STEICHEN,L-1855,LUXEMBOURG (Rue Edward Steichen, Grünewald, Weimershof, Neudorf-Weimershof, Luxembourg, Canton Luxembourg, 2540, Lëtzebuerg, (49.6302147, 6.1713374)) (49.6302147, 6.1713374, 0.0) 49.630215 6.171337 0.0
11000051 9 RUE DU BRILL L-3898 FOETZ 9 RUE DU BRILL,L-3898,FOETZ (Rue du Brill, Mondercange, Canton Esch-sur-Alzette, 3898, Luxembourg, (49.5217917, 6.0101385)) (49.5217917, 6.0101385, 0.0) 49.521792 6.010139 0.0
10000052 3 RUE DU PUITS ROMAIN L-8070 BERTRANGE 3 RUE DU PUITS ROMAIN,L-8070,BERTRANGE (Rue du Puits Romain, Z.A. Bourmicht, Bertrange, Canton Luxembourg, 8070, Lëtzebuerg, (49.6084531, 6.0771901)) (49.6084531, 6.0771901, 0.0) 49.608453 6.077190 0.0
Note & Additional Resources:
The output includes the address that caused the error in your TraceBack
RateLimiter caught an error, retrying (0/2 tries). Called with (*('3 RUE DU PUITS ROMAIN ,L-8070 ,BERTRANGE ',)
Note all the extra whitespace in the address. I've added a line of code to remove whitespace from the beginning and end of the strings
GeocoderTimedOut, a real pain?
Geopy: catch timeout error
Final:
The final result is the service times out because of HTTP Error 429: Too Many Requests for the day.
Review Nominatim Usage Policy
Suggestion: Use a different Geocoder
|
[
"stackoverflow",
"0049257650.txt"
] | Q:
How check if Vue is in development mode?
When I run my Vue app, the console shows:
You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html
So now I want to check if Vue is in development from inside my templates by using:
console.log("mode is " + process.env.NODE_ENV)
But that only logs undefined
Is there a different way to find the NODE_ENV in Vue?
My webpack config has this part:
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
Perhaps relevant: I use typescript, so I included this type declaration:
declare var process: {
env: {
NODE_ENV: string
}
}
A:
Webpack is used for almost all of my Vue projects, so I check to see if webpackHotUpdate is present.
if (webpackHotUpdate) {
console.log('In Dev Mode');
}
It's present in the window object if the webpack dev server is running.
A:
If you started with vue-cli (default webpack) then this should work:
connection: process.env.NODE_ENV === 'development'
? 'ws://localhost:5000'
: 'wss://myawsomeproject.org'
A:
Absolutely the most simple solution is to check for the window.location from you Vue component. That would look something like this:
if (window.location.href === 'YOUR DEVELOPMENT URL') {
//preset form values here
}
|
[
"stackoverflow",
"0012225035.txt"
] | Q:
How can I embed a MySQL database server inside a C# application?
Possible Duplicate:
Self-contained database?
I wish to create a C# application that embeds a MySQL database server. The data need to be stored in files and I need to access it inside the application, make queries and save results back to disk.
How might I approach this?
A:
An Open Source ADO.NET provider SQLLite is the best Option for your scenario. Refer to this: SQLLite
SQLite database engine is an ADO.NET 2.0/3.5 provider all rolled into a single mixed mode assembly.
System.Data.SQLite is the original SQLLite database engine.
It is self-contained, serverless, zero-configuration, transactional SQL database engine.
If you already have MySql database installed then you can embed it using MySql Connector. For detailed information you can go through this: Connecting to MySQL Database using C# and .NET
|
[
"gis.stackexchange",
"0000346244.txt"
] | Q:
How to disconnect a feature from Geometric Network using Python ArcGIS
I am creating a Python add-in for ArcMap, which on click, will disconnect the feature from Geometric Network and then delete it from the feature class. But ArcPy doesn't have any method to disconnect the feature. So, I looked in ArcObjects and there they have method disconnect in INetworkFeature. I am a Python developer and don't know ArcObjects ecosystem. How can I do this?
Assumption of this add-in is that Geometric Network is added to ArcMap, the editor is started and you have selected the feature which you want to disconnect and delete from feature class.
A:
Turns out it is quite an easy task in ArcObject. Type cast the feature to network feature and you are done. Below is the code for reference.
# get current ArcMap application pointer
pApp = NewObj(esriFramework.AppRef, esriFramework.IApplication)
# get selected features from ArcMap
pFeatSel = CType(pApp.Document, esriArcMapUI.IMxDocument).FocusMap.FeatureSelection
# create editor to start operation
pID = NewObj(esriSystem.UID, esriSystem.IUID)
pID.Value = CLSID(esriEditor.Editor)
pExt = pApp.FindExtensionByCLSID(pID)
pEditor = CType(pExt, esriEditor.IEditor)
pEditor.StartOperation()
# get the pointer to first selected feature (in my case only one is selected on map, .Next() will give you next selected feature)
pEnumFeat = CType(pFeatSel, esriGeoDatabase.IEnumFeature)
pEnumFeat.Reset()
pFeat = pEnumFeat.Next()
# cast the feature to network feature as Disconnect is INetworkFeature method
netFeat = CType(pFeat, esriGeoDatabase.INetworkFeature)
netFeat.Disconnect() # call disconnect
# stop edit operation
pEditor.StopOperation('')
I am not an ArcObjects developer so this solution might not be the best suited or bug free.
|
[
"stackoverflow",
"0021352302.txt"
] | Q:
Socket Data issue between Android and iOS
I'm facing a bit of an issue trying to communicate with 2 devices through a socket (UDP, but not the issue here...)
One device is Android, the other is iOS.
Here's the Android code to create the Data I'm sending :
int part = 1;
int num = -1;
ByteBuffer bb = ByteBuffer.allocate(20);
bb.order(ByteOrder.nativeOrder());
bb.putChar('R');
bb.putInt(part);
bb.putInt(num);
bb.flip();
byte[] toSend = new byte[bb.remaining()]; // bb.remaining() = 10
bb.get(toSend);
send(toSend);
On iOS, here's the code I use to parse the data I get from the socket
char *sData = (char*)[data bytes];
if (sData[0] == 'R') {
sData += sizeof(char);
int part = 0;
memcpy(&part, sData, sizeof(int));
sData += sizeof(int);
int num = 0;
memcpy(&num, sData, sizeof(int));
}
The data I get is :
part = 256
num = -256
The weird thing is if I change value from the Android device I get :
part = 0 & num = -1 ---> part = 0 & num = -256
part = 1 & num = -1 ---> part = 256 & num = -256
part = 2 & num = -1 ---> part = 512 & num = -256
part = 3 & num = -1 ---> part = 768 & num = -256
As you can see, the value are correct, they are just multiplied by 256, and I can't understand why...
To avoid compatibility issue between Android and iOS (32/64) I avoided the long type, because on
Android long = 8
iOS 32b long = 4
iOS 64b long = 8
Does anybody can see why it is multiplying my value by 256 ?
EDIT 1 :
From iOS to iOS data transfer, it is working fine, so my guess is that the bug is coming from Android.
A:
In Java, your buffer contains this:
char 2 bytes | int 4 bytes | int 4 bytes
Since iOS stores char in one byte, you are reading it as if it were:
char 1 byte | int 4 bytes | int 4 bytes
This also explains why iOS -> iOS works.
[Edit]
To fix, you could use byte in Java.
byte b = (byte) 'R';
Like this:
ByteBuffer bb = ByteBuffer.allocate(20);
bb.order(ByteOrder.nativeOrder());
bb.putByte((byte)'R');
bb.putInt(part);
bb.putInt(num);
bb.flip();
Note though that casting char to byte "loses" the high 8 bits so this will only work for ASCII chars.
|
[
"stackoverflow",
"0052249215.txt"
] | Q:
How to get the grouped product ID from a linked product in woocommerce
I have a grouped product product-1 , which has many linked products:
-product-1 (grouped product)
|__ product-2 (simple or variable product)
|__ product-3 (simple or
variable product)
I want to get the ID of product-1 using the ID of product-2
A:
You can't get the product Id of a particular grouped product through one of its children product ID, as each children can be in many different grouped products.
The only data that define the children products IDS for a grouped product is located in wp_postmeta table arround the meta_key _children as an array of children product IDs.
Now if the children product ID which you want to use to retrieve the parent grouped product ID is only the children of one unique grouped product, you can use the following SQL query embedded in a function:
function get_parent_grouped_id( $children_id ){
global $wpdb;
$results = $wpdb->get_col("SELECT post_id FROM {$wpdb->prefix}postmeta
WHERE meta_key = '_children' AND meta_value LIKE '%$children_id%'");
// Will only return one product Id or false if there is zero or many
return sizeof($results) == 1 ? reset($results) : false;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
USAGE
Here below 738 is one the children Ids from a grouped product. It can also be a dynamic value through a variable…
$parent_grouped_id = get_parent_grouped_id( 738 );
ADDITION - Get all grouped products using a WC_Product_Query:
1) Array of grouped products Objects:
$grouped_products = wc_get_products( array( 'limit' => -1, 'type' => 'grouped' ) );
1) Array of grouped products IDS only:
$ids = wc_get_products( array( 'limit' => -1, 'type' => 'grouped', 'return' => 'ids' ) );
|
[
"math.stackexchange",
"0001295211.txt"
] | Q:
The Fourier transform of functions with compact support is differentiable.
1) How can I prove that if $f(x)$ is a continous function with compact support (let's say $f(x)=0$ $\forall x\in B(0,R)^c$), then its Fourier transform $\hat{f}(\xi)$ is differentiable?
2) Is there any counter example that $\hat{f}(\xi)$ is differentiable if $f\in C^0 (\mathbb{R})$ (without necessarely having a compact support)?
Thank you!
A:
If $f\in C_c(\Bbb R)$, then you can show that $\hat f$ is differentiable by definition and dominated convergence theorem.
If we want to build $f\in C(\Bbb R)$ such that $\hat f$ is not differentiable, we can use the fact that for even functions $f = \hat{\hat f}$ (up to a multiplicative constant). Now take, for example, $\hat f = \mathbf 1_{[-1,1]}(x)$. This function is not differentiable on $\Bbb R$. Its Fourier transform $\hat{\hat f}$ (and hence Fourier inverse $f$) is continuous (easy to check by definition).
edit
Suppose that $supp (f)\subset [-R,R]$ and $\sup_{x\in[-R,R]} |f(x)|=M$.
$$\frac{\hat f(\xi+h)-\hat f(\xi)}{h} -\int_{-R}^Rixf(x) \exp(ix\xi) dx =\int_{-R}^Rf(x) \exp(ix\xi)\left(\frac{\exp(ixh)-1}{h}-ix\right)dx.$$
The factor $\frac{\exp(ixh)-1}{h}-ix$ converges uniformly to zero on $[-R,R]$ as $h\to 0$, hence
$$\left|\frac{\hat f(\xi+h)-\hat f(\xi)}{h} -\int_{-R}^Rixf(x) \exp(ix\xi) dx\right| \le \left|\int_{-R}^Rf(x) \exp(ix\xi)\left(\frac{\exp(ixh)-1}{h}-ix\right)dx \right|$$
$$\le 2RM\sup_{x\in[-R,R]}\left |\frac{\exp(ixh)-1}{h}-ix\right| \to 0\mbox { as } h\to 0.$$
|
[
"stackoverflow",
"0052596220.txt"
] | Q:
Eliminate null values in mysql
I have this kind of table:
Column 1 | Column 2 | Column 3 | Column 4
----------------------------------------
Value 1 | null | null | null
null | Value 2 | null | null
null | null | Value 3 | null
null | null | null | Value 4
I want to eliminate null values. I want it to be like this:
Column 1 | Column 2 | Column 3 | Column 4
----------------------------------------
Value 1 | Value 2 | Value 3 | Value 4
Any help will be much appreciated. Thanks.
A:
It seems you want aggregation :
select max(col1), max(col2), max(col3), max(col4)
from table t;
Assuming you have a supportive column if so, then you can do :
select col, max(col1), max(col2), max(col3), max(col4)
from table t
group by col;
|
[
"stackoverflow",
"0003087366.txt"
] | Q:
Displaying activity with custom animation
I have a widget which starts an activity when it is clicked. I'd like to have some kind of fancy animation to display this activity, rather than the standard scroll-from-right of Android. I'm having problems setting it, though. This is what I have:
slide_top_to_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator">
<translate android:fromYDelta="-100%" android:toXDelta="0" android:duration="100" />
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="50" />
</set>
...which is referenced in anim.xml
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
android:delay="50%"
android:animation="@anim/slide_top_to_bottom" />
But then where do I reference it from? I've tried both the base element of the activity I want to slide in, and the activitiy's entry in the manifest, both times with
android:layoutAnimation="@+anim/anim"
I might be doing this all wrong. Any help is much appreciated!
A:
You can create a custom Theme with a reference to your own animation and apply it to your Activity in your manifest file.
I was successful in applying a custom animation for a floating window using the following style definition. You might be able to do something similar if you set the parent of your style to be "@android:style/Animation.Activity"
Look at the following files for further details on what you can override.
https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/styles.xml
https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/themes.xml
Here's my a portion of my styles.xml and manifest.xml
styles.xml
<style name="MyTheme" parent="@android:style/Theme.Panel">
<item name="android:windowNoTitle">true</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:windowAnimationStyle">@style/MyAnimation.Window</item>
</style>
<!-- Animations -->
<style name="MyAnimation" />
<!-- Animations for a non-full-screen window or activity. -->
<style name="MyAnimation.Window" parent="@android:style/Animation.Dialog">
<item name="android:windowEnterAnimation">@anim/grow_from_middle</item>
<item name="android:windowExitAnimation">@anim/shrink_to_middle</item>
</style>
Manifest.xml
<activity
android:name="com.me.activity.MyActivity"
android:label="@string/display_name"
android:theme="@style/MyTheme">
</activity>
A:
startActivity(intent);
overridePendingTransition(R.anim.slide_top_to_bottom, R.anim.hold);
Check this link: overridePendingTransition method
Edit:
To Achieve the Animation for the Views. You have use the startAnimation Method like below
view.startAnimation(AnimationUtils.loadAnimation(
WidgetActivity.this,R.anim.slide_top_to_bottom));
Check this link:
|
[
"stackoverflow",
"0017865217.txt"
] | Q:
Getting correct html form action attribute with JSF + Spring 3
I am trying to mix Spring MVC with Java Server Faces. I have a Spring 3.2 @Controller class, which returns a ModelAndView that is resolved to a JSF view. That view contains a <h:form> tag. The problem that I am having is that, on the rendered HTML, the form action attribute combines the original request URL with the name to resolve the view, creating a strange meaningless URL to which the form is POSTed. What I want is just the view name, without the original request URL.
Here is my controller class (org.my.test.MainController):
@Controller
@RequestMapping("/items")
public class MainController
{
@RequestMapping(value="/{itemId}", method=RequestMethod.GET)
public ModelAndView retrieveItem( @PathVariable long itemId ) {
/* Retrieve item */
ModelAndView mav = new ModelAndView();
mav.addObject ("itemName", "A retrieved item");
mav.addObject ("itemId", itemId);
mav.setViewName ("/items");
return mav;
}
}
Here is my JSF template (/items.xhtml)
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Edit item</title>
</h:head>
<h:body>
<h:form>
<h3>Edit item</h3>
<p>
Item name: <h:inputText name="itemName" value="#{itemName}" />
</p>
<p>
Item id: <h:inputText name="itemId" value="#{itemId}" />
</p>
<p>
<h:commandButton value="Submit" />
</p>
</h:form>
</h:body>
</html>
When I request the page http://localhost:8081/items/12345, what is served is this:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Edit item</title></head><body><form id="j_id_6" name="j_id_6" method="post" action="/items/12345/items.xhtml" enctype="application/x-www-form-urlencoded">
<h3>Edit item</h3>
<p>
Item name: <input id="j_id_6:j_id_8" name="j_id_6:j_id_8" type="text" value="A retrieved item" />
</p>
<p>
Item id: <input id="j_id_6:j_id_a" name="j_id_6:j_id_a" type="text" value="12345" />
</p>
<p><input id="j_id_6:j_id_c" name="j_id_6:j_id_c" type="submit" value="Submit" />
</p><input type="hidden" name="j_id_6_SUBMIT" value="1" /><input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="oyc7wGGKZrPGinPPmrv9PmTDy0GBlI3c+pjWpdK0KuY69faJ" /></form></body>
</html>
My problem is the bit that says action="/items/12345/items.xhtml" What I want is action="/items" or action="/items.xhtml"
My question has two parts: why is my setup combining the request URL with the view ID like this, and how do I make it stop?
Here is web.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Minimal JSF + Spring test</display-name>
<!-- - Location of the XML file that defines the root application context.
- Applied by ContextLoaderListener. -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/spring/application-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
</listener>
<!-- - Servlet that dispatches request to registered handlers (Controller
implementations). -->
<servlet>
<servlet-name>ui</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/ui-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ui</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Just here so the JSF implementation can initialize, *not* used at runtime -->
<servlet>
<servlet-name>faces</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Just here so the JSF implementation can initialize -->
<servlet-mapping>
<servlet-name>faces</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
</web-app>
Here is Spring config ui-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:faces="http://www.springframework.org/schema/faces"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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
http://www.springframework.org/schema/faces http://www.springframework.org/schema/faces/spring-faces-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:component-scan base-package="org.my.test" />
<mvc:annotation-driven />
<bean id="faceletsViewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.faces.mvc.JsfView" />
<property name="prefix" value="" />
<property name="suffix" value=".xhtml" />
</bean>
</beans>
Here is main Spring config application-config.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:faces="http://www.springframework.org/schema/faces"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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
http://www.springframework.org/schema/faces http://www.springframework.org/schema/faces/spring-faces-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:component-scan base-package="org.my.test" />
</beans>
And here is faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
This is all running in embedded Jetty 9.0.4. I have tried two different JSF implementations, Apache My-Faces 2.1.11 and Mojarra 2.2.1, both with the same effect. Spring version is 3.2.3.
A:
Changing the url-mapping in web.xml from "/" to "/*" corrected the problem.
Everything is in fact behaving according to the Servlet spec (Java Servlet Specification Version 3.0 Rev a, Section 12.2, page 116):
A string beginning with a / character and ending with a /* suffix is used for path mapping.
...
A string containing only the / character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
(Thank you to this post on Coderanch: http://www.coderanch.com/t/366340/Servlets/java/servlet-mapping-url-pattern)
(Java Servlet 3.0 spec available at http://download.oracle.com/otndocs/jcp/servlet-3.0-mrel-eval-oth-JSpec/)
|
[
"stackoverflow",
"0052673551.txt"
] | Q:
Take random item from list in "for" loop
I have a list containing a random element from another list
var test = listOf<String>("Blah blah " + list1.shuffled().take(1)[0] + " blah blah")
A bigger list biglist, containing a smaller lists like test
Then, there is a "for" loop, in wich i am filling stringbuilder with random lists from biglist
var list3 = listOf<String>("Something something1","Something something2")
var list2 = listOf<String>("item1", "item2", "item3", "item4")
var list = listOf<String>("Blah " + list2.shuffled().take(1)[0] + " blah")
var sb = StringBuilder ()
var biglist = listOf<String>()
if (...) biglist += list
if (...) biglist += list3.get(0)
if (...) biglist += list3.get(1)
for (i in 0 until 4) {
sb.append(biglist.shuffled().take(1)[0] + "\n")
i + 1
}
println(sb)
So, on output, i want to see something like this:
Something something1
Blah item2 blah
Something something2
Blah item4 blah
Instead i am having this:
Something something1
Blah item2 blah
Something something2
Blah item2 blah
My problem is, that in sb, test list will every time contain the same item, randomly picked at the beggining of code from list1
I have kind of solved it, putting creation of the biglist INTO the for loop (and clearing it after sb.append), but it just make my code looks even shittier (and slower?)
Maybe there is a better solution to this?
Thanks
A:
Do your evaluation of list inside the loop:
var list3 = listOf("Something something1", "Something something2")
var list2 = listOf("item1", "item2", "item3", "item4")
var sb = StringBuilder()
(0..4).forEach {
var list = listOf("Blah ${list2.shuffled().first()} blah")
var biglist = listOf<String>()
biglist += list // left out the if statements for simplicity
biglist += list3.get(0)
biglist += list3.get(1)
sb.append(biglist.shuffled().first() + "\n")
}
println(sb)
A few notes:
use a range and forEach to do it multiple times (since you don't need the loop variable i anyways
take(1)[0] can be replaced by first()
use a string template to build the element of list
you don't need the type parameter for list2 and list3, the type (String) can be inferred from the list's elements
if your list becomes big calling shuffle will be a waste of resources, especially because you are only interested in one random element of that list. Use this extension function instead: fun List<*>.randomElement() = this[Random().nextInt(this.size)]
|
[
"electronics.stackexchange",
"0000182486.txt"
] | Q:
Can I connect various LED fixtures to one driver?
Let's say my driver is 32W (700mA). I should be easily able to connect 5 x 5W 350/700mA LEDs right?
My idea is to use driver with DALI interface and control 5 LED's using just one address.
A:
That should be possible, but you won't be able to control each of the LED but just all of the connected ones at once.
When connecting multiple LEDs to one driver make sure to understand the limits of the driver and the way it works. The rated wattage of the driver must be higher than the sum of the wattage of the LEDs (like you figured out, 32W driver > 25W LEDs). There may be a limit on the voltage as well, so some driver will be able to put out say 700mA for a voltage range of 24V-45V, so the permittable wattage range is 16.8W to 32W. In that case you have to add the forward voltages of your LEDs and check that it is in the range of the driver.
If you have a constant current controller you must connect the LEDs in series and each of the LED must be rated for the said constant current. Don't parallel two 350mA LEDs to get a virtual 700mA LED. (the current might not be evenly shared and that might damage the LED in the long run)
If your driver is constant voltage output (that makes it not really a LED driver but just a voltage source imho) you have to parallel the LEDs with a current limiter in series for each LED (don't use a single resistor to limit the total current).
|
[
"stackoverflow",
"0021308907.txt"
] | Q:
How to pass the SelectedValue from a DropDownList as a query string in a LinkButton with/without using CodeBehind in ASP.net C#
I've been fiddling with this issue for quite sometime now where I am not able to pass the value of a DropDownList to a Link Button. The Eval doesn't seem to work at all.
Here's the code:
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl='<%# string.Format(~/DataView.aspx?id=) + Eval(DropDownList1.SelectedValue) %>' Text="New ECRS"></asp:LinkButton>
When I run the above code, the link button doesn't function and there's no page redirection. But I see in many forums that people have given the above code as the answer. Am I doing something wrong? Thanks in advance :)
A:
You could use Response.Redirect in the code behind instead:
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton_Click" Text="New ECRS"></asp:LinkButton>
And in your code-behind:
void LinkButton_Click(Object sender, EventArgs
{
Response.Redirect("~/DataView.aspx?id=" + DropDownList1.SelectedValue, true);
}
|
[
"stackoverflow",
"0005135978.txt"
] | Q:
When to alloc/init an ivar, and when not to
All,
In Apple's sample code "DateCell"
http://developer.apple.com/library/ios/#samplecode/DateCell/Introduction/Intro.html
the ivar "pickerView" is declared in MyTableViewController.h like this:
@interface MyTableViewController : UITableViewController
{
@private
UIDatePicker *pickerView;
UIBarButtonItem *doneButton; // this button appears only when the date picker is open
NSArray *dataArray;
NSDateFormatter *dateFormatter;
}
@property (nonatomic, retain) IBOutlet UIDatePicker *pickerView;
...
It is synthesized in the class file MyTableViewController.m like this:
@implementation MyTableViewController
@synthesize pickerView, doneButton, dataArray, dateFormatter;
...
When this app runs, I can insert NSLog(@"%@",pickerView) into ViewDidLoad and see that, sure enough, the ivar pickerView is real and has a value. Nowhere, though, does this class alloc/init pickerView. And that's the root of the question: how's it getting done if it's not being done explicitly?
Well, I naively copied this stuff to my code into my RootViewController.h and .m files figuring I could do the same, but pickerView stubbornly remains uninitialized (and my NSLog calls return "(nil)" as its value) no matter what I try short of explicitly alloc/initing it. Certainly RootViewController is being instantiated, or the RootView wouldn't be showing up, right? So shouldn't my pickerView be coming along for the ride just as it does for Apple?
So... do I have to manually alloc/init the pickerView instance variable? If so, where's Apple doing it? Or how are they doing it somehow otherwise?
I think I'm missing something very basic here, but I have no idea what it is. I can't see anything in Interface Builder or XCode that looks different between mine and theirs, but I've got tunnel vision at this point and can't see anything clearly anymore.
Thanks,
Bill
A:
The IBOutlet modifier on this line is the key...
@property (nonatomic, retain) IBOutlet UIDatePicker *pickerView;
IBOutlet is a decorator that indicates that the object will be hooked up/connected/initialised when the corresponding xib (Interface Builder) file is loaded. The sample application you're looking up will contain a UITableViewController is a xib which has a connection to a UIPickerView.
You can either go the route of creating your own custom xib file and wire to an instance of UIPickerView or you can manually initialise the picker yourself.
|
[
"apple.stackexchange",
"0000068836.txt"
] | Q:
Where can I download Safari for Windows?
This sounds like an absurd question, I know, but when I go to:
http://www.apple.com/safari/
There isn't a download link! I'm sure it used to be there :-/
Here's what I see:
Scrolling further just has more features. No link!
A:
Safari on Windows is no longer supported by Apple.
Safari 5 (from 2010) is available via Apple's KB. The original page no longer exists, but the EXE is still hosted.
According to 9to5mac, it seems that have Apple decided to stop producing Safari for Windows, so Safari 5 is all that's likely to be available moving forward.
Update: As mentioned at Geek Dashboard, better use a cross-browser testing tool if you just want to test your project UI. With this, you will have the latest version of Safari running right in your favorite browser.
A:
The Windows version was discontinued.
As of 2016-09-29 version 5.34.57.2 is available from Apple here: http://appldnld.apple.com/Safari5/041-5487.20120509.INU8B/SafariSetup.exe
As of 2013-06-14 version 5.1.7 is available from Download.com here:
http://download.cnet.com/Apple-Safari/3000-2356_4-10697481.html?tag=mncol;1
A:
There is no link to Safari for Windows because Apple stopped making it. If you want a copy of Safari for Windows you have to download the installer somewhere, or retrieve it from your backup.
Update: This link still works: SafariSetup.exe
|
[
"stackoverflow",
"0014573424.txt"
] | Q:
C++: Does cout statement makes code slower
I am reading about 3 million rows from a file and inserting them into STL maps. So, inside my while loop where I read each line from the file, I also print to console what row number it is through a simple cout statement. One of my friends recently pointed out that this makes code slower. I was wondering whether it is true and if it is why?
A:
As already mentioned, writing to the terminal is almost definitely going to be slower. Why?
Buffering:
Writing to the terminal uses line buffering* by default. This means the contents of the buffer are transmitted everytime a newline is encountered. When writing to a file, the buffer is flushed only when the buffer becomes full or when you flush the stream manually. This is the main reason for the difference as the number of I/O operations is significantly different.
*: This is true for Unix implementations, but other implementations may be unbuffered (see discussion in comments).
Rendering:
When you write to a terminal, this involves rendering on the screen, and depending on the terminal could involve other operations that can slow your program down (not all terminals are made the same, you might find significant differences in speed by just switching to a different one).
A:
As already mentioned, writing to the terminal is almost definitely going to be slower. Why?
depending on your OS, std::cout may use line buffering - which means each line may be sent to the terminal program separately. When you use std::endl rather than '\n' it definitely flushes the buffer. Writing the data in smaller chunks means extra system calls and rendering efforts that slow things down significantly.
some operating systems / compilers are even slower - for example, Visual C++: https://connect.microsoft.com/VisualStudio/feedback/details/642876/std-wcout-is-ten-times-slower-than-wprintf-performance-bug-in-c-library
terminals displaying output need to make calls to wipe out existing screen content, render the fonts, update the scroll bar, copy the lines into the history/buffer. Especially when they get new content in small pieces, they can't reliably guess how much longer they'd have to wait for some more and are likely to try to update the screen for the little bit they've received: that's costly, and a reason excessive flushing or unbuffered output is slow.
Some terminals offer the option of "jump scrolling" which means if they find they're say 10 pages behind they immediately render the last page and the earlier 9 pages of content never appear on the screen: that can be nice and fast. Still, "jump scrolling" is not always used or wanted, as it means output is never presented to the end users eyes: perhaps the program is meant to print a huge red error message in some case - with jump scrolling there wouldn't even be a flicker of it to catch the user's attention, but without jump scrolling you'd probably notice it.
when I worked for Bloomberg we had a constant stream of log file updates occupying several monitors - at times the displayed output would get several minutes behind; a switch from the default Solaris xterm to rxvt ensured it always kept pace
redirecting output to /dev/null is a good way to see how much your particular terminal is slowing things down
A:
It's almost certainly true. Writing to the terminal is notorious for slowing things down. Run your program and redirect the output to a file and see how much faster it is. Then take out the output statement entirely and measure again. You'll see the behaviour immediately.
Here's a braindead example:
#include <stdio.h>
int main(void)
{
int i;
for (i = 0; i < 10000; i++)
{
printf("Hello, world!\n");
}
return 0;
}
I built this program unoptimized and ran it, once with output to the terminal, and once with output to a file. Results for the terminal output:
real 0m0.026s
user 0m0.003s
sys 0m0.007s
Results for redirected I/O:
real 0m0.003s
user 0m0.001s
sys 0m0.001s
There you go, ~8x faster. And that's for a very small number of prints!
|
[
"stackoverflow",
"0062430480.txt"
] | Q:
Case sensitive option for Pester's -FileContentMatchMultiline in PowerShell
I have a dozen lines or so that need to be consistent across multiple .ps1 files. I was able to get this working using the -FileContentMatchMultiline functionality in Pester but I need the match to be case sensitive. Is there any simple way to do this?
Here is what I have currently:
It "Has all the lines below, but case sensitive" {
Get-ChildItem $directoryOfFilesToCheck | ForEach-Object {
$matchstring = @'
$var1 = Line one blah blah blah
$var2 = Line two blah blah blah
$var3 = Line three blah blah blah
'@
$_ | Should -FileContentMatchMultiline $([regex]::escape($matchString))
}
}
The problem is that it would also match if the files contained:
$var1 = Line one BLAH Blah blAH
$var2 = Line two BLAH Blah blAH
$var3 = Line three BLAH Blah blAH
This is important because in the file there are function calls that are case sensitive because they are used by a program running the script.
A:
Unfortunately it seems Pester doesn't have a FileContentMatchExactlyMultiline assertion at the moment, but looking at how FileContentMatchMultiline works it is this:
$succeeded = [bool] ((& $SafeCommands['Get-Content'] $ActualValue -Delimiter ([char]0)) -match $ExpectedContent)
So it looks like you could simply roll your own equivalent of that by doing this as a workaround:
Describe 'MyTests' {
It "Has all the lines below, but case sensitive" {
$matchstring = @'
$var1 = Line one blah blah blah
$var2 = Line two blah blah blah
$var3 = Line three blah blah blah
'@
Get-ChildItem $directoryOfFilesToCheck | ForEach-Object {
$ActualValue = (Get-Content $_.FullName -Delimiter [char]0)
$ActualValue -cmatch $([regex]::escape($matchstring)) | Should -Be $True
}
}
}
This just switches -match to -cmatch which makes it case sensitive.
Another option would be to use the -MatchExactly assertion having got the file content into $ActualValue as above:
$ActualValue | Should -MatchExactly $([regex]::escape($matchstring))
Contributing a FileContentMatchExactlyMultiline assertion to Pester doesn't seem like it would be that much work based on the above. It would be worth adding an issue for it here: https://github.com/pester/Pester/issues
|
[
"stackoverflow",
"0013717918.txt"
] | Q:
Which of these 2 MySQL DB Schema approaches would be most efficient for retrieval and sorting?
I'm confused as to which of the two db schema approaches I should adopt for the following situation.
I need to store multiple attributes for a website, e.g. page size, word count, category, etc. and where the number of attributes may increase in the future. The purpose is to display this table to the user and he should be able to quickly filter/sort amongst the data (so the table strucuture should support fast querying & sorting). I also want to keep a log of previous data to maintain a timeline of changes. So the two table structure options I've thought of are:
Option A
website_attributes
id, website_id, page_size, word_count, category_id, title_id, ...... (going up to 18 columns and have to keep in mind that there might be a few null values and may also need to add more columns in the future)
website_attributes_change_log
same table strucuture as above with an added column for "change_update_time"
I feel the advantage of this schema is the queries will be easy to write even when some attributes are linked to other tables and also sorting will be simple. The disadvantage I guess will be adding columns later can be problematic with ALTER TABLE taking very long to run on large data tables + there could be many rows with many null columns.
Option B
website_attribute_fields
attribute_id, attribute_name (e.g. page_size), attribute_value_type (e.g. int)
website_attributes
id, website_id, attribute_id, attribute_value, last_update_time
The advantage out here seems to be the flexibility of this approach, in that I can add columns whenever and also I save on storage space. However, as much as I'd like to adopt this approach, I feel that writing queries will be especially complex when needing to display the tables [since I will need to display records for multiple sites at a time and there will also be cross referencing of values with other tables for certain attributes] + sorting the data might be difficult [given that this is not a column based approach].
A sample output of what I'd be looking at would be:
Site-A.com, 232032 bytes, 232 words, PR 4, Real Estate [linked to category table], ..
Site-B.com, ..., ..., ... ,...
And the user needs to be able to sort by all the number based columns, in which case approach B might be difficult.
So I want to know if I'd be doing the right thing by going with Option A or whether there are other better options that I might have not even considered in the first place.
A:
I would recommend using Option A.
You can mitigate the pain of long-running ALTER TABLE by using pt-online-schema-change.
The upcoming MySQL 5.6 supports non-blocking ALTER TABLE operations.
Option B is called Entity-Attribute-Value, or EAV. This breaks rules of relational database design, so it's bound to be awkward to write SQL queries against data in this format. You'll probably regret using it.
I have posted several times on Stack Overflow describing pitfalls of EAV.
Also in my blog: EAV FAIL.
|
[
"math.stackexchange",
"0002524012.txt"
] | Q:
Identifying region from equation
I am trying to identifying the region represented by the equation:
$$x^2-y^2=9$$
I know that if it was a sum then it would be a circle but since it is a difference, how do I go about determining what type of region it is and how do I graph such equation?
A:
Your equation can be rewritten as $\dfrac {x^2}{3^2}-\dfrac {y^2}{3^2}=1$
Equations of the form $\dfrac {(x-h)^2}{a^2}-\dfrac {(y-k)^2}{b^2}=1$ are hyperbolas centered at $(h, k)$.
This is the graph for your equation:
Notice how the vertices of the hyperbola are at $(\pm3, 0)$.
|
[
"stackoverflow",
"0012584277.txt"
] | Q:
Customize UINavigationBar buttons and images by changing size and position
I'm trying to create an app for reading Audio, Video and Doc (PDF).
I chose a design, in which top navigation bar needs to be customized completely.
Like back button and right edit button is much lower than usual and navigation bar background image is much bigger than the usual size (Height = 88 pixel).
I tried a sample project with these spec.
I implemented it in a certain way that :
Navigation bar is set to hidden and placed an imageview with my large sized image. And a custom button is added as subview in the view with navigation controller action.
Code to set image view is as follows :
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 88)];
UIImage *img = [UIImage imageNamed:@"top_bar.png"];
[imgView setImage:img];
[self.view addSubview:imgView];
Code to set back button is as follows :
UIButton *navigationButton = [UIButton buttonWithType:UIButtonTypeCustom];
[navigationButton setImage: [UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
[navigationButton addTarget:view action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
navigationButton.frame = CGRectMake(-2, 23, 75, 55);
[self.view addSubview:navigationButton];
It works fine.
But when I went through some links, I found that there is a chance of appstore rejection if navigation bar is customized.
Can any one suggest me a proper method for doing this or Can I go ahead with this method.
Any help is appreciated. Thanks
A:
This is App Store Review Guidelines. There are no words about rejecting for customizing UINavigationBar. But there is a below phrase.
If your user interface is complex or less than very good, it may be rejected
|
[
"german.stackexchange",
"0000035993.txt"
] | Q:
On the word formation of »beschweren«
I am wondering in which way beschweren ( as in sich beschweren) is derived:
be-schwer-en, where the root is the adj. schwer
or
be- Schwere-n, where the root is the noun Schwere
This question involves elements of both etymology and morphology. My major intent lies in an etymological interpretation of the lexical meaning of sich beschweren. On the other hand, such an etymological approach to lexical meaning is grounded upon morphological facts in this case, so morphological arguments will be as welcome as those of etymology.
A:
Among other features, Canoo.net offers the analysis of the word formation (Wortbildung).
You can find the analysis of the verb beschweren here:
It is your first version:
be + schwer + en
Looking at your second version, Schwere itself is formed by adding a suffix to the adjective (aka suffixation):
schwer + e
Edit to add etymological information:
In Althochdeutsch, swārī (Schwere) is a female noun, which derived from the adjective swār (schwer).
The latter one derived from Proto-Germanic *swēraz.
DWDS lists the etymologic development of beschweren and states that it belongs to the adjective schwer:
beschweren Vb. ‘belasten’,
ahd. biswāren ‘bedrücken, belasten’ (10. Jh.),
mhd. beswæren ‘bedrücken, belästigen, betrüben’
gehört wie das gleichbed. Simplex ahd. swāren (8. Jh.) zu dem unter ↗schwer (s. d.) behandelten Adjektiv.
|
[
"stackoverflow",
"0054303741.txt"
] | Q:
Unexpected keyword argument 'verbose' : scipy curve_fit
I am trying to use the simple curve_fit function in scipy.optimize package. The following is a command for fitting a curve to the gaussian function, but I want to see the progress as it fits, so I use verbose = 2 in curve_fit.
poptb, pcov = curve_fit(gaussian,cno,bkg[350:650],p0=[1000,100,bkg_peak1,3000],verbose=2)
Somehow, everytime I get this following error,
TypeError: leastsq() got an unexpected keyword argument 'verbose'
A:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html
scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, check_finite=True, bounds=(-inf, inf), method=None, jac=None, **kwargs)[source]
As you can see, there is no 'verbose' parameter in v1.2.0
|
[
"stackoverflow",
"0015691126.txt"
] | Q:
When are setValue and setSubmittedValue called on UIComponent?
If I correctly combined the information contained in BalusC's great 2006 post http://balusc.blogspot.ch/2006/09/debug-jsf-lifecycle.html with Optimus Prime's even earlier post http://cagataycivici.wordpress.com/2005/12/28/jsf_component_s_value_local/ I get the following:
My understanding:
During the APPLY_REQUEST_VALUES phase,
the input value is set to a submittedValue property of the UI component (e.g. inputComponent.setSubmittedValue("test")).
During the PROCESS_VALIDATIONS phase,
the same values are read from the submittedValue property (presumably inputComponent.getSubmittedValue()) and used for conversion, if necessary.
If the conversion was successful or skipped, the result is set to a value property of the component (e.g. inputComponent.setValue("test")).
Also, the submittedValue is erased again immediately (e.g. inputComponent.setSubmittedValue(null))
the (converted) value is read from the value property of the UI component (presumably inputComponent.getValue()) and validated.
after validation, the backing bean/model's stored value is read (e.g. myBean.getInputValue()) and compared with the newly converted and validated value. If different, the valueChangeListener method(s) will be called.
During the UPDATE_MODEL_VALUES phase,
the newly converted and validated value is finally stored in the backing bean's property field (e.g. myBean.setInputValue("test")).
Questions:
Is this correct?
Is there something missing for a full understanding of what goes on between the POST and the saving of the input value in the backing bean?
With immediate="true" on the Input Component, are we merely shifting these events to the APPLY_REQUEST_VALUES phase or do we change more than just the timing/order of events?
A:
Almost correct. The component's local value is only set when conversion and validation is successful. After that, the submitted value is set to null. You can find the entire process of the validations phase in a rather self-documenting way in the UIInput#validate() method (line numbers are conform JSF 2.1 API):
934 public void validate(FacesContext context) {
935
936 if (context == null) {
937 throw new NullPointerException();
938 }
939
940 // Submitted value == null means "the component was not submitted
941 // at all".
942 Object submittedValue = getSubmittedValue();
943 if (submittedValue == null) {
944 return;
945 }
946
947 // If non-null, an instanceof String, and we're configured to treat
948 // zero-length Strings as null:
949 // call setSubmittedValue(null)
950 if ((considerEmptyStringNull(context)
951 && submittedValue instanceof String
952 && ((String) submittedValue).length() == 0)) {
953 setSubmittedValue(null);
954 submittedValue = null;
955 }
956
957 Object newValue = null;
958
959 try {
960 newValue = getConvertedValue(context, submittedValue);
961 }
962 catch (ConverterException ce) {
963 addConversionErrorMessage(context, ce);
964 setValid(false);
965 }
966
967 validateValue(context, newValue);
968
969 // If our value is valid, store the new value, erase the
970 // "submitted" value, and emit a ValueChangeEvent if appropriate
971 if (isValid()) {
972 Object previous = getValue();
973 setValue(newValue);
974 setSubmittedValue(null);
975 if (compareValues(previous, newValue)) {
976 queueEvent(new ValueChangeEvent(this, previous, newValue));
977 }
978 }
979
980 }
As to the immediate attribute on the UIInput component, yes this merely shifts the validation to the apply request values phase. See also the source code of UIInput#processDecodes() and UIInput#processValidators(), there's a check on UIInput#isImmediate().
|
[
"stackoverflow",
"0055951507.txt"
] | Q:
How do I group stacked bars in ggplot2 and modify colors for certain values?
Using ggplot2 I am trying to create a grouped AND stacked barchart without using faceting. I want to avoid faceting, because I need to facet on years once I have a grouped and stacked barchart for the variables provided in the example.
This is the best solution so far:
df <- data.frame("industry"=c("A","A", "B", "B", "C", "C",
"A","A", "B", "B", "C", "C"),
"value"=c(4,6,7,1, 5,9,8,3, 5,5,6,7),
"woman"=c(1,0,1,0,1,0,1,0,1,0,1,0),
"disabled"=c(1,1,1,1,1,1,0,0,0,0,0,0))
ggplot(df,aes(paste(industry,disabled),value))+
geom_col(aes(fill=factor(woman)))+
coord_flip()
This is basically what I want (see link above), but the bars should be grouped within each industry, using just one label for industry for both values of disabled. No label needed for disabled. The disabled=0 bars should have a faded color compared to the disabled=1 bars.
The intention of the chart is to display the distribution of employment across industries for the disabled population, compared to the general population (faded) and to show gender proportions for each population. (Values in example just for illustration).
A:
Try this:
library(ggplot2)
ggplot(df, aes(interaction(disabled, industry), value, alpha = factor(woman))) +
geom_col(aes(fill = factor(woman))) +
scale_alpha_manual(values = c(0.5, 1)) +
scale_x_discrete(labels = c(0, 1, 0, 1, 0, 1)) +
annotate("text", label = "A", x = 1.5, y = -2) +
annotate("text", label = "B", x = 3.5, y = -2) +
annotate("text", label = "C", x = 5.5, y = -2) +
coord_cartesian(ylim = c(0, 15), clip = "off", expand = FALSE) +
coord_flip(ylim = c(0, 15), clip = "off", expand = TRUE) +
theme(axis.title.y = element_blank())
We are manually specifying that alpha values should vary by factor(woman) and setting the level-specific alpha values using scale_alpha_manual(). We set your subgroup 0,1 labels manually with scale_x_discrete. We are using annotate() to place your group labels, which can be placed outside of the plotting area by using coord_cartesian() with clip = "off".
|
[
"ru.stackoverflow",
"0000512115.txt"
] | Q:
Зачем в JavaScript использовать паттерн singleton?
Разбираюсь с паттернами. Нашёл в интернете, как сделать на JavaScript конструктор, который бы реализовывал паттерн singleton. Но ведь, как я понимаю, в отличие от многих ООП языков, в JavaScript можно создавать объекты, не описывая классы (конструкторы), а просто создать через фигурные скобочки. Получается, можно всегда, когда в JavaScript нужен singleton, писать не конструктор его реализующий, а просто создавать глобальный объект, и пользоваться им, присваивая его другим переменным. Подскажите, пожалуйста, есть ли в этом недостатки в сравнении с созданием конструктора, реализующего singleton?
A:
Формально, эти самые 'фигурные скобочки' тоже создаются через конструктор new Object, как и примитивы через обёртки.
В пространстве JS, где всё непостоянно и специфично (во всяком случае было когда-то), этот паттерн не очень-то нужен.
Сейчас, когда JS вырос из песочницы браузеров и занимает внушительную нишу, он может использовать Singleton для взрослых целей, где после инициализации менять ничего не нужно: одно подключение к БД, один объект пользователя/сессии и пр.
Впрочем, с новыми возможностями (Object.seal, Object.preventExtensions, Object.freeze), этот паттерн опять же не нужен - всё решено изящнее и в духе языка (ИМХО).
|
[
"stackoverflow",
"0006659826.txt"
] | Q:
how to create dropdown from a hash in rails 3
In rails 3, how to create a Dropdown from hash
I have following code in my User class
class User
... other codes
key :gender, Integer # i use mongo db
class << self
def genders()
genders = {
'1' => 'Male',
'2' => 'Female',
'3' => 'Secret'
}
end
end
end
In the user form, i am trying to create a gender dropdown list
<%= f.collection_select nil, :gender, User.genders, :key, :value %>
but it complain
undefined method `merge' for :value:Symbol
So what is the proper way to create the dropdown?
Thanks
A:
This should work:
<%= f.collection_select :gender, User.genders, :first, :last %>
Edit: Explanations:
collection_select will call each on the object you give (User.genders here) and the two methods (first and last here) on each object. It's roughly equivalent to something like this:
User.genders.each do |object|
output << "<option value=#{object.first.inspect}>#{h object.last}</option>"
end
When you call each on a Hash, it yields an Array of two values (the key and the value). These values can be retreived with the first and last methods.
|
[
"es.stackoverflow",
"0000182110.txt"
] | Q:
Sacar número y porcentaje en una gráfica de highcharts
Estoy haciendo una gráfica combinada.
Estoy atorado en cómo representar la línea en 2 valores, tanto en número como en porcentaje. No entiendo si la misma Highcharts realiza los cálculos o debo añadir una serie o nodo de data adicional para poder representar. Sería una regla de 3 para sacar el porcentaje.
La formula sería
100 - ( (llamadas atendidas * 100) / llamadas recibidas );
No entiendo dónde poner o enviar un arreglo ya con esa información, pero cómo renderizo ambos valores, abandono en valor y en porcentaje
Highcharts.chart('container', {
title: {
text: 'Inbound'
},
xAxis: {
categories: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'junio']
},
labels: {
},
series: [{
type: 'column',
name: 'Llamadas Recibidas',
data: [7128,5067,5816,6005,6569,7260]
}, {
type: 'column',
name: 'Llamadas Atendidas',
data: [5664,4820,5456,5401,5846,5503]
}, {
type: 'column',
name: 'Llamadas Abandonadas',
data: [1463,159,360,603,722,1757]
}, {
type: 'line',
name: 'Abandono',
data: [1463,159,360,603,722,1757],
marker: {
lineWidth: 2,
lineColor: Highcharts.getOptions().colors[3],
fillColor: 'white'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y}</b> ({point.percentage:.1f}%)<br/>'
},
}, ]
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
A:
Si tienes la opcion de manipular los datos, puedes hacerlo asi:
var recibidas = [7128,5067,5816,6005,6569,7260];
var atendidas = [5664,4820,5456,5401,5846,5503];
Highcharts.chart('container', {
title: {
text: 'Inbound'
},
xAxis: {
categories: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'junio']
},
labels: {
},
series: [{
type: 'column',
name: 'Llamadas Recibidas',
data: recibidas
}, {
type: 'column',
name: 'Llamadas Atendidas',
data: atendidas
}, {
type: 'column',
name: 'Llamadas Abandonadas',
data: [1463,159,360,603,722,1757]
}, {
type: 'line',
name: 'Abandono',
data: [1463,159,360,603,722,1757],
marker: {
lineWidth: 2,
lineColor: Highcharts.getOptions().colors[3],
fillColor: 'white'
}
}, ],
tooltip: {
formatter: function() {
if (this.series.name == 'Abandono') {
var index = this.series.data.indexOf( this.point );
var percentage = 100 - (atendidas[index] * 100) / recibidas[index];
return this.series.name + '<b>' + this.point.y + '</b><br>' + percentage.toFixed(2) + '%'
} else {
return this.series.name + '<b>' + this.point.y + '</b>'
}
}
},
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
|
[
"stackoverflow",
"0039050271.txt"
] | Q:
How to prevent Service from getting destroyed
I have a Service that tracks the location of user, in a time I get the location of user though of GoogleApiClient.
It Happen some times Service stop, depend of internet or model phone the Service stop sending location to webservice. It seems like it was destroyed.
How can I prevent this?
public class LocationService extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG = "LocationService";
public long UPDATE_MILLISECONDS_DEFAULT = 180000;
private boolean currentlyProcessingLocation = false;
private LocationRequest locationRequest;
private GoogleApiClient googleApiClient;
@Override
public void onCreate() {
Log.d(TAG,"Location service create");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// if we are currently trying to get a location and the alarm manager has called this again,
// no need to start processing a new location.
if (!currentlyProcessingLocation) {
currentlyProcessingLocation = true;
startTracking();
}
return START_NOT_STICKY;
}
private void startTracking() {
Log.d(TAG, "startTracking");
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (!googleApiClient.isConnected() || !googleApiClient.isConnecting()) {
googleApiClient.connect();
}
} else {
Log.e(TAG, "unable to connect to google play services.");
}
}
protected void sendLocationToServer(Location location) {
// here I call my webservice and send location
Log.d(TAG, "Update to Server location");
}
@Override
public void onDestroy() {
Log.d(TAG,"Destroy service");
stopLocationUpdates();
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onLocationChanged(Location location) {
sendLocationToServer(location);
}
public void stopLocationUpdates() {
if (googleApiClient != null && googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
/**
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
@Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected");
locationRequest = LocationRequest.create();
locationRequest.setInterval(UPDATE_MILLISECONDS_DEFAULT); // milliseconds for default
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//locationRequest.setFastestInterval(1000); // the fastest rate in milliseconds at which your app can handle location updates
LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, this);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "onConnectionFailed");
stopLocationUpdates();
stopSelf();
}
@Override
public void onConnectionSuspended(int i) {
Log.e(TAG, "GoogleApiClient connection has been suspend");
}
}
A:
You're returning START_NOT_STICKY from onStartCommand().
Because of this, whenever the OS kills your Service (to reclaim memory, for example) it will not get re-created.
Change the following line:
return START_NOT_STICKY;
To this:
return START_STICKY;
From the documentation of START_STICKY:
Constant to return from onStartCommand(Intent, int, int): if this
service's process is killed while it is started (after returning from
onStartCommand(Intent, int, int)), then leave it in the started state
but don't retain this delivered intent. Later the system will try to
re-create the service. Because it is in the started state, it will
guarantee to call onStartCommand(Intent, int, int) after creating the
new service instance; if there are not any pending start commands to
be delivered to the service, it will be called with a null intent
object, so you must take care to check for this.
NOTE: START_STICKY does not prevent your Service from being killed. It just tells the OS to restart it as soon as possible (depending on the available resources). To make your Service less likely to be killed, you can
make it run in the foreground by calling startForeground().
|
[
"german.stackexchange",
"0000001122.txt"
] | Q:
Meaning of Mann as a tribe rather than a male individual
Everybody understands the substantive Mann as designating a male human individual.
Some people might also be aware of the kinship between Mann and the verb to command, which crops up for instance in the Old Swedish noun mander.
I have had however a few suspicion that the Mann substantive also could be interpreted collectively as a tribe.
The Alemanni confederation of tribes who became notorious in Roman Gaul during the Late Roman empire and its collapse, which yielded so many ethnonyms for the German people (e.g. "Les Allemands", "Los Alemanes" to name but a few). In this occurrence it seems that "Alle Männer" must be be understood as "all tribes" rather than "all men".
The etymology of the ethnonym the Normans. In old English, you have "Norðmann", a precise translation of which would be the "people from the North" as in "Nordleuten" rather than "men from the North" "Nordmänner"1.
The kinship mentioned above between Mann (a concept related to a single individual) and to command2 (a concept related to a troop, a clan or a party).
Questions
So I'm curious to know whether there are some more indications of an old phased out meaning of Mann as a tribe rather than a single individual.
Considering that in many of today's nomadic people there are clear indications that a tribe is little more than an extended family, would that be a possible explanation.
[1]
Late edit. I quote the "Norðmann" word on the premises that Old English is part of the West Germanic subfamily of Germanic languages. Although both Normannen in German and Norman in English are later loanwords from Old French (11c.), the word Norðmann is endemic to Old English and its use attested in various Wessex manuscripts (10c. also Normann).
[2] Although the etymology of to command through the Latin verb mando is the hand (manus), it ultimately goes back to the PIE root man-.
A:
Neither in everyday language nor in any other use of German I'm familiar with does Mann have even the slightest connotation of tribe. I think you're looking for something that doesn't exist (or has been a 100% lost from the language feeling).
The old plural 'Mannen' has long survived (but is today almost obsolete) in the meaning of "retinue", but doesn't have a connotation of tribe.
A:
Although the modern word Mann has no meaning of tribe anymore, the mentioned roots are visible with Normannen, which would be the word-to-word-translation of Normans.
As far as the wikipedia article tells Normannen is a French loanword.
|
[
"stackoverflow",
"0040880591.txt"
] | Q:
Xamarin Forms: Centering multiple, different controls in a layout?
My XAML looks like this:
<StackLayout Orientation="Vertical" HorizontalOptions="Center">
<controls:BindablePicker HorizontalOptions="Center" />
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListView Grid.Row="0" Grid.Column="1" HorizontalOptions="Center" SeparatorVisibility="None">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid BackgroundColor="Aqua">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<controls:BindablePicker Title="Length" Grid.Row="0" Grid.Column="0" BackgroundColor="White" />
<controls:BindablePicker Title="Units" Grid.Row="0" Grid.Column="1" BackgroundColor="White" />
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</StackLayout>
Here's what I'm getting: Attempt
This is pretty much what I want, except I want the content centered within the aqua area so everything is centered horizontally. I don't mind if the left cell is right justified and the right cell is left justified.
Note that I'm wanting to add other content beneath this, like labels and other grids, all centered on the page.
Any help would be greatly appreciated. Thanks.
A:
First of all I do not think that you need a row definition in your inner grid since you have only one row.
Secondly for performance sake,do not user "Auto" , just remove the width property from the column definitions.
By doing this both columns will have the same width... I hope ;)
I think if you made your list view like below then it would fix it, but also try it without HorizontalOptions for the controls.
<ListView Grid.Row="0" Grid.Column="1" HorizontalOptions="Center" SeparatorVisibility="None">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid BackgroundColor="Aqua">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<controls:BindablePicker Title="Length" Grid.Column="0" BackgroundColor="White" HorizontalOptions = "End" />
<controls:BindablePicker Title="Units" Grid.Column="1" BackgroundColor="White" HorizontalOptions = "Start" />
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Hint: The next release of Xamarin.Forms, which is in the alpha channel now, contains a bindable picker so you do not have to user a 3rd party now.
|
[
"stackoverflow",
"0035402217.txt"
] | Q:
CoreData FetchRequest problems
I'm teaching myself to programme and have thought up this project for myself to learn. I'm having trouble with my code, I was able to save it correctly and load the first state population TVC. However, I'm having problems with the state and number of animals per state TVC. I want to total it per a state. So I would be adding the dogs and cats population together and get the total per a state, but it brings Alabama separately with two different population, can someone help me with this please.
the model below shows how I want it, I'm able to output to State Population correctly but now the second one.
What my code is doing for the second one is that it's getting the data from coredata but I'm using sort descriptor because I don't know any other way to pull the data.
var totalEntries : Int = 0
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var frc : NSFetchedResultsController = NSFetchedResultsController()
func fetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: "Animals")
let sortDescriptor = NSSortDescriptor(key: "state", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
return fetchRequest
}
func getFRC() -> NSFetchedResultsController {
frc = NSFetchedResultsController(fetchRequest: fetchRequest(), managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)
return frc
}
override func viewDidLoad() {
super.viewDidLoad()
frc = getFRC()
frc.delegate = self
do {
try frc.performFetch()
} catch {
print("Failed to fetch data")
return
}
totalEntries = moc.countForFetchRequest(fetchRequest(), error: nil) as Int!
self.tableView.reloadData()
}
override func viewDidAppear(animated: Bool) {
frc = getFRC()
frc.delegate = self
do {
try frc.performFetch()
} catch {
print("Failed to fetch data")
return
}
totalEntries = moc.countForFetchRequest(fetchRequest(), error: nil) as Int!
self.tableView.reloadData()
}
A:
Your problem is the fetched results controllers aren't designed to show aggregated fetch results like you desire, hence you see all the underlying data instead of the aggregate.
You could use the FRC if you cheat... Set the section name of the FRC to the state name, then you will have one section in the table per state. In the table delegate return 1 for the number of rows in each section. When configuring the cell use KVC to @sum the populations of all of the animals in that state (the rows for that section as understood by the FRC).
This is a memory and runtime inefficient solution... It could be improved by caching the calculated sums, but you're adding logic on top of bad design then.
The correct approach would be to abandon the FRC and use a simple array of dictionaries. This would be generated by changing your fetch request to return dictionary type and configuring it to calculate the sums for you. That's done with an expression something like:
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
expressionDescription.name = @"sumOfPopulations";
expressionDescription.expression = [NSExpression expressionForKeyPath:@"@sum.population"];
expressionDescription.expressionResultType = NSDecimalAttributeType;
|
[
"stackoverflow",
"0044954119.txt"
] | Q:
Firebase Google users not showing in Firebase Console Authentication
Using Firebase Google Auth, when a user logs in successfully with their google account, they are not showing on our Firebase Console Authentication->Users screen. Only email/password users are showing up there.
Is there something extra that needs to be done to see the Google Auth users?
A:
As indicated by Frank, to fully sign into Firebase the call to signInWithCredential() was needed. After implementing this functionality, users signing in with Google showed up in the Firebase console.
|
[
"math.stackexchange",
"0002831808.txt"
] | Q:
Dual optimization problem, decomposition.
I have the following problem:
$\min x_1 ^ 2 + x_2 ^2$
s.t.
$x_1 + x_2 \ge 1$
$x_1 \ge 0$
$x_2 \ge 0$
I have three inequality constraints, so my lagrangian would be
$L = x_1 ^2 + x_2 ^2 + \lambda_1 (-x_1 - x_2 + 1) + \lambda _2 (-x_1) + \lambda _3 (-x_2)$
now if I wanted to find the dual form I would minimize $L$ over $x$ and obtain $L_{dual} ( \lambda )$. My lecturer, though, proposes a different approach to this problem, namely he chooses
$L = x_1 ^2 + x_2 ^2 + \lambda (-x_1 - x_2 + 1)$, seemingly ignoring the non-negativity constraints, then he cleverly finds the dual form as $L_{dual} = \underset{x_1 \ge 0}{min} \{x_1 ^2 - \lambda x_1 \} + \underset{x_2 \ge 0}{min} \{x_2 ^2- \lambda x_2 \} $. I don't understand where it comes from. If it has some simple derivation or reasoning behind it I would be interested in finding more about this method, as it seems very convenient in some cases. If this is very complex though, I would be grateful just for providing me with some intuition.
A:
You can add the convex indicator function to the objective function, taking the value 0 if $x_1\geq 0$ and $\infty$ otherwise; and another indicator function for $x_2$. This replaces the constraints and results in the formulation of your lecturer:
$$L = x_1^2 + x_2^2 + \delta(x_1|R_+) + \delta(x_2|R_+) + \lambda(-x_1-x_2+1)$$
$$\begin{align} &\min_x \{ x_1^2 + x_2^2 + \delta(x_1|R_+) + \delta(x_2|R_+) + \lambda(-x_1-x_2+1) \} \\
= \; & \lambda + \min_{x_1} \{ x_1^2 + \delta(x_1|R_+) - \lambda x_1 \} + \min_{x_2} \{ x_2^2 + \delta(x_2|R_+) - \lambda x_2 \} \\
= \; & \lambda + \min_{x_1 \geq 0} \{ x_1^2 - \lambda x_1 \} + \min_{x_2 \geq 0} \{ x_2^2 - \lambda x_2 \} \end{align}$$
|
[
"mathoverflow",
"0000294457.txt"
] | Q:
What are the possible eigenvalues of these matrices?
Edit: since we seem a bit deadlocked at this point, let me weaken the question. It's fairly easy to see that the set of 8-tuples of reals which can be the eigenvalues of a matrix of the desired form is closed. We know from jjcale and Caleb Eckhardt that its complement is nonempty. Is its complement dense? That is, would a generic 8-tuple not be the eigenvalues of such a matrix?
First, here is a baby version of the question, that I already know the answer to. Consider complex Hermitian $4\times 4$ matrices of the form $$\left[\begin{matrix}a I_2&A\cr A^*&b I_2\end{matrix}\right]$$ where $A \in M_2(\mathbb{C})$ and $a,b \in \mathbb{R}$ are arbitrary. Can any four real numbers $\lambda_1 \leq \lambda_2 \leq \lambda_3\leq \lambda_4$ be the eigenvalues of such a matrix, or is there some restriction? Answer: there is a restriction, we must have $\lambda_1 + \lambda_4 = \lambda_2 + \lambda_3$.
The real question is: what are the possible eigenvalues of Hermitian $8\times 8$ matrices of the form $$\left[\begin{array}{c|c}aI_4&A\cr \hline A^*&\begin{matrix}bI_2& B\cr B^*&cI_2\end{matrix}\end{array}\right]$$ with $a,b,c\in\mathbb{R}$, $A \in M_4(\mathbb{C})$, and $B \in M_2(\mathbb{C})$? Can any eight real numbers be the eigenvalues of such a matrix? (I suspect not. If they could, that would tell you that any Hermitian $8\times 8$ matrix is unitarily equivalent to one of this form.)
A:
There is a general framework for answering questions like this although I don't know the answer in this case. You are asking for which coadjoint orbits of $U(8)$ the moment polytope for the action of the subgroup $SU(4) \times SU(2) \times SU(2)$ contains the origin. There is a method for computing these polytopes in Berenstein, Arkady; Sjamaar, Reyer, Coadjoint orbits, moment polytopes, and the Hilbert-Mumford criterion, J. Am. Math. Soc. 13, No.2, 433-466 (2000). ZBL0979.53092..
There is a way of packaging all the coadjoint orbits together, by saying that each coadjoint orbit is a symplectic quotient of the cotangent bundle of the group. This rephrases the problem as that of computing the moment polytope for the $U(8)$ action on $T^*(U(8)/SU(4) \times SU(2) \times SU(2))$. This is going to be a convex polyhedral cone.
General theory says that you can compute the affine space spanned by the polytope from the generic stabilizer (the subgroup of elements fixing a generic point). In your case, the generic stabilizer is the same as the generic stabilizer of $SU(4) \times SU(2) \times SU(2)$ on the quotient of Lie algebras $\mathfrak{u}(8)/{\mathfrak{su}}(4) \oplus \mathfrak{su}(2) \oplus \mathfrak{su}(2)$.
In the 4 by 4 case you mentioned, to find the space perpendicular to the moment polytope you want to compute the generic stabilizer
of $G = SU(2) \times SU(2)$ on $V = \mathfrak{u}(4)/\mathfrak{su}(2) \oplus \mathfrak{su}(2)$. Except for the multiples of the 2 by 2 identity this quotient can be identified with $2 \times 2$ matrices. The generic stabilizer is only defined up to conjugacy, and it's a bit tricky to find the equation for a moment polytope as opposed to one of its Weyl conjugates. The stabilizer $G_B$ at a matrix $B$ is the subgroup of $(A_1,A_2)$ so that $A_1 B A_2^{-1} = B$. Any $B$ is diagonal up to left and right multiplication, and so any diagonal $B$ with generic eigenvalues gives the generic stabilizer. But taking $B$ diagonal the resulting hyperplane doesn't meet the positive Weyl chamber; this is related to the fact that the answer that you want is going to depend on how the eigenvalues are ordered, so its better to take $B$ antidiagonal.
(Once one accepts that the generic stabilizer is abelian, any full rank $B$ is ok.) Take
$$B = \left[ \begin{array}{cc} 0 & b_{12} \\ b_{21} & 0 \end{array} \right] , \ |b_{12}| \neq |b_{21}|, \ \ A_2 = \left[ \begin{array}{ll} a_{11} & a_{12} \\ a_{21} & a_{22} \end{array} \right] .$$
Then we want
$$A_1 = B A_2 B^{-1}$$ to be special unitary. Since
$$ B A_2 B^{-1} = \left[ \begin{array}{ll} a_{22} & (b_{12}/b_{21}) a_{21} \\ (b_{21}/ b_{12}) a_{12} & a_{11} \end{array} \right] $$
is unitary only if $a_{12} = a_{21} =0$, we have
$$A_2 = \operatorname{diag}(t^{-1},t), \ \ t= a_{22}, \ A_1 = \operatorname{diag}(t,t^{-1}) .$$ Hence the generic stabilizer is the set of matrices
$$diag(t,t^{-1},t^{-1},t)$$
for some complex $t$ with norm one.
The Lie algeba of the stabilizer is the span of $(1,-1,-1,1)$, and the perpendicular is the space of $(\lambda_1,\lambda_2,\lambda_3,\lambda_4)$ satisfying
$$\lambda_1 - \lambda_2 - \lambda_3 + \lambda_4 = 0 .$$
In the 8 by 8 case you want to understand, the quotient $\mathfrak{u}(8)/\mathfrak{su}(4) \oplus \mathfrak{su}(2) \oplus \mathfrak{su}(2)$ is
(after forgetting about diagonal matrices) identified with the space of pairs $(A,B)$ where $A$ is 4 by 4
and $B$ is 2 by 2. Generically such matrices are full rank, and take $B$ to be a generic antidiagonal matrix implies that
the the matrices in $SU(2) \times SU(2)$ must be of the form diag$(t,t^{-1},t^{-1},t)$. But then we want
$$ A\,\text{diag}(t,t^{-1},t^{-1},t) A^{-1} $$
to be special unitary which is not the case for generic $A$.
So the generic stabilizer has trivial Lie algebra, which means that the moment polytope is full rank (that is, no linear equations are satisfied).
In a previous version of this answer, I accidentally took $A$ to be generic "unitary" and got the wrong answer that the cone has codimension one. However, my previous wrong answer does suggest something about the facets of the cone. General theory says that the hyperplanes at the boundary of the cone are perpendicular to one-dimensional stabilizers. If one takes $A$ to be a permutation matrix then one gets an element with one-dimensional stabilizer. So I wonder whether the cone you are looking for is the cone whose facets are among those defined by equalities
$$ \lambda_{\sigma(1)} - \lambda_{\sigma(2)} - \lambda_{\sigma(3)} + \lambda_{\sigma(4)} + \lambda_{\sigma(5)} - \lambda_{\sigma(6)} -\lambda_{\sigma(7)} + \lambda_{\sigma(8)} = 0 $$
where $\sigma$ ranges over elements of the eighth symmetric group.
The Berenstein-Sjamaar paper would answer this with enough work. (It is a Schubert calculus computation.)
A:
This is a partial answer that shows an obstruction to certain eigenvalue sequences. First, I claim that if $M$ is rank one then it isn't similar to something of the stated form.
Take a matrix $M$ of the given form and suppose the rank is $0$ or $1.$ If $a\neq0$, then the rank of $M$ is at least 4. If $b\neq0$ or $c\neq0$ then the rank of $M$ is at least 2. Since $M$ is rank 0 or 1 we must have $a=b=c=0.$ Since we have a 0 diagonal, if $A\neq0$, then the rank of $M$ would have to be at least 2 so we must have $A=0$. Similarly, the 0 diagonal and $B\neq0$ forces the rank to be at least 2 so we must have $B=0$, so $M$ is rank $0.$
That eliminates some eigenvalue sequences. Now notice that if the rank of $M$ is $\leq 3$ and $M$ is positive semidefinite this forces $a=0$ and $A=0$ so you are back in the case that you know how to deal with. This will eliminate some other eigenvalue sequences.
A:
Consider the case where the $8\times 8$ matrix is positive semidefinite and assume that the 5 largest eigenvalues are all equal. Then by the argument of Federico Poloni they equal a. Then it follows $A = 0$ and therefore the four smallest eigenvalues are restricted like in the $4\times 4$ case .
|
[
"stackoverflow",
"0008119801.txt"
] | Q:
Best webserver with minimum resource
Now i am using apache2, but i heard about engine-x (nginx) is pretty fast and with low hardware consumption. If the feedback is good enough than my lamp environment will be changed in lxmp.
A:
Use nginx for staic content and apache2 for php.
|
[
"stackoverflow",
"0020798516.txt"
] | Q:
iOS7 Silent Push notification not working
I have implement push notifications in iOS7. As iOS7 having features of receiving push notification silently by using method
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo performFetchWithCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler
{
}
But this method never getting called as I am sending notification. I am receiving the notification in notification tray But notification should not be there as It is silent. I am using Raywenderlich's PHP code to send the push Notification. I have added content-available key also like this
// Create the payload body
$body['aps'] = array(
'content-available' => '1',
'alert' => $message,
'sound' => 'default'
);
Please Help!!!
A:
You should not add 'alert' param in your payload if you want to silent push notification.
pass your param like this.
$body['aps'] = array(
'content-available' => '1'
);
And verify you enabled remote-notification in your project plist.
or
You will get notification by implementing this delegate.
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
// Call or write any code necessary to download new data.
completionHandler(UIBackgroundFetchResultNewData);
}
|
[
"stackoverflow",
"0014657762.txt"
] | Q:
TypeError: takes exactly 1 argument (2 given) within GAE
Within the GAE I'm getting an error telling me:
TypeError: get_default_tile() takes exactly 1 argument (2 given)
As you can see the code from my main py file get_default_tile() is being passed only one argument which is name:
default_tile = self.get_default_tile(name)
The full code follows:
import jinja2 # html template libary
import os
jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
import urllib
import urllib2
import webapp2
from google.appengine.ext import db
from google.appengine.api import urlfetch
class Default_tiles(db.Model):
name = db.StringProperty()
image = db.BlobProperty(default=None)
class MainPage(webapp2.RequestHandler):
def get(self):
# this just prints out the url which the user enters into input
image_name = self.request.get('image_name')
template_values = {
'image_name': image_name,
}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
class Upload(webapp2.RequestHandler):
def post(self):
# get information from form post upload
image_url = self.request.get('image_url')
image_name = self.request.get('image_name')
# create database entry for uploaded image
default_tile = Default_tiles()
default_tile.name = image_name
default_tile.image = db.Blob(urlfetch.Fetch(image_url).content)
default_tile.put()
self.redirect('/?' + urllib.urlencode({'image_name': image_name}))
class Get_default_tile(webapp2.RequestHandler):
def get(self):
name = self.request.get('image_name')
default_tile = self.get_default_tile(name)
self.response.headers['Content-Type'] = "image/png"
self.response.out.write(default_tile.image)
def get_default_tile(name):
result = db.GqlQuery("SELECT * FROM Default_tiles WHERE name = :1 LIMIT 1", name).fetch(1)
if (len(result) > 0):
return result[0]
else:
return None
app = webapp2.WSGIApplication([('/', MainPage),
('/upload', Upload),
('/default_tile_img', Get_default_tile)],
debug=True)
Any help would be appreciated.
A:
get_default_tile(): is a member method of class Get_default_tile so you need to define it like this:
def get_default_tile(self, name):
Or if you want it to be a static method:
@staticmethod
def get_default_tile(name):
|
[
"physics.stackexchange",
"0000026061.txt"
] | Q:
Why did population III stars lack planets?
Jay Wacker1 (professor of physics at the SLAC National Accelerator Laboratory) stated:
The first stars (known as Pop III) were made out of hydrogen and helium. They had no planets.
Why couldn't they have had gas planets?
[1] Requires login at LinkedIn
A:
The earliest stars did not have planets primarily due to a lack of metals. Metals in this sense is an element (with some extra properties that are not relevant in this context) heavier than helium. The very article that you linked to references this. This leads to the following:
Stars without metals tend to not last very long. Metals in a star act to slow down the reaction speed of the fusion. Without metals, the stars quickly get to a state where they will explode. Short time scales do not allow for enough time to form planets.
Metals seem to be the initial building block of planets. This wikipedia article discusses the current leading theories for rocky and gas planets. Basically, they both start with a rock forming that's big enough, leading to a chain effect which ends up to be a planet. Rocks can't form from hydrogen and helium, making planet formation difficult.
A:
Several answers occurred to me.
Timescale. Population III stars only last a few million years. This article, which is billed as as evidence for a much shorter timescale of planetary formation than previously thought, still quotes 10 million years (caveat: for terrestrial planets, but I didn't find a source right off the bat for gas giants). However, if I'm wrong there, there's always these other answers:
In continuation of the discussion of How can a Population III star be so massive?, the metallicity may be a factor. The original stars had virtually no metals, which made their cool down much, much less efficient. For the same reason that you can get larger stars that way, perhaps there won't be much material left over for planet formation?
The upper layers of very large, fluffy stars are barely gravitationally bound, and they have enormous stellar winds. Maybe such massive winds and/or the enormous luminosity of a Pop III star either prevent planets from forming in the first place, or ablate embryonic planets into oblivion?
|
[
"ru.stackoverflow",
"0000386614.txt"
] | Q:
Слишком большой CTR в AdMob в одной стране.
Дано:
AdMob показывает такие данные по США:
сегодня - запросы 10, клики 1, CTR 10,00%, доход на тысячу запросов/показов 48,92$.
вчера - запросы 35, клики 3, CTR 8,57%, доход на тысячу запросов/показов 19,45$.
этот месяц - запросы 1178, клики 9, CTR 0,77%, доход на тысячу запросов/показов 2,37$.
Проблема:
Где-то когда-то читал, что могут забанить аккаунты гугл-плея и AdMob при CTR>8%, объясняя это накруткой кликов.
Связаться с AdMob сложно - они пишут, что из-за праздников могут долго отвечать или вообще не ответить, если у них этот вопрос на их ресурсах разрешён уже. Искать что-то на их ресурсах - страдание.
Вопрос:
Таки могут забанить при таких показателях или нет, т.к. смотрят они только на месячные показатели?
A:
Судя по тому, что за 3 месяца, при периодических повторах сей ситуации меня так и не забанили и гугл даже продолжает гроши слать, всё это либо нормально, либо незаметно.
|
[
"stackoverflow",
"0009429025.txt"
] | Q:
Is there a way to apply per-module view.yml constraints to foreign templates in Symfony 1?
When doing the following, view.yml constraints in neither module a nor b take effect, whilst the 'all' config in module a does.
a/actions/actions.class.php
public function executeShow(sfWebRequest $request) {
$this->setTemplate('example', 'b');
}
I have tried the following in both module a and b's view.yml's:
showSuccess:
components:
breadcrumbs: [sfDoctrineBreadcrumbs, breadcrumbs]
exampleSuccess:
components:
breadcrumbs: [sfDoctrineBreadcrumbs, breadcrumbs]
Just for completeness, I am trying to override the following in module a:
all:
components:
breadcrumbs: false
Taking out this condition does enable the component for the foreign template, but I'd rather now do this.
The all config of module b is also not applied.
A:
I think it's already loaded a view.yml at the point you call setTemplate, and don't think it'll load a second one.
I've used $this->forward instead of setTemplate before to get around the same issue.
|
[
"es.stackoverflow",
"0000021505.txt"
] | Q:
Ir a otro controlador desde javascript
Quiero redireccionar desde una vista a un controlador que esta un nivel más alto, para ello utilizo @url.action de este modo
miUrl = '@Url.Action("CambiarEstadoVisita", "~/Areas/Visitas/Visita")';
Pero el link que genera es este:
http://localhost:10174/Mantenimiento/~/Areas/Visitas/Visita/CambiarEstadoVisita
¿Cómo puedo hacer para ir hacia atrás ?
A:
Ya conseguí solucionarlo. En vez de usar url.Action que no me dejaba navegar hacia atrás con los ../
miUrl = '@Url.Action("CambiarEstadoVisita", "../../Visitas/Visita")';
la url la cree como string
miUrl = '../../Visitas/Visita/CambiarEstadoVisita';
y la pase por ajax
|
[
"stackoverflow",
"0037852630.txt"
] | Q:
Best practice for returning a variable that exists in global scope?
Is the return statement in here unnecessary?
var fahrenheit;
var celsius;
function cToFConvert () {
celsius = temperatureInput.value;
fahrenheit = celsius * (9/5) +32;
console.log(fahrenheit);
return fahrenheit;
}
I can get the fahrenheit value even if I do not use the return statement. Does that mean using a return is redundant if the variable was declared in global scope?
A:
Function and pure function.
The concept to keep a function pure is the idea to use the function without side effects. This means, the function should rely on own parameters and return something which is related to the parameters only.
That means a function should have some input and and some output.
In this case for converting a temperature, you have a value Celsius and want to get the value in Farenheit. This is a good example how to write a function which is resusable for any purpose and could be inserted into a library without changes.
How does it work?
You may think of an input and an output based on the input.
function convertCelsiusToFarenheit(celsius) {
return celsius * 9 / 5 + 32;
}
Now you can use the function with a wanted input and store the output to a variable
var myFarenheit = convertCelsiusToFarenheit(temperatureInput.value);
Or if you like to convert a bunch of values, you could use the function as callback
var myFarenheitData = [-10, 0, 10, 20, 30, 40].map(convertCelsiusToFarenheit);
With this in mind, its is easier to write a multipurpose function.
|
[
"pt.stackoverflow",
"0000069081.txt"
] | Q:
Ajuda a fazer um select
Ao fazer uma encomenda, devo salvar os dados dela (e do cliente) no banco de dados, certo? Mas ao fazer isso, devo guardar também alguma informação do cliente na tabela de encomendas? Visto que eu vou querer listar numa tela qual foi o cliente que fez certa encomenda.
Minhas tabelas:
tabela cliente
-nome
-morada
-datanasc
-sexo
-pais
-cidade
-telemovel
-user
-senha
tabela encomenda
-id
-tamanho
-disponiblidade
-preco
Tenho que adicionar um campo na minha tabela encomenda, para que seja possível listar as encomendas de um cliente?
A:
Respondendo de forma curta, sim você precisa adicionar um identificador do cliente na sua tabela encomenda, esse identificador precisa ser uma coluna da tabela cliente que nunca irá se repetir. Nessa situação utilizamos as chaves primárias e normalmente com auto incremento.
Agora quer saber mais sobre o relacionamento entre as tabelas? Dê uma olhada neste excelente artigo do Thiago Belem.
Conteúdo retirado do blog do Thiago Belem.
Relacionamento de Tabelas no MySQL
O relacionamento de tabelas é necessário quando temos mais de uma tabela com informações que podem e precisam ser cruzadas, por exemplo: categorias e produtos… Cada registro na tabela produtos estará ligado a um registro da tabela categorias.
Só pra vocês saberem, existem três níveis de relacionamento: nosso exemplo será um relação de 1:N (fala-se “um pra N” ou “um para muitos”) onde cada categoria (1) contém um ou mais produtos (N)… Há também o 1:1 onde cada registro de uma tabela (1) está ligado a um e somente um registro de outra tabela (1)… E há outro nível de relacionamento, mais complexo, que é o N:N onde um ou mais registros de uma tabela (N) estão relacionados a um ou mais registros de outra tabela (N), que seria o exemplo de duas tabelas “produtos” e “tags” onde um produto tem várias tags e vários produtos pertencem a uma tag.
Não vou me aprofundar muito no assunto… Vou falar apenas da relação mais comum (1:N) e dar exemplos de como trabalhar com elas.
Para o nosso exemplo de hoje usaremos duas tabelas, chamadas “categorias” e “produtos”:
CREATE TABLE `categorias` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`nome` VARCHAR( 255 ) NOT NULL
) ENGINE = MYISAM;
CREATE TABLE `produtos` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`categoria_id` INT NOT NULL ,
`nome` VARCHAR( 255 ) NOT NULL ,
`preco` DECIMAL( 10,2 ) NOT NULL
) ENGINE = MYISAM;
E vamos inserir alguns dados para exemplo:
-- Extraindo dados da tabela `categorias`
INSERT INTO `categorias` VALUES(1, 'Camisetas');
INSERT INTO `categorias` VALUES(2, 'Canecas');
-- Extraindo dados da tabela `produtos`
INSERT INTO `produtos` VALUES(1, 1, 'Camiseta Social', 15.00);
INSERT INTO `produtos` VALUES(2, 1, 'Camiseta Regata', 11.99);
INSERT INTO `produtos` VALUES(3, 2, 'Caneca Grande', 12.00);
Reparem que na tabela produtos temos uma coluna “especial”, que é a “categoria_id” (INT)… Ela é quem ajudará a fazer a relação das duas tabelas… Nessa coluna entrará o ID da categoria a qual o produto pertence… Ou seja: as duas camisetas pertencem a categoria “Camisetas” (ID 1) e o terceiro produto (a Caneca Grande) pertence a categoria “Canecas” (ID 2) e é na coluna “categoria_id” que armazenamos esses IDs que identificam as categorias.
Esse campo responsável pela relação é normalmente chamado de foreing key (fk) ou “chave estrangeira”.
Mas qual a utilidade dessa tal “relação”?
Sem usar o relacionamento você poderia pegar todos os produtos e depois pegar as informações das categorias com uma segunda consulta, assim:
<?php
// Consulta que pega todos os produtos
$sql = "SELECT * FROM `produtos` ORDER BY `nome` ASC";
$query = mysql_query($sql);
while ($produto = mysql_fetch_assoc($query)) {
// Aqui temos o array $produto com todos os valores do produto
// Consulta para pegar os dados da categoria:
$sqlC = "SELECT * FROM `categorias` WHERE `id` = " . $produto['categoria_id'];
$queryC = mysql_query($sqlC);
$categoria = mysql_fetch_assoc($queryC);
echo 'Titulo: ' . $produto['nome'] . '';
echo 'Preço: ' . $produto['preco'] . '';
echo 'Categoria: ' . $categoria['nome']. '';
echo '<hr />';
}
Até aí tudo bem… Não tem nenhum pecado nisso… Mas imagine que você tem uma loja com 1000 produtos (o que não é muito), seria executada 1 consulta para todos os produtos e, dentro do loop (while) seriam executadas outras 1000 consultas para pegar o nome da categoria a qual o produto pertence… Ou seja, 1001 consultas, o que é um absurdo.
A mágica da relação
Agora vamos montar uma consulta que DE UMA SÓ VEZ irá pegar os dados de cada produto e também o nome da categoria… Com isso reduziremos nossas 1001 consultas pra… uma só! Sem mistérios, sem sub-consultas, nem consultas dentro do while()! :D
Mas antes de mostrar o script vou ajudar a vocês entenderem como a relação é feita… Antes a nossa consulta que pega apenas os produtos era assim:
SELECT * FROM `produtos` ORDER BY `nome` ASC
Sua tradução seria: SELECIONAR todas as colunas da TABELA produtos ORDENADO PELO nome ASCENDETEMENTE
Agora usaremos uma nova “palavra” do MySQL que é o JOIN (tradução: “unir”) e serve para unir resultados de duas tabelas.. ;)
Existem três tipos de JOIN mas não vou falar dos outros dois pois eles são MUITO pouco usados… Falaremos do “INNER JOIN” que exige que haja um registro que corresponda a relação nas duas tabelas, ou seja: se houver um produto sem categoria ou a categoria não existir na tabela categorias esse produto é omitido dos resultados.
A nossa consulta ficará assim:
SELECT `produtos`.* FROM `produtos`
INNER JOIN `categorias` ON `produtos`.`categoria_id` = `categorias`.`id`
ORDER BY `produtos`.`nome` ASC
Sua tradução seria: SELECIONAR todas as colunas [da tabela produtos] da TABELA produtos UNINDO A TABELA categorias ONDE a coluna categoria_id [da tabela produtos] É IGUAL a coluna id [da tabela categorias] ORDENADO PELO nome [da tabela produtos] ASCENDETEMENTE
A nossa “regra de relação” acontece ali entre o ON e o ORDER BY, dizemos que a relação entre as tabelas usará como referencia a coluna “categoria_id” da tabela “produtos” sendo igual a coluna “id” da tabela “categorias”… Se você fosse usar algum WHERE ele entraria depois do ON e antes do ORDER BY.
Pra quem ainda não entendeu, o ON é como o WHERE de uma consulta normal… É a regra da relação.
Repare que agora precisamos usar um formato diferente para identificar as colunas usando: tabela.coluna… Isso é necessário pois agora estamos trabalhando com duas tabelas.
Da forma que a nossa consulta está ainda não estamos pegando o nome da categoria… fazemos isso adicionando mais um campo na parte do SELECT, assim:
SELECT `produtos`.*, `categorias`.`nome` FROM `produtos`
INNER JOIN `categorias` ON `produtos`.`categoria_id` = `categorias`.`id`
ORDER BY `produtos`.`nome` ASC
Agora estamos pegando também o valor da coluna "nome" do registro encontrado (pela relação) na tabela "categorias".
Só que agora temos um novo problema… Nas duas tabelas existe uma coluna chamada “nome”, e quando estivermos lá no PHP, dentro do while, não teríamos como identificar de qual tabela pegamos as informações (veja a próxima imagem), pois as duas seriam $produto['nome']… Precisamos então renomear esse novo campo que adicionamos a busca, assim:
SELECT `produtos`.*, `categorias`.`nome` AS categoria FROM `produtos`
INNER JOIN `categorias` ON `produtos`.`categoria_id` = `categorias`.`id`
ORDER BY `produtos`.`nome` ASC
Agora o resultado de categorias.nome estará presente nos resultados como “categoria” e não “nome”… Sei que parece complicado de início mas vocês vão entender já já.
E por fim, faremos mais uma modificação, pra evitar ficar usando tabela.coluna também podemos renomear as tabelas, e com isso diminuir o tamanho da consulta:
SELECT p.*, c.`nome` AS categoria FROM `produtos` AS p
INNER JOIN `categorias` AS c ON p.`categoria_id` = c.`id`
ORDER BY p.`nome` ASC
Nesse caso p representará a tabela “produtos” e c representará a “categorias”.
Sei que parece uma consulta maior e mais complicada… Mas você fará o MySQL trabalhar muito menos se fizer assim, com JOINS, do que fazer uma 2ª consulta dentro do while… Essa é a forma mais correta de fazer consultas quando precisamos de informações vindas de mais de uma tabela.
Agora vamos ao nosso novo script de PHP que, sem dúvidas, é bem mais prático e eficiente:
<?php
// Consulta que pega todos os produtos e o nome da categoria de cada um
$sql = "SELECT p.*, c.`nome` AS categoria FROM `produtos` AS p INNER JOIN `categorias` AS c ON p.`categoria_id` = c.`id` ORDER BY p.`nome` ASC";
$query = mysql_query($sql);
while ($produto = mysql_fetch_assoc($query)) {
// Aqui temos o array $produto com todos os dados encontrados
echo 'Titulo: ' . $produto['nome'] . '';
echo 'Preço: ' . $produto['preco'] . '';
echo 'Categoria: ' . $produto['categoria']. '';
echo '<hr />';
}
Os outros tipos de JOINs
Existem também outros dois tipos de JOIN: o LEFT JOIN e o RIGHT JOIN:
Se usássemos o LEFT JOIN seriam retornados todos os produtos, independente se eles estão ligados a uma categoria (na tabela categorias) existente ou não.
Já o RIGHT JOIN seria exatamente o contrário: seriam retornados todos os produtos que pertencem categorias existentes e também o nome das outras categorias que não tem ligação com nenhum produto.
O uso desses outros tipos de JOIN é muito raro e acho que não vale a pena ficar filosofando sobre eles enquanto se aprende sobre relacionamentos.
E a relação com mais de duas tabelas?
Só pra exemplo, essa seria a consulta que pega os produtos, as categorias e o nome do usuário que cadastrou o produto e filtrando apenas pelos produtos ativos:
SELECT p.*, c.`nome` AS categoria, u.`nome` AS usuario FROM `produtos` AS p
INNER JOIN `categorias` AS c ON p.`categoria_id` = c.`id`
INNER JOIN `usuarios` AS u ON p.`usuario_id` = u.`id`
WHERE (p.`ativo` = 1) ORDER BY p.`nome` ASC
Fonte: http://blog.thiagobelem.net/relacionamento-de-tabelas-no-mysql/
|
[
"stackoverflow",
"0031561620.txt"
] | Q:
FK Constraint error Headache - SQL Server
For a project I am trying to migrate an Access database to an SQL database.
To do this I created a linked server with the Access database and created a script that inserts the data from the Access into the SQL database. The created script is made with a try catch for each insert so that the ordering of the tables doesnt matter. To give an idea, below the script for 2 tables (total of 130 tables) that insert the data into SQl:
SET NOCOUNT ON
DECLARE @Rows AS INT
-- ****************************************************************************
-- ID = 1
IF NOT EXISTS (select * from TableInserted where ID = 1)
BEGIN
PRINT '~UpdateDB:'
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO [~UpdateDB](
-- [SSMA_TimeStamp],
[StepID],
[SQLInstruction],
[Description],
[Customer],
[InsertDateTime],
[InsertUserID],
[ExecutedateTime]
)
SELECT
[StepID],
[SQLInstruction],
[Description],
[Customer],
[InsertDateTime],
[InsertUserID],
[ExecutedateTime]
FROM [OPS_VSS_LINKED]...[~UpdateDB]
SELECT @Rows = @@ROWCOUNT
PRINT CAST(@Rows as NVARCHAR(10)) + ' Inserted'
COMMIT TRANSACTION
INSERT INTO TableInserted( ID, TableName, RowsInserted) VALUES (1,'~UpdateDB', @Rows)
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE()
ROLLBACK TRANSACTION
END CATCH
END
-- ****************************************************************************
-- ID = 2
IF NOT EXISTS (select * from TableInserted where ID = 2)
BEGIN
PRINT '~VAN SLUISVELD Origineel:'
SET IDENTITY_INSERT dbo.[~VAN SLUISVELD Origineel] ON
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO [~VAN SLUISVELD Origineel](
[ID],
[a]
)
SELECT
[ID],
[a]
FROM [OPS_VSS_LINKED]...[~VAN SLUISVELD Origineel]
SELECT @Rows = @@ROWCOUNT
PRINT CAST(@Rows as NVARCHAR(10)) + ' Inserted'
COMMIT TRANSACTION
INSERT INTO TableInserted( ID, TableName, RowsInserted) VALUES (2,'~VAN SLUISVELD Origineel', @Rows)
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE()
ROLLBACK TRANSACTION
END CATCH
SET IDENTITY_INSERT dbo.[~VAN SLUISVELD Origineel] OFF
END
So this script will only insert data if it hasn't been done yet (check in the TableInserted). If the insert generates error then it will rollback on the specific table.
This all works great but the access database is prety corrupted (cause of bad desingnin).
I am getting 50+ FK errors and I get stuck on this one in particular:
Relaties:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Relaties_Tariefnummers". The conflict occurred in database "OPS-VSS", table "dbo.Tariefnummers", column 'Tariefnummer'.
Tariefnummers:
The INSERT statement conflicted with the FOREIGN KEY constraint "Tariefnummers$RelatiesTariefnummers". The conflict occurred in database "OPS-VSS", table "dbo.Relaties", column 'RelatieNummer'.
Multiple FK errors are with the Relaties table so I thought lets fix that one first.
Above you can see the Relaties table fails inserting because of a FK error on the TariefNummers table, this is not strange since that specific table hasn't got it's data in it since that table also has a FK error.
So the next logical thing for me was to fix the FK error on the TariefNummers table. Though the FK error on the TariefNummers is linked to the Relaties table... So they are diabling each other.. Any clue how to fix this? Should I just delete 1 FK (on the TariefNummers) which isn't preferred.
I might be way off though, but some pointers would be appreciated!
A:
There can be valid reasons to want to have two tables with foreign keys to each other, but how will you ever be able to put data in them in the first place?
To populate the tables, you will have to drop or ignore one of those foreign keys, at least temporarily, until both tables are populated.
|
[
"cs.stackexchange",
"0000088224.txt"
] | Q:
Find the best set of triples of objects, using each object at max one time
I stumbled upon an interesting problem and I'm stuck with it, since I can't find parallels to other problems or algorithms to solve it.
We have a set of objects $O = \{a,b,c,...,z\}$, objects can make triples, e.g. $T=(a,b,c)$ $a,b,c \in O$ and we have a set of triples $X = \{T_1, ... T_n\}$. Each triple is assigned a value $c: X \rightarrow \mathbb{R}$
not every object has to be in a triple
an object can be in multiple triples
there can be triples using the same objects, but in a different order e.g. $(a,b,c),(c,a,b)$
Goal: Find the subset of triples $S \subseteq X$, where $\forall x \in \bigcup S: \exists y \in \bigcup S => y =x$ (Every object may appear at most once in the selection) with maximum $\sum_{T \in S} c(T)$ (maximum value of selection).
Is there a fast way to get the maximum? If not, is there any fast strategy that may produce a good result?
A simple greedy strategy would be to sort the triples descending by value and take a triple into the subset if all of it's objects are unused. This can be done in $O(n \log n)$, but does not produce the optimal result.
A:
Your problem is NP-hard. In particular, 3-dimensional matching is a special case of your problem, and 3-dimensional matching is NP-hard -- so your problem is, too.
|
[
"stackoverflow",
"0017371202.txt"
] | Q:
gdb vague shared library event information
I've made gdb to stop at shared library events. When I continue running application and gdb breaks saying:
"Stopped due to shared library event (no libraries added or removed)"
If I look at backtrace, it shows call to dlopen().
What does this mean? Is it that application tried to open shared library that was already loaded, or something else? Unfortunately I don't have symbols for libdl to figure it out myself.
A:
Is it that application tried to open shared library that was already loaded
Yes.
|
[
"stackoverflow",
"0051120067.txt"
] | Q:
How to zoom in on a specific range of values for a categorical variable in ggplot2?
I just want to zoom-in on the x axis between the values ford and nissan in the mpg dataframe.
packageused: tidyverse
But I am getting the following error when using coord_cartesian() function
p<-ggplot(mpg,aes(x=manufacturer,y=class))
p+geom_point()+ + coord_cartesian(xlim = c('ford','nissan'))
Error in +coord_cartesian(xlim = c("ford", "nissan")) : invalid
argument to unary operator
A:
You can use a function for contextual zoom from ggforce package (facet_zoom) to achieve this:
# loading needed libraries
library(ggplot2)
library(ggforce)
# selecting variables to display
names <- as.vector(unique(mpg$manufacturer))
selected.names <- names[4:11]
# zooming in on the axes
ggplot(mpg, aes(x = manufacturer, y = class)) +
geom_jitter() +
facet_zoom(x = manufacturer %in% selected.names)
Created on 2018-07-01 by the reprex package (v0.2.0).
|
[
"stackoverflow",
"0018801218.txt"
] | Q:
Build a color palette from image URL
I am trying to create an API which takes an image URL as input and returns back a color palette in JSON format as output.
It should work something like this: http://lokeshdhakar.com/projects/color-thief/
But should be in Python. I have looked into PIL (Python Image Library) but didn't get what I want. Can someone point me in the right direction?
Input: Image URL
Output: List of Colors as a palette
A:
import numpy as np
import Image
def palette(img):
"""
Return palette in descending order of frequency
"""
arr = np.asarray(img)
palette, index = np.unique(asvoid(arr).ravel(), return_inverse=True)
palette = palette.view(arr.dtype).reshape(-1, arr.shape[-1])
count = np.bincount(index)
order = np.argsort(count)
return palette[order[::-1]]
def asvoid(arr):
"""View the array as dtype np.void (bytes)
This collapses ND-arrays to 1D-arrays, so you can perform 1D operations on them.
http://stackoverflow.com/a/16216866/190597 (Jaime)
http://stackoverflow.com/a/16840350/190597 (Jaime)
Warning:
>>> asvoid([-0.]) == asvoid([0.])
array([False], dtype=bool)
"""
arr = np.ascontiguousarray(arr)
return arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[-1])))
img = Image.open(FILENAME, 'r').convert('RGB')
print(palette(img))
palette(img) returns a numpy array. Each row can be interpreted as a color:
[[255 255 255]
[ 0 0 0]
[254 254 254]
...,
[213 213 167]
[213 213 169]
[199 131 43]]
To get the top ten colors:
palette(img)[:10]
|
[
"stackoverflow",
"0039796100.txt"
] | Q:
Asp.net Facebook webhook Updates
I have created a Test Ad lead and I am trying to create webhook to consume real time updates. I was able to create a webhook sucessfully but when I try to create a Test lead my webhook is not triggering and I get Error code as 301
Below is my code:
[HttpGet]
public HttpResponseMessage Get()
{
CreaetLogFile("Log_get");
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(HttpContext.Current.Request.QueryString["hub.challenge"]);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return response;
//return Convert.ToInt32(HttpContext.Current.Request.QueryString["hub.challenge"]);
}
// POST api/values
[System.Web.Http.HttpPost]
public void Post()
{
// Do something
CreaetLogFile("Log_post");
}
I do not even see any post request being sent by facebook.
Thanks in advance.
A:
Issue was my URL was not secured. Installed certificates and now I am able to receive updates
|
[
"stackoverflow",
"0052583410.txt"
] | Q:
ArraySegment must be cast to IList to iterate through it with an Index. Is there a way to hide the irrelevant IList methods?
To be able to treat ArraySegment directly like an array, you must cast it to IList with "as". This is described as the proper behavior here:
use of ArraySegment class?
and here:
dotNet ArraySegment Struct
Specifically, Microsoft document says:
If you want to retrieve an element by its index in the ArraySegment
object, you must cast it to an IList object and retrieve it or
modify it by using the IList.Item[Int32] property. The following
example retrieves the element in an ArraySegment object that
delimits a section of a string array.
What's perplexing is that IList has methods like "Remove" and "RemoveAt". You would expect those to not work on an arraysegment cast as a List. I tested this, and in fact calling Remove throws a runtime error. But the compiler doesn't catch the problem.
I'm surprised that Microsoft considered this acceptable behavior in the design of ArraySegment.
I was trying to brainstorm a wrapper class or some way to hide the List methods that shouldn't be called on the ArraySegment as List. But I couldn't come up with anything.
Does anyone have a suggestion on how to fix this?
EDIT: IReadOnlyList has been suggested instead of IList.
IReadOnlyList causes the List to completely read-only, preventing you from modifying the value of elements stored in underlying array. I want to be able to modify the original array values. I just don't want to be able to write list.Remove() or list.Add() since it's clearly wrong and the compiler shouldn't be allowing it.
To anyone who might suggest Span as an alternative:
I am aware of Span, but Span currently has limitations in .NET Framework and Standard. Specifically, it can only be used as a local variable, and thus cannot be passed to other methods.
And to be honest, I actually think Microsoft's IEnumerable heirarchy leaves a bit to be desired -- I can't figure out any way to make an Indexable sequence like List without it offering Add/Remove functionality. ICollection doesn't support Indexing. If anyone has suggestions on that issue itself, I'm all ears.
A:
Turns out, in .NET 4.7.2, the ArraySegment<T> doesn't expose an indexer unless if it's cast to the IList<T> interface, but it does in .NET Core 2.1.
You may cast to the IReadOnlyList<T> interface; note that it doesn't prevent you from changing the contained objects themselves if they are mutable:
The IReadOnlyList<T> represents a list in which the number and order of list elements is read-only. The content of list elements is not guaranteed to be read-only.
So, it only guarantees that the collection itself (the container) is immutable (no adds, removes, replacements). You can't replace an element because the indexer doesn't have a setter.
There's also the ReadOnlyCollection<T> wrapper class (add using System.Collections.ObjectModel;). Also no setter on the indexer though.
If none of these work for you, and you want to implement a wrapper, just create a class that takes in an IList<T> in the constructor, and implement your own indexer. I'd also implement IEnumerable<T>, so that you get LINQ support, and it will also make it work with the foreach loop.
// Add these...
using System.Collections;
using System.Collections.Generic;
//...
public class MyWrapper<T> : IEnumerable<T>
{
private IList<T> _internalList;
public MyWrapper(IList<T> list)
{
_internalList = list;
}
public int Count => _internalList.Count;
// the indexer
public T this[int index]
{
get => _internalList[index];
set => _internalList[index] = value;
}
public IEnumerator<T> GetEnumerator()
{
return _internalList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
And then just pass the array segment to the constructor (without casting).
P.S. If this is some internal code, used in few places only, writing a wrapper may or may not be worth the trouble; it's OK to use an IList<T> as long as its clear what the intention was.
Also, if you don't mind working with a copy of the array that's only limited to the range defined by the array segment, and if the copy operation cost is not a concern, you can call either the ToArray or ToList extension method on the segment. But I suspect you want the original array to be updated and you just need a "window" into a segment.
|
[
"ru.stackoverflow",
"0000083050.txt"
] | Q:
Не работает метод submit
Хочу отменить отправку формы обработчику, пока не будут заполнены все поля. В инпуте пустота, но все равно submit срабатывает.
<script type="text/javascript">
$('#send').submit(function(eventObject){
if($('#name').val() == "" || $('#email').val()=='' || $('#date').val()=='') {
eventObject.preventDefault(); alert('Вы заполнили не все поля');}
});
</script>
Как я заметил, программа вообще во внутрь функции не заходит
A:
Цитата из официального руководства
The submit event is sent to an element
when the user is attempting to submit
a form. It can only be attached to <form> elements.
Надо вешать этот обработчик к форме, а вы похоже к submit-кнопке его вешаете.
|
[
"softwareengineering.stackexchange",
"0000123961.txt"
] | Q:
Alternatives to Professional Version Control
We're teaming up with some non programmers (writers) who need to contribute to one of our projects.
Now they just don't like the idea of using Git (or anything for that matter) for version controlling their work. I think this is because they just don't find it worthwhile to wrap their heads around the twisted concepts of version control. (when I first introduced them to branching and merging -- they looked like I was offending them.)
Now, we're not in a position to educate them or convince them to use it. We're just trying to find alternatives so that we get all their work versioned (which is what we need) -- and they get easy workflow and concentrate on what they do.
I have come up with some ideas...
tell them to save their work as a separate file every time they make some non-trivial change, and then use a diff on our side to just track changes.
write a program (in Python) that implements the "milestones" in CSSEdit in some way.
About the project:
It is a natural language processing system (written in C + Python). We've hired some writers to prepare inputs for the system in different languages. And as we evolve the software, we'd need those writers to make changes to their inputs (articles). Sometimes the changes are very small (a word or two), and other times big.
The reason we need to version control those changes is because every small/big change in the input has the potential to change the system's output dramatically.
A:
when I first introduced them to branching and merging -- they looked
like I was offending them
This is probably because branching and merging are advanced concepts, and infinitely less useful than to simply keep track of the changes.
So why not explain just "commit" (save) and "update"? Two really simple concepts. I'm sure you can explain it in less than 10 minutes.
If you really want to use separate branches and stuff like that, you can do that part yourself without involving them with it.
A:
A rather unorthodox approach would be just use Dropbox. Have the authors save the files in the dropbox directory and you get versioning and backup for free. Plus there is basically no learning curve for the authors.
For git, sounds like in the end you gonna end up providing the authors with the correct branch versions anyway, so just put the git repo in the dropbox and handle the branching and merging for the authors.
A:
Truthfully the answer is in your edit: "We've hired some writers" - sometimes you just have to be bloody minded... they want your money they have to do what you want providing that what you want is not unreasonable.
The argument you make is the argument you've already advanced - we need to be able to do X, Y and Z to make the product work - and in order to do this we need you to do that. We will be as supportive as we can, but for this to work (and therefore for it to continue as an income stream for you, the writer) this has to happen.
I tend to agree that an appropriate Wiki based solution would seem to be a good match - but the challenge here is how to find a compromise between their workflow and your requirements.
I'll repeat the key point - in order for your project to be a success you need the articles to be versioned therefore those who work on the articles have to play by an agreed set of rules, if this doesn't happen you will get burned and by extension so will the writeres.
|
[
"ru.stackoverflow",
"0000579055.txt"
] | Q:
Простой WPF Binding. Будет ли утечка памяти?
Уважаемые гуру, прошу растолковать по привязкам. В учебных статьях "для чайников" вопросы утечек вообще не рассматриваются, а самостоятельный поиск информации по частям привел к тому, что я запутался. Что я нарыл:
Для борьбы с утечками памяти в WPF, нужно привязываться к объектам, реализующим INotifyCollectionChanged. Ок, в случае коллекций, все понятно. Привязываемся через ObservableCollection.
Но как быть с простыми типами данных?
Допустим у нас простая страничка, на которой есть текстовое поле, куда пользователь вводит свое имя. Для работы с этим именем, привяжем его к полю name.
View:
<TextBlock Text="Ваше имя:"/>
<TextBox Text="{Binding name}"/>
ViewModel:
public string name {get; set;}
...
this.DataContext = this;
this.InitializeComponent();
Согласно этой страницы, для борьбы с утечкой, необходимо или реализовать INotifyPropertyChanged на объекте-источнике, либо сделать свойство DependencyProperty. Но я нигде не могу найти простой пример, как это правильно сделать.
Тут, в последнем абзаце, вообще написано:
Если вы используете .NET Framework 4.5, то у вас не будет утечки
памяти
Так как правильно реализовать привязку данных?
A:
В документе, на которые вы ссылаетесь, написано следующее:
This issue occurs if the following conditions are true:
A data-binding path refers to property P of object X.
Object X contains a direct reference or an indirect reference to the target of the data-binding operation.
Property P is accessed through a PropertyDescriptor object instead of a DependencyProperty object or a PropertyInfo object.
Из этих условий необычным является второе: «Object X contains a direct reference or an indirect reference to the target of the data-binding operation».
Если вы программируете с использованием MVVM, ваш объект X скорее всего VM-объект, а целевой элемент привязки — View-объект. В нормальной ситуации объекты VM не имеют права знать о View, и таким образом не должны содержать на него прямых или непрямых ссылок.
Значит, проблема может возникнуть только если у вас View-объект ссылается на другой View-объект. Но свойства UI-объектов обычно являются DependencyProperty, поэтому этот случай тоже в подавляющем большинстве случаев не имеет места.
Что нужно делать?
Если вы производите Binding UI-объекта к другому свойству UI-объекта, имеет смысл обратить внимание на то, является ли то, что вы привязываете, DependencyProperty. В подавляющем большинстве случаев это так и будет.
Если всё же оказывается, что вам кровь из носу нужно забиндить свойство одного UI-объекта на другое свойство, которое не является DependencyProperty (например, как в примере из статьи, которую вы привели:
<StackPanel Name="MyStackPanel">
<TextBlock Text="{Binding ElementName=MyStackPanel, Path=Children.Count}" />
</StackPanel>
в этом примере memory leak возникает и в VS 2015), вам нужно поменять Binding на OneTime: в этом случае всё равно вы не получаете нотификаций об изменении свойства (т. к. INotifyPropertyChanged не реализовано, и свойство не есть DependencyProperty).
Более прагматичный подход — не парьтесь с каждой привязкой, тестируйте ваше приложение при помощи memory profiler'а, и если обнаружите утечку памяти, описанную в статье, почините её как указано в п. 2.
|
[
"stackoverflow",
"0042454144.txt"
] | Q:
NodeJS/AngularJS unable to display information on Webpage
I am following NodeJS and AngularJS (v 1.2.x) app tutorial via Bash on Ubuntu on Windows.
Issues:
Log "I received the data I requested" not displayed in Ubuntu bash shell
Information not displayed on webpage
Results and code:
Ubuntu Shell Result:
Webpage
Controller.js
Server.js
Index.js
A:
You have a space in your tr
Change it to <tr ng-repeat "contact in contactlist">
|
[
"stackoverflow",
"0012927583.txt"
] | Q:
Does Nutch 2.1 still support file segments?
Does Nutch 2.1 still support file segments as the data storage?
I cannot find my answer from the documentation or wiki.
A:
You mean the nutch segments which had part files ? According to me, Nutch 2.0 does NOT have that.
|
[
"stackoverflow",
"0012165558.txt"
] | Q:
Is MultiByteToWideChar reentrant or threadsafe?
Multiple threads in my application will be calling MultiByteToWideChar for converting UTF-8 to wchar_t strings.
I've been unable to find any documentation which states whether this function is re-entrant or thread safe. I want to avoid synchronizing calls to this method if not needed. Does anyone know the answer or how to find it?
A:
The function is thread safe ... but I don't have a definitive link to prove it!
There is some discussion on this thread ... but in general the rule would be that if an API call does not have some specific context (eg. a handle) it is called with or other explicit threading rules (ie. the whole GDI layer) then it should be thread safe.
It would certainly be good to see this more explicitly called out in the documentation though.
|
[
"stackoverflow",
"0040563832.txt"
] | Q:
VB grab text values and save as variables
I was wondering if there is a quicker way to "search" part of a line's string of text and find non-static values and save them to variables?
For instance, I can't really use Substring and search for part of a line because the values in the " " are never the same length.
Example part of the text file that I am reading in:
<I_Sect IDCode="20001" Description="This is desc" Quantity="1000" InclKind="Inc" />
The id names : IDCode Description Quantity and InclKind never change
The values do change: 20001 ... This is desc... etc
Is there a quicker way to search the "" after I do a substring to find the id name and grab how ever long the string between the "" is?
Current code:
Dim list As New List(Of String)()
Dim file As New System.IO.StreamReader(DisplayFile)
While Not file.EndOfStream
Dim line As String = file.ReadLine()
list.Add(line)
End While
file.Close()
Console.WriteLine("{0} lines read", list.Count)
'RichTextBox1.Text = System.IO.File.ReadAllText(DisplayFile)
For counter As Integer = 0 To list.Count
If list(counter).Substring(0, 7) = "<I_Sect" Then
'Do a substring of the line to see if I can locate Description ID string
' .............
Dim desc As String = ' .... [the valve I grab will be "This is desc"]
End If
Next
A:
Using this xml file
<?xml version="1.0" encoding="utf-8" ?>
<root>
<I_SecMain>
<I_SecTop>
<I_SecBrac>
<I_Sect IDCode="20001" Description="This is desc 1" Quantity="10001" InclKind="Inc 1" />
<I_Sect IDCode="20002" Description="This is desc 2" Quantity="10002" InclKind="Inc 2" />
<I_Sect IDCode="20003" Description="This is desc 3" Quantity="10003" InclKind="Inc 3" />
<I_Sect IDCode="20004" Description="This is desc 4" Quantity="10004" InclKind="Inc 4" />
<I_Sect IDCode="20005" Description="This is desc 5" Quantity="10005" InclKind="Inc 5" />
</I_SecBrac>
</I_SecTop>
</I_SecMain>
</root>
You can define a corresponding model you can use to deserialize the file.
Imported namespaces
Imports System.Xml.Serialization
Model
<XmlRoot("root")>
Public Class Root
<XmlElement>
Public Property I_SecMain As I_SecMain
End Class
Public Class I_SecMain
<XmlElement>
Public Property I_SecTop As I_SecTop
End Class
Public Class I_SecTop
<XmlElement>
Public Property I_SecBrac As I_SecBrac
End Class
Public Class I_SecBrac
<XmlElement("I_Sect")>
Public Property I_Sects As List(Of I_Sect)
End Class
Public Class I_Sect
<XmlAttribute>
Public Property IDCode As Integer
<XmlAttribute>
Public Property Description As String
<XmlAttribute>
Public Property Quantity As Integer
<XmlAttribute>
Public Property InclKind As String
End Class
And very simply deserialize the file into strongly typed objects
Dim DisplayFile = "test.xml"
Dim myRoot As Root
Dim mySerializer As New XmlSerializer(GetType(Root))
Using fs As New FileStream(DisplayFile, FileMode.Open)
myRoot = mySerializer.Deserialize(fs)
End Using
which can be iterated over.
For Each isect In myRoot.I_SecMain.I_SecTop.I_SecBrac.I_Sects
Console.WriteLine(
String.Format("ID Code: {0}, Description: {1}, Quantity: {2}, InclKind: {3}",
isect.IDCode, isect.Description, isect.Quantity, isect.InclKind))
Next
From here, it's a matter of defining your model accurately (you didn't post it in your question) and just retrieving properties from the deserialized objects.
Using serialization, it's trivial to write to the file as well, if that's a requirement.
Using fs As New FileStream(DisplayFile, FileMode.Open)
mySerializer.Serialize(fs, myRoot)
End Using
|
[
"stackoverflow",
"0047400955.txt"
] | Q:
Perfect scrollbar not functional with content loaded dynamically using insertAdjacentHTML
I am trying to dynamically load some links from an array(JSON encoded values) as a list inside a div. In my real application this array comes from PHP. I am using insertAdjacentHTML('beforeend', "link content") to set the content.
To style the same I am using "accordion slider" and "Perfect Scrollbar", I have achieved to combine both successfully. I am able to display the links as I want inside the div, but the scroller seems to be disappeared now.
Please check the fiddle here - https://jsfiddle.net/prashu421/2mpL61x7/
If you would check the links that aren't loaded dynamically are scrollable and the scrollbar is displayed there.
I couldn't find any clear reference on the internet for my case.
Any help is greatly appreciated.
Thanks for your consideration.
A:
You're including dynamic HTML on the load event, but initializing the scrollbar on jQuery's $(document).ready() function) which's triggered before the dynamic html load.
So to solve this, put everything in the same function or simply at the end of your document as seen in the code of this fiddle-
https://jsfiddle.net/kumar4215/svhscqcp/
<div id="bloc-accordeon">
<ul class="accordion">
<li id="one" class="files">
<a href="#one">One</a>
<ul class="sub-menu" id="firstClub" style="font-size: 12px;">
<!--Container for dynamically generated links-->
</ul>
</li>
<li id="two" class="mail">
<a href="#two">Two</a>
<ul class="sub-menu">
</ul>
</li>
<li id="three" class="cloud">
<a href="#two">Three</a>
<ul class="sub-menu">
</ul>
</li>
</ul>
</div>
|
[
"stackoverflow",
"0016922679.txt"
] | Q:
Different Colored Markers with JvectorMaps
With JVectorMap, How can I add two sets of markers that are different colors? There's been one other question asked about it and the solution didn't work on JSFiddle. Right now I have markers like and I can attribute types, but I don't know the code that would change the colors of specific types. Any help?
<div id="map"></div>
<script>
$(function(){
$('#map').vectorMap({
map: 'us_aea_en',
zoomOnScroll: true,
hoverOpacity: 0.7,
markerStyle: {
initial: {
fill: '#800000',
stroke: '#383f47'
}
},
markers: [
{latLng: [41.50, -87.37], name: 'Test1 - 2010', type : "chicago"},
{latLng: [39.16, -84.46], name: 'Test2 - 2010'},
{latLng: [39.25, -84.46], name: 'Test3 - 2010'}
]
});
});
</script>
A:
You may use style for different colors:
{latLng: [41.50, -87.37], name: 'Test1 - 2010', style: {fill: 'rgba(0,0,255,0.1)', r:20}},
A:
In the documentation of the plugin it is said:
Each marker is represented by latLng (array of two numeric values),
name (string which will be show on marker's tip) and any marker
styles.
So what we do is the following.
$('#world-map').vectorMap({
markers: [
{ latLng: [38.90, -98.45], name: 'John Doe', style: {r: 8, fill:'yellow'}},
{ latLng: [46.90, -65], name: 'Label name', style: {r: 12, fill:'black'}},
{ latLng: [46.90, -65], name: 'Label name', style: {r: 4, fill:'red'}}
]
});
This way for every marker you create there will be different styles assigned to it.
|
[
"stackoverflow",
"0018738052.txt"
] | Q:
How to add CSS if element has more than one child?
I have td tags and a several div inside td:
<td>
<div class='test'></div>
<div class='test'></div>
</td>
<td>
<div class='test'></div>
</td>
I want to add margin-bottom to div if there are more than one in the td. How can I do this with the css?
A:
You can't directly 'count' total numbers of elements in CSS, so there's no way to only apply the class if there's 2 or more divs (you'd need JavaScript for that).
But a possible workaround is to apply the class to all divs in the td...
td > div {
margin-bottom: 10px;
}
... and then override/disable it with a different style when there's only one element. That indirectly lets you add the style when there's 2+ more child elements.
td > div:only-child {
margin-bottom: 0px;
}
Alternatively you can apply to every div after the first one, if that happens to work for your situation.
td > div:not(:first-child) {
margin-bottom: 10px;
}
Edit: Or as Itay says in the comment, use a sibling selector
td > div + div {
margin-bottom: 10px;
}
A:
Well actually you can do this with css using the nth-last-child selector
FIDDLE
So if your markup was like this:
<table>
<td>
<div class='test'>test</div>
<div class='test'>test</div>
</td>
</table>
<hr />
<table>
<td>
<div class='test'>test</div>
</td>
</table>
CSS
div:nth-last-child(n+2) ~ div:last-child{
margin-bottom: 40px;
}
... the above css will style the last div element only if there exists a container that has at least 2 child divs
Just to see how this works better - here's another example fiddle
A:
td > div:not(:only-child) { margin-bottom: 10px; }
|
[
"stackoverflow",
"0032987273.txt"
] | Q:
Typescript module systems on momentJS behaving strangely
I'm trying to use momentJs from typescript:
depending on what module system I'm using to compile typescript, I find a different behaviour on how I can use momentJs.
When compiling typescript with commonJs everything works as expected and I can just follow momentJs documentation:
import moment = require("moment");
moment(new Date()); //this works
If I use "system" as typescript module system when I import "moment" I am forced to do
import moment = require("moment");
moment.default(new Date()); //this works
moment(new Date()); //this doesn't work
I found a workaround to make them both work regardless of typescript module system used
import m = require("moment")
var moment : moment.MomentStatic;
moment = (m as any).default || m;
I don't like this, and I would like to understand why it behaves like this. Am I doing something wrong? Can anybody explain me what's happening?
A:
This is happening because SystemJS is automatically converting moment to an ES6-style module by wrapping it in a module object, while CommonJS is not.
When CommonJS pulls in moment, we get the actual moment function. This is what we've been doing in JavaScript for a while now, and it should look very familiar. It's as if you wrote:
var moment = function moment() {/*implementation*/}
When SystemJS pulls in moment, it doesn't give you the moment function. It creates an object with the moment function assigned to a property named default. It's as if you wrote:
var moment = {
default: function moment() {/*implementation*/}
}
Why does it do that? Because a module should be a map of one or more properties, not a function, according to ES6/TS. In ES6, the convention for massive external libraries that formerly exported themselves is to export themselves under the default property of a module object using export default (read more here; in ES6/TypeScript, you can import functions like this using the compact import moment from "moment" syntax).
You're not doing anything wrong, you just need to pick the format of your imported modules, and stick to your choice. If you want to use both CommonJS and SystemJS, you might look into configuring them to use the same import style. A search for 'systemjs default import' led me to this discussion of your issue, in which they implement the --allowSyntheticDefaultImports setting.
A:
I did the following:
I installed moment definition file as follows:
tsd install moment --save
Then I created main.ts:
///<reference path="typings/moment/moment.d.ts" />
import moment = require("moment");
moment(new Date());
And I ran:
$ tsc --module system --target es5 main.ts # no error
$ tsc --module commonjs --target es5 main.ts # no error
main.js looks like this:
// https://github.com/ModuleLoader/es6-module-loader/blob/v0.17.0/docs/system-register.md - this is the corresponding doc
///<reference path="typings/moment/moment.d.ts" />
System.register(["moment"], function(exports_1) {
var moment;
return {
setters:[
function (moment_1) {
// You can place `debugger;` command to debug the issue
// "PLACE XY"
moment = moment_1;
}],
execute: function() {
moment(new Date());
}
}
});
My TypeScript version is 1.6.2.
This is what I found out:
Momentjs exports a function (i.e. _moment = utils_hooks__hooks and utils_hooks__hooks is a function, that's quite clear.
If you place a breakpoint at the place I denoted as PLACE XY above, you can see that moment_1 is an object (!) and not a function. Relevant lines: 1, 2
TL;DR: To conclude it, the problem has nothing to do with TypeScript. The issue is that systemjs does not preserve the information that momentjs exports a function. Systemjs simply copy properties of the exported object from a module (a function is an object in JavaScript too). I guess you should file an issue in systemjs repository to find out if they consider it to be a bug (or a feature :)).
|
[
"stackoverflow",
"0060581728.txt"
] | Q:
Get columns of the columns table
How can I get the list of columns of the INFORMATION_SCHEMA.COLUMNS view?
I can get the columns of any table I create using:
select *
from information_schema.columns
where table_name = 'MY_TABLE'
The result set includes multiple columns, such as:
TABLE_CATALOG
TABLE_SCHEMA
TABLE_NAME
COLUMN_NAME
DATA_TYPE
etc.
How can I get the full list of these columns? It seems that the COLUMNS view does not include its columns in itself (as in Oracle, PostgreSQL, or MySQL). If I run:
select *
from information_schema.columns
where table_name = 'COLUMNS'
I get nothing. Maybe I'm searching in the wrong place.
A:
Using sys.dm_exec_describe_first_result_set:
SELECT *
FROM sys.dm_exec_describe_first_result_set(
N'SELECT * FROM INFORMATION_SCHEMA.COLUMNS', NULL, 0);
db<>fiddle demo
|
[
"stackoverflow",
"0010593663.txt"
] | Q:
Ballpark Text Dimensions with Java FontMetrics
I'm currently drawing a string to a canvas with a specified font. I would, however, like to scale this font based on the window size.
Given a target string, how do I find the point size of a particular font face so that printing the target string will be either h units tall, or w units wide? Is there a linear relationship between point size and font dimensions?
I can think of very smelly ways to determine a relative point size (pick an arbitrary size and shrink / grow until the dimensions are within some epsilon of the target), but would rather do it more cleanly.
I want to do this with fonts-only, if possible, and not resort to affine transformations.
A:
For the best metrics, I prefer TextLayout, illustrated here, but deriveFont(), suggested by @StanislavL among the answers here, is surprisingly agile and not at all malodorous.
|
[
"stackoverflow",
"0035249757.txt"
] | Q:
How to setup urls.py to work with app/urls.py and templates in src with Django
Trying to figure out how to setup my own project.
I created a new Django app to make a homepage.
src/home/urls.py:
from django.conf.urls import url
urlpatterns = [
url(r'^$', 'views.index', name='index'),
]
src/home/views.py:
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, "index.html", {})
src/project/urls.py:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^', include('home.urls')),
url(r'^admin/', admin.site.urls),
]
src/templates/index.html:
<h1>Hello World</h1>
The reason this isn't in a templates folder inside of the home app is because I want to use this as my base template eventually for all apps and pages
Error reads:
ImportError at /
No module named 'views'
Using python 3.5 and django 1.9
EDIT*** changed to home.views.index
ERROR now reads:
TemplateDoesNotExist at /
index.html
A:
Make sure you home is a package and you have __init__.py there.
You might also need to change views.index to home.views.index in your urls.py
|
[
"stackoverflow",
"0007292053.txt"
] | Q:
Smooth Coloring Algorithm for the Mandelbrot set on Delphi
I have problems using the smoot coloring algorithm. I just don't get them implemented in my Code.
This is the main code which causes an error after some calculated pixel rows:
g:=StrToInt(Edit3.Text); //maximum iteration count
for x:=0 to Width do
begin
for y:=0 to Height do
begin
zr:=x*(br-ar)/Width+ar;
zi:=y*(bi-ai)/Height+ai;
n:=1;
zr0:=zr;
zi0:=zi;
while (n<g) and (zr*zr+zi*zi<4) do
begin
zrh:=zr;
zr:=zr*zr-zi*zi+zr0;
zi:=zrh*zi+zi*zrh+zi0;
Inc(n) //iterations
end;
n:=Round(n+1-(log2(log2(sqrt(zr*zr+zi*zi))/log2(4)))); //<-- this should smoothen the iterations
Draw_Pixels(n,g,x,y,Image1.Canvas)
end
end;
end;
Henry
A:
If you ever end up with zr == zi == 0, you'll be trying to take log2(0), which is not defined (-inf as a limit).
If zr*zr+zi*zi is ever equal to or less than one, the inner log2 will return 0 or a negative value, which will break the outer log2 (can't take the log of a negative number as long as you're dealing with reals).
(And I don't think that will scale smoothly for values of zr*zr+zi*zi slightly over 1.)
|
[
"stackoverflow",
"0004727770.txt"
] | Q:
android ndk practices
Now with the release of new android NDK, given the fragmentation of android devices, what testing measures one should employ to test over different phones, tablets and/or google tv based devices?
A:
Depending on how you use the NDK, you will only be able to target certain versions of Android. Basic rule is, the simpler the code, the later the version of Android will run it. See the documentation in the NDK and the Android source code for specifics on this. Don't always trust the (scarce) documentation though - read the source code when in doubt. It helps a lot.
That said, a testing policy must include what will be tested, so:
Step 1: Based on your code, decide on which version of Android you can
support.
Step 2: Find out which devices you must target, and which devices you want to target.
Step 3: Make the matrix of device/Android version available and what you can support, for the must category.
Step 4: Based on your investment policy, repeat step #3 for the want category.
Step 5: Get the devices and setup a testing structure.
And, finally, to answer your question:
The problem isn't the testing, the problem is deciding what to support. Good testing measures include testing all the devices you target and provide support for. Excellent testing measures adds the devices you run on, but don't support.
|
[
"stackoverflow",
"0050203339.txt"
] | Q:
PM2 couldn't start keystone
I cant start keystone on pm2. pm2 could not read "COOKIE_SECRET" from .env file.
I did set an environment variable in pm2 config file but I got the error again.
what shall I do ?
A:
First thing you can check is the NODE_ENV variable setup as development or production, or the --env command line that you are using. Reference:
http://pm2.keymetrics.io/docs/usage/environment/
Kindly provide the error message encountered so that there are more information.
Usually one can use "pm2 start keystone.js" to start keystone without problem.
|
[
"stackoverflow",
"0018032488.txt"
] | Q:
C++ Iterator Exception Safety
I have a problem with exception safety and STL containers/iterators.
I assumed for some reason that an iterator of the simple container
std::vector<POD Type>
is not throwing an exception when performing arithmetic operations on it (or deref. it) as long as you stay within the interval [begin(), end()). I tried to look that up in the standard (using N3337) but i have found that no such nothrow guarantees are given (but maybe i missed something!). Also see: May STL iterator methods throw an exception
Until now I wrote quite some code that would be broken in general, taking into account that there are no said nothrow guarantees even for simple containers with reasonable element types.
For example something like the following might still throw an exception (whereby c is a std::vector instance):
for(... i = c.begin(); i != c.end(); ++i) { /* do something here - guaranteed to not throw. */ }
But this incurs exception safety and program stability problems across different STD libraries since you have to know the implementations of the iterator operations as far as I can see.
For example take the clear() function of Boost.Graph's adjacency list (and there are many more such examples within Boost) and suppose the container m_vertices is a std sequence container like std::vector.
inline void clear() {
for (typename StoredVertexList::iterator i = m_vertices.begin(); // begin() and copy assignement does not throw (according to the STD)
i != m_vertices.end(); ++i) // ++i and operator != () might throw
delete (stored_vertex*)*i; // *i might throw
m_vertices.clear(); // will not throw (nothrow per Definition of the STD)
m_edges.clear(); // same
}
This function should be guaranteed to not throw since it is called in the destructor of adjacency_list<...> and it would be reasonable to assume that no clear() function throws, even though I did not find any exception safety guarantees in the docs of Boost.Graph.
I hope you can shed some light onto this exception safety issue and show me what I am missing here. Especially for what kind of iterators arithmetic operations and dereferencing is really not throwing and where such guarantees are defined.
Thanks!
From the C++ STD Paper N3337
23.2.1:10)
Unless otherwise specified (see 23.2.4.1, 23.2.5.1, 23.3.3.4, and 23.3.6.5) all container types defined in this
Clause meet the following additional requirements:
— if an exception is thrown by an insert() or emplace() function while inserting a single element, that
function has no effects.
— if an exception is thrown by a push_back() or push_front() function, that function has no effects.
— no erase(), clear(), pop_back() or pop_front() function throws an exception.
— no copy constructor or assignment operator of a returned iterator throws an exception.
— no swap() function throws an exception.
— no swap() function invalidates any references, pointers, or iterators referring to the elements of the
containers being swapped.
[ Note: The end() iterator does not refer to any element, so it may be
invalidated. —end note ]
A:
Only wide contracts (i.e., operations which can't possibly fail) are given no throw guarantees. All iterator operations have narrow contracts (i.e., they have some precondition), and thus, can fail in arbitrary ways when the preconditions aren't met. Thus, they don't have any exception guarantees, because the undefined behavior preconditions aren't met may result in a given implementation throwing an exception. The behavior of the individual iterator operations are well defined assuming the preconditions are met and the behavior doesn't include throwing any exception: the behavior of the iterator operations is defined in the requirement tables.
That said, in general, you should expect all operations to potentially throw in the first place. To do proper recovery from exception: it is, however, sometimes necessary to know that specific functions won't throw because otherwise the recovery might fail, certain rather basic operations like swapping two objects of a built-in type are defined to not throw.
|
[
"stackoverflow",
"0015441910.txt"
] | Q:
Why does Toolkit.getDefaultToolkit().beep() not work in Windows?
When I try to get a beep by using Toolkit.getDefaultToolkit().beep(), it does not seem to work on any of my Windows computers. I also know someone who has the same problem, but they say it works on other OS's. Does anyone know why?
A:
For me, the problem was that I had "No Sounds" configured (Win7 Pro). After changing this back to "Windows Default", I was able to hear the beep (actually a 'ding') - also when started from within eclipse.
A:
This code works for me on Windows 7, make sure you don't have your sound muted.
import java.awt.*;
public class Beep {
public static void main(String... args) {
Toolkit.getDefaultToolkit().beep();
}
}
You could also just print the ASCII representation for the bell, also works on Windows 7
public class Beep {
public static main(String... args) {
System.out.print("\007"); // \007 is the ASCII bell
System.out.flush();
}
}
|
[
"stackoverflow",
"0044134316.txt"
] | Q:
How do I see "merge events" in history?
I use the GitHub web interface and the git cli. Answers for either or both are appreciated.
Sometimes, when I merge a branch into another branch, I see a commit with a message like "Merge branch 'master' into other_branch" in the GitHub history. But not always. So how do I see all "merge events", inside the history?
Even better if I can get a view with vertical lines showing branches and merges (like a graph).
A:
It's not always possible to recover all merge events, counter-intuitive though that seems. The most likely reason is that, when you (or someone) asked for a merge, a "fast-forward" was possible (and the merge option --no-ff was not given) so no "true merge" was performed. For example:
X -- X -- X -- A <--(master)
\
X -- X -- X -- B <--(branch)
In this case a fast-forward is not possible because the branches have diverged, so after a merge you will see a merge commit.
git checkout master
git merge branch
X -- X -- X -- A -- M <--(master)
\ /
X -- X -- X -- B <--(branch)
but if you had
X --- X --- A <--(master)
\
x --- x --- B <--(branch)
now you created a branch, but there hasn't been any new work on master so the branches haven't diverged. Instead one is just behind the other. If you don't forbid it, a fast-forward will occur when you merge.
git checkout master
git merge branch
X --- X --- A --- x --- x --- B <--(branch)(master)
There is no record of a merge having occurred, and no way to recover the "merge event". (In the local repo where this took place, there is a reflog entry that could be used to figure it out; but reflog entries are temporary and are not shared with remotes, so for all practical purposes you can't count on any record of the merge.)
Moreover, there are lots of people who swear that a linear history is "cleaner" (even if that history ends up made mostly of commits that have never been built and tested), so they deliberately rearrange their commit topology to allow every merge to be a fast-forward. And there are other techniques for combining lines of code that are used in special cases.
So what does it mean for your question?
First, not all merge events are recorded. If you want to make sure your merge events are recorded so that they can be observed later, then you must always merge with the --no-ff option (and without the --squash option).
Second, the git log output will generally show all of the merge events that were recorded. I can't think of a case where history simplification would exclude a merge, but if you're concerned you can add --full-history to the log command. You can even ask to see just the merges (--merges).
You also can get a graphical view of the branches with git log --graph, or by using a gui like gitk.
Note that by default any of the commands I mentioned for viewing commits/merges will only show those reachable from your currently-checked-out commit (HEAD). If you want to see everything, specify --all; if you want to see everything reachable from a list of branches, list the branches.
|
[
"engineering.stackexchange",
"0000033452.txt"
] | Q:
Distinguish between dead center and live center
Distinguish between dead center and live center in a center lathe tool when this terms are used in the context of work holding in a lathe
A:
A center holds the work during rotation at the tailstock end of the lathe. A live center is mounted in bearings and rotates with the work, while a dead center does not rotate - the work rotates about it.
Live center Rotates while dead centre center does not rotate..
|
[
"stackoverflow",
"0035271993.txt"
] | Q:
how to wait for a non-child process with winapi?
I read:
How to wait for a process to finish C++
How to use win32 CreateProcess function to wait until the child done to write to file
Code snippet:
HANDLE hProcess = OpenProcess(SYNCHRONIZE, TRUE, inProcessID);
if (NULL == hProcess)
{
WaitForSingleObject(hProcess,INFINITE);
}
I've tried WaitForSingleObject and WaitForSingleObjectEx, neither are actually waiting.
For example assume notepad is running and I want to wait for it to be closed by some user. What shall I do ?
A:
From the documentation for OpenProcess:
If the function succeeds, the return value is an open handle to the
specified process.
If the function fails, the return value is NULL. To get extended error
information, call GetLastError.
So your if statement should be:
if (NULL != hProcess) ...
|
[
"stackoverflow",
"0026193531.txt"
] | Q:
fancybox open gallery with doubleclick
Is there a way to open a gallery with double-clik instead of single click ?
$(document).ready(function() {
$('.fancybox').click(function (e) {
e.preventDefault();
});
$('.fancybox').dblclick( function(){
$(".fancybox").fancybox({
openEffect : 'none',
closeEffect : 'none',
loop: false,
padding : 0,
});
});
});
<a title="" href="http://url.com/my-image-big.jpg" rel="gallery1" class="fancybox">
<img src="my-image-small.jpg">
</a>
<a title="" href="http://url.com/my-image-big.jpg" rel="gallery1" class="fancybox">
<img src="my-image-small.jpg">
</a>
....
This obviously doesn't work as expected, but is there something that will work ?
A:
First you need to manually build your gallery before you can fire it after a double-click event.
To build your gallery on-the-fly, you need to use .each() to also bind the index of each element so the gallery opens from the double-clicked element instead of the first.
Also, you can bind several events using jQuery .on() so try this :
var gallery = []; // array of gallery elements
jQuery(document).ready(function ($) {
$(".fancybox").each(function (i) {
gallery.push(this.href); // push element to the array
// bind your click and double-click events
$(this).on({
click: function (event) {
event.preventDefault();
},
dblclick: function (event) {
$.fancybox(gallery, {
// API options
padding: 0,
index: i // starts gallery from (double) clicked element
});
}
});
});
}); // ready
See JSFIDDLE
|
[
"stackoverflow",
"0008985602.txt"
] | Q:
getting the foreign key in Yii
I have the database like
======= Group ========
id
name
======= Member ========
id
group_id
firstname
secondname
membersince
Now in my Group Controller file I have used the action update to update the models
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$member = Member::model()->findByPk($_GET['id']);
if(isset($_POST['Group']))
{
$model->attributes=$_POST['Group'];
if($model->save())
{
$member->attributes = $_POST['Member'];
$member->group_id = $model->id;
if($member->save())
{
$this->redirect(array('view','id'=>$model->id));
}
}
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
'member'=>$member,
));
}
Now as I have two model Group and Member , and in group controller file I am saving member attributes. So my problem is when I am using this line
$member = Member::model()->findByPk($_GET['id']);
for getting the group_id from table member where I can get the complete fields for the group. So can some one tell me how o get the group_id from that table.I searched the documntationbut not got any field like findByFk. So pls guide me.
A:
You can use findByAttributes()
$member = Member::model()->findByAttributes(array('group_id'=>$_GET['id']));
|
[
"stackoverflow",
"0055418197.txt"
] | Q:
hive on spark - why doesn't 'select *' spawn spark app/executors?
I have setup Hive (v2.3.4) on Spark (exec engine).
This launches a spark app/executors:
select count(*) from s.t where h_code = 'KGD78' and h_no = '265'
Why doesn't this launch a spark app/executors:
select * from s.t where h_code = 'KGD78' and h_no = '265'
A:
This - the 2nd case - is due to the not so well-known "hive.fetch.task.conversion" parameter.
Depending on how set, Hive can launch a single "fetch task" instead of a Map Reduce job even with a filter i.e. where clause.
If you select * or a non-partitioned column it will launch a fetch task instead of an MR-job - single thread. Single thread is not always a good thing. The count(*) should speak for itself, you need to a lot of processing potentially, the second case can be seen like a cursor.
You can change parameter to "minimal" or "none" in hive-site.xml to obviate this type of processing.
Well spotted.
|
[
"stackoverflow",
"0005139683.txt"
] | Q:
url into UITextField
I have a UIWebView and UITextField in my view but am facing a problem.
The problem is how do I replace the URL of the web page in UITextField automatically, as I surf through different web pages?
A:
Use the following property of the UIWebView instance:
@property(nonatomic, readonly, retain) NSURLRequest *request
So you can get the current NSURLRequest associated with the web view by:
NSURLRequest* urlRequest = myWebView.request;
You can then get the associated instance of NSURL using the following instance method:
- (NSURL *)URL
So you can now get the NSURL object form the UIWebView with the following code:
NSURL* url = [myWebView.request URL];
To convert this to a string you can use either the absoluteString or relativeString instance methods of NSURL. For this example I'll use absoluteString.
NSString* urlString = [[myWebView.request URL] absoluteString];
Now we can set the the text of the UITextField using the simple text property:
myTextField.text = [[myWebView.request URL] absoluteString];
So now all we need to do is ensure that the previous line of code gets called at the correct time in order to update the text field with the url text whenever the page changes. To do this, we need to use a class which is a delegate of the UIWebView (and thus conforms to the UIWebViewDelegate protocol). If you're unsure about how to use delegates I strongly suggest you do some reading of the delegate design patterns and Apple Developer documentation, as it's used throughout iOS development.
In your UIWebViewDelegate class, you need to implement the following method as follows:
- (void)webViewDidStartLoad:(UIWebView *)webView
{
myTextField.text = [[myWebView.request URL] absoluteString];
}
This will ensure the text field always displays the url of the page that last started to load (there are other UIWebViewDelegate methods if you'd rather the text field be updated at a different time).
Hope this helps.
|
[
"stackoverflow",
"0029927262.txt"
] | Q:
Pass checkbox value to controller from GSP in Grails
I've a checkbox in my Grails application:
<g:checkBox name="reservationAvailable" value="${cafeeInfo.isReservationAvailable}"/>
It must be uncheked if isReservationAvailable boolean-value is false and checked if it's true.
When I click on unchecked checkbox, it become checked, then I send a form, but in logs of controller I get false checkbox value. When I update view page, checkbox become empty again.
Using parsing such as:
oldCafeeInfo.isReservationAvailable = Boolean.parseBoolean(params['reservationAvailable'])
doesn't solve my issue.
A:
I noticed, checkbox return "on" string, when it's checked. So available to compare checkbox parameter in response with "on"-constant.
|
[
"stackoverflow",
"0033955848.txt"
] | Q:
c++ minimum value of vector greater than another value
I have a vector of doubles. I wish to find both:
The minimum value in the vector that is greater than (or equal to) a value x.
The maximum value in the vector that is less than (or equal to) a value x.
E.g. If I have a vector:
std::vector<double> vec = {0, 1.0, 3.0, 4.0, 5.0};
and a value
x = 2.6;
I wish to find 1.0 and 3.0.
What is the most efficient way of doing this?
I have something like:
double x1, x2; // But these need to be initialised!!!
double x = 2.6;
for (i = 0; i < vec.size(); ++i)
{
if (vec[i] >= x && vec[i] < x2)
x2 = vec[i];
if (vec[i] <= x && vec[i] > x1)
x1 = vec[i];
}
But how can I initialise x1 and x2? I could make x2 the maximum of the vector and x1 the minimum, but this requires an initial pass through the data. Is there any way to do this more efficiently?
EDIT:
A couple of assumptions I think I can/cannot make about the data:
There are no negatives (i.e. the minimum possible number would be 0)
It is not necessarily sorted.
A:
You can use std::lower_bound :
#include <iterator>
#include <algorithm>
template<class ForwardIt, class T>
std::pair<ForwardIt, ForwardIt> hilo(ForwardIt first, ForwardIt last, T const &value)
{
if (first != last)
{
auto lb = std::lower_bound(first, last, value);
auto prelbd = std::distance(first, lb) - 1;
if (lb == last) return{ std::next(first, prelbd), last };
if (!(value < *lb)) return{ lb, lb };
if (lb == first) return{ last, first };
return{ std::next(first, prelbd), lb };
}
return{ last, last };
}
Which can be used like:
std::vector<double> vec = { -1.0, -1.0, 0.0, 1.0, 3.0, 3.0, 3.0, 3.0, 4.0, 5.0, 5.0 };
// if not ordered
//std::sort(vec.begin(), vec.end());
double x = 5.0;
auto b = hilo(vec.begin(), vec.end(), x);
if (b.first != vec.end())
{
std::cout << "First index: " << std::distance(vec.begin(), b.first)
<< "(value " << *b.first << ")\n";
}
if (b.second != vec.end())
{
std::cout << "Second index: " << std::distance(vec.begin(), b.second)
<< "(value " << *b.second << ")\n";
}
|
[
"tex.stackexchange",
"0000091686.txt"
] | Q:
Preventing page breaks from occurring in bibliography items
Using Bibtex and Natbib, does anyone know how to prevent a pagebreak from occurring mid-item?
I would like the bibliography to either:
Put an entire record on a given page, or
Carry the record over to the following page.
I DONT want the bibliography to:
Break a record halfway through the actual record so that part is on one page, and part on the next.
My bibliography has 6+ pages of records, so I am talking about breaks midway through an INDIVIDUAL record, not through the actual bibliography, which is inevitable and perfectly fine.
My bibliography is in a multicol environment, sample to follow:
In the above, you can see that item 186 and 212 are not complete, therefore, would like them to start on the next column and next page respectively.
MWE for the bibliography as follows:
\bibliographystyle{BSTFILE} %my style file.
\newcommand*{\doi}[1]{\href{http://dx.doi.org/\detokenize{#1}}{\raggedright\mybibdoicolor{DOI: \detokenize{#1}}}} %format DOI's
\setlength{\bibsep}{0.0pt} %separation
\def\mybibfontsize{\small} %fontsize
\def\mybibnumbercolor{gray} %define number color
\renewcommand{\bibnumfmt}[1]{\color{\mybibnumbercolor}[\textbf{#1}]} %change color of number
\addcontentsline{toc}{chapter}{References} %add to toc
\begin{multicols}{2}{
\mybibfontsize\bibliography{BIBLIOGRAPHY}
}
\end{multicols}
A:
Typically bst files provides definition for the various entry type where the first call is to the function output.bibitem and the last on to the function fin.entry. Thus to wrap whole \bibitems in minipage we can add hooks to such functions. The code below illustrates the changes.
FUNCTION {output.bibitem}
{ newline$
"\begin{minipage}{\textwidth}" write$
newline$
"\bibitem[{" write$
label write$
")" make.full.names duplicate$ short.list =
{ pop$ }
{ * }
if$
"}]{" * write$
cite$ write$
"}" write$
newline$
""
before.all 'output.state :=
}
FUNCTION {fin.entry}
{ add.period$
write$
newline$
"\end{minipage}" write$
newline$
}
We introduced
newline$
"\begin{minipage}{\textwidth}" write$
at the begin of the function output.bibitem and
"\end{minipage}" write$
newline$
at the end of the function fin.entry.
A:
One way to achieve (most of) your objective is to modify the thebibliography environment to disallow typographic widows and orphans. By default, the "widow" and "orphan" (TeX's term: "club") penalty parameters are set to a value of 4000 in bibliography environments. By setting the corresponding parameters to 10000 (the maximum meaningful value for a TeX penalty parameter), you can essentially forbid "widows" and "orphans" from occurring. Incidentally, if you take this approach, I recommend also using the \raggedbottom directive, as otherwise the whitespace between consecutive bib entries may become excessively large.
Note that this approach will prevent page breaks from occurring within bibliography items that span three or fewer lines. It will still permit an entry of four or more lines to be broken across pages -- as long as the first and second part each have at least two lines. This approach seems like a reasonable compromise between (i) wanting to keep the information of each bibliographic contained on one page and (ii) wanting to keep the heights of the text block reasonably uniform across columns and pages. Hopefully, most of your bib entries span three or fewer lines -- and will thus not be broken up anymore across pages and/or columns.
\documentclass{article}
\usepackage{etoolbox}
\patchcmd{\thebibliography}{\clubpenalty4000}{\clubpenalty10000}{}{}
\patchcmd{\thebibliography}{\widowpenalty4000}{\clubpenalty10000}{}{}
% rest of preamble
\begin{document}
% the document itself
\clearpage
\raggedbottom
\bibliography{<mybibfile(s)>}
\end{document}
|
[
"stackoverflow",
"0044931337.txt"
] | Q:
app:layout_marginBottom is not working well with android constraint layout
Is there any reason why the following layout_marginBottom is not working?
However, if I use layout_marginTop on the second view it does work well
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ade4ad">
<TextView
android:id="@+id/first"
android:layout_width="90dp"
android:layout_height="40dp"
app:layout_marginBottom="10dp"
android:background="#000"/>
<TextView
android:id="@+id/second"
android:layout_width="90dp"
android:layout_height="40dp"
android:background="#fff"
app:layout_constraintTop_toBottomOf="@+id/first"/>
</android.support.constraint.ConstraintLayout>
A:
In order to
android:layout_marginBottom="20dp"
work well, you should use
app:layout_constraintBottom_toBottomOf="parent"
A:
Layout top/bottom margin works only when:
constraints in the same direction need to connect with their next neighbor child, like a unidirectional linked list.
last constraint in the direction must be set.
In your case, you need to set "layout_constraintBottom_toXXXXX" for each view in the chain, and last view set bottom to parent.
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ade4ad">
<TextView
android:id="@+id/first"
android:layout_width="90dp"
android:layout_height="40dp"
app:layout_marginBottom="10dp"
app:layout_constraintBottom_toTopOf="@+id/second"
android:background="#000"/>
<TextView
android:id="@+id/second"
android:layout_width="90dp"
android:layout_height="40dp"
app:layout_marginBottom="10dp"
app:layout_constraintBottom_toTopOf="@+id/third"
android:background="#fff"/>
<TextView
android:id="@+id/third"
android:layout_width="90dp"
android:layout_height="40dp"
android:background="#fff"
app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>
Moreover, reverse dependency is not required except you want "layout_marginTop" works.
A:
you can use that trick, create a space bellow, align to parent bottom
<Space
android:id="@+id/space"
android:layout_width="wrap_content"
android:layout_height="80dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
and align your view on top of the space
app:layout_constraintBottom_toTopOf="@+id/space"
like so
<TextView
android:id="@+id/howNext"
style="@style/white_action_btn_no_border"
android:layout_width="344dp"
android:layout_height="60dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="@string/got_it_next"
app:layout_constraintBottom_toTopOf="@+id/space"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
|
[
"stackoverflow",
"0042493111.txt"
] | Q:
Django error: Reverse for 'details' with arguments '()' and keyword arguments
Here is part of my django app and I want to create link with get_absolute_url but I get an error:
Reverse for 'details' with arguments '()' and keyword arguments '{'slug': 'product'}' not found. 0 pattern(s) tried: []
My model:
class PortfolioItem(models.Model):
name_item = models.CharField(max_length=120)
slug = models.SlugField(unique=True)
date_from = models.DateField('date from')
date_to = models.DateField('date to')
description = models.TextField()
author = models.ForeignKey(User)
def __str__(self):
return self.name_item
def get_absolute_url(self):
return reverse('details', kwargs={"slug": self.slug})
Here is my view:
class PortfolioDetail(DetailView):
model = PortfolioItem
template_name = "portfoliodetail.html"
Here is my url:
urlpatterns = [
url(r'^$', PortfolioList.as_view(), name='home'),
url(r'^portfolio/(?P<slug>\w+)/$', PortfolioDetail.as_view(), name='details'),
]
Here is an template:
<ul>
{% for i in portfolioitem_list %}
<li><a href="{{ i.get_absolute_url }}">{{ i.name_item }}</a></li>
{% endfor %}
</ul>
A:
You need to include the namespace when referencing the url
return reverse('portfolio:details', kwargs={"slug": self.slug})
|
[
"stackoverflow",
"0043709135.txt"
] | Q:
How to create buttons and alow specifying any string
Is there a way to show a question, with buttons, and allow the user to wither pick one of the buttons or specify a different answer?
For instance, have the bot ask: "how can I help you today?"
the specify buttons with: "Get on a diet, find a good hotel, learn English" and then let the user either pick one of these, or just way something different such as: "I would like to get to the moon".
We are currently using:
PromptDialog.Choice(context, OnMenuOptionSelected, m_requestTypes, "Here's what I can do for you", descriptions: m_requestTypes.Select(t => t.GetDescription()));
In case the user types in text that does not match the buttons it would show the question again.
A:
Definitely doable but not with the out-of-the-box PromptChoice. What you would have to do is to inherit from it, override the TryParse and add your custom logic, to either pass-through any response you receive or just the ones you want.
The CancelablePromptChoice from the ContosoFlowers sample shows this approach, in this case, to accept terms to quit from the PromptChoice.
|
[
"stackoverflow",
"0058780952.txt"
] | Q:
What is the difference between a "unit" quaternion and and "identity" quaternion
I have been using the guide at www.opengl-tutorial.org/intermediate-tutorials/tutorial-17-quaternions/ for learning OpenGL. This guide says that...
glm::quat q;
...creates an identity quaternion (no rotation).
Experimentation shows that q = [0, 0, 0, 0]. Using this as the parent orientation of the root bone causes none of the bones to rotate at all. They lose all rotation.
The guide says that...
A quaternion is a set of 4 numbers, [x y z w], which represents rotations the following way:
// RotationAngle is in radians
x = RotationAxis.x * sin(RotationAngle / 2)
y = RotationAxis.y * sin(RotationAngle / 2)
z = RotationAxis.z * sin(RotationAngle / 2)
w = cos(RotationAngle / 2)
... and ...
[0 0 0 1] (w=1) means that angle = 2*acos(1) = 0, so this is a unit quaternion, which makes no rotation at all.
I have been experimenting with a skeleton system where each bone inherits its parents' orientation before applying its own rotations on top of that.
If I use an "identity" quaternion as the "parent" orientation for the root bone, then none of the bones are rotated at all. If I use the "unit" rotation all is well.
When I set a bone's initial orientation to either the "identity" or "unit" quaternion it displays as I want to. However when I convert user entered Euler angles to an orientation I get a 180 degree rotation. The conversion I did was:
glm::vec3 eulers(glm::radians(pose.lng_rotate),
glm::radians(pose.lat_rotate),
glm::radians(pose.att_rotate));
pose.orientation = glm::quat(eulers);
Note: I use "lng", "lat", and "att" rotate here because by the time a bone has inherited a parent rotation the "x" axis is probably no longer the "x" axis any more.
The last weird thing I noticed was that I used glm::mat4_cast on each type of quaternion and then multiplied by an identity glm::vec4. The "identity" quaternion left the vector unrotated, but the "unit" quaternion caused the vector to invert (multiply by -1) the x and y components of the vector.
I want to understand quaternions better, especially with respect to their use in code.
Conceptually, how is a "unit" quaternion different to an "identity" quaternion?
Where should I use a "unit" quaternion and where should I use an "identity" quaternion?
Am I just being confused by a badly written guide?
A:
Unit and identity quaternions are the same thing. The guide is badly written and confusing.
glm::quat q; does NOT create an identity quaternion. It creates an invalid quaternion. The best way to create an identity quaternion is either by glm::quat q(glm::vec3(0.0, 0.0, 0.0)); or by glm::quat q(1.0, 0.0, 0.0, 0.0);. The first generates the quaternion based on a vector of all zero Euler rotations. The second explicitly initialises it to the identity quaternion.
Note that although quaternions are often described as [x y z w], they are stored and initialised as (w, x, y, z).
|
[
"math.stackexchange",
"0003070967.txt"
] | Q:
Properties of laplace type transform of $t^{\alpha - 1}$
Let $p>2, \frac{1}{p} < \alpha < 1- \frac{1}{p}$ and define $g_\alpha(t) := t^{\alpha - 1} \chi_{[1, \infty]}$. Then $g_\alpha \in L^p(\mathbb R)$. Define $$f(z) := \int_1^\infty g_\alpha(t) \exp(-izt) \, dt.$$
for $z\in \mathbb C, \operatorname{Im }z <0.$ Then:
$a)$ $f$ is holomorphic in the lower half plane,
$b)$ The limit $$f_0(x):= \lim_{\substack{y\to 0 \\ y < 0}} f(x+iy)$$ exists for all $x\neq 0$,
$c)$ $f(z)$ does not satisfy an estimate of the form $$\forall \epsilon >0: \quad \lvert f(z) \rvert \leq C_\epsilon \exp((1+\epsilon)\lvert z \rvert),$$
$d)$ $f_0$ is not $p$-integrable in any neighbourhood of $0$.
I managed to show $a)$ using Lebesgue's theorem on interchanging derivative and integral sign. However, I am unsure with the other assertions, especially $c)$ and $d)$: How does one estimate the integral from below? And how I can I show something about $f_0 $ if I don't explicitly know it? Any help appreciated!
A:
First we prove that
$$\tag{1}f(z) := \int_1^\infty t^{\alpha-1} e^{-izt} \, \mathrm{d} t$$
is convergent (as an improper Riemann integral) for all $z = x-iy$ with $x \ne 0$ and $y >0$. More presioulsy, the convergence is uniform if $|x| \ge x_0$ for fixed $x_0>0$. Thus (1) defines a continuous function and we have for $x \ne 0$ that
$$\tag{2}f_0(x) = \int_1^\infty t^{\alpha-1} e^{-ixt} \, \mathrm{d} t$$
Prove: For any $z= x-iy$ with $|x| \ge x_0$ and $y \ne 0$ we have with $1 \le a < b$ that
\begin{align}
\tag{3}\int_a^b t^{\alpha-1} e^{-izt} dt = \frac{1}{iz} ( a^{\alpha-1} e^{-iza} - b^{\alpha-1} e^{-izb}) - \frac{\alpha-1}{iz} \int_a^b t^{\alpha-2} e^{-izt} dt.
\end{align}
The last line can be bounded by
$$\frac{1}{x_0} (a^{\alpha-1} + b^{\alpha-1}) +\frac{1-\alpha}{x_0} \int_a^b t^{\alpha-2} dt \le \frac{2}{x_0} a^{\alpha-1} $$
and thus (3) is a Cauchy sequence and thus convergent. In fact, it is (uniformly) convergent and thus continuous. (The whole argument is also known as Dirchlet's test, see for example here.)
Prove of (c) and (d): So we have shown (b). With the help of the explicit identity (2) we can also verify (c) and (d). In fact, we have (after coordinate of change) the identity
$$f_0(x) = x^{-\alpha} \int_x^\infty s^{\alpha-1} e^{-is} \, \mathrm{d} s.$$
Since the integrand is locally integrable (also in $s=0$) the function
$$g(x) := \int_x^\infty s^{\alpha-1} e^{-is} \, \mathrm{d} s$$
is continuous in $x=0$ with
$$\tag{4}g(0) = \int_0^\infty s^{\alpha-1} e^{-is} \, \mathrm{d} s.$$
Thus, it remains to show that $g(0) \ne 0$. Here we use the integral representation of (4). In fact, (4) is related to the Gamma function. One representation of the Gamma function (which was proven by Euler by using a contour shift argument) is
$$\Gamma(w) = e^{i \pi w /2} \int_0^\infty s^{w-1} e^{-is} \, \mathrm{d} s$$
if $0 < \mathrm{Re}(w) < 1$. Hence
$$g(0) = e^{-i \alpha \pi/2} \Gamma(\alpha) \neq 0.$$
All in all, we see that
$$\tag{5} f_0(x) \sim_\alpha x^{-\alpha} \quad (\text{for} \ x \rightarrow 0) $$
up to an non-zero constant (depending on $\alpha$).
c) can not hold, because c) would imply that $f_0$ is bounded. (5) implies that $f_0$ is not $p$-integrable (note that $\alpha p >1$) in any neighbourhood of $0$.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.