I just spent several days checking parameters because I have to pass 60 to a stored procedure. It turns out that the one of the variable names (which I load into a list and pass to the Oracle Write method I created) had a space in the name at the end. When comparing to the variables in the stored procedure they were the same, but in the editor I used to compare them, I didnt notice the extra space. Drove me crazy for the last 4 days trying everything I could find, and changing even the .net Oracle driver. Just wanted to throw that out here so it can help someone else. We tend to concentrate on the characters and ignore the spaces. . .
run the below command in command prompt
tnsping Datasource
This should give a response like below
C:>tnsping *******
TNS Ping Utility for *** Windows: Version *** - Production on *****
Copyright (c) 1997, 2014, Oracle. All rights reserved.
Used parameter files: c:\oracle*****
Used **** to resolve the alias Attempting to contact (description=(address_list=(address=(protocol=tcp)(host=)(port=)))(connect_data=(server=)(service_name=)(failover_mode=(type=)(method=)(retries=)(delay=))))** OK (**** msec)
Add the text 'Datasource=' in beginning and credentials at the end. the final string should be
Data Source=(description=(address_list=(address=(protocol=tcp)(host=)(port=)))(connect_data=(server=)(service_name=)(failover_mode=(type=)(method=)(retries=)(delay=))));User Id=;Password=;**
Use this as the connection string to connect to oracle db.
Try to add the path to tnsnames.ora to the config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<oracle.manageddataaccess.client>
<version number="4.112.3.60">
<settings>
<setting name="TNS_ADMIN" value="C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\" />
</settings>
</version>
</oracle.manageddataaccess.client>
</configuration>
First off you need to download and install ODP from this site http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
After installation add a reference of the assembly Oracle.DataAccess.dll.
Your are good to go after this.
using System;
using Oracle.DataAccess.Client;
class OraTest
{
OracleConnection con;
void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
void Close()
{
con.Close();
con.Dispose();
}
static void Main()
{
OraTest ot= new OraTest();
ot.Connect();
ot.Close();
}
}
Oracle has a different syntax for parameters than Sql-Server. So use :
instead of @
using(var con=new OracleConnection(connectionString))
{
con.open();
var sql = "insert into users values (:id,:name,:surname,:username)";
using(var cmd = new OracleCommand(sql,con)
{
OracleParameter[] parameters = new OracleParameter[] {
new OracleParameter("id",1234),
new OracleParameter("name","John"),
new OracleParameter("surname","Doe"),
new OracleParameter("username","johnd")
};
cmd.Parameters.AddRange(parameters);
cmd.ExecuteNonQuery();
}
}
When using named parameters in an OracleCommand you must precede the parameter name with a colon (:).
http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters.aspx
On Charles' comment problem: to make things worse, let
:p1 = 'TRIALDEV'
via a Command Parameter, then execute
select T.table_name as NAME, COALESCE(C.comments, '===') as DESCRIPTION
from all_all_tables T
Inner Join all_tab_comments C on T.owner = C.owner and T.table_name = C.table_name
where Upper(T.owner)=:p1
order by T.table_name
558 line(s) affected. Processing time: 00:00:00.6535711
and when changing the literal string from === to ---
select T.table_name as NAME, COALESCE(C.comments, '---') as DESCRIPTION
[...from...same-as-above...]
ORA-01008: not all variables bound
Both statements execute fine in SQL Developer. The shortened code:
Using con = New OracleConnection(cs)
con.Open()
Using cmd = con.CreateCommand()
cmd.CommandText = cmdText
cmd.Parameters.Add(pn, OracleDbType.NVarchar2, 250).Value = p
Dim tbl = New DataTable
Dim da = New OracleDataAdapter(cmd)
da.Fill(tbl)
Return tbl
End Using
End Using
using Oracle.ManagedDataAccess.dll Version 4.121.2.0 with the default settings in VS2015 on the .Net 4.61 platform.
So somewhere in the call chain, there might be a parser that is a bit too aggressively looking for one-line-comments started by -- in the commandText. But even if this would be true, the error message "not all variables bound" is at least misleading.
end-of-file on communication channel:
One of the course of this error is due to database fail to write the log when its in the stage of opening;
Solution check the database if its running in ARCHIVELOG or NOARCHIVELOG
to check use
select log_mode from v$database;
if its on ARCHIVELOG
try to change into NOARCHIVELOG
by using sqlplus
if it works for this
Then you can adjust your flashrecovery area its possibly that your flashrecovery area is full
-> then after confirm that your flashrecovery area has the space you can alter your database into the ARCHIVELOG
Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point
Introduction: I have encountered such problem when was testing my fist network app. I created: Client and Server then I ran client and suddenly exception was thrown, indeed it blocks the connection, because the port is not being listened!
Error: My port was not listened by the server, because server was down.
Solution: Run the Server first, so the port will be listened by server and once client tries to connect the server will handle that.
why do I have to pass seconds = uptime to timedelta
Because timedelta objects can be passed seconds, milliseconds, days, etc... so you need to specify what are you passing in (this is why you use the explicit key). Typecasting to int
is superfluous as they could also accept floats.
and why does the string casting works so nicely that I get HH:MM:SS ?
It's not the typecasting that formats, is the internal __str__
method of the object. In fact you will achieve the same result if you write:
print datetime.timedelta(seconds=int(uptime))
It is just a name change. before_action
is more specific, because it gets executed before an action.
If you're using PHP you can test your PUT upload using the code below:
#Initiate cURL object
$curl = curl_init();
#Set your URL
curl_setopt($curl, CURLOPT_URL, 'https://local.simbiat.ru');
#Indicate, that you plan to upload a file
curl_setopt($curl, CURLOPT_UPLOAD, true);
#Indicate your protocol
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#Set flags for transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
#Disable header (optional)
curl_setopt($curl, CURLOPT_HEADER, false);
#Set HTTP method to PUT
curl_setopt($curl, CURLOPT_PUT, 1);
#Indicate the file you want to upload
curl_setopt($curl, CURLOPT_INFILE, fopen('path_to_file', 'rb'));
#Indicate the size of the file (it does not look like this is mandatory, though)
curl_setopt($curl, CURLOPT_INFILESIZE, filesize('path_to_file'));
#Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#Execute
curl_exec($curl);
I compared some of the methods suggested here in Firefox for speed.
The string I used contained the following characters: œ´®†¥¨ˆøp¬°??©ƒ?ßåO˜çv?˜µ=
All results are averages of 3 runs each. Times are in milliseconds. Note that all URIEncoding methods behaved similarly and had extreme results, so I only included one.
While there are some fluctuations based on the size of the string, the charCode methods (lovasoa and fuweichin) both perform similarly and the fastest overall, with fuweichin's charCode method the fastest. The Blob and TextEncoder methods performed similarly to each other. Generally the charCode methods were about 75% faster than the Blob and TextEncoder methods. The URIEncoding method was basically unacceptable.
Here are the results I got:
Size 6.4 * 10^6 bytes:
Lauri Oherd – URIEncoding: 6400000 et: 796
lovasoa – charCode: 6400000 et: 15
fuweichin – charCode2: 6400000 et: 16
simap – Blob: 6400000 et: 26
Riccardo Galli – TextEncoder: 6400000 et: 23
Size 19.2 * 10^6 bytes: Blob does kind of a weird thing here.
Lauri Oherd – URIEncoding: 19200000 et: 2322
lovasoa – charCode: 19200000 et: 42
fuweichin – charCode2: 19200000 et: 45
simap – Blob: 19200000 et: 169
Riccardo Galli – TextEncoder: 19200000 et: 70
Size 64 * 10^6 bytes:
Lauri Oherd – URIEncoding: 64000000 et: 12565
lovasoa – charCode: 64000000 et: 138
fuweichin – charCode2: 64000000 et: 133
simap – Blob: 64000000 et: 231
Riccardo Galli – TextEncoder: 64000000 et: 211
Size 192 * 10^6 bytes: URIEncoding methods freezes browser at this point.
lovasoa – charCode: 192000000 et: 754
fuweichin – charCode2: 192000000 et: 480
simap – Blob: 192000000 et: 701
Riccardo Galli – TextEncoder: 192000000 et: 654
Size 640 * 10^6 bytes:
lovasoa – charCode: 640000000 et: 2417
fuweichin – charCode2: 640000000 et: 1602
simap – Blob: 640000000 et: 2492
Riccardo Galli – TextEncoder: 640000000 et: 2338
Size 1280 * 10^6 bytes: Blob & TextEncoder methods are starting to hit the wall here.
lovasoa – charCode: 1280000000 et: 4780
fuweichin – charCode2: 1280000000 et: 3177
simap – Blob: 1280000000 et: 6588
Riccardo Galli – TextEncoder: 1280000000 et: 5074
Size 1920 * 10^6 bytes:
lovasoa – charCode: 1920000000 et: 7465
fuweichin – charCode2: 1920000000 et: 4968
JavaScript error: file:///Users/xxx/Desktop/test.html, line 74: NS_ERROR_OUT_OF_MEMORY:
Here is the code:
function byteLengthURIEncoding(str) {
return encodeURI(str).split(/%..|./).length - 1;
}
function byteLengthCharCode(str) {
// returns the byte length of an utf8 string
var s = str.length;
for (var i=str.length-1; i>=0; i--) {
var code = str.charCodeAt(i);
if (code > 0x7f && code <= 0x7ff) s++;
else if (code > 0x7ff && code <= 0xffff) s+=2;
if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
}
return s;
}
function byteLengthCharCode2(s){
//assuming the String is UCS-2(aka UTF-16) encoded
var n=0;
for(var i=0,l=s.length; i<l; i++){
var hi=s.charCodeAt(i);
if(hi<0x0080){ //[0x0000, 0x007F]
n+=1;
}else if(hi<0x0800){ //[0x0080, 0x07FF]
n+=2;
}else if(hi<0xD800){ //[0x0800, 0xD7FF]
n+=3;
}else if(hi<0xDC00){ //[0xD800, 0xDBFF]
var lo=s.charCodeAt(++i);
if(i<l&&lo>=0xDC00&&lo<=0xDFFF){ //followed by [0xDC00, 0xDFFF]
n+=4;
}else{
throw new Error("UCS-2 String malformed");
}
}else if(hi<0xE000){ //[0xDC00, 0xDFFF]
throw new Error("UCS-2 String malformed");
}else{ //[0xE000, 0xFFFF]
n+=3;
}
}
return n;
}
function byteLengthBlob(str) {
return new Blob([str]).size;
}
function byteLengthTE(str) {
return (new TextEncoder().encode(str)).length;
}
var sample = "œ´®†¥¨ˆøp¬°??©ƒ?ßåO˜çv?˜µ=i";
var string = "";
// Adjust multiplier to change length of string.
let mult = 1000000;
for (var i = 0; i < mult; i++) {
string += sample;
}
let t0;
try {
t0 = Date.now();
console.log("Lauri Oherd – URIEncoding: " + byteLengthURIEncoding(string) + " et: " + (Date.now() - t0));
} catch(e) {}
t0 = Date.now();
console.log("lovasoa – charCode: " + byteLengthCharCode(string) + " et: " + (Date.now() - t0));
t0 = Date.now();
console.log("fuweichin – charCode2: " + byteLengthCharCode2(string) + " et: " + (Date.now() - t0));
t0 = Date.now();
console.log("simap – Blob: " + byteLengthBlob(string) + " et: " + (Date.now() - t0));
t0 = Date.now();
console.log("Riccardo Galli – TextEncoder: " + byteLengthTE(string) + " et: " + (Date.now() - t0));
This below code just show the very basic use of delegate concept .. you name the variable and class as per your requirement.
First you need to declare a protocol:
Let's call it MyFirstControllerDelegate.h
@protocol MyFirstControllerDelegate
- (void) FunctionOne: (MyDataOne*) dataOne;
- (void) FunctionTwo: (MyDatatwo*) dataTwo;
@end
Import MyFirstControllerDelegate.h file and confirm your FirstController with protocol MyFirstControllerDelegate
#import "MyFirstControllerDelegate.h"
@interface FirstController : UIViewController<MyFirstControllerDelegate>
{
}
@end
In the implementation file, you need to implement both functions of protocol:
@implementation FirstController
- (void) FunctionOne: (MyDataOne*) dataOne
{
//Put your finction code here
}
- (void) FunctionTwo: (MyDatatwo*) dataTwo
{
//Put your finction code here
}
//Call below function from your code
-(void) CreateSecondController
{
SecondController *mySecondController = [SecondController alloc] initWithSomeData:.];
//..... push second controller into navigation stack
mySecondController.delegate = self ;
[mySecondController release];
}
@end
in your SecondController:
@interface SecondController:<UIViewController>
{
id <MyFirstControllerDelegate> delegate;
}
@property (nonatomic,assign) id <MyFirstControllerDelegate> delegate;
@end
In the implementation file of SecondController.
@implementation SecondController
@synthesize delegate;
//Call below two function on self.
-(void) SendOneDataToFirstController
{
[delegate FunctionOne:myDataOne];
}
-(void) SendSecondDataToFirstController
{
[delegate FunctionTwo:myDataSecond];
}
@end
Here is the wiki article on delegate.
the worked proposition for me is __call__
on class who create list of little numbers:
import itertools
class SmallNumbers:
def __init__(self, how_much):
self.how_much = int(how_much)
self.work_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
self.generated_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
start = 10
end = 100
for cmb in range(2, len(str(self.how_much)) + 1):
self.ListOfCombinations(is_upper_then=start, is_under_then=end, combinations=cmb)
start *= 10
end *= 10
def __call__(self, number, *args, **kwargs):
return self.generated_list[number]
def ListOfCombinations(self, is_upper_then, is_under_then, combinations):
multi_work_list = eval(str('self.work_list,') * combinations)
nbr = 0
for subset in itertools.product(*multi_work_list):
if is_upper_then <= nbr < is_under_then:
self.generated_list.append(''.join(subset))
if self.how_much == nbr:
break
nbr += 1
and to run it:
if __name__ == '__main__':
sm = SmallNumbers(56)
print(sm.generated_list)
print(sm.generated_list[34], sm.generated_list[27], sm.generated_list[10])
print('The Best', sm(15), sm(55), sm(49), sm(0))
result
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56']
34 27 10
The Best 15 55 49 0
HTML:
<button onclick="scrollToTop(1000);"></button>
1# JavaScript (linear):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const totalScrollDistance = document.scrollingElement.scrollTop;
let scrollY = totalScrollDistance, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollY will be -Infinity
scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = scrollY;
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
2# JavaScript (ease in and out):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const cosParameter = document.scrollingElement.scrollTop / 2;
let scrollCount = 0, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollCount will be Infinity
scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
/*
Explanation:
- pi is the length/end point of the cosinus intervall (see below)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the delta time
a * cos (bx + c) + d | c translates along the x axis = 0
= a * cos (bx) + d | d translates along the y axis = 1 -> only positive y values
= a * cos (bx) + 1 | a stretches along the y axis = cosParameter = window.scrollY / 2
= cosParameter + cosParameter * (cos bx) | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
= cosParameter + cosParameter * (cos scrollCount * x)
*/
Note:
3# Simple scrolling library on Github
mysqldump --no-create-info ...
Also you may use:
--skip-triggers
: if you are using triggers--no-create-db
: if you are using --databases ...
option--compact
: if you want to get rid of extra commentsYes, int values in an array are initialized to zero. But you are not guaranteed this. Oracle documentation states that this is a bad coding practice.
Step 1: Go to the download site from Gradle: https://gradle.org/releases/
Step 2: Extract the downloaded zip file into a directory.
Step 2: Hit Ctrl + Alt + S (mac: ? + ,) in Android studio/Intellij IDEA
Step 3: Goto: Build, Execution, Deployment >> Build Tools >> Gradle (Or just type in the searchbar Gradle)
Step 4: Select: (X) Use local gradle distribution and set Gradle home to your extracted Gradle directory. Click on apply.
Step 5: Get rid of your unnecessary gradle files delete:
- MyApp/gradle/
- gradlew
- gradlew.bat
If your intention is to get hold of already instantiated controller of another component and that if you are following component/directive based approach you can always require
a controller (instance of a component) from a another component that follows a certain hierarchy.
For example:
//some container component that provides a wizard and transcludes the page components displayed in a wizard
myModule.component('wizardContainer', {
...,
controller : function WizardController() {
this.disableNext = function() {
//disable next step... some implementation to disable the next button hosted by the wizard
}
},
...
});
//some child component
myModule.component('onboardingStep', {
...,
controller : function OnboadingStepController(){
this.$onInit = function() {
//.... you can access this.container.disableNext() function
}
this.onChange = function(val) {
//..say some value has been changed and it is not valid i do not want wizard to enable next button so i call container's disable method i.e
if(notIsValid(val)){
this.container.disableNext();
}
}
},
...,
require : {
container: '^^wizardContainer' //Require a wizard component's controller which exist in its parent hierarchy.
},
...
});
Now the usage of these above components might be something like this:
<wizard-container ....>
<!--some stuff-->
...
<!-- some where there is this page that displays initial step via child component -->
<on-boarding-step ...>
<!--- some stuff-->
</on-boarding-step>
...
<!--some stuff-->
</wizard-container>
There are many ways you can set up require.
(no prefix) - Locate the required controller on the current element. Throw an error if not found.
? - Attempt to locate the required controller or pass null to the link fn if not found.
^ - Locate the required controller by searching the element and its parents. Throw an error if not found.
^^ - Locate the required controller by searching the element's parents. Throw an error if not found.
?^ - Attempt to locate the required controller by searching the element and its parents or pass null to the link fn if not found.
?^^ - Attempt to locate the required controller by searching the element's parents, or pass null to the link fn if not found.
Old Answer:
You need to inject $controller
service to instantiate a controller inside another controller. But be aware that this might lead to some design issues. You could always create reusable services that follows Single Responsibility and inject them in the controllers as you need.
Example:
app.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
var testCtrl1ViewModel = $scope.$new(); //You need to supply a scope while instantiating.
//Provide the scope, you can also do $scope.$new(true) in order to create an isolated scope.
//In this case it is the child scope of this scope.
$controller('TestCtrl1',{$scope : testCtrl1ViewModel });
testCtrl1ViewModel.myMethod(); //And call the method on the newScope.
}]);
In any case you cannot call TestCtrl1.myMethod()
because you have attached the method on the $scope
and not on the controller instance.
If you are sharing the controller, then it would always be better to do:-
.controller('TestCtrl1', ['$log', function ($log) {
this.myMethod = function () {
$log.debug("TestCtrl1 - myMethod");
}
}]);
and while consuming do:
.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
var testCtrl1ViewModel = $controller('TestCtrl1');
testCtrl1ViewModel.myMethod();
}]);
In the first case really the $scope
is your view model, and in the second case it the controller instance itself.
Are you absolutely sure this can't be done through inheritance? Reflection is the very last thing you should look at when solving a problem, it makes refactoring, understanding your code, and any automated analysis more difficult.
It looks like you should just have a DrawItem1, DrawItem2, etc class that override your dynMethod.
In virtual Box as said upper, you can add this line hosts file
10.0.2.2 outer
but to save it, if you don't have administrators right in your VM just move hosts file to desktop, then edit it to add the line 10.0....outer, save the file, and move to its original place.
Take a look at Path.Combine
http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
Not too sure to add opacity via CSS is such a good idea.
Opacity has that funny way to be applied to all content and childs from where you set it, with unexpected results in mixed of colours.
It has no really purpose in that case , for a bg color, in my opinion.
If you'd like to lay it hover the bg image, then you may use multiple backgrounds.
this color transparent could be applyed via an extra png repeated (or not with background-position),
CSS gradient (radial-) linear-gradient with rgba colors (starting and ending with same color) can achieve this as well. They are treated as background-image and can be used as filter.
Idem for text, if you want them a bit transparent, use rgba (okay to put text-shadow together).
I think that today, we can drop funny behavior of CSS opacity.
Here is a mixed of rgba used for opacity if you are curious dabblet.com/gist/5685845
Either of these methods may be "better", i.e. more suitable, depending on what you want to do.
A server-side redirect is faster insofar as you get the data from a different page without making a round trip to the browser. But the URL seen in the browser is still the original address, so you're creating a little inconsistency there.
A client-side redirect is more versatile insofar as it can send you to a completely different server, or change the protocol (e.g. from HTTP to HTTPS), or both. And the browser is aware of the new URL. But it takes an extra back-and-forth between server and client.
text.indexOf("newString")
is the best method instead of startsWith
.
Example:
var text = "Format";
if(text.indexOf("Format") == 0) {
alert(text + " = Format");
} else {
alert(text + " != Format");
}
Use the IdentityFile
parameter in your ~/.ssh/config
:
Host github.com
HostName github.com
IdentityFile ~/.ssh/github.rsa
User petdance
why not use date() just like below,try this
$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);
and will be output
09/04/13 16:37:05
You can use {!! $text !!} for render HTML code in Laravel
{!! $text !!}
If you use
{{ $text }}
It will not render HTML code and print as a string.
Get Start Date & End Date by Custom Date
DECLARE @Date NVARCHAR(50)='05/19/2019'
SELECT
DATEADD(DAY,CASE WHEN DATEPART(WEEKDAY, @Date)=1 THEN -6 ELSE 2 - DATEPART(WEEKDAY, @Date) END, CAST(@Date AS DATE)) [Week_Start_Date]
,DATEADD(DAY,CASE WHEN DATEPART(WEEKDAY, @Date)=1 THEN 0 ELSE 8 - DATEPART(WEEKDAY, @Date) END, CAST(@Date AS DATE)) [Week_End_Date]
Because async functions are promises, you can create a static function on your class which executes an async function which returns the instance of the class:
class Yql {
constructor () {
// Set up your class
}
static init () {
return (async function () {
let yql = new Yql()
// Do async stuff
await yql.build()
// Return instance
return yql
}())
}
async build () {
// Do stuff with await if needed
}
}
async function yql () {
// Do this instead of "new Yql()"
let yql = await Yql.init()
// Do stuff with yql instance
}
yql()
Call with let yql = await Yql.init()
from an async function.
Problem: You do not have permission to write to the directories that npm uses to store global packages and commands.
Solution: Allow permission for npm.
Open a terminal:
command + spacebar then type 'terminal'
Enter this command:
sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}
This solution allows permission to ONLY the directories needed, keeping the other directories nice and safe.
I was receiving this error because I happened to be opening a website project over a mapped network drive z:\folder
instead of connecting via a UNC path \\server\path\folder
. Once I opened the project from the UNC path it built just fine.
you can use sorted() method if you want it to return the sorted list. It's more convenient.
l1 = []
n = int(input())
for i in range(n):
user = int(input())
l1.append(user)
sorted(l1,reverse=True)
list.sort() method modifies the list in-place and returns None.
if you still want to use sort you can do this.
l1 = []
n = int(input())
for i in range(n):
user = int(input())
l1.append(user)
l1.sort(reverse=True)
print(l1)
Application class is the object that has the full lifecycle of your application. It is your highest layer as an application. example possible usages:
You can add what you need when the application is started by overriding onCreate in the Application class.
store global variables that jump from Activity to Activity. Like Asynctask.
etc
There are lots of differences between ISO 8601 and RFC 3339. Here is some examples to give you an idea:
2020-12-09T16:09:53+00:00
is a date time value that is compliant both both standards.
2020-12-09 16:09:53+00:00
uses a space to separate the date and time. This is allowed by RFC 3339 but not allowed by ISO 8601.
2020-12-09T16:09:53-00:00
has a negative sign in the time offset. This is allowed by RFC 3339 but not allowed by ISO 8601.
20201209T160953Z
omits the hyphens. This is allowed by ISO 8601 but not allowed by RFC 3339.
ISO 8601 allows for things like ordinal dates such as 2020-344
which represents the 344th day of year 2020. RFC 3339 doesn't allow for that.
For your questions:
Is one just an extension?
No. As shown above each standard supports syntax variations not supported by the the other standard. So one syntax is not a superset or an extension of the other.
Should I use one over the other?
Of course this depends on your scenario. A safe general strategy is to generate date time strings that are valid by both standards.
Another good general strategy is to use an existing standard library for parsing/formatting date time strings and not write custom implementations unless you are addressing a genuinely custom scenario.
Do I really need to care that bad?
Well, that's up to you. Most regular developers who deal with date time strings should have a high level understanding but don't need to dive into the details.
If you want to pass the data using POST instead of GET, you can do it using a combination of PHP and JavaScript, like this:
function formSubmit(house_number)
{
document.forms[0].house_number.value = house_number;
document.forms[0].submit();
}
Then in PHP you loop through the house-numbers, and create links to the JavaScript function, like this:
<form action="house.php" method="POST">
<input type="hidden" name="house_number" value="-1">
<?php
foreach ($houses as $id => name)
{
echo "<a href=\"javascript:formSubmit($id);\">$name</a>\n";
}
?>
</form>
That way you just have one form whose hidden variable(s) get modified according to which link you click on. Then JavasScript submits the form.
This is a way to do it with a while loop:
def reverse(s):
t = -1
s2 = ''
while abs(t) < len(s) + 1:
s2 = s2 + s[t]
t = t - 1
return s2
I did it! :)
Works fine without C++11
class MyClass {
typedef std::map<std::string, int> MyMap;
struct T {
const char* Name;
int Num;
operator MyMap::value_type() const {
return std::pair<std::string, int>(Name, Num);
}
};
static const T MapPairs[];
static const MyMap TheMap;
};
const MyClass::T MyClass::MapPairs[] = {
{ "Jan", 1 }, { "Feb", 2 }, { "Mar", 3 }
};
const MyClass::MyMap MyClass::TheMap(MapPairs, MapPairs + 3);
Last or next date, week, month & year calculation. It might be helpful for anyone.
Current Date:
select curdate();
Yesterday:
select subdate(curdate(), 1)
Tomorrow:
select adddate(curdate(), 1)
Last 1 week:
select between subdate(curdate(), 7) and subdate(curdate(), 1)
Next 1 week:
between adddate(curdate(), 7) and adddate(curdate(), 1)
Last 1 month:
between subdate(curdate(), 30) and subdate(curdate(), 1)
Next 1 month:
between adddate(curdate(), 30) and adddate(curdate(), 1)
Current month:
subdate(curdate(),day(curdate())-1) and last_day(curdate());
Last 1 year:
between subdate(curdate(), 365) and subdate(curdate(), 1)
Next 1 year:
between adddate(curdate(), 365) and adddate(curdate(), 1)
jQuery used to ONLY have the callback functions for success
and error
and complete
.
Then, they decided to support promises with the jqXHR object and that's when they added .done()
, .fail()
, .always()
, etc... in the spirit of the promise API. These new methods serve much the same purpose as the callbacks but in a different form. You can use whichever API style works better for your coding style.
As people get more and more familiar with promises and as more and more async operations use that concept, I suspect that more and more people will move to the promise API over time, but in the meantime jQuery supports both.
The .success()
method has been deprecated in favor of the common promise object method names.
From the jQuery doc, you can see how various promise methods relate to the callback types:
jqXHR.done(function( data, textStatus, jqXHR ) {}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {}); An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.
In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.
jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {}); Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.
If you want to code in a way that is more compliant with the ES6 Promises standard, then of these four options you would only use .then()
.
my recipe:
datatable declaration:
defaultContent: "<button type='button'....
events:
$('#usersDataTable tbody').on( 'click', '.delete-user-btn', function () { var user_data = table.row( $(this).parents('tr') ).data(); }
The ANSI SQL/cross-platform way is to use the INFORMATION_SCHEMA, which was specifically designed to query meta data about objects within SQL databases.
if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'Scores' AND TABLE_SCHEMA = 'dbo')
drop table dbo.Scores;
Most modern RDBMS servers provide, at least, basic INFORMATION_SCHEMA support, including: MySQL, Postgres, Oracle, IBM DB2, and Microsoft SQL Server 7.0 (and greater).
The %
operator is for integers. You're looking for the fmod()
function.
#include <cmath>
int main()
{
double x = 6.3;
double y = 2.0;
double z = std::fmod(x,y);
}
The thing that works best for me when that happens is :
Create a new eclipse project(JAVA)
Take your source file (contents of the src folder!!!) and drag from finder and drop into the src folder in eclipse IDE
Make sure you add your external jars and stuff and tada you're done!!
Simple function for splitting a vector by simply using indexes - no need to over complicate this
vsplit <- function(v, n) {
l = length(v)
r = l/n
return(lapply(1:n, function(i) {
s = max(1, round(r*(i-1))+1)
e = min(l, round(r*i))
return(v[s:e])
}))
}
If you want to capture click on everything then do
$("*").click(function(){
//code here
}
I use this for selector: http://api.jquery.com/all-selector/
This is used for handling clicks: http://api.jquery.com/click/
And then use http://api.jquery.com/event.preventDefault/
To stop normal clicking actions.
to escape non-alphanumeric characters of string variables, including dots, you could use re.escape
:
import re
expression = 'whatever.v1.dfc'
escaped_expression = re.escape(expression)
print(escaped_expression)
output:
whatever\.v1\.dfc
you can use the escaped expression to find/match the string literally.
Put the varible in an array and Use a for Loop to assign the same value to multiple variables.
myArray[moveUP, moveDown, moveLeft];
for(var i = 0; i < myArray.length; i++){
myArray[i] = true;
}
The mz
module provides promisified versions of the core node library. Using them is simple. First install the library...
npm install mz
Then...
const fs = require('mz/fs');
fs.readFile('./Index.html').then(contents => console.log(contents))
.catch(err => console.error(err));
Alternatively you can write them in asynchronous functions:
async function myReadfile () {
try {
const file = await fs.readFile('./Index.html');
}
catch (err) { console.error( err ) }
};
It's usually just easier to skip the mouse altogether--or it would be if Sublime didn't mess up multiselect when word wrapping. Here's the official documentation on using the keyboard and mouse for multiple selection. Since it's a bit spread out, I'll summarize it:
Where shortcuts are different in Sublime Text 3, I've made a note. For v3, I always test using the latest dev build; if you're using the beta build, your experience may be different.
If you lose your selection when switching tabs or windows (particularly on Linux), try using Ctrl + U to restore it.
Building blocks:
Combine as you see fit. For example:
Building blocks:
Combine as you see fit. For example:
On Yosemite and El Capitan, ^?? and ^?? are system keyboard shortcuts by default. If you want them to work in Sublime Text, you will need to change them:
System Preferences
.Shortcuts
tab.Mission Control
in the left listbox.Mission Control
and Application windows
(or disable them). I use ^?? and ^??. They defaults are ^? and ^?; adding ^ to those shortcuts triggers the same actions, but slows the animations.In case you're not familiar with Mac's keyboard symbols:
This seems a bit silly to me, but the only reason I can think of is that object arguments in method parameters already are optional in a way - they can be null. Therefore forcing someone to take an existing object and wrap it in an optional is sort of pointless.
That being said, chaining methods together that take/return optionals is a reasonable thing to do, e.g. Maybe monad.
You can print Unicode objects as well, you don't need to do str() around it.
Assuming you really want a str:
When you do str(u'\u2013') you are trying to convert the Unicode string to a 8-bit string. To do this you need to use an encoding, a mapping between Unicode data to 8-bit data. What str() does is that is uses the system default encoding, which under Python 2 is ASCII. ASCII contains only the 127 first code points of Unicode, that is \u0000 to \u007F1. The result is that you get the above error, the ASCII codec just doesn't know what \u2013 is (it's a long dash, btw).
You therefore need to specify which encoding you want to use. Common ones are ISO-8859-1, most commonly known as Latin-1, which contains the 256 first code points; UTF-8, which can encode all code-points by using variable length encoding, CP1252 that is common on Windows, and various Chinese and Japanese encodings.
You use them like this:
u'\u2013'.encode('utf8')
The result is a str containing a sequence of bytes that is the uTF8 representation of the character in question:
'\xe2\x80\x93'
And you can print it:
>>> print '\xe2\x80\x93'
–
This workflow works best for me:
git checkout -b develop
...make some changes...
...notice master has been updated...
...commit changes to develop...
git checkout master
git pull
...bring those changes back into develop...
git checkout develop
git rebase master
...make some more changes...
...commit them to develop...
...merge them into master...
git checkout master
git pull
git merge develop
If your jenkins is running as service instead of process you should stop it first using
sudo service jenkins stop
After stopping it you can follow the normal flow of removing it using commands respective to your linux flavour
For centos it will be
sudo yum remove jenkins
For ubuntu it will
sudo apt-get remove --purge jenkins
I hope this will solve your issue.
Indeed there is an API to search google programmatically. The API is called google custom search. For using this API, you will need an Google Developer API key and a cx key. A simple procedure for accessing google search from java program is explained in my blog.
Now dead, here is the Wayback Machine link.
Good news, PyDrive has first class support on CoLab! PyDrive is a wrapper for the Google Drive python client. Here is an example on how you would download ALL files from a folder, similar to using glob
+ *
:
!pip install -U -q PyDrive
import os
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
# 1. Authenticate and create the PyDrive client.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
# choose a local (colab) directory to store the data.
local_download_path = os.path.expanduser('~/data')
try:
os.makedirs(local_download_path)
except: pass
# 2. Auto-iterate using the query syntax
# https://developers.google.com/drive/v2/web/search-parameters
file_list = drive.ListFile(
{'q': "'1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk' in parents"}).GetList()
for f in file_list:
# 3. Create & download by id.
print('title: %s, id: %s' % (f['title'], f['id']))
fname = os.path.join(local_download_path, f['title'])
print('downloading to {}'.format(fname))
f_ = drive.CreateFile({'id': f['id']})
f_.GetContentFile(fname)
with open(fname, 'r') as f:
print(f.read())
Notice that the arguments to drive.ListFile
is a dictionary that coincides with the parameters used by Google Drive HTTP API (you can customize the q
parameter to be tuned to your use-case).
Know that in all cases, files/folders are encoded by id's (peep the 1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk) on Google Drive. This requires that you search Google Drive for the specific id corresponding to the folder you want to root your search in.
For example, navigate to the folder "/projects/my_project/my_data"
that
is located in your Google Drive.
See that it contains some files, in which we want to download to CoLab. To get the id of the folder in order to use it by PyDrive, look at the url and extract the id parameter. In this case, the url corresponding to the folder was:
Where the id is the last piece of the url: 1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk.
Yaur: Although what you have copied and pasted is good advice, this does not mean that it is impossible to change the source element of an HTML5 video element elegantly, even in IE9 (or IE8 for that matter).(This solution does NOT involve replacing the entire video element, as it is bad coding practice).
A complete solution to changing/switching videos in HTML5 video tags via javascript can be found here and is tested in all HTML5 browser (Firefox, Chrome, Safari, IE9, etc).
If this helps, or if you're having trouble, please let me know.
Here you've got a very detailed explanation of their differences
http://kyleschaeffer.com/development/css-font-size-em-vs-px-vs-pt-vs/
The jist of it (from source)
Pixels are fixed-size units that are used in screen media (i.e. to be read on the computer screen). Pixel stands for "picture element" and as you know, one pixel is one little "square" on your screen. Points are traditionally used in print media (anything that is to be printed on paper, etc.). One point is equal to 1/72 of an inch. Points are much like pixels, in that they are fixed-size units and cannot scale in size.
You can use this on any element where onclick works:
onclick="window.open('some.htm','_blank');"
Action
is a Type of Delegate provided by the .NET framework. The Action
points to a method with no parameters and does not return a value.
() =>
is lambda expression syntax. Lambda expressions are not of Type Delegate
. Invoke requires Delegate
so Action
can be used to wrap the lambda expression and provide the expected Type
to Invoke()
Invoke
causes said Action
to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions
. For example, if one tries to set the Rtf
property on a RichTextBox
when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid
exception will be thrown. Check Control.InvokeRequired
before calling Invoke.
BeginInvoke
is the Asynchronous version of Invoke
. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.
I finally figured out, it's because the Hibernate is using slf4j log facade now, to bridge to log4j, you need to put log4j and slf4j-log4j12 jars to your lib and then the log4j properties will take control Hibernate logs.
My pom.xml setting looks as below:
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
Old question, but here's another explanation of the problem. You'll get this error even if you have strongly typed views and aren't using ViewData to create your dropdown list. The reason for the error can becomes clear when you look at the MVC source:
// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
selectList = htmlHelper.GetSelectData(name);
usedViewData = true;
}
So if you have something like:
@Html.DropDownList("MyList", Model.DropDownData, "")
And Model.DropDownData
is null, MVC looks through your ViewData for something named MyList
and throws an error if there's no object in ViewData with that name.
Notwithstanding the other answers recommending List<T>
, you'll want to use arrays when handling:
UPDATE:
This answer turned out to be wrong. Please see the comments for the real explanation.
Most of you question has been answered, but as for the final part:
What would be the danger of both copies coming through?
None really. You'd waste bandwidth, might add some milliseconds downloading a second useless copy, but there's not actual harm if they both come through. You should, of course, avoid this using the techniques mentioned above.
The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).
You can use the GUI to do the installation, or you can script the installation of msbuild:
vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet
Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:
You can find documentation about the other available CLI switches here.
The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet
there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin
.
If you don't see them there, try running without --quiet
to see any error messages that may occur during installation.
Kind of, use the XmlAttribute
instead of XmlElement
, but it won't look like what you want. It will look like the following:
<SomeModel SomeStringElementName="testData">
</SomeModel>
The only way I can think of to achieve what you want (natively) would be to have properties pointing to objects named SomeStringElementName and SomeInfoElementName where the class contained a single getter named "value". You could take this one step further and use DataContractSerializer so that the wrapper classes can be private. XmlSerializer won't read private properties.
// TODO: make the class generic so that an int or string can be used.
[Serializable]
public class SerializationClass
{
public SerializationClass(string value)
{
this.Value = value;
}
[XmlAttribute("value")]
public string Value { get; }
}
[Serializable]
public class SomeModel
{
[XmlIgnore]
public string SomeString { get; set; }
[XmlIgnore]
public int SomeInfo { get; set; }
[XmlElement]
public SerializationClass SomeStringElementName
{
get { return new SerializationClass(this.SomeString); }
}
}
Simplest definition of the Coalesce() function could be:
Coalesce() function evaluates all passed arguments then returns the value of the first instance of the argument that did not evaluate to a NULL.
Note: it evaluates ALL parameters, i.e. does not skip evaluation of the argument(s) on the right side of the returned/NOT NULL parameter.
Syntax:
Coalesce(arg1, arg2, argN...)
Beware: Apart from the arguments that evaluate to NULL, all other (NOT-NULL) arguments must either be of same datatype or must be of matching-types (that can be "implicitly auto-converted" into a compatible datatype), see examples below:
PRINT COALESCE(NULL, ('str-'+'1'), 'x') --returns 'str-1, works as all args (excluding NULLs) are of same VARCHAR type.
--PRINT COALESCE(NULL, 'text', '3', 3) --ERROR: passed args are NOT matching type / can't be implicitly converted.
PRINT COALESCE(NULL, 3, 7.0/2, 1.99) --returns 3.0, works fine as implicit conversion into FLOAT type takes place.
PRINT COALESCE(NULL, '1995-01-31', 'str') --returns '2018-11-16', works fine as implicit conversion into VARCHAR occurs.
DECLARE @dt DATE = getdate()
PRINT COALESCE(NULL, @dt, '1995-01-31') --returns today's date, works fine as implicit conversion into DATE type occurs.
--DATE comes before VARCHAR (works):
PRINT COALESCE(NULL, @dt, 'str') --returns '2018-11-16', works fine as implicit conversion of Date into VARCHAR occurs.
--VARCHAR comes before DATE (does NOT work):
PRINT COALESCE(NULL, 'str', @dt) --ERROR: passed args are NOT matching type, can't auto-cast 'str' into Date type.
HTH
In the documentation it's stated: Use the prefix option together with the global option:
The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary. On Unix systems, it's one level up, since node is typically installed at {prefix}/bin/node rather than {prefix}/node.exe.
When the global flag is set, npm installs things into this prefix. When it is not set, it uses the root of the current package, or the current working directory if not in a package already.
(Emphasis by them)
So in your root directory you could install with
npm install --prefix <path/to/prefix_folder> -g
and it will install the node_modules
folder into the folder
<path/to/prefix_folder>/lib/node_modules
Hi if you are having dropdownlist like this
<select id="testID">
<option value="1">Value1</option>
<option value="2">Value2</option>
<option value="3">Value3</option>
<option value="4">Value4</option>
<option value="5">Value5</option>
<option value="6">Value6</option>
</select>
<input type="button" value="Get dropdown selected Value" onclick="getHTML();">
after giving id to dropdownlist you just need to add jquery code like this
function getHTML()
{
var display=$('#testID option:selected').html();
alert(display);
}
In bash
, provided you files names have no spaces:
cd /home/webapps/project1/folder1
for f in *.csv
do
cp -v "$f" /home/webapps/project1/folder2/"${f%.csv}"$(date +%m%d%y).csv
done
Have the style for the parent div and the child divs' set as following. It worked for my case, hope it helps you as well..
<div id="parentDiv">
<div id="backdrop"><img alt="" src='/backdrop.png' /></div>
<div id="curtain" style="background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;"> </div>
</div>
in your JS:
document.getElementById('parentDiv').style.position = 'relative';
document.getElementById('backdrop').style.position = 'absolute';
document.getElementById('curtain').style.position = 'absolute';
document.getElementById('curtain').style.zIndex= '2';//this number has to be greater than the zIndex of 'backdrop' if you are setting any
or in your CSS as in this working example:::
#parentDiv{_x000D_
background: yellow;_x000D_
height: 500px;_x000D_
width: 500px;_x000D_
position: relative;_x000D_
}_x000D_
#backdrop{_x000D_
background: red;_x000D_
height: 300px;_x000D_
width: 300px;_x000D_
position: absolute;_x000D_
}_x000D_
#curtain{_x000D_
background: green;_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
position: absolute;_x000D_
z-index: 2;_x000D_
margin: 100px 0px 150px 100px;_x000D_
}
_x000D_
<div id="parentDiv"><h2>_x000D_
THIS IS PARENT DIV_x000D_
</h2>_x000D_
<div id="backdrop"><h4>_x000D_
THIS IS BACKDROP DIV_x000D_
</h4></div>_x000D_
<div id="curtain"><h6>_x000D_
THIS IS CURTAIN DIV_x000D_
</h6></div>_x000D_
</div>
_x000D_
If you only need to prevent line-breaks on space characters, you can use
entities between words:
No line break
instead of
<span style="white-space:nowrap">No line break</span>
try this html code
<md-input #myInput placeholder="Item name..." [(ngModel)]="name"></md-input>
<div *ngFor="let item of filteredItems | search: name">
{{item.name}}
</div>
use search pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {
transform(value: any, args?: any): any {
if(!value)return null;
if(!args)return value;
args = args.toLowerCase();
return value.filter(function(item){
return JSON.stringify(item).toLowerCase().includes(args);
});
}
}
A lot of the code here was very helpful, but I cleaned it up for my purposes and added some tests. Here's what I ended up with:
using System;
using System.Linq;
using System.Net;
using System.Web;
public class RequestHelpers
{
public static string GetClientIpAddress(HttpRequestBase request)
{
try
{
var userHostAddress = request.UserHostAddress;
// Attempt to parse. If it fails, we catch below and return "0.0.0.0"
// Could use TryParse instead, but I wanted to catch all exceptions
IPAddress.Parse(userHostAddress);
var xForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(xForwardedFor))
return userHostAddress;
// Get a list of public ip addresses in the X_FORWARDED_FOR variable
var publicForwardingIps = xForwardedFor.Split(',').Where(ip => !IsPrivateIpAddress(ip)).ToList();
// If we found any, return the last one, otherwise return the user host address
return publicForwardingIps.Any() ? publicForwardingIps.Last() : userHostAddress;
}
catch (Exception)
{
// Always return all zeroes for any failure (my calling code expects it)
return "0.0.0.0";
}
}
private static bool IsPrivateIpAddress(string ipAddress)
{
// http://en.wikipedia.org/wiki/Private_network
// Private IP Addresses are:
// 24-bit block: 10.0.0.0 through 10.255.255.255
// 20-bit block: 172.16.0.0 through 172.31.255.255
// 16-bit block: 192.168.0.0 through 192.168.255.255
// Link-local addresses: 169.254.0.0 through 169.254.255.255 (http://en.wikipedia.org/wiki/Link-local_address)
var ip = IPAddress.Parse(ipAddress);
var octets = ip.GetAddressBytes();
var is24BitBlock = octets[0] == 10;
if (is24BitBlock) return true; // Return to prevent further processing
var is20BitBlock = octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31;
if (is20BitBlock) return true; // Return to prevent further processing
var is16BitBlock = octets[0] == 192 && octets[1] == 168;
if (is16BitBlock) return true; // Return to prevent further processing
var isLinkLocalAddress = octets[0] == 169 && octets[1] == 254;
return isLinkLocalAddress;
}
}
And here are some NUnit tests against that code (I'm using Rhino Mocks to mock the HttpRequestBase, which is the M<HttpRequestBase> call below):
using System.Web;
using NUnit.Framework;
using Rhino.Mocks;
using Should;
[TestFixture]
public class HelpersTests : TestBase
{
HttpRequestBase _httpRequest;
private const string XForwardedFor = "X_FORWARDED_FOR";
private const string MalformedIpAddress = "MALFORMED";
private const string DefaultIpAddress = "0.0.0.0";
private const string GoogleIpAddress = "74.125.224.224";
private const string MicrosoftIpAddress = "65.55.58.201";
private const string Private24Bit = "10.0.0.0";
private const string Private20Bit = "172.16.0.0";
private const string Private16Bit = "192.168.0.0";
private const string PrivateLinkLocal = "169.254.0.0";
[SetUp]
public void Setup()
{
_httpRequest = M<HttpRequestBase>();
}
[TearDown]
public void Teardown()
{
_httpRequest = null;
}
[Test]
public void PublicIpAndNullXForwardedFor_Returns_CorrectIp()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(null);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(GoogleIpAddress);
}
[Test]
public void PublicIpAndEmptyXForwardedFor_Returns_CorrectIp()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(string.Empty);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(GoogleIpAddress);
}
[Test]
public void MalformedUserHostAddress_Returns_DefaultIpAddress()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(MalformedIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(null);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(DefaultIpAddress);
}
[Test]
public void MalformedXForwardedFor_Returns_DefaultIpAddress()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(MalformedIpAddress);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(DefaultIpAddress);
}
[Test]
public void SingleValidPublicXForwardedFor_Returns_XForwardedFor()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(MicrosoftIpAddress);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(MicrosoftIpAddress);
}
[Test]
public void MultipleValidPublicXForwardedFor_Returns_LastXForwardedFor()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(GoogleIpAddress + "," + MicrosoftIpAddress);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(MicrosoftIpAddress);
}
[Test]
public void SinglePrivateXForwardedFor_Returns_UserHostAddress()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(Private24Bit);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(GoogleIpAddress);
}
[Test]
public void MultiplePrivateXForwardedFor_Returns_UserHostAddress()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
const string privateIpList = Private24Bit + "," + Private20Bit + "," + Private16Bit + "," + PrivateLinkLocal;
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(privateIpList);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(GoogleIpAddress);
}
[Test]
public void MultiplePublicXForwardedForWithPrivateLast_Returns_LastPublic()
{
// Arrange
_httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
const string privateIpList = Private24Bit + "," + Private20Bit + "," + MicrosoftIpAddress + "," + PrivateLinkLocal;
_httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(privateIpList);
// Act
var ip = RequestHelpers.GetClientIpAddress(_httpRequest);
// Assert
ip.ShouldEqual(MicrosoftIpAddress);
}
}
This may be interesting for ppl using Primefaces (which uses CLEditor):
document.getElementById('form:somecontainer:editor')
.getElementsByTagName('iframe')[0].contentWindow
.document.onclick = function(){//do something}
I basically just took the answer from Travelling Tech Guy and changed the selection a bit .. ;)
You need to specify workseet. Change line
If Worksheet.Cells(i, 1).Value = "X" Then
to
If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then
UPD:
Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):
Sub LastRowInOneColumn()
Dim LastRow As Long
Dim i As Long, j As Long
'Find the last used row in a Column: column A in this example
With Worksheets("Sheet2")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
MsgBox (LastRow)
'first row number where you need to paste values in Sheet1'
With Worksheets("Sheet1")
j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
For i = 1 To LastRow
With Worksheets("Sheet2")
If .Cells(i, 1).Value = "X" Then
.Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
j = j + 1
End If
End With
Next i
End Sub
Joblib https://joblib.readthedocs.io supports caching functions in the Memoize pattern. Mostly, the idea is to cache computationally expensive functions.
>>> from joblib import Memory
>>> mem = Memory(cachedir='/tmp/joblib')
>>> import numpy as np
>>> square = mem.cache(np.square)
>>>
>>> a = np.vander(np.arange(3)).astype(np.float)
>>> b = square(a)
________________________________________________________________________________
[Memory] Calling square...
square(array([[ 0., 0., 1.],
[ 1., 1., 1.],
[ 4., 2., 1.]]))
___________________________________________________________square - 0...s, 0.0min
>>> c = square(a)
You can also do fancy things like using the @memory.cache decorator on functions. The documentation is here: https://joblib.readthedocs.io/en/latest/generated/joblib.Memory.html
You could also do this through storyboard. In the attribute inspector of the navigation item of the previous controller you could set " " in the Back button field. Refer Image below. Replace "Your Title here" to " ". By doing this you will achieve the desired result. You don't need to mess with the 'Title' anymore.
Programmatically you could use
[self.navigationItem.backBarButtonItem setTitle:@" "];
where self refers to the controller which pushes your desired View controller.
Sample Before, After Navigation bar
Before
After
e.target
is what triggers the event dispatcher to trigger and e.currentTarget
is what you assigned your listener to.
The best move is to just nest a flexbox inside of a flexbox. All you have to do is give the child align-items: center
. This will vertically align the text inside of its parent.
// Assuming a horizontally centered row of items for the parent but it doesn't have to be
.parent {
align-items: center;
display: flex;
justify-content: center;
}
.child {
display: flex;
align-items: center;
}
[Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:
extension=php_ldap.dll
Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin Restart Apache. You can now use functions of the LDAP Module!
In OS X Mavericks running Sublime Text 2 the following worked for me.
sudo ln -s /Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin/subl /usr/bin/subl
Its handy to locate the file in the finder and drag and drop that into the terminal window so you can be sure the path is the correct one, I'm not a huge terminal user so this was more comfortable for me. then you can go to the start of the path and start adding in the other parts like the shorthand UNIX commands. Hope this helps
This now works as they've made a release in version 23.2, as stated in this post. Quoting the official blogpost
This release brings an exciting new feature to the LayoutManager API: auto-measurement! This allows a RecyclerView to size itself based on the size of its contents. This means that previously unavailable scenarios, such as using WRAP_CONTENT for a dimension of the RecyclerView, are now possible. You’ll find all built in LayoutManagers now support auto-measurement.
From Eclipse Newsgroup:
The warning about the source property is new with Tomcat 6.0.16 and may be ignored. WTP adds a "source" attribute to identify which project in the workspace is associated with the context. The fact that the Context object in Tomcat has no corresponding source property doesn't cause any problems.
I realize that this doesn't answer how to get rid of the warning, but I hope it helps.
your line raising the error is here:
comment = Comment.objects.get(pk=comment_id)
you try to access a non-existing comment.
from django.shortcuts import get_object_or_404
comment = get_object_or_404(Comment, pk=comment_id)
Instead of having an error on your server, your user will get a 404 meaning that he tries to access a non existing resource.
Ok up to here I suppose you are aware of this.
Some users (and I'm part of them) let tabs running for long time, if users are authorized to delete data, it may happens. A 404 error may be a better error to handle a deleted resource error than sending an email to the admin.
Other users go to addresses from their history, (same if data have been deleted since it may happens).
Use Bat To Exe Converter to do this
http://download.cnet.com/Bat-To-Exe-Converter/3000-2069_4-10555897.html
(Choose Direct Download Link)
1 - Open Bat to Exe Converter, select your Bat file.
2 - In Option menu select "Invisible Application", then press compile button.
Done!
The HTML specification never specifies any content formats. That's not its job. There's plenty of standards organizations that are more qualified than the W3C to specify video formats.
That's what content negotiation is for.
<img>
element.<style>
element.<script>
element.<object>
and embed
elements.<audio>
element.Why should it specify one for the <video>
element?
Use render method:
<Route exact path="/details/:id" render={(props)=>{
<DetailsPage id={props.match.params.id}/>
}} />
And you should be able to access the id using:
this.props.id
Inside the DetailsPage component
There are different eclipse plugins available to manage Tomcat server and create war file.
For example you can use tomcatPlugin. It permits to start/stop and build the war simply. You can read this tutorial.
You can use urllib2
import urllib2
content = urllib2.urlopen(some_url).read()
print content
Also you can use httplib
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK
or the requests library
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200
A small improvement: above solutions will not remove leading or trailing spaces in the actual String. It's better to call trim before calling split. Instead of this,
String[] animalsArray = animals.split("\\s*,\\s*");
use
String[] animalsArray = animals.trim().split("\\s*,\\s*");
Here is my solution for this:
def calc_age_months(from_date, to_date):
from_date = time.strptime(from_date, "%Y-%m-%d")
to_date = time.strptime(to_date, "%Y-%m-%d")
age_in_months = (to_date.tm_year - from_date.tm_year)*12 + (to_date.tm_mon - from_date.tm_mon)
if to_date.tm_mday < from_date.tm_mday:
return age_in_months -1
else
return age_in_months
This will handle some edge cases as well where the difference in months between 31st Dec 2018 and 1st Jan 2019 will be zero (since the difference is only a day).
From API 25.3.0 it was introduced the method setSelectedItemId(int id)
which lets you mark an item as selected as if it was tapped.
From docs:
Set the selected menu item ID. This behaves the same as tapping on an item.
Code example:
BottomNavigationView bottomNavigationView;
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(myNavigationItemListener);
bottomNavigationView.setSelectedItemId(R.id.my_menu_item_id);
IMPORTANT
You MUST have already added all items to the menu (in case you do this programmatically) and set the Listener before calling setSelectedItemId(I believe you want the code in your listener to run when you call this method). If you call setSelectedItemId before adding the menu items and setting the listener nothing will happen.
Load image:
BufferedImage bufferedImage = ImageIO.read(file);
Resize it:
private BufferedImage resizeAndCrop(BufferedImage bufferedImage, Integer width, Integer height) {
Mode mode = (double) width / (double) height >= (double) bufferedImage.getWidth() / (double) bufferedImage.getHeight() ? Scalr.Mode.FIT_TO_WIDTH
: Scalr.Mode.FIT_TO_HEIGHT;
bufferedImage = Scalr.resize(bufferedImage, Scalr.Method.ULTRA_QUALITY, mode, width, height);
int x = 0;
int y = 0;
if (mode == Scalr.Mode.FIT_TO_WIDTH) {
y = (bufferedImage.getHeight() - height) / 2;
} else if (mode == Scalr.Mode.FIT_TO_HEIGHT) {
x = (bufferedImage.getWidth() - width) / 2;
}
bufferedImage = Scalr.crop(bufferedImage, x, y, width, height);
return bufferedImage;
}
Using Scalr library:
<dependency>
<groupId>org.imgscalr</groupId>
<artifactId>imgscalr-lib</artifactId>
<version>4.2</version>
</dependency>
In my case easiest way to get browser headers was to use php. It appends headers to file and prints them to test page.
<?php
$fp = fopen('m:/temp/requests.txt', 'a');
$time = $_SERVER['REQUEST_TIME'];
fwrite($fp, $time "\n");
echo "$time.<br>";
foreach (getallheaders() as $name => $value) {
$cur_hd = "$name: $value\n";
fwrite($fp, $cur_hd);
echo "$cur_hd.<br>";
}
fwrite($fp, "***\n");
fclose($fp);
?>
So the issue is in your array declaration you are declaring an empty array with the empty curly braces{} instead of an array that allows slots.
Roughly speaking, there can be three types of inputs :
1. int array[] = null; #Does not point to any memory locations so is a null arrau
2. int array[] = {) which is sort of equivalent to int array[] = new int[0];
3. int array[] = new int[n] where n is some number indicating the number of
memory locations in the array
You can do it by using a constructor, like this:
struct Date
{
int day;
int month;
int year;
Date()
{
day=0;
month=0;
year=0;
}
};
or like this:
struct Date
{
int day;
int month;
int year;
Date():day(0),
month(0),
year(0){}
};
In your case bar.c is undefined,and its value depends on the compiler (while a and b were set to true).
Every time you execute
Random random = new Random (15);
It does not matter if you execute it millions of times, you will always use the same seed.
If you use
Random random = new Random ();
You get different random number sequence, if a hacker guesses the seed and your algorithm is related to the security of your system - your algorithm is broken. I you execute mult. In this constructor the seed is specified by the system clock and if several instances are created in a very short period of time (milliseconds) it is possible that they may have the same seed.
If you need safe random numbers you must use the class
System.Security.Cryptography.RNGCryptoServiceProvider
public static int Next(int min, int max)
{
if(min >= max)
{
throw new ArgumentException("Min value is greater or equals than Max value.");
}
byte[] intBytes = new byte[4];
using(RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
rng.GetNonZeroBytes(intBytes);
}
return min + Math.Abs(BitConverter.ToInt32(intBytes, 0)) % (max - min + 1);
}
Usage:
int randomNumber = Next(1,100);
I solved with this loop, where repeat is an integer that represents the loops's number
repeat=10
for n in $(seq $repeat);
do
command1
command2
done
I faced a similar problem but in my case I was trying to install Visual C++ Redistributable for Visual Studio 2015 Update 1 on Windows Server 2012 R2. However the root cause should be the same.
In short, you need to install the prerequisites of KB2999226.
In more details, the installation log I got stated that the installation for Windows Update KB2999226 failed. According to the Microsoft website here:
Prerequisites To install this update, you must have April 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 (2919355) installed in Windows 8.1 or Windows Server 2012 R2. Or, install Service Pack 1 for Windows 7 or Windows Server 2008 R2. Or, install Service Pack 2 for Windows Vista and for Windows Server 2008.
After I have installed April 2014 on my Windows Server 2012 R2, I am able to install the Visual C++ Redistributable correctly.
os._exit()
:
exit(0)
:
exit(1)
:
sys.exit()
:
quit()
:
Basically they all do the same thing, however, it also depends on what you are doing it for.
I don't think you left anything out and I would recommend getting used to quit()
or exit()
.
You would use sys.exit()
and os._exit()
mainly if you are using big files or are using python to control terminal.
Otherwise mainly use exit()
or quit()
.
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
NSURL *url = [NSURL URLWithString:@"itms-services://?action=download-manifest&url=https://xxxxxx.com/rest/images/apps/ipa/dev/xyz.plist"]];
[[UIApplication sharedApplication] openURL:url];
openUrl method was deprecated.
[[UIApplication sharedApplication] openURL: url options:@{} completionHandler:nil];
This method latest openUrl method and it will display prompt dialog.The dialog will show
xxxxxx.com would like to install "YOUR_APP_NAME"
this messages. If you click the "install" button application will close and ipa will download.
I know it seems too late, but it may help others in future.
I face the same error and the problem was that spring boot did not read my services package so add:
@ComponentScan(basePackages = {"com.example.demo.Services"})
(you have to specify your own path to the services package) and in the class demoApplication
(class that have main function) and for service interface must be annotated @Service
and the class that implement the service interface must be annotated with @Component
, then autowired the service interface.
This was an issue for me years ago and I'd previously fixed it in Eclipse by excluding 1.7 from my projects, but it became an issue again for IntelliJ, which I recently installed. I fixed it by:
Uninstalling the JDK:
cd /Library/Java/JavaVirtualMachines
sudo rm -rf jdk1.8.0_45.jdk
(I had jdk1.8.0_45.jdk
installed; obviously you should uninstall whichever java version is listed in that folder. The offending files are located in that folder and should be deleted.)
Note that the next time you create a new project, or open an existing project, you will need to set the project SDK to point to the new JDK install. You also may still see this bug or have it creep back if you have JDK 1.7 installed in your JavaVirtualMachines folder (which is what I believe happened to me).
My solution is similar to those above but I have abstracted the gesture handling into an abstract class OnGestureRegisterListener.java
, which includes swipe, click and long click gestures.
OnGestureRegisterListener.java
public abstract class OnGestureRegisterListener implements View.OnTouchListener {
private final GestureDetector gestureDetector;
private View view;
public OnGestureRegisterListener(Context context) {
gestureDetector = new GestureDetector(context, new GestureListener());
}
@Override
public boolean onTouch(View view, MotionEvent event) {
this.view = view;
return gestureDetector.onTouchEvent(event);
}
public abstract void onSwipeRight(View view);
public abstract void onSwipeLeft(View view);
public abstract void onSwipeBottom(View view);
public abstract void onSwipeTop(View view);
public abstract void onClick(View view);
public abstract boolean onLongClick(View view);
private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
onLongClick(view);
super.onLongPress(e);
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
onClick(view);
return super.onSingleTapUp(e);
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight(view);
} else {
onSwipeLeft(view);
}
result = true;
}
}
else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom(view);
} else {
onSwipeTop(view);
}
result = true;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
}
And use it like so. Note that you can also easily pass in your View
parameter.
OnGestureRegisterListener onGestureRegisterListener = new OnGestureRegisterListener(this) {
public void onSwipeRight(View view) {
// Do something
}
public void onSwipeLeft(View view) {
// Do something
}
public void onSwipeBottom(View view) {
// Do something
}
public void onSwipeTop(View view) {
// Do something
}
public void onClick(View view) {
// Do something
}
public boolean onLongClick(View view) {
// Do something
return true;
}
};
Button button = findViewById(R.id.my_button);
button.setOnTouchListener(onGestureRegisterListener);
You can transform logical implication A => B
to NOT A or B
. This is one of the most basic laws of logic. In your case it is something like this:
SELECT *
FROM logs
WHERE pw='correct' AND (id>=800 OR success=1)
AND YEAR(timestamp)=2011
I also transformed NOT id<800
to id>=800
, which is also pretty basic.
int x = 0xFF; //your number - 11111111
How do I for example read a 3 bit integer value starting at the second bit
int y = x & ( 0x7 << 2 ) // 0x7 is 111
// and you shift it 2 to the left
In a Colab notebook you can do:
from IPython.display import Audio
Audio(waveform, Rate=16000)
In case anyone else comes across this in a search for an answer...
The test numbers listed in various places no longer work in the Sandbox. PayPal have the same checks in place now so that a card cannot be linked to more than one account.
Go here and get a number generated. Use any expiry date and CVV
https://ppmts.custhelp.com/app/answers/detail/a_id/750/
It's worked every time for me so far...
To get rid of the first column of NAs, you can do it with negative indexing (which removes indices from the R data set). For example:
output = matrix(1:6, 2, 3) # gives you a 2 x 3 matrix filled with the numbers 1 to 6
# output =
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6
output = output[,-1] # this removes column 1 for all rows
# output =
# [,1] [,2]
# [1,] 3 5
# [2,] 4 6
So you can just add output = output[,-1]
after the for loop in your original code.
This code works:
$(".ui-button-text").live(
'hover',
function (ev) {
if (ev.type == 'mouseover') {
$(this).addClass("ui-state-hover");
}
if (ev.type == 'mouseout') {
$(this).removeClass("ui-state-hover");
}
});
Simplification from the above Andrew's answer leads to this key theme to generate the half border.
theme (panel.border = element_blank(),
axis.line = element_line(color='black'))
You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:
lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)
Then you can get hold of the axes objects (an array of axes):
axes = lm.axes
After that you can tweak the axes properties
axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)
creates:
Make sure your eclipse.ini
file includes the following lines.
-vm
C:\path\to\64bit\java\bin\javaw.exe
My eclipse.ini
for example:
-startup
plugins/org.eclipse.equinox.launcher_1.1.1.R36x_v20101122_1400.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.2.R36x_v20101222
-product
org.eclipse.epp.package.java.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
-vm
C:\Program Files\Java\jdk1.6.0_32\bin\javaw.exe
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
Use OS and Eclipse both 64 bit or both 32 bit keep same and config eclipse.ini
.
Your eclipse.ini
file can be found in your eclipse folder.
Well your solution above depends on the image being a jpeg file. For a general solution i used
$img = $_POST['image'];
$img = substr(explode(";",$img)[1], 7);
file_put_contents('img.png', base64_decode($img));
You can try:
df[0] = df[0].str.strip()
or more specifically for all string columns
non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())
This can be achieved with greater cross-browser support than the accepted answer by using pseudo-elements as exemplified by this answer: https://stackoverflow.com/a/19818268/2602816
Static variables represent global state. That's hard to reason about and hard to test: if I create a new instance of an object, I can reason about its new state within tests. If I use code which is using static variables, it could be in any state - and anything could be modifying it.
I could go on for quite a while, but the bigger concept to think about is that the tighter the scope of something, the easier it is to reason about. We're good at thinking about small things, but it's hard to reason about the state of a million line system if there's no modularity. This applies to all sorts of things, by the way - not just static variables.
SQL Server is tuned to apply the filters before it applies aliases (because that usually produces faster results). You could do a nested select statement. Example:
SELECT Latitude FROM
(
SELECT Lat AS Latitude FROM poi_table
) A
WHERE Latitude < 500
I realize this may not be what you are looking for, because it makes your queries much more wordy. A more succinct approach would be to make a view that wraps your underlying table:
CREATE VIEW vPoi_Table AS
SELECT Lat AS Latitude FROM poi_table
Then you could say:
SELECT Latitude FROM vPoi_Table WHERE Latitude < 500
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
RPC is another key difference. Thrift generates code to implement RPC clients and servers wheres Protocol Buffers seems mostly designed as a data-interchange format alone.
If you are using the Spring Boot Maven Plugin, run:
mvn spring-boot:run -Dspring-boot.run.profiles=foo,bar
(https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-profiles.html)
It sounds like you want to list all the metrics?
SELECT Criteria1, Criteria2, Metric1 As Metric
FROM Table1
UNION ALL
SELECT Criteria1, Criteria2, Metric2 As Metric
FROM Table2
ORDER BY 1, 2
If you only want one Criteria1+Criteria2 combination, group them:
SELECT Criteria1, Criteia2, SUM(Metric) AS Metric
FROM (
SELECT Criteria1, Criteria2, Metric1 As Metric
FROM Table1
UNION ALL
SELECT Criteria1, Criteria2, Metric2 As Metric
FROM Table2
)
ORDER BY Criteria1, Criteria2
Since filter
returns a QuerySet
, you can use count to check how many results were returned. This is assuming you don't actually need the results.
num_results = User.objects.filter(email = cleaned_info['username']).count()
After looking at the documentation though, it's better to just call len on your filter if you are planning on using the results later, as you'll only be making one sql query:
A count() call performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).
num_results = len(user_object)
You can also try this handy online tool, which generates .vssettings
file for you.
I'm not sure this has been mentioned yet. But there is a lodash function for that. Snippet below where value is your attribute to sum is 'value'.
_.sumBy(objects, 'value');
_.sumBy(objects, function(o) { return o.value; });
Both will work.
Operating system commands have exit codes. Look for Linux exit codes to see some material on this. The shell uses the exit codes to decide if the program worked, had problems, or failed. There are some efforts to create standard (or at least commonly-used) exit codes. See this Advanced Shell Script posting.
On Windows,Close all the SQL Developer windows. Then You need to completely delete the SQL Developer and sqldeveloper folders located in user/AppData/Roaming. Finally, run the program, you will be prompted for new JDK.
Note that AppData is a hidden folder.
I finally got a very easy solution to this.
use these Support libraries in app level gradle,
compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.android.support:support-v4:26.0.2'
then create a directory named "font" inside the res folder
After that, reference that font from xml like this
<Button
android:id="@+id/btn_choose_employee"
android:layout_width="140dp"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:background="@drawable/rounded_red_btn"
android:onClick="btnEmployeeClickedAction"
android:text="@string/searching_jobs"
android:textAllCaps="false"
android:textColor="@color/white"
android:fontFamily="@font/times_new_roman_test"
/>
In this example, times_new_roman_test is a font ttf file from that font directory
You can use the <embed>
tag with the source of the file in the src
attribute. This uses the native browser PDF viewer.
<embed src="your_pdf_src" style="position:absolute; left: 0; top: 0;" width="100%" height="100%" type="application/pdf">
Live example:
<embed src="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" style="position:absolute; left: 0; top: 0;" width="100%" height="100%" type="application/pdf">
_x000D_
Loading the PDF inside a snippet won't work, since the frame into which the plugin is loading is sandboxed.
Tested in Chrome and Firefox. See it in action.
try
total.Text = DateTime.Now.ToString()
or
Dim theDate As DateTime = System.DateTime.Now
total.Text = theDate.ToString()
You declare Start
as an Integer
, while you are trying to put a DateTime
in it, which is not possible.
Possible solutions is put your dependencies in src/main/resources then in your pom :
<dependency>
groupId ...
artifactId ...
version ...
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/yourJar.jar</systemPath>
</dependency>
Note: system dependencies are not copied into resulted jar/war
(see How to include system dependencies in war built using maven)
Experience With: ASUS ZENFONE
If at all you have faced Missing Driver for Asus Zenfones Follow This Link (http://donandroid.com/how-to-install-adb-interface-drivers-windows-7-xp-vista-623)
I tried with
1) Killing and starting adb server at adb cmd.
2) Switching Usb Debugging on and Off and ...
This is What WORKED with me.
Step 1:Remove Connection with Device and Close Eclipse
Step 2:Navigate to C:/Users/User_name/.android/
Step 3:You Will Find adb_key
Step 4:Just delete it.
Step 5.Connect again and System will ask you Again.
Step 6.Ask Device to remember RSA Key when it Prompts. I think its done.
If you Face The Same Problem after couple of days, just disable and enable USB debugging
I was having the same issue in asp.NET razor C#
I had a ComboBox
filled with titles from an EventMessage
, and I wanted to show the Content of this message with its selected value to show it in a label or TextField
or any other Control
...
My ComboBox
was filled like this:
@Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { @class = "form-control", onchange = "$(this.form).submit();" })
In my EventController
I had a function to go to the page, in which I wanted to show my ComboBox
(which is of a different model type, so I had to use a partial view)?
The function to get from index to page in which to load the partial view:
public ActionResult EventDetail(int id)
{
Event eventOrg = db.Event.Include(s => s.Files).SingleOrDefault(s => s.EventID == id);
// EventOrg eventOrg = db.EventOrgs.Find(id);
if (eventOrg == null)
{
return HttpNotFound();
}
ViewBag.EventBerichten = GetEventBerichtenLijst(id);
ViewBag.eventOrg = eventOrg;
return View(eventOrg);
}
The function for the partial view is here:
public PartialViewResult InhoudByIdPartial(int id)
{
return PartialView(
db.EventBericht.Where(r => r.EventID == id).ToList());
}
The function to fill EventBerichten:
public List<EventBerichten> GetEventBerichtenLijst(int id)
{
var eventLijst = db.EventBericht.ToList();
var berLijst = new List<EventBerichten>();
foreach (var ber in eventLijst)
{
if (ber.EventID == id )
{
berLijst.Add(ber);
}
}
return berLijst;
}
The partialView Model looks like this:
@model IEnumerable<STUVF_back_end.Models.EventBerichten>
<table>
<tr>
<th>
EventID
</th>
<th>
Titel
</th>
<th>
Inhoud
</th>
<th>
BerichtDatum
</th>
<th>
BerichtTijd
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.EventID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Titel)
</td>
<td>
@Html.DisplayFor(modelItem => item.Inhoud)
</td>
<td>
@Html.DisplayFor(modelItem => item.BerichtDatum)
</td>
<td>
@Html.DisplayFor(modelItem => item.BerichtTijd)
</td>
</tr>
}
</table>
VIEUW: This is the script used to get my output in the view
<script type="text/javascript">
$(document).ready(function () {
$("#EventBerichten").change(function () {
$("#log").ajaxError(function (event, jqxhr, settings, exception) {
alert(exception);
});
var BerichtSelected = $("select option:selected").first().text();
$.get('@Url.Action("InhoudByIdPartial")',
{ EventBerichtID: BerichtSelected }, function (data) {
$("#target").html(data);
});
});
});
</script>
@{
Html.RenderAction("InhoudByIdPartial", Model.EventID);
}
<fieldset>
<legend>Berichten over dit Evenement</legend>
<div>
@Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { @class = "form-control", onchange = "$(this.form).submit();" })
</div>
<br />
<div id="target">
</div>
<div id="log">
</div>
</fieldset>
I'm struggling with the same here. But I can show you what I've got doing some research. Basically, you first start adding the page @Output event in the foo.template.ts:
<md-paginator #paginator
[length]="length"
[pageIndex]="pageIndex"
[pageSize]="pageSize"
[pageSizeOptions]="[5, 10, 25, 100]"
(page)="pageEvent = getServerData($event)"
>
</md-paginator>
And later, you have to add the pageEvent attribute in the foo.component.ts class and the others to handle paginator requirements:
pageEvent: PageEvent;
datasource: null;
pageIndex:number;
pageSize:number;
length:number;
And add the method that will fetch the server data:
ngOnInit() {
getServerData(null) ...
}
public getServerData(event?:PageEvent){
this.fooService.getdata(event).subscribe(
response =>{
if(response.error) {
// handle error
} else {
this.datasource = response.data;
this.pageIndex = response.pageIndex;
this.pageSize = response.pageSize;
this.length = response.length;
}
},
error =>{
// handle error
}
);
return event;
}
So, basically every time you click the paginator, you'll activate getServerData(..) method that will call foo.service.ts getting all data required. In this case, you do not need to handle nextPage and nextXXX events because it will be automatically calculated upon view rendering.
Hope this can help you. Let me know if you had success. =]
Do you use the input type="file" to choose the uploadfiles? if so, why not use the accept attribute?
<input type="file" name="myImage" accept="image/x-png,image/gif,image/jpeg" />
I have used the following for "formatting" the database on device after I have changed the structure of the database in assets. I simply uncomment the line in MainActivity when I wanted that the database is read from the assets again. This will reset the device database values and structure to mach with the preoccupied database in assets folder.
//database initialization. Uncomment to clear the database
//deleteDatabase("questions.db");
Next, I will implement a button that will run the deleteDatabase so that the user can reset its progress in the game.
I had a similar problem.
As it turned out, I ran mvn clean package install.
Correct way is mvn clean install
You must include jQuery in the project.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I didn't find any doc about this so I just opened a random code example from tutorialrepublic.com http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-dropdowns.php
Hope this helps someone else.
I had a situation where I could not use any of the above answers. My case involved working with search page where users would get "confirm form resubmission" if the clicked back after navigating to any of the search results. I wrote the following javascript which worked around the issue. It isn't a great fix as it is a bit blinky, and it doesn't work on IE8 or earlier. Still, though this might be useful or interesting for someone dealing with this issue.
jQuery(document).ready(function () {
//feature test
if (!history)
return;
var searchBox = jQuery("#searchfield");
//This occurs when the user get here using the back button
if (history.state && history.state.searchTerm != null && history.state.searchTerm != "" && history.state.loaded != null && history.state.loaded == 0) {
searchBox.val(history.state.searchTerm);
//don't chain reloads
history.replaceState({ searchTerm: history.state.searchTerm, page: history.state.page, loaded: 1 }, "", document.URL);
//perform POST
document.getElementById("myForm").submit();
return;
}
//This occurs the first time the user hits this page.
history.replaceState({ searchTerm: searchBox.val(), page: pageNumber, loaded: 0 }, "", document.URL);
});
Whenever you print any instance of your class, the default
toString
implementation of Object
class is called, which returns the representation that you are getting.
It contains two parts: - Type
and Hashcode
So, in student.Student@82701e that you get as output ->
student.Student
is the Type
, and82701e
is the HashCode
So, you need to override a toString
method in your Student
class to get required String representation
: -
@Override
public String toString() {
return "Student No: " + this.getStudentNo() +
", Student Name: " + this.getStudentName();
}
So, when from your main
class, you print your ArrayList
, it will invoke the toString
method for each instance, that you overrided
rather than the one in Object
class: -
List<Student> students = new ArrayList();
// You can directly print your ArrayList
System.out.println(students);
// Or, iterate through it to print each instance
for(Student student: students) {
System.out.println(student); // Will invoke overrided `toString()` method
}
In both the above cases, the toString
method overrided in Student
class will be invoked and appropriate representation of each instance will be printed.
Quoting when setting $FOO
is not enough. You need to quote the variable reference as well:
me$ FOO="BAR * BAR"
me$ echo "$FOO"
BAR * BAR
This is the simple Console Application to convert List to Datatable.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ComponentModel;
namespace ConvertListToDataTable
{
public static class Program
{
public static void Main(string[] args)
{
List<MyObject> list = new List<MyObject>();
for (int i = 0; i < 5; i++)
{
list.Add(new MyObject { Sno = i, Name = i.ToString() + "-KarthiK", Dat = DateTime.Now.AddSeconds(i) });
}
DataTable dt = ConvertListToDataTable(list);
foreach (DataRow row in dt.Rows)
{
Console.WriteLine();
for (int x = 0; x < dt.Columns.Count; x++)
{
Console.Write(row[x].ToString() + " ");
}
}
Console.ReadLine();
}
public class MyObject
{
public int Sno { get; set; }
public string Name { get; set; }
public DateTime Dat { get; set; }
}
public static DataTable ConvertListToDataTable<T>(this List<T> iList)
{
DataTable dataTable = new DataTable();
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor propertyDescriptor = props[i];
Type type = propertyDescriptor.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
type = Nullable.GetUnderlyingType(type);
dataTable.Columns.Add(propertyDescriptor.Name, type);
}
object[] values = new object[props.Count];
foreach (T iListItem in iList)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(iListItem);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
}
}
If the value is between –2147483648 and 2147483647, cast(string_filed as int) will work. else cast(string_filed as bigint) will work
hive> select cast('2147483647' as int);
OK
2147483647
hive> select cast('2147483648' as int);
OK
NULL
hive> select cast('2147483648' as bigint);
OK
2147483648
Blogged about it on my blog :) Short version is, to find the full names of the resources(unless you already know them):
var assembly = Assembly.GetExecutingAssembly();
foreach (var resourceName in assembly.GetManifestResourceNames())
System.Console.WriteLine(resourceName);
To use all of them for something:
foreach (var resourceName in assembly.GetManifestResourceNames())
{
using(var stream = assembly.GetManifestResourceStream(resourceName))
{
// Do something with stream
}
}
To use resources in other assemblies than the executing one, you'd just get a different assembly object by using some of the other static methods of the Assembly
class. Hope it helps :)
All inputs should be replaced with custom directive that reads a single global variable to toggle readonly status.
// template
<your-input [readonly]="!childmessage"></your-input>
// component value
childmessage = false;
Hope this helps.
let number = 7;
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
Here is a complete function that will log to the console the parity of your input.
const checkNumber = (x) => {
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
}
Lattice solution with additional settings which I needed:
library(lattice)
distribution<-function(x) {2^(-x*2)}
X<-seq(0,10,0.00001)
xyplot(distribution(X)~X,type="l", col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255), cex.lab = 3.5, cex.axis = 3.5, lwd=2 )
X<-seq(0,10,0.00001)
col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255)
lwd = 2
cex.lab = 3.5, cex.axis = 3.5
Pandas is pretty good at dealing with data. Here is one example how to use it:
import pandas as pd
# Read the CSV into a pandas data frame (df)
# With a df you can do many things
# most important: visualize data with Seaborn
df = pd.read_csv('filename.csv', delimiter=',')
# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]
# or export it as a list of dicts
dicts = df.to_dict().values()
One big advantage is that pandas deals automatically with header rows.
If you haven't heard of Seaborn, I recommend having a look at it.
See also: How do I read and write CSV files with Python?
import pandas as pd
# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()
# Convert
dicts = df.to_dict('records')
The content of df is:
country population population_time EUR
0 Germany 82521653.0 2016-12-01 True
1 France 66991000.0 2017-01-01 True
2 Indonesia 255461700.0 2017-01-01 False
3 Ireland 4761865.0 NaT True
4 Spain 46549045.0 2017-06-01 True
5 Vatican NaN NaT True
The content of dicts is
[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-01 00:00:00'), 'EUR': True},
{'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
{'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
{'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
{'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
{'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]
import pandas as pd
# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()
# Convert
lists = [[row[col] for col in df.columns] for row in df.to_dict('records')]
The content of lists
is:
[['Germany', 82521653.0, Timestamp('2016-12-01 00:00:00'), True],
['France', 66991000.0, Timestamp('2017-01-01 00:00:00'), True],
['Indonesia', 255461700.0, Timestamp('2017-01-01 00:00:00'), False],
['Ireland', 4761865.0, NaT, True],
['Spain', 46549045.0, Timestamp('2017-06-01 00:00:00'), True],
['Vatican', nan, NaT, True]]
There is no unique
method for a df, if the number of unique values for each column were the same then the following would work: df.apply(pd.Series.unique)
but if not then you will get an error. Another approach would be to store the values in a dict which is keyed on the column name:
In [111]:
df = pd.DataFrame({'a':[0,1,2,2,4], 'b':[1,1,1,2,2]})
d={}
for col in df:
d[col] = df[col].unique()
d
Out[111]:
{'a': array([0, 1, 2, 4], dtype=int64), 'b': array([1, 2], dtype=int64)}
Whilst I recommend hyphens, I shall also postulate an answer that isn't on your list:
Nothing At All
/quotationrequests/
, /purchaseorders/
and so on.?q=foo+bar
Update: created a js fiddle here to see it live: http://jsfiddle.net/HFMvX/
I went through tons of google searches and didn't find anything satisfying. i like how passpack have done it so essentially reverse-engineered their approach, here we go:
function scorePassword(pass) {
var score = 0;
if (!pass)
return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
// bonus points for mixing it up
var variations = {
digits: /\d/.test(pass),
lower: /[a-z]/.test(pass),
upper: /[A-Z]/.test(pass),
nonWords: /\W/.test(pass),
}
var variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
Good passwords start to score around 60 or so, here's function to translate that in words:
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80)
return "strong";
if (score > 60)
return "good";
if (score >= 30)
return "weak";
return "";
}
you might want to tune this a bit but i found it working for me nicely
For taking parameters, you should use functions!
However $@ get interpreted when creating the alias instead of during the execution of the alias and escaping the $ doesn’t work either. How do I solve this problem?
You need to use shell function instead of an alias to get rid of this problem. You can define foo as follows:
function foo() { /path/to/command "$@" ;}
OR
foo() { /path/to/command "$@" ;}
Finally, call your foo() using the following syntax:
foo arg1 arg2 argN
Make sure you add your foo() to ~/.bash_profile
or ~/.zshrc
file.
In your case, this will work
function trash() { mv $@ ~/.Trash; }
$rootbeer = (float) $InvoicedUnits;
Should do it for you. Check out Type-Juggling. You should also read String conversion to Numbers.
Try browser.execute_script
instead of selenium.GetEval
.
See this answer for example.
I decided to use a couple of methods using a prebuild Powershell script(https://gist.github.com/bradjolicoeur/e77c508089aea6614af3) to increment on each successful build then in Global.asax I've going something like this:
// We are using debug configuration, so increment our builds.
if (System.Diagnostics.Debugger.IsAttached)
{
string version = System.Reflection.Assembly.GetExecutingAssembly()
.GetName()
.Version
.ToString();
var psi = new ProcessStartInfo(@"svn", "commit -m \"Version: " + version + "\n \"");
psi.WorkingDirectory = @"C:\CI\Projects\myproject";
Process.Start(psi);
}
I still think the whole process is overcomplicated and I'm going to look into a more efficient method of achieving the same result. I wanted this mainly for passing the version into SVN and then into Jenkin's without too many addtional tools.
I found one way to access the shared folder without giving the username and password.
We need to change the share folder protect settings in the machine where the folder has been shared.
Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.
By doing the above settings we can access the shared folder without any username/password.
My answer
Use nested for
loops to provide break points to the for /l
loop.
for %%a in (0 1 2 3 4 5 6 7 8 9) do (
for %%b in (0 1 2 3 4 5 6 7 8 9) do (
for /l %%c in (1,1,10) do (
if not exist %%a%%b%%c goto :continue
)
)
)
:continue
Explanation
The code must be tweaked significantly to properly use the nested loops. For example, what is written will have leading zeros.
"Regular" for
loops can be immediately broken out of with a simple goto
command, where for /l
loops cannot. This code's innermost for /l
loop cannot be immediately broken, but an overall break point is present after every 10 iterations (as written). The innermost loop doesn't have to be 10 iterations -- you'll just have to account for the math properly if you choose to do 100 or 1000 or 2873 for that matter (if math even matters to the loop).
History I found this question while trying to figure out why a certain script was running slowly. It turns out I used multiple loops with a traditional loop structure:
set cnt=1
:loop
if "%somecriteria%"=="finished" goto :continue
rem do some things here
set /a cnt += 1
goto :loop
:continue
echo the loop ran %cnt% times
This script file had become somewhat long and it was being run from a network drive. This type of loop file was called maybe 20 times and each time it would loop 50-100 times. The script file was taking too long to run. I had the bright idea of attempting to convert it to a for /l
loop. The number of needed iterations is unknown, but less than 10000. My first attempt was this:
setlocal enabledelayedexpansion
set cnt=1
for /l %%a in (1,1,10000) do (
if "!somecriteria!"=="finished" goto :continue
rem do some things here
set /a cnt += 1
)
:continue
echo the loop ran %cnt% times
With echo
on, I quickly found out that the for /l
loop still did ... something ... without actually doing anything. It ran much faster, but still slower than I thought it could/should. Therefore I found this question and ended up with the nested loop idea presented above.
Side note
It turns out that the for /l
loop can be sped up quite a bit by simply making sure it doesn't have any output. I was able to do this for a noticeable speed increase:
setlocal enabledelayedexpansion
set cnt=1
@for /l %%a in (1,1,10000) do @(
if "!somecriteria!"=="finished" goto :continue
rem do some things here
set /a cnt += 1
) > nul
:continue
echo the loop ran %cnt% times
Short answer: They are now supported nicely, if you can enable developer mode.
From https://blogs.windows.com/buildingapps/2016/12/02/symlinks-windows-10/
Now in Windows 10 Creators Update, a user (with admin rights) can first enable Developer Mode, and then any user on the machine can run the mklink command without elevating a command-line console.
What drove this change? The availability and use of symlinks is a big deal to modern developers:
Many popular development tools like git and package managers like npm recognize and persist symlinks when creating repos or packages, respectively. When those repos or packages are then restored elsewhere, the symlinks are also restored, ensuring disk space (and the user’s time) isn’t wasted.
Easy to overlook with all the other announcements of the "Creator's update", but if you enable Developer Mode, you can create symlinks without elevated privileges. You might have to re-install git and make sure symlink support is enabled, as it's not by default.
Also are supported HTML5 hashchange event and ononline, offline event
I have not used Bootstrap but I worked on Zurb Foundation. On that I used to add space like this.
<div id="main" class="container" role="main">
<div class="row">
<div class="span5 offset1">
<h2>Welcome</h2>
<p>Hello and welcome to my website.</p>
</div>
<div class="span6">
Image Here (TODO)
</div>
</div>
Visit this link: http://getbootstrap.com/2.3.2/scaffolding.html and read the section: Offsetting columns.
I think I know what you are doing wrong. If you are applying padding to the span6
like this:
<div class="span6" style="padding-left:5px;">
<h2>Welcome</h2>
<p>Hello and welcome to my website.</p>
</div>
It is wrong. What you have to do is add padding to the elements inside:
<div class="span6">
<h2 style="padding-left:5px;">Welcome</h2>
<p style="padding-left:5px;">Hello and welcome to my website.</p>
</div>
Using DataTable is valid as user927524 stated. You can also do it by adding rows manually, which will not require to add a specific wrapping class:
List<string> filenamesList = ...;
foreach(string filename in filenamesList)
gvFilesOnServer.Rows.Add(new object[]{filename});
In any case, thanks user927524 for clearing this weird behavior!!
I've created a couple of map tutorials that will cover what you need
Animating the map describes howto create polylines based on a set of LatLngs. Using Google APIs on your map : Directions and Places describes howto use the Directions API and animate a marker along the path.
Take a look at these 2 tutorials and the Github project containing the sample app.
It contains some tips to make your code cleaner and more efficient:
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
$('input:checkbox.class').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
An example to demonstrate.
:checkbox
is a selector for checkboxes (in fact, you could omit the input
part of the selector, although I found niche cases where you would get strange results doing this in earlier versions of the library. I'm sure they are fixed in later versions).
.class
is the selector for element class attribute containing class
.
I use this
<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="500.00:00:00" />
</staticContent>
to cache static content for 500 days with public cache-control header.
If you use AppCompatTextView
( or from API 28
onward ) you can use the combination of those 2 attributes to remove the spacing on the first line:
XML
android:firstBaselineToTopHeight="0dp"
android:includeFontPadding="false"
Kotlin
text.firstBaselineToTopHeight = 0
text.includeFontPadding = false
I've experienced similar problem. Although I had have UTF-8 encodings solved (with mysql2 and Encoding.default_external = Encoding::UTF_8 ...) incompatible character encodings: UTF-8 and ASCII-8BIT arose when I used incorrect helper parameters e.g. f.button :submit, "Zrušit"
- works perfectly but f.button "Zrušit"
- throws encoding error.
A better fix than setting PYTHONPATH
is to use python -m module.path
This will correctly set sys.path[0]
and is a more reliable way to execute modules.
I have a quick writeup about this problem, as other answerers have mentioned the reason for this is python path/to/file.py
puts path/to
on the beginning of the PYTHONPATH
(sys.path
).
I have tested a full layout using flexbox it contains header, footer, main body with left, center and right panels and the panels can contain menu items or footer and headers that should scroll. Pretty complex
IE11 and even IE EDGE have some problems displaying the flex content but it can be overcome. I have tested it in most browsers and it seems to work.
Some fixed i have applies are IE11 height bug, Adding height:100vh and min-height:100% to the html/body. this also helps to not have to set height on container in the dom. Also make the body/html a flex container. Otherwise IE11 will compress the view.
html,body {
display: flex;
flex-flow:column nowrap;
height:100vh; /* fix IE11 */
min-height:100%; /* fix IE11 */
}
A fix for IE EDGE that overflows the flex container: overflow:hidden on main flex container. if you remove the overflow, IE EDGE wil push the content out of the viewport instead of containing it inside the flex main container.
main{
flex:1 1 auto;
overflow:hidden; /* IE EDGE overflow fix */
}
You can see my testing and example on my codepen page. I remarked the important css parts with the fixes i have applied and hope someone finds it useful.
You have to put a period at the end of the external domain so it doesn't think you mean customer1.mycompanydomain.com.localdomain;
So just change:
customer1.com IN CNAME customer1.mycompanydomain.com
To
customer1.com IN CNAME customer1.mycompanydomain.com.
You can't have duplicate keys in a Map
. You can rather create a Map<Key, List<Value>>
, or if you can, use Guava's Multimap
.
Multimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(1, "rohit");
multimap.put(1, "jain");
System.out.println(multimap.get(1)); // Prints - [rohit, jain]
And then you can get the java.util.Map
using the Multimap#asMap()
method.
Fast to write and convenient to use, with promise and error management:
function copyFile(source, target) {
var rd = fs.createReadStream(source);
var wr = fs.createWriteStream(target);
return new Promise(function(resolve, reject) {
rd.on('error', reject);
wr.on('error', reject);
wr.on('finish', resolve);
rd.pipe(wr);
}).catch(function(error) {
rd.destroy();
wr.end();
throw error;
});
}
The same with async/await syntax:
async function copyFile(source, target) {
var rd = fs.createReadStream(source);
var wr = fs.createWriteStream(target);
try {
return await new Promise(function(resolve, reject) {
rd.on('error', reject);
wr.on('error', reject);
wr.on('finish', resolve);
rd.pipe(wr);
});
} catch (error) {
rd.destroy();
wr.end();
throw error;
}
}
The previous answers are quite complete regarding what ::
method reference does. To sum up, it provides a way to refer to a method(or constructor) without executing it, and when evaluated, it creates an instance of the functional interface that provides the target type context.
Below are two examples to find an object with the max value in an ArrayList
WITH and WITHOUT the use of ::
method reference. Explanations are in the comments below.
WITHOUT the use of ::
import java.util.*;
class MyClass {
private int val;
MyClass (int v) { val = v; }
int getVal() { return val; }
}
class ByVal implements Comparator<MyClass> {
// no need to create this class when using method reference
public int compare(MyClass source, MyClass ref) {
return source.getVal() - ref.getVal();
}
}
public class FindMaxInCol {
public static void main(String args[]) {
ArrayList<MyClass> myClassList = new ArrayList<MyClass>();
myClassList.add(new MyClass(1));
myClassList.add(new MyClass(0));
myClassList.add(new MyClass(3));
myClassList.add(new MyClass(6));
MyClass maxValObj = Collections.max(myClassList, new ByVal());
}
}
WITH the use of ::
import java.util.*;
class MyClass {
private int val;
MyClass (int v) { val = v; }
int getVal() { return val; }
}
public class FindMaxInCol {
static int compareMyClass(MyClass source, MyClass ref) {
// This static method is compatible with the compare() method defined by Comparator.
// So there's no need to explicitly implement and create an instance of Comparator like the first example.
return source.getVal() - ref.getVal();
}
public static void main(String args[]) {
ArrayList<MyClass> myClassList = new ArrayList<MyClass>();
myClassList.add(new MyClass(1));
myClassList.add(new MyClass(0));
myClassList.add(new MyClass(3));
myClassList.add(new MyClass(6));
MyClass maxValObj = Collections.max(myClassList, FindMaxInCol::compareMyClass);
}
}
There can be one of the two cause for this error:
You can parse the list as a string and use of the eval
builtin function to read it as a list. In this case, you will have to put single quotes into double quote (or the way around) in order to ensure successful string parse.
# declare the list arg as a string
parser.add_argument('-l', '--list', type=str)
# parse
args = parser.parse()
# turn the 'list' string argument into a list object
args.list = eval(args.list)
print(list)
print(type(list))
Testing:
python list_arg.py --list "[1, 2, 3]"
[1, 2, 3]
<class 'list'>
In my case I had to go to
File -> Settings -> Build, Execution, Deployment -> Gradle
and then I changed the Service directory path
, which was pointing to a wrong location.
AFAIK you will need at least a little bit of JavaScript...
I would suggest to use jQuery.
You can include this library in one line. And then you can access your div with
$('div').click(function(){
// do stuff here
});
and respond to the click event.
Just found an easy way to do it in the new Android Studio:
I had a problem like this before. I don't think tr
can take a border styling directly. My workaround was to style the td
s in the row:
<tr class="border_bottom">
CSS:
tr.border_bottom td {
border-bottom: 1px solid black;
}
You could always try doing a ulimit -n 2048
. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit
Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.
set rlim_fd_max = 166384
set rlim_fd_cur = 8192
On OS X, this same data must be set in /etc/sysctl.conf.
kern.maxfilesperproc=166384
kern.maxfiles=8192
Under Linux, these settings are often in /etc/security/limits.conf.
There are two kinds of limits:
Soft limits could be set by any user while hard limits are changeable only by root. Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits.
There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default.
In my case (Windows 10) the reason was that I dared to unzip the android sdk into non default folder. When I moved it to the default one c:/Users/[username]/AppData/Local/Android/Sdk and changed the paths in Android Studio and System Variables, it started to work.
Basically you can put HTML anywhere outside of PHP tags. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
The data display itself could be at the bottom of the same PHP file or you could include a separate PHP file consisting of mostly HTML.
I prefer this compact style:
<?php
/* do your processing here */
?>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php foreach ( $something as $item ) : ?>
<p><?=$item?></p>
<?php endforeach; ?>
</body>
</html>
Note: you may need to use <?php echo $var; ?>
instead of <?=$var?>
depending on your PHP setup.
Since web.config file is xml file you can open web.config using xmldocument class. Get the node from that xml file that you want to update and then save xml file.
here is URL that explains in more detail how you can update web.config file programmatically.
http://patelshailesh.com/index.php/update-web-config-programmatically
Note: if you make any changes to web.config, ASP.NET detects that changes and it will reload your application(recycle application pool) and effect of that is data kept in Session, Application, and Cache will be lost (assuming session state is InProc and not using a state server or database).
Here's a pure CSS solution, similar to DarkBee's answer, but without the need for an extra .wrapper
div:
.dimmed {
position: relative;
}
.dimmed:after {
content: " ";
z-index: 10;
display: block;
position: absolute;
height: 100%;
top: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.5);
}
I'm using rgba here, but of course you can use other transparency methods if you like.
Especially for the older Git versions, most of the suggestions won't work that well. If that's the case, I'd put a separate .gitignore in the directory where I want the content to be included regardless of other settings and allow there what is needed.
For example: /.gitignore
# ignore all .dll files
*.dll
/dependency_files/.gitignore
# include everything
!*
So everything in /dependency_files (even .dll files) are included just fine.
In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size
like this:
#include <vector>
int main () {
std::vector<int> v;
auto size = v.size();
}
Your third call
int size = v.size();
triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.
int size = static_cast<int>(v.size());
would always compile cleanly and also explicitly states that your conversion from std::vector::size_type
to int
was intended.
Note that if the size of the vector
is greater than the biggest number an int
can represent, size
will contain an implementation defined (de facto garbage) value.
I'm not familiar with tortoise, but with subversion to linux i would type
svn status
Some googling tells me that tortoise also supports commandline commandos, try svn status in the folder that contains the svn repository.
The easiest way would probably be to put your web resources into the assets folder then call:
webView.loadUrl("file:///android_asset/filename.html");
For Complete Communication between Java and Webview See This
Update: The assets folder is usually the following folder:
<project>/src/main/assets
This can be changed in the asset folder configuration setting in your <app>.iml
file as:
<option name=”ASSETS_FOLDER_RELATIVE_PATH” value=”/src/main/assets” />
See Article Where to place the assets folder in Android Studio
Use the which function:
A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)
r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]
public String hasNums(String str) {
char[] nums = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] toChar = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
toChar[i] = str.charAt(i);
for (int j = 0; j < nums.length; j++) {
if (toChar[i] == nums[j]) { return str; }
}
}
return "None";
}
It depends on what you define as the difference. To compare two dates at midnight you can do.
long day1 = ...; // in milliseconds.
long day2 = ...; // in milliseconds.
long days = (day2 - day1) / 86400000;
In a new upcoming php7 among many other features, they added a support for strings bigger than 2^31 bytes:
Support for strings with length >= 2^31 bytes in 64 bit builds.
Sadly they did not specify how much bigger can it be.
You can also use scipy.signal.welch to estimate the power spectral density using Welch’s method. Here is an comparison between np.fft.fft and scipy.signal.welch:
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
fs = 10e3
N = 1e5
amp = 2*np.sqrt(2)
freq = 1234.0
noise_power = 0.001 * fs / 2
time = np.arange(N) / fs
x = amp*np.sin(2*np.pi*freq*time)
x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape)
# np.fft.fft
freqs = np.fft.fftfreq(time.size, 1/fs)
idx = np.argsort(freqs)
ps = np.abs(np.fft.fft(x))**2
plt.figure()
plt.plot(freqs[idx], ps[idx])
plt.title('Power spectrum (np.fft.fft)')
# signal.welch
f, Pxx_spec = signal.welch(x, fs, 'flattop', 1024, scaling='spectrum')
plt.figure()
plt.semilogy(f, np.sqrt(Pxx_spec))
plt.xlabel('frequency [Hz]')
plt.ylabel('Linear spectrum [V RMS]')
plt.title('Power spectrum (scipy.signal.welch)')
plt.show()
Unless you have more style sheets than that, you've messed up your break points:
#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)
The 3rd media query is probably meant to be min-width: 901px
. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.
Edit for updated question:
(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)
Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width
for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:
(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)
Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.
@fthiella 's solution is very elegant.
If in future you want show more than user_id
you could use joins, and there in one line could be all data you need.
If you want to use AND
conditions, and the conditions are in multiple lines in your table, you can use JOINS
example:
SELECT `w_name`.`user_id`
FROM `wp_usermeta` as `w_name`
JOIN `wp_usermeta` as `w_year` ON `w_name`.`user_id`=`w_year`.`user_id`
AND `w_name`.`meta_key` = 'first_name'
AND `w_year`.`meta_key` = 'yearofpassing'
JOIN `wp_usermeta` as `w_city` ON `w_name`.`user_id`=`w_city`.user_id
AND `w_city`.`meta_key` = 'u_city'
JOIN `wp_usermeta` as `w_course` ON `w_name`.`user_id`=`w_course`.`user_id`
AND `w_course`.`meta_key` = 'us_course'
WHERE
`w_name`.`meta_value` = '$us_name' AND
`w_year`.meta_value = '$us_yearselect' AND
`w_city`.`meta_value` = '$us_reg' AND
`w_course`.`meta_value` = '$us_course'
Other thing: Recommend to use prepared statements, because mysql_*
functions is not SQL injection save, and will be deprecated.
If you want to change your code the less as possible, you can use mysqli_
functions:
http://php.net/manual/en/book.mysqli.php
Recommendation:
Use indexes in this table. user_id
highly recommend to be and index, and recommend to be the meta_key
AND meta_value
too, for faster run of query.
The explain:
If you use AND
you 'connect' the conditions for one line. So if you want AND condition for multiple lines, first you must create one line from multiple lines, like this.
Tests: Table Data:
PRIMARY INDEX
int varchar(255) varchar(255)
/ \ |
+---------+---------------+-----------+
| user_id | meta_key | meta_value|
+---------+---------------+-----------+
| 1 | first_name | Kovge |
+---------+---------------+-----------+
| 1 | yearofpassing | 2012 |
+---------+---------------+-----------+
| 1 | u_city | GaPa |
+---------+---------------+-----------+
| 1 | us_course | PHP |
+---------+---------------+-----------+
The result of Query with $us_name='Kovge'
$us_yearselect='2012'
$us_reg='GaPa'
, $us_course='PHP'
:
+---------+
| user_id |
+---------+
| 1 |
+---------+
So it should works.
Comparator
provides a way for you to provide custom comparison logic for types that you have no control over.
Comparable
allows you to specify how objects that you are implementing get compared.
Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator
.
Otherwise you can use Comparable
.
I had this same issue when transitioning from Bootstrap 2 to 3. I'd already got respond.js and html5shiv.js and set my meta to edge. I'd missed that from 2 to 3 the navbar element type had changed. In Bootstrap 2 it was nav. In Bootstrap 3 it's now header. So to fully resolve the problem I had to
<meta http-equiv="X-UA-Compatible" content="IE=edge">
Put this right after I'd loaded my css:
<!--[if lt IE 9]>
<script src="~/Content/compatibility/html5shiv.js"></script>
<script src="~/Content/compatibility/respond.min.js"></script>
<![endif]-->
and then change
<nav class="navbar" role="navigation">
</nav>
to
<header class="navbar" role="navigation">
</header>
Oh and for good measure I also added
<meta name="viewport" content="width=device-width, initial-scale=1.0">
simply because that's what the Bootstrap site itself has.
I had to do a :
git checkout -b master
as git said that it doesn't exists, because it's been wipe with the
git -D master
You can easily normalize the data also using data.Normalization function in clusterSim package. It provides different method of data normalization.
data.Normalization (x,type="n0",normalization="column")
Arguments
x
vector, matrix or dataset
type
type of normalization:
n0 - without normalization
n1 - standardization ((x-mean)/sd)
n2 - positional standardization ((x-median)/mad)
n3 - unitization ((x-mean)/range)
n3a - positional unitization ((x-median)/range)
n4 - unitization with zero minimum ((x-min)/range)
n5 - normalization in range <-1,1> ((x-mean)/max(abs(x-mean)))
n5a - positional normalization in range <-1,1> ((x-median)/max(abs(x-median)))
n6 - quotient transformation (x/sd)
n6a - positional quotient transformation (x/mad)
n7 - quotient transformation (x/range)
n8 - quotient transformation (x/max)
n9 - quotient transformation (x/mean)
n9a - positional quotient transformation (x/median)
n10 - quotient transformation (x/sum)
n11 - quotient transformation (x/sqrt(SSQ))
n12 - normalization ((x-mean)/sqrt(sum((x-mean)^2)))
n12a - positional normalization ((x-median)/sqrt(sum((x-median)^2)))
n13 - normalization with zero being the central point ((x-midrange)/(range/2))
normalization
"column" - normalization by variable, "row" - normalization by object