text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
react.js overlay not working - only displaying parent object
I'm just trying to create an overlay from raw with react.
So I created an empty Overlay Component for now. One App Component, which has the data(a simple line) to be displayed for the normal time.
Now I rendering <Overlay><App/></Overlay>
But the from App is not being rendered?
What is wrong here, actually ?
codesandbox.io
A:
There is an issue in return of Overlay component. Please replace your return statement with <div className="overlay">{this.props.children}<div>
You have to write css for class overlay.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to change a const struct member in C?
I have to change a const member of a const struct instance in C.
I already know it is possible to change a const basic type as follows:
const int a = 2;
*(int*)&a = 3;
I also can change a const member of a struct instance as follows:
typedef struct ST {
const int a;
const int b;
}ST;
ST st = {.a = 1,.b =2};
int main() {
*(int *)(&((*(ST*)(&st)).a)) = 5; //works fine , no problem
}
However i had no success trying to change the const member of the struct instance, if the instance is constant:
typedef struct ST {
const int a;
const int b;
}ST;
const ST st = {.a = 2,.b=3}; //const instance
int main() {
*(int *)(&((*(ST*)(&st)).a)) = 5; //does not work(Seg fault)!!
}
So , would it be possible to change the "a" member value in this last scenario?
If not , why?
A:
I already know it is possible to change a const basic type as follows:
const int a = 2;
*(int*)&a = 3;
The fact that your compiler lets you do it does not make it legal. This code invokes undefined behavior, so the same program could fail or crash if you run it on a different platform, or use a different compiler.
*(int *)(&((*(ST*)(&st)).a)) = 5; //works fine , no problem
This code has the same problem: it invokes undefined behavior.
The last piece of code that you try also has (you guessed it!) undefined behavior. This time, however, the program crashes instead of running to completion.
| {
"pile_set_name": "StackExchange"
} |
Q:
JTestcase for data in xml files with JUnit?
I looked upon some years old code which uses JTestcase for separating data from Test case(JTestCase basically helps to manage data in xml files).
So JTestCase is integrated with JUnit test cases code.
Jar available for JTestcase is 2006 version so i guess there is no new release for same. This makes me think that probably JTestCase is old thing to use otherwise they would have provided new version.
Please tell me if there is some new technology in place of JTestCase and if not what are negatives of Jtestcase(like one can be performance considering fact that it allows use of xml files which is itself in trade off with better organization of complex data).
I couldn't find Maven artifact for JTestcase. Please let me know if it is available on any site.
Which site is good dependable source to find maven artifact. Currently i see https://repository.sonatype.org/index.html#welcome for same purpose.
A:
That seems like a lot of effort to go to just to write a unit test.
I think the negative of using JTestCase is doubling the amount of code you have to write.
I wouldn't use this framework unless you could see some significant benefit to putting your test data into XML. I think doing this for tests would make it harder to maintain in most cases!
| {
"pile_set_name": "StackExchange"
} |
Q:
Should Copy Paste be allowed in Confirm e-mail address field?
Should Copy Paste be allowed in Confirm e-mail address field?
What if we type in incorrect email address. And we are copy pasting the same? And this email id is not used for any sign up process and is used as a part of filing any insurance claim. It can cause issues if mails are not delivered. Personally i don't like to have copy paste feature in Confirm email address field. But i would like to know the common practice. Should it be allowed or not?
A:
Should Copy Paste be allowed in Confirm e-mail address field?
Is this mentioned in your application's requirements?
Personally, I think forcing the user to enter the same information twice is foolish. IMHO, it's far better to have a 2-stage confirmation where the user must respond to an email before registration/confirmation is complete. If the user entered an incorrect email, the 2nd stage will fail and the user will know about it.
But if your requirements are such that a "confirm email" field is required, I think it makes sense to disable the ability to paste into that field. That's an individual preference - the standards in your shop may differ.
What if we type in incorrect email address. And we are copy pasting
the same?
Yes.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I access Private APIs in Chrome extension
I need to get the value of mac address and username and computer. I want to do this with networkingPrivate. But I can’t able to access it.
I wrote in the manifest.json file this:
"permissions": ["networkingPrivate"]
A:
Generally you can't because they're private exactly for the purpose of being private, not public API. It's also whitelisted to specific extensions by Google or its trusted associates.
For your own personal use you may have success by running Chrome with a custom command line parameter --whitelisted-extension-id=abcd where abcd stands for the 32-character id of your extension as seen on chrome://extensions page when developer mode switch is enabled in the top right corner of the page. Or you can mimic a trusted extension's id by finding its manifest.json and copying its "key" to your own manifest.json.
For a public extension you'll have to use a workaround. For example, write a separate utility and invoke it via nativeMessaging API.
| {
"pile_set_name": "StackExchange"
} |
Q:
ubuntu 15.10 default editor for sftp remote files doesn't work
I'm using Ubuntu 15.10 64bit and trying to open a remote file (sftp) with sublimetext2.
All worked fine till yesterday.
Today all files listed in a remote sftp directory are opened with gedit, despite the default program to open these files (.php, .txt, etc) is set up to sublimetext2.
Also, in the "file properties" -> "Open with" there is already set up to default sublimetext2.
Opening this way still use gedit instead:
right click on file -> open with other application -> select sublimetext2 (already set as default).
I already tried with leafpad but the result is exactly the same.
Edit:
I tried this:
- opened sublime from terminal with " > fileName.log" to force it write some log in the terminal.
- made a new file from sublime-text and then save it to the remote location. When pressing Ok to save the file, after some seconds the editor crashes.
In the terminal appears:
(sublime_text:3228): Gtk-WARNING **: Operazione non supportata dal backend
(sublime_text:3228): Gtk-WARNING **: Operazione non supportata dal backend
/usr/bin/sublime-text: riga 3: 3228 Errore di segmentazione (core dump creato)
/opt/sublime_text_2/sublime_text --class=sublime-text-2 "$@"
In the /var/crash/ appeared the file "_opt_sublime_text_2_sublime_text.1000.crash", an excerpt is:
SegvAnalysis:
Segfault happened at: 0x7fab2f9b66fa <strlen+42>: movdqu (%rax),%xmm12
PC (0x7fab2f9b66fa) ok
source "(%rax)" (0x00000000) not located in a known VMA region (needed readable region)!
destination "%xmm12" ok
SegvReason: reading NULL VMA
Stacktrace:
Edit: crash log of Sublime text 3
SegvAnalysis:
Segfault happened at: 0x7fa347c126fa <strlen+42>: movdqu (%rax),%xmm12
PC (0x7fa347c126fa) ok
source "(%rax)" (0x00000000) not located in a known VMA region (needed readable region)!
destination "%xmm12" ok
SegvReason: reading NULL VMA
SourcePackage: sublime-text
Stacktrace:
#0 strlen () at ../sysdeps/x86_64/strlen.S:106
No locals.
#1 0x000000000074c324 in ?? ()
No symbol table info available.
#2 0x00000000005c5ffe in ?? ()
No symbol table info available.
#3 0x000000000044c0eb in ?? ()
No symbol table info available.
#4 0x000000000044c7b8 in ?? ()
No symbol table info available.
#5 0x000000000044c904 in ?? ()
No symbol table info available.
#6 0x000000000057e3c6 in ?? ()
No symbol table info available.
#7 0x000000000058e640 in ?? ()
No symbol table info available.
#8 0x000000000058723c in ?? ()
No symbol table info available.
#9 0x00000000005af5fc in ?? ()
No symbol table info available.
#10 0x00000000005c3924 in ?? ()
No symbol table info available.
#11 0x00000000005c8747 in ?? ()
No symbol table info available.
#12 0x00007fa3426cbe5c in ?? () from /usr/lib/x86_64-linux-gnu/libgtk-x11-2.0.so.0
No symbol table info available.
[...]
sublime_text crashed with SIGSEGV in strlen()
What I must do to solve that frustrating problem?
Thanks!
A:
Solution founded in the italian Ubuntu-it forum:
http://forum.ubuntu-it.org/viewtopic.php?f=8&t=607760
The solution is to use sshfs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Matching array key and value and displaying only those in the matched result
I am working with an API which provides a result set in JSON, I transform that data into a PHP array to work with it on my interface.
The issue i'm having now is trying to filter the data based on a particular key having a certain value.
Here is the result set returned:
[
{
"id":5,
"firstname":"Joel ",
"lastname":"Abase",
"displayName":"Abase, Joel ",
"officeId":3,
"officeName":"Birmingham",
"isLoanOfficer":true,
"isActive":true
},
{
"id":1,
"firstname":"Precious ",
"lastname":"Love",
"displayName":"Love, Precious ",
"officeId":4,
"officeName":"Manchester",
"isLoanOfficer":true,
"isActive":true
},
{
"id":2,
"firstname":"Bernard ",
"lastname":"Aikins",
"displayName":"Aikins, Bernice ",
"officeId":2,
"officeName":"Manchester",
"isLoanOfficer":false,
"isActive":true
},
{
"id":8,
"firstname":"Kwame",
"lastname":"Joseph",
"displayName":"Joseph, Kwame",
"officeId":2,
"officeName":"Manchester",
"isLoanOfficer":true,
"isActive":true,
"joiningDate":[
2018,
5,
1
]
},
{
"id":4,
"firstname":"Janine ",
"lastname":"Hayden",
"displayName":"Hayden, Janine ",
"officeId":1,
"officeName":"Head Office",
"isLoanOfficer":false,
"isActive":true
},
{
"id":6,
"firstname":"Esther",
"lastname":"Monroe",
"displayName":"Monroe, Esther",
"officeId":2,
"officeName":"London",
"isLoanOfficer":true,
"isActive":true,
"joiningDate":[
2017,
11,
1
]
}
]
I would like to filter the results in a loop where the 'isLoanOfficer' is equal to true, essentially only showing those who are loan officers.
Here is what I have tried so far:
<div class="col-sm-5">
<label class="control-label" for="staffId">Loan Officer<span style="color:red;">*</span></label>
<?php
$s = 0;
$temp_staff = json_decode($staff_json, true);
$count_staff = count($temp_staff);
echo '<select class="form-control" type="text" name="staffId" required>';
echo "<option value=". ">" . " </option>";
while($s < $count_staff && $temp_staff[$s]['isLoanOfficer'] == true){
echo "<option value=" . $temp_staff[$s]['id'] . ">" . $temp_staff[$s]['displayName'] . " </option>";
$s++;
}
echo '</select>';
?>
<br>
</div>
I also tried adding this code inside the while loop:
if($temp_staff[$s]['isLoanOfficer'] == true) {
echo "<option value=" . $temp_staff[$s]['id'] . ">" . $temp_staff[$s]['displayName'] . " </option>";
$s++;
}
It seems that it only evaluates the first value and then exits. Any help?
A:
You'll have to use the condition inside the loop. Try the below code :
while($s < $count_staff){
if ($temp_staff[$s]['isLoanOfficer'] == true) {
echo "<option value=" . $temp_staff[$s]['id'] . ">" . $temp_staff[$s]['displayName'] . " </option>";
}
$s++;
}
Due to that condition your $s++ is not being executed properly.
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get Image Resolution via VBScript
How can I get an image resolution in DPI with VBScript?
for example
Res= GET "M.jpg" Resolution
If Res > 100
Echo "GOODQ"
A:
You gan get the image DPI using the HorizontalResolution and VerticalResolution properties of the WIA.ImageFile scripting object:
Set objImage = CreateObject("WIA.ImageFile")
objImage.LoadFile "C:\M.jpg"
If objImage.HorizontalResolution > 100 Then
Log.Message "GOODQ (" & objImage.HorizontalResolution & " DPI)"
End If
Just for completeness, there's another solution for Windows Vista and later — using the Folder.GetDetailsOf method to read the image DPI from the extended file properties. But the code will be longer and a bit messier, because:
The index of the Horizontal resolution and Vertical resolution file properties are different on different Windows versions (see this page and this my answer for details).
The extended file properties return DPI as a string like 240 dpi; you may need to convert it to a number.
' For Windows 7
Const HORIZONTAL_RESOLUTION = 161
Const VERTICAL_RESOLUTION = 163
Dim objShell : Set objShell = CreateObject("Shell.Application")
Dim objFolder : Set objFolder = objShell.Namespace("C:\MyFolder")
Dim objFile : Set objFile = objFolder.ParseName("M.jpg")
Dim strDpi : strDpi = objFolder.GetDetailsOf(objFile, HORIZONTAL_RESOLUTION) ' Returns DPI as a string like "240 dpi"
Dim dpi : dpi = ToInt(strDpi)
If dpi > 100 Then
Log.Message "GOODQ (" & dpi & " DPI)"
End If
' Extracts a number from a string, e.g. "240 dpi" -> 240
' NB: no error handling
Function ToInt(ValueStr)
Dim objRE : Set objRE = New RegExp
objRE.Pattern = "\d+"
Dim colMatches : Set colMatches = objRE.Execute(ValueStr)
ToInt = CLng(colMatches(0).Value)
End Function
| {
"pile_set_name": "StackExchange"
} |
Q:
Find and group all unique versions of a file
I have a convoluted directory structure where there are many copies of foo.txt. I'd like to find all copies of this file and group them by their diff result, i.e.
[type 1]
/bar2/sub1/foo.txt
/foobar/foo.txt
[type 2]
/bar2/sub1/foo.txt
/foobar/foo.txt
[type 3]
/sub3/sub4/sub5/foo.txt
...
A:
How about something simple like calculating the md5sum for each file and sorting based on the hash.
md5deep -r . | sort
d921223ccbe759a632973962bc15a497 /root/.bash_history
dcac40478a92e87cd08a42a6425acea6 /root/testsrv/keys/04.pem
dcac40478a92e87cd08a42a6425acea6 /root/testsrv/keys/client2.crt
e12f5739f81b08c470f20890304bf53e /root/.bashrc
e1b23db3d2293b142938c74649d9fa6a /root/testsrv/list-crl
e4e2818e1ed11a951ed5da4e1a86885a /root/testsrv/keys/revoke-test.pem
ee8bd2ea88220c877a62e22e36a02d20 /root/testsrv/keys/index.txt.attr
ee8bd2ea88220c877a62e22e36a02d20 /root/testsrv/keys/index.txt.attr.old
| {
"pile_set_name": "StackExchange"
} |
Q:
How to force an app to change language in iOS/Objective-C?
I'm having a problem with make app change language immediately like this app.
I've found a lot of similar question like this and this.
But, unfortunately, the related answers to these question don't work for me. I need my app change language immediately when I tap on an cell.
Any ideas? Thank in advance.
A:
My solution
First you need to create the String File
Go to Project Right Click.
New File->iOS
Under iOS you can see the Resource
Click Resource and you can see the String File among the group of files.
Click that give name whatever you want.
Now you can create the string file below.
"Date"="Date";
"Time"="Time";
"Done"="Done";
"Back"="Back";
In appDelegate.h
-(NSString*) languageSelectedStringForKey:(NSString*) key
{
NSString *path;
AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
if(app.currentLanguage==ENGLISH)
path = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
else if(app.currentLanguage==TAMIL)
path = [[NSBundle mainBundle] pathForResource:@"ta-IN" ofType:@"lproj"];
else if(app.currentLanguage==SPANISH)
path = [[NSBundle mainBundle] pathForResource:@"es" ofType:@"lproj"];
else if(app.currentLanguage==FRENCH)
path = [[NSBundle mainBundle] pathForResource:@"fr" ofType:@"lproj"];
else if(app.currentLanguage==JAPANESE)
path = [[NSBundle mainBundle] pathForResource:@"ja" ofType:@"lproj"];
else if(app.currentLanguage==GERMAN)
path = [[NSBundle mainBundle] pathForResource:@"de" ofType:@"lproj"];
else if(app.currentLanguage==KOREAN)
path = [[NSBundle mainBundle] pathForResource:@"ko" ofType:@"lproj"];
else if(app.currentLanguage==RUSSIAN)
path = [[NSBundle mainBundle] pathForResource:@"ru" ofType:@"lproj"];
else if(app.currentLanguage==HINDI)
path = [[NSBundle mainBundle] pathForResource:@"hi" ofType:@"lproj"];
else if(app.currentLanguage==CHINESE)
path = [[NSBundle mainBundle] pathForResource:@"zh-Hans" ofType:@"lproj"];
else if(app.currentLanguage==ITALIAN)
path = [[NSBundle mainBundle] pathForResource:@"it" ofType:@"lproj"];
else if(app.currentLanguage==PORTUGUESE)
path = [[NSBundle mainBundle] pathForResource:@"pt" ofType:@"lproj"];
else if(app.currentLanguage==THAI)
path = [[NSBundle mainBundle] pathForResource:@"th" ofType:@"lproj"];
else if(app.currentLanguage==MALAY)
path = [[NSBundle mainBundle] pathForResource:@"ms" ofType:@"lproj"];
else if(app.currentLanguage==INDONESIAN)
path = [[NSBundle mainBundle] pathForResource:@"id" ofType:@"lproj"];
else if(app.currentLanguage==CHINESE1)
path = [[NSBundle mainBundle] pathForResource:@"zh-Hant" ofType:@"lproj"];
else
{
path = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
}
NSBundle* languageBundle = [NSBundle bundleWithPath:path];
NSString* str=[languageBundle localizedStringForKey:key value:@"" table:@"LocalizeSTRING"];
return str;
}
Call this above method in didFinishLaunchingWithOptions of appDelegate.m
NSString *str=[[[NSUserDefaults standardUserDefaults]objectForKey:@"AppleLanguages"] objectAtIndex:0];
if([str isEqualToString:[NSString stringWithFormat: @"en"]])
{
currentLanguage=ENGLISH;
selectedrow=ENGLISH;
}
else if([str isEqualToString:[NSString stringWithFormat: @"ta-IN"]])
{
currentLanguage=TAMIL;
selectedrow=TAMIL;
}
else if([str isEqualToString:[NSString stringWithFormat: @"es"]])
{
currentLanguage=SPANISH;
selectedrow=SPANISH;
}
else if([str isEqualToString:[NSString stringWithFormat: @"fr"]])
{
currentLanguage=FRENCH;
selectedrow=FRENCH;
}
else if([str isEqualToString:[NSString stringWithFormat: @"ja"]])
{
currentLanguage=JAPANESE;
selectedrow=JAPANESE;
}
else if([str isEqualToString:[NSString stringWithFormat: @"de"]])
{
currentLanguage=GERMAN;
selectedrow=GERMAN;
}
else if([str isEqualToString:[NSString stringWithFormat: @"ko"]])
{
currentLanguage=KOREAN;
selectedrow=KOREAN;
}
else if([str isEqualToString:[NSString stringWithFormat: @"ru"]])
{
currentLanguage=RUSSIAN;
selectedrow=RUSSIAN;
}
else if([str isEqualToString:[NSString stringWithFormat: @"hi"]])
{
currentLanguage=HINDI;
selectedrow=HINDI;
}
else if([str isEqualToString:[NSString stringWithFormat: @"zh-Hans"]])
{
currentLanguage=CHINESE;
selectedrow=CHINESE;
}
else if([str isEqualToString:[NSString stringWithFormat: @"it"]])
{
currentLanguage=ITALIAN;
selectedrow=ITALIAN;
}
else if([str isEqualToString:[NSString stringWithFormat: @"pt"]])
{
currentLanguage=PORTUGUESE;
selectedrow=PORTUGUESE;
}
else if([str isEqualToString:[NSString stringWithFormat: @"th"]])
{
currentLanguage=THAI;
selectedrow=THAI;
}
else if([str isEqualToString:[NSString stringWithFormat: @"ms"]])
{
currentLanguage=MALAY;
selectedrow=MALAY;
}
else if([str isEqualToString:[NSString stringWithFormat: @"id"]])
{
currentLanguage=INDONESIAN;
selectedrow=INDONESIAN;
}
else if([str isEqualToString:[NSString stringWithFormat: @"zh-Hant"]])
{
currentLanguage=CHINESE1;
selectedrow=CHINESE1;
}
[self languageSelectedStringForKey:str];
Then in your Required View Controller
-(NSString*) languageSelectedStringForKey:(NSString*) key
{
app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
if(app.currentLanguage==ENGLISH)
path = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
else if(app.currentLanguage==TAMIL)
path = [[NSBundle mainBundle] pathForResource:@"ta-IN" ofType:@"lproj"];
else if(app.currentLanguage==SPANISH)
path = [[NSBundle mainBundle] pathForResource:@"es" ofType:@"lproj"];
else if(app.currentLanguage==FRENCH)
path = [[NSBundle mainBundle] pathForResource:@"fr" ofType:@"lproj"];
else if(app.currentLanguage==JAPANESE)
path = [[NSBundle mainBundle] pathForResource:@"ja" ofType:@"lproj"];
else if(app.currentLanguage==GERMAN)
path = [[NSBundle mainBundle] pathForResource:@"de" ofType:@"lproj"];
else if(app.currentLanguage==KOREAN)
path = [[NSBundle mainBundle] pathForResource:@"ko" ofType:@"lproj"];
else if(app.currentLanguage==RUSSIAN)
path = [[NSBundle mainBundle] pathForResource:@"ru" ofType:@"lproj"];
else if(app.currentLanguage==HINDI)
path = [[NSBundle mainBundle] pathForResource:@"hi" ofType:@"lproj"];
else if(app.currentLanguage==CHINESE)
path = [[NSBundle mainBundle] pathForResource:@"zh-Hans" ofType:@"lproj"];
else if(app.currentLanguage==ITALIAN)
path = [[NSBundle mainBundle] pathForResource:@"it" ofType:@"lproj"];
else if(app.currentLanguage==PORTUGUESE)
path = [[NSBundle mainBundle] pathForResource:@"pt" ofType:@"lproj"];
else if(app.currentLanguage==THAI)
path = [[NSBundle mainBundle] pathForResource:@"th" ofType:@"lproj"];
else if(app.currentLanguage==MALAY)
path = [[NSBundle mainBundle] pathForResource:@"ms" ofType:@"lproj"];
else if(app.currentLanguage==INDONESIAN)
path = [[NSBundle mainBundle] pathForResource:@"id" ofType:@"lproj"];
else if(app.currentLanguage==CHINESE1)
path = [[NSBundle mainBundle] pathForResource:@"zh-Hant" ofType:@"lproj"];
else
{
path = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
}
NSBundle* languageBundle = [NSBundle bundleWithPath:path];
NSString* str=[languageBundle localizedStringForKey:key value:@"" table:@"LocalizeSTRING"];
return str;
}
Call this above method in your viewDidLoad and viewWillAppear method or Call that method where you want to call
- (void)viewWillAppear:(BOOL)animated
{
//If you want to set language in label,TextFiled
localizeBackLabel.text=[self languageSelectedStringForKey:@"Back"];
localizeDoneLabel.text=[self languageSelectedStringForKey:@"Done"];
localizeTimeLabel.text=[self languageSelectedStringForKey:@"Time"];
localizeDateLabel.text=[self languageSelectedStringForKey:@"Date"];
//If you want to set language in button
[yourButton setTitle:[self languageSelectedStringForKey:@"Back"]; forState:UIControlStateNormal];
[yourButton setTitle:[self languageSelectedStringForKey:@"Done"]; forState:UIControlStateNormal];
//If you want to set the Language in cell
cell.labelHomeList.text=[self languageSelectedStringForKey:@"Date"];
cell.labelHomeList.text=[self languageSelectedStringForKey:@"Time"];
}
Finally if you want to change the language to other language.For example in (Settings) table you have two languages.If you want to change it to other languages please follow the below coding
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
app.selectedrow=indexPath.row;
if (indexPath.row==0)
{
app.currentLanguage=ENGLISH;
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", nil]forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"%d", [[NSUserDefaults standardUserDefaults] synchronize]);
}
else
{
app.currentLanguage=CHINESE1;
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-Hant", nil]forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
it works perfectly.
A:
I think that this will solve your problem.
I had the same problem 1 month ago.
You can follow this tutorial.
Example:
In your .strings file you put translation: "hello" = "HOLA MUNDO";
#import "LocalizationSystem.h"
LocalizationSetLanguage(@"Spanish");
CCLabel* label = [CCLabel labelWithString:AMLocalizedString(@"hello",@"Hello World") fontName:@"Marker Felt" fontSize:32];
EDIT: This is additional information as user asks in comment:If you want to translate whole view where your language option is changed, I propose you to make method that will be called everytime you change language:
-(void)translateOnChoose {
self.label.text = AMLocalizedString(@"hello",@"Hello World");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Variable in \foreach,
I would like to show you my problem. Here you have the script to generate a picture.Now I need to generate a second picture in which the arrows are not equally spaced any more.
\documentclass[letterpaper,11pt]{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{tikz} %for drawings
\usetikzlibrary{shapes}
\usetikzlibrary{arrows}
\usetikzlibrary{calc}
\usepackage{pgfplots}
\usepackage{tkz-fct} %for functions
\usepackage[hmargin=1in,vmargin=1in]{geometry}
\begin{document}
\begin{figure}[h]
\begin{center}
\begin{tikzpicture}[
every path/.style = {},
every node/.append style = {font=\sffamily}
]
% Store points unrolled
\foreach \x in {0,30,60,...,330}
{
\node at (\x /30 , 0) (P1\x) {};
\node at (\x /30+ 1,0) (P2\x) {};
\draw[lightgray] (P1\x) -- (P2\x) {};
};
% Store vorticity points
\foreach \x in {0,30,60,...,330}
{
\node at ($(P1\x)!1cm+0.6cm*sin(\x)!90:(P1\x)$) (V1\x) {};
\node at ($(P2\x)!1cm+0.6cm*sin(\x+30)!270:(P2\x)$) (V2\x) {};
};
% Draw the vorticity distribution
\foreach \x in {0,30,60,...,330}
{
\draw[very thick, <-] (V1\x) -- (P1\x) node(xline)[right] {};
\draw[very thick, <-] (V2\x) -- (P2\x) node(xline)[right] {};
\draw[lightgray] (V1\x) -- (V2\x) node(xline)[right] {};
\draw[lightgray] (V1\x) -- (V2\x) node(xline)[right] {};
}
\end{tikzpicture}
\end{center}
\caption{An example of vorticiy distribution along the N panels when the geometry is unrolled}
\label{Vorticity_distribution_unrolled}
\end{figure}
\end{document}
would anyone be able to generate a figure describing the same function f=f(\x), but with an higher arrow density where the arrows are higher?
I hope that this question is more understandable.
And thanks a lot.
Dario
A:
Based on Symbol 1's answer I have developed the following where the arrow density is higher where the arrows are higher instead of random.
\documentclass[border=9,tikz]{standalone}
\begin{document}
\begin{tikzpicture}[shorten <=2,shorten >=2]
\coordinate (A) at (0, 0);
\coordinate (B) at (0, 1);
\draw[->] (A) -- (B);
\foreach \i [evaluate={\x=\lastx+0.25-(\lasty-1)/3}, evaluate={\y=1+sin(72*\x)/4}, remember=\x as \lastx (initially 0), remember=\y as \lasty (initially 1)] in {1, ..., 60} {
\coordinate (C) at (\x, 0);
\coordinate (D) at (\x, {\y});
\draw[->] (C) -- (D);
\draw[gray] (A) -- (C) coordinate (A);
\draw[gray] (B) -- (D) coordinate (B);
}
\end{tikzpicture}
\end{document}
For more information about the \foreach command see tikz documentation section VII.83 "Repeating Things: The Foreach Statement". Options to customize the foreach-statement are described on page 904.
| {
"pile_set_name": "StackExchange"
} |
Q:
Managing an Entity and its Snapshot with an ORM
I would like to use one of the ideas that Jimmy Nilsson mentioned in his book Applying DDD with Patterns, and that is if i have an entity like a Product for example, i would like to take a snapshot of that entity for historic information, something like ProductSnapshot but i wonder how i might be able to implement this with an ORM (i am currently using Entity Framework). The main problem i am facing is that if i have another Entity like OrderLine that receives the Product via its constructor then entity framework would need you to make a public property of the type you wish to persist so this will force me to have something like this:
class OrderLine {
public Product Original Product {get; set;}
public ProductSnapshot Snapshot {get; set;}
}
and that seems awkward and not intuitive and i don't know how to deal with it properly when it comes to data binding (to which property i should bind), and finally i think that Product is an Entity while ProductSnapshot is a Value Object plus the snapshot is only taken when the OrderLine is accepted and after that the Product is not needed.
A:
When doing DDD, forget that the database exists. This means the ORM doesn't exist either. Now, because you don't have to care about persistence and ORM limits, you can model the ProductSnapshot according to the domain needs.
Create a ProductSnapshot class with all the required members.This class would be a result probably of a SnapshotService.GetSnapshot(Product p) . Once you have the ProductSnapshot just send it to a repository SnapshotsRepository.Save(snapshot) . Being a snapshot, this means it will probably be more of a data structure, a 'dumb' object. It also should be invariable, 'frozen' .
The Repository will use EF to actually save the data. You decide what the EF entities and relations are. ProductSnapshot is a considered to be a business object by the persistence(it doesn't matter if in reality it's just a simple Dto) and the EF entities may look very different (for example, I store business objects in serialized form in a key-value table) according to your querying needs.
Once you define the EF entites you need to map the ProductSnapshot to them. It's very probable that ProductSnapshot itself can be used as an EF Entity so you don't need to do any mapping.
The point is, that taking a snapshot seems to be domain behavior. You deal with the EF only after you have the snapshot and you do exactly as you'd do with any other busines object.
| {
"pile_set_name": "StackExchange"
} |
Q:
Inheritance from multiple interfaces with the same method name
If we have a class that inherits from multiple interfaces, and the interfaces have methods with the same name, how can we implement these methods in my class? How can we specify which method of which interface is implemented?
A:
By implementing the interface explicitly, like this:
public interface ITest {
void Test();
}
public interface ITest2 {
void Test();
}
public class Dual : ITest, ITest2
{
void ITest.Test() {
Console.WriteLine("ITest.Test");
}
void ITest2.Test() {
Console.WriteLine("ITest2.Test");
}
}
When using explicit interface implementations, the functions are not public on the class. Therefore in order to access these functions, you have to first cast the object to the interface type, or assign it to a variable declared of the interface type.
var dual = new Dual();
// Call the ITest.Test() function by first assigning to an explicitly typed variable
ITest test = dual;
test.Test();
// Call the ITest2.Test() function by using a type cast.
((ITest2)dual).Test();
A:
You must use explicit interface implementation
A:
You can implement one or both of those interfaces explicitly.
Say that you have these interfaces:
public interface IFoo1
{
void DoStuff();
}
public interface IFoo2
{
void DoStuff();
}
You can implement both like this:
public class Foo : IFoo1, IFoo2
{
void IFoo1.DoStuff() { }
void IFoo2.DoStuff() { }
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert a List to a Set with Java 8
Is there a one-liner to convert a list of String to a set of enum?
For instance, having:
public enum MyVal {
ONE, TWO, THREE
}
and
List<String> myValues = Arrays.asList("ONE", "TWO", "TWO");
I'd like to convert myValues to a Set<MyVal> containing the same items as:
EnumSet.of(MyVal.ONE, MyVal.TWO)
A:
Yes, you can make a Stream<String> of your elements, map each of them to the respective enum value with the mapper MyVal::valueOf and collect that into a new EnumSet with toCollection initialized by noneOf:
public static void main(String[] args) {
List<String> myValues = Arrays.asList("ONE", "TWO", "TWO");
EnumSet<MyVal> set =
myValues.stream()
.map(MyVal::valueOf)
.collect(Collectors.toCollection(() -> EnumSet.noneOf(MyVal.class)));
System.out.println(set); // prints "[ONE, TWO]"
}
If you are simply interested in having a Set as result, not an EnumSet, you can simply use the built-in collector Collectors.toSet().
A:
Here's a two-liner (but shorter):
EnumSet<MyVal> myVals = EnumSet.allOf(MyVal.class);
myVals.removeIf(myVal -> !myValues.contains(myVal.name()));
Instead of adding elements present on the list, you could create an EnumSet with all possible values and remove the ones that are not present on the list.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to round numbers inside of a object
How can I round numbers inside of a object like this:
{1: {x:10.76, y:50.44}, 2:{x:5.887, y:23.433}, ...}
I tried to do this using map but I guess map only works with arrays
obj.map(function(each_element){
return Number(each_element.toFixed(0.1));
});
A:
Use Object.values to get each inner object, then iterate over each of the entries and assign the new rounded number to the appropriate key of the inner object:
const input = {1: {x:10.76, y:50.44}, 2:{x:5.887, y:23.433} };
Object.values(input).forEach((inner) => {
Object.entries(inner).forEach(([key, val]) => {
inner[key] = Math.round(val);
});
});
console.log(input);
| {
"pile_set_name": "StackExchange"
} |
Q:
About Node serving dynamic pages
I am doing a tech test for a job (Web Development) and in the test I need to get data from an API and there is this conditions for the server:
Focus on client-side (AngularJS)
nodeJS
The server must not serve dynamic pages
My question is: Should I call the API directly using Angular? Or I can get the data from API using the node server?
What does "The server must not serve dynamic pages" mean?
A:
Since this is a tech test, I don't think it's a good idea to answer your first question. The assessors are likely very curious about your answer. Good luck!
As for, "The server must not serve dynamic pages", this just means you can only server static HTML from the web server. That is, you can't merge data into your HTML on the server side. No template engines. If I browse to a URL with a view, that view should always return the same HTML.
The server can also serve raw data
The trick is, you can change HTML in the browser based on the data. All dynamic behavior happens in the browser.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why dismissing view controller is not clearing presented controller from memory?
I have 2 controllers. Each of them have only one button on screen. For first controller button is presenting modally second controller, and for second controller button is dismissing presented controller.
Code of first one is simple as door:
class ViewController: UIViewController {
@IBAction func present(sender: AnyObject) {
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
if let controller = storyboard.instantiateViewControllerWithIdentifier("web") as? UIViewController {
controller.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
self.presentViewController(controller, animated: true, completion: nil)
}
}
}
Second controller code contain some extra code for detecting that after dismissing controller still exist.
static var index: Int = 0
var index: Int
required init(coder aDecoder: NSCoder) {
self.index = WebViewController.index++
super.init(coder: aDecoder)
let timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "action", userInfo: nil, repeats: true)
}
func action() {
NSLog("Class \(self.dynamicType) index is \(self.index)")
}
And all code of second controller looks like:
class WebViewController: UIViewController {
static var index: Int = 0
var index: Int
required init(coder aDecoder: NSCoder) {
self.index = WebViewController.index++
super.init(coder: aDecoder)
let timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "action", userInfo: nil, repeats: true)
}
func action() {
NSLog("Class \(self.view) index is \(self.index)")
}
@IBAction func dismissSelf() {
if let presentingController = self.presentingViewController {
presentingController.dismissViewControllerAnimated(true, completion: nil)
}
}
}
So when you will run this and press button on first controller screen for first time, then each 5 seconds you will see in console something like:
Class Proj.WebViewController index is 0
But if you will dismiss controller and present is again, then you will see both:
Class Proj.WebViewController index is 0
Class Proj.WebViewController index is 1
As I understand dismissing is not removing from memory presented controller even if nobody is catching him from my side.
Do somebody know what is it and how can i solve it?
Also you can download sample project
A:
the timer is catching your view controller
you should keep a weak reference to the timer, and add timer.invalidate() in dismissSelf
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/index.html#//apple_ref/occ/instm/NSTimer/invalidate
| {
"pile_set_name": "StackExchange"
} |
Q:
Compression on tape set..but at 2.27TB..end of space
I have a LTO6 tape inserted
tapeinfo -f /dev/st0
Product Type: Tape Drive
Vendor ID: 'QUANTUM '
Product ID: 'ULTRIUM 6 '
Revision: '4142'
Attached Changer API: No
SerialNumber: 'HU1322VW9U'
MinBlock: 1
MaxBlock: 16777215
SCSI ID: 0
SCSI LUN: 0
Ready: yes
BufferedMode: yes
Medium Type: Not Loaded
Density Code: 0x5a
BlockSize: 0
DataCompEnabled: yes
DataCompCapable: yes
DataDeCompEnabled: yes
CompType: 0x1
DeCompType: 0x1
BOP: yes
Block Position: 0
ActivePartition: 0
EarlyWarningSize: 0
NumPartitions: 0
MaxPartitions: 3
But when backup reach the 2.27TB(tape compressed is 6TB)
exit with error as tape is not compressed
2,27TiB 8:39:36 [75,6MiB/s] [ <=> ]
pv: write failed: Spazio esaurito sul device
error writing output file
I use tar for backup on slackware 14.2
tar cMpf - -X /etc/file.exclude /| openssl enc -e -aes256 -salt -pass file:filepass |(pv -p --timer --rate --bytes > /dev/st0)
A:
In your case it is the file level encryption that is preventing compression.
Encryption tries to make the data stream look as much as random "noise" as possible. Compression tries to increase the data "density" which has a similar effect of limiting further compression.
A:
Compression assumes it can work. tar files generally can not be compressed (they already are), so yes, you may end up not getting the "average compression ratio". Pure text files may compress a lot more. Compression targets are estimates.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I find who pushed a tag(s) to BitBucket
We deleted some unwanted tags from our bitbucket repository and (so we thought) all our local repositories, but obviously we have missed one repo somewhere as they keep getting re-pushed.
How can I find out who is pushing them?
A:
You can't find that easily (maybe BitBucket support has some log), but, as a workaround, you could add a post-receive hook (like a POST one) in order for another git client to be notified of any push.
That git client could check if tags were pushed, and, if those tags are unwanted, push back their deletion.
| {
"pile_set_name": "StackExchange"
} |
Q:
Resources in drawable directory not work properly
Context
This problem happened after I migrated an android application from App to AppCompact using refactor option in Android Studio 3.3 (It had been using nonsupport library version before), this process including manually changed deprecated APIs and so on.
I also updated compileSdkVersion from 27 to 28 and support library version from 27.1.1 to 28.0.0.
Everything work totally fine before I migrated and update compileSdkVersion and support library version.
Problem
After I migrated, I'm able to run in on my phone. However, I noticed that the Buttons that have been styled don't look like the way they should be.
From
To
This is one of the styles that I applied to button.
styles.xml
<style name="GraderButton" parent="@android:style/Widget.Button">
<item name="android:textColor">@color/text</item>
<item name="background">@drawable/button_background</item>
<item name="android:padding">13dip</item>
<item name="fontPath">fonts/THSarabunNew Bold.ttf</item>
<item name="android:textSize">20sp</item>
</style>
And this is one of the button that the above style was applied to.
<Button
android:id="@+id/buttonScan"
style="@style/GraderButton"
android:layout_width="186dp"
android:layout_height="53dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_weight="1"
android:text="@string/action_scan"
app:layout_constraintBottom_toTopOf="@+id/progressStatus"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="@+id/guidelineMiddle"
app:layout_constraintVertical_bias="0.39999998" />
Apparently, from some test I did, shape resources that are applied to background is not recognized or not work properly. From that I investigated.
References to those resources in drawable directory are perfectly working, no red text error, autocomplete working for every resource in the drawable directory.
However, when I hold cursor above those resources name, it said Empty StateList for shape is wrapped in selector
for other resources that aren't wrapped in selector, it just shows the full path to a resource file in red text. Everything work with style except shape that is applied to the button's background
Everything in style other than the things that use resources from drawable works perfectly. (textSize, padding and etc.)
Additional information
There is only one drawable directory in this project, there isn't any drawable-xx.
Before I migrated the application still have android support library but I think it hadn't been used. android.app.Activity, android.app.Fragment, android.widget.ImageView had been used.
A:
Actually here in GraderButton style there is
item name="background"
which is not attribute of Button (Widget)
So, here we have to set background of button using:-
item name="android:background"
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert any base to binary
Is there a algorithm or formula that can convert any base n, say 2 to 36, to binary? I've looked around the web and can't quite find what I'm looking for.
A:
Something to get you started.
unsigned strtou(const char *s, unsigned base) {
unsigned y = 0;
while (*s) {
unsigned digit;
if (isdigit(*s)) digit = ch - '0';
else if (isupper(*s)) digit = ch - 'A' + 10;
else if (islower(*s)) digit = ch - 'a' + 10;
else Handle_IllegalDigit();
if (digit >= base) Handle_IllegalDigit();
y = y*base + digit;
s++;
}
return y;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Information/File Manager
I'm looking for a file manager application which helps to organize a large amount of movies, pictures, music, text documents, databases, audio-books and ebooks. Right now I only use the Finder which doesn't work well, because I really need a function to put single files into multiple categories. Simply using the file system for this creates a confusing nesting of files.
A:
Depending on the number of categories you require to handle, you could always use a combination of the finder with the built in label functionality, thus a movie can be held in one area (movies directory, for example), but "tagged" as something else. Using smart directories and saved searches you can view your files by a combination of the attributes (location, label, media type) to create custom views. All without purchasing software. Cheap and cheerful, but may be suitable to your needs.
A:
Maybe use a file manager that supports Open Meta.
Or use symbolic links for organizing all your media files.
Or even use hardlinked files if you dare.
| {
"pile_set_name": "StackExchange"
} |
Q:
Validate date textbox
I'm using the following code to check if a valid date has been typed into a textbox:
public bool ValidateDate(Control ctrl)
{
if (!string.IsNullOrEmpty(ctrl.Text))
{
DateTime value;
if (!DateTime.TryParse(ctrl.Text, out value))
{
return false;
}
}
return true;
}
private void txtStartDate_Validating(object sender, CancelEventArgs e)
{
if (Utils.ValidateDate(txtStartDate))
{
errorProvider.SetError(txtStartDate, "");
}
else
{
errorProvider.SetError(txtStartDate, "* Invalid Date");
e.Cancel = true;
}
}
This works fine for dates that are entered m/d/yy, m/d/yyyy, mm/dd/yy, mm/dd/yyyy. If a user enters in a date such as "11/17" this will evaluate to a valid date, but, unfortunately, I only want dates that have all three date parts.
Is there an easy way to do this? I was thinking something a long the lines of checking if there are 2 "/" in the textbox, but I'm sure there is a cleaner way of achieving the desired result.
EDIT: Thanks for all the suggestions everyone! I ended up using the following code which accepts M/d/yyyy and M/d/yy ~
public bool ValidateDate(Control ctrl)
{
if (!string.IsNullOrEmpty(ctrl.Text))
{
string[] formats = {"M/d/yyyy", "M/d/yy"};
DateTime value;
if (!DateTime.TryParseExact(ctrl.Text, formats, new CultureInfo("en-US"), DateTimeStyles.None, out value))
{
return false;
}
}
return true;
}
A:
The DateTime.TryParseExact(..) function does allow you to parse a date using a specific date format (for example, "mm/dd/yyyy"). However, if you want to be flexible on the number of digits in the year, then a regex might be a better choice.
A:
You could try using regular expressions:
Regex dateRegExp = new Regex("^(((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00|[048])))$");
Match m = dateRegExp.Match(dateString);
if (m.Success) {
//Valid Date'
}
else
{
//No soup for you, 1 year'
}
(I "borrowed" the regexp from here: RegExpLib)
| {
"pile_set_name": "StackExchange"
} |
Q:
Are the points moving around a sphere in this manner always equidistant?
I recently encountered this gif:
Pretend that there are visible circles constructed along the paths of the smaller black and white "discs", tracing how their individual centers move as they revolve around the center of the whole design. These circles together form an imaginary sphere inside the design.
Assuming that the exact centers of each smaller "disc" are points moving along the sphere, and that they move in perfect circles at the same rate, how does the distance between the points change over a single revolution?
Are they equally distant from each other at all times, or is there a period in which they grow closer, which appears to happen when both "discs" enter the holes of the opposite color?
A:
They are not, as the other answers point out. The simplest way (I think) to see it is the following:
The discs move on circles. We can think of the circles as the equator and a meridian of a sphere. Call the white-disc-circle the equator.
At the moment the discs cross the holes, they are at opposite points of the sphere, and their distance is thus maximal.
When the black disc is at its highest point ("north pole"), the white one is still on the equator. Hence, they are not at opposite points of the sphere, and their distance is clearly less than the maximum value. This is actually the point of closest approach.
The (spatial) distance oscillates between twice the radius ($2 r$) and $\sqrt{2} \,r$.
A:
The two points are revolving on circles in the $xy$ and $yz$ planes, in a synchronized way, on the trajectories
$$x=\sin t,y=\cos t,z=0$$ and
$$x=0,y=-\cos t,z=\sin t.$$
The phases are such that the points are on opposite locations on the $y$ axis at $t=0$.
The distance is thus
$$\sqrt{\sin^2t+4\cos^2t+\sin^2t}=\sqrt{2(1+\cos^2t)}.$$
It is maximum on every half-turn (from the position at $t=0$), forming a straight line with the center, and minimum every quarter turn later, forming a right angle.
The ratio of the long distance over the short one is $\sqrt2$.
A:
Let's say that the sphere has radius 1 centered at the origin in $\Bbb R^3$ and the disks are moving with speed 1. And let's also say that in the picture the $z$-axis points upward, and the $y$ axis points normal to the plane of motion of the black thing. Let's also use the convention that at time zero the black disk has center at $(0,0,1)$ and the white one at $(0,1,0)$ Then You can literally parametrize the two curves which describe the center of the disks in a simple way:
$\gamma_{black}(t) = (\sin t, 0, \cos t)$
$\gamma_{white}(t) = (-\sin t, \cos t, 0)$
So if you compute distances (by subtracting and taking the norm squared), it is clear that they are not always equidistant.
So why does it seem like they are always equidistant in the picture?
Well, if you take a good look, the motion of the two disks is not along an exact sphere but more like some kind of ellipsoid.
So instead of using the spherical model $x^2+y^2+z^2=1$, try the ellipsoidal model $x^2+y^2/2+z^2/2=1$. In other words, let's consider the image of this rigid motion under the map $(x,y,z) \mapsto (x, \sqrt 2 y, \sqrt 2 z)$. So the new parametrizations will be
$\gamma_{black}(t) = (\sin t, 0, \sqrt 2 \cos t)$
$\gamma_{white}(t) = (-\sin t, \sqrt 2 \cos t, 0)$
And in this model we see that they are always equidistant! (Well those are my two cents at least. Might be total BS. Really it depends on how you want to interpret this two dimensional projection of a three dimensional motion - for all we know the planes of motion may not even be orthogonal, which would make the formulas more complicated).
| {
"pile_set_name": "StackExchange"
} |
Q:
Beginner Proof by Induction: Is this correct?
I am asked to prove $\frac{1}{1.4} + \frac{1}{4.7} + ... + \frac{1}{(3n-2)(3n+1)} = \frac{n}{3n+1}, n\geq 1$ by induction.
Can someone verify that I did this correctly. I am unsure about my Inductive Step.
Proof by induction
Inductive Hypothesis Let $P(k) = \sum\limits_{i=1}^{k} \frac{1}{(3i-2)(3i+1)} = \frac{k}{3k+1}$
Base case $n = 1$
\begin{align*}
P(1) &= \sum\limits_{i=1}^{1} \frac{1}{(3(1)-2)(3(1)+1)} = \frac{1}{3(1)+1} \\
&= \frac{1}{(3-2)(3+1)} = \frac{1}{3+1} \\
&= \frac{1}{(1)(4)} = \frac{1}{4} \\
&= \frac{1}{4} = \frac{1}{4} \checkmark
\end{align*}
Inductive Step
For $k \geq 1$, show that $P(k) \to P(k+1)$ is true.
Assume $P(k)$ is true, assume $\sum\limits_{i=1}^{k} \frac{1}{(3i-2)(3i+1)} = \frac{k}{3k+1}$ is true.
Prove $P(k+1)$ is true, examine $\sum\limits_{i=1}^{k+1} \frac{1}{(3i-2)(3i+1)} = \frac{k+1}{3(k+1)+1}$.
\begin{align*}
\sum\limits_{i=1}^{k+1} \frac{1}{(3i-2)(3i+1)} &= \frac{k+1}{3(k+1)+1} \\
\sum\limits_{i=1}^{k+1} \frac{1}{(3i-2)(3i+1)} &= \frac{k}{3(k+1)} \\
\sum\limits_{i=1}^{k+1} \frac{1}{(3i-2)(3i+1)} &= \sum\limits_{i=1}^{k} \frac{1}{(3i-2)(3i+1)}
\end{align*}
Can someone check that this is the correct way to prove the theorem by induction?
A:
I don't understand what you're doing in the last couple of lines for $P(k + 1)$, for example between the third & second last, you change the RHS value but leave the LHS the same.
Instead, I would normally go from one side of the equation, expand or otherwise manipulate it as need be so can use the assumption that $P(k)$ is true, and then do various simplifications to show how it's the same as the other side. In general, I've found it's easiest to start with the summation. As such, here's how I would handle the inductive step.
$$\begin{equation}\begin{aligned}
\sum\limits_{i=1}^{k+1} \frac{1}{(3i-2)(3i+1)} & = \sum\limits_{i=1}^{k} \frac{1}{(3i-2)(3i+1)} + \frac{1}{(3(k+1)-2)(3(k+1)+1)} \\
& = \frac{k}{3k+1} + \frac{1}{(3k+1)(3k+4)} \\
& = \frac{k(3k+4) + 1}{(3k+1)(3k+4)} \\
& = \frac{3k^2 + 4k + 1}{(3k+1)(3k+4)} \\
& = \frac{(3k + 1)(k + 1}{(3k+1)(3k+4)} \\
& = \frac{k + 1}{3(k+1) + 1} \\
& = P(k+1)
\end{aligned}\end{equation}\tag{1}\label{eq1A}$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Access current instance of view controller from app delegate in swift?
my view controller has many initialized methods and variables. When my app enters background, I need to access a particular value in view controller from app delegate.
I have tried to do this in app delegate:
vc = ViewController()
...but that makes a new instance, and values are essentially set as new.
A:
You have two options, the second one is better by design.
First option: (what you want)
I don't know the structure of your view controllers, so let me assume you have a root view controller, you could get it from AppDelegate via:
rootVC = self.window?.rootViewController
And if you want to get the presented view controller from the root view controller (like many apps, the presented view controller is a tab bar controller):
guard let tabBarController = rootVC.presentedViewController as? TabBarController else {
return
}
Once you get your tab bar controller, you can find the view controller in the array of view controllers:
tabBarController.viewControllers
Essentially, what I'm trying to say is you have to jump through your view controllers starting from the root to get to the controller you want, then grab the variable from there. This is very error prone, and generally not recommended.
Second option (better practice):
Have your view controller register as an observer for the UIApplicationWillResignActiveNotification notification. This will allow you to do whatever you want from the view controller when your app is about to enter background.
| {
"pile_set_name": "StackExchange"
} |
Q:
How good of a King was Jaehaerys I?
We have all read about the prosperous and long reign of Jaehaerys I, The Conciliator, and Good Queen Alyssane. He is regarded as the best Targaryen monarch.
However, the question is how much of his success was due to his own skill and how much was due to people like Septon Barth, Grand Maester Benifer, The Lord Velaryon etc.
Would his reign be as good without people like them on his small council?
A:
It seems from the perspective of the Maesters that Jaehaerys started out a great guy and this was furthered by his wife and council.
Though young to the throne, Jaehaerys revealed himself from an early age to be a true king. He was a fine warrior, skilled with lance and bow, and a gifted horseman. He was a dragonrider as well, riding upon Vermithor—a great beast of bronze and tan who was the largest of the living dragons after Balerion and Vhagar. Decisive in thought and deed, Jaehaerys was wise beyond his years, always seeking the most peaceable ends.
His queen, Alysanne, was also well loved throughout the realm, being both beautiful and high-spirited, as well as charming and keenly intelligent. Some said that she ruled the realm as much as the king did, and there was some truth to that. It was at her behest that King Jaehaerys at last forbade the right of the First Night, despite the many lords who jealously guarded it.
With Barth's aid and advice, King Jaehaerys did more to reform the realm than any other king who lived before or after. Where his grandsire, King Aegon, had left the laws of the Seven Kingdoms to the vagaries of local tradition and custom, Jaehaerys created the first unified code, so that from the North to the Dornish Marches, the realm shared a single rule of law. Great works to improve King's Landing were also implemented—drains and sewers and wells, especially, for Barth believed that fresh water and the flushing away of offal and waste were important to a city's health. Furthermore, the Conciliator began the construction of the great network of roads that would one day join King's Landing to the Reach, the stormlands, the westerlands, the riverlands, and even the North—understanding that to knit together the realm it must be easier to travel among its regions. The kingsroad was the greatest of these roads, reaching hundreds of leagues to Castle Black and the Wall.
So it was quite natural for Jaehaerys to go down in history as one of the greatest if not the greatest of the Targaryen kings.
King Jaehaerys, the First of His Name—known as the Conciliator, and the Old King (being the only Targaryen ruler who lived to such an advanced age)—died peacefully in his bed in 103 AC, while Lady Alicent read to him from his friend Barth's Unnatural History. He was nine-and-sixty at his death, and had ruled wisely and well for five-and-fifty years. Westeros mourned, and it was claimed that even in Dorne men wept and women tore their garments in lament for a king who had been so just and good. His ashes were interred with that of his beloved, the Good Queen Alysanne, beneath the Red Keep. And the realm never saw their like again.
All above quotes from The World of Ice and Fire - The Targaryen Kings: Jaehaerys I
So how much of this can be credited to Jaehaerys himself or to his council? It was all teamwork among those who loved each other and were friends. However, in the end the king has the final say and his own tendencies (good or bad) would ultimately shine through.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sails.JS - Get the count of the number of objects/rows in the database
In Sails.js, a lot of work is done for you by generating the models and controllers. The controllers allow for access to the data through API's. It allows for easy pagination by passing the start/skip/offset and take/limit. But in order for me to determine the maximum page of a collection I need to know how many items are in a collection.
I have tried to extend the blueprint in the generator to expose a new API method count and create the count action. According to the Waterline documentation, count is an action that can be called on the model. When I call User.count(), I get this:
{ _context:
{ identity: 'user',
adapter:
{ syncable: false,
defaults: [Object],
registerCollection: [Function],
create: [Function],
find: [Function],
update: [Function],
destroy: [Function],
count: [Function],
identity: 'odata',
globalId: 'odata',
config: [Object] },
attributes: {},
_cast: { _types: [Object] },
_schema: { context: [Circular], schema: [Object], hasSchema: true },
_validator: { validations: {} },
_callbacks:
{ beforeValidation: [Object],
afterValidation: [Object],
beforeUpdate: [Object],
afterUpdate: [Object],
beforeCreate: [Object],
afterCreate: [Object],
beforeDestroy: [Object],
afterDestroy: [Object] },
_instanceMethods: {},
autoPK: true,
autoCreatedAt: true,
autoUpdatedAt: true,
hasSchema: true,
migrate: 'alter',
_model: { [Function] extend: [Function], inject: [Function], __super__: {} },
_transformer: { _transformations: {} },
_tableName: 'user',
_adapterDefs: [ [Object] ],
_adapter:
{ adapter: [Object],
adapterDefs: [Object],
query: [Circular],
collection: 'user' },
syncable: [Function],
defaults: [Function],
registerCollection: [Function],
config: [Function],
findOneById: [Function: dynamicMethod],
findOneByIdIn: [Function: dynamicMethod],
findOneByIdLike: [Function: dynamicMethod],
findById: [Function: dynamicMethod],
findByIdIn: [Function: dynamicMethod],
findByIdLike: [Function: dynamicMethod],
countById: [Function: dynamicMethod],
countByIdIn: [Function: dynamicMethod],
countByIdLike: [Function: dynamicMethod],
idStartsWith: [Function: dynamicMethod],
idContains: [Function: dynamicMethod],
idEndsWith: [Function: dynamicMethod],
findOneByCreatedAt: [Function: dynamicMethod],
findOneByCreatedAtIn: [Function: dynamicMethod],
findOneByCreatedAtLike: [Function: dynamicMethod],
findByCreatedAt: [Function: dynamicMethod],
findByCreatedAtIn: [Function: dynamicMethod],
findByCreatedAtLike: [Function: dynamicMethod],
countByCreatedAt: [Function: dynamicMethod],
countByCreatedAtIn: [Function: dynamicMethod],
countByCreatedAtLike: [Function: dynamicMethod],
createdAtStartsWith: [Function: dynamicMethod],
createdAtContains: [Function: dynamicMethod],
createdAtEndsWith: [Function: dynamicMethod],
findOneByUpdatedAt: [Function: dynamicMethod],
findOneByUpdatedAtIn: [Function: dynamicMethod],
findOneByUpdatedAtLike: [Function: dynamicMethod],
findByUpdatedAt: [Function: dynamicMethod],
findByUpdatedAtIn: [Function: dynamicMethod],
findByUpdatedAtLike: [Function: dynamicMethod],
countByUpdatedAt: [Function: dynamicMethod],
countByUpdatedAtIn: [Function: dynamicMethod],
countByUpdatedAtLike: [Function: dynamicMethod],
updatedAtStartsWith: [Function: dynamicMethod],
updatedAtContains: [Function: dynamicMethod],
updatedAtEndsWith: [Function: dynamicMethod] },
_method: [Function],
_criteria: {},
_values: null }
Note: I am using a custom adapter, but I have created a count method for the adapter.
A:
To get the count of the number of objects in user collection:
User.count(function (err, num) {
if(err) {
return console.log(err);
}
console.log(num);
});
To wrap User.count in another method:
yourMethod = function (callback) {
User.count(callback);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
C# Efficient way to iterate over excel worksheet
I have the following code:
string result = "";
for(int i=2; i<=excelRange.Rows.Count; i++)
{
result += excelRange.Cells[i, 2].Value2;
}
For an excel file with a couple hundred entries this takes 5 seconds. Is there a more efficient way, perhaps? I only want the values from B2 to Bn.
A:
Yes, there is a more efficient way.
Create a range that exactly matches the cells that you really need.
Get the Value2 property of this range. The result will be an array type.
Iterate through the array
The problem with your approach is the large number of inter-process requests between your application and Excel. Your approach requires two or three requests per cell. The proposed approach is much faster because it requires a few requests up-front but not additional requests per cell.
Note that this works up to about 4000 cells. If you need to process more cells, you will need to split it into several ranges, each one containing less than 4000 cells.
Update
Assuming Excel is already running, it would look something like this (the correct number of rows in the B column is automatically selected):
var excelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
var range = (Excel.Range)workSheet.Range[workSheet.Range["B2"],
workSheet.Range["B2"].End[Excel.XlDirection.xlDown]];
var cellData = (Object[,])range.Value2;
string result = "";
foreach (var cell in cellData) {
result += cell.ToString();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is the a quicker way to determine the largest string length in an array?
This is a segment of code that has been troubling me, as I feel certain some simple function exists that will make looping through the array values redundant.
Instead I have used an array, a loop and a boolean to tell me whether the cells are empty (or test their length) and an If statement to run the last part of the code.
I thought perhaps Max would work but I believe that is only for integers. (See the debug.print part
Dim arrArchLoc As Variant
Dim boolArchLoc As Boolean
Dim rowCounter As Long
boolArchLocEmpty = False
arrArchLoc = ActiveSheet.Range(Cells(2, colArchiveLocation), Cells(lastRow, colArchiveLocation))
For rowCounter = LBound(arrArchLoc) To UBound(arrArchLoc)
If Cells(rowCounter, colArchiveLocation) <> "" Then boolArchLocEmpty = True
Next rowCounter
'Debug.Print workshetfunction.Max(arrArchLoc)
If boolArchLocEmpty = True Then
ActiveSheet.Cells(1, colArchiveLocation).Value = "Arch Loc"
Columns(colArchiveLocation).ColumnWidth = 6
End If
Does such a function or simple method exist?
EDIT:
Whilst that specialcells(xlCellTypeBlanks) solution looks pretty good, I would still rather get the string length solution.
My apologies, the code initially had something like...
If len(Cells(rowCounter, colArchiveLocation)) > 6 then...
but I have since removed it after having to get something in place that would work.
Is there something I could do with LEN(MAX)? I experimented with it but didn't get very far.
A:
Given the range is A2:A100, the result you want would be expressed on the sheet as an array formula:
={MAX(LEN(A2:A100))}
In order to execute that from VBA as an array formula and not a regular formula, you need to use Evaluate:
max_len = Evaluate("=MAX(LEN(A2:A100))")
Or, in terms of your code,
Dim arrArchLoc As Range
With ActiveSheet
Set arrArchLoc = .Range(.Cells(2, colArchiveLocation), .Cells(lastRow, colArchiveLocation))
End With
Dim max_len As Long
max_len = Application.Evaluate("=MAX(LEN(" & arrArchLoc.Address(external:=True) & "))")
However it is much better to calculate it explicitly with a loop, like you were already doing.
| {
"pile_set_name": "StackExchange"
} |
Q:
Algorithm to fit shapes to 2D grid?
Let's say you have an n-by-m grid. Some squares are occupied, some are not.
You want to know where in the grid you can fit arbitrary shapes such as to not hit an occupied square. The shapes would variable, and could be x-by-y rectangles, trapezoidal-ish shapes, etc.
Are there algorithmic approaches to this?
A:
This is a form of the Packing Problem.
Here are your options:
Brute force it as Gajet has mentioned. This can be aided by doing a pre-evaluation of existing space in your world grid, so as to find maximal axis-aligned bounding boxes. This article should give you some insight into how one developer applied solutions to the Packing Problem, in regards to packing arbitrarily-sized sprites into a spritesheet.
Use a more physically-based approach to the Packing Problem; I call this "Place-and-Grow" for lack of having seen a better term elsewhere. Select a single pixel/cell of your bitmap/source grid to place -- I would start with the centremost pixel. Randomly pick a position in your bacgkround bitmap / destination grid, to place it on. Keep randomising till you find an open space (this process can be optimised in other ways). If it is now overlapping a solid pixel eg. on the left side, push it out in the opposite direction instead (same applies vice versa and for top/bottom). If you now find it in an empty space once more, you're good to go to the next step. "Grow" the pixel in in all 8 directions around itself, in terms of the source grid / bitmap. Then go back and repeat the shifting step to ensure it's not overlapping anything. Rinse, repeat. Eventually you will get to a point where either your image is completely drawn in to background space, or you cannot expand it anymore in any direction, and will have to try again. Basically this approach is described as "physical" because you are pushing away from any boundaries you meet -- until such time as the algorithm is done or it falls out because there is no space on any side to push out toward.
The second "continuous" approach is more organic, and it may in some ways be easier to handle than the large amounts of logic you might have to write for "discrete" Packing Problem solutions (as in the article above). BUT remember that for each subsequent AABB that you "grow" this way to it's maximal size, you will be doing a haphazard, randomised placement -- which may eventually end up being much slower than brute-forcing, as your grid fills up. It will depend on the sparseness of your grid, i.e. the average proportion of filled vs empty cells. If I wanted to do this efficiently, as you seem to, I think I would opt for the first approach. For procedural world generation algorithms, I would find the second approach to be more useful as it would produce more random / less ordered results.
| {
"pile_set_name": "StackExchange"
} |
Q:
Windows VMWare + VPN + Ubuntu
I have Ubuntu host that has a VMWare running Windows XP.
If I connect to a VPN from my Windows XP, then will that connection be available to my host Ubuntu as well?
Regards
Balaji D Loganathan
A:
No your connection on the virtual Windows XP machine will not be directly available on the phyiscal Ubuntu installation.
The host system (phyisical machine which is running the virtual machines) does not have access to the network connections of a VM.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to draw a cylinder with an irregular cross section, which varies along the cylinder length?
I want to draw a cylinder which has a different and irregular cross section along the cylinder length, with precise measurements
?
At each angle the cylinder has a specific radius, therefore the cross-section shape is nor regular. (like the figure)
A:
If you need to work in micrometers, it is better to select None as the Length unit and just keep in mind that the scene unit is micrometer, because Blender starts malfunctioning if you try to scale units to that size even if you do that with unit scale value:
It is easier to create the cylinder then it may seem. We could use vertex slide functionality(shift+v) to quickly and easily specify the lengths of the radii. Vertex slide works proportionally to the edge it slides on and we want to enter units instead of proportions during the slide operation, so let's adjust the proportion to match the units by making a circle that would have a radius of 1 unit. Once you have the circle, enter edit mode (tab) select the edge loop and extrude it(e), scale it in a bit (s), extrude again and merge the loop to center with alt+m. Now you can take the vertices one by one. Slide every vertex (shiftvv) to the center, slide it again, hit c to clamp it to the path so it can go further than the edge loop marking 1 unit, and enter the units before confirming the operation with a mouse click. Repeat this for all vertices around, once you are done, you can delete the 1 unit mark edge loop, select everything and extrude:
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the limit of the Death Eraser?
The Death Note Wikia states that...
The Death Eraser can revive the people that have been killed by the note
The Death Eraser is an artefact
In the wikia is also states if you wrote "dies from a tragic accident or something",would the person's wounds or destroyed body parts be healed?
Which lead me to ask what is the limits of the Death Eraser and if you wrote "commits suicide by gun" and you used the Death Eraser to bring them back, would the wounds heal even though they come back to life?
A:
First of all, The Death Eraser is a plot device exclusive to the manga pilot.
Death Note includes a rule stating that if the owner of the notebook uses the Death Eraser to erase names in the Death Note, the victims come back to life if they have not been cremated.
With this said we know atleast a body is needed for this
Taro Kagami is offered the Death Eraser by Ryuk, and is told that he can erase the names in the Death Note and the victims will miraculously come back to life
Using the description Miraculously make's it quiet easy for them to get away with just about anything. They are miraculously healed, or the miraculously live on as just a severed head.
Simply said, It all comes down to the fact its a miracle.
A:
I doubt the "Death Eraser" exist (I actually haven't found references in any plot of the official manga/anime), since the Shikigami, who are the original owners of the notes, gets the remaining human life span and adds it to themself. Something that could revive humans would alter fundamentally the propose of the Death Note, and such thing was not devisable by the mangaka.
I remember you that wikia is a fan-made site and references and claims are not official nor accurate.
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring RestTemplate and generic types ParameterizedTypeReference collections like List
An Abstract controller class requires List of objects from REST. While using Spring RestTemplate its not mapping it to required class instead it returns Linked HashMAp
public List<T> restFindAll() {
RestTemplate restTemplate = RestClient.build().restTemplate();
ParameterizedTypeReference<List<T>> parameterizedTypeReference = new ParameterizedTypeReference<List<T>>(){};
String uri= BASE_URI +"/"+ getPath();
ResponseEntity<List<T>> exchange = restTemplate.exchange(uri, HttpMethod.GET, null,parameterizedTypeReference);
List<T> entities = exchange.getBody();
// here entities are List<LinkedHashMap>
return entities;
}
If I use,
ParameterizedTypeReference<List<AttributeInfo>> parameterizedTypeReference =
new ParameterizedTypeReference<List<AttributeInfo>>(){};
ResponseEntity<List<AttributeInfo>> exchange =
restTemplate.exchange(uri, HttpMethod.GET, null,parameterizedTypeReference);
It works fine. But can not put in all subclasses, any other solution.
A:
I worked around this using the following generic method:
public <T> List<T> exchangeAsList(String uri, ParameterizedTypeReference<List<T>> responseType) {
return restTemplate.exchange(uri, HttpMethod.GET, null, responseType).getBody();
}
Then I could call:
List<MyDto> dtoList = this.exchangeAsList("http://my/url", new ParameterizedTypeReference<List<MyDto>>() {});
This did burden my callers with having to specify the ParameterizedTypeReference when calling, but meant that I did not have to keep a static mapping of types like in vels4j's answer
A:
Using ParameterizedTypeReference for a List<Domain>, when Domain is an explicit class, that ParameterizedTypeReference works well, like this:
@Override
public List<Person> listAll() throws Exception {
ResponseEntity<List<E>> response = restTemplate.exchange("http://example.com/person/", HttpMethod.GET, null,
new ParameterizedTypeReference<List<Person>>() {});
return response.getBody();
}
However, if a method listAll is used in generic flavor, that list should be parameterized itself. The best way I found for this is:
public abstract class WebServiceImpl<E> implements BaseService<E> {
private Class<E> entityClass;
@SuppressWarnings("unchecked")
public WebServiceImpl() {
this.entityClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
@Override
public List<E> listAll() throws Exception {
ResponseEntity<List<E>> response = restTemplate.exchange("http://example.com/person/", HttpMethod.GET, null,
new ParameterizedTypeReference<List<E>>() {
@Override
public Type getType() {
Type type = super.getType();
if (type instanceof ParameterizedType) {
Type[] responseWrapperActualTypes = { entityClass };
ParameterizedType responseWrapperType = new ParameterizedTypeImpl(List.class,
responseWrapperActualTypes, null);
return responseWrapperType;
}
return type;
}
});
return response.getBody();
}
}
A:
Couldnt find a solution from Spring, hence I have done it with ParameterizedTypeReference in HashMap like
public final static HashMap<Class,ParameterizedTypeReference> paramTypeRefMap = new HashMap() ;
static {
paramTypeRefMap.put(AttributeDefinition.class, new ParameterizedTypeReference<List<AttributeDefinition>>(){} );
paramTypeRefMap.put(AttributeInfo.class, new ParameterizedTypeReference<List<AttributeInfo>>(){} );
}
and used it
ParameterizedTypeReference parameterizedTypeReference = paramTypeRefMap.get(requiredClass);
ResponseEntity<List> exchange = restTemplate.exchange(uri, HttpMethod.POST, entity, parameterizedTypeReference);
| {
"pile_set_name": "StackExchange"
} |
Q:
Solving a 4x4 Puzzle Grid
I'm attempting to create a program that will find the steps to solve a puzzle with the following rules:
Given any set of colors in a 4x4 grid, attempt to match to an ending pattern with the same number of colors.
Colors are not swapped, but rotated either horizontally or vertically, such that
{W, W, B, W}
can be rotated to
{W, W, W, B}
{B, W, W, W}
{W, B, W, W}
The entire puzzle can be solved in less than 16 steps.
I've already figured out how to store the data of the puzzle itself, but I'm struggling on how to proceed about finding a solution that can display steps. Since the depth is limited to 16 steps, I'm ok with trying to brute force this, but don't really have an idea of how to establish a pattern.
This is similar to solving a Rubik's cube, and I've already looked at the following resources:
stackoverflow.com/questions/34656587/solving-rubiks-cubes-for-dummies/34656726#34656726
stackoverflow.com/questions/5563671/solving-rubiks-cube-programmatically
amzi.com/articles/rubik.htm
chessandpoker.com/rubiks-cube-solution.html
and the 15 numbers problem
stackoverflow.com/questions/3621623/how-to-programatically-solve-the-15-moving-numbers-puzzle
To make this question as clear as possible: What is a good way to a) store/print the steps, and b) find the solution that takes the least steps?
A:
I guess I can't explain a tree without pictures.
Say you have this starting pattern:
[W, W, W, B]
[W, W, W, B]
[B, W, W, W]
[W, W, W, B]
This would be the top node of the tree. Level 0.
So now, we do all possible horizontal and vertical rotations. Horizontal to the right first.
[B, W, W, W]
[W, W, W, B]
[B, W, W, W]
[W, W, W, B]
[W, W, W, B]
[B, W, W, W]
[B, W, W, W]
[W, W, W, B]
[W, W, W, B]
[W, W, W, B]
[W, B, W, W]
[W, W, W, B]
[W, W, W, B]
[W, W, W, B]
[B, W, W, W]
[B, W, W, W]
Horizontal to the left.
[W, W, B, W]
[W, W, W, B]
[B, W, W, W]
[W, W, W, B]
[W, W, W, B]
[W, W, B, W]
[B, W, W, W]
[W, W, W, B]
[W, W, W, B]
[W, W, W, B]
[W, W, W, B]
[W, W, W, B]
[W, W, W, B]
[W, W, W, B]
[B, W, W, W]
[W, W, B, W]
Vertical up
[W, W, W, B]
[B, W, W, B]
[W, W, W, W]
[W, W, W, B]
[W, W, W, B]
[W, W, W, W]
[B, W, W, B]
[W, W, W, B]
Vertical down
[W, W, W, B]
[W, W, W, B]
[W, W, W, W]
[B, W, W, B]
[W, W, W, B]
[W, W, W, B]
[B, W, W, B]
[W, W, W, W]
Since the second and third columns are all W, we only have 2 patterns for vertical up and vertical down.
We have a total of 12 patterns at level 1.
We moved very methodically. There was no randomness in our moves. Horizontal to the right, horizontal to the left, vertical up, and vertical down.
Now, take each of the 12 patterns at level 1 and generate the 16 patterns. You don't have to save the patterns that match the patterns at level 0 and level 1.
The patterns generated and saved make up level 2.
Continue generating each level until you hit level 16 or you have a solution. Because you're removing duplicates from the tree levels, you won't hit the theoretical maximum of 16 to the 16th power nodes on level 16.
Finish the level in case there's more than one solution with a minimum number of moves.
| {
"pile_set_name": "StackExchange"
} |
Q:
convert awt to swing automatically
From what I know and have been reading, converting from awt to swing seems to be quite mechanical. With the exception of the different threading model, most of swing components generally map well with the awt ones.
Was looking for a tool to do this conversion automatically. Understandably, this may not be a 100% conversion, but at least the mechanical process should be fairly automated. Would any one know of a such a tool ?
A:
Why a script changing AWT to Swing component names will not be sufficient.
Swing components must be constructed & updated on the EDT. This restriction does not apply to AWT.
Pre 1.5(?) components needed to be added to Swing top level containers using getContentPane().add()
Scrolling is different between an AWT TextArea (built-in) & Swing JTextArea (wrapped in a JScrollPane)
Constructors may vary. E.G. no JTextArea(String,int,int,int)
In non TLCs. Override paint(Graphics) in AWT, paintComponent(Graphics) in Swing.
There is no direct equivalent of Canvas.
A CheckBox might be translated to a JCheckBox, but a CheckBox in a CheckBoxGroup should be converted to a JRadioButton in a ButtonGroup.
Advantages of Swing it will miss.
JFrame has a defaultCloseOperation(int), which can (often) replace the AWT WindowListener.
| {
"pile_set_name": "StackExchange"
} |
Q:
AES in GCM mode in Python
Does anyone know of a python library or wrapper around a c library that will easily provide Authenticated AES via GCM mode?
PyCrypto does not support it and it does not appear that PyOpenSSL supports direct access to the symmetric cipher portions of OpenSSL
A:
The PyCA cryptography library provides AES-GCM: https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/#cryptography.hazmat.primitives.ciphers.modes.GCM
A:
I have just finished looking for an EAX or GCM mode AES encryption algorithm in python. This was a particularly difficult search because I was unable to download the PyCrypto alpha version, which includes both of these, due to a dependency issue.
Eventually I turned to an offshoot of pycrypto that can be pip installed without issue, and has a stable release of GCM.
http://pycryptodome.readthedocs.org/en/latest/src/introduction.html
| {
"pile_set_name": "StackExchange"
} |
Q:
how to get next friday in sas
friday=intnx('week.5',today(),0)
Is this correct logic to get next Friday?
A:
In SAS 1 is Sunday, so you need to check for 6 instead.
data test;
next_friday=intnx('week.6',today(),1);
following_friday=intnx('week.6',today(),2);
format next_friday date9. following_friday date9. ;
put _all_;
run;
Output:
today is 1-MAY-2018
next_friday=04MAY2018 following_friday=11MAY2018
Note:
According to SAS documentation 0 should show the current week but it shows the previous week because we used week.6 in our case here but when using 1 instead the correct Friday is picked.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is a view of a collection?
I've been reading the term view a few times when using Guava collections and reading its documentation.
I've looked for an explanation of what a view is in this context and whether it's a term used outside of Guava. It's quite often used here. This type from Guava has view in its name.
My guess is that a view of a collection is another collection with the same data but structured differently; for instance when I add the entries from a java.util.HashSet to a java.util.LinkedHashSet the latter would be a view of the former. Is that correct?
Can somebody hook me up with a link to an accepted definition of view, if there is one?
Thanks.
A:
A view of another object doesn't contain its own data at all. All of its operations are implemented in terms of operations on the other object.
For example, the keySet() view of a Map might have an implementation that looks something like this:
class KeySet implements Set<K> {
private final Map<K, V> map;
public boolean contains(Object o) {
return map.containsKey(o);
}
...
}
In particular, whenever you modify the backing object of your view -- here, the Map backs the keySet() -- the view reflects the same changes. For example, if you call map.remove(key), then keySet.contains(key) will return false without you having to do anything else.
Alternately, Arrays.asList(array) provides a List view of that array.
String[] strings = {"a", "b", "c"};
List<String> list = Arrays.asList(strings);
System.out.println(list.get(0)); // "a"
strings[0] = "d";
System.out.println(list.get(0)); // "d"
list.set(0, "e");
System.out.println(strings[0]); // "e"
A view is just another way of looking at the data in the original backing object -- Arrays.asList lets you use the List API to access a normal array; Map.keySet() lets you access the keys of a Map as if it were a perfectly ordinary Set -- all without copying the data or creating another data structure.
Generally, the advantage of using a view instead of making a copy is the efficiency. For example, if you have an array and you need to get it to a method that takes a List, you're not creating a new ArrayList and a whole copy of the data -- the Arrays.asList view takes only constant extra memory, and just implements all the List methods by accessing the original array.
A:
A view in this context is a collection backed by another collection (or array) that itself uses a constant amount memory (i.e. the memory does not depend on the size of the backing collection). Operations applied to the view are delegated to the backing collection (or array). Of course it's possible to expand this definition beyond just collections but your question seems to pertain specifically to them.
For example, Arrays.asList() returns "a list view of the specified array". It does not copy the elements to a new list but rather creates a list that contains a reference to the array and operates based on that.
Another example is Collections.unmodifiableList() which returns "an unmodifiable view of the specified list". In other words, it returns a list containing a reference to the specified list to which all operations are delegated. In this case, the list returned does not permit you to modify it in any way, and so instead of delegating methods responsible for mutating the list, it throws an exception when such methods are called instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
CGImageRef and drawing layers
I have this code:
CGDataProviderRef provider = CGDataProviderCreateWithFilename([myFile UTF8String]);
CGImageRef img = CGImageCreateWithJPEGDataProvider(provider, NULL, true, kCGRenderingIntentDefault);
Later I load that CGImageRef in a UIImage this way:
UIImage *uiImage = [[UIImage alloc] initWithCGImage:destImage];
I'd like to draw a circle over that Image. The point is the circle moves so it has to be deleted and redraw. I guess the best way of accomplishing this is with layers so my question is: How can I add a layer to that code and draw a circle on it? How can I later reset the layer and redraw that circle?
Thank you!
A:
You'll want to use a UIImageView, and then add a separate layer to that view. If your layer [circle] moves, just set its position property to the new center; the view system will take care of re-compositing everything.
To get your circle to show up in the layer, you can either use a fixed image, subclass CALayer and override drawInContext:, or set the delegate and implement drawLayer:inContext:.
| {
"pile_set_name": "StackExchange"
} |
Q:
CodeIgniter: Select the same like parameter on JSON list
I'm trying to use tokeninput from jQuery Token input, but the data is from the API. I already got the data from API and made a JSON list (see below).
When a user inputs in my token input, it will select from the JSON list, like user/auto_unit?queryParam=q for example. It already gets the user input correctly, but it still returns all data, even those that do not match the user input.
What I want is when the user searches for "Sosiologi", the only values that would show are those string which have "sosiologi" in them.
Is it possible to get only the same values and how can I do that? Thanks in advance!
My JSON list:
// 20170401095401
// http://exp.uin-suka.ac.id/aspirasi/user/auto_unit?queryParam=Filsafat%20Agama
[
{
"id": "UA000001",
"name": "Filsafat Agama"
},
{
"id": "UA000002",
"name": "Perbandingan Agama"
},
{
"id": "UA000003",
"name": "Ilmu Al-Qur'an dan Tafsir"
},
{
"id": "UA000004",
"name": "Sosiologi Agama"
},
{
"id": "UA000005",
"name": "Matematika"
},
{
My JSON code to get the list
function auto_unit() {
$data['unit'] = $this->m_simpeg->getAllUnit();
foreach ($data['unit'] as $key ){
$row['id']= $key['UNIT_ID'];
$row['name']= $key['UNIT_NAMA'];
$row_set[] = $row;
}
echo json_encode($row_set);
}
Model to get API M_simpeg.php:
public function getAllUnit(){
return $this->s00_lib_api->post_api(
1001, 1, null,
URL_API_SIMPEG.'simpeg_mix/data_view'
);
}
A:
Check your server side code as it is not filtering the array.
Codeigniter sample code
<?php
function filter(){
$queryParam=$this->input->get('queryParam');
$res=$array.filter($queryParam);
return $res;
}
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it normal for an hwnd to have its high bit set?
I'm passing my HWND to a sub-process so it can send me messages back on its progress. Occasionally I never receive any messages from the sub-process.
While investigating, I've found that GetSafeHwnd() of which I'm passing to the subprocess seems to be returning values I don't expect.
For example:
0xffffffffa5400382
Based on that, I can probably deduce that I'm not properly converting that value to/from an int64/string properly. I can fix that. But what I find odd is that this hwnd just doesn't look right?
Are there scenarios where an HWND can have it's high bit set? Is this a normal window, or is there something special about the hwnd to end up like that?
I'm in C++, this is an CDialog based application window.
A:
The result you are seeing comes from sign extension of the handle value to a 64-bit integer. The actual handle value is 0xa5400382, because handle values are always in the 32-bit range, even if the process is 64-bit!
So you should cast the HWND to std::uint32_t instead and convert that to string (or the other way around).
Convert HWND to wstring:
HWND hwnd = GetSafeHwnd();
std::uint32_t handleValue = reinterpret_cast<std::uint32_t>( hwnd );
std::wstring handleValueStr = std::to_wstring( handleValue );
Convert wstring to HWND:
try
{
std::uint32_t handleValue = std::stoul( someString );
HWND handle = reinterpret_cast<HWND>( handleValue );
}
catch( std::exception& e )
{
// Handle string conversion error
}
The try/catch block is required because std::stoul() may throw exceptions if the conversion fails.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does "O's" mean in bar's (pub's, restaurant's) name?
could you please help me to understand the meaning of "O's" in such names as "Nancy O's restaurant", "George O's bar"... etc. Is there some special meaning, is it translatable? Thank you a lot!
A:
This is not a standard pattern.
In the case of Nancy O's restaurant it is "The restaurant of Nancy O". As far as I can tell "Nancy O" is a fictitious name. But it could suggest an Irish name, as many Irish names such as "O'Brian" or "O'Leary" where the "Ó" means "descendant" in Irish Gaelic.
I can't find "George O's bar". It might be another bar named after a person with an Irish name, or it could be Georges's restaurant in Waco, which serves a drink called "Big Os". That is short for Big Oranges.
Other than that I don't see O's in many other bar names. It is, part of the name, and so not translatable.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get windows thread to work with two functions at the same time?
The question is simple but the solution eludes me. I want to get two functions to be called and have them run at the same time (in separate threads), but I can only get void function1() called and void function2() runs only afterwards not during. I set the thread affinity for processor 1 and 2 (I have a multicore processor, hope you have one too).
The way I see that only one function is called at a time is simply because I get an output of only function 1 whereas normally I would see a mix of function 1 and function 2.
Feel free to reshuffle the code to make it work however possible but please try to keep the original methodology intact with the way a function is called by the thread within a class. Heres the complete code.
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <iostream>
class thread_class
{
private:
public:
void function1()
{
for(int count = 0; count < 1000; count++)
std::cout<<"function 1"<<std::endl;
}
void function2()
{
for(int count = 0; count < 1000; count++)
std::cout<<"function 2"<<std::endl;
}
thread_class(){}
~thread_class(){}
DWORD_PTR WINAPI threadMain0()
{
function1();
return 0;
}
DWORD_PTR WINAPI threadMain1()
{
function2();
return 0;
}
void thread()
{
HANDLE *m_threads = NULL;
DWORD_PTR c = 2;
m_threads = new HANDLE[c];
DWORD_PTR i = 0;
DWORD_PTR m_id0 = 0;
DWORD_PTR m_mask0 = 1 << i;
m_threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadMain0(), (LPVOID)i, NULL, &m_id0);
SetThreadAffinityMask(m_threads[i], m_mask0);
wprintf(L"Creating Thread %d (0x%08x) Assigning to CPU 0x%08x\r\n", i, (LONG_PTR)m_threads[i], m_mask0);
i = 1;
DWORD_PTR m_id1 = 0;
DWORD_PTR m_mask1 = 1 << i;
m_threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadMain1(), (LPVOID)i, NULL, &m_id1);
SetThreadAffinityMask(m_threads[i], m_mask1);
wprintf(L"Creating Thread %d (0x%08x) Assigning to CPU 0x%08x\r\n", i, (LONG_PTR)m_threads[i], m_mask1);
}
};
int main()
{
thread_class* MAIN_THREADS;
MAIN_THREADS = new thread_class();
MAIN_THREADS->thread();
delete MAIN_THREADS;
return 0;
}
edit: This is a slightly modified version of the code below that shows its not running parallel.
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <iostream>
class thread_class
{
private:
public:
void function1()
{
int exit = 0;
while(exit == 0)
{
std::cout<<"enter 1 to exit:"<<std::endl;
std::cin>>exit;
};
}
void function2()
{
for(int count = 0; count < 1000; count++)
std::cout<<"function 2"<<std::endl;
}
thread_class(){}
~thread_class(){}
DWORD_PTR WINAPI threadMain0()
{
function1();
return 0;
}
DWORD_PTR WINAPI threadMain1()
{
function2();
return 0;
}
void thread()
{
HANDLE *m_threads = NULL;
DWORD_PTR c = 2;
m_threads = new HANDLE[c];
DWORD_PTR i = 0;
DWORD_PTR m_id0 = 0;
DWORD_PTR m_mask0 = 1 << i;
m_threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadMain0(), (LPVOID)i, NULL, &m_id0);
SetThreadAffinityMask(m_threads[i], m_mask0);
wprintf(L"Creating Thread %d (0x%08x) Assigning to CPU 0x%08x\r\n", i, (LONG_PTR)m_threads[i], m_mask0);
i = 1;
DWORD_PTR m_id1 = 0;
DWORD_PTR m_mask1 = 1 << i;
m_threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadMain1(), (LPVOID)i, NULL, &m_id1);
SetThreadAffinityMask(m_threads[i], m_mask1);
wprintf(L"Creating Thread %d (0x%08x) Assigning to CPU 0x%08x\r\n", i, (LONG_PTR)m_threads[i], m_mask1);
}
};
int main()
{
thread_class* MAIN_THREADS;
MAIN_THREADS = new thread_class();
MAIN_THREADS->thread();
delete MAIN_THREADS;
return 0;
}
A:
So, a few things:
1) You can't use regular member functions as a ThreadProc. If you have to cast it to get it to compile it's probably wrong. The ThreadProc functions need to be free or static. They also had the wrong signature as a ThreadProc takes a single void* parameter.
2) There are several places where you use DWORD_PTR when you really want DWORD such as the return value from the ThreadProc, c, i, etc.
3) From the CreateProcess docs:
A thread in an executable that calls the C run-time library (CRT) should use the _beginthreadex and _endthreadex functions for thread management rather than CreateThread and ExitThread; this requires the use of the multithreaded version of the CRT. If a thread created using CreateThread calls the CRT, the CRT may terminate the process in low-memory conditions.
Chances are writing to cout eventually hits the CRT. It may not, and even if it does you may not have issues, but if you do that's a good place to look.
4) I/O isn't guaranteed to be interleaved at all, so writing to cout is not a good way to decide if the threads are running simultaneously or not. I've added some Sleep calls to the threads and also created them suspended at first so I could start them as close together as possible to make it seem like the I/O is interleaved, but that may just be coincidence. Once thing I do see that you may as well is that right when the threads are started the string that's printed and the endl are not attached to each other, that is I see both strings followed by two line ends. After that is it somewhat interleaved.
5) You always want to wait for the threads to exit before you delete the class out from under them. You also generally want to close their handles once they are done.
I eliminated the constructor/destructor since they were empty and other fluff just to keep this as short as possible.
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <iostream>
class thread_class
{
public:
void function1()
{
Sleep(0);
for(int count = 0; count < 10; count++)
{
std::cout<<"function 1"<<std::endl;
Sleep(0);
}
}
void function2()
{
Sleep(0);
for(int count = 0; count < 10; count++)
{
std::cout<<"function 2"<<std::endl;
Sleep(0);
}
}
static DWORD WINAPI threadMain0(LPVOID param)
{
thread_class* This = static_cast<thread_class*>(param);
This->function1();
return 0;
}
static DWORD WINAPI threadMain1(LPVOID param)
{
thread_class* This = static_cast<thread_class*>(param);
This->function2();
return 0;
}
void thread()
{
HANDLE m_threads[2] = {};
DWORD threadIDs[2] = {};
LPTHREAD_START_ROUTINE threadProcs[2] = {threadMain0, threadMain1};
DWORD_PTR mask = 0;
for(int i = 0; i < 2; ++i)
{
m_threads[i] = CreateThread(NULL, 0, threadProcs[i], this, CREATE_SUSPENDED, &threadIDs[i]);
mask = 1 << i;
SetThreadAffinityMask(m_threads[i], mask);
wprintf(L"Creating Thread %d (0x%08p) Assigning to CPU 0x%08p\r\n", i, m_threads[i], mask);
}
for(int i = 0; i < 2; ++i)
{
ResumeThread(m_threads[i]);
}
WaitForMultipleObjects(2, m_threads, TRUE, INFINITE);
for(int i = 0; i < 2; ++i)
{
CloseHandle(m_threads[i]);
}
}
};
int main()
{
thread_class* MAIN_THREADS;
MAIN_THREADS = new thread_class();
MAIN_THREADS->thread();
delete MAIN_THREADS;
return 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Are these flip flop conversions correct
Hi I am from computer science background and hence lack any solid foundation in electronics. I am trying to learn some flip flop conversions. Most of them are their online, however I did not found below two. So I made them myselves. But I need to know if I prepared the correct?
SR flipflop to T flipflop
T flipflop to SR flipflop
Are above conversions correct?
A:
Simply put - Yes, your schematics and tables are correct.
*Side note, you can find examples of these anywhere on the net as this is a typical study for undergrad elctrical engineering majors.
| {
"pile_set_name": "StackExchange"
} |
Q:
Correct way to initialize a Keras sequential neural net?
I am trying to initialize a Keras neural net. My X is an matrix of shape (70000, 4) and I want 64 nodes in the first layer
model = Sequential()
model.add(Dense(64, input_shape=(X.shape)))
The above syntax is incorrect. What is correct for my model.add()?
A:
I think you have 70000 samples with 4 points each. In that case, use Dense (64, input_shape=(4,)) and it should work.
The net would iterate over the samples in chunks of batch_size, although your net is likely small enough that you can set batch_size to a few thousand, or even the same size as the input.
Old answer I thought each sample was 70000x4...
The Dense layer cannot take a matrix as an input. From the Keras documentation, Dense(n_nodes, input_shape=(n_inputs,)) is equivalent to Dense(n_nodes, input_dim=n_inputs), and that seems to be the only kind of input it takes. Here n_inputs is an integer.
You basically have two options: either flatten X before passing it to the network with X.reshape(-1), or use Reshape as the first layer, like this:
model = Sequential()
model.add(Reshape((X.size,), input_shape=(X.shape)))
model.add(Dense(64))
You may be able to use Flatten instead of Reshape, although I can't tell from the documentation if Flatten can take an input_shape parameter.
| {
"pile_set_name": "StackExchange"
} |
Q:
C , regarding pointers (or pointers to pointers?), **, and malloc
As said in title, I have a question regarding using * twice, like in the main function of the following code. it DOES run, but I don't understand why using ** is right here. What i want is an array of SPPoints , sized n, where parr is the base adress. Why is ** right and * wrong in this case? thanks.
SPPoint code:
struct sp_point_t
{
double* data;
int dim;
int index;
};
SPPoint* spPointCreate(double* data, int dim, int index)
{
if (data == NULL || dim <= 0 || index < 0)
{
return NULL;
}
SPPoint* point = malloc(sizeof(*point));
if (point == NULL)
{
return NULL;
}
point->data = (double*)malloc(dim * sizeof(*data));
for (int i = 0; i < dim; i++)
{
point->data[i] = data[i];
}
point->dim = dim;
point->index = index;
return point;
}
And this is the main function:
int main()
{
int n, d, k;
scanf("%d %d %d", &n, &d, &k);
double* darr = malloc(d * sizeof(double));
if (darr == NULL)
{
return 0;
}
SPPoint** parr = malloc(n * sizeof(SPPoint*));
if (parr == NULL)
{
return 0;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < d; j++)
{
scanf(" %lf", &darr[j]);
}
parr[i] = spPointCreate(darr, d, i);
}
}
A:
An array can behave similarly to a pointer. For instance, int a [] is very similar to int* a. Each function in SPPoint returns a pointer to a SPPoint struct. An array of pointers to SPPoint can be written as a pointer to a pointer to SPPoint. With the malloc command, you are designating a certain amount of memory (enough to hold n pointers to SPPoint) for storage of pointers to SPPoint structs.
Not all pointers are arrays, however. SPPoint** parr is acting as an array holding pointers to single structs of type SPPoint.
Arrays can behave differently from pointers, especially when used for strings.
The reason why it is advantageous to use pointers to SPPoint (as you are now) is that you can view or modify a single element without having to copy the entire struct.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are Ether price questions allowed?
This hasn't really come up, but where do we draw the line about price discussion? For example, this post asks about the value of ether after the POS switch. This is not simply a "what will the price be" question, but it could lead to excessive speculation, and may be off-topic. Thoughts?
A:
No. It's subjective, primary opinion based, leads to discussions and finally... not really clear what he is asking.
| {
"pile_set_name": "StackExchange"
} |
Q:
Two line segments.
$H_{1}$ of a line segment is $\mathsf{Z}^{e - v + 1}$, so $\mathsf{Z}^{1 - 2 + 1}$ or $\mathsf{Z}^{0}$ \footnote{nj wildberger, homology video}... That equals 0 right? I have only taken calulus III, not linear algebra yet.
With two disjoint line segments I get $\mathsf{Z}^{2-4+1 \; = \; - 1}$....
How am I actually supposed to extend that definition to the two disjoint line segments - because, I can't compute what $\mathsf{Z}^{-1}$ is.
A:
Yes, a line segment has trivial homology. TWO line segments will have nontrivial 0 homology, but trivial homology in every other dimension.
A quick way to see this is by "contracting" the lines down to points, which if you have not seen yet, you will probably see soon. Loosely, homology measures how many "holes" your space has, where a 0 dimensional hole is two points not filled in by a line, a 1 dimensional hole is a circle that isn't filled in by a disk, a 2 dimensional hole is a sphere not filled in by a ball, and so on.
In the one line case, you have every point connected to every other point, and so we get trivial homology (with homology is $\mathbb{Z}^1$ in dimension 0, because there is 1 connected component.
In the two line case, we have TWO connected components, so 0 homology will be $\mathbb{Z}^2$, and all other homology groups will be trivial.
I hope this helps ^_^
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting up a picture thumbnail service on Amazon Ec2 - bare minimum PHP
I am looking for a good strategy for setting up a thumbnailing service on the Amazon EC2 free tier +S3, with only the essentials.
After trying a few Lamp configurations on the Micro instance, 610~ MEGS, I am usually left with around 50-200 megs of memory for the actual image processing. There has to be a better way, with an even smaller footprint.
One idea would be to install Debian Squeeze + Php 5, - would this be all I need? Just Shell commands? No apache, nginx, lighthttpd, etc?
I haven't tried the tutorial as featured in the docs here: http://aws.amazon.com/articles/1602
as it seems to be unnecessarily complicated and expensive with too many moving parts.
Any ideas, links to tuts or duplicate posts would be a great starting point.
A:
FORGET THIS!
After consulting with my buddy, Jaisen, who runs theopenphotoproject.org, he suggested using imagemagick for resizing a set of thumbnails before uploading.
Before uploading. Heh.
Why overcomplicate things? Sometimes the easiest way is still the best way.
| {
"pile_set_name": "StackExchange"
} |
Q:
StackOverflowError when executing cypher queries through Neo4J REST API
I'm using Neo4j version 3.0.7
I'm reading a list of edges from a dataset and I need to pass those edges batch-wise using the REST API.
I used the following query format to create multiple nodes (if they already don't exist) and their relationships in Neo4j through a single Cypher query via the REST API. I obtain the two vertices of an edge and the node properties are set according to the vertex IDs of those vertices.
{
"query":
"MATCH (n { name: 0 }), (m { name:1 })
CREATE (n)-[:X]->(m)
WITH count(*) as dummy
MATCH (n { name: 0 }), (m { name: 6309 })
CREATE (n)-[:X]->(m)"
}
This approach works correctly for a batch of 10 edges but when I try to send a batch of 1000 edges (nodes and their relationships) through a single Cypher query, I get a StackOverflowError exception. Is there a better approach to achieve this task?
Thank you for your help.
The error obtained from the response:
{
"exception" : "StackOverflowError",
"fullname" : "java.lang.StackOverflowError",
"stackTrace" : [ "scala.collection.TraversableOnce$class.$div$colon(TraversableOnce.scala:151) ..."
}
A:
You can use UNWIND to get a single query:
UNWIND [[0,1], [0,6309]] AS pair
MATCH (n {name: pair[0]}), (m {name: pair[1]})
CREATE (n)-[:X]->(m)
Insert your node pairs after UNWIND as a list of two-element lists. As the query uses the name property for finding the nodes, it is worth adding an index to it. For example, if you haven Person nodes, index them with:
CREATE INDEX ON :Person(name)
(See also the Cypher reference card.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Translation of "I don't have anything to smile about"
I'm trying to translate the lyric: "I don't have anything to smile about."
Does
Je n'en ai rien pour sourire
or
Je n'ai rien pour en sourire
sound okay to you? Or would a different translation be better?
A:
In this case, I'd rather say:
Je n'ai pas le coeur à (sou)rire
Je n'ai pas le coeur à en (sou)rire
A:
Neither translation is working. en for some reason doesn't work here as a pronoun for the object of sourire and rien is problematic too. I think you'd have to say :
Je n'ai pas de quoi sourire
A:
Some context would be helpful. Deepl is of handy here:
Je n'ai aucune raison de sourire.
Je n'ai pas de quoi sourire. (already mentioned by @petitrien)
There is also the song Je n'ai pas le Cœur à Sourire of Daniel Guichard
Je n'ai pas le cœur à sourire
(already mentioned by @MercrediAndThenJedi)
Besides, in this link
https://genius.com/Genius-traductions-francaises-halsey-nightmare-traduction-francaise-lyrics
one reads the original lyrics of the song Nightmare by Halsey along the French translation. So
No, I ain't got nothin' to smile about.
Non, je n'ai pas de quoi sourire.
Here is the Pre-chorus
"Come on, little lady, give us a smile" - "Allez, petite fille, fais-nous un sourire"
No, I ain't got nothin' to smile about - Non, je n'ai pas de quoi sourire
I got no one to smile for, I waited a while for -Je n'ai personne à qui sourire, j'ai attendu un certain temps pour
A moment to say I don't owe you a goddamn thing - Un moment pour dire que je ne te dois rien
| {
"pile_set_name": "StackExchange"
} |
Q:
Header contents of a .bin file in Linux
Which contents have the header of an executable .bin file in Linux?
I found information for .exe files in Windows but I can't find any information for .bin files.
TIA
A:
Just to be clear, in Linux, executable files may be called "binary" but don't have an explicit ".bin"
Linux generally uses the ELF format. The first byte is 0x7F followed by ascii for E, L, F - this is easily visible if you can load the binary into a text editor or print it at the command line using 'cat' or 'less'. After that... well I'm rusty but details are easily found on the web.
Try http://www.thegeekstuff.com/2012/07/elf-object-file-format/ and http://www.acsu.buffalo.edu/~charngda/elf.html for a starter. (I found these with a superficial quick search, and do not claim these are the best. Happy hunting!)
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript split not recognizing middle dot
I'm trying to split a string based upon the middle dot. For some reason, it's not recognizing it. I can use a "pipe" character so I know everything else is working, but not the middle dot. Do I need to escape the middle dot? If so, how?
Javascript
var sTags = $(this).text();
// alert(sTags);
sSplitTags = sTags.split(' | ');
// Split isn't recognizing the middot
// var sSplitTags = sTags.split(' · ');
// var sSplitTags = sTags.split(' · ');
// var sSplitTags = sTags.split(' · ');
alert(sSplitTags[0]);
HTML
<div>Upscale · Gadget</div>
<div>Expensive · Widget</div>
<div>Expensive · Widget</div>
Thanks in advance!
A:
' \267 ' Should be what you're looking for. Javascript uses an octal encoding for special characters that differs from the html/css encoding syntax.
Here's a site with a nice lookup table: http://www.evotech.net/blog/2007/04/named-html-entities-in-numeric-order/
-EDIT-
ruakh brought up this version of ' \u00B7 ' which is also just as valid. You'll notice on the page that there is a column for hex codes and for middle dot it is B7. In css you would write \00B7 but in javascript we need to qualify that this is not an octal by appending the little 'u' to the front and you'd end up with \u00B7'.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get child nodes with ELEMENT_NODE type only
I'm parsing a xml document using java DOM and I need to get every single node for doing something.
I have this code:
public void analyze_file(Node node){
if(node.getNodeType() != Node.DOCUMENT_NODE){
//do something
}
NodeList list = node.getChildNodes();
for(int i=0; i<list.getLength(); i++){
if(list.item(i).getNodeType() == Node.ELEMENT_NODE){
analyze_file(list.item(i));
}
}
}
The problem is that, my xml file is very large ( > 30000 lines), and the code above needs too much time for checking whether a node is of ELEMENT_NODE type or not. I see that if the program stopped after it reached the last ELEMENT_NODE node, the execution time would be very small.
Is there any way to get all child nodes whose type is ELEMENT_NODE only?
For example: NodeList list = node.getElementChildNodes();
Thanks for any help!
A:
node.getElementsByTagName("*")
From JavaDoc: Returns a NodeList of all descendant Elements with a given tag name, in document order. Name - The name of the tag to match on. The special value "*" matches all tags.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to link to a nested route action inside a parent loop?
I'm trying to display everything on my index page, but when I try to link to a new_story_substory_path I get undefined local variable or method substory.
Here is the code:
index.html.erb
<% @stories.each do |story| %>
<h3><p><%= story.title %></p></h3>
<p><%= story.plot %></p>
<% if story.user == current_user %>
<%= link_to 'Show XXX', story_path(story), class: "btn btn-success" %>
<%= link_to 'Edit', edit_story_path(story), class: "btn btn-success" %>
<%= link_to "Delete", story_path(story), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-success" %></br>
<% end %>
<% story.substories.each do |substory| %>
<h4><p><%= substory.title %></p></h3>
<p><%= substory.subplot %></p>
<% if story.user == current_user %>
<%= link_to 'Show', story_substory_path(substory.story, substory), class: "btn btn-default" %>
<%= link_to 'Edit', edit_story_substory_path(substory.story, substory), class: "btn btn-default" %>
<%= link_to "Delete", story_substory_path(substory.story, substory), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-default" %>
<% end %>
<% end %>
<br>
<% if story.user == current_user %>
<br>
<br>
# this is where I'm getting the error:
<%= link_to 'New subplot', new_story_substory_path(substory.story, substory), class: "btn btn-warning" %>
# however if I move this up, inside the second loop, it works perfectly.
<br>
<% end %>
<% end %>
<br>
<%= link_to 'New Story', new_story_path, class: "btn btn-danger" %>
Here is my controller, routes and models:
class StoriesController < ApplicationController
before_action :set_story, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@stories = Story.all
end
def show
end
def new
@story = current_user.stories.build
end
def edit
end
def create
@story = current_user.stories.build(story_params)
respond_to do |format|
if @story.save
format.html { redirect_to root_path, notice: 'Story was successfully created.' }
format.json { render :show, status: :created, location: root_path }
else
format.html { render :new }
format.json { render json: root_path.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @story.update(story_params)
format.html { redirect_to root_path, notice: 'Story was successfully updated.' }
format.json { render :show, status: :ok, location: root_path }
else
format.html { render :edit }
format.json { render json: @story.errors, status: :unprocessable_entity }
end
end
end
def destroy
@story.destroy
respond_to do |format|
format.html { redirect_to stories_url, notice: 'Story was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_story
@story = Story.find(params[:id])
end
def story_params
params.require(:story).permit(:title, :plot)
end
end
Rails.application.routes.draw do
devise_for :users
resources :stories do
resources :substories
end
root 'stories#index'
end
class Story < ActiveRecord::Base
has_many :substories, dependent: :destroy
belongs_to :user
end
class Substory < ActiveRecord::Base
belongs_to :story
belongs_to :user
end
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :stories, dependent: :destroy
has_many :substories, dependent: :destroy
end
what am I missing?
Edit:
Here is the controller for the substories:
class SubstoriesController < ApplicationController
before_action :set_substory, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
before_action :set_story
def index
@Substories = @story.substories.all
end
def show
end
def new
@substory = Substory.new
end
def edit
end
def create
@substory = Substory.new(substory_params)
@substory.user_id = current_user.id
@substory.story_id = @story.id
if
@substory.save
redirect_to @story
else
render 'new'
end
end
def update
respond_to do |format|
if @substory.update(substory_params)
format.html { redirect_to root_path, notice: 'Story was successfully updated.' }
format.json { render :show, status: :ok, location: root_path }
else
format.html { render :edit }
format.json { render json: @story.errors, status: :unprocessable_entity }
end
end
end
def destroy
@substory.destroy
redirect_to root_path
end
private
def set_story
@story = Story.find(params[:story_id])
end
def set_substory
@substory = Substory.find(params[:id])
end
def substory_params
params.require(:substory).permit(:title, :subplot)
end
end
A:
I got the answer from the comments.
MrYoshi wrote:
At the line producing the error: You are calling the substory variable but it is only existing in the story.substories.each loop ; you probably meant to use new_story_substory_path(story) (path leading to the creation page of a substory belonging to the story currently been seen/edited)
Basically I changed the line form:
<%= link_to 'New subplot', new_story_substory_path(substory.story, substory), class: "btn btn-warning" %>
to:
<%= link_to 'New subplot', new_story_substory_path(story), class: "btn btn-warning" %>
This works!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to iterate through collection in JSP and set values in an object in an action class
I have a JSP that receives a collection list from an action class. I am iterating through that list and I wish to set the values of that list to another object inside another action class through a form request. When I use the displayMovies.jsp when I use the <s:propertytag in the iterator it displays on the different objects in the collection. I want to save or pass each of those objects in the collection to a different action class.
displayMovies.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="com.sans.model.Movie" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Movie retrieval Page
<br />
<s:iterator value="movieRetrievedArray" var="movieS">
<s:form action="movieDetails.action" method="post" id="movieDetailsForm">
<s:property value="title"/><br />
<s:property value="releaseDate"/><br />
<s:hidden name="movieDetailedInformation.title" value="%{title}" id="hiddenMovie" />
<img src="<s:property value="posterPath" />" onClick="test()">
</s:form>
<br />
<br />
</s:iterator>
<script type="text/javascript">
function test() {
document.getElementById("movieDetailsForm").submit();
}
</script>
</body>
</html>
MovieDetailsActions.java
package com.esi.actions;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sans.model.Movie;
@SuppressWarnings("serial")
@Results({
@Result(name="success", location="/RetrieveMovies/movieDetails.jsp"),
@Result(name="input", location="/RetrieveMovies/movieError.jsp")
})
public class MovieDetailsAction extends ActionSupport {
private Movie movieDetailedInformation = new Movie();
@Action(value="movieDetails")
public String execute() {
System.out.println(movieDetailedInformation.getTitle());
return SUCCESS;
}
public Movie getMovieDetailedInformation() {
return movieDetailedInformation;
}
public void setMovieDetailedInformation(Movie movieDetailedInformation) {
this.movieDetailedInformation = movieDetailedInformation;
}
}
A:
You should use status variable on iterator tag.
<s:form action="movieDetails.action" method="post" id="movieDetailsForm">
<s:iterator value="movieRetrievedArray" var="movieS" status="status">
<s:property value="title"/><br />
<s:property value="releaseDate"/><br />
<s:hidden name="movieDetailedInformationList[%{#status.index}].title" value="%{title}" id="hiddenMovie" />
<br />
<br />
</s:iterator>
<img src="<s:property value="posterPath" />" onClick="test()">
</s:form>
The movieDetailedInformationList is
private List<Movie> movieDetailedInformationList;
public List<Movie> getMovieDetailedInformationList() { return movieDetailedInformationList; }
You don't need to initialize movieDetailedInformationList, because Struts2 populate it with parameters from the post request.
The Movie class should be public and have default constructor, the public setter for title is necessary.
| {
"pile_set_name": "StackExchange"
} |
Q:
Side by Side two navbar bootstrap
How is possible I put two navbars side-by-side using Twitter's bootstrap.
I want the sorting navbar on right side of filtering navbar.
A:
You would need to declare their width and then give them a value of float: left
DEMO http://jsfiddle.net/KY2Pr/27/
.navbar {
width: 200px;
float: left;
}
Fluid width mobile friendly
DEMO http://jsfiddle.net/KY2Pr/28/
.navbar {
width: 50%;
float: left;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does SFINAE not apply to this?
I'm writing some simple point code while trying out Visual Studio 10 (Beta 2), and I've hit this code where I would expect SFINAE to kick in, but it seems not to:
template<typename T>
struct point {
T x, y;
point(T x, T y) : x(x), y(y) {}
};
template<typename T, typename U>
struct op_div {
typedef decltype(T() / U()) type;
};
template<typename T, typename U>
point<typename op_div<T, U>::type>
operator/(point<T> const& l, point<U> const& r) {
return point<typename op_div<T, U>::type>(l.x / r.x, l.y / r.y);
}
template<typename T, typename U>
point<typename op_div<T, U>::type>
operator/(point<T> const& l, U const& r) {
return point<typename op_div<T, U>::type>(l.x / r, l.y / r);
}
int main() {
point<int>(0, 1) / point<float>(2, 3);
}
This gives error C2512: 'point<T>::point' : no appropriate default constructor available
Given that it is a beta, I did a quick sanity check with the online comeau compiler, and it agrees with an identical error, so it seems this behavior is correct, but I can't see why.
In this case some workarounds are to simply inline the decltype(T() / U()), to give the point class a default constructor, or to use decltype on the full result expression, but I got this error while trying to simplify an error I was getting with a version of op_div that did not require a default constructor*, so I would rather fix my understanding of C++ rather than to just do what works.
Thanks!
*: the original:
template<typename T, typename U>
struct op_div {
static T t(); static U u();
typedef decltype(t() / u()) type;
};
Which gives error C2784: 'point<op_div<T,U>::type> operator /(const point<T> &,const U &)' : could not deduce template argument for 'const point<T> &' from 'int', and also for the point<T> / point<U> overload.
A:
Not 100% sure. It appears that the compiler needs to instantiate both overloads to determine which is better, but while trying to instantiate the other op_div with T = int and U = point<float>, this leads to an error that is not covered by SFINAE (the error is not that op_div doesn't have type in this case, but that type cannot be determined).
You could try to disable the second overload if the second type is a point (boost::disable_if).
Also, what seems to work is postponed return type declaration (doing away with the op_div struct, but depending on which C++0x features are supported by your compiler):
template<typename T, typename U>
auto
operator/(point<T> const& l, point<U> const& r) -> point<decltype(l.x / r.x)> {
return {l.x / r.x, l.y / r.y};
}
template<typename T, typename U>
auto
operator/(point<T> const& l, U const& r) -> point<decltype(l.x / r)> {
return {l.x / r, l.y / r};
}
| {
"pile_set_name": "StackExchange"
} |
Q:
¿Cómo aplicar más de una validación personalizada a un campo con mongoose?
Estoy aprendiendo validaciones en mongoose, pero no logro aplicar varias validaciones personalizadas a un mismo campo.
Basándome en:
var Esquema = new mongoose.Schema({
campo1 : {type: String, validate: [
function (campo1) {
//..lo que se necesite validar
},
'Mensaje error de validacion'}
});
Lo anterior funciona a la perfección, pero ¿Cómo se podría hacer si requiero aplicar mas de 1 validación personalizada a campo1?
Hasta ahora lo que he intentado es:
var Esquema = new mongoose.Schema({
campo1 : {type: String, validate: [
function (campo1) {
//..lo que se necesite validar 1
},
'Mensaje error de validacion 1'},
function (campo1) {
//..lo que se necesite validar 2
},
'Mensaje error de validacion 2'}
});
Este intento sólo toma la primera validación.
A:
Prueba con esto:
var variasValidaciones = [
{ validator: validacion1, msg: 'No cumple validacion1' },
{ validator: validacion2, msg: 'No cumple validacion2' }
];
var validacion1 = function(string) {
// Codigo de validacion1
};
var validacion2 = function(string) {
// Codigo de validacion2
};
var Esquema = new mongoose.Schema({
campo1 : {type: String, validate: variasValidaciones}
...
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I make the desired axis on a chart invisible?
Please look at the picture.
The x-axis is removed, but the y-axis is not removed. Why? The Java code is down there.
ValueAxis axis = chart.getXYPlot().getDomainAxis();
axis.setVisible(false);
A:
Note this distinction between the model, a Dataset, and view, an Axis:
XYPlot::getDomainAxis returns a reference to the axis that displays the domain (X values) of the chart's XYDataset.
XYPlot::getRangeAxis returns a reference to the axis that displays the range (Y values) of the chart's XYDataset.
Focusing on the domain axis, the result of setVisible(false) depends on the PlotOrientation. XYPlot::getOrientation returns a reference to the orientation, typically specified in the ChartFactory used to construct the chart. Because a conventional plot has a vertical y-axis, the PlotOrientation is VERTICAL for a plot where the domain axis is horizontal, and the PlotOrientation is HORIZONTAL for a plot where the domain axis is vertical.
In this example, the domain is minutes and the range is number of students.
In both examples below, the domain axis (minutes) is made invisible.
ValueAxis domain = chart.getXYPlot().getDomainAxis();
domain.setVisible(false);
Result with PlotOrientation.VERTICAL; invisible domain axis is horizontal.
Result with PlotOrientation.HORIZONTAL; invisible domain axis is vertical.
A similar analysis applies to making a range axis invisible.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I make an image's height responsive in a Bootstrap 4 column so that an embedded video in an adjacent column is not affected?
I need a row that contains an image, an embedded video, and some text. The site uses Bootstrap for responsive behavior, however, the objects in this row should not stack when the width of the page is reduced.
With an image in the first column the embedded video in the second column has problems resizing when the width of the page is reduced. It appears that as the page width decreases and the row height becomes less than the height of the image in the first column the embedded video in the second column begins to display black bars above and below and loses its aspect ratio. This occurs even though the image itself does seem to be changing height (thus being "responsive"). But the real problem I'm trying to address is the problem with the embedded video in the second column that gets messed up when the page width is reduced (with an image in the first column).
My code is as follows:
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-3 border">
<a href="https://placeholder.com"><img class="img-fluid" src="https://via.placeholder.com/30x225" alt="image"></a>
</div>
<div class="col-6 border embed-responsive embed-responsive-16by9" id="vid">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/kyJUQuaECrg" allowfullscreen></iframe>
</div>
<div class="col-3 border d-flex">
<span class="mt-auto">Some Text</span>
</div>
</div>
</div>
</body>
</html>
The problem appears to center around the image in the first column. If I remove the image and place text in the column then the embedded video in the second column resizes properly at all window widths.
Although the "img-fluid" class added to the image in the first column appears to cause the image to have a responsive height the video in the second column gets messed up when the page width is shrunk. I've tried all sorts of height manipulations using percentages to both the image and the div/col containing the image, but so far I can't find a combination that addresses this issue.
Ultimately I would like to be able to specify a height for the image in the first column that is defined as a percentage of its container. I need the image to have a responsive height and the embedded video to scale but maintain its appearance (no black bars and correct aspect ratio) at all page widths.
BTW the image in the first column could be replaced with text that is rotated 90 degrees to the left. However, any attempt to rotate text within a Bootstrap column has caused a number of other alignment problems.
A:
I found that if I use Bootstrap's embed-responsive class for the first column (containing the image) and wrap the image in a <div> then the embedded video in the second column behaves properly.
For some reason this doesn't work with the anchor around the placeholder image I used in the code in my question above. So I've provided my updated code below with a reference to a local image.
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-3 embed-responsive border">
<div class="embed-responsive-item justify-content-end d-flex ">
<img class="mt-auto" style="height: 100%;" src="img/local_image.jpg">
</div>
</div>
<div class="col-6 border embed-responsive embed-responsive-16by9" id="vid">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/kyJUQuaECrg" allowfullscreen></iframe>
</div>
<div class="col-3 border d-flex">
<span class="mt-auto">Some Text</span>
</div>
</div>
</div>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
Awk statement in bash isn't executing when in for loop
I have a text file with search terms (patts) that I need to delete from 'patterns.txt'. I have tested out the awk statement and it works correctly - except in the script.
Also, the $target variable is printing correctly when I echo to standard output. For some reason, however, the statement isn't executing properly.
#!/usr/local/bin/bash
input_file='patts'
i=0
while read line; do
array[$i]=$line
i=$((i+1))
done < "$input_file"
for (( i=0; i<${#array[@]}; i++ )); do
target=`eval echo ${array[i]}`
echo $target
awk '!/$target/' patterns.txt > temp && mv temp patterns.txt
done
A:
Shell variables don't expand in single quotes. Also it is better to use -v name=value to pass arguments to awk:
awk -v target="$target" '!($0 ~ target)' patterns.txt > temp && mv temp patterns.txt
However it looks like you can use replace awk by grep -v:
grep -v "$target" patterns.txt > temp && mv temp patterns.txt
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get the width of y-axis label in MPAndroidChart
How to get the width of left y-axis label? or the space between the start of chart and y-axis
A:
If you would like the get the longest label width then you can do:
chart.getRendererLeftYAxis()
.getPaintAxisLabels()
.measureText(chart.getAxisLeft().getLongestLabel())
Or you can get the margins on either side of the labels:
chart.getAxisLeft().getXOffset()
Or you can get the axis width (which are the last two values combined):
chart.getAxisLeft().getRequiredWidthSpace(
chart.getRendererLeftYAxis().getPaintAxisLabels())
| {
"pile_set_name": "StackExchange"
} |
Q:
How can a pendulum have amplitude greater than $\pi$?
How can a pendulum have amplitude angle greater than $\pi$? I've been reading about phase plots, which are graphs of the $\frac{d\theta}{dt}$ on the $y$ axis and $\theta$ on the $x$ axis, shown below.
I can understand that the curves are not perfect ovals because we cannot use the small angle approximation. I can also see that there is one curve in the right side's drawing which looks like a sine curve shape, but intersects the $x$ axis at $\pi$ and $-\pi$.
But how are the other curves i.e. the curve intersecting $y$ axis at +2 created? What equation gives that and how would the pendulum's motion look? How would such an equation be derived?
I have a pendulum equation $$\frac{d\theta}{dt}=\pm\sqrt{\frac{2g}{l}(1-cos\theta_A)}$$
($\theta_A$ is amplitude)
I derived that with conservation of energy laws, like for a simple pendulum but I did not do the small angle approximation. I tried to put $\theta_A=\pi+1$ and I got a simple oval, not the pair of curves that is symmetric about the $x$ axis. I do not understand the math and notation being used in this question: What is the period of a physical pendulum without using small-angle approximation?
I'm confused.
A:
How are the other curves i.e. the curve intersecting y axis at +2 created?
The trick behind understanding that phase portrait is realizing that the 'amplitude' is not the fundamental quantity which acts as the difference between those lines.
The amplitude of a pendulum is usually considered to be the angle or displacement at which the velocity is zero, according to conventional intuition. But we see that the line you pointed out, the one with a maximum angular velocity of $2$, never reaches $\frac{d\theta}{dt}=0$, so a 'pendulum'described by that line won't have an amplitude according to our usual definition.
The solution? You need to think of maximum angular velocity as the fundamental quantity instead. For every pendulum shown by that phase portrait, the maximum angular velocity will be at the lowest point of the pendulum's trajectory. So each line in that phase portrait depicts a different trial with the same pendulum, except the angular velocity at that lowest point is different each time.
Think of performing an experiment to test the behavior of your pendulum for different amplitude angles, but each trial, instead of dropping the pendulum from a different position, you launch it from that same base point with a different velocity. And obviously $v=l\dot{\theta}$, where $\frac{d\theta}{dt}=\dot{\theta}$, so you'll be starting with different initial angular velocities.
What equation gives that and how would the pendulum's motion look?
Now let's consider you start the pendulum with a really high angular velocity... it'll eventually end up moving in a complete circle! When the pendulum reaches $\theta=\pi$, it'll still have some kinetic energy, and it'll descend on the opposite 'side' of the pendulum's pivot.
When you're at the lowest point, you'll have the greatest velocity and hence the greatest angular velocity. As the height increases, the potential energy increases, hence the kinetic energy decreases and the angular velocity decreases. And thus you see a minimum, but nonzero angular velocity when $\theta=\pi$ according to the phase portrait.
How would such an equation be derived?
Conservation of energy works again, though the Lagrangian may be easier. You know the initial kinetic energy, because your initial conditions give you $l$ and $\dot{\theta}_{max}$. Also, at any angle $\theta$, the potential energy is $mgl(1-\cos\theta)$. If you consider the energy at a couple of different points and equate them, you'll get $$\dot{\theta}=\pm\sqrt{\dot{\theta}_{max}^2-\frac{2g(1-\cos\theta)}{l}}$$
I may have mentioned that I'm a huge fan of ultra-colorful diagrams, so here's one I threw together. It's much clearer than the monochrome thing in the question.
A:
Have you ever played on a playground swing, and got worried that if you went any faster, you would swing right over the bar and start going around and around? That's what's happening here. If you give the pendulum more energy than $2 m g \ell$, then it'll get to the top and keep going, swinging around and around. Strictly speaking it has no amplitude, since it isn't oscillating.
A:
On your phase portraits, the horizontal axis is $\theta$, and the vertical axis is proportional to $\dot \theta$. Each trajectory (red line) corresponds to a constant energy. The trajectory that intersects the horizonal axis is one that has enough energy to just make it's around a full circle about the pivot. The trajectories like the one you specify that go to +2 on the vertical axis are trajectories that have much more energy, where the pendulum is spinning "rapidly" around the pivot point. In this case there is no amplitude in $\theta$. You also have to keep in mind that time is not explicit on these phase portraits.
For a simple pendulum, another way to write the equation of motion is $\ddot \theta =\frac{g}{L} sin(\theta)$. This equation does not have a solution $\theta (t)$ we can write out with simple functions in general. It must be solved numerically. If we use the small angle approximation, then we can get a nice solution written in terms of sines and cosines. Of course, if we are looking at the phase portrait, then the equation of $\dot \theta (\theta)$ is a perfectly valid way to see "how the pendulum's motion would look", as you asked in your question. The phase portrait does not tell us the rate at which we travel along a trajectory in the phase space, but this is not needed to understand much of this system qualitatively.
I have already mentioned an answer to the title question, but I will address it more explicitly here. The pendulum cannot have an amplitude larger than $\pi$. Amplitude is defined by the largest $\theta$ can be. You can see the the higher energy trajectories do not have a maximum $\theta$, as $\theta$ either increases or decreases forever. Even if you restrict your range of $\theta$ to just be in the range of $[-\pi ,\pi ]$ in these large energy cases, your "amplitude" is now $\pi$ and cannot be any larger.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find out the integral of the following problem?
Let $U$ be a real Hilbert space with orthonormal basis $\{e_n\}_{n \in \mathbb{N}}$. We have a compact linear operator $F'(x)(e_n) : U \to U$ by $$F'(x)(e_n) = 2^{-n} e_n$$ Now i want to find out the function $F$ i.e. how to find out $F$ from its Frechet derivative? Any idea how to go back?
After some ideas, by hit and trial can i say that $$F(x) = \sum_{n=1}^{\infty} \zeta_n^2 2^{-(n+1)} e_n$$ where $x = \sum_{n=1}^{\infty} \zeta_n e_n$ is the $F$?
A:
Note that if you define
$$
G:U \to U: x=\sum_{n=1}^\infty x_n e_n \mapsto \sum_{n=1}^\infty \frac{x_n^2}{2^{n+1}} e_n,
$$
then for any $x \in U$, $h >0$ and $n \in \mathbb{N}$ we have
$$
G(x+he_n)-G(x) = \frac{2x_n h +h^2}{2^{n+1}}e_n.
$$
So the Fréchet derivative will actually be $G'(x)(e_n) =x_n 2^{-n} e_n$, which is quite different from $F'(x)(e_n) = 2^{-n}e_n$.
The proper solution is actually simply the linear map given by $F(e_n) = 2^{-n}e_n$. Because a linear map is its own derivative, it's easily seen that this works.
| {
"pile_set_name": "StackExchange"
} |
Q:
web.config is different in MVC3 and MVC4
Im doing a web application in C# and ASP.NET MVC4.
On inspection of the web.config file I noticed that MVC4 has this:
<system.web>
<compilation debug="true" targetFramework="4.0" />
whereas if you look in the MVC3 web.config file you will see the following:
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
So, my question is why are the assemblies not in MVC4 web.config? Or are they elsewhere?
Many thanks.
A:
Most of this is now all "rolled up"
namespaces are what you typically will now see
If you need to add in an Assembly you are free to do so.
http://www.asp.net/whitepapers/mvc4-release-notes
You should still be able to do this:
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Data.Entity, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
| {
"pile_set_name": "StackExchange"
} |
Q:
5e Item Creation
I'm looking to have a magic item built. I require an eighth level spell to be constantly cast through a belt. I don't know the current requirements for Fifth edition but I do know what I'm after. I just wanted to know the base price for such an item.
A:
5e does not assume that magic items can be bought, at any price.
From the PHB p. 144, emphasis mine: "aside from a few common magic items, you won't normally come across magic items or spells to purchase. The value of magic is far beyond simple gold and should always be treated as such."
From the DMG p.128: "Magic items are the DM's purview, so you decide how they fall into the party's possession."
But we do know how to craft magic items.
If your DM wishes you to be able to commission such an item, it could have been produced by someone following the crafting suggestions on DMG pp.128-129. A few key touchstones might inform this:
a 8th-level spell scroll is already in the "very rare" category (DMG p.200)
a staff of power only casts 5th-level spells, only has 20 charges (not continuous casting), and is in the "very rare" category. (You'll find, looking at the other casting-items, that this is typical.)
Your 8th-level continuous casting permanent item, therefore, at least legendary, if not artifact-level. IMO it's overpowered even compared to the artifacts in existence.
"Work with your GM" is the only real answer to this.
And don't be surprised if they think this item is overpowered. Because it is, at least when compared to all published magical items.
A:
Consulting the Dungeon Master's Guide, "Chapter 6: Between Adventures" pages 130 and 129, we can clearly see the rules for creating a magic item as a player. The cost of creating any magic item depends on its rarity, as does the minimum level required to craft it.
CRAFTING MAGIC ITEMS
\begin{array}{l | l l}
\text{Item Rarity} & \text{Creation Cost (gp)} & \text{Minimum Level} \\ \hline
\text{Common} & 100 & 3 \\
\text{Uncommon} & 500 & 3 \\
\text{Rare} & 5\,000 & 6 \\
\text{Very Rare} & 50\,000 & 11 \\
\text{Legendary} & 500\,000 & 17 \\
\end{array}
In addition, if an item can cast a spell, the crafter must be able to cast that specific spell as well, doing so for each day of creation. The crafter spends eight hours a day working, spending 25 gp per day. This is until so many days have passed that the full cost of creation has been spent. In addition, if the spell that you are replicating normally requires material components, you would have to provide a different set of the components for each day of creation, as the process consumes the components each day.
(NOTE: Exotic materials and/or crafting methods may be required by your DM.
Considering the strength of an Eighth level spell, let alone the fact that it would be casted continuously, I would consider the item at the level of Legendary, meaning that it would take a 17th level character 20000 days (or just a little under 55 years) to craft the item, casting the Eighth level spell in question each day of crafting and spending a total of 500,000 gp.
(THOUGHTS: In reality, the pure strength of this item may warrant an even higher creation cost than listed.)
If you wanted to speed things up, you could have other characters also meeting the level requirement assist, speeding up the process by a factor of the total number of people working on it.
Say you had two other level 17 characters assist you. Considering they each work eight hours a day with you for the entire process, you could accomplish the task in 6667 days (approximately 18 years) , with the total cost coming to 500,000 gp or 166,666 gp, 6 sp, and 7 cp per person if split amongst the crafters equally.
This magical item would be at a ridiculous price to purchase due to its power, required resources and Legendary rarity, considering you could even find a buyer.
(NOTE: The price and speed of creation may be changed by the DM, as well as the ability to craft magic items as a player whatsoever)
So, in reality, if you want to make something like this as a player, you need your DM's approval. If you get that, these are the rules presented in the books, though its always up to the DM on how they want to do it. They may allow you to do it cheaper, more expensive, or maybe they won't let you do it at all. Magic items are something tricky, powerful, and always under DM power.
| {
"pile_set_name": "StackExchange"
} |
Q:
Comparison of Metamask vs Ganache
I watched some videos about Metamask but I am so confused by it
Metamask: To use the final application like the end user would.
Based on that, what is the purpose of React then?
What are the differences between Ganache and Metamask?
A:
Those two products are completely different.
Metamask is a blockchain wallet (account management) that secures a private key and helps you to interact with an Ethereum Blockchain network (like mainnet, testnet, private networks or local).
It's a Browser extension (Chrome/Firefox/Brave) that triggers a popup when a user tries to send a transaction to the blockchain, in this popup, the user needs to accept the transaction (sign the transaction with the private key).
Your dApp is a web application (React or other), rather than interacting with a traditional HTTP API, it interacts with a blockchain that requires client signature (using private key) to send a transaction.
Metamask manages that part of handling securely your private keys, signing transactions and communicating with the network.
Metamask is a tool for dApp users.
Metamask Knowledge Base for more information
Ganache is a tool for developers that allows you to run a private and local blockchain on your machine. It's a very useful tool because a blockchain is a complex peer2p distributed system, so it allows developers to deploy and test locally their development (smart contracts) before going to a public network (mainnet or testnet)
Ganache is a tool for dApp developers.
Ganache documentation
| {
"pile_set_name": "StackExchange"
} |
Q:
What happens to opened files/file pointers(Buffered Reader) inside of a function after the function exits?
I was wondering what happens to opened files/file pointers(Buffered Reader) inside of a function after the function exits?
For example
public void foo(){
String curr;
for (int i = 0; i < 100; i++){
BufferedReader br = new BufferedReader(new FileReader(file_location));
while((curr = br.readLine()) != null){
/* do something */
}
}
}
We must note that I DO NOT close the buffered reader.
Thanks.
A:
Basically the BufferedReader object itself is lost, there is no more way for you to access it.
But of course, the JVM might still hold some file handle for that open file. In that sense, you just create some kind of resource leak; and theoretically, when you do that very often you might run into real issues.
Further details then depend on the JVM itself; and the OS it is running on.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add text to beginning and end of a line in vim
I have a file with over 5000 lines. I need to add the following characters before and after the string, JAMES, for example:
'[^-_.*]JAMES[@-\.]'
Is this correct if I am trying to say that JAMES can be in the beginning of a line, or have dashes, underscores, any character 0 or more times before JAMES, and the @, dash, or period can be followed by JAMES?
I am using a list as a whitelist to print the emails that have a certain string (e.g. JAMES) to another file. So, it should take:
cat file.txt | egrep -e -i < whitelist | sort -u > newfile.txt
file.txt has email addresses separated by new line.
So far, I used the following command in vim:
'%s/^$/[^-_.*]'
However, all this did was add [^-_.*] to the end of the file.
A:
You probably want something like:
:g/.*/s//^[-_.]*&[-@.]*/
The .* looks for the whole line, and the :g/.*/ looks for that on every line in the file. The s//X&Y/ replaces what the g// found (the whole line) with X, what was found, and Y, except that the X is:
^[-_.]*
which means start of line followed by zero of more dashes, underscores or dots, and Y is:
[-@.]*
which means zero or more dashes, at signs, or dots. If you need that anchored to the end of line, add a $ after the *.
Note that the - must appear 'first' in a character class (unless another character must appear first, such as ^ to negate the character class, or ] to match a close square bracket).
| {
"pile_set_name": "StackExchange"
} |
Q:
Help With This Ring
Let ${\mathbb Q}[\sqrt 2, \sqrt 3]$ denote the smallest subring of ${\mathbb R}$ which contains ${\mathbb Q}, \sqrt 2$ and $\sqrt 3$. Show that this consists exactly of the real numbers of the form $a+b\sqrt2+c\sqrt 3+d\sqrt6$ where $a,b,c,d \in {\mathbb Q}$.
I'm given that it suffices to show that $(a)$ the set of elements of the form $a+b\sqrt2+c\sqrt 3+d\sqrt6$ does in fact form a ring and that $(b)$ every ring containing ${\mathbb Q},\sqrt 2$ and $\sqrt3$ has to contain all elements of the form $a+b\sqrt2+c\sqrt 3+d\sqrt6$.
$(a)$ is fine as we merely show that both $0$ and $1$ are of this form and that the addition, subtraction and multiplication of any two elements of this form can be rearranged back into this form. $(b)$ confused me, however. I looked at the solution which said:
"That $(b)$ is true follows from the fact that a ring is closed under addition and multiplication and that $\sqrt 2 \sqrt 3=\sqrt 6$"
I can't really see this, could anyone expand on it a little?
Thank you.
A:
Well, suppose you take any element of the form $a+b\sqrt{2} + c\sqrt{3} + d\sqrt{6} = a + b\sqrt{2} + c\sqrt{3} + (d\sqrt{2})\sqrt{3}$. Isn't this clearly in $\mathbb{Q}(\sqrt{2},\sqrt{3})$?
A:
Hint $ $ The smallest subring of $\,\Bbb R\,$ containing $\,\Bbb Q,\ r,\ s$ is $\,\Bbb Q[r,s],\,$ i.e. the set of all polynomials in $\,r,s\,$ with rational coefficients: clearly they form a ring, and must be contained in any subring containing $\,\Bbb Q,\ r,\ s.\,$ But since $\,r,s = \sqrt{2},\,\sqrt{3}\,$ satisfy $\,r^2 =2,\, s^2=3,\,$ all $\,r^k,s^k$ with $\,k\ge 2\,$ can be eliminated, hence every such polynomial is equal to one of the form $\ a + b r + c s + d rs.$
Remark $\ $ If you are familiar with evaluation homomorphisms then it is more instructive to view the above as follows: the universal way of adjoining $\,r,s\,$ to $\,\Bbb Q\,$ arises by specializing the adjunction of indeterminates $\,\Bbb Q[x,y]\,$ via the evaluation homomorphism $\,x,y\mapsto r,s.\,$ See here for further discussion on the universal view of ring adjunctions.
| {
"pile_set_name": "StackExchange"
} |
Q:
link to a url in a table constructed out of an array
How can I make the $v->Url part from the code below do this:
<a href="Url">Link text</a>
So my cell doesn't 'explode' in case of a long url?
foreach($array as $k=>$v){
print "
<tr>
<td>" . $v->Status . "</td>
<td>" . $v->Url . "</td>
</tr>";
}
A:
I assume that the link text is stored in a member var of $v. Try this:
foreach($array as $k=>$v){
print "
<tr>
<td>{$v->Status}</td>
<td><a href=\"{$v->Url}\">{$v->Text}</a></td>
</tr>";
}
Of course you'll have to rename $v->Text if the member has a different name in your application.
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove duplicate record if it contains certain value in a column
Let's say I have this table:
Student | Task | Result | Reason
Jim | 3 | Success | NULL
Jim | 4 | Success | NULL
John | 3 | Success | NULL
John | 2 | Failed | Task finished too late
Bill | 5 | Success | NULL
Bill | 7 | Failed | Not enough knowledge
Bill | 6 | Unknown | Asked StackOverflow to do his homework
I want to filter out the successful tasks of each Students here IF said student has one or more failed or unknown task. If they didn't fail/unknown at all I only need to see the successful ones.
So my expected result would be:
Student | Task | Result | Reason
Jim | 3 | Success | NULL
Jim | 4 | Success | NULL
John | 2 | Failed | Task finished too late
Bill | 7 | Failed | Not enough knowledge
Bill | 6 | Unknown | Asked StackOverflow to do his homework
I've tried using a group by and the MIN(Result) but then I end up with one record no matter the success/fail.
A:
This is a pretty simple use case of a window function referenced via a Common Table Expression (CTE):
Query
declare @t table(Student varchar(10),Task int,Result varchar(10),Reason varchar(50));
insert into @t values('Jim' ,3,'Success',NULL),('Jim' ,4,'Success',NULL),('John',3,'Success',NULL),('John',2,'Failed ','Task finished too late'),('Bill',5,'Success',NULL),('Bill',7,'Failed ','Not enough knowledge'),('Bill',6,'Unknown','Asked StackOverflow to do his homework');
with s as
(
select *
,sum(case when Result <> 'Success' then 1 else 0 end) over (partition by Student) as NonSuccesses
from @t
)
select Student
,Task
,Result
,Reason
from s
where Result <> 'Success'
or NonSuccesses = 0;
Output
+---------+------+---------+----------------------------------------+
| Student | Task | Result | Reason |
+---------+------+---------+----------------------------------------+
| Bill | 7 | Failed | Not enough knowledge |
| Bill | 6 | Unknown | Asked StackOverflow to do his homework |
| Jim | 3 | Success | NULL |
| Jim | 4 | Success | NULL |
| John | 2 | Failed | Task finished too late |
+---------+------+---------+----------------------------------------+
| {
"pile_set_name": "StackExchange"
} |
Q:
MAGENTO Catalog-Product-Custom Options Adding a custom option
I am very new to magento and I want to add a custom option to the Custom Options as described in the title. I think that I am already in the right file wich is : app->design->adminhtml->default->default->template->catalog->product->edit->options->option.phtml So now is my question, how do I add custom options in there so I can select some of my own code.
For further declaration i'll add a screen shot that might help explain what I mean to do.
http://prntscr.com/38nk5b I have to insert it like this because I don't have enough reputation yet to post a picture. Apoligy for that.
A:
You can add custom options from Magento admin.
Goto Admin->catalog->Manage Products
click on any products. In the left navigation at the bottom there is custom options tab.
Add custom options from there for each product.
OR
$option = Mage::getModel('catalog/product_option');
$option->setProduct($product);
$values = array(
//data here
);
$product->setHasOptions(1); //Hope you can get the $product
$option->addOption($values);
$option->saveOptions();
$product->addOption($option);
check this http://pravams.com/2011/05/25/magento-create-custom-options-dynamically/
| {
"pile_set_name": "StackExchange"
} |
Q:
Fast comparison of base64 encoded images
I have a logic that needs to compare base64 encoded images (JPEG and PNG) and check if they are the same.
The most basic approach to this is to compare the whole strings.
Since the images tend to be quite large, I was wondering if there was a faster and/or more memory efficient way to compare them. For example only comparing the first x characters, but base64 is done byte-by-byte that would only compare the first x bytes of the picture.
I'm not familiar with the inner workings of jpeg and png formats and the chance of the first bytes colliding (producing a false positive match), but if it's fairly low (like 1:10000) that would be acceptable.
Can a better comparsion be implemented?
Can a better comparison be implemented with a low chance of false positive matches?
Not that the basic comparsion is painfully slow, and since I need to read the whole strings into memory anyway for other operations, I will probably end up using a simple equality comparsion on them, I'm just interested in other possiblities.
EDIT:
Sorry for not clarifying this properly but this question was not meant to be about comparing image data. Lossy image formats make it painful anyway, and if the image is saved in a different format or with different options, it is different.
A:
As stated in comments an image will be compared only a few times (3 or 4 possible matches).
The low number of comparisons, probably doesn't make up for the cost of calculating a hash/digest.
I suggest to make a direct string comparison, if you have a match it will be only the length of the strings and if they don't match it will process only a few bytes until the first difference. If you want to avoid retrieving from the database all the records, you can choose to retrieve only the records that have the same length as the string to be compared.
| {
"pile_set_name": "StackExchange"
} |
Q:
when are algebras quiver algebras ?
Good Morning from Belgium,
I'm no stranger to the mantra that quiver-algebras are an extremely powerful tool (see for example the representation theory of finite dimensional algebras). But what is a bit unclear to me is what is known about what kind of algebras are quiver algebras. The first case I can prove is for graded rings with finite dimensional semisimple $A_0$. But what about the ungraded case (I'm pretty sure that it is also true for finite-dimensional algebras over an algebraically closed field for example).
Is there a larger generality possible ?
Answers (and references) are as always much appreciated !
A:
Louis, do you mean by a 'quiver-algebra' the path algebra of a quiver, or do you mean a quotient of a path algebra?
If the first, then I do not understand your comments. k[x,y] is graded with semi-simple part of degree zero but not a path algebra.
If you mean by quiver-algebra a quotient of a path algebra then the answer is simple : any finitely generated C-algebra will do as they are quotients of free algebras (path algebra of one vertex multiple loop quiver).
If you mean by quiver-algebra really the path algebra of a quiver, the answer is trickier.
If your algebra is finite dimensional (I'm always working over C) then the classification is : hereditary and basic (that is, all simples are one-dimensional). In that case, any hereditary is Morita equivalent to a path algebra. All this goes back to Gabriel.
If your algebra is infinite dimensional one has to be careful. Surely it must be formally smooth (that is, it has the lifting property for algebra maps through nilpotent ideals) and have a finite number of isoclasses of one-dimensional representations.
EDIT : Oops, if one has loops then there are of course infinitely many 1-dmls. I should have said that there are only finitely many components of 1-dml representations, all parametrized by affine spaces and such that one can pick one rep in each component to perform the trick with the structural morphism described below.
But that is not enough, take e.g. the groupalgebra of the modular group PSL(2,Z). It has 6 one-dimensionals but is not isomorphic to the 'obvious' quiver one would construct out of these 6 (arrows corresponding to extensions between the simples).
What one needs is that the structural morphism A --> End(SS) (where SS is the semi-simple on the finite number of one-dimls) splits so that A becomes a C^k-algebra. Then one can use formal smoothness of A and the path algebra with semi-simple part End(SS) and arrow part determined by M/M^2 (where M is the kernel of the structural morphism above) to prove that they are isomorphic. An argument like this appears in the paper by Cuntz and Quillen on noncommutative smoothness (they call a formally smooth algebra 'quasi-free').
| {
"pile_set_name": "StackExchange"
} |
Q:
List implementation that is both a Set a List (sequence)?
I'm in the position of extending LinkedList and implement Set, so that I have a list with no duplicates. I'm wondering if such an implementation doesn't exist already?
All I'm planning to do is to override the add(e) method to first look-up the element, and if present don't add it. Something like:
add(E){
if(get(E) == null) super.add(E);
}
A:
No Java implementation exists in the standard collections.
However, you can take a look at SetUniqueList from the Common Collections which may be along the lines of what you are looking for.
A:
Maybe LinkedHashSet does what you want. It keeps elements in (by default) insertion order.
It is not possible to implement both interfaces at the same time (at least if you want to follow the specifications for List and Set), because the hashCode definitions conflict.
Returns the hash code value for this list. The hash code of a list is defined to be the result of the following calculation:
hashCode = 1;
Iterator i = list.iterator();
while (i.hasNext()) {
Object obj = i.next();
hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
}
versus
Returns the hash code value for this set. The hash code of a set is defined to be the sum of the hash codes of the elements in the set, where the hashcode of a null element is defined to be zero. This ensures that s1.equals(s2) implies that s1.hashCode()==s2.hashCode() for any two sets s1 and s2, as required by the general contract of the Object.hashCode method.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to bind a Combobox's SelectedItem/Value/ValuePath from within a ListView
I have a ComboBox inside of a ListView's GridView. I am unable to get the ItemsSource and SelectedItem/Value/ValuePath bindings correct. Below is the smallest complete example demonstrating my problem:
Test_ComboBox_Binding.Views:
<Window x:Class="Test_ComboBox_Binding.Views.UserView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:m="clr-namespace:Test_ComboBox_Binding.Models"
xmlns:vm="clr-namespace:Test_ComboBox_Binding.ViewModels"
xmlns:s="clr-namespace:Test_ComboBox_Binding.Shared"
Title="UserView" Height="300" Width="300">
<Window.DataContext>
<vm:UserViewModel/>
</Window.DataContext>
<Window.Resources>
<DataTemplate x:Key="NameCellTemplate" DataType="m:cUser">
<TextBlock Text="{Binding Name}"></TextBlock>
</DataTemplate>
<DataTemplate x:Key="FavoriteColorCellTemplate" DataType="m:cUser">
<ComboBox ItemsSource="{Binding Colors, RelativeSource={RelativeSource AncestorType=vm:UserViewModel}}"
SelectedValue="{Binding FavoriteColor}"
SelectedValuePath="{Binding FavoriteColor}"
MinWidth="60"/>
</DataTemplate>
</Window.Resources>
<Grid>
<ListView ItemsSource="{Binding Users}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="100" CellTemplate="{StaticResource NameCellTemplate}"></GridViewColumn>
<GridViewColumn Header="Favorite Color" Width="100" CellTemplate="{StaticResource FavoriteColorCellTemplate}"></GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
Test_ComboBoxBinding.ViewModels:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Test_ComboBox_Binding.Models;
using Test_ComboBox_Binding.Shared;
namespace Test_ComboBox_Binding.ViewModels
{
class UserViewModel : cINotifyPropertyChangedBase
{
private ObservableCollection<ColorEnum> _colors;
public ObservableCollection<ColorEnum> Colors
{
get { return _colors; }
set { _colors = value; OnPropertyChanged("Colors"); }
}
private ObservableCollection<cUser> _users;
public ObservableCollection<cUser> Users
{
get { return _users; }
set { _users = value; OnPropertyChanged("Users");}
}
public UserViewModel()
{
Colors = new ObservableCollection<ColorEnum>(){ColorEnum.Red, ColorEnum.White, ColorEnum.Blue};
List<cUser> userList = new List<cUser>();
userList.Add(new cUser("Jack", Colors[0]));
userList.Add(new cUser("Jill", Colors[1]));
userList.Add(new cUser("James", Colors[2]));
Users = new ObservableCollection<cUser>(userList);
}
}
}
Test_ComboBox_Binding.Models:
using System.ComponentModel;
using Test_ComboBox_Binding.Shared;
using Test_ComboBox_Binding.ViewModels;
namespace Test_ComboBox_Binding.Models
{
class cUser : cINotifyPropertyChangedBase
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; OnPropertyChanged("Name"); }
}
private ColorEnum _favoriteColor;
public ColorEnum FavoriteColor
{
get { return _favoriteColor; }
set { _favoriteColor = value; OnPropertyChanged("FavoriteColor"); }
}
public cUser(string name, ColorEnum favoriteColor)
{
Name = name;
FavoriteColor = favoriteColor;
}
}
}
Test_ComboBox_Binding.Shared:
namespace Test_ComboBox_Binding.Shared
{
public enum ColorEnum
{
Red,
White,
Blue
}
}
Running the above code will produce the image below - a ListView with a ComboBox that contains the enumerated ItemsSource correctly, yet not displaying the SelectedValue for each cUser:
Please educate me on how to get the ItemsSource and SelectedItem/Value/ValuePath set correctly. I have scoured the interweb for informations and am unable to solve this problem. I must be missing some key understanding. Thank you!
A:
The AncestorType of a RelativeSource refers to the type of element in the visual tree. You could set it to ListBox and then bind to the Colors property of the DataContext of the ListBox, which is your view model.
You should also bind the SelectedItem property to the FavoriteColor source property. This should work:
<DataTemplate x:Key="FavoriteColorCellTemplate" DataType="m:cUser">
<ComboBox ItemsSource="{Binding DataContext.Colors, RelativeSource={RelativeSource AncestorType=ListBox}}"
SelectedItem="{Binding FavoriteColor}"
MinWidth="60"/>
</DataTemplate>
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS Div Chevron inconsistencies with firefox
I have this code for a css chevron. It works well in chrome but in firefox, it has these separations in the div where in chrome these don't really exist.
.sidenavChevron {
border-style: solid;
border-width: 6px 6px 0 0;
content: '';
height: 12px;
width: 12px;
top: 15px;
right: 20px;
display: inline-block;
transform: rotate(45deg);
transition: var(--delay);
position: relative;
color: #f1f1f1;
float: right;
}
What should I do?
A:
You can use a box shadow instead:
.sidenavChevron {
border-style: solid;
border-width: 6px 6px 0 0;
height: 12px;
width: 12px;
top: 15px;
right: 20px;
display: inline-block;
transform: rotate(45deg);
transition: var(--delay);
position: relative;
left: 30px;
}
.sidenavChevron2 {
box-shadow: 6px -6px 0 currentColor;
height: 18px;
width: 18px;
top: 15px;
right: 20px;
display: inline-block;
transform: rotate(45deg);
transition: var(--delay);
position: relative;
left: 40px;
}
<span class="sidenavChevron"></span>
<span class="sidenavChevron2"></span>
which gives you a different kind of problem:
which you can hide with a clip or equivalent:
.sidenavChevron {
display: inline-block;
height: 25.46px; /* √2 * 18 */
overflow: hidden;
position: relative;
width: 16.97px; /* √2/2 * (18 + 6) */
}
.sidenavChevron::before {
box-shadow: 6px -6px 0 currentColor;
content: '';
height: 18px;
left: -9.5px; /* -18 + √2/2 * (18 - 6) */
position: absolute;
right: 20px;
top: 50%;
transform: rotate(45deg);
transform-origin: right top;
transition: var(--delay);
width: 18px;
}
<span class="sidenavChevron"></span>
… how about a nice SVG instead?
| {
"pile_set_name": "StackExchange"
} |
Q:
displaying an image from sqlite table
I was storing an image in a sqlite table as blob data and displaying it using the following code:
self.myImage.image = [[[UIImage alloc] initWithData:recipe.image] autorelease];
I'm now using the image file name in the sqlite fields instead and storing the image on the filesystem. what would the code be to display it that way? I'm having a hard time figuring it out.
normally to display an image from the filesystem I'd use:
UIImage *image = [UIImage imageNamed:@"something.png"];
in this case I have to grab the string that's in the table field/attribute.
thanks in advance.
A:
You can load UIImage with absolute filepath by following API.
+ (UIImage *)imageWithContentsOfFile:(NSString *)path;
+(UIImage *)imageNamed:(NSString *)name will look for an image from application's main bundle. In other word, it will look for an image from Resources.
Editted:
You said that you stored the image on the filesystem. So, I think you can retrive the absolute filepath of image from sqlite database, doesn't it?
NSString *imgPath;
/// get imgPath from sqlite database
...
/// get the image by filepath
self.myImage.image = [UIImage imageWithContentOfFile:imgPath];
And, my question is how do you store the image on the filesystem.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add line numbers to a UITextView?
I want to add line numbers to my UITextView.
Do I have to write my own UI-Element, or is there an other solution?
A:
I accomplished this by subclassing UIView and overriding the drawRect: method like so:
#define TXT_VIEW_INSETS 8.0 // The default insets for a UITextView is 8.0 on all sides
@implementation NumberedTextView
@synthesize lineNumbers;
@synthesize delegate;
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self setContentMode:UIViewContentModeRedraw];
internalScrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
[internalScrollView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[internalScrollView setBackgroundColor:[UIColor clearColor]];
[internalScrollView setClipsToBounds:YES];
[internalScrollView setScrollsToTop:YES];
[internalScrollView setContentSize:self.bounds.size];
[internalScrollView setContentMode:UIViewContentModeLeft];
[internalScrollView setDelegate:self];
[internalScrollView setBounces:NO];
internalTextView = [[UITextView alloc] initWithFrame:self.bounds];
[internalTextView setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[internalTextView setAutocorrectionType:UITextAutocorrectionTypeNo];
[internalTextView setSpellCheckingType:UITextSpellCheckingTypeNo];
[internalTextView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[internalTextView setBackgroundColor:[UIColor clearColor]];
[internalTextView setClipsToBounds:YES];
[internalTextView setScrollsToTop:NO];
[internalTextView setContentMode:UIViewContentModeLeft];
[internalTextView setDelegate:self];
[internalTextView setBounces:NO];
[internalScrollView addSubview:internalTextView];
[self addSubview:internalScrollView];
}
return self;
}
- (void)drawRect:(CGRect)rect {
if (self.lineNumbers) {
[[internalTextView textColor] set];
CGFloat xOrigin, yOrigin, width/*, height*/;
uint numberOfLines = (internalTextView.contentSize.height + internalScrollView.contentSize.height) / internalTextView.font.lineHeight;
for (uint x = 0; x < numberOfLines; ++x) {
NSString *lineNum = [NSString stringWithFormat:@"%d:", x];
xOrigin = CGRectGetMinX(self.bounds);
yOrigin = ((internalTextView.font.pointSize + abs(internalTextView.font.descender)) * x) + TXT_VIEW_INSETS - internalScrollView.contentOffset.y;
width = [lineNum sizeWithFont:internalTextView.font].width;
// height = internalTextView.font.lineHeight;
[lineNum drawAtPoint:CGPointMake(xOrigin, yOrigin) withFont:internalTextView.font];
}
CGRect tvFrame = [internalTextView frame];
tvFrame.size.width = CGRectGetWidth(internalScrollView.bounds) - width;
tvFrame.size.height = MAX(internalTextView.contentSize.height, CGRectGetHeight(internalScrollView.bounds));
tvFrame.origin.x = width;
[internalTextView setFrame:tvFrame];
tvFrame.size.height -= TXT_VIEW_INSETS; // This fixed a weird content size problem that I've forgotten the specifics of.
[internalScrollView setContentSize:tvFrame.size];
}
}
#pragma mark - UITextView Delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
[self setNeedsDisplay];
return YES;
}
- (void)textViewDidChange:(UITextView *)textView {
[self setNeedsDisplay];
}
- (void)textViewDidChangeSelection:(UITextView *)textView {
[self setNeedsDisplay];
}
#pragma mark - UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
[self setNeedsDisplay];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing the URL of an HTTPS server
Hello Stack Overflowers,
I am a newbie to servers (and Linux in general). I have recently made an HTTP server on Kali Linux (formerly BACKTRACK). When I type in http://localhost/ it works and my HTML page shows up. BUT I want to change the URL to be https://localhost/ The server software that I am using is Apache.
Thank you for your help in advance.
Thomas
A:
https://localhost means, that your Computer does not fetch the site from the internet. You can test this by trying to view your site while offline - this will work.
If you want another domain name, you have to put your site on the internet.
Find a hosting provider, make a contract, choose a name for your site that's not already taken, load up your page.
Be aware that this might cost something.
If you want to change the name only locally, open the file /etc/hosts
as superuser.
It should look like
# Comments Here
127.0.0.1 localhost
# End of /etc/hosts
Add
# Comments Here
127.0.0.1 localhost yourdomain.name
# End of /etc/hosts
Note that your site then can only be viewed on your computer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Any advice on a good Respawn system for pathfinder
I am searching for a good respawn rules set that I can apply to the next Pathfinder game I have in mind. I believe someone already had this idea, but I can't find anything on the subject. So here is my version of what I think will work best.
As in games like Dark Souls, World of Warcraft, or Guild Wars, the player is not permanently punished by death if he is beaten in combat. It is a part of the game that the player accepts and uses to its advantage in some cases. In fact, some even consider death in games as a design flaw.
Respawn system notes:
it should in no cases replace the utility of any resurrection spell
it must not impose permanent changes to the characters (like leaving the character blind, or missing a leg, or having a permanent level drop).
players must still be scared of dying while not making it the end of the story for that beloved companion.
it must be applied only to a certain pool of characters: the players and some NPCs.
I've also heard of systems where a GM manages character death by making a private session with the player(s) that died, and he/they must go through the underworld/limbo to get revived for the next session.
Here's my best guess until now:
Punishment
When a player character dies, they roll a d100, as though they've fumbled or received a severe critical. This indicates the intensity of the punishment the character will get, and will depend on the way the character died (overkill and the player dies from being at -35hp; falling from a cliff; dying from unstabilized blood loss at -10hp, drowning, etc.) in the form of injury, equipment loss/damage, or sickness.
Questions that I came up with
How many times can they resurrect?
should they be able to rise an infinite number of times?
or should they gather items that must be spent each time someone dies? (phoenix feather)
should they need a particular item for each character, but that is not lost upon use? (lich's phylactery)
Where should they "respawn"?
in the nearest cemetery in ghost form and they must retrieve their corpse to complete the ritual?
directly where they died?
on a check point that I decide on the fly?
on a point that I clearly indicate and whose location the players are aware of?
In all cases, it must not be too far from where they died, or they will have a hard time getting back to the group. And if more than one player dies, should they spawn at the same place, or have different resurrection points?
I am seeking advice from anyone having some sort of real-use experience with this kind of system and/or rules set for Pathfinder.
Motives
I want to remove the idea that "death is final" (and no resurrection is possible in game). I'm a video game player, as are most of my players, so it is a sort of compromise between finality and save/load that I seek; very much like Dark Souls offers in its gaming experience, as its world was built around it.
Like mxyzplk said, I plan to make a respawn/revive system to go along with my world, so I expect answers that will help me decide which rules will fit best to punish, but not annoy, my players. (For example, by breaking their weapons each time, or making them spawn 200km away.)
I am aware of the existing mechanics for resurrection, but they are not what I want. These use permanent punishments like negative levels and have restrictions I'm not interested in (like requiring a level 7 cleric). I would prefer to use an existing respawn ruleset that has been proven acceptable in execution, but if none exist, then I will most likely make my own.
The Context
To place this in context, I plan to have the players be in a religious order (LG, LN, N and/or CN) and have them fight for its power/control/influence in a big city/region/continent. Inspirations may come from Assassin's Creed, the Crusades, any religious war-movies/series/stories. It must be in the Dark Ages (500-1500) so I can place the fantasy elements we all love.
I know its still vague, but I plan to work with the system that I will build (and release, if there is some interest) to make the main general plot.
A:
If you remove death as a consequence, institute a new threat to threaten loss with. I used a time limit with infinite respawns and world-reset on party TPK with player precognition-through-death allowed.
Happy Groundhog's Day from daydreamsofmelissa
These insights were taken from my run of a Fourthcore game. Instead of death being the threat, I made time be the ultimate arbiter of failure. I had a large red timer counting down 3 hours. At the end of 3 hours, the players would fail if they had not achieved their goal.
Therefore, if you go with this stylistic mode, every adventure has a goal. When a TPK is suffered, the adventure resets. Death, therefore, is a brief timeout that absolutely allows kibitzing and observation on the player end. Suicide is certainly allowed.
This changes the challenge to a players-versus-game challenge, making the characters almost secondary. But it does provide an interesting and engaging challenge that is appropriate for high-risk high-lethality environments.
It's also quite quite fun to kill the same person 16 times in 3 hours.
Note, that to some people, this is an especial kind of hell. Make sure you have group buy-in first and be prepared for a fascinatingly distorted gameplay as players use their "foreknowledge" to subvert initial obstacles. This precognition by death is absolutely allowed because they have to solve all the puzzles and the combats every time. A TPK is not nice. It costs them time. Be prepared for shortcuts and subverting many combats. This style absolutely encourages that style of play.
To have this work in a campaign framework, allow "checkpoints" to occur that provide world-reset to checkpoint. The timer is important, but instead of "you lose." have it "your antagonists achieve an objective." So it's a back and forth between precognitive through trial and error players and... inexorably advancing antagonists.
A:
I played in a short campaign that was literally us versus the Monstrous Compendium. We created a simple system: Saving or restoring the game required sacrificing a magic item. Since the randomized haul from each randomized monster usually included at least one magic item, it worked well enough in practice for the half-dozen sessions we ended up playing.
A:
My group spent a bit of time experimenting with a system based off of bionoids (http://www.spelljammer.org/monsters/conversions/Bionoid.html):
a component of each character is nigh-indestructible (ie, the bionoid gem).
the full character can be restored from the component
various degrees of destruction warrant various degrees of effort for restoring the character
the indestructible component has to be retrieved before respawn can occur
We had characters carrying around a limited resource that can be used to regenerate/respawn dead team-mates, and the resource would deplete at higher rates depending on the amount of damage a character suffered when killed (ie, if their body melted in a pool of acid, the resource would be at maximum depletion, while death by poison would be minimum depletion).
The gem had to be retrieved/within a short range of the restorative resource, for respawn to be possible, making more obvious type of deaths (jumping off a cliff) more costly in time and resources.
The system seemed to work well - characters dying in basic combat could, mostly, be respawned (usually not until combat was over, and with some penalty to their reward for the encounter, but those are customizable rules depending on your goals), and obviously silly behaviour was discouraged (no jumping off a cliff for fun - only if you have good reason to believe there's something to get at the bottom).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add timestamp to the log file name when we are using size based log files in log4j?
I want to create size based log files. I am setting the following entry in the log4j.properties file:
log4j.appender.UserFileAppenderDebug=org.apache.log4j.RollingFileAppender
log4j.appender.UserFileAppenderDebug.Threshold=TRACE
log4j.appender.UserFileAppenderDebug.File=../log/coordinator-debug.log
log4j.appender.UserFileAppenderDebug.MaxFileSize=1KB
log4j.appender.UserFileAppenderDebug.MaxBackupIndex=7
log4j.appender.UserFileAppenderDebug.layout=org.apache.log4j.PatternLayout
log4j.appender.UserFileAppenderDebug.layout.ConversionPattern=%m%n
multiple log files are created based on size but with following names:
-rw-r--r-- 1 root root 32 Aug 6 11:28 coordinator-debug.log
-rw-r--r-- 1 root root 1.1K Aug 6 11:28 coordinator-debug.log.1
-rw-r--r-- 1 root root 1.1K Aug 6 11:28 coordinator-debug.log.2
-rw-r--r-- 1 root root 1.2K Aug 6 11:28 coordinator-debug.log.3
-rw-r--r-- 1 root root 1.1K Aug 6 11:28 coordinator-debug.log.4
-rw-r--r-- 1 root root 1.1K Aug 6 11:28 coordinator-debug.log.5
-rw-r--r-- 1 root root 1.1K Aug 6 11:28 coordinator-debug.log.6
-rw-r--r-- 1 root root 1.1K Aug 6 11:28 coordinator-debug.log.7
I would like to have the file name as follows
coordinator-debug.log.2013-08-01 11:28:39, 232
I would appreciate if you please share your comments/suggestions.
Thanks.
A:
Have you tried:
log4j.appender.UserFileAppenderDebug.DatePattern='.'yyyy-MM-dd_HH-mm-ss
(remember that your filename will not allow : e.g 11:28:39, you will need to replace them to e.g. 11-28-39 )
(edited)
Sorry, I thought you used the *Daily*RollingFileAppender...
There are RollingPolicys that you might use to get filename pattern for the RollingFileAppender.
E.g.
log4j.appender.UserFileAppenderDebug.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.UserFileAppenderDebug.RollingPolicy.FileNamePattern=../log/coordinator-debug.log.%d{yyyy-MM-dd-HH-mm-ss}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to edit the label of a chart in Excel?
As shown in the figure below, the horizontal axis is automatically produced by the Excel and labeled as 1,2,...,n. What I wanna to do is to change these labels into such a form as case A, case B,..., etc.
I tried to edit the chart, but all failed.
A:
There are two ways you can set the x-axis category labels for the chart.
One way is to put your labels into a range on your worksheet and then include them in the data source for your chart. This is usually done when you create the chart. If the labels are entered in the row above the chart data, Excel will recognize them as x-axis labels. The graphic below shows an example of the setup.
Then you would select the entire range with both labels & data--cells C8:E11--in this case, and insert your chart, with results as shown. This method works with all versions of Excel.
The second way involves editing the chart's settings after it has been created. Step-by-step, here's what's involved (This may work in older versions, but I did it in Excel 2010).
Select your chart and then pick the Chart Tools/Design options on the ribbon.
Then choose Select Data from the options (still on the ribbon).
The chart data range is shown at the top of the dialog box that comes up, with a box below left to make changes to the chart settings for the data series and a box at below right to make changes to the x-axis labels. The latter box will list the "1", "2", etc. numbers that you want to change.
Hit the edit button for the right-hand box (Horizontal Category (Axis) Labels), and you will be prompted to enter an axis label range.
Instead of selecting a range, though, just enter the labels that you want to see on the x-axis, separated by commas, like so:
Press OK, and then again when the Select Data Source dialogue reappears, and it's done.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access android resource attributes
I want to access
getContext().obtainStyledAttributes(attrs,android.R.styleable.TextView)
but I am having error in styleable. There is no styleable available in android.R .
I will use this value in my compound view.
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
init(null);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(attrs);
}
private void init(AttributeSet attrs) {
if (attrs != null && !isInEditMode()) {
TypedValue typedValue = new TypedValue();
int[] textSizeAttr = new int[] { android.R.attr.textSize };
int indexOfAttrTextSize = 0;
TypedArray a = getContext().obtainStyledAttributes(typedValue.data, textSizeAttr);
int textSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
a.recycle();
}
}
}
layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="hgyanani.customcompoundview.MainActivity">
<hgyanani.customcompoundview.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="16sp" />
</RelativeLayout>
A:
You can try like this:
private void init(AttributeSet attrs) {
if (attrs != null && !isInEditMode()) {
int[] attrsArray = new int[] {
android.R.attr.textSize, // 0
};
TypedArray a = getContext().obtainStyledAttributes(attrs, attrsArray);
int textSize = a.getDimensionPixelSize(0 /*index of attribute in attrsArray*/, View.NO_ID);
}
}
textSize will return the value in pixel.
If you want the exact value of textsize in sp then in the constructor of your custom view (the one that takes in the AttributeSet), you can retrieve the attributes from Android's namespace as such:
String xmlProvidedSize = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "textSize");
The value of the xmlProvidedSize will be something like this "16.0sp" and maybe with little bit of String editing you can just extract the numbers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Loadbalancing logic in service resource
In my kubernetes cluster, there is a lot of inter-service communication. I have also enabled horizontal pod autoscaler and we use service resource for all these services.
I need to understand how does the service resource loadbalance the request across the pods.
I did read about SessionAffinity but it only supports ClientIP, if you are not using an Ingress resource.
Want to know if the service can loadbalance based on the load (in terms of cpu, memory, etc.) on a particular pod. In short, does sessionAffinity config support anything other than ClientIP. I dont want to bring in an Ingress resource, as these are not external facing requests, these are inter-service communication.
Thanks in advance.
A:
In short, does sessionAffinity config support anything other than ClientIP
No, it does not. See the model definition here for v1.SessionAffinityConfig: Nor will it; I already feel that sessionAffinity is out of a Service's scope, I'm surprised it exists at all.
You're going to want to use some kind of layer in front of your service if you want to have more control of your connections. There are plenty of Service Meshes that might solve your problem (see isito or Linkerd )
You could also roll your own solution with nginx and send your requests for that service to the nginx pod.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to send an angular param to an onclick event?
here we go...
I have a controller
$scope.selectedScript = {};
$scope.selectedScript.scriptId = null;
$scope.selectScript = function(script, index) {
$scope.selectedScript = script;
$scope.selectedRow = index;
myAppFactory.updateTextArea(script).success(
function(data) {
$scope.selectedScript = data;
});
};
$scope.getSelectedClass = function(script) {
if ($scope.selectedScript.scriptId != undefined) {
if ($scope.selectedScript.scriptId == script.scriptId) {
return "selected";
}
}
return "";
};
i have a html page
<label>Script ID:</label>
<input name="scriptId"
type="text"
id="scriptId"
ng-model="selectedScript.scriptId"
ng-disabled="true"
value="{{selectedScript.scriptId}}" />
and now thx to IARKI i have this
<script type="text/javascript">
function goTo (){
var param1 = angular.element(document.querySelector('.scriptId')).scope.selectedScript.scriptId;
location.href=this.href + '?scriptId='+param1;
return false;
}
</script>
<a href="http://localhost:8080/DSS-war/debug.html" target="_blank" onclick="goTo()">Debug</a>
I have also a list of scripts in a table
<table class="scripts" name="tableScript" arrow-selector>
<tr bgcolor="lightgrey">
<th>Script ID</th>
<th>File Name</th>
</tr>
<tr
ng-repeat="s in scripts | filter:searchField | orderBy:'scriptId'"
ng-click="selectScript(s, $index)" ng-class="getSelectedClass(s)">
<td>{{s.scriptId }}</td>
<td>{{s.fileName }}</td>
</tr>
</table>
Then i press the link above, and a new tab appears, but the link is still the
http://localhost:8080/DSS-war/debug.html
but i need it to open in a new tab as well as to be like this:
http://localhost:8080/DSS-war/debug.html?scriptId=1
http://localhost:8080/DSS-war/debug.html?scriptId=2
http://localhost:8080/DSS-war/debug.html?scriptId=12
and so on...with numbers
any idea?
And it has to be the onclick function, not the ng-click
I know how it works on ng-click, but i need to make it work on onclick...
and now i get this from the chrome debugger:
Uncaught TypeError: Cannot read property 'scriptId' of undefined
in the line
var param1 = angular.element(document.querySelector('.scriptId')).scope.selectedScript.scriptId;
A:
You can try to access angular scope using pure javascript
<script type="text/javascript">
function goTo (){
var param1 = angular.element("#scriptId").scope().selectedScript.scriptId;
location.href=this.href + '?scriptId='+param1;
return false;
}
</script>
<a href="http://localhost:8080/DSS-war/debug.html" target="_blank" onclick="goTo()">Debug</a>
Update
Useless code but I hope it will help you
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>My application</title>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<label>Script ID:</label>
<input name="scriptId" type="text" id="scriptId" ng-model="selectedScript.scriptId" ng-disabled="true">
<button onclick="generateID()">Set code</button>
<a href="#" onclick="goTo()">Debug</a>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script type="text/javascript">
function generateID() {
var code = Math.floor(Math.random() * 20) + 1;
document.getElementById('scriptId').setAttribute('value', code.toString());
}
function goTo() {
var scope = angular.element(document.querySelector('#scriptId')).scope();
scope.$apply(function () {
scope.selectedScript.scriptId = document.querySelector('#scriptId').getAttribute('value');
});
scope.changeURl();
}
angular.module('myApp', [])
.controller('myCtrl', function ($scope, $window) {
$scope.selectedScript = {};
console.log('We are in controller');
$scope.changeURl = function () {
$window.open('http://localhost:8080/DSS-war/debug.html?scriptId=' + $scope.selectedScript.scriptId, '_blank');
}
});
</script>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add price upon checking a check_box in Ruby on Rails
I am working on a paid ad job board, and am using #Payola-Payments (Implementation of Stripe Payment Processor with Rails Application) to charge each job post on the app..
This is what I like to do:
When a check_box is checked, I want the price the application will
deduct to change from default set price in my Jobs table, to the
addition of the check_box worth.
Pictorial explanation of what I like to do:
Upon checking the box, it's suppose to add $20 to my default price in jobs table.
schema.rb
Note: A price default of $200 in cents (i.e. 20000) is set in my jobs table. The reason being what is required in Payola-payments documentation. So anytime anyone posts job advert, $200 will be deducted from his/her credit card by Stripe.
ActiveRecord::Schema.define(version: 20160827065822) do
create_table "jobs", force: :cascade do |t|
t.string "title", limit: 255
t.string "category", limit: 255
t.string "location", limit: 255
t.text "description"
t.text "to_apply"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name", limit: 255
t.integer "price", default: 20000
t.string "permalink", limit: 255
t.string "stripeEmail", limit: 255
t.string "payola_sale_guid", limit: 255
t.string "email", limit: 255
t.string "website", limit: 255
t.string "company_name", limit: 255
t.boolean "highlighted"
end
end
What I have done to solve this:
I defined a method inside my model (job.rb) called price_modification and called before_save on it, such that my model looks like this code below but didn't work:
class Job < ActiveRecord::Base
include Payola::Sellable
before_save :price_modification
def price_modification
price
end
def price_modification=(new_price)
if :highlighted == t
self.price += (price + 2000)
else
self.price = new_price
end
end
end
Thanks in advance.
Am using Ruby 2.2.4 and Rails 4.2.5.1
A:
price_modification is an accessor method that makes no changes.
The before_save :price_modification is calling the price_modification method which only returns the price value but makes no changes.
I'm not certain what you're looking for but my best guess is something like this:
class Job < ActiveRecord::Base
...
# Use before_create instead of before_save so
# apply_extra_fees is *not* called multiple times.
before_create :apply_extra_fees
HIGHLIGHT_FEE_IN_CENTS = 2000
def apply_extra_fees
if highlighted?
self.price += HIGHLIGHT_FEE_IN_CENTS
end
end
...
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Selecting from database using SQLite - 'No such column'
In my application I want to bring up modules depending on who is logged into the application.
This works perfectly if I use test data such as simple data, eg, 1 as username and 1 as password, however when I use real life test data, eg C343, it throws the error saying there is no such column, even though in logcat it shows it in the database.
Here is how I select the information from the database:
in DB.java
public class DB extends SQLiteOpenHelper {
public static final int db_version = 1;
//Student Table
public static final String Table = "Students";
public static final String Student_ID = "Student_ID";
public static final String Student_Name = "Student_Name";
public static final String Student_Password = "Student_Password";
public static final String Student_Gender = "gender";
public static final String Student_Age = "age";
public static final String Student_Course = "course";
public static final String Modules1 = "modules1";
public static final String Modules2 = "modules2";
public static final String Modules = "modules";
public static final String CNumber = "CNumber";
//Modules Table
public static final String Table2 = "Modules";
public static final String Module_ID = "moduleid";
public static final String Module_Name = "modulename";
public static final String Module_Lectureroom = "modulelectureroom";
public static final String Module_Seminarroom = "moduleseminarroom";
public static final String Module_Lecturer = "modulelecturer";
public static final String Module_Group = "modulegroup";
public static final String Module_Lecturetime = "modulelecturetime";
public static final String Module_Seminartime = "moduleseminartime";
public static final String Module_Lecturedate = "modulelecturedate";
public static final String Module_Seminardate = "moduleseminardate";
public boolean checker = false;
public DB(Context context) {
super(context, tableColumns.Database, null, db_version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + Table);
Log.d("DB", "Creating table...");
//Students Table
db.execSQL("CREATE TABLE " + Table + "(" +
Student_ID + " INTEGER PRIMARY KEY, " +
Student_Name + " TEXT, " +
Student_Password + " TEXT, " +
Student_Age + " TEXT, " +
Student_Gender + " TEXT, " +
Student_Course + " TEXT, " +
Modules1 + " TEXT, " +
Modules2 + " TEXT, " +
Modules + " TEXT, " +
CNumber + " TEXT)");
Log.d("DB", "Student Table Created");
//Modules Table
db.execSQL("DROP TABLE IF EXISTS " + Table2);
db.execSQL("CREATE TABLE " + Table2 + "(" +
Module_ID + " INTEGER PRIMARY KEY, " +
Module_Name + " TEXT, " +
Module_Lectureroom + " TEXT, " +
Module_Seminarroom + " TEXT, " +
Module_Lecturer + " TEXT, " +
Module_Group + " TEXT, " +
Module_Lecturetime + " TEXT, " +
Module_Seminartime + " TEXT, " +
Module_Lecturedate + " TEXT, " +
Module_Seminardate + " TEXT)");
Log.d("DB", "Module Table Created");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Table);
db.execSQL("DROP TABLE IF EXISTS " + Table2);
onCreate(db);
}
public boolean Login(String username, String password) throws SQLException
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor mCursor = db.rawQuery("SELECT * FROM " + Table + " WHERE CNumber=? AND Student_Password=?", new String[]{username,password});
if (mCursor != null) {
if(mCursor.getCount() > 0)
{
checker = true;
return true;
}
}
return false;
}
public void createstudents()
{
insertStudent("Matt", "123", 22, "Male", "Computing", "Digital Security", "Mod2", "Mod3", "C3438525");
insertStudent("Charlie", "Test", 19, "Male", "Sport Science", "Biomech Analysis", "Meas & Eval for Phsio", "Prof Dev", "C33429960");
insertStudent("Amber", "Test", 20, "Female", "Travel & Tourism", "Work based learning", "Sustainable Tourism", "Tourism Operations", "C3399607");
insertStudent("1", "1", 1, "1", "1", "1", "1", "3", "2");
insertStudent("Test", "Test", 2, "Test", "Test", "Test", "Test", "Test", "C343Test");
Log.d("Students", "Created");
}
public void createmodules()
{
insertModules("Digital Security", "CAG05", "JG202", "Michael Kemp", "A", "15:00PM", "11:00AM", "Tuesday", "Tuesday");
Log.d("Modules", "Created");
}
public void reset(SQLiteDatabase db)
{
db.execSQL("DROP TABLE IF EXISTS " + Table);
onCreate(db);
}
public List<tableStudents> getData() {
List<tableStudents> studentList = new ArrayList<tableStudents>();
// Select All Query
String selectQuery = "SELECT * FROM " + Table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tableStudents student = new tableStudents();
student.name = cursor.getString(1);
student.password = cursor.getString(2);
student.age = Integer.parseInt(cursor.getString(3));
student.gender = cursor.getString(4);
student.course = cursor.getString(5);
student.modules = cursor.getString(6);
student.modules1 = cursor.getString(7);
student.modules2 = cursor.getString(8);
student.cnumber = cursor.getString(9);
studentList.add(student);
} while (cursor.moveToNext());
}
// return contact list
return studentList;
}
public List<tableStudents> getStudentsModules(String username) {
List<tableStudents> studentModules = new ArrayList<tableStudents>();
// Select All Query depending on who is logged in.
String selectQuery = "SELECT " + Modules1 + ", " + Modules2 + ", " + Modules + " FROM " + Table + " WHERE " + CNumber + " = " + username;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tableStudents student = new tableStudents();
student.modules = cursor.getString(0);
student.modules1 = cursor.getString(1);
student.modules2 = cursor.getString(2);
studentModules.add(student);
} while (cursor.moveToNext());
}
// return contact list
return studentModules;
}
public List<tableModules> getModules() {
List<tableModules> moduleList = new ArrayList<tableModules>();
// Select All Query
String selectQuery = "SELECT * FROM " + Table2;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tableModules module = new tableModules();
module.modulename = cursor.getString(1);
module.modulelectureroom = cursor.getString(2);
module.moduleseminarroom = cursor.getString(3);
module.modulelecturer = cursor.getString(4);
module.modulegroup = cursor.getString(5);
module.modulelecturetime = cursor.getString(6);
module.moduleseminartime = cursor.getString(7);
module.modulelecturedate = cursor.getString(8);
module.moduleseminardate = cursor.getString(9);
moduleList.add(module);
} while (cursor.moveToNext());
}
// return contact list
return moduleList;
}
public boolean insertStudent(String name, String password, int age, String gender, String course, String modules, String modules1, String modules2, String CNumb) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Student_Name, name);
contentValues.put(Student_Gender, gender);
contentValues.put(Student_Age, age);
contentValues.put(Student_Password, password);
contentValues.put(Student_Course, course);
contentValues.put(Modules, modules);
contentValues.put(Modules1, modules1);
contentValues.put(Modules2, modules2);
contentValues.put(CNumber, CNumb);
db.insert(Table, null, contentValues);
Log.d("DB", "Students Inserted Successfully");
return true;
}
public boolean insertModules(String modulename, String modulelectureroom, String moduleseminarroom, String modulelecturer, String modulegroup, String modulelecturetime, String moduleseminartime, String modulelecturedate, String moduleseminardate) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Module_Name, modulename);
contentValues.put(Module_Lectureroom, modulelectureroom);
contentValues.put(Module_Seminarroom, moduleseminarroom);
contentValues.put(Module_Lecturer, modulelecturer);
contentValues.put(Module_Group, modulegroup);
contentValues.put(Module_Lecturetime, modulelecturetime);
contentValues.put(Module_Seminartime, moduleseminartime);
contentValues.put(Module_Lecturedate, modulelecturedate);
contentValues.put(Module_Seminardate, moduleseminardate);
db.insert(Table2, null, contentValues);
Log.d("DB", "Modules Inserted Successfully");
return true;
}
}
and it is then called in MainActivity.java, saving the modules to strings.
List<tableStudents> studentModules = db.getStudentsModules(sessionName);
for (tableStudents session: studentModules)
{
//Save modules to string
String module1 = session.modules.toString();
String module2 = session.modules1.toString();
String module3 = session.modules2.toString();
}
This is the Logcat for when I log in with C343Test as the username and Test as the password:
02-22 00:24:15.214: D/Username+PW Combos(2593): Username: C343Test Password: Test
02-22 00:24:15.214: D/Digital Security(2593): Michael Kemp
02-22 00:24:15.302: E/SQLiteLog(2593): (1) no such column: C343Test
02-22 00:24:15.322: D/AndroidRuntime(2593): Shutting down VM
02-22 00:24:15.333: E/AndroidRuntime(2593): FATAL EXCEPTION: main
02-22 00:24:15.333: E/AndroidRuntime(2593): Process: com.example.project, PID: 2593
02-22 00:24:15.333: E/AndroidRuntime(2593): java.lang.RuntimeException: Unable to resume activity {com.example.project/com.example.project.MainActivity}: android.database.sqlite.SQLiteException: no such column: C343Test (code 1): , while compiling: SELECT modules1, modules2, modules FROM Students WHERE CNumber = C343Test
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2989)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3020)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.app.ActivityThread.access$800(ActivityThread.java:151)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.os.Handler.dispatchMessage(Handler.java:102)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.os.Looper.loop(Looper.java:135)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.app.ActivityThread.main(ActivityThread.java:5257)
02-22 00:24:15.333: E/AndroidRuntime(2593): at java.lang.reflect.Method.invoke(Native Method)
02-22 00:24:15.333: E/AndroidRuntime(2593): at java.lang.reflect.Method.invoke(Method.java:372)
02-22 00:24:15.333: E/AndroidRuntime(2593): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
02-22 00:24:15.333: E/AndroidRuntime(2593): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
02-22 00:24:15.333: E/AndroidRuntime(2593): Caused by: android.database.sqlite.SQLiteException: no such column: C343Test (code 1): , while compiling: SELECT modules1, modules2, modules FROM Students WHERE CNumber = C343Test
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
02-22 00:24:15.333: E/AndroidRuntime(2593): at com.example.project.DB.getStudentsModules(DB.java:160)
02-22 00:24:15.333: E/AndroidRuntime(2593): at com.example.project.MainActivity.onResume(MainActivity.java:79)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.app.Activity.performResume(Activity.java:6076)
02-22 00:24:15.333: E/AndroidRuntime(2593): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2978)
02-22 00:24:15.333: E/AndroidRuntime(2593): ... 11 more
A:
You have to increase the db version if you have modified the tables in any way, otherwise onUpdate will not be called. And you have to use quotes if you are doing string comparision:
String selectQuery = "SELECT " + Modules1 + ", " + Modules2 + ", " + Modules + " FROM " + Table + " WHERE " + CNumber + " = \"" + username + "\"";
| {
"pile_set_name": "StackExchange"
} |
Q:
Satellite Positions in ICRF
For a project I need precise satellite positions in ICRF. After doing some searching I was not able to determine any online resource which provides such time series. In detail I am interested in the coordinate time series of Grace1 and Grace2 of 2017 and 2018. Are those somewhere publicly available?
So far I have found sources for tow-line elements (TLE) which I tried to convert with pyEmph, but I have found no convenient way to get ICRF coordinates from Astrometic Geocentric positions and I am also curious whether the precision would be reasonable this way (cf. accuracy TLE), since I need a precision in the sub-meter range.
A:
Skyfield, at http://rhodesmill.org/skyfield (note the similarity to the location for PyEphem, not a coincidence) does exactly what you are asking for. You give it a TLE and you get coordinates in ICRF (or a variety of other options).
However, you won't get better than several kilometers from TLEs, they are simply not that accurate to begin with, nor is the SGP4 propagator that they are used with. In order to get "...a precision in the sub-meter range" you will have to find some carefully reconstructed (and now historical!) orbit data from the scientists working with the Grace spacecraft for that.
I've plotted the geocentric position, but here are the numerical values for Geocentric, J2000.0 relative to Solar System Barycenter referenced to the Earth's Equator, and to the Ecliptic planes:
[ -725.97623801 -4703.39226501 4823.26596748 ]
[ -1.37224552e+08 5.15960658e+07 2.23564481e+07]
[ -1.37224552e+08 5.62313492e+07 -1.20962433e+04]
TLE = """1 25544U 98067A 18051.96457625 .00002577 00000-0 46169-4 0 9990
2 25544 51.6416 238.1089 0003437 117.8478 357.3261 15.54125912100440"""
L1, L2 = TLE.splitlines()
import numpy as np
import matplotlib.pyplot as plt
from skyfield.api import Loader, EarthSatellite
load = Loader('~/Documents/fishing/SkyData')
data = load('de421.bsp')
ts = load.timescale()
planets = load('de421.bsp')
earth = planets['earth']
ts = load.timescale()
minutes = np.arange(0, 93, 0.5)
time = ts.utc(2018, 2, 27, 0, minutes)
ISS_Geo = EarthSatellite(L1, L2)
ISS_ICRF = earth + EarthSatellite(L1, L2)
ISS_Geo_pos = ISS_Geo.at(time).position.km
ISS_ICRF_pos = ISS_ICRF.at(time).position.km
ISS_ICRF_eclpos = ISS_ICRF.at(time).ecliptic_position().km
for thing in ISS_Geo_pos, ISS_ICRF_pos, ISS_ICRF_eclpos:
print thing[:, 0]
plt.figure()
for thing in ISS_Geo_pos:
plt.plot(thing)
plt.show()
| {
"pile_set_name": "StackExchange"
} |
Q:
Ringtones directory won't update in settings
I removed some of the stock ringtones (from my ROM) that I didn't want from /system/media/audio/ringtones and added some new ones that I got from the xda forums via my SD card and RootExplorer.
When I open the Sound/Default Ringtone menus in settings, some of the old ringtones are listed and new ones are listed as well, none of them play. The only ones that do are the few that I left in /system/media/audio/ringtones and a few stored on my SD card.
How can I fix this issue so that my phone recognises that all files are in their proper directories?
A:
To update the ring tone directory, the media scanner has to run. Usually restarting the phone will do this, but if media scanner is not checking that directory when the device starts you can try to create a file in the sdcard ringtone directory with an app that triggers media scanner. I think Astro File Manager will trigger it.
If that doesn't work, you could try clearing the cache (I assume root since you are using root explorer and deleting system ringtones), the system may be caching that information and thinks they are still there.
| {
"pile_set_name": "StackExchange"
} |
Q:
swift ios - How to run function in ViewController from AppDelegate
I am trying to run a function in certain ViewController using AppDelegate
func applicationDidBecomeActive(_ application: UIApplication) {
ViewController().grabData()
}
But somehow the function does not seem to run at all when the app has become active after entering the app from the background.
The function looks like this
func grabData() {
self._DATASERVICE_GET_STATS(completion: { (int) -> () in
if int == 0 {
print("Nothing")
} else {
print(int)
for (_, data) in self.userDataArray.enumerated() {
let number = Double(data["wage"]!)
let x = number!/3600
let z = Double(x * Double(int))
self.money += z
let y = Double(round(1000*self.money)/1000)
self.checkInButtonLabel.text = "\(y) KR"
}
self.startCounting()
self.workingStatus = 1
}
})
}
And uses this var
var money: Double = 0.000
What have I missed?
Thanks!
A:
ViewController().grabData() will create a new instance of the ViewController and call this function. Then.. as the view controller is not in use it will be garbage collected/removed from memory. You need to be calling this method on the actual view controller that is in use. Not a new instance of it.
The best option would be to listen for the UIApplicationDidBecomeActive notification that iOS provides.
NotificationCenter.default.addObserver(
self,
selector: #selector(grabData),
name: NSNotification.Name.UIApplicationDidBecomeActive,
object: nil)
make sure that you also remove the observer, this is usually done in a deinit method
deinit() {
NotificationCenter.default.removeObserver(self)
}
A:
I simply solved it like this:
func applicationDidBecomeActive(_ application: UIApplication) {
let viewController = self.window?.rootViewController as! ViewController
viewController.grabData()
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to define a type omitting one shared prop from a union but including the rest of them along with union members' private props?
I have two interfaces (Foo and Bar) that extend the same base interface. The two interfaces form together a union (DiscriminatingUnion), so objects of that type have the props of the base interface and the private props of each union member interface.
I want to create a new type that is the same as the aforementioned union with the exception that one of the base props is omitted. How to do this? Using Omit<> doesn't seem to work because it apparently turns into a Pick<> that ignores the private props of a union member.
TL;DR: I want testObject.bar to exist in case block "bar" and testObject.foo to exist in case block "foo" in the example below:
interface Base { propToOmit: string; propToKeep: string }
interface Foo extends Base { type: "foo"; foo: string }
interface Bar extends Base { type: "bar"; bar: string }
type DiscriminatingUnion = Foo | Bar;
type OmitFromDiscUnion = Omit<DiscriminatingUnion, "propToOmit">;
const fooObject: DiscriminatingUnion = {
type: "foo",
foo: "",
propToOmit: "",
propToKeep: ""
};
const barObject: DiscriminatingUnion = {
type: "bar",
bar: "",
propToOmit: "",
propToKeep: ""
};
const testArray: OmitFromDiscUnion[] = [fooObject, barObject];
testArray.forEach((testObject) => {
switch (testObject.type) {
case "bar":
// Property 'bar' does not exist on type 'Pick<DiscriminatingUnion, "type" | "propToKeep">'.
testObject.bar; // Doesn't exist, but I want it to exist!
testObject.foo; // Doesn't exist as expected (switch-case).
testObject.propToOmit; // Doesn't exist as expected (omitted).
testObject.propToKeep; // Exists as expected.
break;
case "foo":
// Property 'foo' does not exist on type 'Pick<DiscriminatingUnion, "type" | "propToKeep">'.
testObject.foo; // Doesn't exist, but I want it to exist!
testObject.bar; // Doesn't exist as expected (switch-case).
testObject.propToOmit; // Doesn't exist as expected (omitted).
testObject.propToKeep; // Exists as expected.
break;
}
});
A:
Apparently I can use Extract<DiscriminatingUnion, { /* allowed props */ }> to achieve this. I'm unsure whether this is the optimal solution.
Using Extract<DiscriminatingUnion, {/*hard coded type*/}> is bad because it's hard coded. A solution I'd appreciate would somehow achieve the goal by defining the new union using the union member types and somehow excluding one specific prop from there.
interface Base { propToOmit: string; propToKeep: string }
interface Foo extends Base { type: "foo"; foo: string }
interface Bar extends Base { type: "bar"; bar: string }
type DiscriminatingUnion = Foo | Bar;
// NEW
type OmitFromDiscUnion = Extract<DiscriminatingUnion, {
// Hard coded, bad! Optimal solution would use the defined types somehow!
propToKeep: string;
type: string;
foo?: string;
bar?: string;
}>;
const fooObject: DiscriminatingUnion = {
type: "foo",
foo: "",
propToOmit: "",
propToKeep: ""
};
const barObject: DiscriminatingUnion = {
type: "bar",
bar: "",
propToOmit: "",
propToKeep: ""
};
const testArray: OmitFromDiscUnion[] = [fooObject, barObject];
testArray.forEach((testObject) => {
switch (testObject.type) {
case "bar":
// NEW
testObject.bar; // Exists now!
testObject.foo; // Doesn't exist as expected (switch-case).
testObject.propToOmit; // Doesn't exist as expected (omitted).
testObject.propToKeep; // Exists as expected.
break;
case "foo":
// NEW
testObject.foo; // Exists now!
testObject.bar; // Doesn't exist as expected (switch-case).
testObject.propToOmit; // Doesn't exist as expected (omitted).
testObject.propToKeep; // Exists as expected.
break;
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Simple quotes app
I created simple app that read ~ delimited txt file, convert it to [String] and display quotes on screen.
How would you improve this code? To be more Haskell like...
in splitStr (c/=) is faster than (/=c) by 20-50 ns. Why?
Any other ways to clear screen in windows console app?
If we compile this code as win console app, I assume threadDelay pauses whole app not just outQ function. Right?
Can someone point me in right direction how to refactor this code to use someting like JavaScripts setInterval or setTimeout.
is there some easy way to catch ctrl+c so I can showCursor on exit?
.
import System.IO
import System.Random
import Control.Concurrent (threadDelay) -- microseconds
import System.Console.ANSI -- clearScreen
fileName = "quotes.txt"
oneSecond = 1000000
delay = 1 -- sec
splitStr _ [] = []
splitStr c xs = takeWhile (c/=) xs : splitStr c (drop 1 $ dropWhile (c/=) xs)
--clear = putStr "\ESC[2J" -- not working on windows
outQ list l sec g = do
clearScreen
setCursorPosition 0 0 -- row col
let (index, gen') = randomR (0, l) g
putStrLn $ list !! index
threadDelay $ sec * oneSecond
outQ list l delay gen' -- works
main :: IO ()
main = do
setTitle "Quotes"
hideCursor -- catch ctrl+c for showCursor
gen <- newStdGen
str <- readFile fileName
let qlist = splitStr '~' str
let len = length qlist -1
outQ qlist len delay gen
A:
I'm going to talk about your splitStr function.
First, it's almost the same as splitOn from Data.List.Split in the split package.
Run cabal install split
Add import Data.List.Split at the start of your code
Replace
let qlist = splitStr '~' str
with
let qlist = splitOn "~" str
But let's suppose you can't use the split package for some reason, and try to improve your splitStr.
splitStr :: Eq a => a -> [a] -> [[a]]
splitStr _ [] = []
splitStr c xs = takeWhile (c/=) xs : splitStr c (drop 1 $ dropWhile (c/=) xs)
We can use span instead of takeWhile and dropWhile. This is clearer and also more efficient as we only have to traverse the list once instead of twice.
splitStr :: Eq a => a -> [a] -> [[a]]
splitStr _ [] = []
splitStr c xs = ys : splitStr c (drop 1 zs)
where (ys, zs) = split (c/=) xs
A:
Let me deal with outQ. I see 3 problems there:
stateful computation without a monad (passing the generator state around)
recursion instead of library function (forever from Control.Monad is appropriate)
using !! to repeatedly access lists which is O(N) and thus not a good idea in most cases.
Let's clean up recursive calls so only the changing parts are passed around and constant parts are kept in a closure:
outQ list l sec = foo where
foo g = do
clearScreen
setCursorPosition 0 0 -- row col
let (index, gen') = randomR (0, l) g
putStrLn $ list !! index
threadDelay $ sec * oneSecond
foo gen' -- works
It's a good practice to split recursive parts from non-recursive, so you more easier can see which library function to use for recursion:
forever1 f = f >=> forever1 f
outQ list l sec = forever1 foo where
foo g = do
clearScreen
setCursorPosition 0 0 -- row col
let (index, gen') = randomR (0, l) g
putStrLn $ list !! index
threadDelay $ sec * oneSecond
return gen'
Now we can load ghci Quotes.hs and check :t forever1. It tells us that
forever1 :: Monad m => (b -> m b) -> b -> m c
Using Hoogle we check that there's no standard function with such type, so we have to stick
with our own. Now we can get rid of foo:
outQ list l sec = forever1 $ \g -> do
clearScreen
setCursorPosition 0 0 -- row col
let (index, gen') = randomR (0, l) g
putStrLn $ list !! index
threadDelay $ sec * oneSecond
return gen'
As for getting rid of generator passing, there are two options:
To use RandT monad transformer from Control.Monad.Random
To use randomRs function to generate all random numbers outside of outQ
For such simple case it's better to stick with option 2. Note as we don't need to pass anything from previous iteration call to next one, we can now use library function mapM_:
outQ list l sec = mapM_ $ \index -> do
clearScreen
setCursorPosition 0 0 -- row col
putStrLn $ list !! index
threadDelay $ sec * oneSecond
main :: IO ()
main = do
setTitle "Quotes"
hideCursor -- catch ctrl+c for showCursor
gen <- newStdGen
str <- readFile fileName
let qlist = splitStr '~' str
let len = length qlist -1
let rand = randomRs (0, len) gen
outQ qlist len delay rand
At this point we can convert our list to an immutable array:
outQ array sec = mapM_ $ \index -> do
clearScreen
setCursorPosition 0 0 -- row col
putStrLn $ array ! index
threadDelay $ sec * oneSecond
listArray' l = listArray (1, length l) l
main :: IO ()
main = do
setTitle "Quotes"
hideCursor -- catch ctrl+c for showCursor
gen <- newStdGen
str <- readFile fileName
let qlist = splitStr '~' str
let qarray = listArray' qlist
let rand = randomRs (bounds qarray) gen
outQ qarray delay rand
At this point I see there's no need in passing both array and rand to outQ:
outQ sec = mapM_ $ \s -> do
clearScreen
setCursorPosition 0 0 -- row col
putStrLn s
threadDelay $ sec * oneSecond
listArray' l = listArray (1, length l) l
main :: IO ()
main = do
setTitle "Quotes"
hideCursor -- catch ctrl+c for showCursor
gen <- newStdGen
str <- readFile fileName
let qlist = splitStr '~' str
let qarray = listArray' qlist
let rand = randomRs (bounds qarray) gen
let stringsToDisplay = map (qarray !) rand
outQ delay stringsToDisplay
Now outQ is crystal clear, so we can condense main:
main :: IO ()
main = do
setTitle "Quotes"
hideCursor -- catch ctrl+c for showCursor
qarray <- listArray' <$> splitStr '~' <$> readFile fileName
map (qarray !) <$> randomRs (bounds qarray) <$> newStdGen >>= outQ delay
Finally, to make code more readable, we can extract two general functions which may become useful elsewhere:
mapM_interval sec f = mapM_ $ \s -> do
f s
threadDelay $ sec * oneSecond
randomElemsFrom qarray = map (qarray !) . randomRs (bounds qarray)
main :: IO ()
main = do
setTitle "Quotes"
hideCursor -- catch ctrl+c for showCursor
qarray <- listArray' <$> splitStr '~' <$> readFile fileName
randomElemsFrom qarray <$> newStdGen >>= mapM_interval delay outQ
As the delay may be applied to other functions such as forever, mapM without underscore and, forM_ etc, you may want to generalize mapM_interval further:
withInterval sec mapFn innerFn = mapFn $ \s -> innerFn s >> threadDelay (sec * oneSecond)
main :: IO ()
main = do
setTitle "Quotes"
hideCursor -- catch ctrl+c for showCursor
qarray <- listArray' <$> splitStr '~' <$> readFile fileName
randomElemsFrom qarray <$> newStdGen >>= withInterval delay mapM_ outQ
So the final version is:
import System.Random (randomRs, newStdGen)
import Control.Concurrent (threadDelay) -- microseconds
import System.Console.ANSI (clearScreen, setCursorPosition, setTitle, hideCursor)
import Control.Applicative ((<$>))
import Data.Array (listArray, bounds, (!))
import Data.List.Split (splitOn)
fileName = "quotes.txt"
oneSecond = 1000000
delay = 1 -- sec
--clear = putStr "\ESC[2J" -- not working on windows
outQ s = do
clearScreen
setCursorPosition 0 0 -- row col
putStrLn s
listArray' l = listArray (1, length l) l
randomElemsFrom qarray = map (qarray !) . randomRs (bounds qarray)
withInterval sec mapFn innerFn = mapFn $ \s -> innerFn s >> threadDelay (sec * oneSecond)
main :: IO ()
main = do
setTitle "Quotes"
hideCursor -- catch ctrl+c for showCursor
qarray <- listArray' <$> splitOn "~" <$> readFile fileName
randomElemsFrom qarray <$> newStdGen >>= withInterval delay mapM_ outQ
Found yet another improvement:
randomElemsFrom x = map (qarray !) . randomRs (bounds qarray) where
qarray = listArray' $ splitOn "~" x
main :: IO ()
main = do
setTitle "Quotes"
hideCursor -- catch ctrl+c for showCursor
liftM2 randomElemsFrom (readFile fileName) newStdGen >>= withInterval delay mapM_ outQ
This version has more separation between monadic and non-monadic code (which is good) but randomElemsFrom was a generally useful function before but now it is tied to the task at hand (which is bad).
| {
"pile_set_name": "StackExchange"
} |
Q:
asp.net the page is loaded even thouhg i am using update panel
I have three taps. with drop down list as this:
I want that when I change the Drop down list, I want to do something in the server side and then update the first two tabs. I can do that.
my problem
If I were in the second tab and I changed the drop down, the page is loaded and set to the first tap.
I tried to
I tried to surrown the table in the second tab with update panel like this:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel2" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<table id="BookingTableTomorrow" runat="server" class="tableResultClass">
<tr>
<th>ID</th>
<th>PlanTime</th>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
see the bellow all code, and note that I have another update panel in the third tab, and that third tab is working perfectly
<div id="tabs">
<ul>
<li><a href="#tabs-1">Today</a></li>
<li><a href="#tabs-2">Tomorrow</a></li>
<li><a href="#tabs-3">Any Date</a></li>
<label style="float: right">
<asp:DropDownList AutoPostBack="true" runat="server" ID="mealTimeSelector" OnSelectedIndexChanged="TodayTab_Click">
<asp:ListItem Value="1">Breakfast</asp:ListItem>
<asp:ListItem Value="2">Lunch</asp:ListItem>
<asp:ListItem Value="3">Dinner</asp:ListItem>
</asp:DropDownList>
</label>
</ul>
<div id="tabs-1">
<table id="BookingTable" runat="server" class="tableResultClass">
<tr>
<th>ID</th>
<th>PlanTime</th>
</tr>
</table>
</div>
<div id="tabs-2">
<div id="circleG" style="margin-left: auto; margin-right: auto; padding-top: 50px; padding-bottom: 50px;">
<div id="circleG_1" class="circleG"></div>
<div id="circleG_2" class="circleG"></div>
<div id="circleG_3" class="circleG"></div>
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel2" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<table id="BookingTableTomorrow" runat="server" class="tableResultClass">
<tr>
<th>ID</th>
<th>PlanTime</th>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div id="tabs-3">
<p>
Date:
<input type="text" id="datepicker" runat="server">
</p>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Button ID="BookingForDate" runat="server" OnClick="BookingForDate_Click" Text="Search" />
<span style="color: red" id="errorDateMessage" runat="server"></span>
<div runat="server" id="circleG2" style="margin-left: auto; margin-right: auto; margin-left: 400px; padding-bottom: 60px;">
<div id="circleG_1" class="circleG"></div>
<div id="circleG_2" class="circleG"></div>
<div id="circleG_3" class="circleG"></div>
</div>
<table id="DateBookingTable" runat="server" class="tableResultClass">
<tr>
<th>ID</th>
<th>PlanTime</th>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
A:
You can set a the dropdownlist as asynchronous postback trigger...
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Dropdownlist1" />
</Triggers>
</asp:UpdatePanel>
| {
"pile_set_name": "StackExchange"
} |
Q:
A recursion algorithm
Ok, this may seem trivial to some, but I'm stuck.
Here's the algorithm I'm supposed to use:
Here’s a recursive algorithm. Suppose we have n integers in a non-increasing sequence, of which the first is the number k. Subtract one from each of the first k numbers after the first. (If there are fewer than k such number, the sequence is not graphical.) If necessary, sort the resulting sequence of n-1 numbers (ignoring the first one) into a non-increasing sequence. The original sequence is graphical if and only if the second one is. For the stopping conditions, note that a sequence of all zeroes is graphical, and a sequence containing a negative number is not. (The proof of this is not difficult, but we won’t deal with it here.)
Example:
Original sequence: 5, 4, 3, 3, 2, 1, 1
Subtract 1 five times: 3, 2, 2, 1, 0, 1
Sort: 3, 2, 2, 1, 1, 0
Subtract 1 three times: 1, 1, 0, 1, 0
Sort: 1, 1, 1, 0, 0
Subtract 1 once: 0, 1, 0, 0
Sort: 1, 0, 0, 0
Subtract 1 once: -1, 0, 0
We have a negative number, so the original sequence is not graphical.
This seems simple enough to me, but when I try to execute the algorithm I get stuck.
Here's the function I've written so far:
//main
int main ()
{
//local variables
const int MAX = 30;
ifstream in;
ofstream out;
int graph[MAX], size;
bool isGraph;
//open and test file
in.open("input3.txt");
if (!in) {
cout << "Error reading file. Exiting program." << endl;
exit(1);
}
out.open("output3.txt");
while (in >> size) {
for (int i = 0; i < size; i++) {
in >> graph[i];
}
isGraph = isGraphical(graph, 0, size);
if (isGraph) {
out << "Yes\n";
}else
out << "No\n";
}
//close all files
in.close();
out.close();
cin.get();
return 0;
}//end main
bool isGraphical(int degrees[], int start, int end){
bool isIt = false;
int ender;
inSort(degrees, end);
ender = degrees[start] + start + 1;
for(int i = 0; i < end; i++)
cout << degrees[i];
cout << endl;
if (degrees[start] == 0){
if(degrees[end-1] < 0)
return false;
else
return true;
}
else{
for(int i = start + 1; i < ender; i++) {
degrees[i]--;
}
isIt = isGraphical(degrees, start+1, end);
}
return isIt;
}
void inSort(int x[],int length)
{
for(int i = 0; i < length; ++i)
{
int current = x[i];
int j;
for(j = i-1; j >= 0 && current > x[j]; --j)
{
x[j+1] = x[j];
}
x[j+1] = current;
}
}
I seem to get what that sort function is doing, but when I debug, the values keep jumping around. Which I assume is coming from my recursive function.
Any help?
EDIT:
Code is functional. Please see the history if needed.
With help from @RMartinhoFernandes I updated my code. Includes working insertion sort.
I updated the inSort funcion boundaries
I added an additional ending condition from the comments. But the algorithm still isn't working. Which makes me thing my base statements are off. Would anyone be able to help further? What am I missing here?
A:
Ok, I helped you out in chat, and I'll post a summary of the issues you had here.
The insertion sort inner loop should go backwards, not forwards. Make it for(i = (j - 1); (i >= 0) && (key > x[i]); i--);
There's an out-of-bounds access in the recursion base case: degrees[end] should be degrees[end-1];
while (!in.eof()) will not read until the end-of-file. while(in >> size) is a superior alternative.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is format preserving encryption suitable for use with words or names?
Is it possible to use FPE to encrypt names and language words like 'Bob' 'the' 'tree', in order to preserve both length and format (like keeping characters within a certain range like A-Z a-z)
The only way I can think of at the moment is to reduce each character to it's decimal value and encrypt that. But that doesn't seem very secure (wouldn't each character map to exactly the same value each time?)
A:
The obvious way to FPE strings of $N$ characters of [A-Za-z] is to treat the string as a base-52 value (with each character being a digit, say, A=0, B=1, ..., y=50, z=51); do a base conversion of that to an integer between 0 and $52^N-1$; use a standard FPE technique to encrypt that value into another integer between 0 and $52^N-1$, and do a base conversion back into a string of $N$ characters of [A-Za-z].
Because you're encrypting the string as a whole, you don't have the data leakage you would have if you encrypted each character individually.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.