It's the comma which is providing that extra white space.
One way is to use the string %
method:
print 'Value is "%d"' % (value)
which is like printf
in C, allowing you to incorporate and format the items after %
by using format specifiers in the string itself. Another example, showing the use of multiple values:
print '%s is %3d.%d' % ('pi', 3, 14159)
For what it's worth, Python 3 greatly improves the situation by allowing you to specify the separator and terminator for a single print
call:
>>> print(1,2,3,4,5)
1 2 3 4 5
>>> print(1,2,3,4,5,end='<<\n')
1 2 3 4 5<<
>>> print(1,2,3,4,5,sep=':',end='<<\n')
1:2:3:4:5<<
One important advantage of BFS would be that it can be used to find the shortest path between any two nodes in an unweighted graph. Whereas, we cannot use DFS for the same.
I agree with Tom van der Woerdt. You could use CSS to hide the video (visibility:hidden or overflow:hidden in a div wrapper constrained by height), but that may violate Youtube's policies. Additionally, how could you control the audio (pause, stop, volume, etc.)?
You could instead turn to resources such as http://www.houndbite.com/ to manage audio.
If your data has the names grouped as shown then you can use this formula in D2 copied down to get a total against the last entry for each name
=IF((A2=A3)*(B2=B3),"",SUM(C$2:C2)-SUM(D$1:D1))
See screenshot
I suppose rgba()
would work here. After all, browser support for both box-shadow
and rgba()
is roughly the same.
/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
div {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
Try the following:
select * From emp_master
where emp_last_name=
case emp_first_name
when 'test' then 'test'
when 'Mr name' then 'name'
end
The guide to getting fired: How to abuse function pointers in GCC on x86 machines by compiling your code by hand:
These string literals are bytes of 32-bit x86 machine code. 0xC3
is an x86 ret
instruction.
You wouldn't normally write these by hand, you'd write in assembly language and then use an assembler like nasm
to assemble it into a flat binary which you hexdump into a C string literal.
Returns the current value on the EAX register
int eax = ((int(*)())("\xc3 <- This returns the value of the EAX register"))();
Write a swap function
int a = 10, b = 20;
((void(*)(int*,int*))"\x8b\x44\x24\x04\x8b\x5c\x24\x08\x8b\x00\x8b\x1b\x31\xc3\x31\xd8\x31\xc3\x8b\x4c\x24\x04\x89\x01\x8b\x4c\x24\x08\x89\x19\xc3 <- This swaps the values of a and b")(&a,&b);
Write a for-loop counter to 1000, calling some function each time
((int(*)())"\x66\x31\xc0\x8b\x5c\x24\x04\x66\x40\x50\xff\xd3\x58\x66\x3d\xe8\x03\x75\xf4\xc3")(&function); // calls function with 1->1000
You can even write a recursive function that counts to 100
const char* lol = "\x8b\x5c\x24\x4\x3d\xe8\x3\x0\x0\x7e\x2\x31\xc0\x83\xf8\x64\x7d\x6\x40\x53\xff\xd3\x5b\xc3\xc3 <- Recursively calls the function at address lol.";
i = ((int(*)())(lol))(lol);
Note that compilers place string literals in the .rodata
section (or .rdata
on Windows), which is linked as part of the text segment (along with code for functions).
The text segment has Read+Exec permission, so casting string literals to function pointers works without needing mprotect()
or VirtualProtect()
system calls like you'd need for dynamically allocated memory. (Or gcc -z execstack
links the program with stack + data segment + heap executable, as a quick hack.)
To disassemble these, you can compile this to put a label on the bytes, and use a disassembler.
// at global scope
const char swap[] = "\x8b\x44\x24\x04\x8b\x5c\x24\x08\x8b\x00\x8b\x1b\x31\xc3\x31\xd8\x31\xc3\x8b\x4c\x24\x04\x89\x01\x8b\x4c\x24\x08\x89\x19\xc3 <- This swaps the values of a and b";
Compiling with gcc -c -m32 foo.c
and disassembling with objdump -D -rwC -Mintel
, we can get the assembly, and find out that this code violates the ABI by clobbering EBX (a call-preserved register) and is generally inefficient.
00000000 <swap>:
0: 8b 44 24 04 mov eax,DWORD PTR [esp+0x4] # load int *a arg from the stack
4: 8b 5c 24 08 mov ebx,DWORD PTR [esp+0x8] # ebx = b
8: 8b 00 mov eax,DWORD PTR [eax] # dereference: eax = *a
a: 8b 1b mov ebx,DWORD PTR [ebx]
c: 31 c3 xor ebx,eax # pointless xor-swap
e: 31 d8 xor eax,ebx # instead of just storing with opposite registers
10: 31 c3 xor ebx,eax
12: 8b 4c 24 04 mov ecx,DWORD PTR [esp+0x4] # reload a from the stack
16: 89 01 mov DWORD PTR [ecx],eax # store to *a
18: 8b 4c 24 08 mov ecx,DWORD PTR [esp+0x8]
1c: 89 19 mov DWORD PTR [ecx],ebx
1e: c3 ret
not shown: the later bytes are ASCII text documentation
they're not executed by the CPU because the ret instruction sends execution back to the caller
This machine code will (probably) work in 32-bit code on Windows, Linux, OS X, and so on: the default calling conventions on all those OSes pass args on the stack instead of more efficiently in registers. But EBX is call-preserved in all the normal calling conventions, so using it as a scratch register without saving/restoring it can easily make the caller crash.
It depends on what your local OS is.
If your local OS is Unix-like, then try:
scp username@remoteHost:/remote/dir/file.txt /local/dir/
If your local OS is Windows ,then you should use pscp.exe
utility.
For example, below command will download file.txt from remote to D:
disk of local machine.
pscp.exe username@remoteHost:/remote/dir/file.txt d:\
It seems your Local OS is Unix, so try the former one.
For those who don't know what pscp.exe
is and don't know where it is, you can always go to putty
official website to download it. And then open a CMD prompt, go to the pscp.exe directory where you put it. Then execute the command as provided above
But that doesn't seem like the proper way to do it..
That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.
Example:
const promises = [_x000D_
new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
.then(data => {_x000D_
console.log("First handler", data);_x000D_
return data.map(entry => entry * 10);_x000D_
})_x000D_
.then(data => {_x000D_
console.log("Second handler", data);_x000D_
});
_x000D_
(catch
handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)
The output we see from that is:
First handler [1,2] Second handler [10,20]
...because the first handler gets the resolution of the two promises (1
and 2
) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.
If the additional work you're doing is synchronous, you can also put it in the first handler:
Example:
const promises = [_x000D_
new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
.then(data => {_x000D_
console.log("Initial data", data);_x000D_
data = data.map(entry => entry * 10);_x000D_
console.log("Updated data", data);_x000D_
return data;_x000D_
});
_x000D_
...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.
Find the path to a process name
#!/bin/bash
# @author Lukas Gottschall
PID=`ps aux | grep precessname | grep -v grep | awk '{ print $2 }'`
PATH=`ls -ald --color=never /proc/$PID/exe | awk '{ print $10 }'`
echo $PATH
If you are using NativeBase as UI Components you can use this sample
<Item floatingLabel>
<Label>Title</Label>
<Input
returnKeyType = {"next"}
autoFocus = {true}
onSubmitEditing={(event) => {
this._inputDesc._root.focus();
}} />
</Item>
<Item floatingLabel>
<Label>Description</Label>
<Input
getRef={(c) => this._inputDesc = c}
multiline={true} style={{height: 100}} />
onSubmitEditing={(event) => { this._inputLink._root.focus(); }} />
</Item>
Everything is fine.Good example of activity/service
communication using Messenger.
One comment : the method MyService.isRunning()
is not required.. bindService()
can be done any number of times. no harm in that.
If MyService is running in a different process then the static function MyService.isRunning()
will always return false. So there is no need of this function.
The idea is that you rely on dependency injection (inversion of control, or IoC). That is, your components are configured with the components they need. These dependencies are injected (via the constructor or setters) - you don't get then yourself.
ApplicationContext.getBean()
requires you to name a bean explicitly within your component. Instead, by using IoC, your configuration can determine what component will be used.
This allows you to rewire your application with different component implementations easily, or configure objects for testing in a straightforward fashion by providing mocked variants (e.g. a mocked DAO so you don't hit a database during testing)
The following "Cake way" is useful because you can grab the full current URL and modify parts of it without manually having to parse out the $_SERVER[ 'REQUEST_URI' ]
string and then manually concatenating it back into a valid url for output.
Full current url:
Router::reverse($this->request, true)
Easily modifying specific parts of current url:
1) make a copy of Cake's request object:
$request_copy = $this->request
2) Then modify $request_copy->params
and/or $request_copy->query
arrays
3) Finally: $new_url = Router::reverse($request_copy, true)
.
You can change the color with tinting the background
<EditText
android:backgroundTint="@color/red"/>
Use the library EventBus to pass event that could contain your variable back and forth. It's a good solution because it keeps your activities and fragments loosely coupled
Very simple, this worked for me (title and icon white):
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="@color/PrimaryColor"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:elevation="4dp" />
just set position: fixed
to the footer element (instead of relative)
Note that you may need to also set a margin-bottom
to the main
element at least equal to the height of the footer element (e.g. margin-bottom: 1.5em;
) otherwise, in some circustances, the bottom area of the main content could be partially overlapped by your footer
If your array is not initialized then it contains randoms values and cannot be checked !
To initialize your array with 0 values:
int array[5] = {0};
Then you can check if the value is 0:
array[4] == 0;
When you compare to NULL, it compares to 0 as the NULL is defined as integer value 0 or 0L.
If you have an array of pointers, better use the nullptr
value to check:
char* array[5] = {nullptr}; // we defined an array of char*, initialized to nullptr
if (array[4] == nullptr)
// do something
Well, no. Why there should be? Just discard the string if you don't need it anymore.
&str
is more useful than String
when you need to only read a string, because it is only a view into the original piece of data, not its owner. You can pass it around more easily than String
, and it is copyable, so it is not consumed by the invoked methods. In this regard it is more general: if you have a String
, you can pass it to where an &str
is expected, but if you have &str
, you can only pass it to functions expecting String
if you make a new allocation.
You can find more on the differences between these two and when to use them in the official strings guide.
The issue in my case was a typo in the PATH variable. Since vsvars32.bat uses the "reg" tool to query the registry, it was failing because the tool was not found (just typing reg
on a command prompt was failing for me).
font-family:'Open Sans' , sans-serif;
For light:
font-weight : 100;
Or
font-weight : lighter;
For normal:
font-weight : 500;
Or
font-weight : normal;
For bold:
font-weight : 700;
Or
font-weight : bold;
For more bolder:
font-weight : 900;
Or
font-weight : bolder;
FirebaseInstanceIdService is now deprecated. you should get the Token in the onNewToken method in the FirebaseMessagingService.
function calculateExamRemainingTime(exam_end_at) {
$(function(){
const calcNewYear = setInterval(function(){
const exam_ending_at = new Date(exam_end_at);
const current_time = new Date();
const totalSeconds = Math.floor((exam_ending_at - (current_time))/1000);;
const totalMinutes = Math.floor(totalSeconds/60);
const totalHours = Math.floor(totalMinutes/60);
const totalDays = Math.floor(totalHours/24);
const hours = totalHours - ( totalDays * 24 );
const minutes = totalMinutes - ( totalDays * 24 * 60 ) - ( hours * 60 );
const seconds = totalSeconds - ( totalDays * 24 * 60 * 60 ) - ( hours * 60 * 60 ) - ( minutes * 60 );
const examRemainingHoursSection = document.querySelector('#remainingHours');
const examRemainingMinutesSection = document.querySelector('#remainingMinutes');
const examRemainingSecondsSection = document.querySelector('#remainingSeconds');
examRemainingHoursSection.innerHTML = hours.toString();
examRemainingMinutesSection.innerHTML = minutes.toString();
examRemainingSecondsSection.innerHTML = seconds.toString();
},1000);
});
}
calculateExamRemainingTime('2025-06-03 20:20:20');
Try this, it's working for me.
Sender:
byte[] message = ...
Socket socket = ...
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeInt(message.length); // write length of the message
dOut.write(message); // write the message
Receiver:
Socket socket = ...
DataInputStream dIn = new DataInputStream(socket.getInputStream());
int length = dIn.readInt(); // read length of incoming message
if(length>0) {
byte[] message = new byte[length];
dIn.readFully(message, 0, message.length); // read the message
}
If you don't like extra null checks:
if (Boolean.TRUE.equals(value)) {...}
As stated in PostgreSQL docs here:
The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages.
Code snippet specifically answering your question:
SELECT field1, field2,
CASE
WHEN field1>0 THEN field2/field1
ELSE 0
END
AS field3
FROM test
if (obj === undefined)
{
// Create obj
}
If you are doing extensive javascript programming you should get in the habit of using === and !== when you want to make a type specific check.
Also if you are going to be doing a fair amount of javascript, I suggest running code through JSLint http://www.jslint.com it might seem a bit draconian at first, but most of the things JSLint warns you about will eventually come back to bite you.
<?php
namespace CMS;
class Model {
const _class = __CLASS__;
}
echo Model::_class; // will return 'CMS\Model'
for older than PHP 5.5
Use this code to ensure the user doesn't just enter spaces but a valid name:
pattern="[a-zA-Z][a-zA-Z0-9\s]*"
Have you tried loading the socket.io script not from a relative URL?
You're using:
<script src="socket.io/socket.io.js"></script>
And:
socket.connect('http://127.0.0.1:8080');
You should try:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
And:
socket.connect('http://localhost:8080');
Switch localhost:8080
with whatever fits your current setup.
Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).
You can check like this:
int x;
cin >> x;
if (cin.fail()) {
//Not an int.
}
Furthermore, you can continue to get input until you get an int via:
#include <iostream>
int main() {
int x;
std::cin >> x;
while(std::cin.fail()) {
std::cout << "Error" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> x;
}
std::cout << x << std::endl;
return 0;
}
EDIT: To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. One needs not clear/ignore the input stream in that situation. Verifying the string is just numbers, convert the string back to an integer. I mean, this was just off the cuff. There might be a better way. This won't work if you're accepting floats/doubles (would have to add '.' in the search string).
#include <iostream>
#include <string>
int main() {
std::string theInput;
int inputAsInt;
std::getline(std::cin, theInput);
while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
std::cout << "Error" << std::endl;
if( theInput.find_first_not_of("0123456789") == std::string::npos) {
std::cin.clear();
std::cin.ignore(256,'\n');
}
std::getline(std::cin, theInput);
}
std::string::size_type st;
inputAsInt = std::stoi(theInput,&st);
std::cout << inputAsInt << std::endl;
return 0;
}
HTML with font-awesome glyphicon.
<span class="fa fa-spinner spin"></span>
CSS
@-moz-keyframes spin {
to { -moz-transform: rotate(360deg); }
}
@-webkit-keyframes spin {
to { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
to {transform:rotate(360deg);}
}
.spin {
animation: spin 1000ms linear infinite;
}
In my case I was using a third party library (i.e. vendor) and the library comes with a sample app which I already had install on my device. So that sample app was now conflicting each time I try to install my own app implementing the library. So I just uninstalled the vendor's sample app and it works afterwards.
This image illustrates this concept well. Unfortunately, I could not find the original source of this image, but someone made it, he has shown this concept very well in the form of an image.
If the other solutions don't work, you can always see the output in the Android Monitor.
Make sure to set your filter to Show only selected application or create a custom filter.
Since you're already using Google's Json-Simple
library, you can parse the json from an InputStream
like this:
InputStream inputStream = ... //Read from a file, or a HttpRequest, or whatever.
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(
new InputStreamReader(inputStream, "UTF-8"));
It is even funnier when you are doing it with inputs, because they should be bound. If you are interested in how to do it in Vue2 with options to insert and delete, please see an example:
please have a look an js fiddle
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
finds: [] _x000D_
},_x000D_
methods: {_x000D_
addFind: function () {_x000D_
this.finds.push({ value: 'def' });_x000D_
},_x000D_
deleteFind: function (index) {_x000D_
console.log(index);_x000D_
console.log(this.finds);_x000D_
this.finds.splice(index, 1);_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
<h1>Finds</h1>_x000D_
<div v-for="(find, index) in finds">_x000D_
<input v-model="find.value">_x000D_
<button @click="deleteFind(index)">_x000D_
delete_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<button @click="addFind">_x000D_
New Find_x000D_
</button>_x000D_
_x000D_
<pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
If you already have filled columns and have added new one or you want to fill out old column with new mock values , do this:
public function up()
{
DB::table('foydabars')->update(
array(
'status' => '0'
)
);
}
As detailed in the Oracle Java SE Support Roadmap
After April 2015, Oracle will no longer post updates of Java SE 7 to its public download sites. Existing Java SE 7 downloads already posted as of April 2015 will remain accessible in the Java Archive
Check the Java SE 7 Archive Downloads page. The last release was update 80, therefore the 32-bit filename to download is jdk-7u80-windows-i586.exe
(64-bit is named jdk-7u80-windows-x64.exe
.
Old Java downloads also require a sign on to an Oracle account now :-( however with some crafty cookie creating one can use wget
to grab the file without signing in.
wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-windows-i586.exe"
Also, linear congruential PRNGs tend to produce more randomness on the higher bits that on the lower bits, so to cap the result don't use modulo, but instead use something like:
j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
(This one is from "Numerical Recipes in C", ch.7)
Use the oncontextmenu
event.
Here's an example:
<div oncontextmenu="javascript:alert('success!');return false;">
Lorem Ipsum
</div>
And using event listeners (credit to rampion from a comment in 2011):
el.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert('success!');
return false;
}, false);
Don't forget to return false, otherwise the standard context menu will still pop up.
If you are going to use a function you've written rather than javascript:alert("Success!")
, remember to return false in BOTH the function AND the oncontextmenu
attribute.
found this and it worked for me.
strSQL = "SELECT * FROM DataTable"
'Where DataTable is the Named range
How can I run SQL statements on a named range within an excel sheet?
Your code can be fixed as follows:
import numpy as np, cv
vis = np.zeros((384, 836), np.float32)
h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
vis0 = cv.fromarray(vis)
cv.CvtColor(vis0, vis2, cv.CV_GRAY2BGR)
Short explanation:
np.uint32
data type is not supported by OpenCV (it supports uint8
, int8
, uint16
, int16
, int32
, float32
, float64
)cv.CvtColor
can't handle numpy arrays so both arguments has to be converted to OpenCV type. cv.fromarray
do this conversion.cv.CvtColor
must have the same depth. So I've changed source type to 32bit float to match the ddestination.Also I recommend you use newer version of OpenCV python API because it uses numpy arrays as primary data type:
import numpy as np, cv2
vis = np.zeros((384, 836), np.float32)
vis2 = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)
Assuming you have the necessary privileges to run svnadmin, you need to use the dump and load commands.
If you are doing Unity Project. You can get this error.
Command PhaseScriptExecution failed with a nonzero exit code
The solution is very simple
https://forum.unity.com/threads/error-on-build.561706/
Pre-requisites: Have cocoapods installed
Not Needed: 1. Install "cocoapods"
for installing run following line in your terminal: $sudo gem install cocoapods
chmod +x MapFileParser.sh
chmod +x process_symbols.sh
It worked for me)
I think that installing "cocoapods" is not necessary, only step 3 and 4 enough to solve, but it does not work, you can try it.
Thanks ya'll. I used this:
=CONCATENATE((number1/GCD(number1,number2)),":",((number2/GCD(number1,number2))))
If you've got 2007 this works great.
You don't tend to execute the make file itself, rather you execute make
, giving it the make file as an argument:
make -f pax.mk
If your make file is actually one of the standard names (like makefile
or Makefile
), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make
man page to see which takes precedence).
Just use GETDATE()
or GETUTCDATE()
(if you want to get the "universal" UTC time, instead of your local server's time-zone related time).
INSERT INTO [Business]
([IsDeleted]
,[FirstName]
,[LastName]
,[LastUpdated]
,[LastUpdatedBy])
VALUES
(0, 'Joe', 'Thomas',
GETDATE(), <LastUpdatedBy, nvarchar(50),>)
The insert statement actually has a syntax for doing just that. It's a lot easier if you specify the column names rather than selecting "*" though:
INSERT INTO new_table (Foo, Bar, Fizz, Buzz)
SELECT Foo, Bar, Fizz, Buzz
FROM initial_table
-- optionally WHERE ...
I'd better clarify this because for some reason this post is getting a few down-votes.
The INSERT INTO ... SELECT FROM syntax is for when the table you're inserting into ("new_table" in my example above) already exists. As others have said, the SELECT ... INTO syntax is for when you want to create the new table as part of the command.
You didn't specify whether the new table needs to be created as part of the command, so INSERT INTO ... SELECT FROM should be fine if your destination table already exists.
To make the image move right:
float: right;
To make the text not wrapped:
clear: right;
For best practice, put the css code in your stylesheets file. Once you add more code, it will look messy and hard to edit.
Here is simple way to access parent id
document.getElementById("child1").parentNode;
will do the magic for you to access the parent div.
<html>
<head>
</head>
<body id="body">
<script>
function alertAncestorsUntilID() {
var a = document.getElementById("child").parentNode;
alert(a.id);
}
</script>
<div id="master">
Master
<div id="child">Child</div>
</div>
<script>
alertAncestorsUntilID();
</script>
</body>
</html>
A couple of things:
You need to set the video bitrate. I have never used minrate and maxrate so I don't know how exactly they work, but by setting the bitrate using the -b
switch, I am able to get high quality video. You need to come up with a bitrate that offers a good tradeoff between compression and video quality. You may have to experiment with this because it all depends on the frame size, frame rate and the amount of motion in the content of your video. Keep in mind that DVD tends to be around 4-5 Mbit/s on average for 720x480, so I usually start from there and decide whether I need more or less and then just experiment. For example, you could add -b 5000k
to the command line to get more or less DVD video bitrate.
You need to specify a video codec. If you don't, ffmpeg will default to MPEG-1 which is quite old and does not provide near the amount of compression as MPEG-4 or H.264. If your ffmpeg version is built with libx264 support, you can specify -vcodec libx264
as part of the command line. Otherwise -vcodec mpeg4
will also do a better job than MPEG-1, but not as well as x264.
There are a lot of other advanced options that will help you squeeze out the best quality at the lowest bitrates. Take a look here for some examples.
First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter
to your simple format and convert it back to a String.
Swift 3
let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")
The printed result is: Dateobj: 10-22-2015
It's short hand for the ternary operator.
FormsAuth = (formsAuth != null) ? formsAuth : new FormsAuthenticationWrapper();
Or for those who don't do ternary:
if (formsAuth != null)
{
FormsAuth = formsAuth;
}
else
{
FormsAuth = new FormsAuthenticationWrapper();
}
Use the REPLACE function.
eg: SELECT REPLACE ('t?es?t', '?', 'w');
For content editable stuff (not regular inputs, you need to use selectNodeContents (rather than just selectNode).
NOTE: All the references to "document.selection" and "createTextRange()" are for IE 8 and lower... You'll not likely need to support that monster if you're attempting to do tricky stuff like this.
function selectElemText(elem) {
//Create a range (a range is a like the selection but invisible)
var range = document.createRange();
// Select the entire contents of the element
range.selectNodeContents(elem);
// Don't select, just positioning caret:
// In front
// range.collapse();
// Behind:
// range.collapse(false);
// Get the selection object
var selection = window.getSelection();
// Remove any current selections
selection.removeAllRanges();
// Make the range you have just created the visible selection
selection.addRange(range);
}
you can use :
git remote remove origin
to remove a linked repo then:
git remote add origin
to add new one
From Android P, defining the READ_PHONE_STATE permission in AndroidManifest only, will not work. We have to actually request for the permission. Below code works for me:
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 101);
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
Log.d(TAG,Build.getSerial());
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 101:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
} else {
//not granted
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Add this permissions in AndroidManifest.xml
<uses-permission android:name = "android.permission.INTERNET"/>
<uses-permission android:name = "android.permission.READ_PHONE_STATE" />
Hope this helps.
Thank You, MJ
@jamylak answer is quite nice, however if you don't want to import a couple of modules just to do this simple task, write your own lambda
in-place:
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> filter(lambda v: v is not None, L)
[0, 23, 234, 89, 0, 35, 9]
Try filtering out the rows that contain strings with the delimiter and work on those only like:
SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM MyTable
WHERE CHARINDEX('/', myColumn) > 0
Or
SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM MyTable
WHERE myColumn LIKE '%/%'
Use this one:
Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")
With rng.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range1.Address
End With
Note that when you're using Dim range1, rng As range
, only rng
has type of Range
, but range1
is Variant
. That's why I'm using Dim range1 As Range, rng As Range
.
About meaning of parameters you can read is MSDN, but in short:
Type:=xlValidateList
means validation type, in that case you should select value from listAlertStyle:=xlValidAlertStop
specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.Operator:= xlBetween
is odd. It can be used only if two formulas are provided for validation.Formula1:="='" & ws.Name & "'!" & range1.Address
for list data validation provides address of list with values (in format =Sheet!A1:A5
)Below are the working steps without the need for any external modules:
Step 1: Create a module in your app.
E.g, lets assume we have an app called user_registration_app. Explore user_registration_app and create a new file.
Lets call this as custom_cors_middleware.py
Paste the below Class definition:
class CustomCorsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Headers"] = "*"
# Code to be executed for each request/response after
# the view is called.
return response
Step 2: Register a middleware
In your projects settings.py file, add this line
'user_registration_app.custom_cors_middleware.CustomCorsMiddleware'
E.g:
MIDDLEWARE = [
'user_registration_app.custom_cors_middleware.CustomCorsMiddleware', # ADD THIS LINE BEFORE CommonMiddleware
...
'django.middleware.common.CommonMiddleware',
]
Remember to replace user_registration_app with the name of your app where you have created your custom_cors_middleware.py module.
You can now verify it will add the required response headers to all the views in the project!
I use this class:
public class JsonContent : StringContent
{
public JsonContent(object obj) :
base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
{ }
}
Sample of usage:
new HttpClient().PostAsync("http://...", new JsonContent(new { x = 1, y = 2 }));
I used the code of this link http://dipaksblogonline.blogspot.com/2012/02/html5-placeholder-in-ie7-and-ie8-fixed.html
But in browser detection I used:
if (navigator.userAgent.indexOf('MSIE') > -1) {
//Your placeholder support code here...
}
There are two methods to get the mod time, os.path.getmtime() or os.stat(), but the ctime is not reliable cross-platform (see below).
getmtime(path)
Return the time of last modification of path. The return value is a number giving the
number of seconds since the epoch (see the time module). Raise os.error if the file does
not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If
os.stat_float_times() returns True, the result is a floating point number.
stat(path)
Perform a stat() system call on the given path. The return value is an object whose
attributes correspond to the members of the stat structure, namely: st_mode (protection
bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid
(user ID of owner), st_gid (group ID of owner), st_size (size of file, in bytes),
st_atime (time of most recent access), st_mtime (time of most recent content
modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows):
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L
>>>
In the above example you would use statinfo.st_mtime or statinfo.st_ctime to get the mtime and ctime, respectively.
$datetime = date("Y-m-d h:i:s");
$timestamp = strtotime($datetime);
$image = $_POST['image'];
$imgdata = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$temp=explode('/',$mime_type);
$path = "uploads/$timestamp.$temp[1]";
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded->>> $timestamp.$temp[1]";
This will be enough for image processing. Special thanks to Mr. Dev Karan Sharma
In addition to Harry's answer, I think it's crucial to add/emphasize that :last-child will not work if the element is not the VERY LAST element in a container. For whatever reason it took me hours to realize that, and even though Harry's answer is very thorough I couldn't extract that information from "The last-child selector is used to select the last child element of a parent."
Suppose this is my selector: a:last-child {}
This works:
<div>
<a></a>
<a>This will be selected</a>
</div>
This doesn't:
<div>
<a></a>
<a>This will no longer be selected</a>
<div>This is now the last child :'( </div>
</div>
It doesn't because the a
element is not the last element inside its parent.
It may be obvious, but it was not for me...
It is possible to download a file using XHR request. You can use angular $http to load the file and then use Blob feature of HTML5 to make browser save it. There is a library that can help you with saving: FileSaver.js.
This command helped me to solve the problem:
export DISPLAY=:0
How about for example https://github.com/joyent/node/wiki/modules#wiki-tcp. A very quick summary =>
Normally set does not keep the order, such as HashSet in order to quickly find a emelent, but you can try LinkedHashSet it will keep the order which you put in.
This error can also be caused by simply missing a comma ,
between the column names in the SELECT statement.
eg:
SELECT MyCol1, MyCol2 MyCol3 FROM SomeTable;
Here is the Swift 4 version.
import Foundation
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
var tableView: UITableView = UITableView()
let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
let cellReuseIdentifier = "cell"
override func viewDidLoad()
{
super.viewDidLoad()
tableView.frame = CGRect(x: 0, y: 50, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
self.view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return animals.count
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = animals[indexPath.row]
return cell
}
private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath)
{
print("You tapped cell number \(indexPath.row).")
}
}
Excel expects dates and times to be stored as a floating point number whose value depends on the Date1904 setting of the workbook, plus a number format such as "mm/dd/yyyy" or "hh:mm:ss" or "mm/dd/yyyy hh:mm:ss" so that the number is displayed to the user as a date / time.
Using SpreadsheetGear for .NET you can do this: worksheet.Cells["A1"].Value = DateTime.Now;
This will convert the DateTime to a double which is the underlying type which Excel uses for a Date / Time, and then format the cell with a default date and / or time number format automatically depending on the value.
SpreadsheetGear also has IWorkbook.DateTimeToNumber(DateTime) and NumberToDateTime(double) methods which convert from .NET DateTime objects to a double which Excel can use.
I would expect XlsIO to have something similar.
Disclaimer: I own SpreadsheetGear LLC
Thought this might help to someone, it happens because "When the number of data queries is greater than 1".reference
If you press Ctrl + Enter after you press something like "/wordforsearch", then you can find the word "wordforsearch" in the current line. Then press n for the next match; press N for previous match.
Firefox new version(64) support CSS Scrollbars Module Level 1
.scroller {_x000D_
width: 300px;_x000D_
height: 100px;_x000D_
overflow-y: scroll;_x000D_
scrollbar-color: rebeccapurple green;_x000D_
scrollbar-width: thin;_x000D_
}
_x000D_
<div class="scroller">_x000D_
Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi_x000D_
welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic._x000D_
Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette_x000D_
tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato._x000D_
Dandelion cucumber earthnut pea peanut soko zucchini._x000D_
</div>
_x000D_
Source: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Scrollbars
Use the std::getline()
from <string>
.
istream & getline(istream & is,std::string& str)
So, for your case it would be:
std::getline(read,x);
using percentage
is much better solution than pixels
.
body {
padding-top: 10%; //This works regardless of display size.
}
If needed you can still be explicit by adding different breakpoints
as mentioned in another answer by @spajus
You can add attributes using attr
like so:
$('#someid').attr('name', 'value');
However, for DOM properties like checked
, disabled
and readonly
, the proper way to do this (as of JQuery 1.6) is to use prop
.
$('#someid').prop('disabled', true);
I has this error because the git repo was (accidentally) initialised twice on the same location : first as a non-bare repo and shortly after as a bare repo. Because the .git folder remains, git assumes the repository is non-bare. Removing the .git folder and working directory data solved the issue.
Use ENUM in MySQL for true / false it gives and accepts the true / false values without any extra code.
ALTER TABLE `itemcategory` ADD `aaa` ENUM('false', 'true') NOT NULL DEFAULT 'false'
A built-in Map type is now available in JavaScript. It can be used instead of simply using Object. It is supported by current versions of all major browsers.
Maps do not support the [subscript]
notation used by Objects. That syntax implicitly casts the subscript
value to a primitive string or symbol. Maps support any values as keys, so you must use the methods .get(key)
, .set(key, value)
and .has(key)
.
var m = new Map();_x000D_
var key1 = 'key1';_x000D_
var key2 = {};_x000D_
var key3 = {};_x000D_
_x000D_
m.set(key1, 'value1');_x000D_
m.set(key2, 'value2');_x000D_
_x000D_
console.assert(m.has(key2), "m should contain key2.");_x000D_
console.assert(!m.has(key3), "m should not contain key3.");
_x000D_
Objects only supports primitive strings and symbols as keys, because the values are stored as properties. If you were using Object, it wouldn't be able to to distinguish key2
and key3
because their string representations would be the same:
var o = new Object();_x000D_
var key1 = 'key1';_x000D_
var key2 = {};_x000D_
var key3 = {};_x000D_
_x000D_
o[key1] = 'value1';_x000D_
o[key2] = 'value2';_x000D_
_x000D_
console.assert(o.hasOwnProperty(key2), "o should contain key2.");_x000D_
console.assert(!o.hasOwnProperty(key3), "o should not contain key3."); // Fails!
_x000D_
var response = taskwithresponse.Result;
var jsonString = response.ReadAsAsync<List<Job>>().Result;
Don't do this.
Your scripts and your data should not be mashed into one big directory. Put your code in some known location (site-packages
or /var/opt/udi
or something) separate from your data. Use good version control on your code to be sure that you have current and previous versions separated from each other so you can fall back to previous versions and test future versions.
Bottom line: Do not mingle code and data.
Data is precious. Code comes and goes.
Provide the working directory as a command-line argument value. You can provide a default as an environment variable. Don't deduce it (or guess at it)
Make it a required argument value and do this.
import sys
import os
working= os.environ.get("WORKING_DIRECTORY","/some/default")
if len(sys.argv) > 1: working = sys.argv[1]
os.chdir( working )
Do not "assume" a directory based on the location of your software. It will not work out well in the long run.
Mind you that this is a highly opinion based question, so I stopped making fjords and made a quick table
Now library comparison is hard because on many parameters, all the four pretty much do the same thing, except possibly for Fresco because there is a whole bunch of new memory level optimizations in it.So let me know if certain parameters you'd like to see a comparison for based on my experience.
Having used Fresco the least, the answer might evolve as I continue to use and understand it for current exploits. The used personally
is having used the library atleast once in a completed app.
*Note - Fresco now supports GIF as well as WebP animations
This also works:
Model:
public class ViewModel
{
public HttpPostedFileBase File{ get; set; }
}
View:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.File, new { type = "file" })
}
Controller action:
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
var postedFile = Request.Files["File"];
// now you can get and validate the file type:
var isFileSupported= IsFileSupported(postedFile);
}
}
public bool IsFileSupported(HttpPostedFileBase file)
{
var isSupported = false;
switch (file.ContentType)
{
case ("image/gif"):
isSupported = true;
break;
case ("image/jpeg"):
isSupported = true;
break;
case ("image/png"):
isSupported = true;
break;
case ("audio/mp3"):
isSupported = true;
break;
case ("audio/wav"):
isSupported = true;
break;
}
return isSupported;
}
A tweaked, even more "bloated" version of red1ynx's answer:
#define __FILENAME__ \
(strchr(__FILE__, '\\') \
? ((strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)) \
: ((strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)))
If we find backslashes, we split on backslashes. Otherwise, split on forward slash. Simple enough.
Just about any alternative would be cleaner (A C++ constexpr is really the gold standard here, in my opinion). However, this may be helpful if you're using some compiler where __BASE_FILE__
isn't available.
You can run your script via cmd and be in script-directory:
cmd /k cd /d $(CURRENT_DIRECTORY) && python $(FULL_CURRENT_PATH)
I think it is linked with your RAM (or probably virtual memory) space and for the absolute maximum constrained to your OS version (e.g. 32 bit or 64 bit)
Once you have localized the dropdown element
dropdownElement = $("#dropdownElement");
Find the <option>
element using the JQuery attribute selector
dropdownElement.find('option[value=foo]').remove();
__file__
is absolute since Python 3.4, except when executing a script directly using a relative path:
Module
__file__
attributes (and related values) should now always contain absolute paths by default, with the sole exception of__main__.__file__
when a script has been executed directly using a relative path. (Contributed by Brett Cannon in bpo-18416.)
Not sure if it resolves symlinks though.
Example of passing a relative path:
$ python script.py
Marshalling is usually between relatively closely associated processes; serialization does not necessarily have that expectation. So when marshalling data between processes, for example, you may wish to merely send a REFERENCE to potentially expensive data to recover, whereas with serialization, you would wish to save it all, to properly recreate the object(s) when deserialized.
Assuming you're using jQuery..
var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
var parts = line.split(' ');
output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');
I Just put my view background (color code) as ClipArt og Image background, and it looks like transparent or no background where both have the same color as background.
Doing
logEvent.timeStamp / (1000*60*60)
will give you hours, not minutes. Try:
logEvent.timeStamp / (1000*60)
and you will end up with the same answer as
TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)
To read the content of .hdf5 file as an array, you can do something as follow
> import numpy as np
> myarray = np.fromfile('file.hdf5', dtype=float)
> print(myarray)
Another way to do it is using a limit
method:
Listing::limit(10)->get();
This can be useful if you're not trying to implement pagination, but for example, return 10 random rows from a table:
Listing::inRandomOrder()->limit(10)->get();
Send a SIGTERM or a SIGKILL to it:
http://en.wikipedia.org/wiki/SIGKILL
http://en.wikipedia.org/wiki/SIGTERM
SIGTERM is polite and lets the process clean up before it goes, whereas, SIGKILL is for when it won't listen >:)
Example from the shell (man page: http://unixhelp.ed.ac.uk/CGI/man-cgi?kill )
kill -9 pid
In C, you can do the same thing using the kill syscall:
kill(pid, SIGKILL);
See the following man page: http://linux.die.net/man/2/kill
Here is the Swift 3 answer for anyone looking since Swift 3 does not accept "Make".
aView.center = CGPoint(x: 200, Y: 200)
If you want to change the range to [0, 1], make sure the output data type is float
.
image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR) # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
You can use pigz instead of gzip, which does gzip compression on multiple cores. Instead of using the -z option, you would pipe it through pigz:
tar cf - paths-to-archive | pigz > archive.tar.gz
By default, pigz uses the number of available cores, or eight if it could not query that. You can ask for more with -p n, e.g. -p 32. pigz has the same options as gzip, so you can request better compression with -9. E.g.
tar cf - paths-to-archive | pigz -9 -p 32 > archive.tar.gz
Here's my current solution to run any code remotely on a given machine or list of machines asynchronously with logging, too!
@echo off
:: by Ralph Buchfelder, thanks to Mark Russinovich and Rob van der Woude for their work!
:: requires PsExec.exe to be in the same directory (download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx)
:: troubleshoot remote commands with PsExec arguments -i or -s if neccessary (see http://forum.sysinternals.com/pstools_forum8.html)
:: will run *in parallel* on a list of remote pcs (if given); to run serially please remove 'START "" CMD.EXE /C' from the psexec call
:: help
if '%1' =='-h' (
echo.
echo %~n0
echo.
echo Runs a command on one or many remote machines. If no input parameters
echo are given you will be asked for a target remote machine.
echo.
echo You will be prompted for remote credentials with elevated privileges.
echo.
echo UNC paths and local paths can be supplied.
echo Commands will be executed on the remote side just the way you typed
echo them, so be sure to mind extensions and the path variable!
echo.
echo Please note that PsExec.exe must be allowed on remote machines, i.e.
echo not blocked by firewall or antivirus solutions.
echo.
echo Syntax: %~n0 [^<inputfile^>]
echo.
echo inputfile = a plain text file ^(one hostname or ip address per line^)
echo.
echo.
echo Example:
echo %~n0 mylist.txt
exit /b 0
)
:checkAdmin
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' neq '0' (
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
)
set ADMINTESTDIR=%WINDIR%\System32\Test_%RANDOM%
mkdir "%ADMINTESTDIR%" 2>NUL
if errorlevel 1 (
cls
echo ERROR: This script requires elevated privileges!
echo.
echo Launch by Right-Click / Run as Administrator ...
pause
exit /b 1
) else (
rd /s /q "%ADMINTESTDIR%"
echo Running with elevated privileges...
)
echo.
:checkRequirements
if not exist "%~dp0PsExec.exe" (
echo PsExec.exe from Sysinternals/Microsoft not found
echo in %~dp0
echo.
echo Download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx
echo.
pause
exit /B
)
:environment
setlocal
echo.
echo %~n0
echo _____________________________
echo.
echo Working directory: %cd%\
echo Script directory: %~dp0
echo.
SET /P REMOTE_USER=Domain\Administrator :
SET "psCommand=powershell -Command "$pword = read-host 'Kennwort' -AsSecureString ; ^
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set REMOTE_PASS=%%p
if NOT DEFINED REMOTE_PASS SET /P REMOTE_PASS=Password :
echo.
if '%1' =='' goto menu
SET REMOTE_LIST=%1
:inputMultipleTargets
if not exist %REMOTE_LIST% (
echo File %REMOTE_LIST% not found
goto menu
)
type %REMOTE_LIST% >nul
if '%errorlevel%' neq '0' (
echo Access denied %REMOTE_LIST%
goto menu
)
set batchProcessing=true
echo Batch processing: %REMOTE_LIST% ...
ping -n 2 127.0.0.1 >nul
goto runOnce
:menu
if exist "%~dp0last.computer" set /p LAST_COMPUTER=<"%~dp0last.computer"
if exist "%~dp0last.listing" set /p LAST_LISTING=<"%~dp0last.listing"
if exist "%~dp0last.directory" set /p LAST_DIRECTORY=<"%~dp0last.directory"
if exist "%~dp0last.command" set /p LAST_COMMAND=<"%~dp0last.command"
if exist "%~dp0last.timestamp" set /p LAST_TIMESTAMP=<"%~dp0last.timestamp"
echo.
echo.
echo (1) select target computer [default]
echo (2) select multiple computers
echo -----------------------------------
echo last target : %LAST_COMPUTER%
echo last listing: %LAST_LISTING%
echo last path : %LAST_DIRECTORY%
echo last command: %LAST_COMMAND%
echo last run : %LAST_TIMESTAMP%
echo -----------------------------------
echo (0) exit
echo.
echo ENTER your choice.
echo.
echo.
:mychoice
SET /P mychoice=(0, 1, ...):
if NOT DEFINED mychoice goto promptSingleTarget
if "%mychoice%"=="1" goto promptSingleTarget
if "%mychoice%"=="2" goto promptMultipleTargets
if "%mychoice%"=="0" goto end
goto mychoice
:promptMultipleTargets
echo.
echo Please provide an input file
echo [one IP address or hostname per line]
SET /P REMOTE_LIST=Filename :
goto inputMultipleTargets
:promptSingleTarget
SET batchProcessing=
echo.
echo Please provide a hostname
SET /P REMOTE_COMPUTER=Target computer :
goto runOnce
:runOnce
cls
echo Note: Paths are mandatory for CMD-commands (e.g. dir,copy) to work!
echo Paths are provided on the remote machine via PUSHD.
echo.
SET /P REMOTE_PATH=UNC-Path or folder :
SET /P REMOTE_CMD=Command with params:
SET REMOTE_TIMESTAMP=%DATE% %TIME:~0,8%
echo.
echo Remote command starting (%REMOTE_PATH%\%REMOTE_CMD%) on %REMOTE_TIMESTAMP%...
if not defined batchProcessing goto runOnceSingle
:runOnceMulti
REM do for each line; this circumvents PsExec's @file to have stdouts separately
SET REMOTE_LOG=%~dp0\log\%REMOTE_LIST%
if not exist %REMOTE_LOG% md %REMOTE_LOG%
for /F "tokens=*" %%A in (%REMOTE_LIST%) do (
if "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "%REMOTE_CMD%" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
if not "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
)
goto restart
:runOnceSingle
SET REMOTE_LOG=%~dp0\log
if not exist %REMOTE_LOG% md %REMOTE_LOG%
if "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "%REMOTE_CMD%" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
if not "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
goto restart
:restart
echo.
echo.
echo Batch completed. Finished with last errorlevel %errorlevel% .
echo All outputs have been saved to %~dp0log\%REMOTE_TIMESTAMP%\.
echo %REMOTE_PATH% >"%~dp0last.directory"
echo %REMOTE_CMD% >"%~dp0last.command"
echo %REMOTE_LIST% >"%~dp0last.listing"
echo %REMOTE_COMPUTER% >"%~dp0last.computer"
echo %REMOTE_TIMESTAMP% >"%~dp0last.timestamp"
SET REMOTE_PATH=
SET REMOTE_CMD=
SET REMOTE_LIST=
SET REMOTE_COMPUTER=
SET REMOTE_LOG=
SET REMOTE_TIMESTAMP=
ping -n 2 127.0.0.1 >nul
goto menu
:end
SET REMOTE_USER=
SET REMOTE_PASS=
Use C# Dictionary datastructure it good for you...
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("one", 1);
dict.Add("two", 2);
You can retrieve data from Ditionary in a simple way..
foreach (KeyValuePair<string, int> pair in dict)
{
MessageBox.Show(pair.Key.ToString ()+ " - " + pair.Value.ToString () );
}
For more example using C# Dictionary... C# Dictionary
Navi.
In 2015 I would go with:
Of course you may want to keep JS for easy project setup and to avoid the transpilation process... there is no ultimate solution.
Or just wait for ECMA6, 7, ... :)
I don't know of Google voice, but using the javaScript speech SpeechSynthesisUtterance, you can add a click event to the element you are reference to. eg:
const listenBtn = document.getElementById('myvoice');
listenBtn.addEventListener('click', (e) => {
e.preventDefault();
const msg = new SpeechSynthesisUtterance(
"Hello, hope my code is helpful"
);
window.speechSynthesis.speak(msg);
});
_x000D_
<button type="button" id='myvoice'>Listen to me</button>
_x000D_
Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:
version: '2'
services:
mysql:
container_name: mysql
image: mysql:latest
restart: always
environment:
- MYSQL_ROOT_PASSWORD=root
ports:
- "3306:3306"
networks:
vpcbr:
ipv4_address: 10.5.0.5
apigw-tomcat:
container_name: apigw-tomcat
build: tomcat/.
ports:
- "8080:8080"
- "8009:8009"
networks:
vpcbr:
ipv4_address: 10.5.0.6
depends_on:
- mysql
networks:
vpcbr:
driver: bridge
ipam:
config:
- subnet: 10.5.0.0/16
gateway: 10.5.0.1
This one line jQuery code creates (and loads) a DOM element img without showing it:
$('<img src="img/1.jpg"/>');
This works cross-browser, provides more accessibility and comes with less markup. ditch the div. Wrap the label
label{
display: block;
height: 35px;
line-height: 35px;
border: 1px solid #000;
}
input{margin-top:15px; height:20px}
<label for="name">Name: <input type="text" id="name" /></label>
I use PHP to find the URL and match the page name (without the extension of .php, also I can add multiple pages that all have the same word in common like contact, contactform, etc. All will have that class added) and add a class with PHP to change the color, etc.
For that you would have to save your pages with file extension .php
.
Here is a demo. Change your links and pages as required. The CSS class for all the links is .tab
and for the active link there is also another class of .currentpage
(as is the PHP function) so that is where you will overwrite your CSS rules.
You could name them whatever you like.
<?php # Using REQUEST_URI
$currentpage = $_SERVER['REQUEST_URI'];?>
<div class="nav">
<div class="tab
<?php
if(preg_match("/index/i", $currentpage)||($currentpage=="/"))
echo " currentpage";
?>"><a href="index.php">Home</a>
</div>
<div class="tab
<?php
if(preg_match("/services/i", $currentpage))
echo " currentpage";
?>"><a href="services.php">Services</a>
</div>
<div class="tab
<?php
if(preg_match("/about/i", $currentpage))
echo " currentpage";
?>"><a href="about.php">About</a>
</div>
<div class="tab
<?php
if(preg_match("/contact/i", $currentpage))
echo " currentpage";
?>"><a href="contact.php">Contact</a>
</div>
</div> <!--nav-->
If you have read till this point, then probably, none of the answers above worked for you or suites you.
My solution to this problem is to shut down your computer, making sure to have saved all necessary open documents. Reboot your computer, Run Visual Studio and then you are good to go.
Without Error Handeling
//Load background texture
new THREE.TextureLoader();
loader.load('https://images.pexels.com/photos/1205301/pexels-photo-1205301.jpeg' , function(texture)
{
scene.background = texture;
});
With Error Handling
// Function called when download progresses
var onProgress = function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
};
// Function called when download errors
var onError = function (error) {
console.log('An error happened'+error);
};
//Function called when load completes.
var onLoad = function (texture) {
var objGeometry = new THREE.BoxGeometry(30, 30, 30);
var objMaterial = new THREE.MeshPhongMaterial({
map: texture,
shading: THREE.FlatShading
});
var boxMesh = new THREE.Mesh(objGeometry, objMaterial);
scene.add(boxMesh);
var render = function () {
requestAnimationFrame(render);
boxMesh.rotation.x += 0.010;
boxMesh.rotation.y += 0.010;
sphereMesh.rotation.y += 0.1;
renderer.render(scene, camera);
};
render();
}
//LOAD TEXTURE and on completion apply it on box
var loader = new THREE.TextureLoader();
loader.load('https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/The_Earth_seen_from_Apollo_17.jpg/1920px-The_Earth_seen_from_Apollo_17.jpg',
onLoad,
onProgress,
onError);
Result:
dic = {"key 1":"value 1","key b":"value b"}
#print the keys:
for key in dic:
print key
#print the values:
for value in dic.itervalues():
print value
#print key and values
for key, value in dic.iteritems():
print key, value
Note:In Python 3, dic.iteritems() was renamed as dic.items()
This has been discussed on SO multiple times. Here are a few links to get you started:
SO: Capturing image from webcam in java?
openCVF applet: http://www.colorfulwolf.com/blog/2011/07/05/accessing-the-webcam-from-inside-a-java-applet/
config: http://ganeshtiwaridotcomdotnp.blogspot.in/2011/12/opencv-javacv-eclipse-project.html
Node v0.6.x has a stable zlib module in core now - there are some examples on how to use it server-side in the docs too.
An example (taken from the docs):
// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
var zlib = require('zlib');
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response) {
var raw = fs.createReadStream('index.html');
var acceptEncoding = request.headers['accept-encoding'];
if (!acceptEncoding) {
acceptEncoding = '';
}
// Note: this is not a conformant accept-encoding parser.
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
if (acceptEncoding.match(/\bdeflate\b/)) {
response.writeHead(200, { 'content-encoding': 'deflate' });
raw.pipe(zlib.createDeflate()).pipe(response);
} else if (acceptEncoding.match(/\bgzip\b/)) {
response.writeHead(200, { 'content-encoding': 'gzip' });
raw.pipe(zlib.createGzip()).pipe(response);
} else {
response.writeHead(200, {});
raw.pipe(response);
}
}).listen(1337);
SELECT * FROM user_cons_columns WHERE table_name = 'table_name';
You can do it with a LIMIT, just not with a LIMIT and an OFFSET.
VT-x can normally be disabled/enabled in your BIOS.
When your PC is just starting up you should press DEL (or something) to get to the BIOS settings. There you'll find an option to enable VT-technology (or something).
Got to the question but could not figure out how to print it from externally-loaded mongo. So:
This works is for console: and is prefered in console, but does not work in external mongo-loaded javascript:
db.quizes.find().pretty()
This works in external mongo-loaded javscript:
db.quizes.find().forEach(printjson)
I am using this class for time in this format "hh:mm:ss" u can use it with "hh:mm:00" (zero seconds) for your example. Here is the complete code. It has compare and between function and also checks the time format (in case of invalid time and throws TimeException). Hope you can use it or modify it for your needs.
Time class:
package es.utility.time;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author adrian
*/
public class Time {
private int hours; //Hours of the day
private int minutes; //Minutes of the day
private int seconds; //Seconds of the day
private String time; //Time of the day
/**
* Constructor of Time class
*
* @param time
* @throws TimeException if time parameter is not valid
*/
public Time(String time) throws TimeException {
//Check if valid time
if (!validTime(time)) {
throw new TimeException();
}
//Init class parametars
String[] params = time.split(":");
this.time = time;
this.hours = Integer.parseInt(params[0]);
this.minutes = Integer.parseInt(params[1]);
this.seconds = Integer.parseInt(params[2]);
}
/**
* Constructor of Time class
*
* @param hours
* @param minutes
* @param seconds
* @throws TimeException if time parameter is not valid
*/
public Time(int hours, int minutes, int seconds) throws TimeException {
//Check if valid time
if (!validTime(hours, minutes, seconds)) {
throw new TimeException();
}
this.time = timeToString(hours, minutes, seconds);
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
/**
* Checks if the sting can be parsed as time
*
* @param time (correct from hh:mm:ss)
* @return true if ok <br/> false if not ok
*/
private boolean validTime(String time) {
String regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(time);
return m.matches();
}
/**
* Checks if the sting can be parsed as time
*
* @param hours hours
* @param minutes minutes
* @param seconds seconds
* @return true if ok <br/> false if not ok
*/
private boolean validTime(int hours, int minutes, int seconds) {
return hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59 && seconds >= 0 && seconds <= 59;
}
/**
* From Integer values to String time
*
* @param hours
* @param minutes
* @param seconds
* @return String generated from int values for hours minutes and seconds
*/
private String timeToString(int hours, int minutes, int seconds) {
StringBuilder timeBuilder = new StringBuilder("");
if (hours < 10) {
timeBuilder.append("0").append(hours);
} else {
timeBuilder.append(hours);
}
timeBuilder.append(":");
if (minutes < 10) {
timeBuilder.append("0").append(minutes);
} else {
timeBuilder.append(minutes);
}
timeBuilder.append(":");
if (seconds < 10) {
timeBuilder.append("0").append(seconds);
} else {
timeBuilder.append(seconds);
}
return timeBuilder.toString();
}
/**
* Compare this time to other
*
* @param compare
* @return -1 time is before <br/> 0 time is equal <br/> time is after
*/
public int compareTime(Time compare) {
//Check hours
if (this.getHours() < compare.getHours()) { //If hours are before return -1
return -1;
}
if (this.getHours() > compare.getHours()) { //If hours are after return 1
return 1;
}
//If no return hours are equeal
//Check minutes
if (this.getMinutes() < compare.getMinutes()) { //If minutes are before return -1
return -1;
}
if (this.getMinutes() > compare.getMinutes()) { //If minutes are after return 1
return 1;
}
//If no return minutes are equeal
//Check seconds
if (this.getSeconds() < compare.getSeconds()) { //If minutes are before return -1
return -1;
}
if (this.getSeconds() > compare.getSeconds()) { //If minutes are after return 1
return 1;
}
//If no return seconds are equeal and return 0
return 0;
}
public boolean isBetween(Time before, Time after) throws TimeException{
if(before.compareTime(after)== 1){
throw new TimeException("Time 'before' is after 'after' time");
}
//Compare with before and after
if (this.compareTime(before) == -1 || this.compareTime(after) == 1) { //If time is before before time return false or time is after after time
return false;
} else {
return true;
}
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
/**
* Override the toString method and return all of the class private
* parameters
*
* @return String Time{" + "hours=" + hours + ", minutes=" + minutes + ",
* seconds=" + seconds + ", time=" + time + '}'
*/
@Override
public String toString() {
return "Time{" + "hours=" + hours + ", minutes=" + minutes + ", seconds=" + seconds + ", time=" + time + '}';
}
}
TimeException class:
package es.utility.time;
/**
*
* @author adrian
*/
public class TimeException extends Exception {
public TimeException() {
super("Cannot create time with this params");
}
public TimeException(String message) {
super(message);
}
}
I tried a lot of these suggestions but noting seemed to work. I've wasted quite a few hours only to found out that this was my mistake:
@Scripts.Render("/bundles/foundation")
It always have me minified and bundled javascript, no matter what I tried. Instead, I should have used this:
@Scripts.Render("~/bundles/foundation")
The extra '~' did it. I've even removed it again in only one instance to see if that was really it. It was... hopefully I can save at least one person the hours I wasted on this.
Agree no matches in your example.
If you mean both columns on either then need a query like this or need to re-examine the data design.
Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA
INNER JOIN TableB
ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2
OR TableA.Col2 = TableB.Col1 OR TableA.Col1 = TableB.Col2
CSS:
.vertical {
display: table-caption;
}
Add this class to the element that contains the things you want to align vertically
It looks like Chrome 24 now support touch events, probably for Windows 8. So the code posted here no longer works. Instead of trying to detect if touch is supported by the browser, I'm now binding both touch and click events and making sure only one is called:
myCustomBind = function(controlName, callback) {
$(controlName).bind('touchend click', function(e) {
e.stopPropagation();
e.preventDefault();
callback.call();
});
};
And then calling it:
myCustomBind('#mnuRealtime', function () { ... });
Hope this helps !
When onMeasure
is called the view gets its measured width/height. After this, you can call layout.getMeasuredHeight()
.
Seems like AngularJS folks are working on it in version 1.3.0.
All you need to do is adding : 'UTC'
after the format string. Something like:
{{someDate | date:'d MMMM yyyy' : 'UTC'}}
As you can see in the docs, you can also play with it here: Plunker example
BTW, I think there is a bug with the Z parameter, since it still show local timezone even with 'UTC'.
I struggled for a couple of days to find anything that would work for me as was passing multiple arrays of ids and returning a blob. Turns out if using .NET CORE I'm using 2.1, you need to use [FromBody] and as can only use once you need to create a viewmodel to hold the data.
Wrap up content like below,
var params = {
"IDs": IDs,
"ID2s": IDs2,
"id": 1
};
In my case I had already json'd the arrays and passed the result to the function
var IDs = JsonConvert.SerializeObject(Model.Select(s => s.ID).ToArray());
Then call the XMLHttpRequest POST and stringify the object
var ajax = new XMLHttpRequest();
ajax.open("POST", '@Url.Action("MyAction", "MyController")', true);
ajax.responseType = "blob";
ajax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
ajax.onreadystatechange = function () {
if (this.readyState == 4) {
var blob = new Blob([this.response], { type: "application/octet-stream" });
saveAs(blob, "filename.zip");
}
};
ajax.send(JSON.stringify(params));
Then have a model like this
public class MyModel
{
public int[] IDs { get; set; }
public int[] ID2s { get; set; }
public int id { get; set; }
}
Then pass in Action like
public async Task<IActionResult> MyAction([FromBody] MyModel model)
Use this add-on if your returning a file
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
Here goes a bunch of different ways to get the ID, including Scope_Identity:
In rails 5, as per the instructions in Rails Guides, you can use:
redirect_back(fallback_location: root_path)
The 'back' location is pulled from the HTTP_REFERER header which is not guaranteed to be set by the browser. Thats why you should provide a 'fallback_location'.
If using an interactive debugger is OK for you, you can try perldebug.
Generally speaking you should not call GC explicitly with System.gc(). There is even the IO lecture (http://www.youtube.com/watch?v=_CruQY55HOk) where they explain what the GC pauses log mean and in which they also state to never call System.gc() because Dalvik knows better than you when to do so.
On the other hand as mentioned in above answers already GC process in Android (like everything else) is sometimes buggy. This means Dalvik GC algorithms are not on par with Hotspot or JRockit JVMs and might get things wrong on some occasions. One of those occasions is when allocating bitmap objects. This is a tricky one because it uses Heap and Non Heap memory and because one loose instance of bitmap object on memory constrained device is enough to give you an OutOfMemory exception. So calling it after you don't need this bitmap any-more is generally suggested by many developers and is even considered good practice by some people.
Better practice is using .recycle() on a bitmap as it is what this method is made for, as it marks native memory of the bitmap as safe to delete. Keep in mind that this is very version dependent, meaning it will generally be required on older Android versions (Pre 3.0 I think) but will not be required on later ones. Also it won't hurt much using it on newer versions ether (just don't do this in a loop or something like that). New ART runtime changed a lot here because they introduced special Heap "partition" for big objects but I think it will not hurt much to do this with ART ether.
Also one very important note about System.gc(). This method is not a command that Dalvik (or JVMs) are obligated to respond to. Consider it more like saying to Virtual machine "Could you please do garbage collection if it's not a hassle".
So many problems in so few lines. I probably forget some:
So
#include <stdio.h>
int main(int argc, char* argv[])
{
char const* const fileName = argv[1]; /* should check that argc > 1 */
FILE* file = fopen(fileName, "r"); /* should check the result */
char line[256];
while (fgets(line, sizeof(line), file)) {
/* note that fgets don't strip the terminating \n, checking its
presence would allow to handle lines longer that sizeof(line) */
printf("%s", line);
}
/* may check feof here to make a difference between eof and io failure -- network
timeout for instance */
fclose(file);
return 0;
}
All required parameters must be placed before any default arguments. Simply because they are mandatory, whereas default arguments are not. Syntactically, it would be impossible for the interpreter to decide which values match which arguments if mixed modes were allowed. A SyntaxError
is raised if the arguments are not given in the correct order:
Let us take a look at keyword arguments, using your function.
def fun1(a="who is you", b="True", x, y):
... print a,b,x,y
Suppose its allowed to declare function as above, Then with the above declarations, we can make the following (regular) positional or keyword argument calls:
func1("ok a", "ok b", 1) # Is 1 assigned to x or ?
func1(1) # Is 1 assigned to a or ?
func1(1, 2) # ?
How you will suggest the assignment of variables in the function call, how default arguments are going to be used along with keyword arguments.
>>> def fun1(x, y, a="who is you", b="True"):
... print a,b,x,y
...
Reference O'Reilly - Core-Python
Where as this function make use of the default arguments syntactically correct for above function calls.
Keyword arguments calling prove useful for being able to provide for out-of-order positional arguments, but, coupled with default arguments, they can also be used to "skip over" missing arguments as well.
I simply override the css:
.modal-dialog {
max-width: 1000px;
}
Just use com.google.common.io.Resources class. Example:
URL url = Resources.getResource("file name")
After that you have methods like: .getContent(), .getFile(), .getPath() etc
Both const
and constexpr
can be applied to variables and functions. Even though they are similar to each other, in fact they are very different concepts.
Both const
and constexpr
mean that their values can't be changed after their initialization. So for example:
const int x1=10;
constexpr int x2=10;
x1=20; // ERROR. Variable 'x1' can't be changed.
x2=20; // ERROR. Variable 'x2' can't be changed.
The principal difference between const
and constexpr
is the time when their initialization values are known (evaluated). While the values of const
variables can be evaluated at both compile time and runtime, constexpr
are always evaluated at compile time. For example:
int temp=rand(); // temp is generated by the the random generator at runtime.
const int x1=10; // OK - known at compile time.
const int x2=temp; // OK - known only at runtime.
constexpr int x3=10; // OK - known at compile time.
constexpr int x4=temp; // ERROR. Compiler can't figure out the value of 'temp' variable at compile time so `constexpr` can't be applied here.
The key advantage to know if the value is known at compile time or runtime is the fact that compile time constants can be used whenever compile time constants are needed. For instance, C++ doesn't allow you to specify C-arrays with the variable lengths.
int temp=rand(); // temp is generated by the the random generator at runtime.
int array1[10]; // OK.
int array2[temp]; // ERROR.
So it means that:
const int size1=10; // OK - value known at compile time.
const int size2=temp; // OK - value known only at runtime.
constexpr int size3=10; // OK - value known at compile time.
int array3[size1]; // OK - size is known at compile time.
int array4[size2]; // ERROR - size is known only at runtime time.
int array5[size3]; // OK - size is known at compile time.
So const
variables can define both compile time constants like size1
that can be used to specify array sizes and runtime constants like size2
that are known only at runtime and can't be used to define array sizes. On the other hand constexpr
always define compile time constants that can specify array sizes.
Both const
and constexpr
can be applied to functions too. A const
function must be a member function (method, operator) where application of const
keyword means that the method can't change the values of their member (non-static) fields. For example.
class test
{
int x;
void function1()
{
x=100; // OK.
}
void function2() const
{
x=100; // ERROR. The const methods can't change the values of object fields.
}
};
A constexpr
is a different concept. It marks a function (member or non-member) as the function that can be evaluated at compile time if compile time constants are passed as their arguments. For example you can write this.
constexpr int func_constexpr(int X, int Y)
{
return(X*Y);
}
int func(int X, int Y)
{
return(X*Y);
}
int array1[func_constexpr(10,20)]; // OK - func_constexpr() can be evaluated at compile time.
int array2[func(10,20)]; // ERROR - func() is not a constexpr function.
int array3[func_constexpr(10,rand())]; // ERROR - even though func_constexpr() is the 'constexpr' function, the expression 'constexpr(10,rand())' can't be evaluated at compile time.
By the way the constexpr
functions are the regular C++ functions that can be called even if non-constant arguments are passed. But in that case you are getting the non-constexpr values.
int value1=func_constexpr(10,rand()); // OK. value1 is non-constexpr value that is evaluated in runtime.
constexpr int value2=func_constexpr(10,rand()); // ERROR. value2 is constexpr and the expression func_constexpr(10,rand()) can't be evaluated at compile time.
The constexpr
can be also applied to the member functions (methods), operators and even constructors. For instance.
class test2
{
static constexpr int function(int value)
{
return(value+1);
}
void f()
{
int x[function(10)];
}
};
A more 'crazy' sample.
class test3
{
public:
int value;
// constexpr const method - can't chanage the values of object fields and can be evaluated at compile time.
constexpr int getvalue() const
{
return(value);
}
constexpr test3(int Value)
: value(Value)
{
}
};
constexpr test3 x(100); // OK. Constructor is constexpr.
int array[x.getvalue()]; // OK. x.getvalue() is constexpr and can be evaluated at compile time.
System
is a final class from the java.lang
package.
out
is a class variable of type PrintStream
declared in the System
class.
println
is a method of the PrintStream
class.
According to new Gradle based build system
. We have to put assets
under main
folder.
Or simply right click on your project and create it like
File > New > folder > assets Folder
A more compact example of a custom adapter (using list array as my data):
class MyAdapter extends ArrayAdapter<Object> {
public ArrayAdapter(Context context, List<MyObject> objectList) {
super(context, R.layout.my_list_item, R.id.textViewTitle, objectList.toArray());
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
TextView title = (TextView) row.findViewById(R.id.textViewTitle);
ImageView icon = (ImageView) row.findViewById(R.id.imageViewAccessory);
MyObject obj = (MyObject) getItem(position);
icon.setImageBitmap( ... );
title.setText(obj.name);
return row;
}
}
And this is how to use it:
List<MyObject> objectList = ...
MyAdapter adapter = new MyAdapter(this.getActivity(), objectList);
listView.setAdapter(adapter);
You can use array_agg
function for that:
SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";
Result:
MOVIE | ACTOR |
---|---|
A | 1,2,3 |
B | 4 |
See this SQLFiddle
For more See 9.18. Aggregate Functions
I prefer to use WebClient, it seems to handle SSL transparently:
http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx
Some troubleshooting help here:
Though alluded to in other comments I thought I'd spell it out a bit for those using the "Controller As" syntax:
<div ng-controller="MyController as ctrl">
<form name="ctrl.myForm">
...inputs
Dirty? {{ctrl.myForm.$dirty}}
<button ng-click="ctrl.saveChanges()">Save</button>
</form>
</div>
Then you can access the FormController in your code like:
function MyController () {
var vm = this;
vm.saveChanges = saveChanges;
function saveChanges() {
if(vm.myForm.$valid) {
// Save to db or whatever.
vm.myForm.$setPristine();
}
}
Use these:
Then you will get the page you want (more options than the admin page) with privileges.
Sure, you can use equals
if you want to go along with the crowd, but if you really want to amaze your fellow programmers check for inequality like this:
if ("success" != statusCheck.intern())
intern method is part of standard Java String API.
Educated guess: You have a ISO-8859-1 encoded pound sign in a UTF-8 encoded page.
Make sure your data is in the right encoding and everything will work fine.
if you're using the compiled bootstrap, one of the ways of fixing it is by editing the bootstrap.min.js before the line
$next[0].offsetWidth
force reflow Change to
if (typeof $next == 'object' && $next.length) $next[0].offsetWidth // force reflow
If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):
>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])
For at DataFrame one can simply type
head(data, num=10L)
to get the first 10 for example.
For a data.frame one can simply type
head(data, 10)
to get the first 10.
If you try to iterate with for ($col = 2; $col <= 'AC'; ++ $col){...}
, or with foreach(range('A','AC') as $col) {...}
it will work for columns from A to Z, but it fails pass the Z (Ex. iterate between 'A' to 'AC').
In order to iterate pass 'Z', you need to convert the column to integer, increment, compare, and get it as string again:
$MAX_COL = $sheet->getHighestDataColumn();
$MAX_COL_INDEX = PHPExcel_Cell::columnIndexFromString($MAX_COL);
for($index=0 ; $index <= $MAX_COL_INDEX ; $index++){
$col = PHPExcel_Cell::stringFromColumnIndex($index);
// do something, like set the column width...
$sheet->getColumnDimension($col)->setAutoSize(TRUE);
}
With this, you easy iterate pass the 'Z' column and set autosize to every column.
The dynamic SQL is a different scope to the outer, calling SQL: so @siteid is not recognised
You'll have to use a temp table/table variable outside of the dynamic SQL:
DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId TABLE (siteid int)
INSERT @siteId
exec ('SELECT TOP 1 Id FROM ' + @dbName + '..myTbl')
select * FROM @siteId
Note: TOP without an ORDER BY is meaningless. There is no natural, implied or intrinsic ordering to a table. Any order is only guaranteed by the outermost ORDER BY
Sorry this answer sucks, but you can't launch an just any external application via a click, as this would be a serious security issue, this functionality isn't available in HTML or javascript. Think of just launching cmd.exe
with args...you want to launch WinMerge with arguments, but you can see the security problems introduced by allowing this for anything.
The only possibly viable exception I can think of would be a protocol handler (since these are explicitly defined handlers), like winmerge://
, though the best way to pass 2 file parameters I'm not sure of, if it's an option it's worth looking into, but I'm not sure what you are or are not allowed to do to the client, so this may be a non-starter solution.
Probably I am too late to answer. But if anybody need it, following works fine, as I have used it a lot of times.
npm config set registry=https://registry.npmjs.com/
You use separator when you are building a file path. So in unix the separator is /
. So if you wanted to build the unix path /var/temp
you would do it like this:
String path = File.separator + "var"+ File.separator + "temp"
You use the pathSeparator
when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is: /path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar
So given a list of files you would do something like this:
String listOfFiles = ...
String[] filePaths = listOfFiles.split(File.pathSeparator);
public static string JSONSerialize<T>(T obj)
{
string retVal = String.Empty;
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
serializer.WriteObject(ms, obj);
var byteArray = ms.ToArray();
retVal = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
}
return retVal;
}
There is an alternative to using COPY, which is the multirow values syntax that Postgres supports. From the documentation:
INSERT INTO films (code, title, did, date_prod, kind) VALUES
('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');
The above code inserts two rows, but you can extend it arbitrarily, until you hit the maximum number of prepared statement tokens (it might be $999, but I'm not 100% sure about that). Sometimes one cannot use COPY, and this is a worthy replacement for those situations.
Your code is perfectly fine, you are just not looking at the right location to find your file. Since you haven't provided absolute path, your file will be created relative to the current working folder (more precisely in the current working folder in your case).
Your current working folder is set by Qt Creator. Go to Projects >> Your selected build >> Press the 'Run' button (next to 'Build) and you will see what it is on this page which of course you can change as well.
With async: false
you get yourself a blocked browser.
For a non blocking synchronous solution you can use the following:
With ES6 you can use a generator & the co library:
beforecreate: function (node, targetNode, type, to) {
co(function*(){
let result = yield jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value));
//Just use the result here
});
}
With ES7 you can just use asyc await:
beforecreate: function (node, targetNode, type, to) {
(async function(){
let result = await jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value));
//Just use the result here
})();
}
You can use now()
like:
Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();
No, it doesn't, see: R Language Definition: Operators
Would a dataframe of NA
s work?
something like:
data.frame(matrix(NA, nrow = 2, ncol = 3))
if you need to be more specific about the data type then may prefer: NA_integer_
, NA_real_
, NA_complex_
, or NA_character_
instead of just NA
which is logical
Something else that may be more specific that the NAs
is:
data.frame(matrix(vector(mode = 'numeric',length = 6), nrow = 2, ncol = 3))
where the mode can be of any type. See ?vector
The activity in which you want to add listview footer and i have also generate an event on listview footer click.
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list_of_f = (ListView) findViewById(R.id.list_of_f);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.web_view, null); // i have open a webview on the listview footer
RelativeLayout layoutFooter = (RelativeLayout) view.findViewById(R.id.layoutFooter);
list_of_f.addFooterView(view);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg" >
<ImageView
android:id="@+id/dept_nav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/dept_nav" />
<ListView
android:id="@+id/list_of_f"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/dept_nav"
android:layout_margin="5dp"
android:layout_marginTop="10dp"
android:divider="@null"
android:dividerHeight="0dp"
android:listSelector="@android:color/transparent" >
</ListView>
</RelativeLayout>
One more solution:
<a data-toggle="modal" data-target="#exampleModalCenter">
<span
class="tags"
data-toggle="tooltip"
data-placement="right"
title="Tooltip text"
>
Text
</span>
</a>
One to one (1-1) relationship: This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.
One to Many (1-M) relationship: This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).
Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.
-- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
ID INT IDENTITY(1, 1) NOT NULL,
CallTime DATETIME NOT NULL DEFAULT GETDATE(),
CallerPhoneNumber CHAR(10) NOT NULL
)
-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
ID INT IDENTITY(1, 1) NOT NULL,
CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
Subject VARCHAR(250) NOT NULL,
Notes VARCHAR(8000) NOT NULL,
Completed BIT NOT NULL DEFAULT 0
)
-- This table will link a phone call with a ticket.
CREATE TABLE dbo.PhoneCalls_Tickets
(
PhoneCallID INT NOT NULL,
TicketID INT NOT NULL
)
You should use what your FPGA documentation recommends. There is no portable way to initialize register values other than using a reset net. This has a hardware cost associated with it on most synthesis targets.
Here's a javascript example from mozilla:
var o = { a:0 } // `o` is now a basic object
Object.defineProperty(o, "b", {
get: function () {
return this.a + 1;
}
});
console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
I've used these A LOT because they are awesome. I would use it when getting fancy with my coding + animation. For example, make a setter that deals with an Number
which displays that number on your webpage. When the setter is used it animates the old number to the new number using a tweener. If the initial number is 0 and you set it to 10 then you would see the numbers flip quickly from 0 to 10 over, let's say, half a second. Users love this stuff and it's fun to create.
Example from sof
<?php
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
?>
citings:
Why do we need virtual functions?
Virtual functions avoid unnecessary typecasting problem, and some of us can debate that why do we need virtual functions when we can use derived class pointer to call the function specific in derived class!the answer is - it nullifies the whole idea of inheritance in large system development, where having single pointer base class object is much desired.
Let's compare below two simple programs to understand the importance of virtual functions:
Program without virtual functions:
#include <iostream>
using namespace std;
class father
{
public: void get_age() {cout << "Fathers age is 50 years" << endl;}
};
class son: public father
{
public : void get_age() { cout << "son`s age is 26 years" << endl;}
};
int main(){
father *p_father = new father;
son *p_son = new son;
p_father->get_age();
p_father = p_son;
p_father->get_age();
p_son->get_age();
return 0;
}
OUTPUT:
Fathers age is 50 years
Fathers age is 50 years
son`s age is 26 years
Program with virtual function:
#include <iostream>
using namespace std;
class father
{
public:
virtual void get_age() {cout << "Fathers age is 50 years" << endl;}
};
class son: public father
{
public : void get_age() { cout << "son`s age is 26 years" << endl;}
};
int main(){
father *p_father = new father;
son *p_son = new son;
p_father->get_age();
p_father = p_son;
p_father->get_age();
p_son->get_age();
return 0;
}
OUTPUT:
Fathers age is 50 years
son`s age is 26 years
son`s age is 26 years
By closely analyzing both the outputs one can understand the importance of virtual functions.
Just export you view and you will have all SQL need to make some change on it.
Just need to add your change in SQL query for the view and change :
CREATE for CREATE OR REPLACE
MVP:
Advantages:
Presenter will be present in between Model and view.Presenter will fetch data from Model and will do manipulations for data as view wants and give it to view and view is responsible only for rendering.
Disadvantages:
1)We can't use presenter for multiple modules because data is being modified in presenter as desired by one view class.
3)Breaking Clean architecture because data flow should be only outwards but here data is coming back from presenter to View.
MVC:
Advanatages:
Here we have Controller in between view and model.Here data request will be done from controller to view but data will be sent back to view in form of interface but not with controller.So,here controller won't get bloated up because of many transactions.
Disadvantagaes:
Data Manipulation should be done by View as it wants and this will be extra work on UI thread which may effect UI rendering if data processing is more.
MVVM:
After announcing Architectural components,we got access to ViewModel which provided us biggest advantage i.e it's lifecycle aware.So,it won't notify data if view is not available.It is a clean architecture because flow is only in forward mode and data will be notified automatically by LiveData. So,it is Android's recommended architecture.
Even MVVM has a disadvantage. Since it is a lifecycle aware some concepts like alarm or reminder should come outside app.So,in this scenario we can't use MVVM.
Rather than adding libraries which increases your apk size, I will suggest you to convert Svg to drawable using http://inloop.github.io/svg2android/ .
and add vectorDrawables.useSupportLibrary = true
in gradle,
This is what I managed to do so far. I guess this is kind of what you're trying to pull out. The only thing is that I can still not manage to assign the proper height to the container DIV.
The HTML:
<div id="container">
<div id="header">HEADER</div>
<div id="fixeddiv-top">FIXED DIV (TOP)</div>
<div id="content-container">
<div id="content">CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT</div>
</div>
<div id="fixeddiv-bottom">FIXED DIV (BOTTOM)</div>
</div>
And the CSS:
html {
height:100%;
}
body {
height:100%;
margin:0;
padding:0;
}
#container {
width:600px;
height:50%;
text-align:center;
display:block;
position:relative;
}
#header {
background:#069;
text-align:center;
width:100%;
height:80px;
}
#fixeddiv-top {
background:#AAA;
text-align:center;
width:100%;
height:20px;
}
#content-container {
height:100%;
}
#content {
text-align:center;
height:100%;
background:#F00;
margin:0 auto;
overflow:auto;
}
#fixeddiv-bottom {
background:#AAA;
text-align:center;
width:100%;
height:20px;
}
Clone your fork:
git clone [email protected]:YOUR-USERNAME/YOUR-FORKED-REPO.git
Add remote from original repository in your forked repository:
cd into/cloned/fork-repo
git remote add upstream git://github.com/ORIGINAL-DEV-USERNAME/REPO-YOU-FORKED-FROM.git
git fetch upstream
Updating your fork from original repo to keep up with their changes:
git pull upstream master
git push
Python 2
Using urllib.urlretrieve
import urllib
urllib.urlretrieve("http://www.gunnerkrigg.com//comics/00000001.jpg", "00000001.jpg")
Python 3
Using urllib.request.urlretrieve (part of Python 3's legacy interface, works exactly the same)
import urllib.request
urllib.request.urlretrieve("http://www.gunnerkrigg.com//comics/00000001.jpg", "00000001.jpg")
According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource
, as per this line:
java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource
class in it.
Reflection
has many uses. The one I am more familiar with, is to be able to create code on the fly.
IE: dynamic classes, functions, constructors - based on any data (xml/array/sql results/hardcoded/etc..)
In my case none of the answers helped. Finally it turned out, that changing to a 64 bit version of PHP (M$ Windows) fixed the problem immediately. I did not change any settings - it just worked.
As of IE 9. You can now load a text file and set a style.innerHTML property. So essentially you can now load a css file through ajax (and get the callback) and then just set the text inside of a style tag like this.
This works in other browsers, not sure how far back. But as long as you don't need to support IE8 then it would work.
// RESULT: doesn't work in IE8 and below. Works in IE9 and other browsers.
$(document).ready(function() {
// we want to load the css as a text file and append it with a style.
$.ajax({
url:'myCss.css',
success: function(result) {
var s = document.createElement('style');
s.setAttribute('type', 'text/css');
s.innerHTML = result;
document.getElementsByTagName("head")[0].appendChild(s);
},
fail: function() {
alert('fail');
}
})
});
and then you can have it pull an external file like the myCss.css
.myClass { background:#F00; }
Use count(d.ertek)
or count(d.id)
instead of count(d)
. This can be happen when you have composite primary key at your entity.
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
Here's a batch file, called base64encode.bat, that encodes base64.
@echo off
if not "%1" == "" goto :arg1exists
echo usage: base64encode input-file [output-file]
goto :eof
:arg1exists
set base64out=%2
if "%base64out%" == "" set base64out=con
(
set base64tmp=base64.tmp
certutil -encode "%1" %base64tmp% > nul
findstr /v /c:- %base64tmp%
erase %base64tmp%
) > %base64out%
Well, the most likely difference is that you still have to do an actual lookup of localhost
somewhere.
If you use 127.0.0.1
, then (intelligent) software will just turn that directly into an IP address and use it. Some implementations of gethostbyname
will detect the dotted format (and presumably the equivalent IPv6 format) and not do a lookup at all.
Otherwise, the name has to be resolved. And there's no guarantee that your hosts
file will actually be used for that resolution (first, or at all) so localhost
may become a totally different IP address.
By that I mean that, on some systems, a local hosts
file can be bypassed. The host.conf
file controls this on Linux (and many other Unices).
You most likely want to examine the documentation for T-SQL's CAST and CONVERT functions, located in the documentation here: http://msdn.microsoft.com/en-US/library/ms187928(v=SQL.90).aspx
You will then use one of those functions in your T-SQL query to convert the [idate] column from the database into the datetime format of your liking in the output.
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
This probably means that python doesn't know where PyQt5 is located. To check, go into the interactive terminal and type:
import sys
print sys.path
What you probably need to do is add the directory that contains the PyQt5 module to your PYTHONPATH
environment variable. If you use bash
, here's how:
~/.bashrc
export PYTHONPATH=/path/to/PyQt5/directory:$PYTHONPATH
where /path/to/PyQt5/directory
is the path to the folder where the PyQt5 library is located.
Try this-
$('select').on('change', function() {_x000D_
alert( this.value );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
<option value="1">One</option>_x000D_
<option value="2">Two</option>_x000D_
</select>
_x000D_
You can also reference with onchange event-
function getval(sel)_x000D_
{_x000D_
alert(sel.value);_x000D_
}
_x000D_
<select onchange="getval(this);">_x000D_
<option value="1">One</option>_x000D_
<option value="2">Two</option>_x000D_
</select>
_x000D_
If you are creating a code library, then I would use namespace. However, you can still only have one Color enum inside that namespace. If you need an enum that might use a common name, but might have different constants for different classes, use your approach.
Sounds like a job for a shell script to me:
for file in 'find -name *.xml'
do
grep 'hello' file
done
or something like that
Here's straightforward way without resorting to custom comparators or stuff like that:
Set<String> gasNames = new HashSet<String>();
List<YourRecord> records = ...;
for(YourRecord record : records) {
gasNames.add(record.getGasName());
}
// now gasNames is a set of unique gas names, which you could operate on:
List<String> sortedGasses = new ArrayList<String>(gasNames);
Collections.sort(sortedGasses);
Note: Using TreeSet
instead of HashSet
would give directly sorted arraylist and above Collections.sort
could be skipped, but TreeSet
is otherwise less efficent, so it's often better, and rarely worse, to use HashSet
even when sorting is needed.
Here is what i did and it works.
I just used a stringified object.
$scope.thread = [
{
mostRecent:{text:'hello world',timeStamp:12345678 }
allMessages:[]
}
{MoreThreads...}
{etc....}
]
<div ng-repeat="message in thread | orderBy : '-mostRecent.timeStamp'" >
if i wanted to sort by text i would do
orderBy : 'mostRecent.text'
To recap (and make it clearer) ...
this code:
function Hello() {
alert("caller is " + arguments.callee.caller.toString());
}
is equivalent to this:
function Hello() {
alert("caller is " + Hello.caller.toString());
}
Clearly the first bit is more portable, since you can change the name of the function, say from "Hello" to "Ciao", and still get the whole thing to work.
In the latter, in case you decide to refactor the name of the invoked function (Hello), you would have to change all its occurrences :(
With older Linux distros yet another option is to use wrapping script, e.g. in Perl or Python.
See solutions here:
http://linuxaria.com/article/how-to-make-dmesg-timestamp-human-readable?lang=en http://jmorano.moretrix.com/2012/03/dmesg-human-readable-timestamps/
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
I faced the same problem when I wanted to run a Rake Task but without running the callbacks for every record I was saving. This worked for me (Rails 5), and it must work for almost every version of Rails:
class MyModel < ApplicationRecord
attr_accessor :skip_callbacks
before_create :callback1
before_update :callback2
before_destroy :callback3
private
def callback1
return true if @skip_callbacks
puts "Runs callback1"
# Your code
end
def callback2
return true if @skip_callbacks
puts "Runs callback2"
# Your code
end
# Same for callback3 and so on....
end
The way it works is that it just returns true in the first line of the method it skip_callbacks is true, so it doesn't run the rest of the code in the method. To skip callbacks you just need to set skip_callbacks to true before saving, creating, destroying:
rec = MyModel.new() # Or Mymodel.find()
rec.skip_callbacks = true
rec.save
27
is the code for the escape key. :)
I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.
Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!
Hope to help
You can user pagination of Instagram PHP API: https://github.com/cosenary/Instagram-PHP-API/wiki/Using-Pagination
Something like that:
$Instagram = new MetzWeb\Instagram\Instagram(array(
"apiKey" => IG_APP_KEY,
"apiSecret" => IG_APP_SECRET,
"apiCallback" => IG_APP_CALLBACK
));
$Instagram->setSignedHeader(true);
$pictures = $Instagram->getUserMedia(123);
do {
foreach ($pictures->data as $picture_data):
echo '<img src="'.$picture_data->images->low_resolution->url.'">';
endforeach;
} while ($pictures = $instagram->pagination($pictures));
you're stuck with the
WHERE something LIKE 'bla%'
OR something LIKE '%foo%'
OR something LIKE 'batz%'
unless you populate a temp table (include the wild cards in with the data) and join like this:
FROM YourTable y
INNER JOIN YourTempTable t On y.something LIKE t.something
try it out (using SQL Server syntax):
declare @x table (x varchar(10))
declare @y table (y varchar(10))
insert @x values ('abcdefg')
insert @x values ('abc')
insert @x values ('mnop')
insert @y values ('%abc%')
insert @y values ('%b%')
select distinct *
FROM @x x
WHERE x.x LIKE '%abc%'
or x.x LIKE '%b%'
select distinct x.*
FROM @x x
INNER JOIN @y y On x.x LIKE y.y
OUTPUT:
x
----------
abcdefg
abc
(2 row(s) affected)
x
----------
abc
abcdefg
(2 row(s) affected)
Using element-wise multiplication and a set:
>>> states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> set(multiply(states,range(1,len(states)+1))-1).difference({-1})
Output:
{4, 5, 7}
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
It only worked with me when I "flushed" after the commands mentioned here. Here's the full list of commands I used:
Previous answers might not work for later mysql versions. Try these steps if previous answers did not work for you:
1- Click on the wamp icon > mysql > mysql console
2- write following commands, one by one
use mysql;
update user set authentication_string=password('your_password') where user='root';
FLUSH PRIVILEGES;
quit