text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Cos'è la "collamidina"?
Nel romanzo Pane e tempesta di Stefano Benni ho letto questa frase:
La sorella di Carmela, Marcella la cartolaia, sexy e odorosa di quaderni freschi e collamidina.
Non so cos'è la "collamidina", ma dal contesto immagino fosse qualche prodotto di cartoleria. Non ho trovato il significato di questo vocabolo in nessuno dei dizionari che ho consultato e neanche in altri siti web. Potreste spiegarmelo?
A:
La collamidina era un prodotto di cartoleria, una colla in pasta dal caratteristico odore di mandorla utilizzata negli anni '30 e '40, ad esempio, come collante per le figurine dei calciatori.
Da Saltatempo di Stefano Benni:
Una volta che lui aveva lasciato l'album su una panchina, scaldai la
collamidina con un fiammifero e staccai Ghigghia della Roma, che era una figurina rarissima, non l'aveva nessuno.
Qui puoi vedere la sua confezione caratteristica del tempo
| {
"pile_set_name": "StackExchange"
} |
Q:
Communicating Via serial port with GSM modem
I am using a EVB for siemens MC45 GSM modem. Itried to send At commands to it via serial port with Hyperterminal in windows (both Xp and 7). But the hyperterminal window is showing that I am connected but when I type something it doesnot show my writings. and no response from the GSM modem is received.
What Can I do ?
A:
The problem is with your hyper terminal settings when you are connecting with the modem.
Use these settings: Baud rate:9600 data bits:8 stop bits:1 parity bits: none flow control:none Should work now. Also check whether you are communicating with the correct port
| {
"pile_set_name": "StackExchange"
} |
Q:
this inside prototype function equal to window instead of object instance
In the following code in HeadDirective.prototype.link, this is equal to the global window object rather than the HeadDirective instance. My understanding is that the value of this inside a prototype function is the containing object itself.
var HeadDirective = (function () {
function HeadDirective($rootScope, $compile) {
this.$rootScope = $rootScope;
this.$compile = $compile;
this.restrict = 'E';
}
HeadDirective.prototype.link = function (scope, elem) {
var html = '<link rel="stylesheet" ng-repeat="cssUrl in routeStyles" ng-href="{{cssUrl}}" />';
elem.append(this.$compile(html)(scope));
scope.routeStyles = [];
this.$rootScope.$on('$routeChangeStart', function (e, next, current) {
if (next && next.$$route && next.$$route.css) {
if (!Array.isArray(next.$$route.css)) {
next.$$route.css = [next.$$route.css];
}
angular.forEach(next.$$route.css, function (sheet) {
scope.routeStyles.push(sheet);
});
}
});
this.$rootScope.$on('$routeChangeSuccess', function (e, next, current) {
if (current && current.$$route && current.$$route.css) {
if (!Array.isArray(current.$$route.css)) {
current.$$route.css = [current.$$route.css];
}
angular.forEach(current.$$route.css, function (sheet) {
scope.routeStyles.splice(scope.routeStyles.indexOf(sheet), 1);
});
}
});
};
return HeadDirective;
})();
directives.directive('head', [
'$rootScope', '$compile', function ($rootScope, $compile) {
return new HeadDirective($rootScope, $compile);
}]);
The above code was generated from the following TypeScript:
class HeadDirective implements ng.IDirective {
constructor(private $rootScope: ng.IRootScopeService, private $compile: ng.ICompileService) {}
link(scope: IScope, elem: JQuery): void {
var html = '<link rel="stylesheet" ng-repeat="cssUrl in routeStyles" ng-href="{{cssUrl}}" />';
elem.append(this.$compile(html)(scope));
scope.routeStyles = [];
this.$rootScope.$on('$routeChangeStart', (e: ng.IAngularEvent, next?: IRoute, current?: IRoute): any => {
if(next && next.$$route && next.$$route.css){
if(!Array.isArray(next.$$route.css)){
next.$$route.css = [next.$$route.css];
}
angular.forEach(next.$$route.css, (sheet: string) => {
scope.routeStyles.push(sheet);
});
}
});
this.$rootScope.$on('$routeChangeSuccess', (e: ng.IAngularEvent, next?: IRoute, current?: IRoute): any => {
if(current && current.$$route && current.$$route.css){
if(!Array.isArray(current.$$route.css)){
current.$$route.css = [current.$$route.css];
}
angular.forEach(current.$$route.css, (sheet) => {
scope.routeStyles.splice(scope.routeStyles.indexOf(sheet), 1);
});
}
});
}
restrict = 'E';
}
directives.directive('head', ['$rootScope','$compile', ($rootScope: ng.IRootScopeService, $compile: ng.ICompileService): ng.IDirective =>{
return new HeadDirective($rootScope, $compile);
}]);
According to the latest TypeScript language specification:
The type of this in an expression depends on the location in which the reference takes place:
In a constructor, instance member function, instance member accessor, or instance member variable initializer, this is of the class instance type of the containing class.
In a static member function or static member accessor, the type of this is the constructor function type of the containing class.
In a function declaration or a standard function expression, this is of type Any.
In the global module, this is of type Any.
In all other contexts it is a compile-time error to reference this.
The TypeScript language specification is quite clear. Inside a member function (which is compiled into a prototype function), this refers to the class instance. This is obviously not what I'm seeing.
Any ideas? Could Browserify be interfering with this?
A:
The this keyword is highly contextual. If a method is called by an event, this will be the object that is the event target, for example.
You can get around this problem by shimmying this into a variable, or by using the JavaScript call (or apply) methods to bind the scope of this.
Short example... here is the premise:
class MyClass {
constructor(private myProp: string) {
}
myMethod() {
alert(this.myProp);
}
}
var myClass = new MyClass('Test');
// 'Test'
myClass.myMethod();
// undefined
window.setTimeout(myClass.myMethod, 1000);
Solution One - Arrow Syntax
In TypeScript the arrow syntax will shimmy this into a variable called _this automatically for you and substitute usages inside the arrow function... So this will solve the undefined issue above and instead alert Test.
class MyClass {
constructor(private myProp: string) {
}
public myMethod = () => {
alert(this.myProp);
}
}
Solution Two - Call Method
You can use the call method to replace the contextual this with any object you like, in the example below we reset it to be the myClass instance.
This works whether you are writing TypeScript or plain JavaScript... whereas the first solution is really a TypeScript solution.
window.setTimeout(function() { myClass.myMethod.call(myClass) }, 1000);
Or to be shorter (to be clear, the use of the arrow function here has nothing to do with scope - it is just a shorter syntax arrow functions only affect scope if you have this inside of them):
window.setTimeout(() => myClass.myMethod.call(myClass), 1000);
| {
"pile_set_name": "StackExchange"
} |
Q:
WebRTC getUserMedia() works only on Firefox
I'm working on a mobile web project that needs to access the camera and take a photo and then manipulate it. The problem is that we need to take the photo directly from the browser, and not open the native camera app to take it.
Ok, I use WebRTC for this task. I access to getUserMedia() and play a "video" that is the real time camera view. This task is for Android and iOS.
This works perfectly on Firefox. I assume that in Safari this will be impossible to achieve since getUserMedia() is still not supported by this browser, but Google Chrome have support but I'm unable to make it work on Chrome.
The problem on Chrome seems to be a bug that user is unable to select rear or front camera, so the image never displays, it always is a black image.
My code is very simple, I take it from https://davidwalsh.name/browser-camera but theorically it works on all browsers, but I can't make it work on Chrome. This is the code:
<video id="video" width="480" height="640" autoplay controls></video>
<button id="snap">Capture</button>
<canvas id="canvas" width="480" height="740"></canvas>
<script>
// Grab elements, create settings, etc.
var video = document.getElementById('video');
var i = 0;
// Get access to the camera!
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// Not adding `{ audio: true }` since we only want video now
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
});
}
else if(navigator.getUserMedia) { // Standard
navigator.getUserMedia({ video: true }, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia({ video: true }, function(stream){
alert(window.webkitURL);
alert(window.webkitURL.createObjectURL(stream));
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
} else if(navigator.mozGetUserMedia) { // Mozilla-prefixed
navigator.mozGetUserMedia({ video: true }, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// Elements for taking the snapshot
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('video');
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
});
</script>
How can I make it work on Chrome? How can I make that Chrome ask to user what camera he needs to use (rear / front)? I've found over internet a user that tells Chrome has a bug selecting the camera, so I think this is the problem.
Note that on Chrome Desktop it works perfectly, since there is only one camera and has not to delegate on the user to choose what camera should use. But on mobile devices with two cameras is impossible to choose how.
Thank you.
I'm not using polyfills. The duplicate mark is not solving my issue. I need some help with this. I need a canonical answer with a solution to the problem. Thank you for your time! I offer a bounty.
A:
Are you deploying on https? Chrome does not allow getUserMedia on http pages for security reasons.
See also this sample for enumerating and selecting cameras. The facingmode constraint you're asking about is unfortunately broken right now.
A:
To chose the camera add a constraint paramater with facingMode set to "user" or "environment". To let the user chose don't add these details.
var myConstraints = {
audio: false,
video: {
facingMode: "user"
}
};
see https://w3c.github.io/mediacapture-main/#dom-mediadevices-getusermedia
The new API will become Promised based:
navigator.getUserMedia(myConstraints).then(function(stream) {
video.srcObject = stream;
video.play();
}).catch(errBack);
To use a future proof API and make it work now you can use a polyfill like https://github.com/webrtc/adapter
| {
"pile_set_name": "StackExchange"
} |
Q:
Given an orthonormal basis $(e_n)_{n\in\mathbb N}$ of $H_0^1(\Lambda)$, construct an orthonormal basis of $H_0^1(\Lambda)^d$
Let
$k,d\in\mathbb N$
$\Lambda\subseteq\mathbb R^k$ be open
$(e_n)_{n\in\mathbb N}$
be an orthonormal basis of $H_0^1(\Lambda)$ and $$f^n:=\frac1d(\underbrace{e_n,\ldots,e_n}_{d\text{-times}})\;\;\;\text{for }n\in\mathbb N$$
Can we conclude that $(f^n)_{n\in\mathbb N}$ is an orthonormal basis of $H_0^1(\Lambda)^d$? That should be the case, cause $$\langle f^i,f^j\rangle_{H^1(\Lambda,\:\mathbb R^d)}=\langle e_i,e_j\rangle_{H^1(\Lambda)}\;\;\;\text{for all }i,j\in\mathbb N\;.$$
A:
It is not true even in finite dimensional space. For example, if $V$ is $n$-dimensional, $V^d$ is $nd$-dimensional, so an orthonormal basis should have $nd$-elements instead of $n$ elements.
Instead, try
$$f^k_n := (0,0,\cdots 0, e_n,0,\cdots, 0),$$
(the nonvanishing term is at the $k$-th entry). Then
$$\{ f^k_n\}_{k=1,\cdots,d, n\in \mathbb N}$$
forms an orthonormal basis for the direct sum. Note that this is true for all Hilbert spaces. Related question has been asked here
| {
"pile_set_name": "StackExchange"
} |
Q:
CentOS No Login Prompt After rc.local Executes
This is a CentOS 6.4 server with no GUI. After rc.local executes in the boot sequence, I am not presented with a console style login prompt. I can type characters on the screen but there is no login prompt nor shell.
I checked /etc/init/tty.conf and /etc/init/start-ttys.conf. Everything looks normal. I am able to access the server via the recovery console and see no errors in the log files.
Please note: I converted an Amazon EC2 Machine to a RAW file, converted it to VMDK, and it is booting in VMware Fusion.
A:
Default TTY's are configured in /etc/sysconfig/init. Please make sure the ACTIVE_CONSOLES= line is configured with the default value /dev/tty[1-6].
# What ttys should gettys be started on?
ACTIVE_CONSOLES=/dev/tty[1-6]
| {
"pile_set_name": "StackExchange"
} |
Q:
Calling View from Class
I think I have a simple issue with my app.
First of all I am using the PraseSDK in order to use the LoginView they offer.
Now I was going to create that function and let it called by a view controller in
-(void) viewDidLoad
It worked perfectly.
Now I was wondering if I can put that code into a global function class?
Well I created a Class called: glo_function
Inside of it I created a function which is call
+(void) CallLoginScreen{
PFLogInViewController *login = [[PFLogInViewController alloc] init];
login.fields = PFLogInFieldsUsernameAndPassword | PFLogInFieldsLogInButton;
[self presentModalViewController:login animated:NO];}
In My ViewController Iam using "callLoginScreen" like this
[glo_function CallLoginScreen]
The methode is going to be called by the View Controller but the view will not show up.
Well I get that error will trying to run the app.
No known class method for selector 'presentModalViewController:animated:'
So I am pretty sure It do to the fact that I used the "self" in->
[self presentModalViewController:login animated:NO]
Can someone help me out with it? should be easy, hopefully :)
-----------------------Response------------------------------
Hi after I did that, the app crashes.
The Call methode looks like that:
[glo_function showLoginScreenUsingViewController];
In glo_function.m the methode looks like that:
+ (void)showLoginScreenUsingViewController:(UIViewController *)VC {
PFLogInViewController *login = [[PFLogInViewController alloc] init];
login.fields = PFLogInFieldsUsernameAndPassword | PFLogInFieldsLogInButton;
[VC presentModalViewController:login animated:NO];}
The Result when starting the App:
2012-12-28 21:20:24.003 Logbuch40[1942:c07]
*** Terminating app due to uncaught exception 'NSInvalidArgumentException'
, reason: '+[glo_function showLoginScreenUsingViewController]:
unrecognized selector sent to class 0x22e9ec
A:
"self" always refers to the object you are in. In your case it's the glo_function object. So when you say self you are talking to the wrong object.
You could still do what you want but in your glo_function method you need to pass in a reference to your view controller. Then just use that in your function instead of self.
+ (void)showLoginScreenUsingViewController:(UIViewController *)VC {
PFLogInViewController *login = [[PFLogInViewController alloc] init];
login.fields = PFLogInFieldsUsernameAndPassword | PFLogInFieldsLogInButton;
[VC presentModalViewController:login animated:NO];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Launch new program using exec in new terminal
I've got a program called pgm1 which create a new process using fork.
Then in this process, I launch a new program (pgm2) using the following command:
execv( exec_path_name, argv ).
But the thing is that with this method I've got both output in the same terminal.
I've been searching for a while ans the only solution i found was this one:
Open a new terminal with a system call
Attach my pgm2 to the new terminal using this soft http://blog.nelhage.com/2011/01/reptyr-attach-a-running-process-to-a-new-terminal/comment-page-1/#comment-27264
So my question is really simple, is there a more simple way to do that ?
Thanks in advance !
PS: Distro - Ubuntu 11.10 32bit
A:
I can think of two possible solutions:
Do The Right Thing(TM) and send your output to a file: Each process can use a different file, providing both clear separation of the output and better record-keeping. As a bonus, you are also bound to see a performance improvement - terminal output is computationally expensive, even nowadays...
Execute a terminal emulator with the proper arguments: Most terminal emulators provide a way to execute a specific program in place of the shell. For example xterm:
$ xterm top
This will launch top in an xterm instance, without a shell. Quiting top also terminates the xterm window.
If your terminal emulator of choice supports this, you can use it simply by modifying the arguments passed to execv(). Of course, in this case you will be actually executing the terminal emulator instead of your program, which will then call your own process.
Keep in mind that, depending on the terminal emulator, any open file descriptors may not be passed correctly to your program - the terminal will at least mangle the standard file descriptors.
| {
"pile_set_name": "StackExchange"
} |
Q:
Delphi parsing a Json with multiple array types?
Following is my JSON:
{
"forms": {
"frmLogin": [
{
"frmLoginPg": "Se connecter - Application de gestion de PC"
},
{
"lbl_login_Title": "Application de gestion Pc"
},
{
"lbl_loginName": "Nom d'utilisateur"
},
{
"lblLanguage": "langue préférée"
},
{
"btnLogin": "Se connecter"
},
{
"btnReset_Loginfrm": "Réinitialiser"
}
],
"frmHome": [
{
"frmHomepg": "Accueil"
},
{
"lbladdUser_Title": "Ajouter un utilisateur"
},
{
"lblName": "prénom"
},
{
"lblEmail": "EMail"
},
{
"popmemFile": "Fichier"
}
]
}
}
I am trying to get the values assigned to each key so I can change the Caption of each component.
I tried the following way, but I am getting an Invalid class typecast error:
function Translationspg.GetTranslationsJson(formNameJson, frmName_FORMJson
: TComponentName; formsam: TForm): string;
var
lJsonBytes: TBytes;
lJsonVal, lJsonScenar: TJSONValue;
lJsonScenarioValue: string; // lJsonString,
lJsonObj: TJSONObject; // , lJsonScenario
lJsonArray: TJSONArray;
lJsonScenarioEntry: TJSOnString;
lJsonPair: TJSONPair;
begin
lJsonBytes := TFile.ReadAllBytes(scJSONFileName_French);
lJsonScenar := TJSONObject.ParseJSONValue(lJsonBytes, 0);
if lJsonScenar <> nil then
begin
lJsonArray := lJsonScenar as TJSONArray;
for lJsonVal in lJsonArray do
begin
lJsonObj := lJsonVal as TJSONObject;
lJsonPair := lJsonObj.Get(formNameJson);
lJsonScenarioEntry := lJsonPair.JsonString;
lJsonScenarioValue := lJsonScenarioEntry.Value;
end;
end;
Result := lJsonScenarioValue;
end;
A:
lJsonArray := lJsonScenar as TJSONArray
The root of your JSON is not an array. It is an object. That objects has a single name/value pair, named forms. You need to read that, and then look for the form by name. Like this:
lJsonObj := TJSONObject.ParseJSONValue(lJsonBytes, 0) as TJSONObject;
lJsonObj := lJsonObj.GetValue('forms') as TJSONObject;
lJsonPair := lJsonObj.Get(formNameJson);
....
This program
{$APPTYPE CONSOLE}
uses
System.SysUtils, System.JSON, System.IOUtils;
procedure Main(const fileName, formName: string);
var
lJsonBytes: TBytes;
lJsonObj: TJSONObject;
lJsonArray: TJSONArray;
lJsonValue: TJSONValue;
lJsonPair: TJSONPair;
begin
lJsonBytes := TFile.ReadAllBytes(fileName);
lJsonObj := TJSONObject.ParseJSONValue(lJsonBytes, 0) as TJSONObject;
lJsonObj := lJsonObj.GetValue('forms') as TJSONObject;
lJsonArray := lJsonObj.GetValue(formName) as TJSONArray;
Writeln(fileName, ' ', formName);
for lJsonValue in lJsonArray do begin
lJsonObj := lJsonValue as TJSONObject;
for lJsonPair in lJsonObj do begin
Writeln(lJsonPair.JsonString.ToString, ': ', lJsonPair.JsonValue.ToString);
end;
end;
Writeln;
end;
begin
try
Main('C:\desktop\json.txt', 'frmLogin');
Main('C:\desktop\json.txt', 'frmHome');
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
has this output:
C:\desktop\json.txt frmLogin
"frmLoginPg": "Se connecter - Application de gestion de PC"
"lbl_login_Title": "Application de gestion Pc"
"lbl_loginName": "Nom d'utilisateur"
"lblLanguage": "langue préférée"
"btnLogin": "Se connecter"
"btnReset_Loginfrm": "Réinitialiser"
C:\desktop\json.txt frmHome
"frmHomepg": "Accueil"
"lbladdUser_Title": "Ajouter un utilisateur"
"lblName": "prénom"
"lblEmail": "EMail"
"popmemFile": "Fichier"
| {
"pile_set_name": "StackExchange"
} |
Q:
How to ask user to turn on location
How can I prompt the user to turn on the gps in this way in below image. I tried using the alert dialog method but it takes to the settings view I wanted gps to be turned on without moving to settings activity like the most of the apps do..How can I achieve it
A:
This works in java AndroidX 2020 updated:
private void enableLoc() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
Task<LocationSettingsResponse> result =
LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
@Override
public void onComplete(Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response = task.getResult(ApiException.class);
// All location settings are satisfied. The client can initialize location
// requests here.
} catch (ApiException exception) {
switch (exception.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the
// user a dialog.
try {
// Cast to a resolvable exception.
ResolvableApiException resolvable = (ResolvableApiException) exception;
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
resolvable.startResolutionForResult(
Maps.this,
LOCATION_SETTINGS_REQUEST);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
} catch (ClassCastException e) {
// Ignore, should be an impossible error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
}
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does Appium push the apk?
I'm currently working on an automation project for setting up tablets. I am very familiar with Selenium and Java. To keep this question simple, which one of these lines is pushing the apk? What if I want to push multiple apks?
public class AppiumTest {
private static AndroidDriver<MobileElement> driver;
@BeforeTest
public void firstatest() throws MalformedURLException, InterruptedException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("automationName", "Appium");
capabilities.setCapability("appium-version", "1.4.0");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("platformVersion", "4.4.2");
capabilities.setCapability("deviceName", "0123456789ABCDEF");
capabilities.setCapability("app", "/Users/User/Documents/Appium/1.apk"); // ########
capabilities.setCapability("appPackage", "FILL-IN-INFORMATION"); // ########
capabilities.setCapability("appActivity", "FILL-IN-INFORMATION"); // ########
URL serveraddress = new URL("http://127.0.0.1:4723/wd/hub");
AppiumDriver<MobileElement> driver = new AndroidDriver<MobileElement>(serveraddress, capabilities);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
A:
AppiumDriver<MobileElement> driver = new AndroidDriver<MobileElement>(serveraddress, capabilities);
above line will create a new session and it will check app is installed or not. If not it will install and open the app.
You can not push multiple apks when you start a new session, but later you can install apks by calling driver.installApp(apkPath); method.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does the dual of a vector bundle use the inverse transpose?
I would expect that the dual of a vector bundle would be defined by the inverse conjugate transpose, as that would be the inverse of the adjoint. When $\alpha_{ij}:X\to Y$ is a transition matrix in $E$, we have $\alpha_{ij}^*:Y^*\to X^*$, so $(\alpha_{ij}^*)^{-1}:X^*\to Y^*$ would be (in my opinion) the most canonical choice for a transition matrix in $E^*$. So why do we use $(\alpha_{ij}^t)^{-1}$ instead of $(\alpha_{ij}^*)^{-1}=(\overline{\alpha_{ij}}^t)^{-1}$?
A:
In general you like various objects to be holomorphic, so why introduce complex conjugations ad hoc? Furthermore, if you change basis in a complex vector space with transition matrix $\alpha$, then the dual basis in the dual space is change by the inverse transpose of $\alpha$. Remember that the dual pairing is bilinear, not sesqulinear.
I think the reason you think conjugation may be useful is that you have experience with hermitian forms on complex vector spaces (or bundles). But the main reason these beasts are so nice is positive-definitness, which is not possible for complex bilinear scalar products. For a pairing between two different spaces, positive definitness is undefined, so why bother with sesqulinearity?
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use C++ Classes exported by a dll in Delphi
is there a way to use C++ classes exported by a win32 dll in Delphi for win32? Are there other ways to archieve similar things (COM, .NET, ...)?
A:
You can't import a class. You can only import functions. Rudy Velthuis has written at length on the topic. Although you can't directly use an exported C++ class, he describes a couple of techniques to achieve the same effect:
"Flatten" the object, so on the calling side there is no object anymore, just a pointer that gets passed to the DLL along with other parameters for a series of functions that wrap the object's methods. Writing the wrapper is very simple, although it can be tedious.
Use pure virtual classes. Windows C++ compilers and Delphi have generally the same VMT layouts, so if the C++ class can be described by a list of pure virtual methods, you can create an equivalent Delphi declaration, do some type-casting with the object pointer returned by the DLL, and proceed.
Complete examples of both ways are given in the article.
A:
You can't use C++ classes exported from a DLL as far as I know in Delphi; you can use C functions and you can import COM classes into Delphi.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get parts of string separated by delimiter
I have list of strings like
FDENR8027ROR 0.10-CTW-SI2-2-0-0-A4
FDENR7932ROR-1-0-0-A2
FDENS3311-4-5-105-A2
FDENS1759-T-6-1-107-A3
The output needed to be created as,
FDENR8027ROR 0.10-CTW-SI2, 2, 0 , 0, A4
FDENR7932ROR, 1, 0, 0, A2
FDENS3311, 4, 5, 105, A2
FDENS1759-T, 6, 1, 107, A3
The difficulty is, I need to check for -(hyphen) from End of the string and only last four strings are needed to be separated. Remained text can be used as is.
I tried:
string s = "FDENR8027ROR 0.10-CTW-SI2-2-0-0-A4";
int idx = s.LastIndexOf('-');
Console.WriteLine(s.Substring(0, idx)); //FDENR8027ROR 0.10-CTW-SI2-2-0-0
Console.WriteLine(s.Substring(idx + 1)); //A4
But it's for once, what about other three strings. :(
How to do it?
A:
Something like this:
string s = "FDENR8027ROR 0.10-CTW-SI2-2-0-0-A4";
string[] parts = s.Split('-');
List<string> result = new List<string>{ string.Join("-", parts.Take(parts.Length - 4)) };
result.AddRange(parts.Skip(parts.Length - 4).Take(4));
See my working fiddle.
| {
"pile_set_name": "StackExchange"
} |
Q:
php extract a sub-string before and after a character from a string
need to extract an info from a string which strats at 'type-' and ends at '-id'
IDlocationTagID-type-area-id-492
here is the string, so I need to extract values : area and 492 from the string :
After 'type-' and before '-id' and after 'id-'
A:
This is what you want using two explode.
$str = 'IDlocationTagID-type-area-id-492';
echo explode("-id", explode("type-", $str)[1])[0]; //area
echo trim(explode("-id", explode("type-", $str)[1])[1], '-'); //492
Little Simple ways.
echo explode("type-", explode("-id-", $str)[0])[1]; // area
echo explode("-id-", $str)[1]; // 492
Using Regular Expression:
preg_match("/type-(.*)-id-(.*)/", $str, $output_array);
print_r($output_array);
echo $area = $output_array[1]; // area
echo $fnt = $output_array[2]; // 492
| {
"pile_set_name": "StackExchange"
} |
Q:
Fluids in thermodynamic equlibrium
I am reading about the Euler equations of fluid dynamics from
Leveque's Numerical Methods for Conservation Laws (Amazon link). After introducing the mass, momentum and energy equations, some thermodynamic
concepts are discussed, to introduce an equation of state.
He says
In the Euler equations we assume that the gas is in chemical and thermodynamic equilibrium and that the internal energy is a known function of pressure and density.
After this, the usual thermodynamics-related equation of state (EOS) discussions are carried out.
Now chemical equilibrium I understand (number of moles of the chemical constituents do not change), however I don't understand how the assumption
of thermodynamic equilibrium can be imposed.
From what baby thermodynamics I know, any thermodynamic analysis is always
calculated for quasi-static processes, like 'slowly' pushing a piston
in a cylinder of gas.
But in fluid dynamics fluids are flowing and that too rapidly and from intuition there will not be any thermodynamic equilibrium during fluid flow.
Where is my understanding going wrong?
A:
The excerpt from the text forgets to mention that you assume Local Thermodynamic Equilibrium, and not full Thermodynamic Equilibrium, so to make it possible to define point to point (or from region to region) an EoS.
If there is no sense of being 'close' to thermodynamical equilibrium, it is simply impossible to talk about EoS, pressure and the like from the "Hydrodynamics as Local Thermal Equilibrium".
From the strict thermodynamic view, you can't talk of anything time-dependent. All piston an thermal cycles use the abuse of talking of 'quasi-equilibrium' without really defining it, and simply postulate that you can use full traditional thermodynamics all around. From a 'rigorous' point of view, the only thing that you can talk in thermodynamics are stationary, homogeneous systems, which are in the 'thermodynamical limit' ( $N,V,S...\rightarrow \infty$ but $N/V, S/V...$ fixed), so no time dependence.
The idea of flow is that even if the fluid flows very fast in relation to a fixed observer, if you go to the rest frame of that piece of fluid, you can talk of thermodynamic equilibrium close to that small part of the fluid.
I believe that the best way to understand how this all works is through Boltzmann Equation, which I can develop latter if you wish so.
Edit(Complementing the answer, as asked):
So, you have boltzmann equation:
$
\frac{\partial f}{\partial t}+\vec v \cdot \frac{\partial f}{\partial \vec r}+\vec F\cdot \frac{\partial f}{\partial \vec p} = \int d^3 \vec p_0 d\Omega\ g\ \sigma(g,\Omega) (f'f_1' - ff_1)
$
Where:$g=|\vec p - \vec p_0|$, $\sigma(g,\Omega)$ is the differential cross section between gas molecules, and the primed distributions are evaluated with the momentum that corresponds to an out-going (solid)-angle $\Omega$, with ingoing momenta $\vec p$ and $\vec p_0$. The normalization is $\int d^3\vec r\ d^3 \vec p\ f(t,\vec r,\vec p)=N$, where N is the total number of particles.
We believe that this equation provides a good description to 1-particle distribution function, in phase space, of a a rarefied gas composed with hard-spheres(i.e. hard, short range, repulsive potential, with only elastic collisions). Putting aside whether it's justified or not to model a gas this way, simply believe for the moment that it works.
Now you want to model a gas inside a box as beeing in full thermodynamical equilibrium. Equilibrium is when you have stationary, homogeneous material. So, you want to look for solutions of Boltzmann equation that have this kind of symmetry, and thus:
$f(t,\vec r, \vec p) = \frac{N}{V}Id_V(\vec r)f_0(\vec p)$
So, the most of inhomogeneity that there may be is an indicator function that says that outside the box, there is no gas. We are also supposing that the only external forces are on the walls of the box, and so, in the bulk of the gas we have $\vec F=0$
Now we feed this ansatz to the Boltzmann equation and see what happens. Now, from the above assumptions $\partial f/\partial t=0$, $\partial f/\partial \vec r = 0$ and $\vec F=0$ on the bulk. This gives us:
$
\frac{\partial f}{\partial t}+\vec v \cdot \frac{\partial f}{\partial \vec r}+\vec F\cdot \frac{\partial f}{\partial \vec p} = 0 = \int d^3 \vec p_0 d\Omega\ g\ \sigma(g,\Omega) (f'f_1' - ff_1)
$
So we need to kill the collision kernel in order to satisfy the Boltzmann equation. The easiest way is to nullify the subtraction inside it by putting:
$
f_0(\vec p)f_0(\vec p_1)=f_0(\vec p')f_0(\vec p_1')
$
For all possible (elastic) collision outcomes. Now comes the the smart point. Lets take the $\log$ of the above expression.
$
\log f_0(\vec p) + \log f_0(\vec p_1)=\log f_0(\vec p') + \log f_0(\vec p_1')
$
If $\log f_0$ is function only of additive conserved quantities on the collision, we get the relation above for free! (Ok, not completely for free, its possible to show that this is essentially the only way to do it)
Now, for elastic binary collisions, we have only 3 conserved quantitites: Mass, Linear Momentum (because we believe that there is no relevant rotation) and kinectic energy.
Now we write:
$\log f_0(\vec p) = A\frac{\vec p^2}{2m}+ \vec B \cdot \vec p + Cm$
Massaging the above expression and we use integrability conditions, we may write:
$\log f_0(\vec p) = -\frac{ (\vec p-\vec p_0)^2}{2m\sigma^2}+ \log N_0$
In the case of the box, we know that the box isn't moving (equivalently, it's locally isotropic), so we put $\vec p_0=0$ and we get the Boltzmann Distribution as a solution to Boltzmann equation for equilibrium conditions. Further, we can identify $\sigma^2 = k_BT$ and we close the identification.
Now, to hydrodynamics. To find hydrodynamical equation from Botlzmann equation, we "Take Moments" from it, i.e., e multiply it by powers of the linear momentum, and integrate in momentum, so we get equations for things that live in usual 3D space.
Multiplying by $\chi(\vec p)$ and integrating:
$
\frac{\partial}{\partial t}\left(\int d^3\vec p\ \chi(\vec p) f\right) + \frac{1}{m} \nabla_{\vec r} \cdot \left(\int d^3\vec p\ \chi(\vec p)\vec p f\right) + \vec F \cdot \left(\int d^3\vec p\ \chi(\vec p) \frac{\partial f}{\partial \vec p}\right) = \int d^3 \vec p\ d^3 \vec p_0\ d\Omega\ g\chi(\vec p)\ \sigma(g,\Omega) (f'f_1' - ff_1)
$
It's possible to show that if $\chi(\vec p)$ is a conserved quantity on binary collisions, the last term is $=0$, so that's what we are going to look for. Choosing $\chi(\vec p)=m$, we arrive at:
$
\frac{\partial}{\partial t}\left(\int d^3\vec p\ m f\right) + \nabla_{\vec r} \cdot \left(\int d^3\vec p\ \vec p f\right) = 0
$
Identifying $\rho = \int d^3\vec p\ m f$ as the mass density and $\int d^3\vec p\ \vec p f = \vec j = \rho <\vec v> = \rho \vec u$ the mass current, we have the continuity equation for mass density:
$
\frac{\partial \rho}{\partial t} + \nabla \cdot (\rho \vec v) = 0
$
Setting $\chi(\vec p) = \vec p$ we arrive at:
$
\frac{\partial }{\partial t}(\rho \vec u) + \nabla \cdot \Sigma - \rho F = 0
$
Where $\Sigma_{ij} = \int d^3\vec p\ p_i p_j f(t,\vec r,\vec p)$. Now we can decompose $\vec p = m<\vec v> + \delta \vec p = m\vec u + \delta \vec p$, where we identify the average velocity as $\vec u = \frac{1}{\rho} \vec j$. This average velocity is what we identify as the fluid velocity. Going back to the last equation we have:
$
\frac{\partial }{\partial t}(\rho \vec u) + \nabla \cdot \left(\rho \vec u \otimes \vec u + \Pi
\right) = \vec f
$
Where, finally, we identify $\Pi_{ij} = \int d^3\vec p\ \delta p_i \delta p_j f(t,\vec r,\vec p)$ as the stress tensor. The convective par is already there, and we now can appreciate the conection between kinectic theory and hydrodynamics. Comming back to Boltzmann Distribuition:
$f=n(t,\vec r)f_0(\vec p)$
$f_0(\vec p) = \frac{1}{(2\pi m k_BT)^{3/2}}e^{-\frac{ (\vec p-\vec p_0)^2}{2mk_BT}}$
We said that for Thermodynamics, we had $n$,$T$ and $\vec p_0$ constant all along the gas. For Hydrodynamics, we try to retain that functional form, and relax this assumption, i.e., we try (again) to find solutions to Boltzmann equation with the above form, but with $T(t,\vec r)$ and $\vec p(t,\vec r)$ possibly have some dependence in time and space, and so we talk about local thermal equilibrium, since we try to keep, locally, an equilibrium distribution.
If we do that, we end up with $\rho = m\times n(t,\vec r)$ and $\vec u = \frac{\vec p_0}{m}$, which wasn't totally unexpected, and $\vec p - m\vec u= \delta \vec p$, so the Boltzmann distribution measures the (local) fluctuation of velocity. Now computing the stress tensor:
$\Pi_{ij} = \frac{n}{(2\pi m k_BT)^{3/2}}\int d^3\vec p\ \delta p_i \delta p_j e^{-\frac{\delta \vec p^2}{2mk_BT}}$
It' not too difficult to see that the stress tensor above is proportional to the identity tensor, and we identify $\Pi_{ij} = p \delta_{ij}$, and since we have a relation between pressure, density and temperature, we have an EoS. If you plug that on the original equation with $\Pi$, you end up with Euler equation for Fluid Dynamics. So you can think that Euler equation is an evolution equation for something that is in strict local equilibrium.
Also, if you look closely, you will see that the probability distribution only care about the velocity fluctuation $\delta \vec p/m$, and not the actual velocity of the fluid $\vec u$. Here enters your question about the fluid flow:
But in fluid dynamics fluids are flowing and that too rapidly and from intuition there will not be any thermodynamic equilibrium during fluid flow.
From the fluid standpoint, the average velocity is not important to the thermodynamics, only the fluctuations around this average velocity.
Chemical equilibrium is not being considered here, since we are supposing that the fluid have a single chemical species, so it's naturally in chemical equilibrium.
Now, beyond Euler equation:
One very (strong) assumption that we made was that the fluid had the distribution in phase space that was locally Maxwell-Boltzmann. What would happen if we dropped this assumption?
Generally, we can't solve (or can only solve numerically) Boltzmann Equation except on very special cases, so, as any good physicist, we go to the next best thing: Approximate Solutions
What happens if our system is not on equilibrium but close to equilibrium? It should be possible to write $f=f_0\phi$ where $\phi \approx 1$. Now, you would like to find some parameter that you could use to to some kind of perturbation expansion around it. This parameter is essentially the Knudsen Number of the system. If you do this, essentially, the only thing that should change here is the stress tensor, which depends explicitly of the form of the distribution on phase space.
The Knudsen Number is essencially a measure of how far the "microscopic" scale of your system is far from the "macroscopic" scale. If they are sufficiently far apart, i.e. $Kn << 1$, an macroscopic, or Hydrodynamical, description of your system should be good.
The zero-th order on Kn should be $f_0$, so you seek something like $\phi = 1+Kn \phi_1 + (Kn)^2 \phi_2 + ...$
You can carry out this calculation, which is rather lengthy, and what you find (if I remember correctly) is that in first order on the Knudsen Number, you find the Navier-Stokes Stress tensor, which in turn bring you to Navier-Stokes equation, with the bulk and shear viscosity coefficients.
Not only this, you can calculate the dependence on the density and temperature for this coeficients, so you not only have the general form of the evolution equation, but you also have an "EoS" in the extended sense, so to encompass also the viscosity coeffients.
So, the idea of using this method is to define pressure, temperature and the like on the "Equilibrium" part of the distribution, and viscosity and any other kind of effect on the "Non-Equilibrium" part. In this sense you can talk about thermodynamics since you are near (local) equilibrium, even you are not exactly on equilibrium.
So, this is one way to see hydrodynamics as 'mean kinetic theory', and also as an (almost) local thermodynamics. There are also other ways to do it. One is to study Non-Equilibrium Thermodynamics as a macroscopic (in the same sense as classical thermodynamics) mean theory. This is done, in the linear theory, by De Groot & Mazur.
I hope that I have clarified some of your questions. I believe this is a very interesting subject, and I like it very much myself.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is javac 1.5 running so slowly compared with the Eclipse compiler?
I have a Java Maven project with about 800 source files (some generated by javacc/JTB) which is taking a good 25 minutes to compile with javac.
When I changed my pom.xml over to use the Eclipse compiler, it takes about 30 seconds to compile.
Any suggestions as to why javac (1.5) is running so slowly? (I don't want to switch over to the Eclipse compiler permanently, as the plugin for Maven seems more than a little buggy.)
I have a test case which easily reproduces the problem. The following code generates a number of source files in the default package. If you try to compile ImplementingClass.java with javac, it will seem to pause for an inordinately long time.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class CodeGenerator
{
private final static String PATH = System.getProperty("java.io.tmpdir");
private final static int NUM_TYPES = 1000;
public static void main(String[] args) throws FileNotFoundException
{
PrintStream interfacePs = new PrintStream(PATH + File.separator + "Interface.java");
PrintStream abstractClassPs = new PrintStream(PATH + File.separator + "AbstractClass.java");
PrintStream implementingClassPs = new PrintStream(PATH + File.separator + "ImplementingClass.java");
interfacePs.println("public interface Interface<T> {");
abstractClassPs.println("public abstract class AbstractClass<T> implements Interface<T> {");
implementingClassPs.println("public class ImplementingClass extends AbstractClass<Object> {");
for (int i=0; i<NUM_TYPES; i++)
{
String nodeName = "Node" + i;
PrintStream nodePs = new PrintStream(PATH + File.separator + nodeName + ".java");
nodePs.printf("public class %s { }\n", nodeName);
nodePs.close();
interfacePs.printf("void visit(%s node, T obj);%n", nodeName);
abstractClassPs.printf("public void visit(%s node, T obj) { System.out.println(obj.toString()); }%n", nodeName);
}
interfacePs.println("}");
abstractClassPs.println("}");
implementingClassPs.println("}");
interfacePs.close();
abstractClassPs.close();
implementingClassPs.close();
}
}
A:
Sun has confirmed to me by email that this is a new bug (6827648 in their bug database).
A:
You get the same behaviour with JDK 1.6, including update 14, build 04, using G1 doesn't change the behaviour, (though G1 appears to work really well).
Monitoring javac with jvisualvm, repeated thread dumps show the main thread spending lots of time in
at com.sun.tools.javac.code.Types.isSubSignature(Types.java:1846)
at com.sun.tools.javac.code.Symbol$MethodSymbol.overrides(Symbol.java:1108)
at com.sun.tools.javac.code.Symbol$MethodSymbol.implementation(Symbol.java:1159)
at com.sun.tools.javac.comp.Check.checkCompatibleConcretes(Check.java:1239)
at com.sun.tools.javac.comp.Check.checkCompatibleSupertypes(Check.java:1567)
at com.sun.tools.javac.comp.Attr.attribClassBody(Attr.java:2674)
at com.sun.tools.javac.comp.Attr.attribClass(Attr.java:2628)
at com.sun.tools.javac.comp.Attr.attribClass(Attr.java:2564)
at com.sun.tools.javac.main.JavaCompiler.attribute(JavaCompiler.java:1036)
at com.sun.tools.javac.main.JavaCompiler.compile2(JavaCompiler.java:765)
at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:730)
at com.sun.tools.javac.main.Main.compile(Main.java:353)
at com.sun.tools.javac.main.Main.compile(Main.java:279)
at com.sun.tools.javac.main.Main.compile(Main.java:270)
at com.sun.tools.javac.Main.compile(Main.java:69)
at com.sun.tools.javac.Main.main(Main.java:54)
and churning through a large number of short lived instances of these classes:
com.sun.tools.javac.code.Types$Subst
com.sun.tools.javac.util.List
com.sun.tools.javac.code.Types$MethodType
I suspect the code is churning through com.sun.tools.javac.comp.Check.checkCompatibleConcretes comparing each method with every other method
That method's javadoc:
/** Check that a class does not inherit two concrete methods
* with the same signature.
*/
It may be that eclipse's compiler either doesn't perform that check, or doesn't perform it in the same way.
A:
It may be that the javac compiler operates close at its heap limit (64MB or so). In that case, it spends most of the time in the garbage collector. Give the compiler a good chunk of memory, say 256M or 512M and see if it runs faster.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does Captain Phasma type with thimbles on her fingers?
How does Captain Phasma type her password to deactivate the shield protecting Starkiller Base when she is wearing thimbles on her fingers?
A:
Because she doesn't type to do it (in the film)- it appears to be a dial / handle.
Finn never indicates she should type in a password, he simply says:
FINN
You want me to blast that bucket off
your head? Lower the shields.
CAPTAIN PHASMA
You're making a big mistake.
FINN
Do it.
You can see that there is no standard keyboard on this particular control panel
A:
This is addressed in the film's tie-in novelisations. Apparently the lowering of the shield was accomplished by pushing buttons rather than typing commands on a keyboard.
Chewie backed him up with a roar.
As Phasma pushed a few buttons, Finn looked at Han. “Solo, if this works, we’re not going to have a lot of time to find Rey.”
The Force Awakens: Finn's Story
The sequence did not require extensive typing.
He planted Phasma at a console and ordered her to initiate the deactivation. When she refused, he pressed his blaster harder against her helmet. “Do it.”
She did. A few keystrokes were all it took to bypass the automatic systems and start the sequence to shut down the shields.
Star Wars: The Force Awakens: A Junior Novel
| {
"pile_set_name": "StackExchange"
} |
Q:
Looking for a Vampire movie based on a scene I remember
More than 10 years ago, I watched a vampire movie on a French TV channel and I have been searching for its title for 2 years now. I believe it is not a famous movie since I was not able to find anything.
There was a scene where the main hero (I think he was a vampire hunter, at least he was killing vampires in the movie, badass style), transfused the blood of a vampire to reduce his heartbeat and avoid being detected by other vampires, to be able to access their nest.
The final scene of the movie shows the hero driving and putting sunglasses as the rays of the sunrise were bothering him.
The scenes are blurred in my mind as it is just a childhood memory, for me now.
A:
Sounds a bit like Vampires: Los Muertos. The hero, Jon Bon Jovi, receives a transfusion of vampire blood, I think to make him strong enough to fight the big bad (although could be for the reason given, I can't remember).
The finals scene shows him putting on his sunglasses as he drives off, as described.
A:
Could this be the first Blade (Wesley Snipes) installment?
There is some transfusion mentioned, but only with a serum to protect Blade from succumbing to full-fledged vampirism.
| {
"pile_set_name": "StackExchange"
} |
Q:
Diagonalizability of a matrix
Show that $$ A :=\begin{pmatrix} 1 & 0 & 0 \\ -2 & 1 & 2 \\ -2 & 0 & 3 \end{pmatrix}$$ is diagonalizable.
What I did:
First, I determined the characteristic polynomial $$\chi_A(X) = \det(X \cdot E_3-A)=(X-3)(X-1)(X-1)=X^3-5X^2+7X-3,$$
so the eigenvalues are $3$ and $1$.
I then determined the eigenspaces of each eigenvalue:
$$X=3: \left(\begin{array}{@{}ccc|c@{}}
2 & 0 & 0 & 0 \\
-2 & 2 & 2 & 0 \\
-2 & 0 & 0 & 0 \\
\end{array}\right) \leadsto \left(\begin{array}{@{}ccc|c@{}}
2 & 0 & 0 & 0 \\
0 & 2 & 2 & 0 \\
0 & 0 & 0 & 0 \\
\end{array}\right),$$ so $x_1=0$, $x_2=-x_3$, $x_3=x_3$ and thus $V_3(C) = \left< \begin{pmatrix} 0\\-1\\1 \end{pmatrix} \right>$.
Analogous:
$$X=1: \left(\begin{array}{@{}ccc|c@{}}
0 & 0 & 0 & 0 \\
-2 & 0 & 2 & 0 \\
-2 & 0 & -2 & 0 \\
\end{array}\right) \leadsto \left(\begin{array}{@{}ccc|c@{}}
-2 & 0 & 2 & 0 \\
0 & 0 & -4 & 0 \\
0 & 0 & 0 & 0 \\
\end{array}\right),$$ so $x_1=x_3=0$, $x_2=x_2$ and thus $V_1(A) = \left< \begin{pmatrix} 0\\1\\0 \end{pmatrix} \right>$.
It now follows that $\dim(V_3(C)) + \dim(V_1(A)) = 1+1=2 \lt 3 = \dim(A)$ and because of the $\lt$, A shouldn't be diagonalizable, but it is.
So where's the mistake? Thanks in advance!
A:
When $X=1$ the matrix becomes $$XI-A=I-A=\begin{bmatrix}0 & 0 & 0 \\ 2 & 0 & -2 \\ 2 & 0 & -2\end{bmatrix}$$ which has rank 1.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to compare two nano time values? [javadoc confusion]
I have read the javadoc for System.nanoTime() and it all seems clear. Until I reached the final paragraph:
To compare two nanoTime values
long t0 = System.nanoTime();
...
long t1 = System.nanoTime();
one should use t1 - t0 < 0, not t1 < t0, because of the possibility of numerical overflow.
There are two things that are unclear to me:
Why would one check if t1 < t0 if t1 was taken after t0? My understanding is that nano time is always increasing. So, I would rather check t1 > t0.
Let's suppose that's a typo, and they meant the correct check is t1 - t0 > 0. I still don't get it why that is the correct way of checking and not t1 > t0. They mention the numerical overflow and I don't quite get what they mean. Regarding the numerical overflow, here's what is mentioned:
Differences in successive calls that span greater than approximately 292 years (2^63 nanoseconds) will not correctly compute elapsed time due to numerical overflow.
OK, so since the nano time is stored as a long value, it will eventually overflow in 292 years. And what happens next? Does it start from the beginning, i.e. the lowest negative value -2^63? Or does it stop measuring and returns (2^63 - 1) always?
A:
You are right, the parts of the documentation that you quoted seem to be a bit confused.
However, the part of the documentation that counts is this:
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.
(emphasis added by me.)
What this means is that you do not have any guarantees that your code will not happen to be running at the time that the yielded long value will happen to flip from positive to negative.
There is nothing that guarantees that this will happen in 300 years from now, it may happen today.
Currently, my JVM returns some number like 3496793269188, but it could, if it wanted to, be returning some number very close to 9223372036854775807, (which is Long.MAX_VALUE,) which would make a flip from positive to negative imminent.
So, you should take all necessary precautions.
A:
Well, javadoc says truth. Consider such example:
long t0 = Long.MAX_VALUE;
long t1 = Long.MIN_VALUE;
System.out.println(t1 < t0);
System.out.println(t1 - t0 < 0);
It will give
true
false
while mathematically both expressions are true. But in our case we know, that negative value of time means, that it is overflowed, hence it should be really greater then positive number.
| {
"pile_set_name": "StackExchange"
} |
Q:
Magnolia Page Template not registering
I watched a Tutorial from Magnolia here is the link: [https://www.youtube.com/watch?v=qdDb-oYt18k].
During watching it I followed his orders. I also read the hello world tutorial in the documentation. That is, I installed magnolia with cli and created a light module and a page. Everything was created with cli so there is no way that my module could have any errors. I restarted my tomcat server and entered the admin panel. First off my module is not shown in the resource folder, neither is it shown in the page template selection menu.
What exactly could this be?
A:
As per comments under the question,solution to this issue was to ensure property in magnolia.properties file denoting folder with light modules points to correct directory.
When in doubt always use absolute path.
| {
"pile_set_name": "StackExchange"
} |
Q:
Traversing tree and extracting information with reusable components
I have a tree of nested structs in a Go project. I would like to walk through the tree and perform different actions, such as picking out certain structs at different levels in the tree and appending them to a list, or modifying the structs in place.
I would like to do this using reusable components so that I can focus on implementing that perform the tasks, not having to reimplement the walker for every such function. So far the only thing I can think of is this API:
type applyFunc func(*Node)
func walker(node *Node, f applyFunc) {
....
for _, child := range node.children() {
walker(child, f)
}
}
The function walker can clearly be used to modify the tree because it is passed pointers to the tree nodes. I like it because I can write applyFunc functions separately without having to bother with the actual recursive walker code. However, extracting nodes or deleting them is more difficult.
For extracting information from nodes, perhaps I can use a closure:
values := &[]int{}
f := func(node *Node) {
values.append(node.val)
}
walker(root, f)
//values now hold the information I am interested in
Would this be a good solution? Are there better ones?
A:
You could also add the walk function to your tree type, add a pointer to the parent in a node and add a deleteChild method to a node which takes the index of the child as argument which would allow you to manipulate easily.
Example (here i called walk apply):
type node struct {
children []*node
parent *node
value int
}
func (n *node) deleteChild(index int) {
n.children = append(n.children[:index], n.children[index+1:]...)
}
func (n *node) delete(index int) {
if n.parent != nil {
n.parent.deleteChild(index)
}
}
func (n *node) apply(index int, f func(int, *node)) {
f(index, n)
for childIndex, child := range n.children {
child.apply(childIndex, f)
}
}
func main() {
t := &node{}
t.children = []*node{
&node{
children: []*node{
&node{value: 2},
},
value: 1,
parent: t,
},
}
// extract all values in nodes
values := []int{}
t.apply(0, func(index int, n *node) {
values = append(values, n.value)
})
fmt.Println(values) // [0 1 2]
// delete a node
fmt.Println(t.children) // [0xc4.....]
t.apply(0, func(index int, n *node) {
n.delete(index)
})
fmt.Println(t.children) // []
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Local degree of local homeomorphism is $\pm 1$
Let $f:X\to Y$ be a local homeomorphism. I claim that local degree of $f$ is $\pm 1$. I was wondering if my proof is correct: Let $x\in f^{-1}(\{y\})$ , $U$ be a neighbourhood of $x$ and $V$ be a neighbourhood of $y$ so that $f\vert_{U}:U\to V$ is homeomorphism. Then $f_{*}:H_{n}(U,U-\{x\})\to H_{n}(V,V-\{y\})$ is an isomorphism. Hence local degree at $x$ is $\pm1$. Is the proof OK?
A:
The proof is correct; however, remember to add the assumption that both $X$ and $Y$ are manifolds. As Idrissi says in the comments, this proof also applies to homology manifolds.
| {
"pile_set_name": "StackExchange"
} |
Q:
fibers are connected implies that total space is connected in a surjective submersion between manifold
Could anyone tell me how to prove the following problem?I have no idea! Thank you!
If $f:M\to N$ is a surjective submersion in the category of smooth manifolds, if $N$ is connected, and if $f^{-1}(y)$ is connected for all $y$ in $N$, then $M$ is connected.
A:
Suppose we are given a continuous function $g: M \to \{0,1\}$. It follows from the assumption on $f^{-1}(y)$ being connected, that $g$ is constant on fibers. Since $f: M \to N$ is open and surjective, it is a quotient map. Since $g$ is constant on fibers, it descends to a continuous map $\tilde g: N \to \{0,1\}$ such that $\tilde g \circ f = g$. As $N$ is connected, $\tilde g$ (and hence also $g$) must be constant.
This shows that every continuous map $g: M \to \{0,1\}$ is constant. This is equivalent to the connectedness of $M$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Odata Client Code Generator-Unable to generate .cs file
I have a WPF clinet and I am using Odata Client Code Generator for creating a client of an odata service using Web Api 2.
I have followed this tutorial:
http://blogs.msdn.com/b/odatateam/archive/2014/03/12/how-to-use-odata-client-code-generator-to-generate-client-side-proxy-class.aspxd
The problem is that I am getting an empty .cs file that is being created by following the steps described in the tutorial(the link of which is given above).
The MatadataDocumentUri that I am using is: http://localhost:56045/odata
Is there something I am missing?
Here is the Metadata by using http://localhost:56045/odata/$metadata:
<edmx:Edmx xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx" Version="1.0">
<edmx:DataServices xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0">
<Schema xmlns="http://schemas.microsoft.com/ado/2009/11/edm" Namespace="RestApiServer.Models">
<EntityType Name="User">
<Key>
<PropertyRef Name="UserId"/>
</Key>
<Property Name="UserId" Type="Edm.Int32" Nullable="false"/>
<Property Name="UserName" Type="Edm.String"/>
<Property Name="UserType" Type="Edm.String"/>
<NavigationProperty Name="UserAddress" Relationship="RestApiServer.Models.RestApiServer_Models_User_UserAddress_RestApiServer_Models_UserAddress_UserAddressPartner" ToRole="UserAddress" FromRole="UserAddressPartner"/>
</EntityType>
<EntityType Name="UserAddress">
<Property Name="UserId" Type="Edm.Int32" Nullable="false"/>
<Property Name="UserAddress1" Type="Edm.String"/>
<NavigationProperty Name="User" Relationship="RestApiServer.Models.RestApiServer_Models_UserAddress_User_RestApiServer_Models_User_UserPartner" ToRole="User" FromRole="UserPartner"/>
</EntityType>
<Association Name="RestApiServer_Models_User_UserAddress_RestApiServer_Models_UserAddress_UserAddressPartner">
<End Type="RestApiServer.Models.UserAddress" Role="UserAddress" Multiplicity="0..1"/>
<End Type="RestApiServer.Models.User" Role="UserAddressPartner" Multiplicity="0..1"/>
</Association>
<Association Name="RestApiServer_Models_UserAddress_User_RestApiServer_Models_User_UserPartner">
<End Type="RestApiServer.Models.User" Role="User" Multiplicity="0..1"/>
<End Type="RestApiServer.Models.UserAddress" Role="UserPartner" Multiplicity="0..1"/>
</Association>
</Schema>
<Schema xmlns="http://schemas.microsoft.com/ado/2009/11/edm" Namespace="Default">
<EntityContainer Name="Container" m:IsDefaultEntityContainer="true">
<EntitySet Name="Users" EntityType="RestApiServer.Models.User"/>
<EntitySet Name="UserAddresses" EntityType="RestApiServer.Models.UserAddress"/>
<AssociationSet Name="RestApiServer_Models_User_UserAddress_RestApiServer_Models_UserAddress_UserAddressPartnerSet" Association="RestApiServer.Models.RestApiServer_Models_User_UserAddress_RestApiServer_Models_UserAddress_UserAddressPartner">
<End Role="UserAddressPartner" EntitySet="Users"/>
<End Role="UserAddress" EntitySet="UserAddresses"/>
</AssociationSet>
<AssociationSet Name="RestApiServer_Models_UserAddress_User_RestApiServer_Models_User_UserPartnerSet" Association="RestApiServer.Models.RestApiServer_Models_UserAddress_User_RestApiServer_Models_User_UserPartner">
<End Role="UserPartner" EntitySet="UserAddresses"/>
<End Role="User" EntitySet="Users"/>
</AssociationSet>
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>
A:
Your metadata is actually a V3 format metadata. Please check:
http://services.odata.org/V4/OData/OData.svc/$metadata, the root is:
<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
and for http://services.odata.org/V3/OData/OData.svc/$metadata
<edmx:Edmx xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx" Version="1.0">
So your service is actually a OData V3 service, which our client generator does not support yet.
| {
"pile_set_name": "StackExchange"
} |
Q:
React final form triggers handleSubmit after the initial render
I've got only Switch component in my react-final-form. It looks like this:
<Form
onSubmit={onSubmit}
initialValues={initialValues}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<Field name="booleanValue" component={Switch} onChange={handleSubmit}/> //triggers when receives value
</form>
)
}
/>
I want to trigger handleSubmit only after user changes, not at first render of the form.
A:
<Field/> doesn't have an onChange prop like you are attempting. Something like this could work.
import { OnChange } from 'react-final-form-listeners'
...
<Form
onSubmit={onSubmit}
initialValues={initialValues}
render={({ handleSubmit, form }) => (
<form onSubmit={handleSubmit}>
<Field name="booleanValue" component={Switch}/>
<OnChange name="booleanValue">
{(value, previousValue) => {
form.submit()
}}
</OnChange>
</form>
)
}
/>
P.S. I hope your Switch component knows to get its value and onChange from the input prop.
Hope that helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Long list of Hit and Get from sudo apt update
Why are there so many repeats of getting similar packages during sudo apt update? Is this normal? Previously, I noticed that there were only 5 to 7 Hit or Get in total. Recently, I noticed this update list seemed to have grown longer and longer.
Hit:1 http://archive.ubuntu.com/ubuntu bionic InRelease
Hit:2 http://archive.canonical.com/ubuntu bionic InRelease
Get:4 http://archive.ubuntu.com/ubuntu bionic-updates InRelease [88.7 kB]
Get:7 http://archive.ubuntu.com/ubuntu bionic-backports InRelease [74.6 kB]
Get:8 http://archive.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]
Get:9 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 Packages [728 kB]
Get:10 http://archive.ubuntu.com/ubuntu bionic-updates/main i386 Packages [580 kB]
Get:11 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 DEP-11 Metadata [285 kB]
Get:12 http://archive.ubuntu.com/ubuntu bionic-updates/main DEP-11 48x48 Icons [70.9 kB]
Get:13 http://archive.ubuntu.com/ubuntu bionic-updates/main DEP-11 64x64 Icons [140 kB]
Get:14 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 DEP-11 Metadata [253 kB]
Get:15 http://archive.ubuntu.com/ubuntu bionic-updates/universe DEP-11 48x48 Icons [209 kB]
Get:16 http://archive.ubuntu.com/ubuntu bionic-updates/universe DEP-11 64x64 Icons [452 kB]
Get:17 http://archive.ubuntu.com/ubuntu bionic-updates/multiverse amd64 DEP-11 Metadata [2,468 B]
Get:18 http://archive.ubuntu.com/ubuntu bionic-backports/universe amd64 DEP-11 Metadata [7,924 B]
Get:19 http://archive.ubuntu.com/ubuntu bionic-security/main i386 Packages [368 kB]
Get:20 http://archive.ubuntu.com/ubuntu bionic-security/main amd64 Packages [502 kB]
Get:21 http://archive.ubuntu.com/ubuntu bionic-security/main Translation-en [170 kB]
Get:22 http://archive.ubuntu.com/ubuntu bionic-security/main amd64 DEP-11 Metadata [22.6 kB]
Get:23 http://archive.ubuntu.com/ubuntu bionic-security/main DEP-11 48x48 Icons [10.4 kB]
Get:24 http://archive.ubuntu.com/ubuntu bionic-security/main DEP-11 64x64 Icons [31.7 kB]
Get:25 http://archive.ubuntu.com/ubuntu bionic-security/restricted amd64 Packages [6,600 B]
Get:26 http://archive.ubuntu.com/ubuntu bionic-security/restricted Translation-en [2,840 B]
Get:27 http://archive.ubuntu.com/ubuntu bionic-security/universe i386 Packages [590 kB]
Get:28 http://archive.ubuntu.com/ubuntu bionic-security/universe amd64 Packages [604 kB]
Get:29 http://archive.ubuntu.com/ubuntu bionic-security/universe Translation-en [201 kB]
Get:30 http://archive.ubuntu.com/ubuntu bionic-security/universe amd64 DEP-11 Metadata [42.1 kB]
Get:31 http://archive.ubuntu.com/ubuntu bionic-security/universe DEP-11 64x64 Icons [116 kB]
Get:32 http://archive.ubuntu.com/ubuntu bionic-security/multiverse amd64 DEP-11 Metadata [2,464 B]
Fetched 5,652 kB in 23s (245 kB/s)
Reading package lists... Done
Update:
I just ran sudo apt update again. This time, only 8 Hit & Get were involved. Why does it sometime require such a long update while other times require a much shorter update?
Hit:1 http://archive.canonical.com/ubuntu bionic InRelease
Hit:3 http://archive.ubuntu.com/ubuntu bionic InRelease
Hit:5 http://archive.ubuntu.com/ubuntu bionic-updates InRelease
Hit:7 http://archive.ubuntu.com/ubuntu bionic-backports InRelease
Hit:8 http://archive.ubuntu.com/ubuntu bionic-security InRelease
Fetched 1,310 B in 2s (579 B/s)
Reading package lists... Done
Building dependency tree
Reading state information... Done
A:
This is normal, apt is downloading updated package lists, metadata, icons, translations for each of your configured repositories. “Hit” means a file hasn’t changed since its last download, “Get” means it has and apt has downloaded it.
Your second run only checked the InRelease files; these contain an index, with checksums, of the various other indexes that apt update might download, and allow apt to determine if any have changed compared to what’s currently on your system. If nothing has changed, it doesn’t download anything else. You can see this in your first run too: the first two InRelease files hadn’t changed, so nothing else was downloaded for those repositories.
| {
"pile_set_name": "StackExchange"
} |
Q:
$\int(x+1)dx$ yielding different results with $u$-substitution and termwise integration
Considering two methods of integrating the very easy:
$\int(x+1)dx$
First just going term by term:
$\int(x+1)dx = x^2/2 + x + C$
Or by making a u-subtitution. Let $u = x+1$, then $du = dx$ and the integral becomes
$\int u du = u^2/2$ = $\frac {(x+1)^2}{2} + C$, which is not the same. Where have I gone wrong?
A:
They are equivalent, they differ by a constant.
Change your second $C$ to $D$ and we have $C=\frac12 +D$.
A:
The two results differ by a constant, which is zero when differentiated.$$\frac 12(x+1)^2=\frac 12x^2+x+\color{red}{\frac 12}=\frac 12x^2+x+\color{red}{C}$$
In fact, generally when you're evaluating an indefinite integral and you get two different results, most of the time, they're both valuable answers because they differ by a constant and not because you messed up in your work.
Of course, you can still make a mistake when evaluating indefinite integrals. I'm just saying, most of the time, it's the constant that changes the result and not your "error" you made.
| {
"pile_set_name": "StackExchange"
} |
Q:
Log4j2: How to find out in console logs whether the logging configuration file has been located
I want to know if log4j2 has found my configuration file or the errors it encountered while looking for it. Basically, I want to see log4j2's own logs.
I'm actually trying to put the (non-standard) log file name and location in web.xml as described here and I want to know why its not getting picked up
Here's my web.xml
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>classpath:log4j2-assessment.xml</param-value>
</context-param>
<context-param>
<param-name>isLog4jContextSelectorNamed</param-name>
<param-value>false</param-value>
</context-param>
(Additional info: Why I need to do all this is because I want to give a custom name to my log4j2.xml file and I cannot do that in application.properties using the logging.file property because I have a custom name for application.properties itself, and with a custom name, the logging.file property isn't loaded by Spring in time for the logging to start)
P.S: If I don't rename the log4j2.xml file, it gets picked up without a problem.
A:
I want to see log4j2's own logs.
You can set the logging level of the logger to TRACE with help of run configs:
org.apache.logging.log4j.simplelog.StatusLogger.level=TRACE
Source: here (scroll to "Status Messages")
The output displays explicitly what config files are searched and where.
Please, be aware that there is no ouput, if a file was successfully found, it just stops searching as soon as one was found.
To proof this works, just add a dummy log4j2.properties - log4j2 should stop searching any config file after that, meaning the filename searched for last is the one that was found.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error $ is not defined in Angular Universal
I have this problem in Angular Universal
ERROR ReferenceError: $ is not defined
Does anyone know any way to solve it?
This is the part of code that fails
//some imports ...
declare var $ : any;
ngOnInit() {
generateDirectory(){
this.api.getCities('country_id='+3996063).subscribe(res => {
$("#find").append("<ul class='findDir'>");
for(let c in res){
$("#find>ul").append('<li><a href="/find/'+res[c].name.split(' ').join('_').toLowerCase()+'">'+res[c].name+'</a></li>');
}
$("#find").append("</ul>");
});
}
}
A:
You should not use jQuery when using Angular, really. Angular has all the tools to manipulate HTML the way you want it. This would be the correct way to do it Angular-way:
interface City {
name: string;
}
class CitiesComponent implements OnInit {
public cities$: Observable<City[]>;
constructor(private readonly api: ApiClient) {}
ngOnInit() {
this.cities$ = this.api.getCities(`country_id=3996063`);
}
}
<ul class="findDir" *ngIf="(cities$ | async) as cities">
<li *ngFor="let city of cities">
<a [attr.href]="'/find/' + city.name.split(' ').join('_').toLowerCase()">{{city.name}}</a>
</li>
</ul>
I hope that I didn't leave any mistakes. But the idea is that you create a subscription of cities$ which is of type City[].
Then in template code you subscribe to it using async pipe and then iterate over list of cities using *ngFor directive
To do it even better, I'd advice again any kind of functions to be called from template and try to do as much as possible within your subscription, so that would be it:
interface City {
name: string;
}
class CitiesComponent implements OnInit {
public cities$: Observable<City[]>;
constructor(private readonly api: ApiClient) {}
ngOnInit() {
this.cities$ = this.api.getCities(`country_id=3996063`).pipe(
map(cities => cities.map(city => ({
...city,
url: city.name.split(' ').join('_').toLowerCase()
}))
)
);
}
}
<ul class="findDir" *ngIf="(cities$ | async) as cities">
<li *ngFor="let city of cities">
<a [attr.href]="city.url">{{city.name}}</a>
</li>
</ul>
as you can see, I do use map pipe operator to add url property to Observable instead of doing that in template. This is better practice.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error with position
I get error:
ERROR: The left-hand side of an assignment must be a variable, a property or an indexer
What is the problem?
A:
The type of Transform.position is Vector3, which is a struct. That means when you access it, you get a copy of the value. Then ScreenToWorldPoint takes that value and returns another Vector3. Mutating that value wouldn't do anything useful - it wouldn't change anything in the transform, which is presumably what you're trying to achieve. It sounds like you probably want something like:
var transform = GameObject.FindWithTag("Object").transform;
var position = Camera.main.ScreenToWorldPoint(transform.position);
position.x -= 10;
transform.position = Camera.main.WorldToScreenPoint(position);
Note the conversion back from world to screen co-ordinates, to keep everything in the original context.
Having written all of this, it should be noted that I've never done any Unity3d coding - this is just on the basis of regular C#.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is uncertainty and correlations actualy the same thing?
In this paper on page 2 it is said that
The entropy $S(\rho_A)$ measures the amount of correlation (classical and/or quantum) between $A$ with the external world.
Now this is confusing me a little bit. If I have a quantum system described by a density operator $\rho$ I thought that $S(\rho)$ would be a measure of the uncertainty in the actual pure state of the system. In other words, this seems to be exactly like statistical physics where we have a system, we don't know the actual microscopic state, but we have some probability distribution for it.
Actually, since $\rho$ is hermitian, there is a basis such that
$$\rho=\sum_i p_i |\psi_i\rangle \langle \psi_i|,$$
and we can think that we have an ensemble of identical systems, such that if we pick one of them randomly it has probability $p_i$ of being in the state $|\psi_i\rangle$.
In that description, we have that
$$S(\rho)=-\operatorname{Tr}\rho\ln\rho=-\sum p_i \ln p_i,$$
which is the entropy of the probability distribution $\{p_i\}$ of said ensemble.
So indeed it seems to quantify the uncertanty in the state of the system.
So why "it measures the amount of correlation with the external world"? Is correlation with the external world equivalent to uncertainty in the state? If so, how is this, because I truly fail to see it.
A:
Just to expand a little bit Bruce's answer...You can convince yourself about the properties of the Von Neumann entropy by proving two simple properties.
Let suppose to have a state $\rho$ in a $d$-dimensional Hilbert space $\mathcal{H}$ . Then:
1) $\rho$ is pure $\iff S(\rho)=0$.
2) The maximum value of $S(\rho)$ is $\log d$, and it occurs when $\rho$ is the maximally mixed state in $\mathcal{H}$.
If you take these two extreme cases, the relationship between entanglement, correlations (with external systems) and Von-Neumann entropy is evident. In the first case you have a pure state. Thus, it cannot be entangled with anything else and the entropy is zero.
In the latter case, the state is maximally mixed. Therefore, you can take a purification $|\psi\rangle$ of $\rho$ which is maximally entangled (i.e., the purification $|\psi\rangle$ is a maximally entangled state). Indeed, the entropy is maximum.
Of course, Von Neumann entropy also quantifies the uncertainty "in the preparation of a state" (like Shannon entropy does in classical communication theory).
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I get the content of body element by using html5lib in Python?
How can I get the content of <body> element by using html5lib in Python?
Example input data: <html><head></head><body>xxx<b>yyy</b></hr></body></html>
Expected output: xxx<b>yyy</b></hr>
It should work even if HTML is broken (unclosed tags,...).
A:
html5lib allows you to parse your documents using a variety of standard tree formats. You can do this using lxml, as I've done below, or you can follow the instructions in their user documentation to do it either with minidom, ElementTree or BeautifulSoup.
file = open("mydocument.html")
doc = html5lib.parse(file, treebuilder="lxml")
content = doc.findtext("html/body", default=None):
Response to comment
It is possible to acheive this without installing any external libs using their own simpletree.py, but judging by the comment at the start of the file
I would guess this is not the recommended way...
# Really crappy basic implementation of a DOM-core like thing
If you still want to do this, however, you can parse the html document like so:
f = open("mydocument.html")
doc = html5lib.parse(f)
and then find the element you're looking for by doing a breadth-first search of the child nodes in the document. The nodes are kept in an array named childNodes and each node has a name stored in the field name.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where does this accent belong to?
I'm going insane trying to identify this accent that appears in The Name of the Wind by Patrick Rothfuss. It's supposed to be bumpkin accent, but I don't have much more information about location. Could someone give me a hand?
He came up to where we stood, his weathered face grim as he squinted at us. “Wat are the tae o’ yeh daen oot here?” he said suspiciously. “Oi taut Oi heard sengen.”
“At twere meh coosin,” I said, making a nod toward Denna. “Shae dae have a loovlie voice far scirlin, dain’t shae?” I held out my hand. “Oi’m greet glad tae meet ye, sar. Y’clep me Kowthe.”
He looked taken aback when he heard me speak, and a good portion of the grim suspicion faded from his expression. “Pleased Oi’m certain, Marster Kowthe,” he said, shaking my hand. “Et’s a rare troit tae meet a fella who speks propper. Grummers round these ports sound loik tae’ve got a mouth fulla wool.”
A:
In my opinion, the words Wat, daen, daen oot would suggest a Scottish accent.
The sentence Oi taught i heard Sengen sounds very Irish because of the lack of "h" proceeding "t".
I actually think the accent being portrayed is a West Country accent.
The words dain't, Marster and loik most definitive do not sound Irish and don't really sound Scottish (try and say the "r" in "Marster" in a Scottish accent).
I just read the plot of the book on Wikipedia and given the plot, it seems highly unlikely that the accent portrayed is actually a 'real accent' at all, rather an accent conjured by the author to fit the character.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fire a function when data gets read by a unique user?
How can I fire a function once data gets read by a unique user?
Cloud Functions has a parameter called onWrite. Is there something like onRead?
A:
There is currently no way to trigger Cloud Functions when a user reads data.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fuji Transonic 2.8 2016: rear derailleur hanger direct mount or standard?
I have a Fuji Transonic 2.8 from 2016 that has the following hanger installed:
https://wheelsmfg.com/derailleur-hanger-215.html
I am replacing the short cage Shimano 105 rear derailleur with the medium cage version to be able to use an 11-34 cassette.
Now the previous bike mechanic installed the short cage derailleur with the b-link removed, so clearly it was being treated as direct mount hanger, but I want to make sure that I should do the same with the medium cage derailleur. Couldn't find any documentation anywhere on which type the above hanger is, found a bunch of sites trying to explain the direct mount vs standard distinction but they all look the same to me. I want to make sure I don't remove the b-link by mistake when it is really needed.
Thanks.
A:
TLDR: You have a standard mount hanger, leave the B pivot on the derailleur.
Looking at this Wheels Manufacturing page, what they call 'direct' hangers put the M10 mounting hole further to the rear than 'standard' hangers.
I believe that with the newer groupset series that introduced 'Shadow Technology' (moving the derailleur in and behind the cassette a bit) Shimano wanted the B pivot further rearward than previous designs and added the B-link to do this. They provided for original bicycle manufacturers and third party hanger manufacturers to make 'direct' hangers by making the B-link removable.
If your hanger goes straight down it's a standard type, use the B-pivot. If your hanger goes down and rearward at about 45 degrees, and there is a horizontal separation between the axle and M10 mounting hole of 1-2cm it's a direct type, remove the B-pivot.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's better: Writing functions, or writing methods? What costs more performance?
Currently I am making some decisions for my first objective-c API. Nothing big, just a little help for myself to get things done faster in the future.
After reading a few hours about different patterns like making categories, singletons, and so on, I came accross something that I like because it seems easy to maintain for me. I'm making a set of useful functions, that can be useful everywhere.
So what I did is:
1) I created two new files (.h, .m), and gave the "class" a name: SLUtilsMath, SLUtilsGraphics, SLUtilsSound, and so on. I think of that as kind of "namespace", so all those things will always be called SLUtils******. I added all of them into a Group SL, which contains a subgroup SLUtils.
2) Then I just put my functions signatures in the .h file, and the implementations of the functions in the .m file. And guess what: It works!! I'm happy with it, and it's easy to use. The only nasty thing about it is, that I have to include the appropriate header every time I need it. But that's okay, since that's normal. I could include it in the header prefix pch file, though.
But then, I went to toilet and a ghost came out there, saying: "Hey! Isn't it better to make real methods, instead of functions? Shouldn't you make class methods, so that you have to call a method rather than a function? Isn't that much cooler and doesn't it have a better performance?" Well, for readability I prefer the functions. On the other hand they don't have this kind of "named parameters" like methods, a.f.a.i.k..
So what would you prefer in that case?
Of course I dont want to allocate an object before using a useful method or function. That would be harrying.
Maybe the toilet ghost was right. There IS a cooler way. Well, for me, personally, this is great:
MYNAMESPACECoolMath.h
#import <Foundation/Foundation.h>
@interface MYNAMESPACECoolMath : NSObject {
}
+ (float)randomizeValue:(float)value byPercent:(float)percent;
+ (float)calculateHorizontalGravity:(CGPoint)p1 andPoint:(CGPoint)p2;
// and some more
@end
Then in code, I would just import that MYNAMESPACECoolMath.h and just call:
CGFloat myValue = [MYNAMESPACECoolMath randomizeValue:10.0f byPercent:5.0f];
with no nasty instantiation, initialization, allocation, what ever. For me that pattern looks like a static method in java, which is pretty nice and easy to use.
The advantage over a function, is, as far as I noticed, the better readability in code. When looking at a CGRectMake(10.0f, 42.5f, 44.2f, 99.11f) you'll may have to look up what those parameters stand for, if you're not so familiar with it. But when you have a method call with "named" parameters, then you see immediately what the parameter is.
I think I missed the point what makes a big difference to a singleton class when it comes to simple useful methods / functions that can be needed everywhere. Making special kind of random values don't belong to anything, it's global. Like grass. Like trees. Like air. Everyone needs it.
A:
Performance-wise, a static method in a static class compile to almost the same thing as a function.
Any real performance hits you'd incur would be in object instantiation, which you said you'd want to avoid, so that should not be an issue.
As far as preference or readability, there is a trend to use static methods more than necessary because people are viewing Obj-C is an "OO-only" language, like Java or C#. In that paradigm, (almost) everything must belong to a class, so class methods are the norm. In fact, they may even call them functions. The two terms are interchangeable there. However, this is purely convention. Convention may even be too strong of a word. There is absolutely nothing wrong with using functions in their place and it is probably more appropriate if there are no class members (even static ones) that are needed to assist in the processing of those methods/functions.
A:
The problem with your approach is the "util" nature of it. Almost anything with the word "util" it in suggests that you have created a dumping ground for things you don't know where to fit into your object model. That probably means that your object model is not in alignment with your problem space.
Rather than working out how to package up utility functions, you should be thinking about what model objects these functions should be acting upon and then put them on those classes (creating the classes if needed).
To Josh's point, while there is nothing wrong with functions in ObjC, it is a very strongly object-oriented language, based directly on the grand-daddy of object-oriented languages, Smalltalk. You should not abandon the OOP patterns lightly; they are the heart of Cocoa.
I create private helper functions all the time, and I create public convenience functions for some objects (NSLocalizedString() is a good example of this). But if you're creating public utility functions that aren't front-ends to methods, you should be rethinking your patterns. And the first warning sign is the desire to put the word "util" in a file name.
EDIT
Based on the particular methods you added to your question, what you should be looking at are Categories. For instance, +randomizeValue:byPercent: is a perfectly good NSNumber category:
// NSNumber+SLExtensions.h
- (double)randomizeByPercent:(CGFloat)percent;
+ (double)randomDoubleNear:(CGFloat)percent byPercent:(double)number;
+ (NSNumber *)randomNumberNear:(CGFloat)percent byPercent:(double)number;
// Some other file that wants to use this
#import "NSNumber+SLExtensions.h"
randomDouble = [aNumber randomizeByPercent:5.0];
randomDouble = [NSNumber randomDoubleNear:5.0 byPercent:7.0];
If you get a lot of these, then you may want to split them up into categories like NSNumber+Random. Doing it with Categories makes it transparently part of the existing object model, though, rather than creating classes whose only purpose is to work on other objects.
| {
"pile_set_name": "StackExchange"
} |
Q:
what is the most aggresive FLUSH / RESET mysql command to clear query cache (and anything else...)
i am reading here on mysql.com, there are multiple variants of this FLUSH / RESET command.
what is the most aggressive method of flushing EVERYTHING POSSIBLE (caches, buffers, EVERYTHING) from mysqld?
we want to get as close to 'just started' as possible, without shutting down the daemon.
thanks!
A:
I guess these should do:
RESET QUERY CACHE;
FLUSH STATUS, TABLES WITH READ LOCK;
Please read the appropriate manual sections and make sure you know what you are doing ;)
http://dev.mysql.com/doc/refman/5.1/en/reset.html
http://dev.mysql.com/doc/refman/5.1/en/flush.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Background script to send notifications in php
I have a code which needs to send notifications to all users in the database
function sendPushNotificationToUsers($users, $message)
{
$iPhoneUsers = array();
$androidUsers = array();
foreach ($users as $user)
{
if($user['deviceType'] == "iPhone")
$iPhoneUsers[] = $user;
else if($user['deviceType'] == "Android")
$androidUsers[] = $user;
}
sendApplePushNotifications($iPhoneUsers, $message);
//sendGooglePushNotifications($androidUsers, $message);
return true;
}
Its usually going to take 2-3 hours. How can i run this code inside a script which can run in background while i navigate other things in php ? I run this code from a form.
A:
Use the following at the top of your php script:
set_time_limit(0);
ignore_user_abort(true);
The above code ensures that, even if you close your browser/ssh session, the script will run until it finishes or the web server service is restarted.
set_time_limit
Set the number of seconds a script is allowed to run. If this is
reached, the script returns a fatal error. The default limit is 30
seconds or, if it exists, the max_execution_time value defined in the
php.ini.
When called, set_time_limit() restarts the timeout counter from zero.
In other words, if the timeout is the default 30 seconds, and 25
seconds into script execution a call such as set_time_limit(20) is
made, the script will run for a total of 45 seconds before timing out.
ignore_user_abort
Sets whether a client disconnect should cause a script to be aborted.
When running PHP as a command line script, and the script's tty goes
away without the script being terminated then the script will die the
next time it tries to write anything, unless value is set to TRUE
| {
"pile_set_name": "StackExchange"
} |
Q:
Wordpress wpdb->prepare sql string from form
I'm currently using a custom wordpress table to store an external xml feed and this information needs to be filterable by a basic html form with several options.
What is the best way to go about this and build the string using wpdb->prepare? I'm using the below for my pagination and the $user_query is currently set to $user_query .= "ANDquery1LIKE $query1 "; etc.
However i feel like this could lead to problems as i'm not doing it through the second parameter such as %d, $variable etc.
//Get Results
$results = $wpdb->get_results(
$wpdb->prepare("SELECT * FROM `feed` WHERE `price` != 0 $user_query LIMIT %d,
%d", $offset, $items_per_page, OBJECT)
);
I hope the above makes sense. I'm just trying to build the SQL query from the form $_GET values with no SQL injection issues.
Many thanks
A:
You can call $wpdb->prepare on partial queries:
$user_query = $wpdb->prepare('AND query1 LIKE %s', $query1);
You can also call esc_sql directly on user input to sanitize it.
Also, LIKE expressions need to be escaped separately:
https://codex.wordpress.org/Class_Reference/wpdb/esc_like
$wpdb->esc_like escapes character specific to like expressions (%, \, _), but does not do any additional escaping. You still need to call prepare or esc_sql after escaping a like expression.
Update: Using this example from the comments:
$user_query = $_GET['query1'];
$user_query2 = $_GET['query2'];
$user = $wpdb->prepare('AND query1 = %s ', $user_query);
$user2 = $wpdb->prepare('AND query2 = %s ', $user_query2);
$results = $wpdb->get_results( $wpdb->prepare('SELECT * FROM test WHERE price != 0' . $user . $user2 . 'LIMIT 20') );
Here there isn't any point to building the query in parts, you could just build your query like this:
$query = 'SELECT * FROM test
WHERE price != 0
AND query1 = %s
AND query1 = %s
LIMIT 20';
$results = $wpdb->get_results( $wpdb->prepare($query, $user_query, $user_query2) );
For the sake of example, I'll assume that the user queries are optional. If that is the case then you need to prepare your WHERE conditions separately only if the parameter is provided:
$query = 'SELECT * FROM test
WHERE price != 0';
if($user_query) {
$cond = $wpdb->prepare(' AND query1 = %s', $user_query);
$query .= $cond;
}
if($user_query2) {
$cond = $wpdb->prepare(' AND query2 = %s', $user_query2);
$query .= $cond;
}
$query .= ' LIMIT 20';
$results = $wpdb->get_results( $query );
Note that there is no need to call prepare on the query when passing it to get_results as all user input has already been sanitized.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a naming convention for the various standard-formats as they existed throughout history?
It's very typical to say "current standard". Right now that means Innistrad (with Dark Ascension, Avacyn Restored, and M13) and Return to Ravnica (with Gatecrash, Dragon's Maze, and soon to come M14). Years from now, when these long past rotated out of standard, how might I reference the name of this set "standard" play (or any other "previous current standard"? Is there a convention for it?
A:
You can:
Refer to the blocks: "Scars-Innistrad Standard," or just "Scars Standard" (using the name of the full block, which tends to define the format more) is very common. People are likely to place it into context at a glance, but it lacks some specificity, though that's mostly relevant for flash-in-the-pan decks that vanish when the next set tweaks the card pool.
Refer to the most recent set released: "NPH Standard." This is the most specific. The one downside is that some players don't remember all the small sets too well. This approach is concise and the card pool is totally unambiguous, with the rare exceptions of mid-season bans. Also it's pretty clunky when the last set is a core set.
Refer to a year: "In 2005, the best deck was..." People can look up the sets or figure them out from context.
Refer to a deck: Honestly, most often when people discuss old Standard they are just talking about a famous top deck — Caw-Blade, Faeries, Affinity, Academy, &c. — or a deck with some rare and special oddball name (Owling Mine). Not that great if you're trying to discuss the difference between red decks in 2003 and 2005, of course.
Oftentimes articles will do a bit of scene-setting, telling you the year and what blocks were in Standard in prose form. If you're writing out other information in an expansive way anyway (like a mention of the top cards or top decks of the time period, to provide context about how this deck works), you might as well save a bit of jargon and use a full sentence to describe the format.
| {
"pile_set_name": "StackExchange"
} |
Q:
Encoding a C string.
I want to write a program that takes as an input a string and returns an encoded string. An encoded string would be string where each of the characters present in the original string are shifted by a few fixed number of places.
Eg. Suppose each character in a string is shifted by 2 places. So if the user enters 'abcd' the output will be 'cdef'.
I am able to do it by taking the whole string as input and then processing each character to give the final output string.
But what I want is that as soon as the user enters a character, it should be shown in its encoded form and not its original form.
I tried the following code for a single character.
char r;
scanf("%c",&r);
printf("\b%c",r+2);
But the user is still able to see he character he entered. The encoded character doesn't appear unless I press 'Enter'. How can I rectify this? Maybe using another function to get the character? Any help appreciated.
A:
If you are on UNIX, you can change the mode of the terminal like this:
#include <stdlib.h>
#include <stdio.h>
int main( void ) {
system( "stty -icanon 2>/dev/null" ); // this line sets the mode
while( 1 ) {
int c = getc( stdin ); // a simpler way to get character input
printf( "\b%c", c + 2 ); // print the shifted value
}
}
stty -icanon sets "canonical input", which means you can get input the moment it is typed, instead of waiting for a newline (it's quite complicated and I don't fully understand everything it does, but it has the right effect). See the man page for full details. As I understand it, it sets a mode where a single character is enough to return the input, instead of waiting for a newline. You can also use min N to change that to wait for 2 or more characters, or time N to only wait a certain time before giving up (in tenths of a second).
The 2>/dev/null is a common syntax for redirecting stderr to /dev/null, which just means "ignore any errors".
On Windows, this won't work, and you should use getch as already suggested.
Finally, your cypher code is a bit odd; typing y and z will produce { and |!
| {
"pile_set_name": "StackExchange"
} |
Q:
Add syntax highlighting language code lang-r to [data.table]
This post title follows the pattern of another FR from earlier this year that was successful. Data.table is an R library and its docs would benefit from R syntax highlighting. Let me know if any more info is needed.
Now that docs are here and we want many libraries' docs to live separately from their parent languages, I guess there will be a lot of requests like this. For reference, here are all the supported language codes.
While you're at it, there are several other R libraries that have tags likely to get their own docs (dplyr, ggplot2, ...).
A:
This has been completed. I've set the syntax highlighting for data.table, dplyr, and ggplot2 to be lang-r.
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting the surface from Draggable
Please guys, help me out. I have this code:
var image = new ImageSurface({
size: [300, 300],
properties: {
border: '4px solid white'
}
});
image.setContent('/img/' + _.random(1,7) + '.jpg');
var draggable = new Draggable({scale: 1});
image.pipe(draggable);
draggable.on('end', function(e) {
// SURFACE????
});
var stateModifier = new StateModifier();
node.add(stateModifier).add(draggable).add(image);
stateModifier.setTransform(
Transform.translate(100, 10, 0),
{ duration : 1000, curve: Easing.outElastic }
);
How can I get the Surface object from the draggable event? The parameter from the event is just the position.
A:
First, I am wondering why you need to get the surface from the event. If you have one draggable per surface, then you could do something with simple data binding.
eg..
var draggable = new Draggable({scale: 1});
draggable.image = image;
draggable.on('end', function(e) {
var image = this.image;
});
If you really need to get the surface from the event you will have to edit the code that emits the event.
Just for the case of the end event..
Starting at line 129 of Draggable.js
function _handleEnd() {
if (!this._active) return;
this.eventOutput.emit('end', {position : this.getPosition()});
}
Could be changed to..
function _handleEnd() {
if (!this._active) return;
this.eventOutput.emit('end', {position : this.getPosition(), originalEvent:event });
}
Now you can do..
var draggable = new Draggable({scale: 1});
draggable.on('end', function(e) {
var image = e.originalEvent.origin;
});
Good Luck!
| {
"pile_set_name": "StackExchange"
} |
Q:
How create a link on the master page when ever no one is signed in
I created a site with anonymous access and forms based authentication. Now I want to show the link to create a new user in the master page when ever no one is signed in. Can any one please help to achieve this process? Following are the screen shots for more details.
A:
You could add a delegate control and user control to check to your master page, and check if the user is anonymous then show the link :)
Add a Delegate control to your master page:
<SharePoint:DelegateControl runat="server" ControlId="PageHeader">
</SharePoint:DelegateControl>
Only thing to note here at this stage is the ControlId attribute - the Feature we create will use this to substitute the real user/server control.
Then we have the feature.xml file, where we specify the feature details (including scope):
<Feature xmlns="http://schemas.microsoft.com/sharepoint/" Id="373042ED-718D-46e2-9596-50379DA4D522"
Title="COB.Demos.DelegateControls"
Description="Specifies which user control should be used for the 'PageHeader' DelegateControl used on the site master page. The replacement user control is stored in the CONTROLTEMPLATES directory." Scope="Farm"
Hidden="FALSE"
Version="1.0.0.0">
<ElementManifests>
<ElementManifest Location="elements.xml"/>
</ElementManifests>
</Feature>
the 'instructions' for the feature are in the element manifest:
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<!-- using a sequence number LOWER than default of 100 so our custom control gets loaded -->
<Control Id="PageHeader" Sequence="90" ControlSrc="~/_ControlTemplates/COBPageHeader.ascx" />
</Elements>
In the COBPageHeader.ascx code-behind, add the logic of hiding link.
| {
"pile_set_name": "StackExchange"
} |
Q:
Struct C++ array in function parameters not working at all
hello i have to do a program using an array of structures.. and i have to initialize it in a function. below i am trying, but my prototype keeps getting error "Expected primary expression".. i have followed tutorials but cant figure out what im doing wrong please help. i cant use pointers or vectors.. just basic stuff thank you for your time
struct gameCases{
bool flag = false;
int casenum;
double value;
};
int initialize(gameCases cases); //prototype
--- main()
gameCases cases[26];
initialize(cases); //call
int initialize(gameCases cases) //definition
{
double values[26] = {.01, 1, 5, 10, 25, 50,
75, 100, 200, 300, 400, 500, 750, 1000,
5000, 10000 , 25000, 50000, 75000, 100000,
200000 , 300000, 400000, 500000,
1000000, 2000000};
for (int i = 0; i < 26; i++)
{
array[i].value = values[i];
}
}
A:
int initialize(gameCases cases[26]); //prototype
int initialize(gameCases cases[26]) //definition
{
double values[26] = {.01, 1, 5, 10, 25, 50,
75, 100, 200, 300, 400, 500, 750, 1000,
5000, 10000 , 25000, 50000, 75000, 100000,
200000 , 300000, 400000, 500000,
1000000, 2000000};
for (int i = 0; i < 26; i++)
{
cases[i].value = values[i];
}
}
and to call:
initialize(cases);
| {
"pile_set_name": "StackExchange"
} |
Q:
Usage of "is" with "and"
I am confused in using this sentence.
"Code in SVN and Test case document is updated accordingly."
I am thinking of using are instead because "Code" here is a set of Source Code files and "Test case document" is a single document file.
But are would contradict with "document" which is singular. So which form should I use?
Any help would be appreciated.
A:
**I'm assuming code is referring collectively to all the pieces of coding in files SVN and Test case document.
In this sentence:
"Code in SVN and Test case document is updated accordingly."
the code is being updated, which is present in the files SVN and Test case document. Since 'code' is singular, you should use 'is', not 'are'.
We aren't referring to the SVN and TCD while talking about the updating. That is only to do with the code. So we check out the plurality by seeing 'code'.
Even if your sentence were, say:
"The code in all the files has been updated."
Even though 'files' is plural, it is the singular 'code' which is being updated. This is why we use 'has been updated' (which is used for singular) rather than 'have been updated' (which would have been used in case of plural).
Check out this sentence:
"The Java codes in the file are being updated."
Over here, we've used 'are' because the update is happening to the Java codes, which is plural. Even though the word just before 'are' is singular (file).
| {
"pile_set_name": "StackExchange"
} |
Q:
Highlight product features image with css and jquery
I am creating a product features page that highlights the area of an image and a corresponding description. I have opted to use divs with absolute positioning, instead of an image map. I have the page working, but my jquery is lacking and I would like to know the best way writing the following script?
$(document).ready(function(){
$('#feature_1').mouseover(function(){
$(this).find('.features_heading').css('color', '#CE4125');
$('#feature_1_highlight').css('display', 'inherit');
});
$('#feature_1').mouseout(function(){
$(this).find('.features_heading').css('color','#56534F');
$('#feature_1_highlight').css('display', 'none');
});
$('#feature_2').mouseover(function(){
$(this).find('.features_heading').css('color', '#CE4125');
$('#feature_2_highlight').css('display', 'inherit');
});
$('#feature_2').mouseout(function(){
$(this).find('.features_heading').css('color','#56534F');
$('#feature_2_highlight').css('display', 'none');
});
$('#feature_3').mouseover(function(){
$(this).find('.features_heading').css('color', '#CE4125');
$('#feature_3_highlight').css('display', 'inherit');
});
$('#feature_3').mouseout(function(){
$(this).find('.features_heading').css('color','#56534F');
$('#feature_3_highlight').css('display', 'none');
});
$('#feature_4').mouseover(function(){
$(this).find('.features_heading').css('color', '#CE4125');
$('#feature_4_highlight').css('display', 'inherit');
});
$('#feature_4').mouseout(function(){
$(this).find('.features_heading').css('color','#56534F');
$('#feature_4_highlight').css('display', 'none');
});
$('#feature_5').mouseover(function(){
$(this).find('.features_heading').css('color', '#CE4125');
$('#feature_5_highlight').css('display', 'inherit');
});
$('#feature_5').mouseout(function(){
$(this).find('.features_heading').css('color','#56534F');
$('#feature_5_highlight').css('display', 'none');
});
$('#feature_6').mouseover(function(){
$(this).find('.features_heading').css('color', '#CE4125');
$('#feature_6_highlight').css('display', 'inherit');
});
$('#feature_6').mouseout(function(){
$(this).find('.features_heading').css('color','#56534F');
$('#feature_6_highlight').css('display', 'none');
});
});
.features_left, .woocommerce .features_right {
width:295px;
height:380px;
float:left;
margin-bottom:30px;
}
.features_heading {
text-transform:uppercase;
font-weight:800;
font-size:.8em;
width:100%;
padding-bottom:5px;
}
.features_desc {
font-size:.8em;
width:100%;
padding-bottom:45px;
line-height:1.5;
}
.features_image {
width:380px;
height:380px;
float:left;
margin:0 20px;
position:relative;
}
.features_image img{
width:380px;
}
.feature_highlight {
position:absolute;
width: 40px;
height: 40px;
background: rgba(206,65,37,0.50);
border:4px solid #CE4125;
-moz-border-radius: 20px;
-webkit-border-radius: 20px;
border-radius: 20px;
z-index:10;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="features_left">
<div id="feature_1">
<div class="features_heading highlight">Title 1</div>
<div class="features_desc">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div>
</div>
<div id="feature_3">
<div class="features_heading">Title 3</div>
<div class="features_desc">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div>
</div>
<div id="feature_5">
<div class="features_heading">Title 5</div>
<div class="features_desc">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div>
</div>
</div>
<div class="features_image">
<img src="http://lorempixel.com/300/300/technics" >
<div id="feature_1_highlight" class="feature_highlight" style="top:50px; left:50px;"></div>
<div id="feature_2_highlight" class="feature_highlight" style="top:150px; left:100px;"></div>
<div id="feature_3_highlight" class="feature_highlight" style="top:200px; left:50px;"></div>
<div id="feature_4_highlight" class="feature_highlight" style="top:250px; left:150px;"></div>
<div id="feature_5_highlight" class="feature_highlight" style="top:50px; left:200px;"></div>
<div id="feature_6_highlight" class="feature_highlight" style="top:150px; left:150px;"></div>
</div>
<div class="features_right">
<div id="feature_2">
<div class="features_heading">Title 2</div>
<div class="features_desc">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div>
</div>
<div id="feature_4">
<div class="features_heading">Title 3</div>
<div class="features_desc">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div>
</div>
<div id="feature_6">
<div class="features_heading">Title 4</div>
<div class="features_desc">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div>
</div>
</div>
I included the HTML and CSS for reference. It is best to view full screen. (The image is randomly generated, so who knows what you will get!)
A:
The way I would do it is.
Since, on mouseover you want to highlight a particular feature and you know which element should highlight which features. I would add the targeted feature's id as part of the data-attribute like so.
<div class="features_left">
<div class="feature" data-highlight="#feature_1_highlight">
<div class="features_heading highlight">Title 1</div>
<div class="features_desc">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div>
</div>
<div class="feature" data-highlight="#feature_2_highlight">
<div class="features_heading">Title 3</div>
<div class="features_desc">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div>
</div>
<div class="feature" data-highlight="#feature_3_highlight">
<div class="features_heading">Title 5</div>
<div class="features_desc">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div>
</div>
</div>
<div class="features_image">
<img src="http://lorempixel.com/300/300/technics" >
<div id="feature_1_highlight" class="feature_highlight" style="top:50px; left:50px;"></div>
<div id="feature_2_highlight" class="feature_highlight" style="top:150px; left:100px;"></div>
<div id="feature_3_highlight" class="feature_highlight" style="top:200px; left:50px;"></div>
<div id="feature_4_highlight" class="feature_highlight" style="top:250px; left:150px;"></div>
<div id="feature_5_highlight" class="feature_highlight" style="top:50px; left:200px;"></div>
<div id="feature_6_highlight" class="feature_highlight" style="top:150px; left:150px;"></div>
</div>
<div class="features_right">
<div class="feature" data-highlight="#feature_4_highlight">
<div class="features_heading">Title 2</div>
<div class="features_desc">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div>
</div>
<div class="feature" data-highlight="#feature_5_highlight">
<div class="features_heading">Title 3</div>
<div class="features_desc">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div>
</div>
<div class="feature" data-highlight="#feature_6_highlight">
<div class="features_heading">Title 4</div>
<div class="features_desc">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</div>
</div>
</div>
And now my javascript will look like this.
$(document).ready(function(){
$('.feature').mouseover(function(){
$(this).find('.features_heading').css('color', '#CE4125');
$($(this).attr("data-highlight")).css('display', 'inherit');
}).mouseout(function(){
$(this).find('.features_heading').css('color','#56534F');
$($(this).attr("data-highlight")).css('display', 'none');
});
});
JSFiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Removing Collection Entity From Within EF4 Entity Method
I am trying to simplify my code and am moving some of the core logic on to the Entity Framework entities themselves (Seems like that is why we have entities that model business logic). Presently entities are pretty much just a bunch of properties and collections.
I am looking at having a function on the entity that removes an item from a collection and adds it to another collection on the entity.
Now the add to the other collection function works perfectly. However the remove - removes the item from the collection however it doesn't delete.
I get:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable.
I understand that this is because removing from collection doesn't actually mark for delete and when context save changes occurs it is upset by the key being nulled but not marked for removal. As I am not in a repository and have no access to the context within. How am I supposed to let the context know that this item needs to be deleted?
I thought I was supposed to make sure domain entities encapsulated appropriate business logic. Is this just the wrong thing to be doing? How can I get around this? Should I get around this?
If I use the extension method:
public static ObjectContext GetContext(this IEntityWithRelationships entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
var relationshipManager = entity.RelationshipManager;
var relatedEnd = relationshipManager.GetAllRelatedEnds()
.FirstOrDefault();
if (relatedEnd == null)
throw new Exception("No relationships found");
var query = relatedEnd.CreateSourceQuery() as ObjectQuery;
if (query == null)
throw new Exception("The Entity is Detached");
return query.Context;
}
I can access the context within the entity like this:
var context = this.GetContext() as Entities;
context.events.DeleteObject(event);
This seems hideous but does work. Surely doing this can't be the right way?
A:
I changed the models to make the relationships between parent and child identities identifying relationships by using a composite key containing the parents key. This means that removing the entity from the child collection removes it without requiring access to the context. See this question Is it possible to remove child from collection and resolve issues on SaveChanges?
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does TLS 1.3 deprecate custom DHE groups?
According to the second draft of the TLS 1.3 specification, custom DH groups have been deprecated. As we all know, hardcoded DH groups are vulnerable to a precomputation attack that allows retroactive decryption. Since TLS 1.3 doesn't deprecate DH for key exchange entirely, I imagine this means it will fall back to the standard groups (e.g. Oakley groups). With this in mind, why does TLS 1.3 deprecate custom DH groups? Why not do the opposite and deprecate standard groups instead, or even deprecate all DH key exchange to make way for ECC?
A:
With TLS 1.2 the server first needed to tell the client within the ServerKeyExchange message about the parameters of the DHE group it supports. Only then the client could act on these. With TLS 1.3 the client chooses instead from a set of named groups from start. Since the client now chooses the groups instead of the server the key exchange can start immediately (all information are known from start) which cuts a full RTT from the handshake, resulting in better performance.
Of course, in theory one could also still have custom groups this way, only that the client defines these groups this time and not the server. I cannot find any specific information why custom groups where removed but it seemed to happen during some interim meeting in mid 2014 based on this message in the TLS mailing list. I cannot find any information about this on the official meeting in 03/2014 nor on the next one in 07/2014.
But, some information in the paper Indiscreet Logs: Persistent Diffie-Hellman Backdoors
in TLS from 2016 might point into the right direction. This paper discusses deniable backdoors using custom DH groups and in VII. Discussion A. Mitigation Strategies various strategies are discussed to prevent such backdoors, like disabling DHE completely or using only known good (named) DH groups similar to what is done with ECC. If fully removing DHE is not an option then having a fixed set of named DHE parameters looks like the easiest way to handle this problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is "How was entire game X made?" off-topic?
In the past, we1 decided that "How can I make an entire game like X?" was a bad question. There seems to be a new-ish variant of this, "What technology did entire game X use?"
What technology does the iPhone game “Zombie Highway” use?
What game engine does Mega Jump use?
What language was used to make Jetpack Joyride?
Game engine used for iPhone Zombie Cafe?
This seems no more useful to me than the first kind. Fundamentally, it's the same question - how do I make an entire game? / how was an entire game made?
Usually a better question can be formed by extracting the parts someone is actually interested in. This uses the game as a shared reference explaining the goal, rather than the whole game being the question per se.
How does Half Life's covering work?
How do they do the 3d effect in Animal Crossing?
How to create the “drunk camera” effect in GTA 4?
How do other people feel about either categorically closing (or drastically editing into the second form) such questions?
1 A very tiny subset of "we" that didn't actually include me.
A:
My take on this is: Usually nobody except the creators of the game know the exact technology that was used. So unless the creators of the game happen to be part of this community, all answers are going to be speculative.
Also: How does it help to know the technology that was used? Does it really matter if a game was written in C++ or Java? Does it matter which 3d modelling tool was used to create the assets?
If you know that game X was written in C++, does that help you in any way as a game-developer? I think not.
I think questions in the form of: "How can I achieve a similar effect as in Game X" are way better (example).
A:
Part of the reason "how to make game X" is a bad question is because it's overly broad.
https://gamedev.stackexchange.com/faq#dontask
Your questions should be reasonably scoped. If you can imagine an entire book that answers your question, you’re asking too much.
Now these questions aren't terribly interesting, but they're at least reasonably scoped. Granted, they aren't exactly solving a particular problem and the asker should drill down (like you're getting at), but I don't agree that they're the same classification of question.
A:
The big difference I see between the first group of questions and the second group is that the first group of questions does not seek to solve a problem while the second group does (notice all the first group are "what" questions while all the second group are "how" questions). As Jeff pointed out, they are essentially trivia questions.
I think an appropriate general response to such questions goes something like, "What does that game do that you want to do? Inquire about that instead." If this line of thought isn't helpful, there's probably no substance behind the question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Toggle class when checkbox is checked with JQuery
I have a switcher made with bootstrap, i want that when the checkbox (switch) is checked, the class of the panel change, from grey to green. I did this before but i changed my switcher and it doesn't work anymore.
The main markup of the switcher is this:
<label class="switch-light well" onclick="">
<input type="checkbox">
<span>
Wireless
<span>Off</span>
<span>On</span>
</span>
<a class="btn btn-primary"></a>
</label>
And the toggleclass of JQuery is this:
$(document).ready(function () {
$('.switch-light').bootstrapSwitch();
$('.switch-light').on('input:checked', function () {
$("#tasksList > div > div.panel").toggleClass("panel-off2 panel-off", this.checked).toggleClass("panel-success", !this.checked);
}).change()
});
This is my jsfiddle: http://jsfiddle.net/CYLcY/
A:
Try this code:
$(document).ready(function () {
$('.switch-light').bootstrapSwitch();
$('.panel-body input').on('change', function() {
$(this).parents('.panel-body').prev().parent('.panel').toggleClass("panel-off2", !this.checked).toggleClass("panel-success", this.checked);
})
});
Also you can check it here: http://jsfiddle.net/CYLcY/27/.
| {
"pile_set_name": "StackExchange"
} |
Q:
Do Owlbears hibernate?
Do Owlbears hibernate like bears or stay active all winter like owls? Even the full page description of Owlbears in the AD&D 2nd Edition Monstrous Manual is silent on this topic. I don't have back issues of Dragon Magazine available so I'm unsure if hibernation was ever discussed. The campaign I run is set in the Dalelands in the 1350s DR, a temperate climate for wild Owlbears, with plentiful caves, and ruins.
A:
Yes, they hibernate
There are two sources for this, one is the 2nd Edition sourcebook Monstrous Manual, which has this on the ecology of the owlbear:
Ecology: Owlbears have a lifespan of 20 years. They are warm-blooded mammals, but lay eggs. They prey on anything, from rabbits to bears, to trolls, to snakes and reptiles. Owlbears prefer temperate climates, but some thrive in subarctic environments. As a hybrid of two animals, one diurnal and the other nocturnal, they have an unusual active time, waking at noon, hunting animals active during the day, then hunting nocturnal creatures before going to sleep at midnight. Owlbears are active in the summer months and hibernate during the cold season. There are rumors of white arctic owlbears, a cross between arctic owls and polar bears, but no specimens have ever been captured.
This is also somewhat corroborated by a (non official) tweet from Chris Perkins:
Whatever works for your world. Personally, I dig that they hunt at night like owls and hibernate like bears.
So, essentially the last part of what he said. You can go with official past lore and have them hibernate, or not hibernate, or any variant in between. If you do decide they hibernate, there are past publications to back up that stance.
A:
Owlbears do hibernate
According to the AD&D 2nd edition Monstrous Compendium Volume One:
Owlbears are active in the summer months and hibernate during the cold season.
| {
"pile_set_name": "StackExchange"
} |
Q:
React Native - Click item of Flatlist (after searched the list)
I have Flatlist and TextInput as a search bar on ListHeaderComponent.
When i filled the TextInput and clicked the item of flatlist (using TouchableOpacity), there is only a keyboard dismiss action, it needs to click the second time to be able to select items from the flatlist
any solution?
A:
Add the keyboardShouldPersistTaps prop to FlatList.
<FlatList
keyboardShouldPersistTaps={'handled'}
data={...}
renderItem={...}
... />
A similar suggested was made in this Github issue. But, you're not using a ScrollView. Even though FlatList is not documented to have the keyboardShouldPersistTaps prop, it does have it, because FlatList is a 'convenience wrapper around <VirtualizedList>, and thus inherits its props (as well as those of <ScrollView>)'. source
Alternative: dismiss the keyboard in your TextInput search handler, this is how the Gmail app does search. Once your user is done typing and they press submit, Keyboard.dismiss(). This won't work if the user is not required to 'submit' though, like how most browser apps work.
| {
"pile_set_name": "StackExchange"
} |
Q:
postgresql execute dynamic sql command
I'm slowly learning more about PostgreSQL, as we are attempting to move to it from MSSQL Server.
In MSSQL I have the following code:
DECLARE ServiceabilityParameters
CURSOR FORWARD_ONLY READ_ONLY STATIC LOCAL FOR
SELECT WorkbookParameterType.ID,
WorkbookParameterType.Name,
WorkbookParameter.DefaultValue,
WorkbookParameter.CommandText
FROM WorkbookParameter
JOIN WorkbookParameterType ON WorkbookParameterType.ID = WorkbookParameter.WorkbookParameterTypeID
JOIN WorkbookParameterDirectionType ON WorkbookParameterDirectionType.ID = WorkbookParameter.WorkbookParameterDirectionTypeID
AND WorkbookParameterDirectionType.Writable = 1
WHERE WorkbookParameter.WorkbookID = @WorkbookID
OPEN ServiceabilityParameters
FETCH NEXT FROM ServiceabilityParameters INTO @WorkbookParameterTypeID, @WorkbookParameterTypeName, @WorkbookDefaultValue, @WorkbookCommandText
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @ActualValue NVARCHAR(256) = NULL
IF @WorkbookCommandText IS NOT NULL
BEGIN
EXEC sp_executesql @statement = @WorkbookCommandText,
@params = N'@ApplicationContainerID INT, @Value NVARCHAR(256) OUTPUT',
@ApplicationContainerID = @ApplicationContainerID,
@Value = @ActualValue OUTPUT
END
IF @ActualValue IS NULL AND @WorkbookDefaultValue IS NOT NULL
BEGIN
SET @ActualValue = @WorkbookDefaultValue
END
INSERT @InputParameters (
ID, Name, Value
) VALUES (
@WorkbookParameterTypeID, @WorkbookParameterTypeName, @ActualValue
)
FETCH NEXT FROM ServiceabilityParameters INTO @WorkbookParameterTypeID, @WorkbookParameterTypeName, @WorkbookDefaultValue, @WorkbookCommandText
END
CLOSE ServiceabilityParameters
DEALLOCATE ServiceabilityParameters
I'm trying to work out how to do the sp_executesql part in a PostgreSQL function. I believe that I can do the rest, but most of the examples that I have found show a simple select with maybe a few variables, whereas I need to execute another function, with parameters, where the function name is text in a table.
Many Thanks.
A:
In case you want to execute a function with parameters
EXECUTE 'SELECT Value FROM ' || v_workbookCommandText || '(ApplicationContainerID :=$1)'
INTO v_actualValue
USING v_applicationContainerID;
In case you need select records a function, you can using INOUT refcursor variable
EXECUTE 'SELECT Value FROM ' || v_workbookCommandText || '(ApplicationContainerID :=$1, refcur:= $2)'
INTO v_actualValue
USING v_applicationContainerID, my_cursor;
| {
"pile_set_name": "StackExchange"
} |
Q:
Java Spring - ManyToMany Call Error - Object references an unsaved transient instance
I have a problem with a repository call to an object's attribute, which is part of a Many-To-Many relationship.
I am trying to get all the lecturers assigned to a specific course (getting all the courses for a specific lecturer works very well). But when I am calling the method from the repository below I get the
error:
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: app.model.Course
The CascadeType is set for both parts of the relationship.
I have the following configuration:
Lecturer
@Entity
@Table(name = "LECTURERS")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Lecturer extends AbstractUser {
@ManyToMany(fetch = FetchType.EAGER, targetEntity = Course.class, cascade = CascadeType.ALL)
@Fetch(FetchMode.SELECT)
@JoinTable(name = "COURSE_OWNERSHIPS",
joinColumns = {@JoinColumn(name = "lecturer_id")},
inverseJoinColumns = {@JoinColumn(name = "course_id")})
@JsonSerialize(using = CustomCourseListSerializer.class)
private List<Course> courses = new ArrayList<>();
...
}
Course
@Entity
@Table(name = "COURSES")
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Course implements Item, Serializable {
...
@ManyToMany(mappedBy = "courses", fetch = FetchType.EAGER, targetEntity = Lecturer.class, cascade = CascadeType.ALL)
@Fetch(value = FetchMode.SUBSELECT)
@JsonSerialize(using = CustomLecturerListSerializer.class)
private List<Lecturer> lecturers;
...
}
Lecturer Repository
public interface LecturerRepository extends PagingAndSortingRepository<Lecturer, Long> {
...
Page<Lecturer> findAllByCourses(Course course, Pageable pageable);
}
Edited
Course Service Method
@Override
public Page<Lecturer> getLecturers(Course course, int page) {
return lecturers.findAllByCourses(course, new PageRequest(page, 10));
}
Edit 2
Full course service method
@Override
public Page<LecturerDto> getLecturers(CourseDto course, int page) {
Type listType = new TypeToken<Page<LecturerDto>>() {}.getType();
return modelMapper.map(lecturers.findAllByCourses(modelMapper.map(course, Course.class), new PageRequest(page, 10)), listType);
}
I've tried a few things but I can't make it work. Do you have any idea why I encounter this? I would like to do this because I want the lecturers of a course paginated.
Thank you.
A:
Try changing findAllByCourses to findAllByCoursesId with the course id as a parameter.
findAllByCourses would be perfectly fine if called from within a transaction, and with the course argument being a managed entity. In your code, however, it is called with an entity that is not managed by JPA (as it is assembled by modelMapper.map(course, Course.class) and never merged into the persistence context). Apparently, JPA doesn't like that.
The solution is simply not to use finder methods with detached entities as query parameters.
| {
"pile_set_name": "StackExchange"
} |
Q:
openlayers 5.2 Cannot read property 'boundingExtent' of undefined
Upgrading from ol 4.6.5, trying to figure out the correct syntax for bounding extent. I'm using angular 5 and getting the error Cannot read property 'boundingExtent' of undefined. The code was used in 4.6.5 (with proper namespacing) and worded
I have imported extent
import extent from 'ol/extent';
a code snippet is as follows:
const destLoc = [res.minX, res.minY];
const currentLoc = [res.maxX, res.maxY];
const ext = extent.boundingExtent([currentLoc, destLoc]);
this.map.getView().fit(ext, this.map.getSize());
If I debug the code, extent is not known. I do see something called extent_1, which does have the boundingExtent function
A:
//Solution to my question.
import { boundingExtent } from 'ol/extent';
const destLoc = [-119.36781263222342, 36.56368212151636];
const currentLoc = [-119.3587861884934, 36.57445863282557];
const ext = boundingExtent([currentLoc, destLoc]);
//const ext = ol.extent.boundingExtent([currentLoc, destLoc]); openlayers 4.6.5
console.log('Extent', ext); map.getView().fit(ext, map.getSize());
| {
"pile_set_name": "StackExchange"
} |
Q:
Saving memory, huge array alternative c programming
I'm using an two arrays (unsigned int) with dimensions: 20000x20000.
I have a lot of empty spacing inside the arrays, many zeros or nulls.
There is something I can do to save memory?, because I'm running out of it.
I tried reading from a list in a file, but it's extremely slow.
I have heard that in other languages they have vectors.
A:
You are looking for a sparse matrix, which basically works by storing entries as a list of (index1, index2, value), and only has entries for nonzero elements.
| {
"pile_set_name": "StackExchange"
} |
Q:
Having a good idea for a challenge but lacking the skill to manage it, what do I do?
I feel like I have a cool idea for a king-of-the-hill challenge but I seriously lack the skill to host such a challenge, what should I do?
I could of course post it to the sandbox as suggested here, but what should I expect then? For someone to get interested in the challenge and take over by actually asking the question in the end or should I find someone to help me out with the technical side but still post the question myself?
The latter seems a bit rude and if I'm going for the former, I feel like I should take it somewhere other than the sandbox.
So, where should I go with my idea and what should I expect/hope for?
A:
There are a few things to note. First, this is your challenge idea. If somebody were to post this challenge on the main site without obvious consent from you, I would downvote, closevote, and flag it. Plenty of people are not sure how to run a challenge; this is okay. The sandbox is there to help you work it out.
However, it sounds like you have this idea for your challenge, but you don't have the programming skill to be able to write a controlling program for it.
I do not think that you should let somebody else post your challenge for you. It is your challenge. Instead, I encourage that you request help in composing the program. Yes this is a lot to ask for. But I'm sure that there are several users on this site who would help, including me.
(Note that you should definitely acknowledge anyone who helps to a greater extent than usual)
What I suggest is that you do what you can with the control program. Find some way to get people to help contribute to it. I think github may be able to do this.
A:
Post it to the sandbox, put into words everything you can put into words and ask for help, the chat is also a great place to ask for quicker feedback, people there are generally very helpful.
If no one immediately takes the challenge off your hands (which is to be expected), you should start coding by it yourself. Any work you do, others don't have to and it's a great way to learn. If you never do anything yourself (or at least try), you'll never get better.
In the end, with a little (or a lot of) help form the friendly PPCG people, you'll have made a fun challenge you can be proud of. Even if it does turn out a bit different from what you originally envisioned.
| {
"pile_set_name": "StackExchange"
} |
Q:
I think a book I didn't write would make a great movie - What can I do?
I'm a novel writer (unpublished, but soon to write my first real novel). I've skimmed the surface of screenwriting, just enough to know that I would far rather write novels.
I recently came across a picture book I had read as a kid. I flipped through it again, and realized that it actually has a well-structured plot, with all the points a good novel needs. It would need to be fleshed out a bit, as a lot of character development is missing (because it's a picture book for young kids), but I can easily see it as a movie. For some reason I can't get this idea out of my head.
Is there anything I can do to make this dream a reality? I didn't write the book, and I don't know the first thing about movie production. I'd like to write a screenplay for it, but I'd need someone who actually knows what they are doing with all the timings and everything, as I do not. Who do I talk to if I want this book turned into a movie? Obviously the author/publisher has to get involved at some point, but I'm not sure if I would contact them first, or try to find a producer interested in creating the movie first.
Or am I just asking for trouble if I try to get involved in something I - to be perfectly honest - have no say whatsoever in?
A:
Put some effort into seeing if anyone holds the rights to it first. The chances are that if it's a good book, someone will own the rights to make it into a movie. Then hire a lawyer. A good one.
Many books have screenplays kicking around Hollywood, being held up for many different reasons.
If you think it's good enough to be a film, the chances are that a hundred other people do as well, and they're ahead of you in the queue.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get next row in SQL server 2008 unsorted table
I have the following table:
Shift | Eqmt | StartTime | Category | Event
1201 A201 0 2 1
1204 A201 235 3 0
1202 A202 5413 5 1
1205 A203 213 6 1
1206 A204 4313 1 0
I want to add all the next row GIVEN ONE, but there is one consideration, the table first must be sorted by Eqmt,Shift and StartTime (in that order, all desc)
Final result must look like this:
Shift | Eqmt | StartTime | Category | Event | ShiftF | EqmtF | StartTimeF | CategoryF | EventF
1201 A201 0 2 1 1201 A201 235 3 0
1201 A201 235 3 0 1202 A201 0 2 1
1202 A201 0 2 1 1201 A202 213 6 1
1201 A202 213 6 1 1202 A202 4313 1 0
1202 A202 4313 1 0 1203 A202 0 2 1
In MS SQL 2012 we have new window functions like FIRST_VALUE and LAST_VALUE, unfortunately in sql 2008 these functions are missing.
A:
Seems like a simple self join to me:
WITH cte AS
(
SELECT Shift, Eqmt, StartTime, Category, Event,
ROW_NUMBER() OVER(ORDER BY Eqmt DESC, Shift DESC, StartTime DESC) As Rn
FROM TableName
)
SELECT t0.Shift, t0.Eqmt, t0.StartTime, t0.Category, t0.Event,
t1.Shift, t1.Eqmt, t1.StartTime, t1.Category, t1.Event
FROM cte t0
JOIN cte t1
ON t0.Rn + 1 = t1.Rn
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does repeating one word over and over again sound weird to us after some time?
This effect seems to be observed with almost any word. I would say this phenomenon 'works' for longer and complex words better.
When we repeat a word over and over again, it starts to sound very weird and become only a bunch of repeating sounds. You don't even need to repeat it quickly.
Why does a word repeated many times lose its meaning and the brain can't recognize it properly any more?
A:
This is called semantic saturation, or semantic satiation; studies of event-related potentials (brain waves) suggest that it is negatively correlated with N400 amplitude (the subjective experience of satiation increases as the N400 amplitude decreases) without any change to upstream sensory components. As N400 amplitude indexes initial lexical integration--that is, understanding the word at hand in relation to the words that preceded it--this sugggests that semantic satiation is in fact due to some kind of habituation in the semantic processes, and not in upstream sensory processing.
Citations:
Wikipedia on Semantic saturation
Kounios, J., Kotz, S. A., & Holcomb, P. J. (2000). On the locus of the semantic satiation effect: Evidence from event-related brain potentials. Memory & cognition, 28(8), 1366-1377.
A:
The accepted answer by @krysta may not be the full story: it depends on the way words are repeated.
I understand from @tsykora's question that words are repeated without a separation (syllables are produced at a fixed pace). Kounios et al. used spoken words (mean length of 544 milliseconds) that were repeated several times at a fixed interval of 800 milliseconds. This means that blanks (no sound) separated each presentation of a word.
The blank period between words is of importance since repeated words in a blank context may not "sound very weird" (words are clearly, physically, separable) but only loose their meaning. In a no-blank context (continuous speech), both meaning and percept change. An auditory example can be found in the "ILLUSORY CHANGES OF REPEATED WORDS: THE VERBAL TRANSFORMATION EFFECT" section (http://www4.uwm.edu/APL/demonstrations.html). For instance, while listening to repetitions of the word "rest", listeners are likely to switch between perceiving it as a repetition of "rest" and "tress" or "stress" (Warren & Gregory, 1958).
The verbal transformation effect originates in a multistable representation of a speech form. Pitt and Shoaf (2002) argues that one possible cause is the perceptual regrouping of the acoustic elements that make up a word. It involves some top-down processes in the perceptual organization of speech. A visual analogue of such illusion is found in the Necker cube where the percept changes according to where the eyes land (http://en.wikipedia.org/wiki/Necker_cube).
Such acoustic phenomenon makes me think of a statistical learning in language acquisition in children. It has been shown by Saffran and colleagues that a child can learn to segment a continuous speech into distinct words using transitional probabilities between syllables. In the context of repeated words, a word boundary is first placed between "ted-re" of "re-pea-ted-re-pea-ted" because "ted-re" is not frequent in English while the two other transitions are frequent. Going further in the auditory sequence, repetitive presentation of an utterance promotes alternative groupings of the acoustic elements because the elements occur at regular, predictable points in time (Bregman, 1990). Here, repeating a word at a fixed syllable pace abolishes the frequency of the syllable transitions (the frequencies are momentarily all equal) so that "pi-a-no-pi-a-no" is sometimes heard as "piano" and sometimes "anopi".
Ref.
Bregman, 1990. Auditory scene analysis: The perceptual organization of sound.
Kounios et al., 2000. Memory & Cognition ; http://www.psychonomic.org/pubmed/mc/mc-28-1366.pdf
Pitt and Shoaf, 2002. JEP:HPP ; http://lpl.psy.ohio-state.edu/documents/PittShoafVTE-17_000.pdf
Warren & Gregory, 1958. An auditory analogue of the visual reversible figure, American Journal of Psychology.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to fetch unchecked checkbox value into a cursor in Oracle Apex
Here is my PL/SQL code to fetch checked checkbox value in a button's dynamic action.
DECLARE
IHC_ID_Y VARCHAR2(9);
IHC_ID_N VARCHAR2(9);
CURSOR Y IS
SELECT regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level)
FROM DUAL
CONNECT BY regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level) IS NOT NULL;
CURSOR N IS
SELECT regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level)
FROM DUAL
CONNECT BY regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level) IS NULL;
BEGIN
OPEN Y;
OPEN N;
LOOP
FETCH Y INTO IHC_ID_Y;
EXIT WHEN Y%NOTFOUND;
INSERT INTO INFANT_RESPONSE (INF_ID, IHC_ID, IR_DESCRIPTION) VALUES (:INF_ID, IHC_ID_Y, 'Y');
END LOOP;
CLOSE Y;
LOOP
FETCH N INTO IHC_ID_N;
EXIT WHEN N%NOTFOUND;
INSERT INTO INFANT_RESPONSE (INF_ID, IHC_ID, IR_DESCRIPTION) VALUES (:INF_ID, IHC_ID_N, 'N');
END LOOP;
CLOSE N;
END;
However, I met a problem in this part,
CURSOR N IS
SELECT regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level)
FROM DUAL
CONNECT BY regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level) IS NULL;
LOOP
FETCH N INTO IHC_ID_N;
EXIT WHEN N%NOTFOUND;
INSERT INTO INFANT_RESPONSE (INF_ID, IHC_ID, IR_DESCRIPTION) VALUES (:INF_ID, IHC_ID_N, 'N')
As you can see, when I change the condition from IS NOT NULL to IS NULL, the values being fetched will all be nulls and hence cannot be inserted into the table rows. Is there any way to fetch the unchecked checkbox values?
A:
I'd suggest a different approach:
insert checked health conditions (as you know how to identify them; it is your cursor Y); I used it as well, but within the cursor FOR loop as it is way simpler to use - you don't have to explicitly open it, pay attention about exiting the loop nor when to close the cursor - Oracle does that for you.
in order to insert unchecked health conditions, do that for all conditions that exist in a table you use to create those checkboxes that aren't inserted as "checked" in the first step
Something like this:
begin
-- Checked conditions (using your cursor, but as a cursor FOR loop)
for cur_y in
(SELECT regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level) ihc_id_y
FROM DUAL
CONNECT BY regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level) IS NOT NULL
)
loop
insert into infant_response (inf_id, ihc_id, ir_description)
values (:inf_id, cur_y.ihc_id_y, 'Y');
end loop;
-- To insert unchecked conditions, insert values that exist in the table
-- that contains ALL health conditions (let's call it LIST_OF_HEALTH_CONDITIONS)
-- that aren't inserted as "checked" in the above cursor FOR loop
insert into infant_response (inf_id, ihc_id, ir_description)
select :inf_id,
h.ihc_id,
'N'
from list_of_health_conditions h
where h.ihc_id not in (select r.ihc_id
from infant_response r
where r.inf_id = :inf_id
and r.ir_description = 'Y'
);
end;
Can't test it as I don't have your tables nor data, but - unless I made a typo, that should be OK.
| {
"pile_set_name": "StackExchange"
} |
Q:
Имя класса в переменной
namespace My\Namespace;
use ExtNamespace\FloatToInt;
class test
{
function t ()
{
$class_a = 'FloatToInt';
$class_b = 'ExtNamespace\FloatToInt';
// $d = new FloatToInt() - работает.
// $d = new $class_a() - не работает: Fatal error: Class 'FloatToInt' not found...
// $d = new $class_b() - работает.
}
}
Подскажите, как записать имя класса в переменную, не указывая полного пути к классу и почему не работает создание объекта при помощи new $class_a()? Ведь на первый взгляд, код во второй и третей строке идентичен:
1 $class_a = 'FloatToInt';
2 $d = new FloatToInt();
3 $d = new $class_a();
A:
Ответ на свой вопрос нашел, как не удивительно, в документации:
Если с директивой new используется строка (string), содержащая имя класса, то будет создан новый экземпляр этого класса. Если имя находится в пространстве имен, то оно должно быть задано полностью.
Весьма странное поведение, как по мне...
| {
"pile_set_name": "StackExchange"
} |
Q:
conditional javascript execution based on browser window size?
I have a simple jQuery function--detailed below-- that I'm using to manipulate the position of the document header, and I'm wondering if I can add a parameter such that the function is only executed if the browser window is of a certain size? In this case, I'd like the "stickyHeaderTop" function to execute only if the browser window width exceeds 1024px; is this possible?
<script type="text/javascript">
$(function(){
var stickyHeaderTop = $('header').offset().top;
$(window).scroll(function(){
if( $(window).scrollTop() > stickyHeaderTop ) {
$('header').css({position: 'fixed', top: '0px'});
} else {
$('header').css({position: 'relative', top: '30px'});
}
});
});
</script>
A:
You can use the screen-Object's height, width, availHeight and availWidth attributes.
In case you want to execute some code on screens smaller than 800px for example just do:
if (screen.width < 800){
// do stuff
}
Be aware that this is an area that has some cross-browser pitfalls (and problems when having sth like the stumbleupon toolbar), so an alternative would be using jQuery (that you are already using) to detect your client's window size:
if ($(window).width() < 800){
// do stuff
}
Further reading at MDN regarding pure JS and jquery.com for the jQuery part
| {
"pile_set_name": "StackExchange"
} |
Q:
What is a good alternative to `ContractTranslator.encode_abi`
Since the ethereum Python library has been deprecated in May 2019, the ContractTranslator.encode_abi function is probably not the best way to turn Python argument lists into calldata strings. In particular, it doesn't support functions with the same name but different argument lists.
What is a better way to do this? I've been digging into web3.py _utils but they don't have a single reusable function for this. Any alternatives to use in Python?
I'm looking for a function with an equivalent signature to this:
def encode_abi(abi, function_name: str, args: List[Any]) -> bytes:
A:
With Brownie
Brownie allows you to generate calldata using the ContractTx.encode_input method:
>>> token
<Token Contract object '0x79447c97b6543F6eFBC91613C655977806CB18b0'>
>>> token.transfer.encode_input(accounts[0], 1000)
0xa9059cbb0000000000000000000000000d36bdba474b5b442310a5bfb989903020249bba00000000000000000000000000000000000000000000000000000000000003e8
It handles function overloading with the OverloadedMethod class:
>>> erc223.transfer
<OverloadedMethod object 'ERC223Token.transfer'>
>>> erc223.transfer['address,uint']
<ContractTx object 'transfer(address,uint256)'>
>>> erc223.transfer['address', 'uint256', 'uint256']
<ContractTx object 'transfer(address,uint256,uint256)'>
With eth-abi
If you prefer not to use a framework, eth-abi provides several encoding methods:
>>> import eth_abi
>>> eth_abi.encode_abi(['address', 'uint256'], (web3.eth.accounts[0], 1000).hex()
0xa9059cbb0000000000000000000000000d36bdba474b5b442310a5bfb989903020249bba00000000000000000000000000000000000000000000000000000000000003e8
Disclosure: I am the lead developer for Brownie.
A:
Web3 provides a Contract.encodeABI class method: https://web3py.readthedocs.io/en/stable/contracts.html#web3.contract.Contract.encodeABI.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery Multiple conditionals with isNumeric
I'm trying to figure out what the best practice is with a couple of things.
Whether having if statements inside of if statements is a bad thing.
If there is a better way to condense my code so I'm not chaining a bunch of logical operators chained together.
Also I can't figure out why my isNumeric is not working, I've got a really simple
form with a couple of input boxes and I'm looping around them in my
jquery. What happens is I can input a string of letters that is > 5 and it won't
hit the isNumeric conditional. Ideally a user has to enter numbers for this.
Any ideas?
$("form :input").each(function(){
if(this.id = "zipCode" && $(this).val().length < 5 && $(this).is(":visible")){
if($.isNumeric($(this).val())){
//do something
}
}
});
A:
You're passing a wrong parameter to the isNumeric function. This line
if($.isNumeric($(this.val())){
should be
if($.isNumeric($(this).val())){
As for the long list of conditionals, you can refactor them into a separate function with a name that reflects its purpose. In this case for example, you could create a function like this:
function isValidZipcode(field) {
return field.id = "zipCode" &&
$(field).val().length < 5 &&
$(field).is(":visible");
}
Then it looks cleaner like this:
if(isValidZipcode(this)){
if($.isNumeric($(this).val())){
//do something
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
php searchform with multistring?
Don't know if the title is right but my problem is that i got this adress
index?system&search&result=query
How should i make that work in a form? to go to that address and show output?
if i enter the url it's fine I get querys and output. But when i try with form I only get ?result=query
A:
Kinda solved it by using session if anyone interested
<?php
if(!empty($_POST)){
$_SESSION['search'] = strip_tags($_POST['search']);
echo "
<script type='text/javascript'>
self.location='index.php?system=search&result=".$_SESSION['search']."'
</script>";
}
?>
<form method='post'> <section class='colh col-4'>
<input type='text' name="search">
<input type='submit' name="psubmit" value="sök">
</form>
| {
"pile_set_name": "StackExchange"
} |
Q:
fastboot usage example explained?
Can some one please explain in more detail how the example posted in the "Fastboot" readme file would work, as to where in an existing Ember application this would be integrated? Thanks.
This is a copy of the code I don't understand:
// Usage
const FastBoot = require('fastboot');
let app = new FastBoot({
distPath: 'path/to/dist'
});
app.visit('/photos')
.then(result => result.html())
.then(html => res.send(html));
A:
Here's a link that should help: https://www.ember-fastboot.com/quickstart
The main idea, from what I read is. Using Fastboot give you a choice of 'running your code' on your local server(browser) or server(web). Using Fastboot you don't have to alter your environment for the code to work. Your code remain the same(just write code), your environment that your code run in is what changes. Hope that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the ways to connect to an ec2 instance in a private subnet?
I have a VPC with private and public subnets and I want to ssh into one of the machines which is in the private subnets.
I have heard of the bastion method but want to try others too, please help me with any methods you know,
I also have the NAT Gateway.
A:
Unless you're using a VPN (https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpn-connections.html) or Direct Connect (https://aws.amazon.com/directconnect/) setup to an existing network, a bastion host on a public IP is pretty much your only option.
You can also connect from a host in another VPC if you've setup VPC Peering (https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-peering.html).
| {
"pile_set_name": "StackExchange"
} |
Q:
Access the json response from xhr in jquery
I have a question about how the XMLHttpRequest object works. In https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest, under properties I am looking at the "response" property. The description says I should get a JavaScript object back if my content type is json. However, in my code the xhr.response property is undefined.
Specifically, I have a .ajaxSuccess() callback that is setup on a DOM element, it receives the parameters (event, xhr, settings). xhr.responseText is the plaintext version of my json, but xhr.response is undefined. Is there any way I can get the object from xhr without calling $.parseJson(xhr.responseText)?
A:
I think you are confusing the XMLHttpRequest object with jQuery's jqXHR object used by $.ajaxSuccess(), which is supposed to be a superset of the former.
Instead, you could use $.ajax()'s done handler, which will parse the JSON for you if the data type is json. For example:
$.ajax({
url: url,
dataType: 'json',
}).done(function (response) {
// response is a JSON object, previously parsed by jQuery using $.parseJSON
});
Also note that even though the documentation of $.ajaxSuccess() says that you get a vanilla XMLHttpRequest object, that is no longer true as of jQuery 1.4.1. Instead, you get a jqXHR object.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is this objective-c syntax
What is the caret (^) for here and what is it doing ?
- (NSUInteger)hash {
return [self.name hash] ^ [self.birthday hash];
}
A:
It's a bitwise exclusive OR. It's not Objective-C, it's just plain old C. It compares the bits of both items you give it and returns a value with 1s for only the bits that are 1 in one of the items but not the other.
If you have two numbers:
5 (00000101)
11 (00001011)
The bitwise exclusive OR will yield the result:
14 (00001110)
| {
"pile_set_name": "StackExchange"
} |
Q:
Find a non-principal ideal in $ \Bbb Z [2i]$.
Find a non-principal ideal in $ \Bbb Z [2i]$.
I think it might be $(1+2i,1-2i)$, but have problems with proving this.
I know that $|1+2i|=|1-2i|=5$.
Moreover, there are only 6 elements with non-bigger norm than 5 (except these two),
I mean $1,-1,2,-2,2i,-2i$. None of these has norm equal to 5, so if this ring was principal, then $1+2i = a(1-2i)$, where $|a|=1$. Of course this is not possible, so our ideal is not principal.
Is this correct?
A:
Hint. $\mathbb Z[2i]\simeq\mathbb Z[X]/(X^2+4)$. Now recall the usual example of a non-principal ideal in $\mathbb Z[X]$.
$(2,2i)$ is a non-principal ideal in $\mathbb Z[2i]$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why did NBA coach of the year Dwane Casey get fired?
On Friday, May 11th, the Toronto Raptors fired their head coach of seven years, Dwane Casey after getting swept in the second round of the playoffs by the Cleveland Cavaliers. The decision came following the announcement that Casey had unofficially won the Coach of the Year award after having turned the Raptors franchise around; from a team that wasn't making the playoffs year after year to winning a franchise record 59 games this season.
My question is why did the Raptors fire Casey after he helped build the franchise to the successful club it is today?
Edit: I know there is a question similar to this one here but I would like to know why specifically Casey got fired, not other coaches of the year.
A:
I don't think that it's entirely accurate to say that Casey built the club to the current success that it is, because quite frankly, I don't understand how he's been the coach for as long as he has. Historically, his player rotations have been somewhat strange, as has his justification. And as @jcmcclorey mentioned, he didn't advance in the playoffs. The simple reason is that you have to win in the playoffs, and Casey has a 21-30 record (19-22 as the higher seed) in the playoffs with Toronto. I'll give a possible explanation as to why that is the case.
Specifically, I would refer to the 2015 series against Washington (after which, I think he should have been let go), and then talk about this most recent playoff run. In this article, you can see that Casey was making some very strange comments in light of how he had managed that series and also season. In particular, he calls James Johnson the most talented player on their roster, while only playing him 12 minutes over the entire series, where they struggled defensively (and also offensively). When we look to this past playoffs, we again see some personel decisions that are bizarre, generally as it pertains to Valanciunas. Some of the reason for that is his general tendency to plays the game on the opponent's terms, as opposed to forcing them to play on Toronto's terms. With Valanciunas, it typically leads to benching him, where he provides Toronto with an offensive advantage. Jumping around a bit, we also see this trend last year with respect to Casey's willingness to play Valanciunas vs Ibaka or PJ Tucker. One issue with the team over his tenure (that, to his credit did get fixed this year) was the lack of ball movement in the offense, and this can be seen in the falling assist rate over the course of his time in Toronto prior to this year. This is notable, because assist rates are fairly indicative of playoff success; whereas, Toronto has been very dependent upon free throw shooting over the last few years, which is actually not indicative of playoff success (see here). Now, as I had mentioned, they did fix some of these problems throughout the regular season (also, you'd note that in the last article, they were 30th in DREB% last year, but only 12th this year), but seemed to revert to more of their isolation-focused basketball from years past.
Edit: One other issue with Casey has been his tendency to not hold the star players accountable. This article comes from 2 years ago where they went to the ECF in 2016. The article talks about DeRozan's struggles in the first 2 games of their opening round series against Indiana, where Indiana focused on taking DeRozan out of the offence and forcing the other Raptors to beat them. What's notable is the contrasting suggestions from Casey and Lowry on what DeRozan should do in Game 3. Casey said he should be a facilitator, while Lowry said he should keep shooting. The author also notes the advantage they had with Valanciunas against Ian Manhinmi. Clearly, DeRozan listened to the "the little devil yammering in his other ear", going 7-19 in 36+ minutes in Game 3. Just as importantly, this shows a severe disconnect between the coach and the star players. I do also remember there being some whispers about a locker room schism in the 2014-15 season (the one that ended with the sweep to Washington) where you had a DeRozan-Lowry-Lou Williams faction against a Valanciunas-Amir Johnson-James Johnson group, with the latter being very dissatisfied that the former could do whatever they liked without repercussion, but Valanciunas would constantly be benched. Now, I can't find any sources for this, but I do recall seeing some articles about this in 2015.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add "dont show me again" checkbox to an alertbox?
When my android app starts there will be a prompt that asks user whether to upgrade to newer version or not.I used an alertbox to display it.I have two buttons in it, "Upgrade" and "No thanks".Then I added a checkbox to it.And the label for that check box is "Dont ask me again". When user click on that checkbox,that should be remembered and the prompt shouldnt asked again.Can anyone suggest me a solution to achieve this?
A:
The Best option you can go for is of SharedPreference. You can Save the in Internal Database.
PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
int currentVersion = info.versionCode;
// version name here for display in the about box later.
this.sVersionName = info.versionName;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int lastVersion = prefs.getInt("Key", 0);
if (currentVersion > lastVersion) {
prefs.edit().putInt("key",currentVersion).commit();
Intent intent = new Intent(this, StartUp.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
// Your Code goes here if you want to Display it Only Once.
return true;
}
EDIT
SavePreferences("MEMORY1","Your String Here");
private void SavePreferences(String key, String value) {
SharedPreferences settings = getSharedPreferences(pref, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences() {
SharedPreferences settings = getSharedPreferences(Settings.pref, 0);
String sDefault_Card = settings.getString("MEMORY1", "");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Suggestions to reduce memory usage on table partitioning (psql 11)
I have few tables will 20-40million rows, due to which my queries used to take a lot of time for execution. Are there any suggestions to troubleshoot/analyze the queries in details as of where most of the memory is consumed or any more suggestions before going for partitioning?
Also, I have few queries which are used for analysis too, and these queries run over whole range of dates (have to go through whole data).
So I will need an overall solution to keep my basic queries fast and that the analysis queries doesn't fail by going out of memory or crashing the DB.
One table size is nearly 120GB, other tables just have huge number of rows.
I tried to partition the tables with weekly and monthly date basis but then the queries are running out of memory, number of locks increases by a huge factor while having partitions, normal table query took 13 locks and queries on partitioned tables take 250 locks (monthly partition) and 1000 locks (weekly partitions).
I read, there is an overhead that adds up while we have partitions.
Analysis query:
SELECT id
from TABLE1
where id NOT IN (
SELECT DISTINCT id
FROM TABLE2
);
TABLE1 and TABLE2 are partitioned, the first by event_data_timestamp and the second by event_timestamp.
Analysis queries run out of memory and consumes huge number of locks, date based queries are pretty fast though.
QUERY:
EXPLAIN (ANALYZE, BUFFERS) SELECT id FROM Table1_monthly WHERE event_timestamp > '2019-01-01' and id NOT IN (SELECT DISTINCT id FROM Table2_monthly where event_data_timestamp > '2019-01-01');
Append (cost=32731.14..653650.98 rows=4656735 width=16) (actual time=2497.747..15405.447 rows=10121827 loops=1)
Buffers: shared hit=3 read=169100
-> Seq Scan on TABLE1_monthly_2019_01_26 (cost=32731.14..77010.63 rows=683809 width=16) (actual time=2497.746..3489.767 rows=1156382 loops=1)
Filter: ((event_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone) AND (NOT (hashed SubPlan 1)))
Rows Removed by Filter: 462851
Buffers: shared read=44559
SubPlan 1
-> HashAggregate (cost=32728.64..32730.64 rows=200 width=16) (actual time=248.084..791.054 rows=1314570 loops=6)
Group Key: TABLE2_monthly_2019_01_26.cid
Buffers: shared read=24568
-> Append (cost=0.00..32277.49 rows=180458 width=16) (actual time=22.969..766.903 rows=1314570 loops=1)
Buffers: shared read=24568
-> Seq Scan on TABLE2_monthly_2019_01_26 (cost=0.00..5587.05 rows=32135 width=16) (actual time=22.965..123.734 rows=211977 loops=1)
Filter: (event_data_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone)
Rows Removed by Filter: 40282
Buffers: shared read=4382
-> Seq Scan on TABLE2_monthly_2019_02_25 (cost=0.00..5573.02 rows=32054 width=16) (actual time=0.700..121.657 rows=241977 loops=1)
Filter: (event_data_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone)
Buffers: shared read=4371
-> Seq Scan on TABLE2_monthly_2019_03_27 (cost=0.00..5997.60 rows=34496 width=16) (actual time=0.884..123.043 rows=253901 loops=1)
Filter: (event_data_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone)
Buffers: shared read=4704
-> Seq Scan on TABLE2_monthly_2019_04_26 (cost=0.00..6581.55 rows=37855 width=16) (actual time=0.690..129.537 rows=282282 loops=1)
Filter: (event_data_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone)
Buffers: shared read=5162
-> Seq Scan on TABLE2_monthly_2019_05_26 (cost=0.00..6585.38 rows=37877 width=16) (actual time=1.248..122.794 rows=281553 loops=1)
Filter: (event_data_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone)
Buffers: shared read=5165
-> Seq Scan on TABLE2_monthly_2019_06_25 (cost=0.00..999.60 rows=5749 width=16) (actual time=0.750..23.020 rows=42880 loops=1)
Filter: (event_data_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone)
Buffers: shared read=784
-> Seq Scan on TABLE2_monthly_2019_07_25 (cost=0.00..12.75 rows=73 width=16) (actual time=0.007..0.007 rows=0 loops=1)
Filter: (event_data_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone)
-> Seq Scan on TABLE2_monthly_2019_08_24 (cost=0.00..12.75 rows=73 width=16) (actual time=0.003..0.004 rows=0 loops=1)
Filter: (event_data_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone)
-> Seq Scan on TABLE2_monthly_2019_09_23 (cost=0.00..12.75 rows=73 width=16) (actual time=0.003..0.004 rows=0 loops=1)
Filter: (event_data_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone)
-> Seq Scan on TABLE2_monthly_2019_10_23 (cost=0.00..12.75 rows=73 width=16) (actual time=0.007..0.007 rows=0 loops=1)
Filter: (event_data_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone)
-> Seq Scan on TABLE1_monthly_2019_02_25 (cost=32731.14..88679.16 rows=1022968 width=16) (actual time=1008.738..2341.807 rows=1803957 loops=1)
Filter: ((event_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone) AND (NOT (hashed SubPlan 1)))
Rows Removed by Filter: 241978
Buffers: shared hit=1 read=25258
-> Seq Scan on TABLE1_monthly_2019_03_27 (cost=32731.14..97503.58 rows=1184315 width=16) (actual time=1000.795..2474.769 rows=2114729 loops=1)
Filter: ((event_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone) AND (NOT (hashed SubPlan 1)))
Rows Removed by Filter: 253901
Buffers: shared hit=1 read=29242
-> Seq Scan on TABLE1_monthly_2019_04_26 (cost=32731.14..105933.54 rows=1338447 width=16) (actual time=892.820..2405.941 rows=2394619 loops=1)
Filter: ((event_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone) AND (NOT (hashed SubPlan 1)))
Rows Removed by Filter: 282282
Buffers: shared hit=1 read=33048
-> Seq Scan on TABLE1_monthly_2019_05_26 (cost=32731.14..87789.65 rows=249772 width=16) (actual time=918.397..2614.059 rows=2340789 loops=1)
Filter: ((event_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone) AND (NOT (hashed SubPlan 1)))
Rows Removed by Filter: 281553
Buffers: shared read=32579
-> Seq Scan on TABLE1_monthly_2019_06_25 (cost=32731.14..42458.60 rows=177116 width=16) (actual time=923.367..1141.672 rows=311351 loops=1)
Filter: ((event_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone) AND (NOT (hashed SubPlan 1)))
Rows Removed by Filter: 42880
Buffers: shared read=4414
-> Seq Scan on TABLE1_monthly_2019_07_25 (cost=32731.14..32748.04 rows=77 width=16) (actual time=0.008..0.008 rows=0 loops=1)
Filter: ((event_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone) AND (NOT (hashed SubPlan 1)))
-> Seq Scan on TABLE1_monthly_2019_08_24 (cost=32731.14..32748.04 rows=77 width=16) (actual time=0.003..0.003 rows=0 loops=1)
Filter: ((event_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone) AND (NOT (hashed SubPlan 1)))
-> Seq Scan on TABLE1_monthly_2019_09_23 (cost=32731.14..32748.04 rows=77 width=16) (actual time=0.003..0.003 rows=0 loops=1)
Filter: ((event_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone) AND (NOT (hashed SubPlan 1)))
-> Seq Scan on TABLE1_monthly_2019_10_23 (cost=32731.14..32748.04 rows=77 width=16) (actual time=0.003..0.003 rows=0 loops=1)
Filter: ((event_timestamp > '2019-01-01 00:00:00+00'::timestamp with time zone) AND (NOT (hashed SubPlan 1)))
Planning Time: 244.669 ms
Execution Time: 15959.111 ms
(69 rows)
A:
A query that joins two large partitioned tables to produce 10 million rows is going to consume resources, there is no way around that.
You can trade memory consumption for speed by reducing work_mem: smaller vakues will make your queries slower, but consume less memory.
I'd say that the best thing would be to leave work_mem high but reduce max_connections so that you don't run out of memory so fast. Also, putting more RAM into the machine is one of the cheapest hardware tuning techniques.
You can improve the query slighty:
Remove the DISTINCT, which is useless, consumes CPU resources and throws your estimates off.
ANALYZE table2 so that you get better estimates.
About partitioning: if these queries scan all partitions, the query will be slower with partitioned tables.
Whether partitioning is a good idea for you or not depends on the question if you have other queries that benefit from partitioning:
First and foremost, mass deletion, which is painless by dropping partitions.
Sequential scans where the partitioning key is part of the scan filter.
Contrary to popular belief, partitioning is not something you always benefit from if you have large tables: many queries become slower by partitioning.
The locks are your least worry: just increase max_locks_per_transaction.
| {
"pile_set_name": "StackExchange"
} |
Q:
Evaluate the long multiplication
Evaluate Q1:$[-100\times (-99)] \times [-99 \times (-98)] \times [-98 \times (-97)]..... (97\times 98)\times (98 \times 99) \times (99 \times 100)$
And
Evaluate Q2:$(-100-98) \times (-99-97) \times (-98-96).....(96+98) \times (97+99) \times (98+100)$ (Clue:there is a pattern, but is "disrupted" by the $+(-)$ property.
Then, after evaluating this, solve the fraction with the answers you got previously.
$\frac {Q1 evalution} {Q2 evaluation}$
Is a scientific calculator able to calculate the result?(Assuming the calulator cannot calculate answers bigger than 10000000000)(Yeah, a lousy scientific calculator that fails to understand how to put in a standard number form (like for example $3.1839\times10^{65}$)
A:
Both multiplications have a factor of 0.
The first one obviously and the other one in the factor (-1+1).
So the result is 0 in both cases.
0/0 doesn't exists so the second question hasn't an answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
не проходит git push
Здравствуйте. У меня при добавлении файлов на git следующая ситуация. При git add все нормально как обычно, при git commit тоже, а когда пишу git push origin master появляется такая ошибка:
*To [email protected]:triodjangopiter/junior.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to '[email protected]:triodjangopiter/junior.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.*
Помогите пожалуйста.
Спасибо.
A:
Решил проблему с командой:
git branch --set-upstream-to=origin/master
Всем спасибо.
| {
"pile_set_name": "StackExchange"
} |
Q:
Which aspects of renal physiology are standing in the way of an artificial (mechanical) kidney?
Scientists have been able to create artificial organs with varying degrees of success. The mechanical heart (in its various forms, e.g. ventricular assist) is able to sustain life for some period of time.
Efforts to grow whole organs in the lab will probably ultimately lead to a more pragmatic solution. What aspects of the renal physiology are standing in the way of an implantable mechanical kidney (fashioned more so from tubules and membranes than simply being a shrunken down dialysis machine)?
A:
The problem is that real organs are just damn complex - yes the kidney's prime role is just to be a filter, but in order to do so it must be plugged in to a dozen regulation mechanisms - osmotic balance, ion management, protein management and a plethora of more subtle ones. Moreover it is a part of body, so it must also follow all the standard protocols to live with immune system, obtain necessary resources to its function and maintenance, cooperate with nearby tissues...
Currently we only have rough knowledge about major processes, deciphering them all is a work for many, many years (if it is not futile at all). Finally, our technology will be long not capable of implementing all those protocols; in peaks of perfection we can serially do simple parts in 100nm scale (microprocessors), while this is a scale of a complete molecular device.
| {
"pile_set_name": "StackExchange"
} |
Q:
Answers to a deleted question not deleted?
I just ran across this review item and immediately thought to myself "yes, that should be deleted." But before I recommended deletion, I took a quick look at the question.
What the hell? A red background? The question is deleted? Must be a review audit... But then I still get a popup when I click the Recommend Deletion button... Ok, now I'm confused...
Taking a look at the actual question, none of the answers under it are actually deleted.
Is this something to do with the question having been posted clear back in 2008? I mean, it wasn't deleted until 2011 (but automatically), so I wouldn't suspect that to be the problem. Is something else going on here? Should we clearly be blaming Sam for this?
If this isn't a bug, I'd say that LQP review certainly shouldn't be picking answers from closed and deleted questions. It's not like anyone can actually see those (and it should be deleted anyways).
A:
This is one of those weird side-effects of migration rejection.
See, this question was migrated to Software Engineering way back in the dawn of time. The stub left on Stack Overflow was automatically deleted after a month. Then somewhat later, the question on Software Engineering was closed - but migration rejection didn't exist at the time, so nothing happened.
Until a few minutes ago, when a moderator on Software Engineering.se deleted the question. This finally triggered the migration to be rejected, undeleting and unlocking all of the answers there.
Of course, since the question was deleted it didn't accomplish much, and within about 24 hours, the answers will be re-deleted automatically. But in the meantime, you get weirdness.
| {
"pile_set_name": "StackExchange"
} |
Q:
Norm of an inverse operator: $\|T^{-1}\|=\|T\|^{-1}$?
I am a beginner of funcional analysis. I have a simple question when I study this subject.
Let $L(X)$ denote the Banach algebra of all bounded linear operators on Banach space X, $T\in X$ is invertible, then $||T^{-1}||=||T||^{-1}$? Is this result correct?
A:
In general you have $\|T^{-1}\|\geq \dfrac{1}{\|T\|}$ and cannot say much more. If $x_1$ and $x_2$ are nonzero with $Tx_1=y_1$ and $Tx_2=y_2$, then $\|T\|\geq\max\left\{\dfrac{\|y_1\|}{\|x_1\|},\dfrac{\|y_2\|}{\|x_2\|}\right\}$, while $\|T^{-1}\|\geq\max\left\{\dfrac{\|x_1\|}{\|y_1\|},\dfrac{\|x_2\|}{\|y_2\|}\right\}$. The only way it is possible for these lower bounds to be reciprocals is if $\dfrac{\|y_1\|}{\|x_1\|}=\dfrac{\|y_2\|}{\|x_2\|}$, which will typically not happen. If this happens for all $x_1,x_2$, then $T$ must be a scalar multiple of an isometric isomorphism.
To see this another way, suppose that $\|T^{-1}\|=\dfrac{1}{\|T\|}$, and let $S=\dfrac{1}{\|T\|}T$. Then $\|S\|=1$ and $\|S^{-1}\|=1$. Thus for all $x$, $\|Sx\|\leq \|x\|$ and $\|x\|=\|S^{-1}(Sx)\|\leq \|Sx\|$, which implies that $\|Sx\|=\|x\|$ for all $x$, and $T=\|T\|S$ is a scalar multiple of the isometric isomorphism $S$.
A useful upper bound for $\|T^{-1}\|$ can be given in one particular context. If $\|T-I\|<1$, then $T^{-1}=\sum_{k=0}^\infty(I-T)^k$, which implies that $\|T^{-1}\|\leq \dfrac{1}{1-\|I-T\|}$.
A:
Consider operator given by matrix
$$
M=
\begin{pmatrix}
0 & 2^{-1}\\
2 & 0\\
\end{pmatrix}
$$
then $M^{-1}=M$. Note that $\Vert M\Vert\geq \Vert Me_1\Vert/\Vert e_1\Vert=2$. Hence $\Vert M^{-1}\Vert=\Vert M\Vert\geq 2$ and equality $\Vert M^{-1}\Vert=\Vert M\Vert^{-1}$ doesn't hold in general.
A:
The following formula for $\|T^{-1}\|$ is relevant for the question posted.
Let $(\mathcal E, \|\cdot\|_{\mathcal E})$ and $(\mathcal F, \|\cdot\|_{\mathcal F})$ be Banach spaces and let $\mathcal L(\mathcal E,\mathcal F)$ be the space of all bounded operators from $\mathcal E$ into $\mathcal F$. Let $T \in \mathcal L(\mathcal E,\mathcal F)$. The following two statements are equivalent.
$T$ is an injection and the range of $T$, $\operatorname{ran} T$, is a closed subspace of $\mathcal F$.
$\inf \bigl\{\|Tu\|_{\mathcal F}\, :\, u\in\mathcal E \quad \text{and} \quad \|u\|_{\mathcal E} = 1\bigr\} \gt 0$.
If either of the equivalent statements above is satisfied, then $T^{-1} \in \mathcal L(\operatorname{ran} T,\mathcal E)$ and
\begin{equation} \tag{*}
\inf \bigl\{\|Tu\|_{\mathcal F}\, :\, u\in\mathcal E \quad \text{and} \quad \|u\|_{\mathcal E} = 1\bigr\} = \frac{1}{\|T^{-1}\|},
\end{equation}
where $\|T^{-1}\|$ denotes the norm of $T^{-1}$ in the Banach space $\mathcal L(\operatorname{ran} T,\mathcal E)$.
Here are the proofs. Assume that $T$ is an injection and that $\operatorname{ran} T$ is closed in $\mathcal F$. Then $T: \operatorname{ran} T \to \mathcal E$ is a linear operator with a closed graph defined on a Banach space. By the Closed Graph Theorem the operator $T^{-1}$ is bounded. That is $T^{-1} \in \mathcal L(\operatorname{ran} T,\mathcal E)$.
Notice that $T$ is a bijection between the sets $\mathcal E\setminus\{0\}$ and $(\operatorname{ran} T)\setminus\{0\}$. We use this fact to calculate
\begin{align*}
\|T^{-1}\| & = \sup \bigl\{ \|T^{-1} x \|_{\mathcal E} : x \in \operatorname{ran} T \quad \text{and} \quad \|x\|_{\mathcal F} = 1 \bigr\} \\
& = \sup \left\{ \frac{\|T^{-1} x \|_{\mathcal E}}{\|x\|_{\mathcal F}} : x\in (\operatorname{ran} T) \setminus\{0\} \right\} \\
& = \sup \left\{ \frac{\|T^{-1} T v \|_{\mathcal E}}{\|T v\|_{\mathcal F}} : v\in {\mathcal E} \setminus\{0\} \right\} \\
& = \sup \left\{ \frac{\|v \|_{\mathcal E}}{\|T v\|_{\mathcal F}} : v\in {\mathcal E} \setminus\{0\} \right\} \\
& = \sup \left\{ \frac{1}{\|T u\|_{\mathcal F}} : u\in {\mathcal E} \quad \text{and} \quad \|u \|_{\mathcal E} = 1 \right\}.
\end{align*}
This proves 2. and (*).
Now assume 2. and denote by $m$ the infimum in there. Then for every $v \in \mathcal E$ we have $\|Tv\|_{\mathcal F} \geq m \|v\|_{\mathcal E}$. Therefore $T$ is injective. From the last inequality in a straightforward manner it also follows that $\operatorname{ran} T$ is closed.
Notice that the formula at the bottom of the first answer is a consequence of the triangle inequality and (*).
To see this, let $T \in \mathcal L(\mathcal E, \mathcal E)$ be invertible and $\|I - T\| \lt 1$. Let $x \in \mathcal E$ be such that $\|x\|_{\mathcal E} = 1$. Then by the triangle inequality
$$
\|Tx\|_{\mathcal E} = \|x - (I - T)x\|_{\mathcal E} \geq 1 - \|(I - T)x\|_{\mathcal E} \geq 1 - \|I - T\|.
$$
Thus
$$
\inf \bigl\{\|Tx\|_{\mathcal E}\, :\, x\in\mathcal E \quad \text{and} \quad \|x\|_{\mathcal E} = 1 \bigl\} \geq 1 - \|I - T\|
$$
and therefore by (*)
$$
\frac{1}{\|T^{-1}\|} \geq 1 - \|I - T\|.
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
foliation with many tangencies
Suppose you have smooth foliation on a Euclidean ball $\mathbb{B}^{4} \subset \mathbb{C}^{2}$, whose leaves are holomorphic curves with respect to the standard complex structure. Let $(z_{1},z_{2})$ be coordinates on $\mathbb{C}^{2}$.
Suppose that at every point $p$ in the $z_{1}$-axis, the leaf of the foliation through $p$ meets the $z_{1}$-axis tangentially.
Can we deduce that in fact the $z_{1}$-axis must be a leaf of the foliation? how to show it?
A:
If you take a submersion $g$ defining the foliation around $p \in \{ z_1 =0 \}$ and compose with the inclusion $h\colon \mathbb{D} \rightarrow \{ z_1 =0 \} \subset\mathbb{C}^2$. The tangency implies that $g\circ h$ is constant, hence $g$ is constant on $\{ z_1 =0 \}$. The result follows by connectedness.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python - Reading a spreadsheet
What I need to know is, can I get Python to read a spreadsheet (preferably Microsoft Excel), then parse the information and input it into an equation?
It's for a horse-racing program, where the information for several horses will be in one excel spreadsheet, in different rows or columns. I need to know if I can run a calculation for each of those horses separately and then calculate a score for the given horse.
A:
My suggestion is:
Save the Excel file as a csv comma separated value file, which is a plain text format and much easier to work with.
Use Python's built-in csv module to work with the data in csv format.
You can work with Excel files directly in Python (Excel 2003 format supported via the third party modules xlwt, xlrd) but this is much harder than working with CSV.
A:
OpenPyXL ("A Python library to read/write Excel 2007 xlsx/xlsm files") has a very nice and Pythonic API.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dependency graph. Parallel processing
I need to realize dependecies from the dependency graph using TPL (all processes must start parallel). Here is my code:
TaskFactory factory = Task.Factory;
// 1 and 6
Task task_1 = factory.StartNew(() => A());
Task task_6 = factory.StartNew(() => F());
// 4 and 6
Task task_2 = task_1.ContinueWith((t) => B());
Task task_4 = task_6.ContinueWith((t) => D());
// 5 and 7
Task task_5 = task_2.ContinueWith((t) => E());
Task task_7 = task_4.ContinueWith((t) => G());
// 3
Task task_3 = factory.ContinueWhenAll(new[] { task_1, task_2, task_4, task_5, task_6, task_7 }, (tasks) => C());
Task.WaitAll(task_3);
All my methods look like:
private static void A()
{
Console.WriteLine("1");
}
Is there more elegant solution?
A:
Since most of your graph consists of simple paths, you could simplify your code to something like (assuming the dependency graph is fixed):
Task task125 = factory.StartNew(() => { A(); B(); E(); });
Task task647 = factory.StartNew(() => { F(); D(); G(); });
Task.WaitAll(task125, task647);
C();
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do I have a coax splice behind this blank face plate?
Behind this blank face plate is a coaxial cable. I already have a coaxial cable in the middle of this room that I use for cable.
I'd like to just push this into the wall and patch up the hole but I'm not sure if its used for anything.
A:
It is likely a remnant from either the initial cable-pulling process, or that connected cable is an extension that was used to "move" the coax to that other point in the room that you mentioned. I would see what happens if you disconnect it - does the coax stop working somewhere else in your house? That's the surest way to find out what it is used for.
Since it is a connection, having the access box is handy if you ever need to tighten the connection / move the coax port back to this box. I don't think there is any code requirement on having access in this instance, though, as it's a signal wire (low voltage) - not power. (as always, IANAL)
A:
I get we all want smooth walls, but you really shouldn’t just cover up a splice box.
While that is a less serious problem with data cable, it is absolutely essential it not be done with power cables, especially AC mains!
The reason is that splices do fail (whereas cables in walls generally do not). You need to be able to access each end of the cable for testing and repair.
Further, you are looking at the matter from the perspective of the room as it’s arranged currently. It’s quite likely this is the original location of the coax outlet, and you’re seeing an extension cable to the present location, because someone agreed with your arrangement. It’s even possible you arranged the room that way because that’s where the coax or other utilities were located. You or someone else might want to arrange the room differently. You could swap cover plates with the present outlet, and make this the live outlet instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
Namespaced API with resources specified twice
I'm trying to create a namespaced API in rails and am running into an issue
# Resources
resources :users do
resources :contacts
end
#==========================================>
# API namespacing and routing
#==========================================>
namespace :api do
namespace :v1 do
# =======================>
# Resources -> Users
# Resources -> Contacts
# =======================>
resources :users do
resources :contacts
end
# =======================>
# Resources -> Messages
# Resources -> Transcriptions
# =======================>
resources :messages do
resources :transcriptions
end
end
end
I want to have my html-responding version of the resource outside of the 'api' namespace (i.e. in the regular app/controllers/users_controller.rb area) but my json-responding inside the namespace.
However when I point my url at the "/api/v1/users.json" link it utilizes the controller specified by the OUTSIDE resources app/controllers/users_controller rather than the one I put in app/controllers/api/v1/users_controller.
Am I only allowed one resources reference despite it being namespaced differently?
Why exactly is this happending
A:
Your routing definitions look ok. The first thing I'd check is what routes are generated by your rails router by running:
$ bundle exec rake routes | grep users
You should have your defined users routes mapped to their respective URL structure. If something's amiss then your routes aren't probably defined correctly. Which i doubt in your case.
Another possible issue might be your controller class name in your namespaced users controller. So your users controller under app/controllers/api/v1 should be
class Api::V1::UsersController < ApplicationController
....
end
Look at the Rubygems.org source which has the same kind of structure you're trying to implement.
| {
"pile_set_name": "StackExchange"
} |
Q:
A basic question about opamp buffer offset and input offset voltage
The definition of "input offset voltage" is the differential voltage which is required to apply between the two terminals of the op-amp such that the output of the op-amp will become zero.
What I want to learn is: Imagine we have an opamp buffer and we apply(at its non-inverting input) a very well known constant precise voltage 1.0000V for instance and we measure 1.0015V meaning that there is 1.5mV offset. What is this offset voltage called? And does it have any relation with "input offset voltage"?
simulate this circuit – Schematic created using CircuitLab
A:
The offset at the output could be called the 'output offset voltage'.
If the op-amp has non-zero input offset voltage (but is otherwise ideal) then the output offset voltage is equivalent to (and caused by) the input offset voltage for an op-amp configured as a follower, which you show.
However, if the op-amp has other nonidealities such as input bias/offset current, finite open-loop gain, finite CMRR, etc. then the output offset voltage will not be caused entirely by the input offset voltage but by a combination of these effects. However, in a practical case, if an op-amp has millivolts of input offset voltage, then this will probably be the dominant effect.
| {
"pile_set_name": "StackExchange"
} |
Q:
Extracting output from `zlogit$sim()` (Zelig)
I'm still trying to get used to the totally new syntax the developers of Zelig are working towards (in Zelig5, instructions for installing the current development version here). Feels very Pythonic, except, not...
Anyway, I just want to store the results of a sim exercise, but can only figure out how to print the results to the console.
Let's use the example cited in the documentation (well, sort of--updated to reflect the Zelig5 syntax seen, e.g., here):
set.seed(1234)
library(Zelig) #Zelig_5.0-5
ztob<-ztobit$new()
ztob$zelig(durable~age+quant,data=tobin)
ztob$setx(ztob)
ztob$sim()
summary(ztob)
sim x :
-----
ev
mean sd 50% 2.5% 97.5%
1 1.534273 0.6350075 1.451001 0.5103966 3.042459
pv
mean sd 50% 2.5% 97.5%
[1,] 3.002031 4.027547 1.310886 0 13.19713
I don't really know what pv means (not really documented), but I'm pretty sure the expected value I want is 1.53 (under ev,mean).
Can anyone figure out how to extract that value? I can't find anything like summary.Zelig or summary.zelig; I've tried:
summary(ztob)$ev / ztob$ev
print(summary(ztob))
summary(ztob)[1] / summary(ztob)[[1]]
Anything?
A:
In cases like this, str is your friend.
You can get all the values:
x<-unlist(ztob[["sim.out"]][["x"]][["ev"]])
And the mean:
mean(x)
| {
"pile_set_name": "StackExchange"
} |
Q:
Lotus is a/the national flower of India?
Lotus is a/the national flower of India.
Before "national flower", which article should I use?
A:
If India has only one national flower, then the. If several, then a.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to say “go to hell” in French?
Is there a phrase or term in French that have the same meaning as “go to hell”?
A:
Littéralement:
Va au diable !
Avec un sens plus fort, plus imagé, voire artistique ou mélodramatique, un peu théâtral :
Va en enfer, Brûle en enfer !
Plus simple et direct dans le même sens:
Disparais !
familier:
Fiche-moi la paix (avec ça) !
Il y en a toute une série d'autres beaucoup moins correctes avec le lien déjà mentionné: Comment dire « go take a flying leap » en français ?
A:
As other comments say, "Va au diable !" (when talking to a single person) is an old way to say it.
There are plenty of other ways to say it more rudely. A more recent version and still "formal" would be
Va te faire cuire un oeuf.
And more usual :
Va te faire voir
A:
"Va te faire foutre" is the colloquial equivalent. The other translations given are too literal and much stronger than the intended meaning in English.
| {
"pile_set_name": "StackExchange"
} |
Q:
is it possible to get amount of tabs opened in Firefox browser?
I want to iterate over opened tabs and do specific tasks.
Is there a way to get the amount of opened tabs?
A:
If you need a js-script, I hope the following code should be helpful:
var wM = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
var numberOfTabs = wM.getMostRecentWindow("navigator:browser").gBrowser.browsers.length;
| {
"pile_set_name": "StackExchange"
} |
Q:
Como restringir valores minimos y maximos de un DatePickerDialog que emerge de un EditText de tipo Date en Android?
Quiero establecer el valor minimo y maximo de un DatePickerDialog que emerge al darle clic a un Edit Text de tipo Date, segun lo que he investigado se puede realizar con esto:
setMaxDate(long maxDate)
setMinDate(long minDate)
Pero no se como aplicarlo al codigo que tengo, mi codigo es el siguiente:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static EditText fechauso, horainicio;
private int anio, dia, mes, hora, minuto;
private static final int TIPO_DIALOGO = 0;
private static DatePickerDialog.OnDateSetListener oyenteSelectorFecha;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fechauso = (EditText) findViewById(R.id.txt_fechadeuso);
horainicio = (EditText) findViewById(R.id.txt_horainicio);
horainicio.setOnClickListener(this);
fechauso.setInputType(InputType.TYPE_NULL);
Calendar calendario = Calendar.getInstance();
anio = calendario.get(Calendar.YEAR);
mes = calendario.get(Calendar.MONTH);
dia = calendario.get(Calendar.DAY_OF_MONTH);
oyenteSelectorFecha = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
anio = year;
mes = monthOfYear;
dia = dayOfMonth;
mostrarFecha();
horainicio.requestFocus();
}
};
fechauso.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
closeSoftKeyBoard();
mostrarCalendario(fechauso);
}
}
});
horainicio.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
closeSoftKeyBoard();
mostrarTime();
}
}
});
}
public void mostrarCalendario(View control) {
showDialog(TIPO_DIALOGO);
}
public void mostrarFecha() {
fechauso.setText(anio + "-" + (mes + 1) + "-" + dia);
}
public void mostrarTime() {
// Get Current Time
final Calendar c = Calendar.getInstance();
hora = c.get(Calendar.HOUR);
minuto = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
horainicio.setText(hourOfDay + ":" + minute + ":00");
}
}, hora, minuto, false);
timePickerDialog.show();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0:
return new DatePickerDialog(this, oyenteSelectorFecha, anio, mes, dia);
}
return null;
}
public void closeSoftKeyBoard() {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
@Override
public void onClick(View v) {
if (v == horainicio) {
closeSoftKeyBoard();
mostrarTime();
}
}
}
A:
Debes usar setMinDate(long maxDate)
datePicker.setMinDate(System.currentTimeMillis() - 1000);
y setMaxDate(long minDate)
Calendar c = Calendar.getInstance();
c.set(2016, 6, 18);
datePicker.setMaxDate(c.getTimeInMillis());
actualización:
Recordaba que existía una pregunta similar aquí ¿Cómo deshabilitar días en el datepicker de android?, este sería un ejemplo:
Definimos variables para configurar nuestro DatePickerDialog:
private int miAnio, miMes, miDia;
Este es un ejemplo para crear un DatePicker y definir una fecha minima, por ejemplo definimos que sea el mes anterior y un día antes:
Calendar calendar = Calendar.getInstance();
miAnio = calendar.get(Calendar.YEAR);
miMes = calendar.get(Calendar.MONTH);
miDia = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog oyenteSelectorFecha = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Log.i("TAG", String.valueOf(year) + String.valueOf(monthOfYear) + String.valueOf(dayOfMonth));
}
}, miAnio, miMes, miDia);
//Como ejemplo: deseamos que la fecha minima sea un mes antes y un dia antes.
Calendar calendarioMin = Calendar.getInstance();
calendarioMin.add(Calendar.MONTH, - 1); //Mes anterior
calendarioMin.add(Calendar.DAY_OF_MONTH, - 1); //dia anterior
//defines que el día que deseas
oyenteSelectorFecha.getDatePicker().setMinDate(calendarioMin.getTimeInMillis() - 1000);
oyenteSelectorFecha.show();
Por lo tanto tu DatePicker únicamente permitirá como mínimo valor el definido en calendarioMin.getTimeInMillis().
| {
"pile_set_name": "StackExchange"
} |
Q:
Лингвистический термин
В интернете встретил задание:
В русском языке существует слово, которое часто входит в состав лингвистических терминов. У этого слова в составе терминов есть два антонима. При этом у этих антонимов одна и та же
приставка, а корни имеют противоположное значение. Что это за слово?
Ответ мне неизвестен. Может, вы знаете?
A:
Я думаю, это термин ассимиляция (уподобление): оглушение, озвончение.
Если это задание для старшеклассников, они должны знать этот термин.
A:
В русском языке существует слово, которое часто входит в состав
лингвистических терминов. У этого слова в составе терминов есть два
антонима. При этом у этих антонимов одна и та же приставка, а корни
имеют противоположное значение. Что это за слово?
Не удивлюсь, если окажется, что это задание или недостаточно корректно было составлено или же неправильно кем-то воспроизведено…
И не удивлюсь тому, что ответ мог предполагаться примерно таким:
ГЛАСНЫЙ звук.
Антонимом к слову ГЛАСНЫЙ в данном случае является слово СОГЛАСНЫЙ.
Ну а СОГЛАСНЫЕ звуки бывают разными — и твёрдыми, и мягкими… и ПОЛУТВЁРДЫМИ (ПОЛУМЯГКИМИ).
ПОЛУ — приставка.
ТВЁРДЫЙ, МЯГКИЙ — антонимы.
| {
"pile_set_name": "StackExchange"
} |
Q:
Styling radio button label inside just one table row
Here is the thing, I have one table with multiple rows containing radio buttons, i want to achieve this:
When i check a radio button the adjacent label changes color, and all other labels in THAT single row loose the color.
Right now im close but im missing some jquery skills to remove the color properly on other radio buttons of the same row.
Here is the fiddle, worth more than thousand words. Any help is much appreciated.
http://jsfiddle.net/cos33qvk/
Javascript:
$('input:radio').change(function(){
if($('input:radio').is(":checked")) {
$(this).parent().find('label i').addClass("on");
} else {
$(this).parent().find('label i').removeClass("on");
}
});
A:
$('input:radio').change(function() {
// remove color properly on other radio buttons
$(this).parents('tr').find('td label i').removeClass("on");
// add class for current label
if ($('input:radio').is(":checked")) {
$(this).parent().find('label i').addClass("on");
}
});
Demo: http://jsfiddle.net/cos33qvk/2/
| {
"pile_set_name": "StackExchange"
} |
Q:
Are specific tool related questions appropriate for SQA?
There does not appear to be a specific stack exchange site for questions and answers for specific testing tools (like QTP, Selenium, TestComplete, etc). I know that the tools themselves have their own support forums and such. However, would it be valid to ask questions about specific techniques, tasks, etc, for those tools?
A:
Given that the Selenium StackExchange proposal got merged into this site, I can't see how testing tool questions could be off-topic.
A:
If they are testing tools, or, even if it's a person using it for testing, or another QA task, I don't see any reason why they shouldn't be asked here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Filter List by using another List
Sorry to Post this stupid question but I do need some help from you
I have two lists in c#. Let's call them list<objet1> listObjet1 and list<objet2> listObjet2.
Here's the question : I want to somehow filter list<objet1> according to some matching value in objet2 and objet1
public class Objet1
{
public int Id { get; set; }
public string Libelle { get; set; }
public string IdObjet2 { get; set; }
}
public class Objet2
{
public int Id { get; set; }
public string Libelle { get; set; }
public string IdTrain { get; set; }
}
I am eager to have a List<Objet1> where Objet2.Id is equal to Objet1.Id, I tried these Linq
List<Objet1> listObjet1= (listObjet1.Select(p => p.id).Contains(listObjet2.Select(q=>q.idObjet1)))toList();
List<Objet1> listObjet1= (listObjet1.Select(p => p.id).Equal(listObjet2.Select(q=>q.idObjet1))).toList();
Or Equal() which can only return some lists I don't need like List<int>;.
What I need is just a List<Objet1>
A:
You're looking for a simple Join:
var result = listObjet1.Join(listObjet2, o1 => o1.Id, o2 => o2.Id, (o1, o2) => o1).ToList();
| {
"pile_set_name": "StackExchange"
} |
Q:
Is a Boros Guildgate considered a mountain?
I ask this question because I don't know if we can enchant a guilgate, like a boros guildgate as example, with Chained to the Rocks.
A:
No it is not. Mountain is a subtype of a land cards; for Boros Guildgate, the subtype is "Gate".
However, Steam Vents is a mountain and can be enchanted with Chained to the Rocks, because it has subtypes "Island" and "Mountain".
| {
"pile_set_name": "StackExchange"
} |
Q:
Pronotum: meaning and suffix context?
Pronotum
The pronotum (Biology) is a prominent plate-like structure that covers
all or part of the thorax of some insects. The pronotum covers the
dorsal surface of the thorax.
The word can be split in two parts: pro + notum. pro is reasonably unambiguous, but the notum part is frustrating.
pro (etymonline)
1: word-forming element meaning "forward, forth, toward the front" (as
in proclaim, proceed); "beforehand, in advance" (prohibit, provide);
2: The common modern sense "in favor of, on behalf of, supporting" (pro-independence,
pro-fluoridation, pro-Soviet, etc.) was not in classical Latin and is
attested in English from early 19c.
notus (etymologeek)
-sḱéti Proto-Indo-European (ine-pro)
*ǵn̥h₃sḱéti Proto-Indo-European (ine-pro) To recognise.
(Wikipedia) *gnōskō Proto-Italic (itc-pro) Know, get to know.
It has the root *gno*, same as in "ignore"
noton (Wikipedia)
νῶτον (noton) From Proto-Indo-European *not- (“rear, buttock”);
related to Latin natis (“rump”).
a combining form meaning “the back,” used in the formation of compound words:
eg. notochord [Greek nōton, nōtos back + Latin chorda cord]
eg. notodont adj. [Gr. notos, back; odous, tooth]
What is the coinage pronotum supposed to mean? The usage and origin of notum leaves me begging for a sensible literal meaning of the word, on whether it comes from "-notus" or "-noton".
Is it supposed to be "the notable supporting structure", or "the structure preceding the back", or something else?
(Extra: there are also the genera "Lanthonotus" and "Camponotus" - do they use the same notus suffix as in pronotum?)
A:
In a comment, someone said:
Oxford Dictionaries (now Lexico) say notum (which exists as a stand-alone word as well, without the pro-) is from Greek νῶτον referring to the back. So the notum is a plate on the back of the thorax, hence the ‘back’; the pronotum is the notum on the prothorax. – Janus Bahs Jacquet
Below is a screenshot from Google, which shows that notum is derived from nōtun and was coined in the late 19th century.
A:
Janus Bahs Jacquet left a comment pointing out that νῶτον exists as an independent word in Greek (a neuter noun) with the meaning "back". See the linked LSJ entry for further details. A synonymous variant masculine form νῶτος also exists.
I think it's not really any more accurate to call -notum/-notus a suffix than it is to call -arm a suffix in the word forearm. And I think it's unnecessary to call -notum/-notus a "combining form" because it's really the same form as the independent word. A special combining form of νῶτον exists for use in words where it is not the last element of the compound: that combining form is νωτο- (noto-) (or sometimes not-, before a vowel), as in your examples of noto-chord and not-odont.
The occurrence of "Pronotum" in Burmeister's entomological texts
According to the Oxford English Dictionary (OED), pronotum was formed in German (as Pronotum) by Hermann Burmeister, first appearing in his Handbuch der Entomologie (1832) alongside the parallel formations Mesonotum and Metanotum. The OED identifies the last element as Ancient Greek νῶτον, discussed above.
Unfortunately, I haven't been able to view the German source text (if you think you'd have better luck finding the cited passage, the OED specifically cites "I. i. iii. 81" as the location in the 1832 handbook where the word Pronotum occurs).
I found an 1836 translation of Burmeister, A manual of entomology, (translated by W. E. Shuckard), that gives a etymology that doesn't seem to agree with the OED's:
The superior, which we call PRONOTUM* (Pl. IX. and XII. A,A,A, Prothorax of Kirby and Spence), takes very different figures. [...]
*This name is compounded of προ, anterior, and νότος, the back.
(p. 75)
The title page says that this translation contains "original notes and plates by the translator", so my guess is that Shuckard misspelled νῶτος as νότος in this note. Both Greek spellings would be pronounced the same way in the traditional English pronunciation of Latin and Greek (and also in modern Greek pronunciation, actually), but νότος seems to be a different word meaning "south wind". Despite the misspelling, and Shuckard's reference to the masculine rather than the neuter variant of the Ancient Greek word for "back", the meaning given by Shuckard is consistent with the OED's explanation.
Latin notus and English "notable" aren't relevant
Latin nōtus "known" is unrelated, as shown by the etymologies that you cite: PIE *ǵneh₃- is different from PIE *not-.
And "notable", from Latin nŏta, probably is unrelated to either of the preceding words. A traditional etymology connected nŏta with nōtus, but the short vowel in nŏta makes that hypothesis difficult to support: de Vaan 2008 writes that "Schrijver 1991 has clearly shown that it is impossible to derive nota from [...] *ǵneh₃- 'to know'" (Etymological Dictionary of Latin and the other Italic Languages, p. 414).
I don't see any way pronotum could represent "the notable supporting structure": it wouldn't be put together the right way (assuming you're thinking that pro- might provide the meaning "supporting" and -notum might provide the meaning "notable") and the parts don't mean that.
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS Layout Problems, FlowChart Design
i need to build a dynamic template to create a flow chart diagram, but only with HTML and CSS
See Image.
enter image description here
The black DIV should have a defined width and height.
The red DIV represent a row in the black DIV.
The green DIV are boxes with a border and a defined size with 100px height and 200px width.
It should be possible to add two or more green DIVs into one red DIV (See yellow rect)
All the content should align in the middle (See blue line)
.page {
position: relative;
width: 800px;
height: 800px;
}
.row{
width: 100%;
text-align: center;
margin-bottom: 10px;
}
.element{
display: inline-block;
text-align: center;
width: 200px;
height: 50px;
border: 1px solid #000;
}
<div class="page">
<div class="row">
<div class="element">Start</div>
</div>
<div class="row">
<div class="element">Step_1</div>
<div class="element">Step_2</div>
</div>
<div class="row">
<div class="element">Step_1_2</div>
</div>
<div class="row">
<div class="element">Ende</div>
</div>
</div>
Maybe someone can help me to implement the layout.
Thank you
A:
I think you are looking for something like this: https://jsfiddle.net/m1pz6zcu/
.page {
width: 400px;
height: 400px;
border-style: solid;
border-width: 1px;
text-align: center;
}
.row {
width: calc(100% - 2px);
border-style: solid;
border-width: 1px;
border-color: red;
display: flex;
height: calc(25% - 2px);
}
.element {
min-width: 20%;
border-style: solid;
border-width: 1px;
border-color: green;
margin-right: auto;
margin-left: auto;
height: 50px;
height: calc(100% - 2px);
}
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.