Assuming you do as David Zaslavsky suggests, so that the first argument simply is the program to run (no option-parsing required), you're dealing with the question of how to pass arguments 2 and on to your external program. Here's a convenient way:
#!/bin/bash
ext_program="$1"
shift
"$ext_program" "$@"
The shift
will remove the first argument, renaming the rest ($2
becomes $1, and so on).
$@` refers to the arguments, as an array of words (it must be quoted!).
If you must have your --file
syntax (for example, if there's a default program to run, so the user doesn't necessarily have to supply one), just replace ext_program="$1"
with whatever parsing of $1
you need to do, perhaps using getopt or getopts.
If you want to roll your own, for just the one specific case, you could do something like this:
if [ "$#" -gt 0 -a "${1:0:6}" == "--file" ]; then
ext_program="${1:7}"
else
ext_program="default program"
fi
For me the solution was one of the methods had to be void, I had it as Boolean.
public static class DateTimeExtensions
{
public static DateTime LastDayOfMonth(this DateTime date)
{
return date.AddDays(1-(date.Day)).AddMonths(1).AddDays(-1);
}
}
select name, count(*) from table group by name;
i think should do it
Wrap all the children inside of another LinearLayout with wrap_content
for both the width and the height as well as the vertical orientation.
All interaction between server(your flask app) and client(browser) going by request and response. When user hit button submit in your form his browser send request with this form to your server (flask app), and you can get content of the form like:
request.args.get('form_name')
Try this:
jsonResponse = json.loads(response.decode('utf-8'))
You can see in this List of useful HTTP headers.
X-XSS-Protection: This header enables the Cross-site scripting (XSS) filter built into most recent web browsers. It's usually enabled by default anyway, so the role of this header is to re-enable the filter for this particular website if it was disabled by the user. This header is supported in IE 8+, and in Chrome (not sure which versions). The anti-XSS filter was added in Chrome 4. Its unknown if that version honored this header.
This actually is possible, and I discovered how quite by accident while designing my first large-scale responsive design site.
<div class="wrapper">
<div class="box">
<img src="/logo.png" alt="">
</div>
</div>
.wrapper { position:relative; overflow:hidden; }
.box { float:left; } //Note: 'float:right' would work too
.box > img { width:50%; }
The overflow:hidden gives the wrapper height and width, despite the floating contents, without using the clearfix hack. You can then position your content using margins. You can even make the wrapper div an inline-block.
In
int *ptr= l_matrix[0];
you can access like
*p
*(p+1)
*(p+2)
after all 2 dimensional arrays are also stored as 1-d.
I stumbled over the same question and I've found a solution.
First make sure you upgrade to LESS 1.6 at least.
You can use npm
for that case.
Now you can use the following mixin:
.if (@condition, @property, @value) when (@condition = true){
@{property}: @value;
}
Since LESS 1.6 you are able to pass PropertyNames to Mixins as well. So for example you could just use:
.myHeadline {
.if(@include-lineHeight, line-height, '35px');
}
If @include-lineheight resolves to true LESS will print the line-height: 35px
and it will skip the mixin if @include-lineheight is not true.
You can create separate class for validation as below:
enum AIValidationRule: Int {
case
EmptyCheck,
MinMaxLength,
FixedLength,
EmailCheck,
UpperCase,
LowerCase,
SpecialCharacter,
DigitCheck,
WhiteSpaces,
None
}
let ValidationManager = AIValidationManager.sharedManager
func validateTextField(txtField:AITextField, forRule rule:AIValidationRule, withMinimumChar minChar:Int, andMaximumChar maxChar:Int) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {
switch rule {
case .EmptyCheck:
return (txtField.text?.characters.count == 0) ? (false,"Please enter \(txtField.placeholder!.lowercased())",txtField) : nil
case .MinMaxLength:
return (txtField.text!.characters.count < minChar || txtField.text!.characters.count > maxChar) ? (false,"\(txtField.placeholder!) should be of \(minChar) to \(maxChar) characters",txtField) : nil
case .FixedLength:
return (txtField.text!.characters.count != minChar) ? (false,"\(txtField.placeholder!) should be of \(minChar) characters",txtField) : nil
case .EmailCheck:
return (!(txtField.text?.isValidEmail())!) ? (false,"Please enter valid email",txtField) : nil
case .UpperCase:
return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet.uppercaseLetters).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one uppercase letter",txtField) : nil
case .LowerCase:
return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet.lowercaseLetters).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one lowercase letter",txtField) : nil
case .SpecialCharacter:
let symbolCharacterSet = NSMutableCharacterSet.symbol()
symbolCharacterSet.formUnion(with: NSCharacterSet.punctuationCharacters)
return ((txtField.text! as NSString).rangeOfCharacter(from: symbolCharacterSet as CharacterSet).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one special letter",txtField) : nil
case .DigitCheck:
return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet(charactersIn: "0123456789") as CharacterSet).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one digit letter",txtField) : nil
case .WhiteSpaces:
return (txtField.text!.containsAdjacentSpaces() || txtField.text!.isLastCharcterAWhiteSpace()) ? (false,"\(txtField.placeholder!) seems to be invalid",txtField) : nil
case .None:
return nil
}
}
func validateTextField(txtField:AITextField, forRules rules:[AIValidationRule]) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {
return validateTextField(txtField: txtField, forRules: rules, withMinimumChar: 0, andMaximumChar: 0)
}
func validateTextField(txtField:AITextField, forRules rules:[AIValidationRule], withMinimumChar minChar:Int, andMaximumChar maxChar:Int) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {
var strMessage:String = ""
for eachRule in rules {
if let result = validateTextField(txtField: txtField, forRule: eachRule, withMinimumChar: minChar, andMaximumChar: maxChar) {
if(eachRule == AIValidationRule.EmptyCheck){
return result
}else{
strMessage += "\(strMessage.characters.count == 0 ? "" : "\n\n") \(result.errMessage)"
}
}
}
return strMessage.characters.count > 0 ? (false,strMessage,txtField) : nil
}
Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed
The API does not support that directly. You can use the for(int i..) loop and count the elements or use subLists(0, size - 1) and handle the last element explicitly:
if(x.isEmpty()) return;
int last = x.size() - 1;
for(Integer i : x.subList(0, last)) out.println(i);
out.println("last " + x.get(last));
This is only useful if it does not introduce redundancy. It performs better than the counting version (after the subList overhead is amortized). (Just in case you cared after the boxing anyway).
Like that. Except char hi=hello;
should be char hi=hello.charAt(0)
. (Don't forget your break;
statements).
In working with a similar problem I created the following function after combining a lot of resources I ran into on the web, and adding my own cookie handling. Hopefully this is useful to someone else.
function get_web_page( $url, $cookiesIn = '' ){
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, //return headers in addition to content
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLINFO_HEADER_OUT => true,
CURLOPT_SSL_VERIFYPEER => true, // Validate SSL Certificates
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_COOKIE => $cookiesIn
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$rough_content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header_content = substr($rough_content, 0, $header['header_size']);
$body_content = trim(str_replace($header_content, '', $rough_content));
$pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m";
preg_match_all($pattern, $header_content, $matches);
$cookiesOut = implode("; ", $matches['cookie']);
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['headers'] = $header_content;
$header['content'] = $body_content;
$header['cookies'] = $cookiesOut;
return $header;
}
In C++0x/11 we get std::begin
and std::end
which are overloaded for arrays:
#include <algorithm>
int main(){
int v[2000];
std::sort(std::begin(v), std::end(v));
}
If you don't have access to C++0x, it isn't hard to write them yourself:
// for container with nested typedefs, non-const version
template<class Cont>
typename Cont::iterator begin(Cont& c){
return c.begin();
}
template<class Cont>
typename Cont::iterator end(Cont& c){
return c.end();
}
// const version
template<class Cont>
typename Cont::const_iterator begin(Cont const& c){
return c.begin();
}
template<class Cont>
typename Cont::const_iterator end(Cont const& c){
return c.end();
}
// overloads for C style arrays
template<class T, std::size_t N>
T* begin(T (&arr)[N]){
return &arr[0];
}
template<class T, std::size_t N>
T* end(T (&arr)[N]){
return arr + N;
}
Found this absolute hack that actually works quite well:
https://codepen.io/nikitahl/pen/vyZbwR
Not CSS only though.
The basic gist is to have a container on the dropdown, .select-container
in this case. That container has it's ::before
set up to display content
based on its data-content
attribute/dataset, along with all of the overflow:hidden; text-overflow: ellipsis;
and sizing necessary to make the ellipsis work.
When the select changes, javascript assigns the value (or you could retrieve the text of the option out of the select.options
list) to the dataset.content of the container, and voila!
Copying content of the codepen here:
var selectContainer = document.querySelector(".select-container");_x000D_
var select = selectContainer.querySelector(".select");_x000D_
select.value = "lingua latina non penis canina";_x000D_
_x000D_
selectContainer.dataset.content = select.value;_x000D_
_x000D_
function handleChange(e) {_x000D_
selectContainer.dataset.content = e.currentTarget.value;_x000D_
console.log(select.value);_x000D_
}_x000D_
_x000D_
select.addEventListener("change", handleChange);
_x000D_
span {_x000D_
margin: 0 10px 0 0;_x000D_
}_x000D_
_x000D_
.select-container {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
.select-container::before {_x000D_
content: attr(data-content);_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 10px;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
padding: 7px;_x000D_
font: 11px Arial, sans-serif;_x000D_
white-space: nowrap;_x000D_
text-overflow: ellipsis;_x000D_
overflow: hidden;_x000D_
text-transform: capitalize;_x000D_
pointer-events: none;_x000D_
}_x000D_
_x000D_
.select {_x000D_
width: 80px;_x000D_
padding: 5px;_x000D_
appearance: none;_x000D_
background: transparent url("https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-arrow-down-b-128.png") no-repeat calc(~"100% - 5px") 7px;_x000D_
background-size: 10px 10px;_x000D_
color: transparent;_x000D_
}_x000D_
_x000D_
.regular {_x000D_
display: inline-block;_x000D_
margin: 10px 0 0;_x000D_
.select {_x000D_
color: #000;_x000D_
}_x000D_
}
_x000D_
<span>Hack:</span><div class="select-container" data-content="">_x000D_
<select class="select" id="words">_x000D_
<option value="lingua latina non penis canina">Lingua latina non penis canina</option>_x000D_
<option value="lorem">Lorem</option>_x000D_
<option value="ipsum">Ipsum</option>_x000D_
<option value="dolor">Dolor</option>_x000D_
<option value="sit">Sit</option>_x000D_
<option value="amet">Amet</option>_x000D_
<option value="lingua">Lingua</option>_x000D_
<option value="latina">Latina</option>_x000D_
<option value="non">Non</option>_x000D_
<option value="penis">Penis</option>_x000D_
<option value="canina">Canina</option>_x000D_
</select>_x000D_
</div>_x000D_
<br />_x000D_
_x000D_
<span>Regular:</span>_x000D_
<div class="regular">_x000D_
<select style="width: 80px;">_x000D_
<option value="lingua latina non penis canina">Lingua latina non penis canina</option>_x000D_
<option value="lorem">Lorem</option>_x000D_
<option value="ipsum">Ipsum</option>_x000D_
<option value="dolor">Dolor</option>_x000D_
<option value="sit">Sit</option>_x000D_
<option value="amet">Amet</option>_x000D_
<option value="lingua">Lingua</option>_x000D_
<option value="latina">Latina</option>_x000D_
<option value="non">Non</option>_x000D_
<option value="penis">Penis</option>_x000D_
<option value="canina">Canina</option>_x000D_
</select>_x000D_
</div>
_x000D_
I would grab date.js or else you will need to roll your own formatting function.
You can use \centering
with your parbox to do this.
(Sorry for the Google cached link; the original one I had doesn't work anymore.)
You can use native win command:
WMIC /node:ComputerName process call create “cmd.exe /c start.exe”
The WMIC is part of wbem win folder: C:\Windows\System32\wbem
import java.util.Scanner;
public class StringReverse {
public static void main(String[] args) {
//Read user Data From Console
Scanner sc = new Scanner(System.in);
System.out.println("Enter Your String:");
//Take an String so that it can Store the string data
String s1 = sc.nextLine();
//split the string and keep in an array
String[] s2 = s1.split(" ");
String s3 = " ";
//reverse the string and placed in an String s3
for (int i = 0; i < s2.length; i++) {
for (int j= s2[i].length()-1;j>=0;j--) {
s3 += s2[i].charAt(j);
}//for
s3 += " ";
}//for
System.out.println("After Reverse: "+s3);
}//main
}//StringReverse
The helpers are there mainly to help you display labels, form inputs, etc for the strongly typed properties of your model. By using the helpers and Visual Studio Intellisense, you can greatly reduce the number of typos that you could make when generating a web page.
With that said, you can continue to create your elements manually for both properties of your view model or items that you want to display that are not part of your view model.
Changing the name of model name starting with Uppercase works. Example : Login_model.php instead of login_model.php
An extension of some other answers that covers hexadecimal representation:
public int CharToInt(char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
else if (c >= 'a' && c <= 'f')
{
return 10 + c - 'a';
}
else if (c >= 'A' && c <= 'F')
{
return 10 + c - 'A';
}
return -1;
}
In an AngularJS directive the scope allows you to access the data in the attributes of the element to which the directive is applied.
This is illustrated best with an example:
<div my-customer name="Customer XYZ"></div>
and the directive definition:
angular.module('myModule', [])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
customerName: '@name'
},
controllerAs: 'vm',
bindToController: true,
controller: ['$http', function($http) {
var vm = this;
vm.doStuff = function(pane) {
console.log(vm.customerName);
};
}],
link: function(scope, element, attrs) {
console.log(scope.customerName);
}
};
});
When the scope
property is used the directive is in the so called "isolated scope" mode, meaning it can not directly access the scope of the parent controller.
In very simple terms, the meaning of the binding symbols is:
someObject: '='
(two-way data binding)
someString: '@'
(passed directly or through interpolation with double curly braces notation {{}}
)
someExpression: '&'
(e.g. hideDialog()
)
This information is present in the AngularJS directive documentation page, although somewhat spread throughout the page.
The symbol >
is not part of the syntax.
However, <
does exist as part of the AngularJS component bindings and means one way binding.
This is because your Page2
class doesn't have a companion object which is similar to static
in Java so to use your class. To pass your class as an argument to Intent
, you will have to do something like this
val changePage = Intent(this, Page2::class.java)
select C.ComputerName, S.Version, A.Name from Computer C inner join Software_Computer SC on C.Id = SC.ComputerId Inner join Software S on SC.SoftwareID = S.Id Inner join Application A on S.ApplicationId = A.Id ;
From Oracle Wiki, error 02287 is
An ORA-02287 occurs when you use a sequence where it is not allowed.
Of the places where sequences can't be used, you seem to be trying:
In a sub-query
So it seems you can't do multiples in the same statement.
The solution they offer is:
If you want the sequence value to be inserted into the column for every row created, then create a before insert trigger and fetch the sequence value in the trigger and assign it to the column
TypeScript, React, index.html
//conf.js:
window.bar = "bar";
//index.html
<script type="module" src="./conf.js"></script>
//tsconfig.json
"include": ["typings-custom/**/*.ts"]
//typings-custom/typings.d.ts
declare var bar:string;
//App.tsx
console.log('bar', window.bar);
or
console.log('bar', bar);
When you type x = 0
that is creating a new int
variable (name) and assigning a zero to it.
When you type x[age1]
that is trying to access the age1
'th entry, as if x
were an array.
This because every runtime.exec(..)
returns a Process
class that should be used after the execution instead that invoking other commands by the Runtime
class
If you look at Process doc you will see that you can use
getInputStream()
getOutputStream()
on which you should work by sending the successive commands and retrieving the output..
When using Monkey Script I noticed that DispatchPress(KEYCODE_BACK) is doing nothing which really suck. In many cases this is due to the fact that the Activity doesn't consume the Key event. The solution to this problem is to use a mix of monkey script and adb shell input command in a sequence.
1 Using monkey script gave some great timing
control. Wait a certain amount of second for the activity and is a
blocking adb call.
2 Finally sending adb shell input keyevent 4 will end the running APK.
EG
adb shell monkey -p com.my.application -v -v -v -f /sdcard/monkey_script.txt 1
adb shell input keyevent 4
The for each
syntax is supported as an extension to native c++ in Visual Studio.
The example provided in msdn
#include <vector>
#include <iostream>
using namespace std;
int main()
{
int total = 0;
vector<int> v(6);
v[0] = 10; v[1] = 20; v[2] = 30;
v[3] = 40; v[4] = 50; v[5] = 60;
for each(int i in v) {
total += i;
}
cout << total << endl;
}
(works in VS2013) is not portable/cross platform but gives you an idea of how to use for each
.
The standard alternatives (provided in the rest of the answers) apply everywhere. And it would be best to use those.
I had this very same issue.
However I was using bootbox.js, so it could have been something to do with that.
Either way, I realised that the issue was being caused by having an element with the same class as it's parent. When one of these elements is used to bind a click function to display the modal, then the problem occurs.
i.e. this is what causes the problem:
<div class="myElement">
<div class="myElement">
Click here to show modal
</div>
</div>
change it so that the element being clicked on doesn't have the same class as it's parent, any of it's children, or any other ancestors. It's probably good practice to do this in general when binding click functions.
<!DOCTYPE html>
<html>
<title>Welcome</title>
<style type="text/css">
.head1 {
width:300px;
border-right:1px solid #333;
float:left;
height:500px;
}
.head2 {
float:left;
padding-left:100PX;
padding-top:10PX;
}
</style>
<body>
<h1 class="head1">Ramya</h1>
<h2 class="head2">Reddy</h2>
</body>
</html>
Django provides it. You can use either:
{{ forloop.counter }}
index starts at 1.{{ forloop.counter0 }}
index starts at 0.In template, you can do:
{% for item in item_list %}
{{ forloop.counter }} # starting index 1
{{ forloop.counter0 }} # starting index 0
# do your stuff
{% endfor %}
More info at: for | Built-in template tags and filters | Django documentation
I don't believe there is a direct supported way. However, if you are desparate, then under navigation options, select to show system objects. Then in your table list, system tables will appear. Two tables are of interest here: MSysIMEXspecs and MSysIMEXColumns. You'll be able edit import and export information. Good luck!
From MSDN:
C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.
The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
In other words, the using
statement tells .NET to release the object specified in the using
block once it is no longer needed.
Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.
Note, also, that your usage of .filter()
was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each()
loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:
$(".buttonClick").click(function () {
$("input[type=text]").each(function () {
var validated = true;
if(this.value.length < 8)
validated = false;
if(!/\d/.test(this.value))
validated = false;
if(!/[a-z]/.test(this.value))
validated = false;
if(!/[A-Z]/.test(this.value))
validated = false;
if(/[^0-9a-zA-Z]/.test(this.value))
validated = false;
$('div').text(validated ? "pass" : "fail");
// use DOM traversal to select the correct div for this input above
});
});
I got the same error when xampp was installed on windows 10.
www.example.com:443:0 server certificate does NOT include an ID which matches the server name
So I opened httpd-ssl.conf
file in xampp folder and changed the following line
ServerName www.example.com:443
To
ServerName localhost
And the problem was fixed.
/etc/systemd/system/docker.service.d/docker.conf
. Inside the file docker.conf
, paste below content:[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock
Note that if there is no directory like
docker.service.d
or a file nameddocker.conf
then you should create it.
Restart Docker. After saving this file, reload the configuration by systemctl daemon-reload
and restart Docker by systemctl restart docker.service
.
Check your Docker daemon. After restarting docker service, you can see the port in the output of systemctl status docker.service
like /usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock
.
Hope this may help
Thank you!
Correct me if I am wrong. By doing
[button setSelected:YES];
you are clearly changing the state of the buttons as selected. So naturally by the code you have provided the image will that for the selected state in your case checked.png
foreach($arr as $key=>$value){
echo($key); // key
}
The best solution I have found that Works:
Connect your device thru USB
And type these commands:
rvictl -s UDID - (id of device 20 chars, you can locate 4t in iTunes or organiser in Xcode)
sudo launchctl list com.apple.rpmuxd
sudo tcpdump -n -t -i rvi0 -q tcp
OR just sudo tcpdump -i rvi0 -n
If rvictl is not working install Xcode
For more info: Remote Virtual Interface
http://useyourloaf.com/blog/2012/02/07/remote-packet-capture-for-ios-devices.html
You're best bet as far as I know is to use
window.addEventListener('load', function() {
console.log('All assets loaded')
});
The #1 answer of using the DOMContentLoaded
event is a step backwards since the DOM will load before all assets load.
Other answers recommend setTimeout
which I would strongly oppose since it is completely subjective to the client's device performance and network connection speed. If someone is on a slow network and/or has a slow cpu, a page could take several to dozens of seconds to load, thus you could not predict how much time setTimeout
will need.
As for readystatechange
, it fires whenever readyState
changes which according to MDN will still be before the load
event.
Complete
The state indicates that the load event is about to fire.
You wouldn't really want to do this given the existing Instr/InstrRev functions but there are times when it is handy to use EVALUATE to return the result of Excel worksheet functions within VBA
Option Explicit
Public Sub test()
Debug.Print ContainsSubString("bc", "abc,d")
End Sub
Public Function ContainsSubString(ByVal substring As String, ByVal testString As String) As Boolean
'substring = string to test for; testString = string to search
ContainsSubString = Evaluate("=ISNUMBER(FIND(" & Chr$(34) & substring & Chr$(34) & ", " & Chr$(34) & testString & Chr$(34) & "))")
End Function
You'll want to check HTML5 Differences from HTML4: W3C Working Group Note 9 December 2014 for the complete differences. There are many new elements and element attributes. Some elements were removed and others have different semantic value than before.
There are also APIs defined, such as the use of canvas, to help build the next generation of web apps and make sure implementations are standardized.
var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
zoom: 10,_x000D_
center: new google.maps.LatLng(13.103, 80.274),_x000D_
mapTypeId: google.maps.MapTypeId.ROADMAP_x000D_
});_x000D_
_x000D_
var myMarker = new google.maps.Marker({_x000D_
position: new google.maps.LatLng(18.103, 80.274),_x000D_
draggable: true_x000D_
});_x000D_
_x000D_
google.maps.event.addListener(myMarker, 'dragend', function(evt) {_x000D_
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';_x000D_
});_x000D_
google.maps.event.addListener(myMarker, 'dragstart', function(evt) {_x000D_
document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';_x000D_
});_x000D_
map.setCenter(myMarker.position);_x000D_
myMarker.setMap(map);_x000D_
_x000D_
function getLocation() {_x000D_
if (navigator.geolocation) {_x000D_
navigator.geolocation.getCurrentPosition(showPosition);_x000D_
} else {_x000D_
x.innerHTML = "Geolocation is not supported by this browser.";_x000D_
}_x000D_
}_x000D_
_x000D_
function showPosition(position) {_x000D_
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + position.coords.latitude + ' Current Lng: ' + position.coords.longitude + '</p>';_x000D_
var myMarker = new google.maps.Marker({_x000D_
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),_x000D_
draggable: true_x000D_
});_x000D_
google.maps.event.addListener(myMarker, 'dragend', function(evt) {_x000D_
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';_x000D_
});_x000D_
google.maps.event.addListener(myMarker, 'dragstart', function(evt) {_x000D_
document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';_x000D_
});_x000D_
map.setCenter(myMarker.position);_x000D_
myMarker.setMap(map);_x000D_
}_x000D_
getLocation();
_x000D_
#map_canvas {_x000D_
width: 980px;_x000D_
height: 500px;_x000D_
}_x000D_
_x000D_
#current {_x000D_
padding-top: 25px;_x000D_
}
_x000D_
<script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<section>_x000D_
<div id='map_canvas'></div>_x000D_
<div id="current">_x000D_
<p>Marker dropped: Current Lat:18.103 Current Lng:80.274</p>_x000D_
</div>_x000D_
</section>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.
instancelist = [ MyClass() for i in range(29)]
and then access the instances through the index of the list.
instancelist[5].attr1 = 'whamma'
You can do it using the datasource-proxy, as I described in this post.
Assuming your application expects a dataSource
bean (e.g. via @Resource
), this is how you can configure datasource-proxy
:
<bean id="actualDataSource" class="bitronix.tm.resource.jdbc.PoolingDataSource" init-method="init"
destroy-method="close">
<property name="className" value="bitronix.tm.resource.jdbc.lrc.LrcXADataSource"/>
<property name="uniqueName" value="actualDataSource"/>
<property name="minPoolSize" value="0"/>
<property name="maxPoolSize" value="5"/>
<property name="allowLocalTransactions" value="false" />
<property name="driverProperties">
<props>
<prop key="user">${jdbc.username}</prop>
<prop key="password">${jdbc.password}</prop>
<prop key="url">${jdbc.url}</prop>
<prop key="driverClassName">${jdbc.driverClassName}</prop>
</props>
</property>
</bean>
<bean id="proxyDataSource" class="net.ttddyy.dsproxy.support.ProxyDataSource">
<property name="dataSource" ref="testDataSource"/>
<property name="listener">
<bean class="net.ttddyy.dsproxy.listener.ChainListener">
<property name="listeners">
<list>
<bean class="net.ttddyy.dsproxy.listener.CommonsQueryLoggingListener">
<property name="logLevel" value="INFO"/>
</bean>
<bean class="net.ttddyy.dsproxy.listener.DataSourceQueryCountListener"/>
</list>
</property>
</bean>
</property>
</bean>
<alias name="proxyDataSource" alias="dataSource"/>
Now the Hibernate output vs datasource-proxy:
INFO [main]: n.t.d.l.CommonsQueryLoggingListener - Name:, Time:1, Num:1, Query:{[select company0_.id as id1_6_, company0_.name as name2_6_ from Company company0_][]}
INFO [main]: n.t.d.l.CommonsQueryLoggingListener - Name:, Time:0, Num:1, Query:{[insert into WarehouseProductInfo (id, quantity) values (default, ?)][19]}
INFO [main]: n.t.d.l.CommonsQueryLoggingListener - Name:, Time:0, Num:1, Query:{[insert into Product (id, code, company_id, importer_id, name, version) values (default, ?, ?, ?, ?, ?)][phoneCode,1,-5,Phone,0]}
The datasource-proxy
queries contain parameter values and you can even add custom JDBC statement interceptors so that you can catch N+1 query issues right from your integration tests.
I would do it this way:
(function($) {
jQuery.fn.doSomething = function() {
return this.each(function() {
var $this = $(this);
$this.click(function(event) {
event.preventDefault();
// Your function goes here
});
});
};
})(jQuery);
Then on document ready you can do stuff like this:
$(document).ready(function() {
$('#div1').doSomething();
$('#div2').doSomething();
});
public class MainClass {
public static void main(String args[]) {
Thread t = Thread.currentThread();
t.setName("My Thread");
t.setPriority(1);
System.out.println("current thread: " + t);
int active = Thread.activeCount();
System.out.println("currently active threads: " + active);
Thread all[] = new Thread[active];
Thread.enumerate(all);
for (int i = 0; i < active; i++) {
System.out.println(i + ": " + all[i]);
}
}
}
You can use this Android Library: https://github.com/danielemaddaluno/Android-Update-Checker. It aims to provide a reusable instrument to check asynchronously if exists any newer released update of your app on the Store. It is based on the use of Jsoup (http://jsoup.org/) to test if a new update really exists parsing the app page on the Google Play Store:
private boolean web_update(){
try {
String curVersion = applicationContext.getPackageManager().getPackageInfo(package_name, 0).versionName;
String newVersion = curVersion;
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + package_name + "&hl=en")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select("div[itemprop=softwareVersion]")
.first()
.ownText();
return (value(curVersion) < value(newVersion)) ? true : false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
And as "value" function the following (works if values are beetween 0-99):
private long value(String string) {
string = string.trim();
if( string.contains( "." )){
final int index = string.lastIndexOf( "." );
return value( string.substring( 0, index ))* 100 + value( string.substring( index + 1 ));
}
else {
return Long.valueOf( string );
}
}
If you want only to verify a mismatch beetween versions, you can change:
value(curVersion) < value(newVersion)
with value(curVersion) != value(newVersion)
GNU parallel
and xargs
These two tools that can make scripts simpler, and also control the maximum number of threads (thread pool). E.g.:
seq 10 | xargs -P4 -I'{}' echo '{}'
or:
seq 10 | parallel -j4 echo '{}'
See also: how to write a process-pool bash shell
This uses a regular expression, and it works as well:
var date = new Date(parseInt(/^\/Date\((.*?)\)\/$/.exec(jsonDate)[1], 10));
To get Token Device you can do by some steps:
1) Enable APNS (Apple Push Notification Service) for both Developer Certification and Distribute Certification, then redownload those two file.
2) Redownload both Developer Provisioning and Distribute Provisioning file.
3) In Xcode interface: setting provisioning for PROJECT and TARGETS with two file provisioning have download.
4) Finally, you need to add the code below in AppDelegate file to get Token Device (note: run app in real device).
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
NSLog(@"Registering for push notifications...");
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
return YES;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
NSLog(@"%@", str);
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSString *str = [NSString stringWithFormat: @"Error: %@", err];
NSLog(@"%@",str);
}
You can save image , save the file in your current directory application and move the file to any directory .
Bitmap btm = new Bitmap(image.width,image.height);
Image img = btm;
img.Save(@"img_" + x + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
FileInfo img__ = new FileInfo(@"img_" + x + ".jpg");
img__.MoveTo("myVideo\\img_" + x + ".jpg");
You are thinking in the function ABS
, that gives you the absolute value of numeric data.
SELECT ABS(a) AS AbsoluteA, ABS(b) AS AbsoluteB
FROM YourTable
Yes, it is. You can write :
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
or you can get values from another join of the select ...
In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:
<select id="continents">
<option value = 0>All</option>
<option value = 1>Asia</option>
<option value = 2>Europe</option>
<option value = 3>Africa</option>
</select>
<select id="selectcountries"></select>
Uses (in the jsFiddle)
MAIN.createRelatedSelector
( document.querySelector('#continents') // from select element
,document.querySelector('#selectcountries') // to select element
,{ // values object
Asia: ['China','Japan','North Korea',
'South Korea','India','Malaysia',
'Uzbekistan'],
Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
}
,function(a,b){return a>b ? 1 : a<b ? -1 : 0;} // sort method
);
[Edit 2021] or use data-attributes, something like:
document.addEventListener("change", checkSelect);
function checkSelect(evt) {
const origin = evt.target;
if (origin.dataset.dependentSelector) {
const selectedOptFrom = origin.querySelector("option:checked")
.dataset.dependentOpt || "n/a";
const addRemove = optData => (optData || "") === selectedOptFrom
? "add" : "remove";
document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
.forEach( opt =>
opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
}
}
_x000D_
[data-from-dependent] {
display: none;
}
[data-from-dependent].display {
display: initial;
}
_x000D_
<select id="source" name="source" data-dependent-selector="#status">
<option>MANUAL</option>
<option data-dependent-opt="ONLINE">ONLINE</option>
<option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
<option data-from-dependent="ONLINE">SHIPPED</option>
<option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
<option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
_x000D_
Apart from steps mentioned in posted answers by @daniele3004 above, I had to open SSMS as Administrator otherwise it was showing Primary file is read only error.
Go to Start Menu , navigate to SSMS link , right click on the SSMS link , select Run As Administrator. Then perform the above steps.
You can use MySQL variables to do it. Something like this should work (though, it consists of two queries).
SELECT 0 INTO @x;
SELECT itemID,
COUNT(*) AS ordercount,
(@x:=@x+1) AS rownumber
FROM orders
GROUP BY itemID
ORDER BY ordercount DESC;
If you want to change the contents of each and every cell in a datatable then we need to Create another Datatable and bind it as follows using "Import Row". If we don't create another table it will throw an Exception saying "Collection was Modified".
Consider the following code.
//New Datatable created which will have updated cells
DataTable dtUpdated = new DataTable();
//This gives similar schema to the new datatable
dtUpdated = dtReports.Clone();
foreach (DataRow row in dtReports.Rows)
{
for (int i = 0; i < dtReports.Columns.Count; i++)
{
string oldVal = row[i].ToString();
string newVal = "{"+oldVal;
row[i] = newVal;
}
dtUpdated.ImportRow(row);
}
This will have all the cells preceding with Paranthesis({)
TortoiseGit has matured and I recommend it especially if you have used TortoiseSVN.
You could also use the stringr
package:
library(stringr)
str_length("foo")
[1] 3
This will depend on the device you're using. If you're using a pdf device, you can do this:
pdf( "mygraph.pdf", width = 11, height = 8 )
plot( x, y )
You can then divide up the space in the pdf using the mfrow parameter like this:
par( mfrow = c(2,2) )
That makes a pdf with four panels available for plotting. Unfortunately, some of the devices take different units than others. For example, I think that X11 uses pixels, while I'm certain that pdf uses inches. If you'd just like to create several devices and plot different things to them, you can use dev.new(), dev.list(), and dev.next().
Other devices that might be useful include:
There's a list of all of the devices here.
Use properties file. Here is a good start: http://www.mkyong.com/java/java-properties-file-examples/
Here's a compact Objective-C version as a Category on NSData. It takes some thinking about...
@implementation NSData (DataUtils)
static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- (NSString *)newStringInBase64FromData
{
NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];
unsigned char * working = (unsigned char *)[self bytes];
int srcLen = [self length];
// tackle the source in 3's as conveniently 4 Base64 nibbles fit into 3 bytes
for (int i=0; i<srcLen; i += 3)
{
// for each output nibble
for (int nib=0; nib<4; nib++)
{
// nibble:nib from char:byt
int byt = (nib == 0)?0:nib-1;
int ix = (nib+1)*2;
if (i+byt >= srcLen) break;
// extract the top bits of the nibble, if valid
unsigned char curr = ((working[i+byt] << (8-ix)) & 0x3F);
// extract the bottom bits of the nibble, if valid
if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) & 0x3F);
[dest appendFormat:@"%c", base64[curr]];
}
}
return dest;
}
@end
Padding can be added if required by making the scope of 'byt' wider and appending 'dest' with (2-byt) "=" characters before returning.
A Category can then be added to NSString, thus:
@implementation NSString (StringUtils)
- (NSString *)newStringInBase64FromString
{
NSData *theData = [NSData dataWithBytes:[self UTF8String] length:[self length]];
return [theData newStringInBase64FromData];
}
@end
I believe best practice these days is H/5 * * * *
, which means every 5 minutes with a hashing factor to avoid all jobs starting at EXACTLY the same time.
Requires Newtonsoft Json.Net
A little late, but I came up with this. It gives you just the keys and then you can use those on the dynamic:
public List<string> GetPropertyKeysForDynamic(dynamic dynamicToGetPropertiesFor)
{
JObject attributesAsJObject = dynamicToGetPropertiesFor;
Dictionary<string, object> values = attributesAsJObject.ToObject<Dictionary<string, object>>();
List<string> toReturn = new List<string>();
foreach (string key in values.Keys)
{
toReturn.Add(key);
}
return toReturn;
}
Then you simply foreach like this:
foreach(string propertyName in GetPropertyKeysForDynamic(dynamicToGetPropertiesFor))
{
dynamic/object/string propertyValue = dynamicToGetPropertiesFor[propertyName];
// And
dynamicToGetPropertiesFor[propertyName] = "Your Value"; // Or an object value
}
Choosing to get the value as a string or some other object, or do another dynamic and use the lookup again.
This was answered by a few others but I found a solution that worked really well for me.
System.out.println(CvType.typeToString(yourMat.type()));
Make a new batch file (example: openclass.bat) and write this line in the file:
java %~n1
Then place the batch file in, let's say, the system32 folder, go to your Java class file, right click, Properties, Open with..., then find your batch file, select it and that's that...
It works for me.
PS: I can't find a way to close the cmd window when I close the Java class. For now...
Localization support in legacy browsers is poor. Originally, this was due to phrases in the ECMAScript
language spec that look like this:
Number.prototype.toLocaleString()
Produces a string value that represents the value of the Number formatted according to the conventions of the host environment’s current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.
Every localization method defined in the spec is defined as "implementation-dependent", which results in a lot of inconsistencies. In this instance, Chrome Opera and Safari would return the same thing as .toString()
. Firefox and IE will return locale formatted strings, and IE even includes a thousand separator (perfect for currency strings). Chrome was recently updated to return a thousands-separated string, though with no fixed decimal.
For modern environments, the ECMAScript Internationalization API spec, a new standard that complements the ECMAScript Language spec, provides much better support for string comparison, number formatting, and the date and time formatting; it also fixes the corresponding functions in the Language Spec. An introduction can be found here. Implementations are available in:
There is also a compatibility implementation, Intl.js, which will provide the API in environments where it doesn't already exist.
Determining the user's preferred language remains a problem since there's no specification for obtaining the current language. Each browser implements a method to obtain a language string, but this could be based on the user's operating system language or just the language of the browser:
// navigator.userLanguage for IE, navigator.language for others
var lang = navigator.language || navigator.userLanguage;
A good workaround for this is to dump the Accept-Language header from the server to the client. If formatted as a JavaScript, it can be passed to the Internationalization API constructors, which will automatically pick the best (or first-supported) locale.
In short, you have to put in a lot of the work yourself, or use a framework/library, because you cannot rely on the browser to do it for you.
Various libraries and plugins for localization:
Feel free to add/edit.
select project navigator > select Target > Identity > Display Name > Name
See the UIScreen Reference: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIScreen_Class/Reference/UIScreen.html
if([[UIScreen mainScreen] respondsToSelector:NSSelectorFromString(@"scale")])
{
if ([[UIScreen mainScreen] scale] < 1.1)
NSLog(@"Standard Resolution Device");
if ([[UIScreen mainScreen] scale] > 1.9)
NSLog(@"High Resolution Device");
}
Problem Cause
In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.
Solution
~/.matplotlib
. ~/.matplotlib/matplotlibrc
there and add the following code: backend: TkAgg
From this link you can try different diagrams.
Devices with android <=4.0.4 need to add the plugin https://www.npmjs.com/package/cordova-plugin-crosswalk-webview-pgb-adapt
By default session object is available on jsp page(implicit object). It will not available in normal POJO java class. You can get the reference of HttpSession object on Servelt by using HttpServletRequest
HttpSession s=request.getSession()
s.setAttribute("name","value");
You can get session on an ActionSupport based Action POJO class as follows
ActionContext ctx= ActionContext.getContext();
Map m=ctx.getSession();
m.put("name", value);
look at: http://ohmjavaclasses.blogspot.com/2011/12/access-session-in-action-class-struts2.html
Yes, it is coming soon. See proposal here and implementation status here.
It looks like this:
x ?? y
const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: '',
showSplashScreen: false
}
};
const undefinedValue = response.settings?.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings?.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings?.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings?.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings?.showSplashScreen ?? true; // result: false
if you have an array and array element is stdClass
item then this is the solution:
foreach($post_id as $key=>$item){
$post_id[$key] = (array)$item;
}
now the stdClass
has been replaced with an array inside the array as new array element
Let's say you don't use es6; You can use IFFY function:
var funcs = [];
for (var i = 0; i < 13; i++) {
funcs[i] = (function(x) {
console.log("My value: " + i)})(i);}
But it will be different.
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
If both database on same server. You can check similar tables by using following query :
select
fdb.name, sdb.name
from
FIRSTDBNAME.sys.tables fdb
join SECONDDBNAME.sys.tables sdb
on fdb.name = sdb.name -- compare same name tables
order by
1
By listing out similar table you can compare columns schema using sys.columns
view.
Hope this helps you.
<?php
if (isset($_POST['submit']) and ! empty($_POST['submit'])) {
if (isset($_POST['radio'])) {
$radio_input = $_POST['radio'];
echo $radio_input;
}
} else {
}
?>
<form action="radio.php" method="post">
<input type="radio" name="radio" value="v1"/>
<input type="radio" name="radio" value="v2"/>
<input type="radio" name="radio" value="v3"/>
<input type="radio" name="radio" value="v4"/>
<input type="radio" name="radio" value="v5"/>
<input type= "submit" name="submit"value="submit"/>
</form>
You can also query the INFORMATION_SCHEMA.SCHEMATA view:
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA
I believe querying the INFORMATION_SCHEMA views is recommended as they protect you from changes to the underlying sys tables. From the SQL Server 2008 R2 Help:
Information schema views provide an internal, system table-independent view of the SQL Server metadata. Information schema views enable applications to work correctly although significant changes have been made to the underlying system tables. The information schema views included in SQL Server comply with the ISO standard definition for the INFORMATION_SCHEMA.
Ironically, this is immediately preceded by this note:
Some changes have been made to the information schema views that break backward compatibility. These changes are described in the topics for the specific views.
In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*')
. See here:
SQL Function
Description
REGEXP_LIKE
This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.
...
REGEXP_REPLACE
This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.
...
REGEXP_INSTR
This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.
...
REGEXP_SUBSTR
This function returns the actual substring matching the regular expression pattern you specify.
(Of course, REGEXP_LIKE only matches queries containing the search string, so if you want a complete match, you'll have to use '^$'
for a beginning (^
) and end ($
) match, e.g.: '^regex.*$'
.)
Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.
Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.
You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.
To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.
A typical C++ code will be:
hVaultLib = LoadLibrary(L"vaultcli.dll");
if (hVaultLib != NULL)
{
pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");
bStatus = (pVaultEnumerateVaults != NULL)
&& (pVaultFree != NULL)
&& (pVaultGetItemW7 != NULL)
&& (pVaultGetItemW8 != NULL)
&& (pVaultOpenVault != NULL)
&& (pVaultCloseVault != NULL)
&& (pVaultEnumerateItems != NULL);
}
Then you enumerate all stored credentials by calling
VaultEnumerateVaults
Then you go over the results.
@Chris Noe
Note that the space in front of the & becomes part of the previous command. That has bitten me with SET, which happily puts trailing blanks into the value.
To get around the trailing-space being added to an environment variable, wrap the set command in parens.
E.g. FOR /F %%I IN ('DIR "*.*" /B /O:D') DO (SET NewestFile=%%I)
I've used HttpClient in .NET 4.0 applications on numerous occasions. If you are familiar with NuGet, you can do an Install-Package Microsoft.Net.Http to add it to your project. See the link below for further details.
It's a GNU extension. In a nutshell it's a convenient way to declare an object having the same type as another. For example:
int x; /* Plain old int variable. */
typeof(x) y; /* Same type as x. Plain old int variable. */
It works entirely at compile-time and it's primarily used in macros. One famous example of macro relying on typeof
is container_of
.
Joins in update
statements are non-standard and not supported by all vendors. What you're trying to do can be accomplished with a sub-select:
update
file1
set
firstfield = (select 'stuff' concat something from file2 where substr(file1.field1, 10, 20) = substr(file2.xxx,1,10) )
where
file1.foo like 'BLAH%'
An alternative on Linux to using either /proc/self/exe
or argv[0]
is using the information passed by the ELF interpreter, made available by glibc as such:
#include <stdio.h>
#include <sys/auxv.h>
int main(int argc, char **argv)
{
printf("%s\n", (char *)getauxval(AT_EXECFN));
return(0);
}
Note that getauxval
is a glibc extension, and to be robust you should check so that it doesn't return NULL
(indicating that the ELF interpreter hasn't provided the AT_EXECFN
parameter), but I don't think this is ever actually a problem on Linux.
You have some options, depending on your needs. If you want to handle errors on a per-request basis, add a catch
to your request. If you want to add a global solution, use HttpInterceptor
.
Open here the working demo plunker for the solutions below.
In the simplest case, you'll just need to add a .catch()
or a .subscribe()
, like:
import 'rxjs/add/operator/catch'; // don't forget this, or you'll get a runtime error
this.httpClient
.get("data-url")
.catch((err: HttpErrorResponse) => {
// simple logging, but you can do a lot more, see below
console.error('An error occurred:', err.error);
});
// or
this.httpClient
.get("data-url")
.subscribe(
data => console.log('success', data),
error => console.log('oops', error)
);
But there are more details to this, see below.
If you need to handle errors in only one place, you can use catch
and return a default value (or empty response) instead of failing completely. You also don't need the .map
just to cast, you can use a generic function. Source: Angular.io - Getting Error Details.
So, a generic .get()
method, would be like:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/retry'; // don't forget the imports
@Injectable()
export class DataService {
baseUrl = 'http://localhost';
constructor(private httpClient: HttpClient) { }
// notice the <T>, making the method generic
get<T>(url, params): Observable<T> {
return this.httpClient
.get<T>(this.baseUrl + url, {params})
.retry(3) // optionally add the retry
.catch((err: HttpErrorResponse) => {
if (err.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', err.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
}
// ...optionally return a default fallback value so app can continue (pick one)
// which could be a default value
// return Observable.of<any>({my: "default value..."});
// or simply an empty observable
return Observable.empty<T>();
});
}
}
Handling the error will allow you app to continue even when the service at the URL is in bad condition.
This per-request solution is good mostly when you want to return a specific default response to each method. But if you only care about error displaying (or have a global default response), the better solution is to use an interceptor, as described below.
Run the working demo plunker here.
Once again, Angular.io guide shows:
A major feature of
@angular/common/http
is interception, the ability to declare interceptors which sit in between your application and the backend. When your application makes a request, interceptors transform it before sending it to the server, and the interceptors can transform the response on its way back before your application sees it. This is useful for everything from authentication to logging.
Which, of course, can be used to handle errors in a very simple way (demo plunker here):
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse,
HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/retry'; // don't forget the imports
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.catch((err: HttpErrorResponse) => {
if (err.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', err.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
}
// ...optionally return a default fallback value so app can continue (pick one)
// which could be a default value (which has to be a HttpResponse here)
// return Observable.of(new HttpResponse({body: [{name: "Default value..."}]}));
// or simply an empty observable
return Observable.empty<HttpEvent<any>>();
});
}
}
Providing your interceptor: Simply declaring the HttpErrorInterceptor
above doesn't cause your app to use it. You need to wire it up in your app module by providing it as an interceptor, as follows:
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpErrorInterceptor } from './path/http-error.interceptor';
@NgModule({
...
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorInterceptor,
multi: true,
}],
...
})
export class AppModule {}
Note: If you have both an error interceptor and some local error handling, naturally, it is likely that no local error handling will ever be triggered, since the error will always be handled by the interceptor before it reaches the local error handling.
Run the working demo plunker here.
All of this can easily be acheived in the xaml by adding the following code in the grid
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/MyProject;component/Images/bg.png"/>
</Grid.Background>
</Grid>
Left for you to do, is adding a folder to the solution called 'Images' and adding an existing file to your new 'Images' folder, in this case called 'bg.png'
I use text-align-center in a row like this
<div class="row tac">
<h1>Centered content</h1>
</div>
<style>
.tac { text-align: center}
</style>
A bit verbose, but it's the standard way of parsing and formatting dates in Java:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
Date dt = formatter.parse("08:19:12");
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
} catch (ParseException e) {
// This can happen if you are trying to parse an invalid date, e.g., 25:19:12.
// Here, you should log the error and decide what to do next
e.printStackTrace();
}
Below is some code to format columns A and C as text in SpreadsheetGear for .NET which has an API which is similar to Excel - except for the fact that SpreadsheetGear is frequently more strongly typed. It should not be too hard to figure out how to convert this to work with Excel / COM:
IWorkbook workbook = Factory.GetWorkbook();
IRange cells = workbook.Worksheets[0].Cells;
// Format column A as text.
cells["A:A"].NumberFormat = "@";
// Set A2 to text with a leading '0'.
cells["A2"].Value = "01234567890123456789";
// Format column C as text (SpreadsheetGear uses 0 based indexes - Excel uses 1 based indexes).
cells[0, 2].EntireColumn.NumberFormat = "@";
// Set C3 to text with a leading '0'.
cells[2, 2].Value = "01234567890123456789";
workbook.SaveAs(@"c:\tmp\TextFormat.xlsx", FileFormat.OpenXMLWorkbook);
Disclaimer: I own SpreadsheetGear LLC
I don't understand what the meaning of ordering with the same column ASC
and DESC
in the same ORDER BY
, but this how you can do it: naam DESC, naam ASC
like so:
ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC
I had the same problem for days until I noticed (how could I look at it and not read the code :-(..) that config.inc.php
is calling config-db.php
** MySql Server version: 5.7.5-m15
** Apache/2.4.10 (Ubuntu)
** phpMyAdmin 4.2.9.1deb0.1
/etc/phpmyadmin/config-db.php:
$dbuser='yourDBUserName';
$dbpass='';
$basepath='';
$dbname='phpMyAdminDBName';
$dbserver='';
$dbport='';
$dbtype='mysql';
Here you need to define your username, password, dbname and others that are showing empty' use default unless you changed their configuration.
That solved the issue for me.
U hope it helps you.
latest.phpmyadmin.docs
Use:
TextView tv = new TextView(this);
tv.setTextColor(Color.rgb(285,0,0));
JMeter would be one such tool. Can be a bit hard to learn and configure, but it's usually worth it.
Have you looked into rasdial?
Just incase anyone wanted to do this and finds this in the future, you can use rasdial.exe from command prompt to connect to a VPN network
ie
rasdial "VPN NETWORK NAME" "Username" *
it will then prompt for a password, else you can use "username" "password", this is however less secure
http://www.msfn.org/board/topic/113128-connect-to-vpn-from-cmdexe-vista/?p=747265
I suspect because of modules, which remove the need for the #import <Cocoa/Cocoa.h>
.
As to where to put code that you would put in a prefix header, there is no code you should put in a prefix header. Put your imports into the files that need them. Put your definitions into their own files. Put your macros...nowhere. Stop writing macros unless there is no other way (such as when you need __FILE__
). If you do need macros, put them in a header and include it.
The prefix header was necessary for things that are huge and used by nearly everything in the whole system (like Foundation.h
). If you have something that huge and ubiquitous, you should rethink your architecture. Prefix headers make code reuse hard, and introduce subtle build problems if any of the files listed can change. Avoid them until you have a serious build time problem that you can demonstrate is dramatically improved with a prefix header.
In that case you can create one and pass it into clang, but it's incredibly rare that it's a good idea.
EDIT: To your specific question about a HUD you use in all your view controllers, yes, you should absolutely import it into every view controller that actually uses it. This makes the dependencies clear. When you reuse your view controller in a new project (which is common if you build your controllers well), you will immediately know what it requires. This is especially important for categories, which can make code very hard to reuse if they're implicit.
The PCH file isn't there to get rid of listing dependencies. You should still import UIKit.h
or Foundation.h
as needed, as the Xcode templates do. The reason for the PCH is to improve build times when dealing with really massive headers (like in UIKit).
It is possible to use apache commons (commons-lang3) and its DurationFormatUtils class.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
For example:
String formattedDuration = DurationFormatUtils.formatDurationHMS(12313152);
// formattedDuration value is "3:25:13.152"
String otherFormattedDuration = DurationFormatUtils.formatDuration(12313152, DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN);
// otherFormattedDuration value is "P0000Y0M0DT3H25M13.152S"
Hope it can help ...
To make it work, instead of ignoring it, you can install the m2e connector for the maven-dependency-plugin:
https://github.com/ianbrandt/m2e-maven-dependency-plugin
Here is how you would do it in Eclipse:
There are a couple issues here. First, you need to make sure to bind your JSON object back to the model in the controller. This is done by changing
data: JSON.stringify(usersRoles),
to
data: { model: JSON.stringify(usersRoles) },
Secondly, you aren't binding types correctly with your jquery call. If you remove
contentType: "application/json; charset=utf-8",
it will inherently bind back to a string.
All together, use the first ActionResult method and the following jquery ajax call:
jQuery.ajax({
type: "POST",
url: "@Url.Action("AddUser")",
dataType: "json",
data: { model: JSON.stringify(usersRoles) },
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
Another thing you can do is to change the Deployment target to the highest value. This will prevent the Scheme Menu from displaying older versions.
To do this go to: Target->Summary then change the Deployment Target.
As a workaround, you can use a code block to render the code literally. Just surround your text with triple backticks ```. It will look like this:
2018-07-20 Wrote this answer
Can format it without
Also don't need <br /> for new line
Note that using <pre>
and <code>
you get slightly different behaviour:  
and <br />
will be parsed rather than inserted literally.
<pre>:
2018-07-20 Wrote this answer Can format it without Also don't need
for new line
<code>:
2018-07-20 Wrote this answer
Can format it without
Also don't need
for new line
Try this
static DataTable ConvertToDatatable(List<Item> list)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Price");
dt.Columns.Add("URL");
foreach (var item in list)
{
var row = dt.NewRow();
row["Name"] = item.Name;
row["Price"] = Convert.ToString(item.Price);
row["URL"] = item.URL;
dt.Rows.Add(row);
}
return dt;
}
Using this fiddle, you can play around with the width
of each div. I've tried in both Chrome and IE and I notice a difference in width between 33%
and 33.3%
. I also notice a very small difference between 33.3%
and 33.33%
. I don't notice any difference further than this.
The difference between 33.33%
and the theoretical 33.333...%
is a mere 0.00333...%
.
For arguments sake, say my screen width is 1960px
; a fairly high but common resolution. The difference between these two widths is still only 0.065333...px
.
So, further than two decimal places, the difference in precision is negligible.
You can add listener all video events nicluding ended, loadedmetadata, timeupdate
where ended
function gets called when video ends
$("#myVideo").on("ended", function() {_x000D_
//TO DO: Your code goes here..._x000D_
alert("Video Finished");_x000D_
});_x000D_
_x000D_
$("#myVideo").on("loadedmetadata", function() {_x000D_
alert("Video loaded");_x000D_
this.currentTime = 50;//50 seconds_x000D_
//TO DO: Your code goes here..._x000D_
});_x000D_
_x000D_
_x000D_
$("#myVideo").on("timeupdate", function() {_x000D_
var cTime=this.currentTime;_x000D_
if(cTime>0 && cTime % 2 == 0)//Alerts every 2 minutes once_x000D_
alert("Video played "+cTime+" minutes");_x000D_
//TO DO: Your code goes here..._x000D_
var perc=cTime * 100 / this.duration;_x000D_
if(perc % 10 == 0)//Alerts when every 10% watched_x000D_
alert("Video played "+ perc +"%");_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<video id="myVideo" controls="controls">_x000D_
<source src="your_video_file.mp4" type="video/mp4">_x000D_
<source src="your_video_file.mp4" type="video/ogg">_x000D_
Your browser does not support HTML5 video._x000D_
</video>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:
1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)
2: Run your formula
3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank
4: Replace All
Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.
Yes, there is a difference. continue
forces the loop to start at the next iteration while pass
means "there is no code to execute here" and will continue through the remainder or the loop body.
Run these and see the difference:
for element in some_list:
if not element:
pass
print 1 # will print after pass
for element in some_list:
if not element:
continue
print 1 # will not print after continue
This question is very old, but I found myself studying for a Microsoft Certification, and in the study book it was suggested to use:
oldElement.replaceNode(newElement)
I looked it up and it seems to only be supported in IE. Doh..
I thought I'd just add it here as a funny side note ;)
Add items:
arr[0] = "product_1";
arr[1] = "100";
arr[2] = "10";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
Retrieve items:
productName = listView1.SelectedItems[0].SubItems[0].Text;
price = listView1.SelectedItems[0].SubItems[1].Text;
quantity = listView1.SelectedItems[0].SubItems[2].Text;
you dont need to change your JSON format.
replace:
console.log(data.phones.length);
with:
console.log( Object.keys( data.phones ).length ) ;
Refer to RFC 6266 (Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)) http://tools.ietf.org/html/rfc6266
Simply mark all the data-toggles...
jQuery(function () {
jQuery('[data-toggle=tooltip]').tooltip();
});
This code will return list of duplicated values. Hash keys are used as an efficient way of checking which values have already been seen. Based on whether value has been seen, the original array ary
is partitioned into 2 arrays: first containing unique values and second containing duplicates.
ary = ["hello", "world", "stack", "overflow", "hello", "again"]
hash={}
arr.partition { |v| hash.has_key?(v) ? false : hash[v]=0 }.last.uniq
=> ["hello"]
You can further shorten it - albeit at a cost of slightly more complex syntax - to this form:
hash={}
arr.partition { |v| !hash.has_key?(v) && hash[v]=0 }.last.uniq
With a single with block, you can search and replace your text:
with open('file.txt','r+') as f:
filedata = f.read()
filedata = filedata.replace('abc','xyz')
f.truncate(0)
f.write(filedata)
You can drop index duplicates with 'drop_duplicates':
df.loc[df.index.drop_duplicates(keep='first')]
net stop w32time
w32tm /config /syncfromflags:manual /manualpeerlist:"0.it.pool.ntp.org 1.it.pool.ntp.org 2.it.pool.ntp.org 3.it.pool.ntp.org"
net start w32time
w32tm /config /update
w32tm /resync /rediscover
.BAT Sample File: https://gist.github.com/thedom85/dbeb58627adfb3d5c3af
I also recommend this program: http://www.timesynctool.com/
You can use java8 + rxjava.
//import java.util.stream.IntStream;
//import rx.Observable;
IntStream intStream = IntStream.range(1,10000000);
Observable.from(() -> intStream.iterator())
.takeWhile(n -> n < 10)
.forEach(n-> System.out.println(n));
SELECT * FROM
(SELECT ROW_NUMBER() OVER(ORDER BY Id) AS RowNum, * FROM maps006) AS DerivedTable
WHERE RowNum BETWEEN 49 AND 101
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
Any other places you use TimerEventProcessor or Counter?
Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.
So instead of _Counter, you should use:
// when starting the timer:
DateTime _started = DateTime.UtcNow;
// in TimerEventProcessor:
seconds = (DateTime.UtcNow-started).TotalSeconds;
Label.Text = seconds.ToString();
Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.
var seconds_inputs = document.getElementsByClassName('deal_left_seconds');
var total_timers = seconds_inputs.length;
for ( var i = 0; i < total_timers; i++){
var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var cal_seconds = seconds_inputs[i].getAttribute('value');
eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
}
function timer() {
for ( var i = 0; i < total_timers; i++) {
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);
if (eval('seconds_'+ seconds_prod_id) == 0) {
clearInterval(countdownTimer);
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
} else {
var value = eval('seconds_'+seconds_prod_id);
value--;
eval('seconds_' + seconds_prod_id + '= ' + value + ';');
}
}
}
var countdownTimer = setInterval('timer()', 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">
<div class="box-wrapper">
<div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
<div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
<div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
<div class="seconds box"> <span class="key" id="deal_sec_1">0p0</span> <span class="value">SEC</span> </div>
</div>
_x000D_
I didn't understand your problem clearly but I think this is what you're looking for(Based on my understanding)
person = {"name"=>"BillGates", "company_name"=>"Microsoft", "position"=>"Chairman"}
person.delete_if {|key, value| key == "name"} #doing something if the key == "something"
Output: {"company_name"=>"Microsoft", "position"=>"Chairman"}
Editor warning: This solution is computationally inefficient and may bring down your connection for a large table.
NB - You need to do this first on a test copy of your table!
When I did it, I found that unless I also included AND n1.id <> n2.id
, it deleted every row in the table.
If you want to keep the row with the lowest id
value:
DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name
If you want to keep the row with the highest id
value:
DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name
I used this method in MySQL 5.1
Not sure about other versions.
Update: Since people Googling for removing duplicates end up here
Although the OP's question is about DELETE
, please be advised that using INSERT
and DISTINCT
is much faster. For a database with 8 million rows, the below query took 13 minutes, while using DELETE
, it took more than 2 hours and yet didn't complete.
INSERT INTO tempTableName(cellId,attributeId,entityRowId,value)
SELECT DISTINCT cellId,attributeId,entityRowId,value
FROM tableName;
Replaced the reader declaration with this one and now it works!
Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)
Encoding.Default represents the ANSI code page that is set under Windows Control Panel.
IMHO the biggest advantage that REST enables is that of reducing client/server coupling. It is much easier to evolve a REST interface over time without breaking existing clients.
It is important to recognize that the copyright laws have changed and that for non-US sources, especially after the USA joining the Berne Convention on March 1, 1989, copyright registration in not necessary for enforcement of a copyright notice.
Here is a resumé quoted from the Cornell University Law School (copied on March 4, 2015 from https://www.law.cornell.edu/wex/copyright:
"Copyright
copyright: an overview
The U.S. Copyright Act, 17 U.S.C. §§ 101 - 810, is Federal legislation enacted by Congress under its Constitutional grant of authority to protect the writings of authors. See U.S. Constitution, Article I, Section 8. Changing technology has led to an ever expanding understanding of the word "writings." The Copyright Act now reaches architectural design, software, the graphic arts, motion pictures, and sound recordings. See § 106. As of January 1, 1978, all works of authorship fixed in a tangible medium of expression and within the subject matter of copyright were deemed to fall within the exclusive jurisdiction of the Copyright Act regardless of whether the work was created before or after that date and whether published or unpublished. See § 301. See also preemption.
The owner of a copyright has the exclusive right to reproduce, distribute, perform, display, license, and to prepare derivative works based on the copyrighted work. See § 106. The exclusive rights of the copyright owner are subject to limitation by the doctrine of "fair use." See § 107. Fair use of a copyrighted work for purposes such as criticism, comment, news reporting, teaching, scholarship, or research is not copyright infringement. To determine whether or not a particular use qualifies as fair use, courts apply a multi-factor balancing test. See § 107.
Copyright protection subsists in original works of authorship fixed in any tangible medium of expression from which they can be perceived, reproduced, or otherwise communicated, either directly or with the aid of a machine or device. See § 102. Copyright protection does not extend to any idea, procedure, process, system, method of operation, concept, principle, or discovery. For example, if a book is written describing a new system of bookkeeping, copyright protection only extends to the author's description of the bookkeeping system; it does not protect the system itself. See Baker v. Selden, 101 U.S. 99 (1879).
According to the Copyright Act of 1976, registration of copyright is voluntary and may take place at any time during the term of protection. See § 408. Although registration of a work with the Copyright Office is not a precondition for protection, an action for copyright infringement may not be commenced until the copyright has been formally registered with the Copyright Office. See § 411.
Deposit of copies with the Copyright Office for use by the Library of Congress is a separate requirement from registration. Failure to comply with the deposit requirement within three months of publication of the protected work may result in a civil fine. See § 407. The Register of Copyrights may exempt certain categories of material from the deposit requirement.
In 1989 the U.S. joined the Berne Convention for the Protection of Literary and Artistic Works. In accordance with the requirements of the Berne Convention, notice is no longer a condition of protection for works published after March 1, 1989. This change to the notice requirement applies only prospectively to copies of works publicly distributed after March 1, 1989.
The Berne Convention also modified the rule making copyright registration a precondition to commencing a lawsuit for infringement. For works originating from a Berne Convention country, an infringement action may be initiated without registering the work with the U.S. Copyright Office. However, for works of U.S. origin, registration prior to filing suit is still required.
The federal agency charged with administering the act is the Copyright Office of the Library of Congress. See § 701 of the act. Its regulations are found in Parts 201 - 204 of title 37 of the Code of Federal Regulations."
hex_string = "".join("%02x" % b for b in array_alpha)
You should add System.configuration dll as reference and use System.Configuration.ConfigurationManager.AppSettings["configFile"].ToString
Don't forget to add using
statement at the beginning. Hope it will help.
I tried user968421's answer and the OP's solution but the browser popped up a security error for a checkout page. I can't tell you why exactly.
Our host (Site Ground) couldn't figure it out either.
The final solution was close, but a slight tweak to user968421's answer (side note: unlike the OP, I was trying to redirect to the corresponding page, not just to the homepage so I maintained the back reference [the $1
after the domain] from user968421's answer):
RewriteEngine on
RewriteRule (.*) https://newdomain.com/$1 [R=301,L]
Got the tweak from this htaccess redirect generator recommended by a Host Gator article (desperate times, desperate measures, amiright?).
Its better to perform this over Master branch
Edit .gitignore file. Add the below line in it.
.idea
Remove .idea folder from remote repo. using below command.
git rm -r --cached .idea
For more info. reference: Removing Files from a Git Repository Without Actually Deleting Them
Stage .gitignore file. Using below command
git add .gitignore
Commit
git commit -m 'Removed .idea folder'
Push to remote
git push origin master
Try [^- ]
, \s
will match 5 other characters beside the space (like tab, newline, formfeed, carriage return).
to join you can do multiple things (using eclipselink)
in jpql you can do left join fetch
in named query you can specify query hint
in TypedQuery you can say something like
query.setHint("eclipselink.join-fetch", "e.projects.milestones");
there is also batch fetch hint
query.setHint("eclipselink.batch", "e.address");
see
http://java-persistence-performance.blogspot.com/2010/08/batch-fetching-optimizing-object-graph.html
In order to pass the parameters you create new intent and put a parameter map:
Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);
In order to get the parameters values inside the started activity, you must call the get[type]Extra()
on the same intent:
// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"
If your parameters are ints you would use getIntExtra()
instead etc.
Now you can use your parameters like you normally would.
In my own findings, I think it's good to mention that you (as far as I can tell) must declare the full namespace path of a class.
MyClass.php
namespace com\company\lib;
class MyClass {
}
index.php
namespace com\company\lib;
//Works fine
$i = new MyClass();
$cname = 'MyClass';
//Errors
//$i = new $cname;
//Works fine
$cname = "com\\company\\lib\\".$cname;
$i = new $cname;
Here is the directive I use. It automatically cleans itself up when the form is unloaded. If you want to prevent the prompt from firing (e.g. because you successfully saved the form), call $scope.FORMNAME.$setPristine(), where FORMNAME is the name of the form you want to prevent from prompting.
.directive('dirtyTracking', [function () {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
function isDirty() {
var formObj = $scope[$element.attr('name')];
return formObj && formObj.$pristine === false;
}
function areYouSurePrompt() {
if (isDirty()) {
return 'You have unsaved changes. Are you sure you want to leave this page?';
}
}
window.addEventListener('beforeunload', areYouSurePrompt);
$element.bind("$destroy", function () {
window.removeEventListener('beforeunload', areYouSurePrompt);
});
$scope.$on('$locationChangeStart', function (event) {
var prompt = areYouSurePrompt();
if (!event.defaultPrevented && prompt && !confirm(prompt)) {
event.preventDefault();
}
});
}
};
}]);
I found several functions defined in http://tw1.php.net/unpack are very useful.
They can covert string to byte array and vice versa.
Take byteStr2byteArray() as an example:
<?php
function byteStr2byteArray($s) {
return array_slice(unpack("C*", "\0".$s), 1);
}
$msg = "abcdefghijk";
$byte_array = byteStr2byteArray($msg);
for($i=0;$i<count($byte_array);$i++)
{
printf("0x%02x ", $byte_array[$i]);
}
?>
I had the same question and found this article with a really clean solution:
http://leon.radley.se/2017/01/angular-cli-and-bootstrap-4/
Here are the instructions, but with my simplified solution:
Install Bootstrap 4 (instructions):
npm install --save [email protected]
If needed, rename your src/styles.css to styles.scss and update .angular-cli.json to reflect the change:
"styles": [
"styles.scss"
],
Then add this line to styles.scss:
@import '~bootstrap/scss/bootstrap';
jQuery recently started using source maps.
For example, let's look at the minified jQuery 2.0.3 file's first few lines.
/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/
Excerpt from Introduction to JavaScript Source Maps:
Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.
Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.
emphasis mine
It's incredibly useful, and will only download if the user opens dev tools.
Remove the source mapping line, or do nothing. It isn't really a problem.
Side note: your server should return 404, not 500. It could point to a security problem if this happens in production.
Take a look at requirejs project.
Here is how to integrate CSS star rating into an HTML form without using javascript (only html and css):
CSS:
.txt-center {
text-align: center;
}
.hide {
display: none;
}
.clear {
float: none;
clear: both;
}
.rating {
width: 90px;
unicode-bidi: bidi-override;
direction: rtl;
text-align: center;
position: relative;
}
.rating > label {
float: right;
display: inline;
padding: 0;
margin: 0;
position: relative;
width: 1.1em;
cursor: pointer;
color: #000;
}
.rating > label:hover,
.rating > label:hover ~ label,
.rating > input.radio-btn:checked ~ label {
color: transparent;
}
.rating > label:hover:before,
.rating > label:hover ~ label:before,
.rating > input.radio-btn:checked ~ label:before,
.rating > input.radio-btn:checked ~ label:before {
content: "\2605";
position: absolute;
left: 0;
color: #FFD700;
}
HTML:
<div class="txt-center">
<form>
<div class="rating">
<input id="star5" name="star" type="radio" value="5" class="radio-btn hide" />
<label for="star5">?</label>
<input id="star4" name="star" type="radio" value="4" class="radio-btn hide" />
<label for="star4">?</label>
<input id="star3" name="star" type="radio" value="3" class="radio-btn hide" />
<label for="star3">?</label>
<input id="star2" name="star" type="radio" value="2" class="radio-btn hide" />
<label for="star2">?</label>
<input id="star1" name="star" type="radio" value="1" class="radio-btn hide" />
<label for="star1">?</label>
<div class="clear"></div>
</div>
</form>
</div>
Please check the demo
go
create proc GetEmail
@name varchar(22),
@gmail varchar(22)
as
begin
declare @a varchar(22)
set select @a=substring(@gmail,charindex('@',@gmail),len(@gmail)-charindex('@',@gmail)+1)
if (@a = 'gmail.com)
insert into table_name values(@name,@gmail)
else
print 'please enter valid email address'
end
You can use the tee
command to redirect output:
/usr/bin/mysqldump -u user -pupasswd my-database | \
tee >(gzip -9 -c > /home/user/backup/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz) | \
gzip> /home/user/backup2/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz 2>&1
see documentation here
Try using .strip() at the end of your line
line.strip()
worked well for me
strSearch in this case is probably null (not simply empty).
Try using
String.IsNullOrEmpty(strSearch)
if you are just trying to determine if the string doesn't have any contents.
To fix this solution i followed: this
1.Click Start and then type Run
2.Type services.msc and click OK
3.Scroll down the list and locate that the VMware Authorization service.
4.Click Start the service, unless the service is showing a status of Started.
Why is it necessary for an interface to be "declared" abstract?
It's not.
public abstract interface Interface {
\___.__/
|
'----> Neither this...
public void interfacing();
public abstract boolean interfacing(boolean really);
\___.__/
|
'----> nor this, are necessary.
}
Interfaces and their methods are implicitly abstract
and adding that modifier makes no difference.
Is there other rules that applies with an abstract interface?
No, same rules apply. The method must be implemented by any (concrete) implementing class.
If abstract is obsolete, why is it included in Java? Is there a history for abstract interface?
Interesting question. I dug up the first edition of JLS, and even there it says "This modifier is obsolete and should not be used in new Java programs".
Okay, digging even further... After hitting numerous broken links, I managed to find a copy of the original Oak 0.2 Specification (or "manual"). Quite interesting read I must say, and only 38 pages in total! :-)
Under Section 5, Interfaces, it provides the following example:
public interface Storing {
void freezeDry(Stream s) = 0;
void reconstitute(Stream s) = 0;
}
And in the margin it says
In the future, the " =0" part of declaring methods in interfaces may go away.
Assuming =0
got replaced by the abstract
keyword, I suspect that abstract
was at some point mandatory for interface methods!
Related article: Java: Abstract interfaces and abstract interface methods
I use GUIDs as random keys for database type operations.
The hexadecimal form, with the dashes and extra characters seem unnecessarily long to me. But I also like that strings representing hexadecimal numbers are very safe in that they do not contain characters that can cause problems in some situations such as '+','=', etc..
Instead of hexadecimal, I use a url-safe base64 string. The following does not conform to any UUID/GUID spec though (other than having the required amount of randomness).
import base64
import uuid
# get a UUID - URL safe, Base64
def get_a_uuid():
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return r_uuid.replace('=', '')
pip install packageName -t pathOfDirectory
or
pip install packageName --target pathOfDirectorty
A simple way to do it would be to just annotate the Quartz Jobs with @Component
annotation, and then Spring will do all the DI magic for you, as it is now recognized as a Spring bean. I had to do something similar for an AspectJ
aspect - it was not a Spring bean until I annotated it with the Spring @Component
stereotype.
A good alternative is this:
find . -type f | xargs chmod -v 644
and for directories:
find . -type d | xargs chmod -v 755
and to be more explicit:
find . -type f | xargs -I{} chmod -v 644 {}
If you're running a local server on Apache, you can get what look like caching problems. This happened to me when I had a Apache server running under Vagrant (in virtualbox).
Just add the following lines to your config file (/etc/httpd/conf/httpd.conf
or equivalent):
#Disable image serving for network mounted drive
EnableSendfile off
Note that it's worth searching through the config file to see if EnableSendfile
is set to on
anywhere else.
This method will not truncate a word in the middle.
list($output)=explode("\n",wordwrap(strip_tags($str),500),1);
echo $output. ' ... <a href="#">Read more</a>';
I rarely use a struct for things. But that's just me. It depends whether I need the object to be nullable or not.
As stated in other answers, I use classes for real-world objects. I also have the mindset of structs are used for storing small amounts of data.
This might be more desirable, that is use float instead
SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC
simply insert new line where necessary
sql="
SELECT c1, c2
from Table1, Table2
where ...
"
shell will be looking for the closing quotation mark
Just use queuecomplete that's what its there for and its so so simple. Check the docs http://www.dropzonejs.com/
queuecomplete > Called when all files in the queue finished uploading.
this.on("queuecomplete", function (file) {
alert("All files have uploaded ");
});
This should print the list of positions without the -1
at the end that Peter Lawrey's solution has had.
int index = word.indexOf(guess);
while (index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index + 1);
}
It can also be done as a for
loop:
for (int index = word.indexOf(guess);
index >= 0;
index = word.indexOf(guess, index + 1))
{
System.out.println(index);
}
[Note: if guess
can be longer than a single character, then it is possible, by analyzing the guess
string, to loop through word
faster than the above loops do. The benchmark for such an approach is the Boyer-Moore algorithm. However, the conditions that would favor using such an approach do not seem to be present.]
After you've retrieved the reflect.Value
of the field by using Field(i)
you can get a
interface value from it by calling Interface()
. Said interface value then represents the
value of the field.
There is no function to convert the value of the field to a concrete type as there are,
as you may know, no generics in go. Thus, there is no function with the signature GetValue() T
with T
being the type of that field (which changes of course, depending on the field).
The closest you can achieve in go is GetValue() interface{}
and this is exactly what reflect.Value.Interface()
offers.
The following code illustrates how to get the values of each exported field in a struct using reflection (play):
import (
"fmt"
"reflect"
)
func main() {
x := struct{Foo string; Bar int }{"foo", 2}
v := reflect.ValueOf(x)
values := make([]interface{}, v.NumField())
for i := 0; i < v.NumField(); i++ {
values[i] = v.Field(i).Interface()
}
fmt.Println(values)
}
Adding to Jim's elaborate answer:
Check the typing
module -- this module supports type hints as specified by PEP 484.
For example, the function below takes and returns values of type str
and is annotated as follows:
def greeting(name: str) -> str:
return 'Hello ' + name
The typing
module also supports:
Try this. This script gets current logged in user's name & home directory:
On Error Resume Next
Dim objShell, strTemp
Set objShell = WScript.CreateObject("WScript.Shell")
strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERNAME"
WScript.Echo "Logged in User: " & objShell.RegRead(strTemp)
strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERPROFILE"
WScript.Echo "User Home: " & objShell.RegRead(strTemp)
unicodestring = '\xa0'
decoded_str = unicodestring.decode("windows-1252")
encoded_str = decoded_str.encode('ascii', 'ignore')
Works for me
As doc says also keep in mind the correct value combination:
The setting must be one of the values listed in the following table, or a combination of one "state..." value plus one "adjust..." value. Setting multiple values in either group — multiple "state..." values, for example — has undefined results. Individual values are separated by a vertical bar (|). For example:
<activity android:windowSoftInputMode="stateVisible|adjustResize" . . . >
The easiest way is to remove it from the tab index all together:
$('#control').find('input[readonly]').each(function () {
$(this).attr('tabindex', '-1');
});
I already use this on a couple of forms.
The </script>
inside the Javascript string litteral is interpreted by the HTML parser as a closing tag, causing unexpected behaviour (see example on JSFiddle).
To avoid this, you can place your javascript between comments (this style of coding was common practice, back when Javascript was poorly supported among browsers). This would work (see example in JSFiddle):
<script type="text/javascript">
<!--
if (jQuery === undefined) {
document.write('<script type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"></script>');
}
// -->
</script>
...but to be honest, using document.write
is not something I would consider best practice. Why not manipulating the DOM directly?
<script type="text/javascript">
<!--
if (jQuery === undefined) {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js');
document.body.appendChild(script);
}
// -->
</script>
Relying on column order is generally a bad idea in SQL. SQL is based on Relational theory where order is never guaranteed - by design. You should treat all your columns and rows as having no order and then change your queries to provide the correct results:
For Columns:
For Rows:
Hope this helps...
df = pd.DataFrame(scale.fit_transform(df.values), columns=df.columns, index=df.index)
This should work without depreciation warnings.
For me, an issue where json_encode would return null encoding of an entity was because my jsonSerialize implementation fetched entire objects for related entities; I solved the issue by making sure that I fetched the ID of the related/associated entity and called ->toArray() when there were more than one entity associated with the object to be json serialized. Note, I'm speaking about cases where one implements JsonSerializable
on entities.
This question is very helpfully BUT Don't forget to mount SD Card in your emulator, if you don't do this its doesn't work.
I lose my time before discover this.
For setting java properties on Windows app server:
then add Java opts:
restart service.
Turned out there was some extra code in the AppModel that was messing things up:
in beforeFind
and afterFind
:
App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");
I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.
The aptitude --download-only ...
approach only works if you have a debian distro with internet connection in your hands.
If you don't, I think it is better to run the following script on the disconnected debian machine:
apt-get --print-uris --yes install <my_package_name> | grep ^\' | cut -d\' -f2 >downloads.list
move the downloads.list file into a connected linux (or non linux) machine, and run:
wget --input-file myurilist
this downloads all your files into the current directory.After that you can copy them on an USB key and install in your disconnected debian machine.
credits: http://www.tuxradar.com/answers/517
PS I basically copied the blog post because it was not very readable, and in case the post will disappear.
It is possible with CSS3 :
#myDiv {
-webkit-filter: blur(20px);
-moz-filter: blur(20px);
-o-filter: blur(20px);
-ms-filter: blur(20px);
filter: blur(20px);
opacity: 0.4;
}
Example here => jsfiddle
(Latest as of 2020) For version Chrome Version 83.0.4103.61 :
Select the element you want to inspect
Choose the Event Listeners tab
Make sure to check the Framework listeners to show the real javascript file instead of the jquery function.
When I used the code mysqld_safe --skip-grant-tables &
but I get the error:
mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.
$ systemctl stop mysql.service
$ ps -eaf|grep mysql
$ mysqld_safe --skip-grant-tables &
I solved:
$ mkdir -p /var/run/mysqld
$ chown mysql:mysql /var/run/mysqld
Now I use the same code mysqld_safe --skip-grant-tables &
and get
mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
If I use $ mysql -u root
I'll get :
Server version: 5.7.18-0ubuntu0.16.04.1 (Ubuntu)
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Now time to change password:
mysql> use mysql
mysql> describe user;
Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A
Database changed
mysql> FLUSH PRIVILEGES;
mysql> SET PASSWORD FOR root@'localhost' = PASSWORD('newpwd');
or If you have a mysql root account that can connect from everywhere, you should also do:
UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
Alternate Method:
USE mysql
UPDATE user SET Password = PASSWORD('newpwd')
WHERE Host = 'localhost' AND User = 'root';
And if you have a root account that can access from everywhere:
USE mysql
UPDATE user SET Password = PASSWORD('newpwd')
WHERE Host = '%' AND User = 'root';`enter code here
now need to quit
from mysql and stop/start
FLUSH PRIVILEGES;
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start
now again ` mysql -u root -p' and use the new password to get
mysql>
There is an easiest way to do this using css:
.modal-dialog {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width:500px;
height:300px;
}
That's it. Notice that it is only needed to be applied to the .modal-dialog
container div.
According to the API
totalMemory()
Returns the total amount of memory in the Java virtual machine. The value returned by this method may vary over time, depending on the host environment. Note that the amount of memory required to hold an object of any given type may be implementation-dependent.
maxMemory()
Returns the maximum amount of memory that the Java virtual machine will attempt to use. If there is no inherent limit then the value Long.MAX_VALUE will be returned.
freeMemory()
Returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by freeMemory.
In reference to your question, maxMemory()
returns the -Xmx
value.
You may be wondering why there is a totalMemory() AND a maxMemory(). The answer is that the JVM allocates memory lazily. Lets say you start your Java process as such:
java -Xms64m -Xmx1024m Foo
Your process starts with 64mb of memory, and if and when it needs more (up to 1024m), it will allocate memory. totalMemory()
corresponds to the amount of memory currently available to the JVM for Foo. If the JVM needs more memory, it will lazily allocate it up to the maximum memory. If you run with -Xms1024m -Xmx1024m
, the value you get from totalMemory()
and maxMemory()
will be equal.
Also, if you want to accurately calculate the amount of used memory, you do so with the following calculation :
final long usedMem = totalMemory() - freeMemory();
Here is my sugestion:
Dim i As integer, j as integer
With Worksheets("TimeOut")
i = 26
Do Until .Cells(8, i).Value = ""
For j = 9 to 100 ' I do not know how many rows you will need it.'
.Cells(j, i).Formula = "YourVolFormulaHere"
.Cells(j, i + 1).Formula = "YourCapFormulaHere"
Next j
i = i + 2
Loop
End With
Here, the myThing variable is private and is part of the closure:
class Person {
constructor() {
var myThing = "Hello World";
return {
thing: myThing,
sayThing: this.sayThing
}
}
sayThing() {
console.log(this.thing);
}
}
var person = new Person();
console.log(person);
My humble take on the subject, a generalization of Alex Martelli's answer, with start() and stop() control:
from threading import Timer
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
Usage:
from time import sleep
def hello(name):
print "Hello %s!" % name
print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
sleep(5) # your long-running job goes here...
finally:
rt.stop() # better in a try/finally block to make sure the program ends!
Features:
start()
and stop()
are safe to call multiple times even if the timer has already started/stoppedinterval
anytime, it will be effective after next run. Same for args
, kwargs
and even function
!table users (user_id int unsigned PK, username varchar(32))
alter table users add column verified tinyint unsigned default 0
I had that issue and here is much simpler solution:
Replace default petstore url in dist/index.html with your localhost/api-docs or to make it more generalized, replace with this:
location.protocol+'//' + location.hostname+(location.port ? ':' + location.port: '') + "/api-docs";
Hit again localhost/swagger-ui
Voila! You local swagger implementation is ready
DECLARE @cols VARCHAR(max),@colsUpd VARCHAR(max), @query VARCHAR(max),@queryUpd VARCHAR(max), @subQuery VARCHAR(max)
DECLARE @TableNameTest NVARCHAR(150)
SET @TableNameTest = @TableName+ '_Staging';
SELECT @colsUpd = STUF ((SELECT DISTINCT '], T1.[' + name,']=T2.['+name+'' FROM sys.columns
WHERE object_id = (
SELECT top 1 object_id
FROM sys.objects
WHERE name = ''+@TableNameTest+''
)
and name not in ('Action','Record_ID')
FOR XML PATH('')
), 1, 2, ''
) + ']'
Select @queryUpd ='Update T1
SET '+@colsUpd+'
FROM '+@TableName+' T1
INNER JOIN '+@TableNameTest+' T2
ON T1.Record_ID = T2.Record_Id
WHERE T2.[Action] = ''Modify'''
EXEC (@queryUpd)
In case someone is using Data Binding. We can define binding adapter like this
@BindingAdapter("html")
fun setHtml(view: TextView, html: String) {
view.setText(HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY))
}
Then we can use it on a TextView
app:html="@{@string/bold_text}"
where bold_text is
<string name="bold_text"><![CDATA[Part of text is <b>bold</b>]]></string>
An import is required, import scipy.io
...
import scipy.io
mat = scipy.io.loadmat('file.mat')
Why is everyone making life so hard. Tuples are for rather temporary data processing. Working with Tuples all the time will make the code very hard to understand at some point. Creating classes for everything could eventually bloat your project.
It's about balance, however...
Your problem seems to be something you would want a class for. And just for the sake of completeness, this class below also contains constructors.
This is the proper pattern for
public class OrderRelatedIds
{
public int OrderGroupId { get; set; }
public int OrderTypeId { get; set; }
public int OrderSubTypeId { get; set; }
public int OrderRequirementId { get; set; }
public OrderRelatedIds()
{
}
public OrderRelatedIds(int orderGroupId)
: this()
{
OrderGroupId = orderGroupId;
}
public OrderRelatedIds(int orderGroupId, int orderTypeId)
: this(orderGroupId)
{
OrderTypeId = orderTypeId;
}
public OrderRelatedIds(int orderGroupId, int orderTypeId, int orderSubTypeId)
: this(orderGroupId, orderTypeId)
{
OrderSubTypeId = orderSubTypeId;
}
public OrderRelatedIds(int orderGroupId, int orderTypeId, int orderSubTypeId, int orderRequirementId)
: this(orderGroupId, orderTypeId, orderSubTypeId)
{
OrderRequirementId = orderRequirementId;
}
}
Or, if you want it really simple: You can also use type initializers:
OrderRelatedIds orders = new OrderRelatedIds
{
OrderGroupId = 1,
OrderTypeId = 2,
OrderSubTypeId = 3,
OrderRequirementId = 4
};
public class OrderRelatedIds
{
public int OrderGroupId;
public int OrderTypeId;
public int OrderSubTypeId;
public int OrderRequirementId;
}
If possible, check out SSIS (SQL Server Integration Services). I am just getting my feet wet with this toolkit, but already am looping over 40+ servers and preparing to wreak all kinds of havoc ;)
Here's the proper way to do things:
<?PHP
$sql = 'some query...';
$result = mysql_query($q);
if (! $result){
throw new My_Db_Exception('Database error: ' . mysql_error());
}
while($row = mysql_fetch_assoc($result)){
//handle rows.
}
Note the check on (! $result) -- if your $result is a boolean, it's certainly false, and it means there was a database error, meaning your query was probably bad.
I find these params acceptable as well and more then likely don't have false positives when switching web servers.
$_SERVER['HTTPS_SERVER_SUBJECT']
if($_SERVER['HTTPS_KEYSIZE'] != NULL){/*do foobar*/}
var cur_value = $(this).find('option:selected').text();
Since option
is likely to be immediate child of select
you can also use:
var cur_value = $(this).children('option:selected').text();