Execute a shell script in current shell with sudo permission
If you really want to "ExecuteCall a shell script in current shell with sudo permission" you can use exec
to...
replace the shell with a given program (executing it, not as new process)
I insist on replacing "execute" with "call" because the former has a meaning that includes creating a new process and ID, where the latter is ambiguous and leaves room for creativity, of which I am full.
Consider this test case and look closely at pid 1337
# Don't worry, the content of this script is cat'ed below
$ ./test.sh -o foo -p bar
User ubuntu is running...
PID TT USER COMMAND
775 pts/1 ubuntu -bash
1408 pts/1 ubuntu \_ bash ./test.sh -o foo -p bar
1411 pts/1 ubuntu \_ ps -t /dev/pts/1 -fo pid,tty,user,args
User root is running...
PID TT USER COMMAND
775 pts/1 ubuntu -bash
1337 pts/1 root \_ sudo ./test.sh -o foo -p bar
1412 pts/1 root \_ bash ./test.sh -o foo -p bar
1415 pts/1 root \_ ps -t /dev/pts/1 -fo pid,tty,user,args
Take 'exec' out of the command and this script would get cat-ed twice. (Try it.)
#!/usr/bin/env bash
echo; echo "User $(whoami) is running..."
ps -t $(tty) -fo pid,tty,user,args
if [[ $EUID > 0 ]]; then
# exec replaces the current process effectively ending execution so no exit is needed.
exec sudo "$0" "$@"
fi
echo; echo "Take 'exec' out of the command and this script would get cat-ed twice. (Try it.)"; echo
cat $0
Here is another test using sudo -s
$ ps -fo pid,tty,user,args; ./test2.sh
PID TT USER COMMAND
10775 pts/1 ubuntu -bash
11496 pts/1 ubuntu \_ ps -fo pid,tty,user,args
User ubuntu is running...
PID TT USER COMMAND
10775 pts/1 ubuntu -bash
11497 pts/1 ubuntu \_ bash ./test2.sh
11500 pts/1 ubuntu \_ ps -fo pid,tty,user,args
User root is running...
PID TT USER COMMAND
11497 pts/1 root sudo -s
11501 pts/1 root \_ /bin/bash
11503 pts/1 root \_ ps -fo pid,tty,user,args
$ cat test2.src
echo; echo "User $(whoami) is running..."
ps -fo pid,tty,user,args
$ cat test2.sh
#!/usr/bin/env bash
source test2.src
exec sudo -s < test2.src
And a simpler test using sudo -s
$ ./exec.sh
bash's PID:25194 user ID:7809
systemd(1)---bash(23064)---bash(25194)---pstree(25196)
Finally...
bash's PID:25199 user ID:0
systemd(1)---bash(23064)---sudo(25194)---bash(25199)---pstree(25201)
$ cat exec.sh
#!/usr/bin/env bash
pid=$$
id=$(id -u)
echo "bash's PID:$pid user ID:$id"
pstree -ps $pid
# the quoted EOF is important to prevent shell expansion of the $...
exec sudo -s <<EOF
echo
echo "Finally..."
echo "bash's PID:\$\$ user ID:\$(id -u)"
pstree -ps $pid
EOF
When to use If-else if-else over switch statements and vice versa
Let's say you have decided to use switch as you are only working on a single variable which can have different values. If this would result in a small switch statement (2-3 cases), I'd say that is fine. If it seems you will end up with more I would recommend using polymorphism instead. An AbstractFactory pattern could be used here to create an object that would perform whatever action you were trying to do in the switches. The ugly switch statement will be abstracted away and you end up with cleaner code.
Run bash script from Windows PowerShell
If you add the extension .SH
to the environment variable PATHEXT
, you will be able to run shell scripts from PowerShell by only using the script name with arguments:
PS> .\script.sh args
If you store your scripts in a directory that is included in your PATH environment variable, you can run it from anywhere, and omit the extension and path:
PS> script args
Note: sh.exe or another *nix shell must be associated with the .sh extension.
Can HTTP POST be limitless?
POST allows for an arbitrary length of data to be sent to a server, but there are limitations based on timeouts/bandwidth etc.
I think basically, it's safer to assume that it's not okay to send lots of data.
How to read a text file?
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
How to automatically allow blocked content in IE?
I believe this will only appear when running the page locally in this particular case, i.e. you should not see this when loading the apge from a web server.
However if you have permission to do so, you could turn off the prompt for Internet Explorer by following Tools (menu) → Internet Options → Security (tab) → Custom Level (button) → and Disable Automatic prompting for ActiveX controls.
This will of course, only affect your browser.
Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]
For me the error was caused by wrong type hint of url string. I used:
export class TodoService {
apiUrl: String = 'https://jsonplaceholder.typicode.com/todos' // wrong uppercase String
constructor(private httpClient: HttpClient) { }
getTodos(): Observable<Todo[]> {
return this.httpClient.get<Todo[]>(this.apiUrl)
}
}
where I should have used
export class TodoService {
apiUrl: string = 'https://jsonplaceholder.typicode.com/todos' // lowercase string!
constructor(private httpClient: HttpClient) { }
getTodos(): Observable<Todo[]> {
return this.httpClient.get<Todo[]>(this.apiUrl)
}
}
Print specific part of webpage
Here what worked for me
With jQuery and https://developer.mozilla.org/en-US/docs/Web/API/Window/open
var $linkToOpenPrintDialog = $('#tvcPrintThisLinkId');
var windowObjectReference = null;
var windowFeatures = 'left=0,top=0,width=800,height=900,menubar=no,toolbar=no,location=yes,resizable=no,scrollbars=no,status=no';
var windowFeaturesStyles = '<link rel="stylesheet" media="print" href="/wp-content/themes/salient-child/dist/css/app-print.css">';
$linkToOpenPrintDialog.on('click', function(event) {
openPrintDialog(this.href, this.target, 'tvcInnerCalculatorDivId', event);
return false;
});
function openPrintDialog(url, windowName, elementToOpen, event) {
var elementContent = document.getElementById(elementToOpen);
if(windowObjectReference == null || windowObjectReference.closed) {
windowObjectReference = window.open( url, windowName, windowFeatures);
windowObjectReference.document.write(windowFeaturesStyles);
windowObjectReference.document.write(elementContent.innerHTML);
windowObjectReference.document.close();
windowObjectReference.focus();
windowObjectReference.print();
windowObjectReference.close();
} else {
windowObjectReference.focus();
};
event.preventDefault();
}
app-print.css
@media print {
body {
margin: 0;
color: black;
background-color: white;
}
}
Get the value of checked checkbox?
I am using this in my code.Try this
var x=$("#checkbox").is(":checked");
If the checkbox is checked x
will be true otherwise it will be false.
Datagridview: How to set a cell in editing mode?
Well, I would check if any of your columns are set as ReadOnly
. I have never had to use BeginEdit, but maybe there is some legitimate use. Once you have done dataGridView1.Columns[".."].ReadOnly = False;
, the fields that are not ReadOnly
should be editable. You can use the DataGridView CellEnter
event to determine what cell was entered and then turn on editing on those cells after you have passed editing from the first two columns to the next set of columns and turn off editing on the last two columns.
Effects of the extern keyword on C functions
Inline functions have special rules about what extern
means. (Note that inline functions are a C99 or GNU extension; they weren't in original C.
For non-inline functions, extern
is not needed as it is on by default.
Note that the rules for C++ are different. For example, extern "C"
is needed on the C++ declaration of C functions that you are going to call from C++, and there are different rules about inline
.
ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"
Answer for BigDecimal throws ArithmeticException
public static void main(String[] args) {
int age = 30;
BigDecimal retireMentFund = new BigDecimal("10000.00");
retireMentFund.setScale(2,BigDecimal.ROUND_HALF_UP);
BigDecimal yearsInRetirement = new BigDecimal("20.00");
String name = " Dennis";
for ( int i = age; i <=65; i++){
recalculate(retireMentFund,new BigDecimal("0.10"));
}
BigDecimal monthlyPension = retireMentFund.divide(
yearsInRetirement.divide(new BigDecimal("12"), new MathContext(2, RoundingMode.CEILING)), new MathContext(2, RoundingMode.CEILING));
System.out.println(name+ " will have £" + monthlyPension +" per month for retirement");
}
public static void recalculate (BigDecimal fundAmount, BigDecimal rate){
fundAmount.multiply(rate.add(new BigDecimal("1.00")));
}
Add MathContext object in your divide method call and adjust precision and rounding mode. This should fix your problem
pass array to method Java
You got a syntax wrong. Just pass in array's name. BTW - it's good idea to read some common formatting stuff too, for example in Java methods should start with lowercase letter (it's not an error it's convention)
Controlling fps with requestAnimationFrame?
These are all good ideas in theory, until you go deep. The problem is you can't throttle an RAF without de-synchronizing it, defeating it's very purpose for existing. So you let it run at full-speed, and update your data in a separate loop, or even a separate thread!
Yes, I said it. You can do multi-threaded JavaScript in the browser!
There are two methods I know that work extremely well without jank, using far less juice and creating less heat. Accurate human-scale timing and machine efficiency are the net result.
Apologies if this is a little wordy, but here goes...
Method 1: Update data via setInterval, and graphics via RAF.
Use a separate setInterval for updating translation and rotation values, physics, collisions, etc. Keep those values in an object for each animated element. Assign the transform string to a variable in the object each setInterval 'frame'. Keep these objects in an array. Set your interval to your desired fps in ms: ms=(1000/fps). This keeps a steady clock that allows the same fps on any device, regardless of RAF speed. Do not assign the transforms to the elements here!
In a requestAnimationFrame loop, iterate through your array with an old-school for loop-- do not use the newer forms here, they are slow!
for(var i=0; i<sprite.length-1; i++){ rafUpdate(sprite[i]); }
In your rafUpdate function, get the transform string from your js object in the array, and its elements id. You should already have your 'sprite' elements attached to a variable or easily accessible through other means so you don't lose time 'get'-ing them in the RAF. Keeping them in an object named after their html id's works pretty good. Set that part up before it even goes into your SI or RAF.
Use the RAF to update your transforms only, use only 3D transforms (even for 2d), and set css "will-change: transform;" on elements that will change. This keeps your transforms synced to the native refresh rate as much as possible, kicks in the GPU, and tells the browser where to concentrate most.
So you should have something like this pseudocode...
// refs to elements to be transformed, kept in an array
var element = [
mario: document.getElementById('mario'),
luigi: document.getElementById('luigi')
//...etc.
]
var sprite = [ // read/write this with SI. read-only from RAF
mario: { id: mario ....physics data, id, and updated transform string (from SI) here },
luigi: { id: luigi .....same }
//...and so forth
] // also kept in an array (for efficient iteration)
//update one sprite js object
//data manipulation, CPU tasks for each sprite object
//(physics, collisions, and transform-string updates here.)
//pass the object (by reference).
var SIupdate = function(object){
// get pos/rot and update with movement
object.pos.x += object.mov.pos.x; // example, motion along x axis
// and so on for y and z movement
// and xyz rotational motion, scripted scaling etc
// build transform string ie
object.transform =
'translate3d('+
object.pos.x+','+
object.pos.y+','+
object.pos.z+
') '+
// assign rotations, order depends on purpose and set-up.
'rotationZ('+object.rot.z+') '+
'rotationY('+object.rot.y+') '+
'rotationX('+object.rot.x+') '+
'scale3d('.... if desired
; //...etc. include
}
var fps = 30; //desired controlled frame-rate
// CPU TASKS - SI psuedo-frame data manipulation
setInterval(function(){
// update each objects data
for(var i=0; i<sprite.length-1; i++){ SIupdate(sprite[i]); }
},1000/fps); // note ms = 1000/fps
// GPU TASKS - RAF callback, real frame graphics updates only
var rAf = function(){
// update each objects graphics
for(var i=0; i<sprite.length-1; i++){ rAF.update(sprite[i]) }
window.requestAnimationFrame(rAF); // loop
}
// assign new transform to sprite's element, only if it's transform has changed.
rAF.update = function(object){
if(object.old_transform !== object.transform){
element[object.id].style.transform = transform;
object.old_transform = object.transform;
}
}
window.requestAnimationFrame(rAF); // begin RAF
This keeps your updates to the data objects and transform strings synced to desired 'frame' rate in the SI, and the actual transform assignments in the RAF synced to GPU refresh rate. So the actual graphics updates are only in the RAF, but the changes to the data, and building the transform string are in the SI, thus no jankies but 'time' flows at desired frame-rate.
Flow:
[setup js sprite objects and html element object references]
[setup RAF and SI single-object update functions]
[start SI at percieved/ideal frame-rate]
[iterate through js objects, update data transform string for each]
[loop back to SI]
[start RAF loop]
[iterate through js objects, read object's transform string and assign it to it's html element]
[loop back to RAF]
Method 2. Put the SI in a web-worker. This one is FAAAST and smooth!
Same as method 1, but put the SI in web-worker. It'll run on a totally separate thread then, leaving the page to deal only with the RAF and UI. Pass the sprite array back and forth as a 'transferable object'. This is buko fast. It does not take time to clone or serialize, but it's not like passing by reference in that the reference from the other side is destroyed, so you will need to have both sides pass to the other side, and only update them when present, sort of like passing a note back and forth with your girlfriend in high-school.
Only one can read and write at a time. This is fine so long as they check if it's not undefined to avoid an error. The RAF is FAST and will kick it back immediately, then go through a bunch of GPU frames just checking if it's been sent back yet. The SI in the web-worker will have the sprite array most of the time, and will update positional, movement and physics data, as well as creating the new transform string, then pass it back to the RAF in the page.
This is the fastest way I know to animate elements via script. The two functions will be running as two separate programs, on two separate threads, taking advantage of multi-core CPU's in a way that a single js script does not. Multi-threaded javascript animation.
And it will do so smoothly without jank, but at the actual specified frame-rate, with very little divergence.
Result:
Either of these two methods will ensure your script will run at the same speed on any PC, phone, tablet, etc (within the capabilities of the device and the browser, of course).
Spring Boot Configure and Use Two DataSources
Refer the official documentation
Creating more than one data source works same as creating the first one. You might want to mark one of them as @Primary if you are using the default auto-configuration for JDBC or JPA (then that one will be picked up by any @Autowired injections).
@Bean
@Primary
@ConfigurationProperties(prefix="datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix="datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?
FXCop typically prefers OrdinalIgnoreCase
. But your requirements may vary.
For English there is very little difference. It is when you wander into languages that have different written language constructs that this becomes an issue. I am not experienced enough to give you more than that.
OrdinalIgnoreCase
The StringComparer returned by the
OrdinalIgnoreCase property treats
the characters in the strings to
compare as if they were converted
to uppercase using the conventions
of the invariant culture, and then
performs a simple byte comparison
that is independent of language.
This is most appropriate when
comparing strings that are generated
programmatically or when comparing
case-insensitive resources such as
paths and filenames.
http://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase.aspx
InvariantCultureIgnoreCase
The StringComparer returned by the
InvariantCultureIgnoreCase property
compares strings in a linguistically
relevant manner that ignores case, but
it is not suitable for display in any
particular culture. Its major
application is to order strings in a
way that will be identical across
cultures.
http://msdn.microsoft.com/en-us/library/system.stringcomparer.invariantcultureignorecase.aspx
The invariant culture is the
CultureInfo object returned by the
InvariantCulture property.
The InvariantCultureIgnoreCase
property actually returns an instance
of an anonymous class derived from the
StringComparer class.
Change remote repository credentials (authentication) on Intellij IDEA 14
None of above worked for me. Using Android Studio 3.5 Beta 4.
I even selected "do not save, forget passwords after restart" in file>settings>appearance & behavior>System settings>password
So What I did.
VCS>git>remotes
- remove the repo and add again.
- will ask for credentials.
- then try git fetch in terminal.
- Will prompt for password.
- Issue fixed. :D
Class method decorator with self arguments?
You can't. There's no self
in the class body, because no instance exists. You'd need to pass it, say, a str
containing the attribute name to lookup on the instance, which the returned function can then do, or use a different method entirely.
How to get ID of clicked element with jQuery
Your IDs are #1
, and cycle
just wants a number passed to it. You need to remove the #
before calling cycle
.
$('a.pagerlink').click(function() {
var id = $(this).attr('id');
$container.cycle(id.replace('#', ''));
return false;
});
Also, IDs shouldn't contain the #
character, it's invalid (numeric IDs are also invalid). I suggest changing the ID to something like pager_1
.
<a href="#" id="pager_1" class="pagerlink" >link</a>
$('a.pagerlink').click(function() {
var id = $(this).attr('id');
$container.cycle(id.replace('pager_', ''));
return false;
});
Find oldest/youngest datetime object in a list
have u tried this :
>>> from datetime import datetime as DT
>>> l =[]
>>> l.append(DT(1988,12,12))
>>> l.append(DT(1979,12,12))
>>> l.append(DT(1979,12,11))
>>> l.append(DT(2011,12,11))
>>> l.append(DT(2022,12,11))
>>> min(l)
datetime.datetime(1979, 12, 11, 0, 0)
>>> max(l)
datetime.datetime(2022, 12, 11, 0, 0)
"And" and "Or" troubles within an IF statement
I like assylias' answer, however I would refactor it as follows:
Sub test()
Dim origNum As String
Dim creditOrDebit As String
origNum = "30062600006"
creditOrDebit = "D"
If creditOrDebit = "D" Then
If origNum = "006260006" Then
MsgBox "OK"
ElseIf origNum = "30062600006" Then
MsgBox "OK"
End If
End If
End Sub
This might save you some CPU cycles since if creditOrDebit
is <> "D"
there is no point in checking the value of origNum
.
Update:
I used the following procedure to test my theory that my procedure is faster:
Public Declare Function timeGetTime Lib "winmm.dll" () As Long
Sub DoTests2()
Dim startTime1 As Long
Dim endTime1 As Long
Dim startTime2 As Long
Dim endTime2 As Long
Dim i As Long
Dim msg As String
Const numberOfLoops As Long = 10000
Const origNum As String = "006260006"
Const creditOrDebit As String = "D"
startTime1 = timeGetTime
For i = 1 To numberOfLoops
If creditOrDebit = "D" Then
If origNum = "006260006" Then
' do something here
Debug.Print "OK"
ElseIf origNum = "30062600006" Then
' do something here
Debug.Print "OK"
End If
End If
Next i
endTime1 = timeGetTime
startTime2 = timeGetTime
For i = 1 To numberOfLoops
If (origNum = "006260006" Or origNum = "30062600006") And _
creditOrDebit = "D" Then
' do something here
Debug.Print "OK"
End If
Next i
endTime2 = timeGetTime
msg = "number of iterations: " & numberOfLoops & vbNewLine
msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
" ms" & vbNewLine
msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
" ms"
MsgBox msg
End Sub
I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)
After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit
is <>"D"
, my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.
And that is why I refactored it - to short-circuit the logic so that origNum
doesn't need to be evaluated when creditOrDebit <> "D"
.
At this point, the rest depends on the OP's spreadsheet. If creditOrDebit
is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit
has a wide range of possible values, and D
is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.
How to view the current heap size that an application is using?
Personal favourite for when jvisualvm is overkill or you need cli-only: jvmtop
JvmTop 0.8.0 alpha amd64 8 cpus, Linux 2.6.32-27, load avg 0.12
https://github.com/patric-r/jvmtop
PID MAIN-CLASS HPCUR HPMAX NHCUR NHMAX CPU GC VM USERNAME #T DL
3370 rapperSimpleApp 165m 455m 109m 176m 0.12% 0.00% S6U37 web 21
11272 ver.resin.Resin [ERROR: Could not attach to VM]
27338 WatchdogManager 11m 28m 23m 130m 0.00% 0.00% S6U37 web 31
19187 m.jvmtop.JvmTop 20m 3544m 13m 130m 0.93% 0.47% S6U37 web 20
16733 artup.Bootstrap 159m 455m 166m 304m 0.12% 0.00% S6U37 web 46
How can I add a .npmrc file?
There are a few different points here:
- Where is the
.npmrc
file created.
- How can you download private packages
Running npm config ls -l
will show you all the implicit settings for npm, including what it thinks is the right place to put the .npmrc
. But if you have never logged in (using npm login
) it will be empty. Simply log in to create it.
Another thing is #2. You can actually do that by putting a .npmrc
file in the NPM package's root. It will then be used by NPM when authenticating. It also supports variable interpolation from your shell so you could do stuff like this:
; Get the auth token to use for fetching private packages from our private scope
; see http://blog.npmjs.org/post/118393368555/deploying-with-npm-private-modules
; and also https://docs.npmjs.com/files/npmrc
//registry.npmjs.org/:_authToken=${NPM_TOKEN}
Pointers
Setting the number of map tasks and reduce tasks
It's important to keep in mind that the MapReduce framework in Hadoop allows us only to
suggest the number of Map tasks for a job
which like Praveen pointed out above will correspond to the number of input splits for the task. Unlike it's behavior for the number of reducers (which is directly related to the number of files output by the MapReduce job) where we can
demand that it provide n reducers.
Sqlite primary key on multiple columns
PRIMARY KEY (id, name)
didn't work for me. Adding a constraint did the job instead.
CREATE TABLE IF NOT EXISTS customer (
id INTEGER, name TEXT,
user INTEGER,
CONSTRAINT PK_CUSTOMER PRIMARY KEY (user, id)
)
How to shutdown a Spring Boot Application in a correct way?
They are many ways to shutdown a spring application. One is to call close() on the ApplicationContext
:
ApplicationContext ctx =
SpringApplication.run(HelloWorldApplication.class, args);
// ...
ctx.close()
Your question suggest you want to close your application by doing Ctrl+C
, that is frequently used to terminate a command. In this case...
Use endpoints.shutdown.enabled=true
is not the best recipe. It means you expose an end-point to terminate your application. So, depending on your use case and your environment, you will have to secure it...
Ctrl+C
should work very well in your case. I assume your issue is caused by the ampersand (&) More explanation:
A Spring Application Context may have register a shutdown hook with the JVM runtime. See ApplicationContext documentation.
I don't know if Spring Boot configure this hook automatically as you said. I assume it is.
On Ctrl+C
, your shell sends an INT
signal to the foreground application. It means "please interrupt your execution". The application can trap this signal and do cleanup before its termination (the hook registered by Spring), or simply ignore it (bad).
nohup
is command that execute the following program with a trap to ignore the HUP signal. HUP is used to terminate program when you hang up (close your ssh connexion for example). Moreover it redirects outputs to avoid that your program blocks on a vanished TTY. nohup
does NOT ignore INT signal. So it does NOT prevent Ctrl+C
to work.
I assume your issue is caused by the ampersand (&), not by nohup. Ctrl+C
sends a signal to the foreground processes. The ampersand causes your application to be run in background. One solution: do
kill -INT pid
Use kill -9
or kill -KILL
is bad because the application (here the JVM) cannot trap it to terminate gracefully.
Another solution is to bring back your application in foreground. Then Ctrl+C
will work. Have a look on Bash Job control, more precisely on fg
.
How to send parameters with jquery $.get()
Try this:
$.ajax({
type: 'get',
url: 'manageproducts.do',
data: 'option=1',
success: function(data) {
availableProductNames = data.split(",");
alert(availableProductNames);
}
});
Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.
How to round float numbers in javascript?
Number((6.688689).toFixed(1));
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
Use toFixed()
function.
(6.688689).toFixed();
(6.688689).toFixed(1);
(6.688689).toFixed(2);
Opening Chrome From Command Line
you can create batch file and insert into it the bellow line:
cmd /k start chrome "http://yourWebSite.com
after that you do just double click on this batch file.
How to iterate through a DataTable
foreach (DataRow row in myDataTable.Rows)
{
Console.WriteLine(row["ImagePath"]);
}
I am writing this from memory.
Hope this gives you enough hint to understand the object model.
DataTable
-> DataRowCollection
-> DataRow
(which one can use & look for column contents for that row, either using columnName or ordinal).
-> = contains.
How to catch and print the full exception traceback without halting/exiting the program?
This is my solution to write the error in a log file and also on console:
import logging, sys
import traceback
logging.basicConfig(filename='error.log', level=logging.DEBUG)
def handle_exception(exc_type, exc_value, exc_traceback):
import sys
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
exc_info=(exc_type, exc_value, exc_traceback)
logging.critical("\nDate:" + str(datetime.datetime.now()), exc_info=(exc_type, exc_value, exc_traceback))
print("An error occured, check error.log to see the error details")
traceback.print_exception(*exc_info)
sys.excepthook = handle_exception
How much RAM is SQL Server actually using?
You need to run Perfmon (start->control panel->administrative tools->performance). The counters you want, I believe, are in SQL Server:Memory Manager. Target Server Memory is how much it's allowed to take if needed, Total Server Memory is how much it's currently using. If you click on Explain it'll pop open a box with the details.
By default it's uncapped, and should use all but a couple gb of memory (it leaves that for the OS). However, there are various bugs and memory leaks that can cause it to go into paging.
How to save and extract session data in codeigniter
In codeigniter we are able to store session values in a database.
In the config.php file make the sess_use_database variable true
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
and create a ci_session table in the database
CREATE TABLE IF NOT EXISTS `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(45) DEFAULT '0' NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id),
KEY `last_activity_idx` (`last_activity`)
);
For more details and reference, click here
Skip Git commit hooks
From man githooks
:
pre-commit
This hook is invoked by git commit, and can be bypassed with --no-verify option. It
takes no parameter, and is invoked before obtaining the proposed commit log message
and making a commit. Exiting with non-zero status from this script causes the git
commit to abort.
"The system cannot find the file specified"
Server Error in '/' Application.
The system cannot find the file specified
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.ComponentModel.Win32Exception: The system
cannot find the file specified
Source Error:
{
SqlCommand cmd = new SqlCommand("select * from tblemployee",con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
Source File: d:\C#
programs\kudvenkat\adobasics1\adobasics1\employeedata.aspx.cs Line:
23
if your error is same like mine..just do this
right click on your table in sqlserver object explorer,choose properties
in lower left corner in general option there is a connection block with server and connection specification.in your web config for datasource=. or local choose name specified in server in properties..
Convert NSDate to NSString
If you are on Mac OS X you can write:
NSString* s = [[NSDate date] descriptionWithCalendarFormat:@"%Y_%m_%d_%H_%M_%S" timeZone:nil locale:nil];
However this is not available on iOS.
How to read/write arbitrary bits in C/C++
If you keep grabbing bits from your data, you might want to use a bitfield. You'll just have to set up a struct and load it with only ones and zeroes:
struct bitfield{
unsigned int bit : 1
}
struct bitfield *bitstream;
then later on load it like this (replacing char with int or whatever data you are loading):
long int i;
int j, k;
unsigned char c, d;
bitstream=malloc(sizeof(struct bitfield)*charstreamlength*sizeof(char));
for (i=0; i<charstreamlength; i++){
c=charstream[i];
for(j=0; j < sizeof(char)*8; j++){
d=c;
d=d>>(sizeof(char)*8-j-1);
d=d<<(sizeof(char)*8-1);
k=d;
if(k==0){
bitstream[sizeof(char)*8*i + j].bit=0;
}else{
bitstream[sizeof(char)*8*i + j].bit=1;
}
}
}
Then access elements:
bitstream[bitpointer].bit=...
or
...=bitstream[bitpointer].bit
All of this is assuming are working on i86/64, not arm, since arm can be big or little endian.
How to lookup JNDI resources on WebLogic?
I just had to update legacy Weblogic 8 app to use a data-source instead of hard-coded JDBC string.
Datasource JNDI name on the configuration tab in the Weblogic admin showed: "weblogic.jdbc.ESdatasource", below are two ways that worked:
Context ctx = new InitialContext();
DataSource dataSource;
try {
dataSource = (DataSource) ctx.lookup("weblogic.jdbc.ESdatasource");
response.getWriter().println("A " +dataSource);
}catch(Exception e) {
response.getWriter().println("A " + e.getMessage() + e.getCause());
}
//or
try {
dataSource = (DataSource) ctx.lookup("weblogic/jdbc/ESdatasource");
response.getWriter().println("F "+dataSource);
}catch(Exception e) {
response.getWriter().println("F " + e.getMessage() + e.getCause());
}
//use your datasource
conn = datasource.getConnection();
That's all folks. No passwords and initial context factory needed from the inside of Weblogic app.
How to replace values at specific indexes of a python list?
for index in a:
This will cause index
to take on the values of the elements of a
, so using them as indices is not what you want. In Python, we iterate over a container by actually iterating over it.
"But wait", you say, "For each of those elements of a
, I need to work with the corresponding element of m
. How am I supposed to do that without indices?"
Simple. We transform a
and m
into a list of pairs (element from a, element from m), and iterate over the pairs. Which is easy to do - just use the built-in library function zip
, as follows:
for a_element, m_element in zip(a, m):
s[a_element] = m_element
To make it work the way you were trying to do it, you would have to get a list of indices to iterate over. This is doable: we can use range(len(a))
for example. But don't do that! That's not how we do things in Python. Actually directly iterating over what you want to iterate over is a beautiful, mind-liberating idea.
what about operator.itemgetter
Not really relevant here. The purpose of operator.itemgetter
is to turn the act of indexing into something, into a function-like thing (what we call "a callable"), so that it can be used as a callback (for example, a 'key' for sorting or min/max operations). If we used it here, we'd have to re-call it every time through the loop to create a new itemgetter, just so that we could immediately use it once and throw it away. In context, that's just busy-work.
How to convert an xml string to a dictionary?
@dibrovsd: Solution will not work if the xml have more than one tag with same name
On your line of thought, I have modified the code a bit and written it for general node instead of root:
from collections import defaultdict
def xml2dict(node):
d, count = defaultdict(list), 1
for i in node:
d[i.tag + "_" + str(count)]['text'] = i.findtext('.')[0]
d[i.tag + "_" + str(count)]['attrib'] = i.attrib # attrib gives the list
d[i.tag + "_" + str(count)]['children'] = xml2dict(i) # it gives dict
return d
Regex to split a CSV
I had a similar need for splitting CSV values from SQL insert statements.
In my case, I could assume that strings were wrapped in single quotations and numbers were not.
csv.split(/,((?=')|(?=\d))/g).filter(function(x) { return x !== '';});
For some probably obvious reason, this regex produces some blank results. I could ignore those, since any empty values in my data were represented as ...,'',...
and not ...,,...
.
How to use range-based for() loop with std::map?
From this paper: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2049.pdf
for( type-speci?er-seq simple-declarator : expression ) statement
is syntactically equivalent to
{
typedef decltype(expression) C;
auto&& rng(expression);
for (auto begin(std::For<C>::begin(rng)), end(std::For<C>::end(rng)); begin != end; ++ begin) {
type-speci?er-seq simple-declarator(*begin);
statement
}
}
So you can clearly see that what is abc
in your case will be std::pair<key_type, value_type >
.
So for printing you can do access each element by abc.first
and abc.second
What are the special dollar sign shell variables?
Take care with some of the examples; $0 may include some leading path as well as the name of the program. Eg save this two line script as ./mytry.sh and the execute it.
#!/bin/bash
echo "parameter 0 --> $0" ; exit 0
Output:
parameter 0 --> ./mytry.sh
This is on a current (year 2016) version of Bash, via Slackware 14.2
How can I change the size of a Bootstrap checkbox?
Following works in bootstrap 4 and displays well in CSS, mobile and has no issues with label spacing.
CSS
.checkbox-lg .custom-control-label::before,
.checkbox-lg .custom-control-label::after {
top: .8rem;
width: 1.55rem;
height: 1.55rem;
}
.checkbox-lg .custom-control-label {
padding-top: 13px;
padding-left: 6px;
}
.checkbox-xl .custom-control-label::before,
.checkbox-xl .custom-control-label::after {
top: 1.2rem;
width: 1.85rem;
height: 1.85rem;
}
.checkbox-xl .custom-control-label {
padding-top: 23px;
padding-left: 10px;
}
HTML
<div class="custom-control custom-checkbox checkbox-lg">
<input type="checkbox" class="custom-control-input" id="checkbox-3">
<label class="custom-control-label" for="checkbox-3">Large checkbox</label>
</div>
You can also make it extra large by declaring checkbox-xl
If anyone from BS team is reading this, it would be really good if you make this available right out of the box, I don't see anything for it in BS 5 either
source
Datetime equal or greater than today in MySQL
SELECT * FROM table_name WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) , '-', SUBSTRING( json_date, 7, 2 ) , '-', SUBSTRING(json_date, 3, 2 ) ) >= NOW();
json_date ["05/11/2011"]
Could not commit JPA transaction: Transaction marked as rollbackOnly
Save sub object first and then call final repository save method.
@PostMapping("/save")
public String save(@ModelAttribute("shortcode") @Valid Shortcode shortcode, BindingResult result) {
Shortcode existingShortcode = shortcodeService.findByShortcode(shortcode.getShortcode());
if (existingShortcode != null) {
result.rejectValue(shortcode.getShortcode(), "This shortode is already created.");
}
if (result.hasErrors()) {
return "redirect:/shortcode/create";
}
**shortcode.setUser(userService.findByUsername(shortcode.getUser().getUsername()));**
shortcodeService.save(shortcode);
return "redirect:/shortcode/create?success";
}
Implementing multiple interfaces with Java - is there a way to delegate?
As said, there's no way. However, a bit decent IDE can autogenerate delegate methods. For example Eclipse can do. First setup a template:
public class MultipleInterfaces implements InterFaceOne, InterFaceTwo {
private InterFaceOne if1;
private InterFaceTwo if2;
}
then rightclick, choose Source > Generate Delegate Methods and tick the both if1
and if2
fields and click OK.
See also the following screens:
How do I determine the size of an object in Python?
Just use the sys.getsizeof function defined in the sys
module.
sys.getsizeof(object[, default])
:
Return the size of an object in bytes.
The object can be any type of object.
All built-in objects will return
correct results, but this does not
have to hold true for third-party
extensions as it is implementation
specific.
Only the memory consumption directly attributed to the object is
accounted for, not the memory consumption of objects it refers to.
The default
argument allows to define
a value which will be returned if the
object type does not provide means to
retrieve the size and would cause a
TypeError
.
getsizeof
calls the object’s
__sizeof__
method and adds an additional garbage collector overhead
if the object is managed by the
garbage collector.
See recursive sizeof recipe for an example of using getsizeof()
recursively to find the size of containers and all their contents.
Usage example, in python 3.0:
>>> import sys
>>> x = 2
>>> sys.getsizeof(x)
24
>>> sys.getsizeof(sys.getsizeof)
32
>>> sys.getsizeof('this')
38
>>> sys.getsizeof('this also')
48
If you are in python < 2.6 and don't have sys.getsizeof
you can use this extensive module instead. Never used it though.
Android: install .apk programmatically
For ICS I´ve implemented your code and made a class that extends AsyncTask
. I hope you appreciate it! Thanks for your code and solution.
public class UpdateApp extends AsyncTask<String,Void,Void>{
private Context context;
public void setContext(Context contextf){
context = contextf;
}
@Override
protected Void doInBackground(String... arg0) {
try {
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = "/mnt/sdcard/Download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "update.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
context.startActivity(intent);
} catch (Exception e) {
Log.e("UpdateAPP", "Update error! " + e.getMessage());
}
return null;
}
}
To use it, in your main activity call by this way:
atualizaApp = new UpdateApp();
atualizaApp.setContext(getApplicationContext());
atualizaApp.execute("http://serverurl/appfile.apk");
How is malloc() implemented internally?
The sbrk
system call moves the "border" of the data segment. This means it moves a border of an area in which a program may read/write data (letting it grow or shrink, although AFAIK no malloc
really gives memory segments back to the kernel with that method). Aside from that, there's also mmap
which is used to map files into memory but is also used to allocate memory (if you need to allocate shared memory, mmap
is how you do it).
So you have two methods of getting more memory from the kernel: sbrk
and mmap
. There are various strategies on how to organize the memory that you've got from the kernel.
One naive way is to partition it into zones, often called "buckets", which are dedicated to certain structure sizes. For example, a malloc
implementation could create buckets for 16, 64, 256 and 1024 byte structures. If you ask malloc
to give you memory of a given size it rounds that number up to the next bucket size and then gives you an element from that bucket. If you need a bigger area malloc
could use mmap
to allocate directly with the kernel. If the bucket of a certain size is empty malloc
could use sbrk
to get more space for a new bucket.
There are various malloc
designs and there is propably no one true way of implementing malloc
as you need to make a compromise between speed, overhead and avoiding fragmentation/space effectiveness. For example, if a bucket runs out of elements an implementation might get an element from a bigger bucket, split it up and add it to the bucket that ran out of elements. This would be quite space efficient but would not be possible with every design. If you just get another bucket via sbrk
/mmap
that might be faster and even easier, but not as space efficient. Also, the design must of course take into account that "free" needs to make space available to malloc
again somehow. You don't just hand out memory without reusing it.
If you're interested, the OpenSER/Kamailio SIP proxy has two malloc
implementations (they need their own because they make heavy use of shared memory and the system malloc
doesn't support shared memory). See: https://github.com/OpenSIPS/opensips/tree/master/mem
Then you could also have a look at the GNU libc malloc
implementation, but that one is very complicated, IIRC.
Get Folder Size from Windows Command Line
You can just add up sizes recursively (the following is a batch file):
@echo off
set size=0
for /r %%x in (folder\*) do set /a size+=%%~zx
echo %size% Bytes
However, this has several problems because cmd
is limited to 32-bit signed integer arithmetic. So it will get sizes above 2 GiB wrong1. Furthermore it will likely count symlinks and junctions multiple times so it's at best an upper bound, not the true size (you'll have that problem with any tool, though).
An alternative is PowerShell:
Get-ChildItem -Recurse | Measure-Object -Sum Length
or shorter:
ls -r | measure -sum Length
If you want it prettier:
switch((ls -r|measure -sum Length).Sum) {
{$_ -gt 1GB} {
'{0:0.0} GiB' -f ($_/1GB)
break
}
{$_ -gt 1MB} {
'{0:0.0} MiB' -f ($_/1MB)
break
}
{$_ -gt 1KB} {
'{0:0.0} KiB' -f ($_/1KB)
break
}
default { "$_ bytes" }
}
You can use this directly from cmd
:
powershell -noprofile -command "ls -r|measure -sum Length"
1 I do have a partially-finished bignum library in batch files somewhere which at least gets arbitrary-precision integer addition right. I should really release it, I guess :-)
How to select a range of the second row to the last row
Try this:
Dim Lastrow As Integer
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Range("A2:L" & Lastrow).Select
Let's pretend that the value of Lastrow
is 50. When you use the following:
Range("A2:L2" & Lastrow).Select
Then it is selecting a range from A2 to L250.
Bypass invalid SSL certificate errors when calling web services in .Net
The approach I used when faced with this problem was to add the signer of the temporary certificate to the trusted authorities list on the computer in question.
I normally do testing with certificates created with CACERT, and adding them to my trusted authorities list worked swimmingly.
Doing it this way means you don't have to add any custom code to your application and it properly simulates what will happen when your application is deployed. As such, I think this is a superior solution to turning off the check programmatically.
Removing multiple keys from a dictionary safely
I think using the fact that the keys can be treated as a set is the nicest way if you're on python 3:
def remove_keys(d, keys):
to_remove = set(keys)
filtered_keys = d.keys() - to_remove
filtered_values = map(d.get, filtered_keys)
return dict(zip(filtered_keys, filtered_values))
Example:
>>> remove_keys({'k1': 1, 'k3': 3}, ['k1', 'k2'])
{'k3': 3}
Python strftime - date without leading 0?
using, for example, "%-d" is not portable even between different versions of the same OS.
A better solution would be to extract the date components individually, and choose between date specific formatting operators and date attribute access for each component.
e = datetime.date(2014, 1, 6)
"{date:%A} {date.day} {date:%B}{date.year}".format(date=e)
Using Node.js require vs. ES6 import/export
The most important thing to know is that ES6 modules are, indeed, an official standard, while CommonJS (Node.js) modules are not.
In 2019, ES6 modules are supported by 84% of browsers. While Node.js puts them behind an --experimental-modules flag, there is also a convenient node package called esm, which makes the integration smooth.
Another issue you're likely to run into between these module systems is code location. Node.js assumes source is kept in a node_modules
directory, while most ES6 modules are deployed in a flat directory structure. These are not easy to reconcile, but it can be done by hacking your package.json
file with pre and post installation scripts. Here is an example isomorphic module and an article explaining how it works.
npm command to uninstall or prune unused packages in Node.js
You can use npm-prune to remove extraneous packages.
npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]
This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.
Extraneous packages are packages that are not listed on the parent package's dependencies list.
If the --production flag is specified or the NODE_ENV environment variable is set to production, this command will remove the packages specified in your devDependencies. Setting --no-production will negate NODE_ENV being set to production.
If the --dry-run flag is used then no changes will actually be made.
If the --json flag is used then the changes npm prune made (or would have made with --dry-run) are printed as a JSON object.
In normal operation with package-locks enabled, extraneous modules are pruned automatically when modules are installed and you'll only need this command with the --production flag.
If you've disabled package-locks then extraneous modules will not be removed and it's up to you to run npm prune from time-to-time to remove them.
Use npm-dedupe to reduce duplication
npm dedupe
npm ddp
Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.
For example, consider this dependency graph:
a
+-- b <-- depends on [email protected]
| `-- [email protected]
`-- d <-- depends on c@~1.0.9
`-- [email protected]
In this case, npm-dedupe will transform the tree to:
a
+-- b
+-- d
`-- [email protected]
Because of the hierarchical nature of node's module lookup, b and d will both get their dependency met by the single c package at the root level of the tree.
The deduplication algorithm walks the tree, moving each dependency as far up in the tree as possible, even if duplicates are not found. This will result in both a flat and deduplicated tree.
Purpose of Activator.CreateInstance with example?
Well i can give you an example why to use something like that. Think of a game where you want to store your level and enemies in an XML file. When you parse this file, you might have an element like this.
<Enemy X="10" Y="100" Type="MyGame.OrcGuard"/>
what you can do now is, create dynamically the objects found in your level file.
foreach(XmlNode node in doc)
var enemy = Activator.CreateInstance(null, node.Attributes["Type"]);
This is very useful, for building dynamic enviroments. Of course its also possible to use this for Plugin or addin scenarios and alot more.
Force Java timezone as GMT/UTC
The OP answered this question to change the default timezone for a single instance of a running JVM, set the user.timezone
system property:
java -Duser.timezone=GMT ... <main-class>
If you need to set specific time zones when retrieving Date/Time/Timestamp objects from a database ResultSet
, use the second form of the getXXX
methods that takes a Calendar
object:
Calendar tzCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
ResultSet rs = ...;
while (rs.next()) {
Date dateValue = rs.getDate("DateColumn", tzCal);
// Other fields and calculations
}
Or, setting the date in a PreparedStatement:
Calendar tzCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
PreparedStatement ps = conn.createPreparedStatement("update ...");
ps.setDate("DateColumn", dateValue, tzCal);
// Other assignments
ps.executeUpdate();
These will ensure that the value stored in the database is consistent when the database column does not keep timezone information.
The java.util.Date
and java.sql.Date
classes store the actual time (milliseconds) in UTC. To format these on output to another timezone, use SimpleDateFormat
. You can also associate a timezone with the value using a Calendar object:
TimeZone tz = TimeZone.getTimeZone("<local-time-zone>");
//...
Date dateValue = rs.getDate("DateColumn");
Calendar calValue = Calendar.getInstance(tz);
calValue.setTime(dateValue);
Usefull Reference
https://docs.oracle.com/javase/9/troubleshoot/time-zone-settings-jre.htm#JSTGD377
https://confluence.atlassian.com/kb/setting-the-timezone-for-the-java-environment-841187402.html
Window.open as modal popup?
You can try open a modal dialog with html5 and css3, try this code:
_x000D_
_x000D_
.windowModal {_x000D_
position: fixed;_x000D_
font-family: Arial, Helvetica, sans-serif;_x000D_
top: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
background: rgba(0,0,0,0.8);_x000D_
z-index: 99999;_x000D_
opacity:0;_x000D_
-webkit-transition: opacity 400ms ease-in;_x000D_
-moz-transition: opacity 400ms ease-in;_x000D_
transition: opacity 400ms ease-in;_x000D_
pointer-events: none;_x000D_
}_x000D_
.windowModal:target {_x000D_
opacity:1;_x000D_
pointer-events: auto;_x000D_
}_x000D_
_x000D_
.windowModal > div {_x000D_
width: 400px;_x000D_
position: relative;_x000D_
margin: 10% auto;_x000D_
padding: 5px 20px 13px 20px;_x000D_
border-radius: 10px;_x000D_
background: #fff;_x000D_
background: -moz-linear-gradient(#fff, #999);_x000D_
background: -webkit-linear-gradient(#fff, #999);_x000D_
background: -o-linear-gradient(#fff, #999);_x000D_
}_x000D_
.close {_x000D_
background: #606061;_x000D_
color: #FFFFFF;_x000D_
line-height: 25px;_x000D_
position: absolute;_x000D_
right: -12px;_x000D_
text-align: center;_x000D_
top: -10px;_x000D_
width: 24px;_x000D_
text-decoration: none;_x000D_
font-weight: bold;_x000D_
-webkit-border-radius: 12px;_x000D_
-moz-border-radius: 12px;_x000D_
border-radius: 12px;_x000D_
-moz-box-shadow: 1px 1px 3px #000;_x000D_
-webkit-box-shadow: 1px 1px 3px #000;_x000D_
box-shadow: 1px 1px 3px #000;_x000D_
}_x000D_
_x000D_
.close:hover { background: #00d9ff; }
_x000D_
<a href="#divModal">Open Modal Window</a>_x000D_
_x000D_
<div id="divModal" class="windowModal">_x000D_
<div>_x000D_
<a href="#close" title="Close" class="close">X</a>_x000D_
<h2>Modal Dialog</h2>_x000D_
<p>This example shows a modal window without using javascript only using html5 and css3, I try it it¡</p>_x000D_
<p>Using javascript, with new versions of html5 and css3 is not necessary can do whatever we want without using js libraries.</p>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How to validate IP address in Python?
I have to give a great deal of credit to Markus Jarderot for his post - the majority of my post is inspired from his.
I found that Markus' answer still fails some of the IPv6 examples in the Perl script referenced by his answer.
Here is my regex that passes all of the examples in that Perl script:
r"""^
\s* # Leading whitespace
# Zero-width lookaheads to reject too many quartets
(?:
# 6 quartets, ending IPv4 address; no wildcards
(?:[0-9a-f]{1,4}(?::(?!:))){6}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-5 quartets, wildcard, ending IPv4 address
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
(?:::(?!:))
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-4 quartets, wildcard, 0-1 quartets, ending IPv4 address
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:)))?
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-3 quartets, wildcard, 0-2 quartets, ending IPv4 address
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:))){0,2}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-2 quartets, wildcard, 0-3 quartets, ending IPv4 address
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:))){0,3}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-1 quartets, wildcard, 0-4 quartets, ending IPv4 address
(?:[0-9a-f]{1,4}){0,1}
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:))){0,4}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# wildcard, 0-5 quartets, ending IPv4 address
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:))){0,5}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 8 quartets; no wildcards
(?:[0-9a-f]{1,4}(?::(?!:))){7}[0-9a-f]{1,4}
|
# 0-7 quartets, wildcard
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?
(?:::(?!:))
|
# 0-6 quartets, wildcard, 0-1 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?
(?:::(?!:))
(?:[0-9a-f]{1,4})?
|
# 0-5 quartets, wildcard, 0-2 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
|
# 0-4 quartets, wildcard, 0-3 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
|
# 0-3 quartets, wildcard, 0-4 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
|
# 0-2 quartets, wildcard, 0-5 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
|
# 0-1 quartets, wildcard, 0-6 quartets
(?:[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?
|
# wildcard, 0-7 quartets
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?
)
(?:/(?:1(?:2[0-7]|[01]\d)|\d\d?))? # With an optional CIDR routing prefix (0-128)
\s* # Trailing whitespace
$"""
I also put together a Python script to test all of those IPv6 examples; it's here on Pastebin because it was too large to post here.
You can run the script with test result and example arguments in the form of "[result]=[example]", so like:
python script.py Fail=::1.2.3.4: pass=::127.0.0.1 false=::: True=::1
or you can simply run all of the tests by specifying no arguments, so like:
python script.py
Anyway, I hope this helps somebody else!
Ajax success event not working
I tried removing the dataType row and it didn't work for me. I got around the issue by using "complete" instead of "success" as the callback. The success callback still fails in IE, but since my script runs and completes anyway that's all I care about.
$.ajax({
type: 'POST',
url: 'somescript.php',
data: someData,
complete: function(jqXHR) {
if(jqXHR.readyState === 4) {
... run some code ...
}
}
});
in jQuery 1.5 you can also do it like this.
var ajax = $.ajax({
type: 'POST',
url: 'somescript.php',
data: 'someData'
});
ajax.complete(function(jqXHR){
if(jqXHR.readyState === 4) {
... run some code ...
}
});
How to install all required PHP extensions for Laravel?
Laravel Server Requirements mention that BCMath
, Ctype
, JSON
, Mbstring
, OpenSSL
, PDO
, Tokenizer
, and XML
extensions are required. Most of the extensions are installed and enabled by default.
You can run the following command in Ubuntu to make sure the extensions are installed.
sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip
PHP version specific installation (if PHP 7.4 installed)
sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring
You may need other PHP extensions for your composer packages. Find from links below.
PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)
PHP extensions for Ubuntu 18.04 LTS (Bionic)
PHP extensions for Ubuntu 16.04 LTS (Xenial)
Posting form to different MVC post action depending on the clicked submit button
You can choose the url where the form must be posted (and thus, the invoked action) in different ways, depending on the browser support:
In this way you don't need to do anything special on the server side.
Of course, you can use Url
extensions methods in your Razor to specify the form action.
For browsers supporting HMTL5: simply define your submit buttons like this:
<input type='submit' value='...' formaction='@Url.Action(...)' />
For older browsers I recommend using an unobtrusive script like this (include it in your "master layout"):
$(document).on('click', '[type="submit"][data-form-action]', function (event) {
var $this = $(this);
var formAction = $this.attr('data-form-action');
$this.closest('form').attr('action', formAction);
});
NOTE: This script will handle the click for any element in the page that has type=submit
and data-form-action
attributes. When this happens, it takes the value of data-form-action
attribute and set the containing form's action to the value of this attribute. As it's a delegated event, it will work even for HTML loaded using AJAX, without taking extra steps.
Then you simply have to add a data-form-action
attribute with the desired action URL to your button, like this:
<input type='submit' data-form-action='@Url.Action(...)' value='...'/>
Note that clicking the button changes the form's action, and, right after that, the browser posts the form to the desired action.
As you can see, this requires no custom routing, you can use the standard Url
extension methods, and you have nothing special to do in modern browsers.
How to call Oracle MD5 hash function?
In Oracle 12c you can use the function STANDARD_HASH. It does not require any additional privileges.
select standard_hash('foo', 'MD5') from dual;
The dbms_obfuscation_toolkit is deprecated (see Note here). You can use DBMS_CRYPTO directly:
select rawtohex(
DBMS_CRYPTO.Hash (
UTL_I18N.STRING_TO_RAW ('foo', 'AL32UTF8'),
2)
) from dual;
Output:
ACBD18DB4CC2F85CEDEF654FCCC4A4D8
Add a lower function call if needed. More on DBMS_CRYPTO.
How to store date/time and timestamps in UTC time zone with JPA and Hibernate
I encountered just the same problem when I wanted to store the dates in the DB as UTC and avoid using varchar
and explicit String <-> java.util.Date
conversions, or setting my whole Java app in the UTC time zone (because this could lead to another unexpected issues, if the JVM is shared across many applications).
So, there is an open source project DbAssist
, which allows you to easily fix the read/write as UTC date from the database. Since you are using JPA Annotations to map the fields in the entity, all you have to do is to include the following dependency to your Maven pom
file:
<dependency>
<groupId>com.montrosesoftware</groupId>
<artifactId>DbAssist-5.2.2</artifactId>
<version>1.0-RELEASE</version>
</dependency>
Then you apply the fix (for Hibernate + Spring Boot example) by adding @EnableAutoConfiguration
annotation before the Spring application class. For other setups installation instructions and more use examples, just refer to the project's github.
The good thing is that you don't have to modify the entities at all; you can leave their java.util.Date
fields as they are.
5.2.2
has to correspond to the Hibernate version you are using. I am not sure, which version you are using in your project, but the full list of provided fixes is available on the wiki page of the project's github. The reason why the fix is different for various Hibernate versions is because Hibernate creators changed the API a couple of times between the releases.
Internally, the fix uses hints from divestoclimb, Shane and a few other sources in order to create a custom UtcDateType
. Then it maps the standard java.util.Date
with the custom UtcDateType
which handles all the necessary time zone handling.
The mapping of the types is achieved using @Typedef
annotation in the provided package-info.java
file.
@TypeDef(name = "UtcDateType", defaultForType = Date.class, typeClass = UtcDateType.class),
package com.montrosesoftware.dbassist.types;
You can find an article here which explains why such a time shift occurs at all and what are the approaches to solve it.
urllib2.HTTPError: HTTP Error 403: Forbidden
import urllib.request
bank_pdf_list = ["https://www.hdfcbank.com/content/bbp/repositories/723fb80a-2dde-42a3-9793-7ae1be57c87f/?path=/Personal/Home/content/rates.pdf",
"https://www.yesbank.in/pdf/forexcardratesenglish_pdf",
"https://www.sbi.co.in/documents/16012/1400784/FOREX_CARD_RATES.pdf"]
def get_pdf(url):
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
#url = "https://www.yesbank.in/pdf/forexcardratesenglish_pdf"
headers={'User-Agent':user_agent,}
request=urllib.request.Request(url,None,headers) #The assembled request
response = urllib.request.urlopen(request)
#print(response.text)
data = response.read()
# print(type(data))
name = url.split("www.")[-1].split("//")[-1].split(".")[0]+"_FOREX_CARD_RATES.pdf"
f = open(name, 'wb')
f.write(data)
f.close()
for bank_url in bank_pdf_list:
try:
get_pdf(bank_url)
except:
pass
How to increase size of DOSBox window?
go to dosbox installation directory (on my machine that is C:\Program Files (x86)\DOSBox-0.74 ) as you see the version number is part of the installation directory name.
run "DOSBox 0.74 Options.bat"
the script starts notepad with configuration file: here change
windowresolution=1600x800
output=ddraw
(the resolution can't be changed if output=surface - that's the default).
- safe configuration file changes.
Returning Promises from Vuex actions
TL:DR; return promises from you actions only when necessary, but DRY chaining the same actions.
For a long time I also though that returning actions contradicts the Vuex cycle of uni-directional data flow.
But, there are EDGE CASES where returning a promise from your actions might be "necessary".
Imagine a situation where an action can be triggered from 2 different components, and each handles the failure case differently.
In that case, one would need to pass the caller component as a parameter to set different flags in the store.
Dumb example
Page where the user can edit the username in navbar and in /profile page (which contains the navbar). Both trigger an action "change username", which is asynchronous.
If the promise fails, the page should only display an error in the component the user was trying to change the username from.
Of course it is a dumb example, but I don't see a way to solve this issue without duplicating code and making the same call in 2 different actions.
Vue.js—Difference between v-model and v-bind
There are cases where you don't want to use v-model
. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.
In these cases, it's not a good idea to use either watchers or computed properties.
Instead, take your v-model
and split it as above answer indicates
<input
:value="something"
@input="something = $event.target.value"
>
In practice, if you are decoupling your logic this way, you'll probably be calling a method.
This is what it would look like in a real world scenario:
_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
<input :value="extendedCost" @input="_onInputExtendedCost" />_x000D_
<p> {{ extendedCost }}_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
var app = new Vue({_x000D_
el: "#app",_x000D_
data: function(){_x000D_
return {_x000D_
extendedCost: 0,_x000D_
}_x000D_
},_x000D_
methods: {_x000D_
_onInputExtendedCost: function($event) {_x000D_
this.extendedCost = parseInt($event.target.value);_x000D_
// Go update other inputs here_x000D_
}_x000D_
}_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_
Losing scope when using ng-include
I've figured out how to work around this issue without mixing parent and sub scope data.
Set a ng-if
on the the ng-include
element and set it to a scope variable.
For example :
<div ng-include="{{ template }}" ng-if="show"/>
In your controller, when you have set all the data you need in your sub scope, then set show to true
. The ng-include
will copy at this moment the data set in your scope and set it in your sub scope.
The rule of thumb is to reduce scope data deeper the scope are, else you have this situation.
Max
Loop through the rows of a particular DataTable
You want to loop on the .Rows, and access the column for the row like q("column")
Just:
For Each q In dtDataTable.Rows
strDetail = q("Detail")
Next
Also make sure to check msdn doc for any class you are using + use intellisense
How to read data from a file in Lua
Try this:
-- http://lua-users.org/wiki/FileInputOutput
-- see if the file exists
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then return {} end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- tests the functions above
local file = 'test.lua'
local lines = lines_from(file)
-- print all line numbers and their contents
for k,v in pairs(lines) do
print('line[' .. k .. ']', v)
end
Convert multidimensional array into single array
If you come across a multidimensional array that is pure data, like this one below, then you can use a single call to array_merge() to do the job via reflection:
$arrayMult = [ ['a','b'] , ['c', 'd'] ];
$arraySingle = call_user_func_array('array_merge', $arrayMult);
// $arraySingle is now = ['a','b', 'c', 'd'];
MongoDB: Combine data from multiple collections into one..how?
Code snippet. Courtesy-Multiple posts on stack overflow including this one.
db.cust.drop();
db.zip.drop();
db.cust.insert({cust_id:1, zip_id: 101});
db.cust.insert({cust_id:2, zip_id: 101});
db.cust.insert({cust_id:3, zip_id: 101});
db.cust.insert({cust_id:4, zip_id: 102});
db.cust.insert({cust_id:5, zip_id: 102});
db.zip.insert({zip_id:101, zip_cd:'AAA'});
db.zip.insert({zip_id:102, zip_cd:'BBB'});
db.zip.insert({zip_id:103, zip_cd:'CCC'});
mapCust = function() {
var values = {
cust_id: this.cust_id
};
emit(this.zip_id, values);
};
mapZip = function() {
var values = {
zip_cd: this.zip_cd
};
emit(this.zip_id, values);
};
reduceCustZip = function(k, values) {
var result = {};
values.forEach(function(value) {
var field;
if ("cust_id" in value) {
if (!("cust_ids" in result)) {
result.cust_ids = [];
}
result.cust_ids.push(value);
} else {
for (field in value) {
if (value.hasOwnProperty(field) ) {
result[field] = value[field];
}
};
}
});
return result;
};
db.cust_zip.drop();
db.cust.mapReduce(mapCust, reduceCustZip, {"out": {"reduce": "cust_zip"}});
db.zip.mapReduce(mapZip, reduceCustZip, {"out": {"reduce": "cust_zip"}});
db.cust_zip.find();
mapCZ = function() {
var that = this;
if ("cust_ids" in this.value) {
this.value.cust_ids.forEach(function(value) {
emit(value.cust_id, {
zip_id: that._id,
zip_cd: that.value.zip_cd
});
});
}
};
reduceCZ = function(k, values) {
var result = {};
values.forEach(function(value) {
var field;
for (field in value) {
if (value.hasOwnProperty(field)) {
result[field] = value[field];
}
}
});
return result;
};
db.cust_zip_joined.drop();
db.cust_zip.mapReduce(mapCZ, reduceCZ, {"out": "cust_zip_joined"});
db.cust_zip_joined.find().pretty();
var flattenMRCollection=function(dbName,collectionName) {
var collection=db.getSiblingDB(dbName)[collectionName];
var i=0;
var bulk=collection.initializeUnorderedBulkOp();
collection.find({ value: { $exists: true } }).addOption(16).forEach(function(result) {
print((++i));
//collection.update({_id: result._id},result.value);
bulk.find({_id: result._id}).replaceOne(result.value);
if(i%1000==0)
{
print("Executing bulk...");
bulk.execute();
bulk=collection.initializeUnorderedBulkOp();
}
});
bulk.execute();
};
flattenMRCollection("mydb","cust_zip_joined");
db.cust_zip_joined.find().pretty();
The difference between sys.stdout.write and print?
My question is whether or not there are situations in which sys.stdout.write()
is preferable to print
If you're writing a command line application that can write to both files and stdout then it is handy. You can do things like:
def myfunc(outfile=None):
if outfile is None:
out = sys.stdout
else:
out = open(outfile, 'w')
try:
# do some stuff
out.write(mytext + '\n')
# ...
finally:
if outfile is not None:
out.close()
It does mean you can't use the with open(outfile, 'w') as out:
pattern, but sometimes it is worth it.
CSS background-image-opacity?
Try this
<div style="background: linear-gradient( rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7) ), url(/image.png);background-repeat: no-repeat; background-position: center;"> </div>
"Logging out" of phpMyAdmin?
This happens because the current account you have used to log in probably has very limited priviledges.
To fix this problem, you can change your the AllowNoPassword config setting to false in config.inc.php
. You may also force the authentication to use the config file and specify the default username and password .
$cfg['Servers'][$i]['AllowNoPassword'] = false;
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = ''; // leave blank if no password
After this, the PhPMyAdmin login page should show up when you refresh the page.
You can then log in with the default root password.
More details can be found on this post ..
Importing class from another file
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
How can I hide/show a div when a button is clicked?
Use JQuery. You need to set-up a click event on your button which will toggle the visibility of your wizard div.
$('#btn').click(function() {
$('#wizard').toggle();
});
Refer to the JQuery website for more information.
This can also be done without JQuery. Using only standard JavaScript:
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
Then add onclick="toggle_visibility('id_of_element_to_toggle');"
to the button that is used to show and hide the div.
WRONGTYPE Operation against a key holding the wrong kind of value php
Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.
Here are the commands to retrieve key value:
- if value is of type string -> GET
<key>
- if value is of type hash -> HGETALL
<key>
- if value is of type lists -> lrange
<key> <start> <end>
- if value is of type sets -> smembers
<key>
- if value is of type sorted sets -> ZRANGEBYSCORE
<key> <min> <max>
Use the TYPE
command to check the type of value a key is mapping to:
What does it mean to "program to an interface"?
Imagine you have a product called 'Zebra' that can be extended by plugins. It finds the plugins by searching for DLLs in some directory. It loads all those DLLs and uses reflection to find any classes that implement IZebraPlugin
, and then calls the methods of that interface to communicate with the plugins.
This makes it completely independent of any specific plugin class - it doesn't care what the classes are. It only cares that they fulfill the interface specification.
Interfaces are a way of defining points of extensibility like this. Code that talks to an interface is more loosely coupled - in fact it is not coupled at all to any other specific code. It can inter-operate with plugins written years later by people who have never met the original developer.
You could instead use a base class with virtual functions - all plugins would be derived from the base class. But this is much more limiting because a class can only have one base class, whereas it can implement any number of interfaces.
How can I change default dialog button text color in android 5
Using styles.xml (value)
Very Easy solution , change colorPrimary as your choice and it will change color of button text of alert box.
<style name="MyAlertDialogStyle" parent="android:Theme.Material.Dialog.Alert">
<!-- Used for the buttons -->
<item name="colorAccent">@android:color/white</item>
<!-- Used for the title and text -->
<item name="android:textColorPrimary">@color/black</item>
<!-- Used for the background -->
<item name="android:background">#ffffff</item>
<item name="android:colorPrimary">@color/white</item>
<item name="android:colorAccent">@color/white</item>
<item name="android:windowEnterAnimation">@anim/bottom_left_enter</item>
</style>
Alternative (Using Java)
@SuppressLint("ResourceAsColor")
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
AlertDialog dialog = new AlertDialog.Builder(view.getContext(), R.style.MyAlertDialogStyle)
.setTitle("Royal Frolics")
.setIcon(R.mipmap.ic_launcher)
.setMessage(message)
.setPositiveButton("OK", (dialog1, which) -> {
//do nothing
result.confirm();
}).create();
Objects.requireNonNull(dialog.getWindow()).getAttributes().windowAnimations = R.style.MyAlertDialogStyle;
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(R.color.white);
return true;
}
Switch statement with returns -- code correctness
Keep the breaks - you're less likely to run into trouble if/when you edit the code later if the breaks are already in place.
Having said that, it's considered by many (including me) to be bad practice to return from the middle of a function. Ideally a function should have one entry point and one exit point.
Case objects vs Enumerations in Scala
I think the biggest advantage of having case classes
over enumerations
is that you can use type class pattern a.k.a ad-hoc polymorphysm. Don't need to match enums like:
someEnum match {
ENUMA => makeThis()
ENUMB => makeThat()
}
instead you'll have something like:
def someCode[SomeCaseClass](implicit val maker: Maker[SomeCaseClass]){
maker.make()
}
implicit val makerA = new Maker[CaseClassA]{
def make() = ...
}
implicit val makerB = new Maker[CaseClassB]{
def make() = ...
}
MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?
Alright so after trying every solution out there to solve this exact issues on a wordpress blog, I might have done something either really stupid or genius... With no idea why there's an increase in Mysql connections, I used the php script below in my header to kill all sleeping processes..
So every visitor to my site helps in killing the sleeping processes..
<?php
$result = mysql_query("SHOW processlist");
while ($myrow = mysql_fetch_assoc($result)) {
if ($myrow['Command'] == "Sleep") {
mysql_query("KILL {$myrow['Id']}");}
}
?>
Visual studio code CSS indentation and formatting
There are several to pick from in the gallery but the one I'm using, which offers considerable level of configurability still remaining unobtrusive to the rest of the settings is Beautify by Michele Melluso. It works on both CSS and SCSS and lets you indent 3 spaces keeping the rest of the code at 2 spaces, which is nice.
You can snatch it from GitHub and adapt it yourself, should you feel like it too.
How to use variables in SQL statement in Python?
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
Note that the parameters are passed as a tuple.
The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (%
), because
- it does not do any escaping or quoting.
- it is prone to Uncontrolled string format attacks e.g. SQL injection.
How can foreign key constraints be temporarily disabled using T-SQL?
WITH CHECK CHECK
is almost certainly required!
This point was raised in some of the answers and comments but I feel that it is important enough to call it out again.
Re-enabling a constraint using the following command (no WITH CHECK
) will have some serious drawbacks.
ALTER TABLE MyTable CHECK CONSTRAINT MyConstraint;
WITH CHECK | WITH NOCHECK
Specifies whether the data in the table is or is not validated against
a newly added or re-enabled FOREIGN KEY or CHECK constraint. If not
specified, WITH CHECK is assumed for new constraints, and WITH NOCHECK
is assumed for re-enabled constraints.
If you do not want to verify new CHECK or FOREIGN KEY constraints
against existing data, use WITH NOCHECK. We do not recommend doing
this, except in rare cases. The new constraint will be evaluated in
all later data updates. Any constraint violations that are suppressed
by WITH NOCHECK when the constraint is added may cause future updates
to fail if they update rows with data that does not comply with the
constraint.
The query optimizer does not consider constraints that are defined
WITH NOCHECK. Such constraints are ignored until they are re-enabled
by using ALTER TABLE table WITH CHECK CHECK CONSTRAINT ALL.
Note: WITH NOCHECK is the default for re-enabling constraints. I have to wonder why...
- No existing data in the table will be evaluated during the execution of this command - successful completion is no guarantee that the data in the table is valid according to the constraint.
- During the next update of the invalid records, the constraint will be evaluated and will fail - resulting in errors that may be unrelated to the actual update that is made.
- Application logic that relies on the constraint to ensure that data is valid may fail.
- The query optimizer will not make use of any constraint that is enabled in this way.
The sys.foreign_keys system view provides some visibility into the issue. Note that it has both an is_disabled
and an is_not_trusted
column. is_disabled
indicates whether future data manipulation operations will be validated against the constraint. is_not_trusted
indicates whether all of the data currently in the table has been validated against the constraint.
ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT MyConstraint;
Are your constraints to be trusted? Find out...
SELECT * FROM sys.foreign_keys WHERE is_not_trusted = 1;
Pressed <button> selector
Should we include a little JS? Because CSS was not basically created for this job. CSS was just a style sheet to add styles to the HTML, but its pseudo classes can do something that the basic CSS can't do. For example button:active
active is pseudo.
Reference:
http://css-tricks.com/pseudo-class-selectors/ You can learn more about pseudo here!
Your code:
The code that you're having the basic but helpfull. And yes :active
will only occur once the click event is triggered.
button {
font-size: 18px;
border: 2px solid gray;
border-radius: 100px;
width: 100px;
height: 100px;
}
button:active {
font-size: 18px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}
This is what CSS would do, what rlemon suggested is good, but that would as he suggested would require a
tag.
How to use CSS:
You can use :focus
too. :focus
would work once the click is made and would stay untill you click somewhere else, this was the CSS, you were trying to use CSS, so use :focus
to make the buttons change.
What JS would do:
The JavaScript's jQuery library is going to help us for this code. Here is the example:
$('button').click(function () {
$(this).css('border', '1px solid red');
}
This will make sure that the button stays red even if the click gets out. To change the focus type (to change the color of red to other) you can use this:
$('button').click(function () {
$(this).css('border', '1px solid red');
// find any other button with a specific id, and change it back to white like
$('button#red').css('border', '1px solid white');
}
This way, you will create a navigation menu. Which will automatically change the color of the tabs as you click on them. :)
Hope you get the answer. Good luck! Cheers.
How to add a second x-axis in matplotlib
Answering your question in Dhara's answer comments: "I would like on the second x-axis these tics: (7,8,99) corresponding to the x-axis position 10, 30, 40. Is that possible in some way?"
Yes, it is.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
a = np.cos(2*np.pi*np.linspace(0, 1, 60.))
ax1.plot(range(60), a)
ax1.set_xlim(0, 60)
ax1.set_xlabel("x")
ax1.set_ylabel("y")
ax2 = ax1.twiny()
ax2.set_xlabel("x-transformed")
ax2.set_xlim(0, 60)
ax2.set_xticks([10, 30, 40])
ax2.set_xticklabels(['7','8','99'])
plt.show()
You'll get:
How can I install a .ipa file to my iPhone simulator
In Xcode 6+ and iOS8+ you can do the simple steps below
- Paste .app file on desktop.
Open terminal and paste the commands below:
cd desktop
xcrun simctl install booted xyz.app
- Open iPhone simulator and click on app and use
For versions below iOS 8, do the following simple steps.
Note: You'll want to make sure that your app is built for all architectures, the Simulator is x386
in the Build Settings and Build Active Architecture Only
set to No
.
- Path: Library->Application Support->iPhone Simulator->7.1 (or another version if you need it)->Applications
- Create a new folder with the name of the app
- Go inside the folder and place the .app file here.
Get all object attributes in Python?
I use __dict__
Example:
class MyObj(object):
def __init__(self):
self.name = 'Chuck Norris'
self.phone = '+6661'
obj = MyObj()
print(obj.__dict__)
# Output:
# {'phone': '+6661', 'name': 'Chuck Norris'}
sscanf in Python
When I'm in a C mood, I usually use zip and list comprehensions for scanf-like behavior. Like this:
input = '1 3.0 false hello'
(a, b, c, d) = [t(s) for t,s in zip((int,float,strtobool,str),input.split())]
print (a, b, c, d)
Note that for more complex format strings, you do need to use regular expressions:
import re
input = '1:3.0 false,hello'
(a, b, c, d) = [t(s) for t,s in zip((int,float,strtobool,str),re.search('^(\d+):([\d.]+) (\w+),(\w+)$',input).groups())]
print (a, b, c, d)
Note also that you need conversion functions for all types you want to convert. For example, above I used something like:
strtobool = lambda s: {'true': True, 'false': False}[s]
How do I read a string entered by the user in C?
Using scanf
removing any blank spaces before the string is typed and limiting the amount of characters to be read:
#define SIZE 100
....
char str[SIZE];
scanf(" %99[^\n]", str);
/* Or even you can do it like this */
scanf(" %99[a-zA-Z0-9 ]", str);
If you do not limit the amount of characters to be read with scanf
it can be as dangerous as gets
How to send a stacktrace to log4j?
This answer may be not related to the question asked but related to title of the question.
public class ThrowableTest {
public static void main(String[] args) {
Throwable createdBy = new Throwable("Created at main()");
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(os);
createdBy.printStackTrace(pw);
try {
pw.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
logger.debug(os.toString());
}
}
OR
public static String getStackTrace (Throwable t)
{
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
t.printStackTrace(printWriter);
printWriter.close(); //surprise no IO exception here
try {
stringWriter.close();
}
catch (IOException e) {
}
return stringWriter.toString();
}
OR
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for(StackTraceElement stackTrace: stackTraceElements){
logger.debug(stackTrace.getClassName()+ " "+ stackTrace.getMethodName()+" "+stackTrace.getLineNumber());
}
How to change text transparency in HTML/CSS?
There is no CSS property like background-opacity that you can use only for changing the opacity or transparency of an element's background without affecting the child elements, on the other hand if you will try to use the CSS opacity property it will not only changes the opacity of background but changes the opacity of all the child elements as well.
In such situation you can use RGBA color introduced in CSS3 that includes alpha transparency as part of the color value. Using RGBA color you can set the color of the background as well as its transparency.
How to check if a Docker image with a specific tag exist locally?
In bash script I do this to check if image exists by tag :
IMAGE_NAME="mysql:5.6"
if docker image ls -a "$IMAGE_NAME" | grep -Fq "$IMAGE_NAME" 1>/dev/null; then
echo "could found image $IMAGE_NAME..."
fi
Example script above checks if mysql image with 5.6 tag exists. If you want just check if any mysql image exists without specific version then just pass repository name without tag as this :
IMAGE_NAME="mysql"
JavaScript: replace last occurrence of text in a string
Old fashioned and big code but efficient as possible:
function replaceLast(origin,text){
textLenght = text.length;
originLen = origin.length
if(textLenght == 0)
return origin;
start = originLen-textLenght;
if(start < 0){
return origin;
}
if(start == 0){
return "";
}
for(i = start; i >= 0; i--){
k = 0;
while(origin[i+k] == text[k]){
k++
if(k == textLenght)
break;
}
if(k == textLenght)
break;
}
//not founded
if(k != textLenght)
return origin;
//founded and i starts on correct and i+k is the first char after
end = origin.substring(i+k,originLen);
if(i == 0)
return end;
else{
start = origin.substring(0,i)
return (start + end);
}
}
How to format font style and color in echo
foreach($months as $key => $month){
if(strpos($filename,$month)!==false){
echo "<div style ='font:11px/21px Arial,tahoma,sans-serif;color:#ff0000'> Movie List for $key 2013</div>";
}
}
Reducing video size with same format and reducing frame size
Instead of chosing fixed bit rates, with the H.264 codec, you can also chose a different preset as described at https://trac.ffmpeg.org/wiki/x264EncodingGuide. I also found Video encoder comparison at KeyJ's blog (archived version) an interesting read, it compares H.264 against Theora and others.
Following is a comparison of various options I tried. The recorded video was originally 673M in size, taken on an iPad using RecordMyScreen. It has a duration of about 20 minutes with a resolution of 1024x768 (with half of the video being blank, so I cropped it to 768x768). In order to reduce size, I lowered the resolution to 480x480. There is no audio.
The results, taking the same 1024x768 as base (and applying cropping, scaling and a filter):
- With no special options: 95M (encoding time: 1m19s).
- With only
-b 512k
added, the size dropped to 77M (encoding time: 1m17s).
- With only
-preset veryslow
(and no -b
), it became 70M (encoding time: 6m14s)
- With both
-b 512k
and -preset veryslow
, the size becomes 77M (100K smaller than just -b 512k
).
- With
-preset veryslow -crf 28
, I get a file of 39M which took 5m47s (with no visual quality difference to me).
N=1, so take the results with a grain of salt and perform your own tests.
What's NSLocalizedString equivalent in Swift?
In addition to great extension written here if you are lazy to find and replace old NSLocalizedString
you can open find & replace in Xcode and in the find section you can write NSLocalizedString\(\(".*"\), comment: ""\)
then in the replace section you need to write $1.localized
to change all NSLocalizedString
with "blabla".localized
in your project.
Inline JavaScript onclick function
you can use Self-Executing Anonymous Functions. this code will work:
<a href="#" onClick="(function(){
alert('Hey i am calling');
return false;
})();return false;">click here</a>
see JSfiddle
good postgresql client for windows?
I recommend Navicat strongly. What I found particularly excellent are it's import functions - you can import almost any data format (Access, Excel, DBF, Lotus ...), define a mapping between the source and destination which can be saved and is repeatable (I even keep my mappings under version control).
I have tried SQLMaestro and found it buggy (particularly for data import); PGAdmin is limited.
What's the safest way to iterate through the keys of a Perl hash?
The place where each
can cause you problems is that it's a true, non-scoped iterator. By way of example:
while ( my ($key,$val) = each %a_hash ) {
print "$key => $val\n";
last if $val; #exits loop when $val is true
}
# but "each" hasn't reset!!
while ( my ($key,$val) = each %a_hash ) {
# continues where the last loop left off
print "$key => $val\n";
}
If you need to be sure that each
gets all the keys and values, you need to make sure you use keys
or values
first (as that resets the iterator). See the documentation for each.
unique() for more than one variable
This is an addition to Josh's answer.
You can also keep the values of other variables while filtering out duplicated rows in data.table
Example:
library(data.table)
#create data table
dt <- data.table(
V1=LETTERS[c(1,1,1,1,2,3,3,5,7,1)],
V2=LETTERS[c(2,3,4,2,1,4,4,6,7,2)],
V3=c(1),
V4=c(2) )
> dt
# V1 V2 V3 V4
# A B 1 2
# A C 1 2
# A D 1 2
# A B 1 2
# B A 1 2
# C D 1 2
# C D 1 2
# E F 1 2
# G G 1 2
# A B 1 2
# set the key to all columns
setkey(dt)
# Get Unique lines in the data table
unique( dt[list(V1, V2), nomatch = 0] )
# V1 V2 V3 V4
# A B 1 2
# A C 1 2
# A D 1 2
# B A 1 2
# C D 1 2
# E F 1 2
# G G 1 2
Alert: If there are different combinations of values in the other variables, then your result will be
unique combination of V1 and V2
Update TextView Every Second
If you want to show time on textview then better use Chronometer or TextClock
Using Chronometer:This was added in API 1. It has lot of option to customize it.
Your xml
<Chronometer
android:id="@+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp" />
Your activity
Chronometer mChronometer=(Chronometer) findViewById(R.id.chronometer);
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
Using TextClock: This widget is introduced in API level 17. I personally like Chronometer.
Your xml
<TextClock
android:id="@+id/textClock"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:format12Hour="hh:mm:ss a"
android:gravity="center_horizontal"
android:textColor="#d41709"
android:textSize="44sp"
android:textStyle="bold" />
Thats it, you are done.
You can use any of these two widgets. This will make your life easy.
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
Uses for the '"' entity in HTML
In my experience it may be the result of auto-generation by a string-based tools, where the author did not understand the rules of HTML.
When some developers generate HTML without the use of special XML-oriented tools, they may try to be sure the resulting HTML is valid by taking the approach that everything must be escaped.
Referring to your example, the reason why every occurrence of "
is represented by "
could be because using that approach, you can safely use such "special" characters in both attributes and values.
Another motivation I've seen is where people believe, "We must explicitly show that our symbols are not part of the syntax." Whereas, valid HTML can be created by using the proper string-manipulation tools, see the previous paragraph again.
Here is some pseudo-code loosely based on C#, although it is preferred to use valid methods and tools:
public class HtmlAndXmlWriter
{
private string Escape(string badString)
{
return badString.Replace("&", "&").Replace("\"", """).Replace("'", "'").Replace(">", ">").Replace("<", "<");
}
public string GetHtmlFromOutObject(Object obj)
{
return "<div class='type_" + Escape(obj.Type) + "'>" + Escape(obj.Value) + "</div>";
}
}
It's really very common to see such approaches taken to generate HTML.
Is it possible to use global variables in Rust?
You can use static variables fairly easily as long as they are thread-local.
The downside is that the object will not be visible to other threads your program might spawn. The upside is that unlike truly global state, it is entirely safe and is not a pain to use - true global state is a massive pain in any language. Here's an example:
extern mod sqlite;
use std::cell::RefCell;
thread_local!(static ODB: RefCell<sqlite::database::Database> = RefCell::new(sqlite::open("test.db"));
fn main() {
ODB.with(|odb_cell| {
let odb = odb_cell.borrow_mut();
// code that uses odb goes here
});
}
Here we create a thread-local static variable and then use it in a function. Note that it is static and immutable; this means that the address at which it resides is immutable, but thanks to RefCell
the value itself will be mutable.
Unlike regular static
, in thread-local!(static ...)
you can create pretty much arbitrary objects, including those that require heap allocations for initialization such as Vec
, HashMap
and others.
If you cannot initialize the value right away, e.g. it depends on user input, you may also have to throw Option
in there, in which case accessing it gets a bit unwieldy:
extern mod sqlite;
use std::cell::RefCell;
thread_local!(static ODB: RefCell<Option<sqlite::database::Database>> = RefCell::New(None));
fn main() {
ODB.with(|odb_cell| {
// assumes the value has already been initialized, panics otherwise
let odb = odb_cell.borrow_mut().as_mut().unwrap();
// code that uses odb goes here
});
}
How can I add new item to the String array?
You can't. A Java array has a fixed length. If you need a resizable array, use a java.util.ArrayList<String>
.
BTW, your code is invalid: you don't initialize the array before using it.
.gitignore file for java eclipse project
You need to add your source files with git add
or the GUI equivalent so that Git will begin tracking them.
Use git status
to see what Git thinks about the files in any given directory.
SQL update fields of one table from fields of another one
The question is old but I felt the best answer hadn't been given, yet.
Is there an UPDATE
syntax ... without specifying the column names?
General solution with dynamic SQL
You don't need to know any column names except for some unique column(s) to join on (id
in the example). Works reliably for any possible corner case I can think of.
This is specific to PostgreSQL. I am building dynamic code based on the the information_schema, in particular the table information_schema.columns
, which is defined in the SQL standard and most major RDBMS (except Oracle) have it. But a DO
statement with PL/pgSQL code executing dynamic SQL is totally non-standard PostgreSQL syntax.
DO
$do$
BEGIN
EXECUTE (
SELECT
'UPDATE b
SET (' || string_agg( quote_ident(column_name), ',') || ')
= (' || string_agg('a.' || quote_ident(column_name), ',') || ')
FROM a
WHERE b.id = 123
AND a.id = b.id'
FROM information_schema.columns
WHERE table_name = 'a' -- table name, case sensitive
AND table_schema = 'public' -- schema name, case sensitive
AND column_name <> 'id' -- all columns except id
);
END
$do$;
Assuming a matching column in b
for every column in a
, but not the other way round. b
can have additional columns.
WHERE b.id = 123
is optional, to update a selected row.
SQL Fiddle.
Related answers with more explanation:
Partial solutions with plain SQL
With list of shared columns
You still need to know the list of column names that both tables share. With a syntax shortcut for updating multiple columns - shorter than what other answers suggested so far in any case.
UPDATE b
SET ( column1, column2, column3)
= (a.column1, a.column2, a.column3)
FROM a
WHERE b.id = 123 -- optional, to update only selected row
AND a.id = b.id;
SQL Fiddle.
This syntax was introduced with Postgres 8.2 in 2006, long before the question was asked. Details in the manual.
Related:
With list of columns in B
If all columns of A
are defined NOT NULL
(but not necessarily B
),
and you know the column names of B
(but not necessarily A
).
UPDATE b
SET (column1, column2, column3, column4)
= (COALESCE(ab.column1, b.column1)
, COALESCE(ab.column2, b.column2)
, COALESCE(ab.column3, b.column3)
, COALESCE(ab.column4, b.column4)
)
FROM (
SELECT *
FROM a
NATURAL LEFT JOIN b -- append missing columns
WHERE b.id IS NULL -- only if anything actually changes
AND a.id = 123 -- optional, to update only selected row
) ab
WHERE b.id = ab.id;
The NATURAL LEFT JOIN
joins a row from b
where all columns of the same name hold same values. We don't need an update in this case (nothing changes) and can eliminate those rows early in the process (WHERE b.id IS NULL
).
We still need to find a matching row, so b.id = ab.id
in the outer query.
db<>fiddle here
Old sqlfiddle.
This is standard SQL except for the FROM
clause.
It works no matter which of the columns are actually present in A
, but the query cannot distinguish between actual NULL values and missing columns in A
, so it is only reliable if all columns in A
are defined NOT NULL
.
There are multiple possible variations, depending on what you know about both tables.
Get the length of a String
var str = "Hello, playground"
var newString = str as NSString
countElements(str)
This counts the characters in Regular Swift String
countElements((newString as String))
This counts the characters in a NSString
End of File (EOF) in C
EOF indicates "end of file". A newline (which is what happens when you press enter) isn't the end of a file, it's the end of a line, so a newline doesn't terminate this loop.
The code isn't wrong[*], it just doesn't do what you seem to expect. It reads to the end of the input, but you seem to want to read only to the end of a line.
The value of EOF is -1 because it has to be different from any return value from getchar
that is an actual character. So getchar
returns any character value as an unsigned char, converted to int, which will therefore be non-negative.
If you're typing at the terminal and you want to provoke an end-of-file, use CTRL-D (unix-style systems) or CTRL-Z (Windows). Then after all the input has been read, getchar()
will return EOF
, and hence getchar() != EOF
will be false, and the loop will terminate.
[*] well, it has undefined behavior if the input is more than LONG_MAX characters due to integer overflow, but we can probably forgive that in a simple example.
Disable Transaction Log
You can't do without transaction logs in SQL Server, under any circumstances. The engine simply won't function.
You CAN set your recovery model to SIMPLE on your dev machines - that will prevent transaction log bloating when tran log backups aren't done.
ALTER DATABASE MyDB SET RECOVERY SIMPLE;
Changing default shell in Linux
You should have a 'skeleton' somewhere in /etc
, probably /etc/skeleton
, or check the default settings, probably /etc/default
or something. Those are scripts that define standard environment variables getting set during a login.
If it is just for your own account: check the (hidden) file ~/.profile
and ~/.login
. Or generate them, if they don't exist. These are also evaluated by the login process.
HTML5 Canvas 100% Width Height of Viewport?
(Expanding upon ????'s answer)
Style the canvas to fill the body. When rendering to the canvas take its size into account.
http://jsfiddle.net/mqFdk/356/
<!DOCTYPE html>
<html>
<head>
<title>aj</title>
</head>
<body>
<canvas id="c"></canvas>
</body>
</html>
CSS:
body {
margin: 0;
padding: 0
}
#c {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden
}
Javascript:
function redraw() {
var cc = c.getContext("2d");
c.width = c.clientWidth;
c.height = c.clientHeight;
cc.scale(c.width, c.height);
// Draw a circle filling the canvas.
cc.beginPath();
cc.arc(0.5, 0.5, .5, 0, 2*Math.PI);
cc.fill();
}
// update on any window size change.
window.addEventListener("resize", redraw);
// first draw
redraw();
Java - Change int to ascii
There are many ways to convert an int to ASCII (depending on your needs) but here is a way to convert each integer byte to an ASCII character:
private static String toASCII(int value) {
int length = 4;
StringBuilder builder = new StringBuilder(length);
for (int i = length - 1; i >= 0; i--) {
builder.append((char) ((value >> (8 * i)) & 0xFF));
}
return builder.toString();
}
For example, the ASCII text for "TEST" can be represented as the byte array:
byte[] test = new byte[] { (byte) 0x54, (byte) 0x45, (byte) 0x53, (byte) 0x54 };
Then you could do the following:
int value = ByteBuffer.wrap(test).getInt(); // 1413829460
System.out.println(toASCII(value)); // outputs "TEST"
...so this essentially converts the 4 bytes in a 32-bit integer to 4 separate ASCII characters (one character per byte).
Execute Stored Procedure from a Function
I have figured out a solution to this problem. We can build a Function or View with "rendered" sql in a stored procedure that can then be executed as normal.
1.Create another sproc
CREATE PROCEDURE [dbo].[usp_FunctionBuilder]
DECLARE @outerSql VARCHAR(MAX)
DECLARE @innerSql VARCHAR(MAX)
2.Build the dynamic sql that you want to execute in your function (Example: you could use a loop and union, you could read in another sproc, use if statements and parameters for conditional sql, etc.)
SET @innerSql = 'your sql'
3.Wrap the @innerSql in a create function statement and define any external parameters that you have used in the @innerSql so they can be passed into the generated function.
SET @outerSql = 'CREATE FUNCTION [dbo].[fn_GeneratedFunction] ( @Param varchar(10))
RETURNS TABLE
AS
RETURN
' + @innerSql;
EXEC(@outerSql)
This is just pseudocode but the solution solves many problems such as linked server limitations, parameters, dynamic sql in function, dynamic server/database/table name, loops, etc.
You will need to tweak it to your needs, (Example: changing the return in the function)
Java Loop every minute
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();
How to make an authenticated web request in Powershell?
The PowerShell is almost exactly the same.
$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)
Android Min SDK Version vs. Target SDK Version
android:minSdkVersion
An integer designating the minimum API Level required for the application to run. The Android system will prevent the user from installing the application if the system's API Level is lower than the value specified in this attribute. You should always declare this attribute.
android:targetSdkVersion
An integer designating the API Level that the application is targetting.
With this attribute set, the application says that it is able to run on older versions (down to minSdkVersion), but was explicitly tested to work with the version specified here. Specifying this target version allows the platform to disable compatibility settings that are not required for the target version (which may otherwise be turned on in order to maintain forward-compatibility) or enable newer features that are not available to older applications. This does not mean that you can program different features for different versions of the platform—it simply informs the platform that you have tested against the target version and the platform should not perform any extra work to maintain forward-compatibility with the target version.
For more information refer this URL:
http://developer.android.com/guide/topics/manifest/uses-sdk-element.html
How to get records randomly from the oracle database?
Here's how to pick a random sample out of each group:
SELECT GROUPING_COLUMN,
MIN (COLUMN_NAME) KEEP (DENSE_RANK FIRST ORDER BY DBMS_RANDOM.VALUE)
AS RANDOM_SAMPLE
FROM TABLE_NAME
GROUP BY GROUPING_COLUMN
ORDER BY GROUPING_COLUMN;
I'm not sure how efficient it is, but if you have a lot of categories and sub-categories, this seems to do the job nicely.
Parse date string and change format
As this question comes often, here is the simple explanation.
datetime
or time
module has two important functions.
- strftime - creates a string representation of date or time from a datetime or time object.
- strptime - creates a datetime or time object from a string.
In both cases, we need a formating string. It is the representation that tells how the date or time is formatted in your string.
Now lets assume we have a date object.
>>> from datetime import datetime
>>> d = datetime(2010, 2, 15)
>>> d
datetime.datetime(2010, 2, 15, 0, 0)
If we want to create a string from this date in the format 'Mon Feb 15 2010'
>>> s = d.strftime('%a %b %d %y')
>>> print s
Mon Feb 15 10
Lets assume we want to convert this s
again to a datetime
object.
>>> new_date = datetime.strptime(s, '%a %b %d %y')
>>> print new_date
2010-02-15 00:00:00
Refer This document all formatting directives regarding datetime.
SELECT * WHERE NOT EXISTS
You can do a LEFT JOIN and assert the joined column is NULL.
Example:
SELECT * FROM employees a LEFT JOIN eotm_dyn b on (a.joinfield=b.joinfield) WHERE b.name IS NULL
What is setContentView(R.layout.main)?
You can set content view (or design) of an activity. For example you can do it like this too :
public void onCreate(Bundle savedinstanceState) {
super.onCreate(savedinstanceState);
Button testButon = new Button(this);
setContentView(testButon);
}
Also watch this tutorial too.
How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?
Hi you can make something like this:
Create class which implements AsyncTask
// TASK
public class SomeClass extends AsyncTask<Void, Void, String>>
{
private OnTaskExecutionFinished _task_finished_event;
public interface OnTaskExecutionFinished
{
public void OnTaskFihishedEvent(String Reslut);
}
public void setOnTaskFinishedEvent(OnTaskExecutionFinished _event)
{
if(_event != null)
{
this._task_finished_event = _event;
}
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected String doInBackground(Void... params)
{
// do your background task here ...
return "Done!";
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(this._task_finished_event != null)
{
this._task_finished_event.OnTaskFihishedEvent(result);
}
else
{
Log.d("SomeClass", "task_finished even is null");
}
}
}
Add in Main Activity
// MAIN ACTIVITY
public class MyActivity extends ListActivity
{
...
SomeClass _some_class = new SomeClass();
_someclass.setOnTaskFinishedEvent(new _some_class.OnTaskExecutionFinished()
{
@Override
public void OnTaskFihishedEvent(String result)
{
Toast.makeText(getApplicationContext(),
"Phony thread finished: " + result,
Toast.LENGTH_SHORT).show();
}
});
_some_class.execute();
...
}
Close application and launch home screen on Android
Start the second activity with startActivityForResult and in the second activity return a value, that once in the onActivityResult method of the first activity closes the main application. I think this is the correct way Android does it.
R : how to simply repeat a command?
It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.
If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate
and colMeans
, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.
However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for
loop.
> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 >
So in your case, if you just wanted to print the mean of your Tandem
object 5 times:
for (ii in 1:5) { Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL) TandemMean <- mean(Tandem) print(TandemMean) }
As mentioned above, replicate
is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.
set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) { tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) } tandem[1] tandem[100] tandem[20:25]
...creates this output:
> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { + tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } > > tandem[1] [[1]] [1] 1.511923 > tandem[100] [[1]] [1] 1.496777 > tandem[20:25] [[1]] [1] 1.500669 [[2]] [1] 1.487552 [[3]] [1] 1.503409 [[4]] [1] 1.501362 [[5]] [1] 1.499728 [[6]] [1] 1.492798 >
Add a custom attribute to a Laravel / Eloquent model on load?
I had something simular:
I have an attribute picture in my model, this contains the location of the file in the Storage folder.
The image must be returned base64 encoded
//Add extra attribute
protected $attributes = ['picture_data'];
//Make it available in the json response
protected $appends = ['picture_data'];
//implement the attribute
public function getPictureDataAttribute()
{
$file = Storage::get($this->picture);
$type = Storage::mimeType($this->picture);
return "data:" . $type . ";base64," . base64_encode($file);
}
How do I get only directories using Get-ChildItem?
From PowerShell v2 and newer (k represents the folder you are beginning your search at):
Get-ChildItem $Path -attributes D -Recurse
If you just want folder names only, and nothing else, use this:
Get-ChildItem $Path -Name -attributes D -Recurse
If you are looking for a specific folder, you could use the following. In this case, I am looking for a folder called myFolder
:
Get-ChildItem $Path -attributes D -Recurse -include "myFolder"
Running java with JAVA_OPTS env variable has no effect
I don't know of any JVM that actually checks the JAVA_OPTS
environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java
command-line.
The key thing to understand here is that arguments to java
that come before the -jar analyse.jar
bit will only affect the JVM and won't be passed along to your program. So, modifying the java
line in your script to:
java $JAVA_OPTS -jar analyse.jar $*
Should "just work".
Vertical alignment of text and icon in button
There is one rule that is set by font-awesome.css
, which you need to override.
You should set overrides in your CSS files rather than inline, but essentially, the icon-ok class is being set to vertical-align: baseline;
by default and which I've corrected here:
<button id="whatever" class="btn btn-large btn-primary" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Example here: http://jsfiddle.net/fPXFY/4/ and the output of which is:
I've downsized the font-size of the icon above in this instance to 30px
, as it feels too big at 40px
for the size of the button, but this is purely a personal viewpoint. You could increase the padding on the button to compensate if required:
<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Producing: http://jsfiddle.net/fPXFY/5/ the output of which is:
Remove a cookie
I had the same problem in my code and found that it was a cookie path issue. Check out this stack overflow post: Can't delete php set cookie
I had set the cookie using a path value of "/", but didn't have any path value when I tried to clear it, so it didn't clear. So here is an example of what worked:
Setting the cookie:
$cookiePath = "/";
$cookieExpire = time()+(60*60*24);//one day -> seconds*minutes*hours
setcookie("CookieName",$cookieValue,$cookieExpire,$cookiePath);
Clearing the cookie:
setcookie("cookieName","", time()-3600, $cookiePath);
unset ($_COOKIE['cookieName']);
Hope that helps.
jQuery - Follow the cursor with a DIV
You don't need jQuery for this. Here's a simple working example:
<!DOCTYPE html>
<html>
<head>
<title>box-shadow-experiment</title>
<style type="text/css">
#box-shadow-div{
position: fixed;
width: 1px;
height: 1px;
border-radius: 100%;
background-color:black;
box-shadow: 0 0 10px 10px black;
top: 49%;
left: 48.85%;
}
</style>
<script type="text/javascript">
window.onload = function(){
var bsDiv = document.getElementById("box-shadow-div");
var x, y;
// On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
window.addEventListener('mousemove', function(event){
x = event.clientX;
y = event.clientY;
if ( typeof x !== 'undefined' ){
bsDiv.style.left = x + "px";
bsDiv.style.top = y + "px";
}
}, false);
}
</script>
</head>
<body>
<div id="box-shadow-div"></div>
</body>
</html>
I chose position: fixed;
so scrolling wouldn't be an issue.
In Python, how do I create a string of n characters in one line of code?
Why "one line"? You can fit anything onto one line.
Assuming you want them to start with 'a', and increment by one character each time (with wrapping > 26), here's a line:
>>> mkstring = lambda(x): "".join(map(chr, (ord('a')+(y%26) for y in range(x))))
>>> mkstring(10)
'abcdefghij'
>>> mkstring(30)
'abcdefghijklmnopqrstuvwxyzabcd'
Is there a C++ decompiler?
You can use IDA Pro by Hex-Rays. You will usually not get good C++ out of a binary unless you compiled in debugging information. Prepare to spend a lot of manual labor reversing the code.
If you didn't strip the binaries there is some hope as IDA Pro can produce C-alike code for you to work with. Usually it is very rough though, at least when I used it a couple of years ago.
Default session timeout for Apache Tomcat applications
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
jQuery’s .bind() vs. .on()
These snippets all perform exactly the same thing:
element.on('click', function () { ... });
element.bind('click', function () { ... });
element.click(function () { ... });
However, they are very different from these, which all perform the same thing:
element.on('click', 'selector', function () { ... });
element.delegate('click', 'selector', function () { ... });
$('selector').live('click', function () { ... });
The second set of event handlers use event delegation and will work for dynamically added elements. Event handlers that use delegation are also much more performant. The first set will not work for dynamically added elements, and are much worse for performance.
jQuery's on()
function does not introduce any new functionality that did not already exist, it is just an attempt to standardize event handling in jQuery (you no longer have to decide between live, bind, or delegate).
How to configure Fiddler to listen to localhost?
The Light,
You can configure the process acting as the client to use fiddler as a proxy.
Fiddler sets itself up as a proxy conveniently on 127.0.0.1:8888, and by default overrides the system settings under Internet Options in the Control Panel (if you've configured any) such that all traffic from the common protocols (http, https, and ftp) goes to 127.0.0.1:8888 before leaving your machine.
Now these protocols are often from common processes such as browsers, and so are easily picked up by fiddler. However, in your case, the process initiating the requests is probably not a browser, but one for a programming language like php.exe, or java.exe, or whatever language you are using.
If, say, you're using php, you can leverage curl. Ensure that the curl module is enabled, and then right before your code that invokes the request, include:
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
Hope this helps. You can also always lookup stuff like so from the fiddler documentation for a basis for you to build upon e.g. http://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/ConfigurePHPcURL
Excel VBA, How to select rows based on data in a column?
The easiest way to do it is to use the End
method, which is gives you the cell that you reach by pressing the end key and then a direction when you're on a cell (in this case B6). This won't give you what you expect if B6 or B7 is empty, though.
Dim start_cell As Range
Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Range(start_cell, start_cell.End(xlDown)).Copy Range("[Workbook2.xlsx]Sheet1!A2")
If you can't use End
, then you would have to use a loop.
Dim start_cell As Range, end_cell As Range
Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Set end_cell = start_cell
Do Until IsEmpty(end_cell.Offset(1, 0))
Set end_cell = end_cell.Offset(1, 0)
Loop
Range(start_cell, end_cell).Copy Range("[Workbook2.xlsx]Sheet1!A2")
The transaction log for the database is full
Try this:
USE YourDB;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE YourDB
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 50 MB.
DBCC SHRINKFILE (YourDB_log, 50);
GO
-- Reset the database recovery model.
ALTER DATABASE YourDB
SET RECOVERY FULL;
GO
I hope it helps.
What is [Serializable] and when should I use it?
Since the original question was about the SerializableAttribute, it should be noted that this attribute only applies when using the BinaryFormatter or SoapFormatter.
It is a bit confusing, unless you really pay attention to the details, as to when to use it and what its actual purpose is.
It has NOTHING to do with XML or JSON serialization.
Used with the SerializableAttribute are the ISerializable Interface and SerializationInfo Class. These are also only used with the BinaryFormatter or SoapFormatter.
Unless you intend to serialize your class using Binary or Soap, do not bother marking your class as [Serializable]. XML and JSON serializers are not even aware of its existence.
Javascript to stop HTML5 video playback on modal window close
I'm not sure whether ZohoGorganzola's solution is correct; however, you may want to try getting at the element directly rather than trying to invoke a method on the jQuery collection, so instead of
$("#videoContainer").pause();
try
$("#videoContainer")[0].pause();