Expanding a bit on the answers from @Guru and @Ronnis, you can hide the sequence and make it look more like an auto-increment using a trigger, and have a procedure that does the insert for you and returns the generated ID as an out parameter.
create table batch(batchid number,
batchname varchar2(30),
batchtype char(1),
source char(1),
intarea number)
/
create sequence batch_seq start with 1
/
create trigger batch_bi
before insert on batch
for each row
begin
select batch_seq.nextval into :new.batchid from dual;
end;
/
create procedure insert_batch(v_batchname batch.batchname%TYPE,
v_batchtype batch.batchtype%TYPE,
v_source batch.source%TYPE,
v_intarea batch.intarea%TYPE,
v_batchid out batch.batchid%TYPE)
as
begin
insert into batch(batchname, batchtype, source, intarea)
values(v_batchname, v_batchtype, v_source, v_intarea)
returning batchid into v_batchid;
end;
/
You can then call the procedure instead of doing a plain insert, e.g. from an anoymous block:
declare
l_batchid batch.batchid%TYPE;
begin
insert_batch(v_batchname => 'Batch 1',
v_batchtype => 'A',
v_source => 'Z',
v_intarea => 1,
v_batchid => l_batchid);
dbms_output.put_line('Generated id: ' || l_batchid);
insert_batch(v_batchname => 'Batch 99',
v_batchtype => 'B',
v_source => 'Y',
v_intarea => 9,
v_batchid => l_batchid);
dbms_output.put_line('Generated id: ' || l_batchid);
end;
/
Generated id: 1
Generated id: 2
You can make the call without an explicit anonymous block, e.g. from SQL*Plus:
variable l_batchid number;
exec insert_batch('Batch 21', 'C', 'X', 7, :l_batchid);
... and use the bind variable :l_batchid
to refer to the generated value afterwards:
print l_batchid;
insert into some_table values(:l_batch_id, ...);
Using the DISTINCT flag will remove duplicate rows.
SELECT DISTINCT
C.Content_ID,
C.Content_Title,
M.Media_Id
FROM tbl_Contents C
LEFT JOIN tbl_Media M ON M.Content_Id = C.Content_Id
ORDER BY C.Content_DatePublished ASC
Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Then you could use
Call fso.CopyFile(source, destination[, overwrite] )
where source and destination are the full names (including paths) of the file.
See https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method
When you need to do it in a string (eg: in your resources) you need to use xml:space="preserve"
and the ampersand character codes:
<System:String x:Key="TwoLiner" xml:space="preserve">First line Second line</System:String>
Or literal newlines in the text:
<System:String x:Key="TwoLiner" xml:space="preserve">First line
Second line</System:String>
Warning: if you write code like the second example, you have inserted either a newline, or a carriage return and newline, depending on the line endings your operating system and/or text editor use. For instance, if you write that and commit it to git from a linux systems, everything may seem fine -- but if someone clones it to Windows, git will convert your line endings to \r\n
and depending on what your string is for ... you might break the world.
Just be aware of that when you're preserving whitespace. If you write something like this:
<System:String x:Key="TwoLiner" xml:space="preserve">
First line
Second line
</System:String>
You've actually added four line breaks, possibly four carriage-returns, and potentially trailing white space that's invisible...
At my company they didn't configure the server to provide a list of repositories, so svn list
worked for a specific repository but not at a higher level to list all repositories.
However they installed FishEye which gives you a GUI listing the repositories https://www.atlassian.com/software/fisheye
It's a paid option, so it's not for everyone, but the functionality is nice.
While a bit more cryptic than join
, you can also multiply the array by a string.
@arr * " "
In a fresh spreadsheet (US locale) with 12/19/11
in A1 and DT 30
in B1 then:
=A1+right(B1,2)
in say C1 returns 1/18/12
.
As a string function RIGHT returns Text but that can be coerced into a number when adding. In adding a number to dates unity is treated as one day. Within (very wide) limits, months and even years are adjusted automatically.
Hello was looking for the same, and it could be also
unlist(lapply(mtcars,class))
new Buffer(number) // Old
Buffer.alloc(number) // New
new Buffer(string) // Old
Buffer.from(string) // New
new Buffer(string, encoding) // Old
Buffer.from(string, encoding) // New
new Buffer(...arguments) // Old
Buffer.from(...arguments) // New
Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.
Whatever code you are writing in viewDidLoad
, Add that in viewWillappear()
. This will solve your problem.
Just supply the IP / hostname of the remote machine in your database connection string, instead of localhost
. For example:
jdbc:mysql://192.168.15.25:3306/yourdatabase
Make sure there is no firewall blocking the access to port 3306
Also, make sure the user you are connecting with is allowed to connect from this particular hostname. For development environments it is safe to do this by 'username'@'%'
. Check the user creation manual and the GRANT
manual.
Adding to NightOwl888's answer, you can go one step further and add an AssemblyInfo
class rather than just a plain class:
Mockito offers a reflection-matcher:
For latest version of Mockito use:
Assert.assertTrue(new ReflectionEquals(expected, excludeFields).matches(actual));
For older versions use:
Assert.assertThat(actual, new ReflectionEquals(expected, excludeFields));
I found a way to make this work in pure css:
a pure CSS method to enable img:after.
You can check out the CodePen: I'm just fake content or see the source.
img {_x000D_
/* hide the default image */_x000D_
height:0;_x000D_
width:0;_x000D_
_x000D_
/* hide fake content */_x000D_
font-size:0;_x000D_
color:transparent;_x000D_
_x000D_
/* enable absolute position for pseudo elements */_x000D_
position:relative;_x000D_
_x000D_
/* and this is just fake content */_x000D_
content:"I'm just fake content";_x000D_
}_x000D_
_x000D_
/* initial absolute position */_x000D_
img:before,_x000D_
img:after {_x000D_
position:absolute;_x000D_
top:0;_x000D_
left:0; _x000D_
}_x000D_
_x000D_
/* img:before - chrome & others */_x000D_
img:before {_x000D_
content:url(http://placekitten.com/g/250/250);_x000D_
}_x000D_
_x000D_
/* img:before - firefox */_x000D_
body:not(:-moz-handler-blocked) img:before {_x000D_
padding:125px;_x000D_
background:url(http://placekitten.com/g/250/250) no-repeat;_x000D_
}_x000D_
_x000D_
/* img:after */_x000D_
img:after {_x000D_
/* width of img:before */_x000D_
left:250px;_x000D_
_x000D_
content:url(http://lorempixel.com/350/200/city/1);_x000D_
}
_x000D_
<img_x000D_
alt="You are watching the ~ I'm just fake content ~ method" _x000D_
/>
_x000D_
✓ Chrome 10+
✓ Firefox 11+
✓ Opera 9.8+
✓ Safari
⊗ Internet Explorer 8 / 9
Please test in other browsers
Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N
for the S/U and U/S contention, as in No Conflict.
As for the HOLDLOCK hint the documentation states:
HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.
...
SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...
and the Transaction Isolation Level topic explains what SERIALIZABLE means:
No other transactions can modify data that has been read by the current transaction until the current transaction completes.
Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.
Therefore the behavior you see is perfectly explained by the product documentation:
SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...
After OP edit:
I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.
The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.
Well, the window is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.
What about the document object then? The document object is your html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc. What does this really mean? That means if you want to access a property for the window it is window.property, if it is document it is window.document.property which is also available in short as document.property.
That seems simple enough. But what happens once an IFRAME is introduced?
Run the below command to create a migration file:
rails g migration ChangeHasedPasswordToHashedPassword
Then in the file generated in the db/migrate
folder, write rename_column
as below:
class ChangeOldCoulmnToNewColumn < ActiveRecord::Migration
def change
rename_column :table_name, :hased_password, :hashed_password
end
end
If the user name that is in the connection string has access to more then one database you have to specify the database you want the connection string to connect to. If your user has only one database available then you are correct that it doesn't matter. But it is good practice to put this in your connection string.
To install composer and add to your global path:
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
run these in terminal. It does say if you get an error that usr doesn't exist, you do need to manually make it. I know an answer was selected, so this is for anyone who may see this in the future, as i am sometimes, and don't want to be advised to visit yet another site. Its simple just two lines, might have to be in sudo if you have permission error
Here is the way I created ssn directive which checks for the the pattern and I have used RobinHerbots jquery.inputmask
angular.module('SocialSecurityNumberDirective', [])
.directive('socialSecurityNumber', socialSecurityNumber);
function socialSecurityNumber() {
var jquery = require('jquery');
var inputmask = require("jquery.inputmask");
return {
require: 'ngModel',
restrict: 'A',
priority: 1000,
link: function(scope,element, attr, ctrl) {
var jquery_element = jquery(element);
jquery_element.inputmask({mask:"***-**-****",autoUnmask:true});
jquery_element.on('keyup paste focus blur', function() {
var val = element.val();
ctrl.$setViewValue(val);
ctrl.$render();
});
var pattern = /^\d{9}$/;
var newValue = null;
ctrl.$validators.ssnDigits = function(value) {
newValue = element.val();
return newValue === '' ? true : pattern.test(newValue);
};
}
};
}
The output of dpkg -s ...
demonstrates that docker-compose
is not installed from a package. Without more information from you there are at least two possibilities:
docker-compose simply isn't installed at all, and you need to install it.
The solution here is simple: install docker-compose
.
docker-compose is installed in your $HOME
directory (or other location not on root's $PATH
).
There are several solution in this case. The easiest is probably to replace:
sudo docker-compose ...
With:
sudo `which docker-compose` ...
This will call sudo
with the full path to docker-compose
.
You could alternatively install docker-compose
into a system-wide directory, such as /usr/local/bin
.
For me it got resolved using following link: http://viralpatel.net/blogs/wamp-server-not-getting-started-problem/
where i was using skype and Wamp both installed and running
Long story short,
IQueryable
is designed to postpone RUN process and firstly build the expression in conjunction with other IQueryable
expressions, and then interprets and runs the expression as a whole.
But ToList()
method (or a few sort of methods like that), are ment to run the expression instantly "as is".
Your first method (GetAllUrlsAsync
), will run imediately, because it is IQueryable
followed by ToListAsync()
method. hence it runs instantly (asynchronous), and returns a bunch of IEnumerable
s.
Meanwhile your second method (GetAllUrls
), won't get run. Instead, it returns an expression and CALLER of this method is responsible to run the expression.
Remove this from #info
:
margin-left:auto;
Add this for your header:
#info p {
text-align: center;
}
Do you need the fixed width etc.? I removed the in my opinion not necessary stuff and centered the header with text-align
.
Sample
http://jsfiddle.net/Vc8CB/
Active Record gives you _before_type_cast
attributes which contain the raw attribute data before typecasting. This can be useful for returning error messages with pre-typecast values or just doing validations that aren't possible after typecast.
I would shy away from Daniel Von Fange's suggestion of overriding the accessor, because doing validation in an accessor changes the accessor contract slightly. Active Record has a feature explicitly for this situation. Use it.
To answer your questions in order:
1) There is no specific name for this. It's simply multiple elements with the same name (and in this case type as well). Name isn't unique, which is why id was invented (it's supposed to be unique).
2)
function getElementsByTagAndName(tag, name) { //you could pass in the starting element which would make this faster var elem = document.getElementsByTagName(tag); var arr = new Array(); var i = 0; var iarr = 0; var att; for(; i < elem.length; i++) { att = elem[i].getAttribute("name"); if(att == name) { arr[iarr] = elem[i]; iarr++; } } return arr; }
I recommend php-ffmpeg library.
Extracting image
You can extract a frame at any timecode using the
FFMpeg\Media\Video::frame
method.This code returns a
FFMpeg\Media\Frame
instance corresponding to the second 42. You can pass anyFFMpeg\Coordinate\TimeCode
as argument, see dedicated documentation below for more information.
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');
If you want to extract multiple images from the video, you can use the following filter:
$video
->filters()
->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
By default, this will save the frames as jpg images.
You are able to override this using setFrameFileType
to save the frames in another format:
$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);
$video->addFilter($filter);
Before pasting into the terminal, try :set paste
and then :set nopaste
after you're done. This will turn off the auto-indent, line-wrap and other features that are messing up your paste.
edit: Also, I should point out that a much better result than =
indenting can usually be obtained by using an external program. For example, I run :%!perltidy
all the time. astyle
, cindent
, etc. can also be used. And, of course, you can map those to a key stroke, and map different ones to the same keystroke depending on file type.
In PHP, you can send POST data with cURL. Is there something comparable for .NET?
Yes, HttpWebRequest, see my post below.
I found that I also had to set the Access Modifier in the Resources tab to 'Public' - by default it was set to Internal and my icon only appeared in design mode but not when I ran the application.
The syntax is
pid_t waitpid(pid_t pid, int *statusPtr, int options);
1.where pid is the process of the child it should wait.
2.statusPtr is a pointer to the location where status information for the terminating process is to be stored.
3.specifies optional actions for the waitpid function. Either of the following option flags may be specified, or they can be combined with a bitwise inclusive OR operator:
WNOHANG WUNTRACED WCONTINUED
If successful, waitpid returns the process ID of the terminated process whose status was reported. If unsuccessful, a -1 is returned.
benifits over wait
1.Waitpid can used when you have more than one child for the process and you want to wait for particular child to get its execution done before parent resumes
2.waitpid supports job control
3.it supports non blocking of the parent process
Promise returned from $http
can not be binded directly (I dont exactly know why).
I'm using wrapping service that works perfectly for me:
.factory('DocumentsList', function($http, $q){
var d = $q.defer();
$http.get('/DocumentsList').success(function(data){
d.resolve(data);
});
return d.promise;
});
and bind to it in controller:
function Ctrl($scope, DocumentsList) {
$scope.Documents = DocumentsList;
...
}
UPDATE!:
In Angular 1.2 auto-unwrap promises was removed. See http://docs.angularjs.org/guide/migration#templates-no-longer-automatically-unwrap-promises
DataFrames
are based on RDDs. RDDs are immutable structures and do not allow updating elements on-site. To change values, you will need to create a new DataFrame by transforming the original one either using the SQL-like DSL or RDD operations like map
.
A highly recommended slide deck: Introducing DataFrames in Spark for Large Scale Data Science.
In .ts :
today: Date;
constructor() {
this.today =new Date();
}
.html:
<input type="date"
[ngModel]="today | date:'yyyy-MM-dd'"
(ngModelChange)="today = $event"
name="dt"
class="form-control form-control-rounded" #searchDate
>
On top of everything that's been said (
https://stackoverflow.com/a/4416666/172109
),
which is correct, TFS isn't just a VCS. One major feature that TFS provides is natively integrated bug tracking functionality. Changesets are linked to issues and could be tracked. Various policies for check-ins are supported, as well as integration with Windows domain, which is what people who run TFS have. Tightly integrated GUI with Visual Studio is another selling point, which appeals to less than average mouse and click developer and his manager.
Hence comparing Git to TFS isn't a proper question to ask. Correct, though impractical, question is to compare Git with just VCS functionality of TFS. At that, Git blows TFS out of the water. However, any serious team needs other tools and this is where TFS provides one stop destination.
$('#loginBtn').click(function(e) {
e.preventDefault(); /// it should not have this code or else it wont continue
//....
});
(Taken from my comment)
pip
won't handle system level dependencies. You'll have to apt-get install libfreetype6-dev
before continuing. (It even says so right in your output. Try skimming over it for such errors next time, usually build outputs are very detailed)
Look into twitter cards.
The trick is not in the button but rather the page you are sharing. Twitter Cards pull the image from the meta tags similar to facebook
sharing.
Example:
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@site_username">
<meta name="twitter:title" content="Top 10 Things Ever">
<meta name="twitter:description" content="Up than 200 characters.">
<meta name="twitter:creator" content="@creator_username">
<meta name="twitter:image" content="http://placekitten.com/250/250">
<meta name="twitter:domain" content="YourDomain.com">
Read line by line, not the whole file:
for line in open(file_name, 'rb'):
# process line here
Even better use with
for automatically closing the file:
with open(file_name, 'rb') as f:
for line in f:
# process line here
The above will read the file object using an iterator, one line at a time.
Store it in the database in a field with a data type of uniqueidentifier.
https://toolki.com/en/php-decoder/
Decode hidden PHP eval(), gzinflate(), str_rot13(), str_replace() and base64_decode()
This works fine ....
int a = nextInt();
int b = nextInt();
int c = nextInt();
Or you can read them in a loop
In case you came to this question but related to newer Angular version >= 2.0.
<div [id]="element.id"></div>
Add this to your class to import the DLL file:
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
const int SW_HIDE = 0;
const int SW_SHOW = 5;
And then if you want to hide it use this command:
var handle = GetConsoleWindow();
ShowWindow(handle, SW_HIDE);
And if you want to show the console:
var handle = GetConsoleWindow();
ShowWindow(handle, SW_SHOW);
>>> format(3735928559, 'x')
'deadbeef'
OK, I found this post: http://msdn.microsoft.com/en-us/library/aa479319.aspx
with this very illustrative diagram:
(source: microsoft.com)
in essence, to get at those exception details i need to store them myself in Global.asax, for later retrieval on my custom error page.
it seems the best way is to do the bulk of the work in Global.asax, with the custom error pages handling helpful content rather than logic.
I had to run this for a column introduced in the later stages of a product, on 10+ tables. So wrote this quick untidy script to generate the alter command for all 'relevant' tables.
SET @NeighboringColumn = '<YOUR COLUMN SHOULD COME AFTER THIS COLUMN>';
SELECT CONCAT("ALTER TABLE `",t.TABLE_NAME,"` CHANGE COLUMN `",COLUMN_NAME,"`
`",COLUMN_NAME,"` ", c.DATA_TYPE, CASE WHEN c.CHARACTER_MAXIMUM_LENGTH IS NOT
NULL THEN CONCAT("(", c.CHARACTER_MAXIMUM_LENGTH, ")") ELSE "" END ," AFTER
`",@NeighboringColumn,"`;")
FROM information_schema.COLUMNS c, information_schema.TABLES t
WHERE c.TABLE_SCHEMA = '<YOUR SCHEMA NAME>'
AND c.COLUMN_NAME = '<COLUMN TO MOVE>'
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
AND t.TABLE_TYPE = 'BASE TABLE'
AND @NeighboringColumn IN (SELECT COLUMN_NAME
FROM information_schema.COLUMNS c2
WHERE c2.TABLE_NAME = t.TABLE_NAME);
function count(){
var c= 0;
for(var p in this) if(this.hasOwnProperty(p))++c;
return c;
}
var O={a: 1, b: 2, c: 3};
count.call(O);
To add on to others' answers, if you don't have access to that private key anymore it's fairly simple to get back up and running:
- revoke your active certificate in the provisioning portal
- create new developer certificate (keychain access/.../request for csr...etc.)
- download and install a new certificate
- create a new provisioning profile for existing app id (on provisioning portal)
- download and install new provisioning profile and in the build, settings set the appropriate code signing identities
Note that if you are trying to do that operation often, especially in loops, a list is the wrong data structure.
Lists are not optimized for modifications at the front, and somelist.insert(0, something)
is an O(n) operation.
somelist.pop(0)
and del somelist[0]
are also O(n) operations.
The correct data structure to use is a deque
from the collections
module. deques expose an interface that is similar to those of lists, but are optimized for modifications from both endpoints. They have an appendleft
method for insertions at the front.
Demo:
In [1]: lst = [0]*1000
In [2]: timeit -n1000 lst.insert(0, 1)
1000 loops, best of 3: 794 ns per loop
In [3]: from collections import deque
In [4]: deq = deque([0]*1000)
In [5]: timeit -n1000 deq.appendleft(1)
1000 loops, best of 3: 73 ns per loop
when I send only one object from the client to server all works well.
when I attempt to send several objects one after another on the same stream I get
StreamCorruptedException
.
Actually, your client code is writing one object to the server and reading multiple objects from the server. And there is nothing on the server side that is writing the objects that the client is trying to read.
One option is to give the <a>
a display of inline-block
and then apply text-align: center;
on the containing block (remove the float as well):
div {
background: red;
overflow: hidden;
text-align: center;
}
span a {
background: #222;
color: #fff;
display: inline-block;
/* float:left; remove */
margin: 10px 10px 0 0;
padding: 5px 10px
}
In my case of using ViewPager 2 alpha 2 the below snippet works
viewPager.isUserInputEnabled = false
Ability to disable user input (setUserInputEnabled, isUserInputEnabled)
refer to this for more changes in viewpager2 1.0.0-alpha02
Also some changes were made latest version ViewPager 2 alpha 4
orientation and isUserScrollable attributes are no longer part of SavedState
refer to this for more changes in viewpager2#1.0.0-alpha04
The normal way of doing it is:
You don't need a JsonResult or jQuery for this.
For whatever reason the above would not work for me. This is what did:
if (tabControl.SelectedTab.Name == "tabName" )
{
.. do stuff
}
where tabControl.SelectedTab.Name is the name attribute assigned to the page in the tabcontrol itself.
Had a similar problem. Solved it by calling ToList() on the entity collection and querying the list. If the collection is small this is an option.
IQueryable<entity> pages = context.pages.ToList().Where(p=>p.serial == item.Key.ToString())
Hope this helps.
Is there a reason why you aren't using a table variable and the aggregate SUM operator, instead of a cursor? SQL excels at set-oriented operations. 99.87% of the time that you find yourself using a cursor, there's a set-oriented alternative that's more efficient:
declare @MonthsSale table
(
MonthNumber int,
MonthName varchar(9),
MonthSale decimal(18,2)
)
insert into @MonthsSale
select
1, 'January', 100.00
union select
2, 'February', 200.00
union select
3, 'March', 300.00
union select
4, 'April', 400.00
union select
5, 'May', 500.00
union select
6, 'June', 600.00
union select
7, 'July', 700.00
union select
8, 'August', 800.00
union select
9, 'September', 900.00
union select
10, 'October', 1000.00
union select
11, 'November', 1100.00
union select
12, 'December', 1200.00
select * from @MonthsSale
select SUM(MonthSale) as [TotalSales] from @MonthsSale
You don't need quotes around the variable, so simply change this:
Get-ADComputer -Filter {name -like '$nameregex' -and Enabled -eq "true"}
into this:
Get-ADComputer -Filter {name -like $nameregex -and Enabled -eq "true"}
Note, however, that the scriptblock notation for filter statements is misleading, because the statement is actually a string, so it's better to write it as such:
Get-ADComputer -Filter "name -like '$nameregex' -and Enabled -eq 'true'"
And FTR: you're using wildcard matching here (operator -like
), not regular expressions (operator -match
).
If you are looking to reduce the size using coding itself, you can follow this code in php.
<?php
function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
return $destination;
}
$source_img = 'source.jpg';
$destination_img = 'destination .jpg';
$d = compress($source_img, $destination_img, 90);
?>
$d = compress($source_img, $destination_img, 90);
This is just a php function that passes the source image ( i.e., $source_img
), destination image ( $destination_img
) and quality for the image that will take to compress ( i.e., 90 ).
$info = getimagesize($source);
The getimagesize()
function is used to find the size of any given image file and return the dimensions along with the file type.
Use this instead
echo $LINE | sed -e 's/12345678/$replace/g'
this works for me just simply remove the quotes
I just had this problem too. I closed and opened VS2015 and it "fixed" the issue...
Is it possible to add onclick to a div and have it occur if any area of the div is clicked.
Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work
If yes then why is the onclick method not going through to my div.
You are assigning a string where a function is expected.
divTag.onclick = printWorking;
There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.
That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener
You might sort the helper[]
array directly:
java.util.Arrays.sort(helper, 1, helper.length);
Sorts the array from index 1 to the end. Leaves the first item at index 0 untouched.
Multiline comment in bash
: <<'END_COMMENT'
This is a heredoc (<<) redirected to a NOP command (:).
The single quotes around END_COMMENT are important,
because it disables variable resolving and command resolving
within these lines. Without the single-quotes around END_COMMENT,
the following two $() `` commands would get executed:
$(gibberish command)
`rm -fr mydir`
comment1
comment2
comment3
END_COMMENT
If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.
Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)
Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.
If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...
The Scanner should be closed. It is a good practice to close Readers, Streams...and this kind of objects to free up resources and aovid memory leaks; and doing so in a finally block to make sure that they are closed up even if an exception occurs while handling those objects.
Thread.interrupt()
sets the interrupted status/flag of the target thread to true which when checked using Thread.interrupted()
can help in stopping the endless thread. Refer http://www.yegor256.com/2015/10/20/interrupted-exception.html
You can access values in the $_POST
array by their key. $_POST is an associative array, so to access taskOption
you would use $_POST['taskOption'];
.
Make sure to check if it exists in the $_POST array before proceeding though.
<form method="post" action="process.php">
<select name="taskOption">
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
</select>
<input type="submit" value="Submit the form"/>
</form>
process.php
<?php
$option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
if ($option) {
echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
} else {
echo "task option is required";
exit;
}
After reading through manny forums found a really easy solution.
I use redux-form. Urgo mapped redux-from fieldToClass. Upon error I navigate to the first error on the list of syncErrors.
No refs and no third party modules. Just simple querySelector
& scrollIntoView
handleToScroll = (field) => {
const fieldToClass = {
'vehicleIdentifier': 'VehicleIdentifier',
'locationTags': 'LocationTags',
'photos': 'dropzoneContainer',
'description': 'DescriptionInput',
'clientId': 'clientId',
'driverLanguage': 'driverLanguage',
'deliveryName': 'deliveryName',
'deliveryPhone': 'deliveryPhone',
"deliveryEmail": 'deliveryEmail',
"pickupAndReturn": "PickupAndReturn",
"payInCash": "payInCash",
}
document?.querySelector(`.${fieldToClasses[field]}`)
.scrollIntoView({ behavior: "smooth" })
}
If you mark this variable static then as you know, you would be requiring static methods to again access these values,this will be useful if you already think of using these variables only in static methods. If this is so then this would be the best one.
You can however make the variable now as public since no one can modify it just like "System.out", it again depends upon your intentions and what you want to achieve.
Quick and dirty:
LP
== Long Pointer. Just think pointer or char*
C
= Const, in this case, I think they mean the character string is a const, not the pointer being const.
STR
is string
the T
is for a wide character or char (TCHAR) depending on compile options.
I can handle this way:
select to_number(to_char(sysdate,'MI')) - to_number(to_char(*YOUR_DATA_VALUE*,'MI')),max(exp_time) from ...
Or if you want to the hour just change the MI;
select to_number(to_char(sysdate,'HH24')) - to_number(to_char(*YOUR_DATA_VALUE*,'HH24')),max(exp_time) from ...
the others don't work for me. Good luck.
You can escape the calc
arguments in order to prevent them from being evaluated on compilation.
Using your example, you would simply surround the arguments, like this:
calc(~'100% - 10px')
Demo : http://jsfiddle.net/c5aq20b6/
I find that I use this in one of the following three ways:
Everything inside the calc
arguments is defined as a string, and is totally static until it's evaluated by the client:
div {
> span {
width: calc(~'100% - 10px');
}
}
div > span {
width: calc(100% - 10px);
}
You can insert a LESS variable into the string:
div {
> span {
@pad: 10px;
width: calc(~'100% - @{pad}');
}
}
div > span {
width: calc(100% - 10px);
}
You may want to escape a percentage value, but go ahead and evaluate something on compilation:
@btnWidth: 40px;
div {
> span {
@pad: 10px;
width: calc(~'(100% - @{pad})' - (@btnWidth * 2));
}
}
div > span {
width: calc((100% - 10px) - 80px);
}
Source: http://lesscss.org/functions/#string-functions-escape.
I found a good solution that uses the maxlength attribute if the browser supports it, and falls back to an unobtrusive javascript pollyfill in unsupporting browsers.
Thanks to @Dan Tello's comment I fixed it up so it works in IE7+ as well:
HTML:
<textarea maxlength="50" id="text">This textarea has a character limit of 50.</textarea>
Javascript:
function maxLength(el) {
if (!('maxLength' in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function () {
if (this.value.length >= max) return false;
};
}
}
maxLength(document.getElementById("text"));
There is no such thing as a minlength
attribute in HTML5.
For the following input types: number
, range
, date
, datetime
, datetime-local
, month
, time
, and week
(which aren't fully supported yet) use the min
and max
attributes.
c#: "\""
, thus s.Replace("\"", "")
vb/vbs/vb.net: ""
thus s.Replace("""", "")
Unfortunately, no. You will have to cast each value individually.
using redis-cli:
root@server:~# redis-cli
127.0.0.1:6379> CONFIG SET requirepass secret_password
OK
this will set password temporarily (until redis or server restart)
test password:
root@server:~# redis-cli
127.0.0.1:6379> AUTH secret_password
OK
I found that for me the best permanent solution to stay up-to-date under Linux was to install the R-patched project. This will keep your R installation up-to-date, and you needn't even move your packages between installations (which is described in RyanStochastic's answer).
For openSUSE, see the instructions here.
request.data
This is great to use but remember that it comes in as a string and will need iterated through.
This works 1) for multiline text as well 2) and even in IE9!
<div class="measureText" id="measureText">
</div>
.measureText {
margin: 0;
padding: 0;
border: 0;
font-family: Arial;
position: fixed;
visibility: hidden;
height: auto;
width: auto;
white-space: pre-wrap;
line-height: 100%;
}
function getTextFieldMeasure(fontSize, value) {
const div = document.getElementById("measureText");
// returns wrong result for multiline text with last line empty
let arr = value.split('\n');
if (arr[arr.length-1].length == 0) {
value += '.';
}
div.innerText = value;
div.style['font-size']= fontSize + "px";
let rect = div.getBoundingClientRect();
return {width: rect.width, height: rect.height};
};
UPDATE `tbl_user` SET `name`=concat('tbl_user.first_name','tbl_user.last_name') WHERE student_roll>965
Many neural network training algorithms involve making multiple presentations of the entire data set to the neural network. Often, a single presentation of the entire data set is referred to as an "epoch". In contrast, some algorithms present data to the neural network a single case at a time.
"Iteration" is a much more general term, but since you asked about it together with "epoch", I assume that your source is referring to the presentation of a single case to a neural network.
For some reason the responsive table in particular doesn't behave as it should. You can patch it by getting rid of display:block;
.table-responsive {
display: table;
}
I may file a bug report.
Edit:
None of the previous answers either applied or worked for me. In my case, updating the settings of the test project, as follows, fixed it:
For better performance in UITableView
or UICollectionView
use light weight library Smart Lazy Loading You can use this lazy loading approach if you want to load images from url Asynchronous
Smart 'Lazy Loading' in UICollectionView
or UITableView
using NSOperation
and NSOperationQueue
in iOS So in this project we can download the multiple images in any View (UICollectionView
or UITableView
) by optimising the performance of an app by using Operation
and OperationQueue
for concurrency. following are the key point of this project Smart Lazy Loading: Creating image download Service. Prioritise the downloading based on the visibility of cells.
ImageDownloadService class will create a singleton instance and have NSCache instance to cache the images that have been downloaded. We have inherited the Operation class to TOperation to mauled the functionality according to our need. I think the properties of the operation subclass are pretty clear in terms of functionality. We are monitoring operations changes of state by using KVO.
To check your MySQL version on your mac, navigate to the directory where you installed it (default is usr/local/mysql/bin) and issue this command:
./mysql --version
Alternatively, to avoid needing to navigate to that specific dir to run the command, add its location to your path ($PATH). There's more than one way to add a dir to your $PATH (with explanations on stackoverflow and other places on how to do so), such as adding it to your ./bash_profile.
After adding the mysql bin dir to your $PATH, verify it's there by executing:
echo $PATH
Thereafter you can check your mysql version from anywhere by running (note no "./"):
mysql --version
Just create a Pair<TFirst, TSecond>
type and use that as your value.
I have an example of one in my C# in Depth source code. Reproduced here for simplicity:
using System;
using System.Collections.Generic;
public sealed class Pair<TFirst, TSecond>
: IEquatable<Pair<TFirst, TSecond>>
{
private readonly TFirst first;
private readonly TSecond second;
public Pair(TFirst first, TSecond second)
{
this.first = first;
this.second = second;
}
public TFirst First
{
get { return first; }
}
public TSecond Second
{
get { return second; }
}
public bool Equals(Pair<TFirst, TSecond> other)
{
if (other == null)
{
return false;
}
return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&
EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
}
public override bool Equals(object o)
{
return Equals(o as Pair<TFirst, TSecond>);
}
public override int GetHashCode()
{
return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
EqualityComparer<TSecond>.Default.GetHashCode(second);
}
}
mkdir -p
-p, --parents no error if existing, make parent directories as needed
It means that the most portable way to define method implementations of template classes is to define them inside the template class definition.
template < typename ... >
class MyClass
{
int myMethod()
{
// Not just declaration. Add method implementation here
}
};
The exception message says:
Books is not mapped [SELECT COUNT(*) FROM Books]; nested exception is org.hibernate.hql.ast.QuerySyntaxException: Books is not mapped [SELECT COUNT(*) FROM Books]
Books
is not mapped. That is, that there is no mapped type called Books
.
And indeed, there isn't. Your mapped type is called Book
. It's mapped to a table called Books
, but the type is called Book
. When you write HQL (or JPQL) queries, you use the names of the types, not the tables.
So, change your query to:
select count(*) from Book
Although I think it may need to be
select count(b) from Book b
If HQL doesn't support the *
notation.
The best solution is to add to your apache .htaccess
file the following line after RewriteEngine On
RewriteRule ^sitemap\.xml$ sitemap.php [L]
and then simply having a file sitemap.php
in your root folder that would be normally accessible via http://www.yoursite.com/sitemap.xml
, the default URL where all search engines will firstly search.
The file sitemap.php
shall start with
<?php
//Saturday, 11 January 2020 @kevin
header('Content-type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url>
<loc>https://www.yoursite.com/</loc>
<lastmod>2020-01-08T13:06:14+00:00</lastmod>
<priority>1.00</priority>
</url>
</urlset>
it works :)
Building on Allison and Deepak's answer, I started using logrus and really like it:
var log = logrus.New()
func init() {
// log to console and file
f, err := os.OpenFile("crawler.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
wrt := io.MultiWriter(os.Stdout, f)
log.SetOutput(wrt)
}
I have a defer f.Close() in the main function
It is not the asker's problem in this instance but the first troubleshooting step for a generic "AttributeError: __exit__" should be making sure the brackets are there, e.g.
with SomeContextManager() as foo:
#works because a new object is referenced...
not
with SomeContextManager as foo:
#AttributeError because the class is referenced
Catches me out from time to time and I end up here -__-
The previous answers seem all to be a little confusing or incomplete, so here is a table of the differences...
+----------------+-----------------+----------------+----------------+
| Command | Displays Output | Can Get Output | Gets Exit Code |
+----------------+-----------------+----------------+----------------+
| system() | Yes (as text) | Last line only | Yes |
| passthru() | Yes (raw) | No | Yes |
| exec() | No | Yes (array) | Yes |
| shell_exec() | No | Yes (string) | No |
| backticks (``) | No | Yes (string) | No |
+----------------+-----------------+----------------+----------------+
Other misc things to be aware of:
import time
int(time.time())
Output:
1521462189
The following structure in docker-compose.yaml will allow you to have the Dockerfile in a subfolder from the root:
version: '3'
services:
db:
image: postgres:11
environment:
- PGDATA=/var/lib/postgresql/data/pgdata
volumes:
- postgres-data:/var/lib/postgresql/data
ports:
- 127.0.0.1:5432:5432
**web:
build:
context: ".."
dockerfile: dockerfiles/Dockerfile**
command: ...
...
Then, in your Dockerfile, which is in the same directory as docker-compose.yaml, you can do the following:
ENV APP_HOME /home
RUN mkdir -p ${APP_HOME}
# Copy the file to the directory in the container
COPY test.json ${APP_HOME}/test.json
COPY test.py ${APP_HOME}/test.py
# Browse to that directory created above
WORKDIR ${APP_HOME}
You can then run docker-compose from the parent directory like:
docker-compose -f .\dockerfiles\docker-compose.yaml build --no-cache
The only way I think then to get the functionality you want would be to do something like
import junit.framework.Test;
import junit.framework.TestResult;
import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("TestEverything");
//$JUnit-BEGIN$
suite.addTestSuite(TestOne.class);
suite.addTestSuite(TestTwo.class);
suite.addTestSuite(TestThree.class);
//$JUnit-END$
}
public static void main(String[] args)
{
AllTests test = new AllTests();
Test testCase = test.suite();
TestResult result = new TestResult();
setUp();
testCase.run(result);
tearDown();
}
public void setUp() {}
public void tearDown() {}
}
I use something like this in eclipse, so I'm not sure how portable it is outside of that environment
Such thing is easy with ggplot2
library(ggplot2)
dataset <- data.frame(X = c(rep(65, times=5), rep(25, times=5),
rep(35, times=10), rep(45, times=4)))
ggplot(dataset, aes(x = X)) +
geom_histogram(aes(y = ..density..)) +
geom_density()
or to mimic the result from Dirk's solution
ggplot(dataset, aes(x = X)) +
geom_histogram(aes(y = ..density..), binwidth = 5) +
geom_density()
If you import the module (.py) file you are creating now from another python script it will not execute the code within
if __name__ == '__main__':
...
If you run the script directly from the console, it will be executed.
Python does not use or require a main() function. Any code that is not protected by that guard will be executed upon execution or importing of the module.
This is expanded upon a little more at python.berkely.edu
I found a solution, which works, but does result in a Warning
(WARN/Resources(268): Converting to float: TypedValue{t=0x3/d=0x4d "1.2" a=2 r=0x7f06000a}
) in LogCat.
<resources>
<string name="text_line_spacing">1.2</string>
</resources>
<android:lineSpacingMultiplier="@string/text_line_spacing"/>
d4 = dict(d1.items() + d2.items() + d3.items())
alternatively (and supposedly faster):
d4 = dict(d1)
d4.update(d2)
d4.update(d3)
Previous SO question that both of these answers came from is here.
It works nicely.
activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.custom_actionbar, null);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
((TextView) v.findViewById(R.id.title)).setText(FRAGMENT_TITLE);
activity.getSupportActionBar().setCustomView(v, p);
activity.getSupportActionBar().setDisplayShowTitleEnabled(true);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Below layout of custom_actionbar:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:text="Example"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:ellipsize="end"
android:maxLines="1"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@color/colorBlack" />
</RelativeLayout>
Other methods also exist to check but I prefer the following method as my best to check (as you can easily check types of other objects).
> a = [1, 2]
[ 1, 2 ]
>
> Object.prototype.toString.call(a).slice(8,).replace(/\]$/, '')
'Array'
>
> Object.prototype.toString.call([]).slice(8,-1) // best approach
'Array'
Explanation (with simple examples on Node REPL)»
> o = {'ok': 1}
{ ok: 1 }
> a = [1, 2]
[ 1, 2 ]
> typeof o
'object'
> typeof a
'object'
>
> Object.prototype.toString.call(o)
'[object Object]'
> Object.prototype.toString.call(a)
'[object Array]'
>
Object or Array »
> Object.prototype.toString.call(o).slice(8,).replace(/\]$/, '')
'Object'
>
> Object.prototype.toString.call(a).slice(8,).replace(/\]$/, '')
'Array'
>
Null or Undefined »
> Object.prototype.toString.call(undefined).slice(8,).replace(/\]$/, '')
'Undefined'
> Object.prototype.toString.call(null).slice(8,).replace(/\]$/, '')
'Null'
>
String »
> Object.prototype.toString.call('ok').slice(8,).replace(/\]$/, '')
'String'
Number »
> Object.prototype.toString.call(19).slice(8,).replace(/\]$/, '')
'Number'
> Object.prototype.toString.call(19.0).slice(8,).replace(/\]$/, '')
'Number'
> Object.prototype.toString.call(19.7).slice(8,).replace(/\]$/, '')
'Number'
>
I appreciate @mpen
's suggestion to use -1 in place of regular expression as follows.
> Object.prototype.toString.call(12).slice(8,-1)
'Number'
>
> Object.prototype.toString.call(12.0).slice(8,-1)
'Number'
>
> Object.prototype.toString.call([]).slice(8,-1)
'Array'
> Object.prototype.toString.call({}).slice(8,-1)
'Object'
>
> Object.prototype.toString.call('').slice(8,-1)
'String'
>
As described in Cloaking your ASP.NET MVC Web Application on IIS 7, you can turn off the X-AspNet-Version header by applying the following configuration section to your web.config:
<system.web>
<httpRuntime enableVersionHeader="false"/>
</system.web>
and remove the X-AspNetMvc-Version header by altering your Global.asax.cs as follows:
protected void Application_Start()
{
MvcHandler.DisableMvcResponseHeader = true;
}
As described in Custom Headers You can remove the "X-Powered-By" header by applying the following configuration section to your web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
</customHeaders>
</httpProtocol>
</system.webServer>
There is no easy way to remove the "Server" response header via configuration, but you can implement an HttpModule
to remove specific HTTP Headers as described in Cloaking your ASP.NET MVC Web Application on IIS 7 and in how-to-remove-server-x-aspnet-version-x-aspnetmvc-version-and-x-powered-by-from-the-response-header-in-iis7.
physical collection of Class, interface, enum etc which is in IL code. Which can be .EXE or .DLL file .EXE is executable file and .DLL can dynamically used in any .net Supported language.
Remove any whitespace at the start of the .key file.
There's a tagName
property, and a attributes
property as well:
var element = document.getElementById("wtv");
var openTag = "<"+element.tagName;
for (var i = 0; i < element.attributes.length; i++) {
var attrib = element.attributes[i];
openTag += " "+attrib.name + "=" + attrib.value;
}
openTag += ">";
alert(openTag);
See also How to iterate through all attributes in an HTML element? (I did!)
To get the contents between the open and close tags you could probably use innerHTML
if you don't want to iterate over all the child elements...
alert(element.innerHTML);
... and then get the close tag again with tagName
.
var closeTag = "</"+element.tagName+">";
alert(closeTag);
Not sure about solutions but a temporary workaround is to ask eslint to ignore it by adding the following on top of the problem line.
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
I might have a solution for the video as background, stretched to the browser-width or height, (but the video will still preserve the aspect ratio, couldnt find a solution for that yet.):
Put the video right after the body-tag with style="width:100%;"
.
Right afterwords, put a "bodydummy"-tag:
<body>
<video id="bgVideo" autoplay poster="videos/poster.png">
<source src="videos/test-h264-640x368-highqual-winff.mp4" type="video/mp4"/>
<source src="videos/test-640x368-webmvp8-miro.webm" type="video/webm"/>
<source src="videos/test-640x368-theora-miro.ogv" type="video/ogg"/>
</video>
<img id="bgImg" src="videos/poster.png" />
<!-- This image stretches exactly to the browser width/height and lies behind the video-->
<div id="bodyDummy">
Put all your content inside the bodydummy
-div and put the z-indexes correctly in CSS like this:
#bgImg{
position: absolute;
top: 0;
left: 0;
border: 0;
z-index: 1;
width: 100%;
height: 100%;
}
#bgVideo{
position: absolute;
top: 0;
left: 0;
border: 0;
z-index: 2;
width: 100%;
height: 100%;
}
#bodyDummy{
position: absolute;
top: 0;
left: 0;
z-index: 3;
overflow: auto;
width: 100%;
height: 100%;
}
Hope I could help. Let me know when you could find a solution that the video does not maintain the aspect ratio, so it could fill the whole browser window so we do not have to put a bgimage.
Addition to @BalusC 's answer. You also need to set width of headers. In my case, below css can only apply to my table's column width.
.myTable td:nth-child(1),.myTable th:nth-child(1) {
width: 20px;
}
The then()
method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:
getFeed().then(function(data) { vm.feed = data;});
The then()
function returns the promise with a resolved value of the previous then()
callback, allowing you the pass the value to subsequent callbacks:
promiseB = promiseA.then(function(result) {
return result + 1;
});
// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1
You might try changing this line in your persistence.xml from
<property name="hbm2ddl.auto" value="create"/>
to:
<property name="hibernate.hbm2ddl.auto" value="update"/>
This is supposed to maintain the schema to follow any changes you make to the Model each time you run the app.
Got this from JavaRanch
date()
and localtime()
both use the local timezone for the server unless overridden; you can override the timezone used with date_default_timezone_set()
.
http://www.php.net/manual/en/function.date-default-timezone-set.php
I have had this issue before.
client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
do this against your wcf proxy before making the call.
Given the following tables..
Domain Table
dom_id | dom_url
Review Table
rev_id | rev_dom_from | rev_dom_for
Try this sql... (It's pretty much the same thing that Stephen Wrighton wrote above) The trick is that you are basically selecting from the domain table twice in the same query and joining the results.
Select d1.dom_url, d2.dom_id from
review r, domain d1, domain d2
where d1.dom_id = r.rev_dom_from
and d2.dom_id = r.rev_dom_for
If you are still stuck, please be more specific with exactly it is that you don't understand.
There is an appropriate index on column_having_index, and its use actually increase performance, but Oracle didn't use it...
You should gather statistics on your table to let optimizer see that index access can help. Using direct hint is not a good practice.
The examples above are a bit confusing, and this is probably the best way:
$.ajaxSetup({
headers: {
'Authorization': "Basic " + btoa(USERNAME + ":" + PASSWORD)
}
});
I took the above from a combination of Rico and Yossi's answer.
Be careful of race conditions: if the file disappears between the "exists" check and the time you open it, your program will fail unexpectedly.
It's better to go and open the file, check for failure and if all is good then do something with the file. It's even more important with security-critical code.
Details about security and race conditions: http://www.ibm.com/developerworks/library/l-sprace.html
What type is the collection? If it's List, you can use the helpful "RemoveAll":
int cnt = workspace.RoleAssignments
.RemoveAll(spa => spa.Member.Name == shortName)
(This works in .NET 2.0. Of course, if you don't have the newer compiler, you'll have to use "delegate (SPRoleAssignment spa) { return spa.Member.Name == shortName; }" instead of the nice lambda syntax.)
Another approach if it's not a List, but still an ICollection:
var toRemove = workspace.RoleAssignments
.FirstOrDefault(spa => spa.Member.Name == shortName)
if (toRemove != null) workspace.RoleAssignments.Remove(toRemove);
This requires the Enumerable extension methods. (You can copy the Mono ones in, if you are stuck on .NET 2.0). If it's some custom collection that cannot take an item, but MUST take an index, some of the other Enumerable methods, such as Select, pass in the integer index for you.
If you want to use a the openFileInput
method from a Context for this, you can use the following code.
This will create a BufferArrayOutputStream
and append each byte as it's read from the file to it.
/**
* <p>
* Creates a InputStream for a file using the specified Context
* and returns the Bytes read from the file.
* </p>
*
* @param context The context to use.
* @param file The file to read from.
* @return The array of bytes read from the file, or null if no file was found.
*/
public static byte[] read(Context context, String file) throws IOException {
byte[] ret = null;
if (context != null) {
try {
InputStream inputStream = context.openFileInput(file);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int nextByte = inputStream.read();
while (nextByte != -1) {
outputStream.write(nextByte);
nextByte = inputStream.read();
}
ret = outputStream.toByteArray();
} catch (FileNotFoundException ignored) { }
}
return ret;
}
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
Use .getMinutes()
to get the current minutes, then add 20 and use .setMinutes()
to update the date object.
var twentyMinutesLater = new Date();
twentyMinutesLater.setMinutes(twentyMinutesLater.getMinutes() + 20);
% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
You can also check the .IsConnected property of the socket if you were to poll.
If you define classproperty
as follows, then your example works exactly as you requested.
class classproperty(object):
def __init__(self, f):
self.f = f
def __get__(self, obj, owner):
return self.f(owner)
The caveat is that you can't use this for writable properties. While e.I = 20
will raise an AttributeError
, Example.I = 20
will overwrite the property object itself.
Check out the JavaScript onbeforeunload event. It's non-standard JavaScript introduced by Microsoft, however it works in most browsers and their onbeforeunload documentation has more information and examples.
For use the syntax like return Post::getAll();
you should have a magic function __callStatic
in your class where handle all static calls:
public static function __callStatic($method, $parameters)
{
return (new static)->$method(...$parameters);
}
My fix is more simple, create a factory, and implement as one variable. For example
angular.module('myApp', [])_x000D_
_x000D_
// This a searchCustom factory. Copy the factory and implement in the controller_x000D_
.factory("searchCustom", function($http,$log){ _x000D_
return {_x000D_
valuesParams : function(params){_x000D_
paramsResult = [];_x000D_
params = params.replace('(', '').replace(')','').split("&");_x000D_
_x000D_
for(x in params){_x000D_
paramsKeyTmp = params[x].split("=");_x000D_
_x000D_
// Si el parametro esta disponible anexamos al vector paramResult_x000D_
if (paramsKeyTmp[1] !== '' && paramsKeyTmp[1] !== ' ' && _x000D_
paramsKeyTmp[1] !== null){ _x000D_
_x000D_
paramsResult.push(params[x]);_x000D_
}_x000D_
}_x000D_
_x000D_
return paramsResult;_x000D_
}_x000D_
}_x000D_
})_x000D_
_x000D_
.controller("SearchController", function($scope, $http,$routeParams,$log,searchCustom){_x000D_
$ctrl = this;_x000D_
_x000D_
var valueParams = searchCustom.valuesParams($routeParams.value);_x000D_
valueParams = valueParams.join('&');_x000D_
_x000D_
$http({_x000D_
method : "GET",_x000D_
url: webservice+"q?"+valueParams_x000D_
}).then( function successCallback(response){_x000D_
data = response.data;_x000D_
$scope.cantEncontrados = data.length; _x000D_
$scope.dataSearch = data;_x000D_
_x000D_
} , function errorCallback(response){_x000D_
console.log(response.statusText);_x000D_
})_x000D_
_x000D_
})
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body ng-app="myApp">_x000D_
<div ng-controller="SearchController">_x000D_
<form action="#" >_x000D_
_x000D_
_x000D_
<input ng-model="param1" _x000D_
placeholder="param1" />_x000D_
_x000D_
<input ng-model="param2" _x000D_
placeholder="param2"/>_x000D_
_x000D_
<!-- Implement in the html code _x000D_
(param1={{param1}}¶m2={{param2}}) -> this is a one variable, the factory searchCustom split and restructure in the array params_x000D_
--> _x000D_
<a href="#seach/(param1={{param1}}¶m2={{param2}})">_x000D_
<buttom ng-click="searchData()" >Busqueda</buttom>_x000D_
</a>_x000D_
</form> _x000D_
</div>_x000D_
</body>
_x000D_
<div style={{ visibility: this.state.driverDetails.firstName != undefined? 'visible': 'hidden'}}></div>
Checkout the above code. That will do the trick.
You can get current year, month, day etc from a calendar instance
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val hour = c.get(Calendar.HOUR_OF_DAY)
val minute = c.get(Calendar.MINUTE)
If you need it as a LocalDateTime, simply create it by using the parameters you got above
val myLdt = LocalDateTime.of(year, month, day, ... )
In Bootstrap 4 alpha+ you can use this
class margin-bottom-5
The classes are named using the format: {property}-{sides}-{size}
The onBlur
event is fired when you have moved away from an object without necessarily having changed its value.
The onChange
event is only called when you have changed the value of the field and it loses focus.
You might want to take a look at quirksmode's intro to events. This is a great place to get info on what's going on in your browser when you interact with it. His book is good too.
Easiest solution is to add onWheel={ event => event.currentTarget.blur() }}
on input itself.
It varies on implementation and version, but usually it depends on the VM used (e.g. client or server, see -client
and -server
parameters) and on your system memory.
Often for client
the default value is 1/4th of your physical memory or 1GB (whichever is smaller).
Also Java configuration options (command line parameters) can be "outsourced" to environment variables including the -Xmx
, which can change the default (meaning specify a new default). Specifically the JAVA_TOOL_OPTIONS
environment variable is checked by all Java tools and used if exists (more details here and here).
You can run the following command to see default values:
java -XX:+PrintFlagsFinal -version
It gives you a loooong list, -Xmx
is in MaxHeapSize
, -Xms
is in InitialHeapSize
. Filter your output (e.g. |grep
on linux) or save it in a file so you can search in it.
Ignore this answer for now. The other answers, particularly that of aix, are mostly correct. Over the long term they're the way to bet. And if you have enough data (on one benchmark on one machine, it seemed to be about one million entries) ArrayList and LinkedList do currently work as advertized. However, there are some fine points that apply in the early 21st century.
Modern computer technology seems, by my testing, to give an enormous edge to arrays. Elements of an array can be shifted and copied at insane speeds. As a result arrays and ArrayList will, in most practical situations, outperform LinkedList on inserts and deletes, often dramatically. In other words, ArrayList will beat LinkedList at its own game.
The downside of ArrayList is it tends to hang onto memory space after deletions, where LinkedList gives up space as it gives up entries.
The bigger downside of arrays and ArrayList is they fragment free memory and overwork the garbage collector. As an ArrayList expands, it creates new, bigger arrays, copies the old array to the new one, and frees the old one. Memory fills with big contiguous chunks of free memory that are not big enough for the next allocation. Eventually there's no suitable space for that allocation. Even though 90% of memory is free, no individual piece is big enough to do the job. The GC will work frantically to move things around, but if it takes too long to rearrange the space, it will throw an OutOfMemoryException. If it doesn't give up, it can still slow your program way down.
The worst of it is this problem can be hard to predict. Your program will run fine one time. Then, with a bit less memory available, with no warning, it slows or stops.
LinkedList uses small, dainty bits of memory and GC's love it. It still runs fine when you're using 99% of your available memory.
So in general, use ArrayList for smaller sets of data that are not likely to have most of their contents deleted, or when you have tight control over creation and growth. (For instance, creating one ArrayList that uses 90% of memory and using it without filling it for the duration of the program is fine. Continually creating and freeing ArrayList instances that use 10% of memory will kill you.) Otherwise, go with LinkedList (or a Map of some sort if you need random access). If you have very large collections (say over 100,000 elements), no concerns about the GC, and plan lots of inserts and deletes and no random access, run a few benchmarks to see what's fastest.
A very useful solution here for SQLite3. Because the OP does not indicate MySQL specifically and there was a failed attempt to use some solutions on SQLite.
$table_name = 'content_containers';
$container_result = $connect->query("PRAGMA table_info(" . $table_name . ")");
$container_result->setFetchMode(PDO::FETCH_ASSOC);
foreach ($container_result as $conkey => $convalue)
{
$elements[$convalue['name']] = $convalue['name'];
}
This returns an array. Since this is a direct information dump you'll need to iterate over and filter the results to get something like this:
Array
(
[ccid] => ccid
[administration_title] => administration_title
[content_type_id] => content_type_id
[author_id] => author_id
[date_created] => date_created
[language_id] => language_id
[publish_date] => publish_date
[status] => status
[relationship_ccid] => relationship_ccid
[url_alias] => url_alias
)
This is particularly nice to have when the table is empty.
the bast way i use i bind the textblock and combobox to same property and this property should support notifyPropertyChanged.
i used relativeresource to bind to parent view datacontext which is usercontrol to go up datagrid level in binding because in this case the datagrid will search in object that you used in datagrid.itemsource
<DataGridTemplateColumn Header="your_columnName">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.SelectedUnit.Name, Mode=TwoWay}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox DisplayMemberPath="Name"
IsEditable="True"
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.UnitLookupCollection}"
SelectedItem="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.SelectedUnit, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValue="{Binding UnitId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Id" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
How about jQuery.makeArray(obj)
This is how I did it in my app.
You are using prettyfaces too? Then set dispatcher to FORWARD:
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
import subprocess
result = []
win_cmd = 'ipconfig'(curr_user,filename,ip_address)
process = subprocess.Popen(win_cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE )
for line in process.stdout:
print line
result.append(line)
errcode = process.returncode
for line in result:
print line
EDIT: THIS IS WAY BETTER!!! You don't need that old function, sorry. Just do as follows:
Microsoft.Office.Interop.Excel.Range neededRange = currentWS.Range["A1", ((Microsoft.Office.Interop.Excel.Range)currentWS.Cells[nRowCount, nColumnCount])];
That should work like a charm. And for future reference, put the relevant code that you are using inside of your question. Don't make people ask for it in comments. I imagine that's why you got downvoted.
In addition to all other answers, there's an important difference for IE8: If you use display:none
and try to get the element's width or height, IE8 returns 0 (while other browsers will return the actual sizes). IE8 returns correct width or height only for visibility:hidden
.
Unlike Virtualization, containerization uses the same host os. So the container built on linux can not be run on windows and vice versa.
In windows, you have to take help of virtuallization (using Hyper-v) to have same os as your containers's os and then you should be able to run the same.
Docker for windows is similar app which is built on Hyper-v and helps in running linux docker container on windows. But as far as I know, there is nothing as such which helps run windows containers on linux.
You can install csvtool
(on Ubuntu) via
sudo apt-get install csvtool
and then run:
csvtool readable filename | view -
This will make it nice and pretty inside of a read-only vim instance, even if you have some cells with very long values.
May be this can help you guys. Multi Line Ellipses with tooltip hover. https://codepen.io/Anugraha123/pen/WOBdOb
<div>
<p class="cards-values">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc aliquet lorem commodo, semper mauris nec, suscipit nisi. Nullam laoreet massa sit amet leo malesuada imperdiet eu a augue. Sed ac diam quis ante congue volutpat non vitae sem. Vivamus a felis id dui aliquam tempus
</p>
<span class="tooltip"></span>
</div>
Arbitrarily choosing to keep the minimum PIC_ID. Also, avoid using the implicit join syntax.
SELECT U.NAME, MIN(P.PIC_ID)
FROM USERS U
INNER JOIN POSTINGS P1
ON U.EMAIL_ID = P1.EMAIL_ID
INNER JOIN PICTURES P
ON P1.PIC_ID = P.PIC_ID
WHERE P.CAPTION LIKE '%car%'
GROUP BY U.NAME;
Peter, you should really take a look at Canappi, it does all that for you, all you have to do is specify the layout as such:
button mySubmitButton 'Sumbit' (100,100,100,30 + 0,88,0,0) { ... }
From there Canappi will generate the correct objective-c code that detects the device the app is running on and will use:
(100,100,100,30) for iPhone4
(100,**188**,100,30) for iPhone 5
Canappi works like Interface Builder and Story Board combined, except that it is in a textual form. If you already have XIB files, you can convert them so you don't have to recreate the entire UI from scratch.
File -> Settings
Preferences->Project Interpreter->Python Interpreters
If it's not listed add it.
Did you try using double-quotes? Regardless, no one in 2011 should be limited by the native VB6 shell command. Here's a function that uses ShellExecuteEx, much more versatile.
Option Explicit
Private Const SEE_MASK_DEFAULT = &H0
Public Enum EShellShowConstants
essSW_HIDE = 0
essSW_SHOWNORMAL = 1
essSW_SHOWMINIMIZED = 2
essSW_MAXIMIZE = 3
essSW_SHOWMAXIMIZED = 3
essSW_SHOWNOACTIVATE = 4
essSW_SHOW = 5
essSW_MINIMIZE = 6
essSW_SHOWMINNOACTIVE = 7
essSW_SHOWNA = 8
essSW_RESTORE = 9
essSW_SHOWDEFAULT = 10
End Enum
Private Type SHELLEXECUTEINFO
cbSize As Long
fMask As Long
hwnd As Long
lpVerb As String
lpFile As String
lpParameters As String
lpDirectory As String
nShow As Long
hInstApp As Long
lpIDList As Long 'Optional
lpClass As String 'Optional
hkeyClass As Long 'Optional
dwHotKey As Long 'Optional
hIcon As Long 'Optional
hProcess As Long 'Optional
End Type
Private Declare Function ShellExecuteEx Lib "shell32.dll" Alias "ShellExecuteExA" (lpSEI As SHELLEXECUTEINFO) As Long
Public Function ExecuteProcess(ByVal FilePath As String, ByVal hWndOwner As Long, ShellShowType As EShellShowConstants, Optional EXEParameters As String = "", Optional LaunchElevated As Boolean = False) As Boolean
Dim SEI As SHELLEXECUTEINFO
On Error GoTo Err
'Fill the SEI structure
With SEI
.cbSize = Len(SEI) ' Bytes of the structure
.fMask = SEE_MASK_DEFAULT ' Check MSDN for more info on Mask
.lpFile = FilePath ' Program Path
.nShow = ShellShowType ' How the program will be displayed
.lpDirectory = PathGetFolder(FilePath)
.lpParameters = EXEParameters ' Each parameter must be separated by space. If the lpFile member specifies a document file, lpParameters should be NULL.
.hwnd = hWndOwner ' Owner window handle
' Determine launch type (would recommend checking for Vista or greater here also)
If LaunchElevated = True Then ' And m_OpSys.IsVistaOrGreater = True
.lpVerb = "runas"
Else
.lpVerb = "Open"
End If
End With
ExecuteProcess = ShellExecuteEx(SEI) ' Execute the program, return success or failure
Exit Function
Err:
' TODO: Log Error
ExecuteProcess = False
End Function
Private Function PathGetFolder(psPath As String) As String
On Error Resume Next
Dim lPos As Long
lPos = InStrRev(psPath, "\")
PathGetFolder = Left$(psPath, lPos - 1)
End Function
I think this is because you are using client software and not the server.
mysql
is client mysqld
is the serverTry:
sudo service mysqld start
To check that service is running use: ps -ef | grep mysql | grep -v grep
.
Uninstalling:
sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean
Re-Installing:
sudo apt-get update
sudo apt-get install mysql-server
Backup entire folder before doing this:
sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade
It looks like your Google Play registration payment didn’t process. This can happen sometimes if a card has expired, the credit card or credit card verification (CVC) number was entered incorrectly, or if your billing address doesn't match the address in your Google Payments account.
Here’s how you can find the details of your transaction:
Sign in to your Google Payments account at https://payments.google.com.
On the left menu, select the “Subscriptions and services” page.
On the “Other purchase activity” card, click View purchases.
Click the “Google Play” registration transaction to see your payment method.
You can click “Payment methods” on the left menu if you need to edit the addresses on your Google Payments account.
To add a new credit or debit card to your account, you can follow the instructions on the Google Payments Help Center (https://support.google.com/payments/answer/6220309).
HTML
<div id='sample'>
<span class='vertical'>Test Message</span>
</div>
CSS
#sample
{
height:100px;
width:100%;
background-color:#003366;
display:table;
text-align: center;
}
.vertical
{
color:white;
display:table-cell;
vertical-align:middle;
}
Fiddle : Demo
Use the Find method if item_manuf_id
is a primary key:
var result = dtPs.Rows.Find("some value");
If you only want to know if the value is in there then use the Contains method.
if (dtPs.Rows.Contains("some value"))
{
...
}
Primary key restriction applies to Contains
aswell.
$('#myForm').bind('submit', function () {
var elements = this.elements;
});
The elements variable will contain all the inputs, selects, textareas and fieldsets within the form.
You have to use br when using echo , like this :
echo "Thanks for your email" ."<br>". "Your orders details are below:"
and it will work properly
I have my images in a separate class library ("MyClassLibrary") and they are placed in the folder "Images". In the example I used "myImage.jpg" as the background image.
ImageBrush myBrush = new ImageBrush();
Image image = new Image();
image.Source = new BitmapImage(
new Uri(
"pack://application:,,,/MyClassLibrary;component/Images/myImage.jpg"));
myBrush.ImageSource = image.Source;
Grid grid = new Grid();
grid.Background = myBrush;
Download the latest build from https://github.com/macvim-dev/macvim/releases
Expand the archive.
Put MacVim.app into /Applications/
.
Done.
Edit - this answer was for an earlier version of Charles. See @semicircle21 answer below for the proper steps for v3.10.x -- much easier than this approach too... :-)
For what it's worth here are the step by step instructions for this. They should apply equally well in iOS too:
You should then be able to see the SSL files in Charles. If you want to intercept and change the values you can use the "Map Local" tool which is really awesome:
I had to add a Return-Path header in emails send by a Redmine instance. I agree with greatwolf only the sender can determine a correct (non default) Return-Path. The case is the following : E-mails are send with the default email address : [email protected] But we want that the real user initiating the action receives the bounce emails, because he will be the one knowing how to fix wrong recipients emails (and not the application adminstrators that have other cats to whip :-) ). We use this and it works perfectly well with exim on the application server and zimbra as the final company mail server.
Here's how I solved this problem.
Done :)
Use git rm foo
to stage the file for deletion. (This will also delete the file from the file system, if it hadn't been previously deleted. It can, of course, be restored from git, since it was previously checked in.)
To stage the file for deletion without deleting it from the file system, use git rm --cached foo
Try doing this :
recipients="[email protected],[email protected],[email protected]"
And another approach, using shell here-doc :
/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from
Example Message
EOF
Be sure to separate the headers from the body with a blank line as per RFC 822.
The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.
If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.
Conceptually, the simplest regular expressions are literal characters. The pattern N
matches the character 'N'.
Regular expressions next to each other match sequences. For example, the pattern Nick
matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.
If you've ever used grep
on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re
in grep
refers to regular expressions.)
Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick
. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c]
matches either 'a' or 'b' or 'c'.
The pattern .
is special: rather than matching a literal dot only, it matches any character†. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...]
.
Think of character classes as menus: pick just one.
Using .
can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]
. Digits are a frequent match target, so you could instead use the shortcut \d
. Others are \s
(whitespace) and \w
(word characters: alphanumerics or underscore).
The uppercased variants are their complements, so \S
matches any non-whitespace character, for example.
From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c
matches 'abc' or 'ac' because the ?
quantifier makes the subpattern it modifies optional. Other quantifiers are
*
(zero or more times)+
(one or more times){n}
(exactly n times){n,}
(at least n times){n,m}
(at least n times but no more than m times)Putting some of these blocks together, the pattern [Nn]*ick
matches all of
The first match demonstrates an important lesson: *
always succeeds! Any pattern can match zero times.
A few other useful examples:
[0-9]+
(and its equivalent \d+
) matches any non-negative integer\d{4}-\d{2}-\d{2}
matches dates formatted like 2019-01-01A quantifier modifies the pattern to its immediate left. You might expect 0abc+0
to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c
. This means 0abc+0
matches '0abc0', '0abcc0', '0abccc0', and so on.
To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0
. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr
.
Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick
. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |
, e.g., (Nick|nick)
.
For another example, you could equivalently write [a-c]
as a|b|c
, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.
Although some characters match themselves, others have special meanings. The pattern \d+
doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+
. A backslash removes the special meaning from the following character.
Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.
For example, say the input is
"Hello," she said, "How are you?"
You might expect ".+"
to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.
To switch from greedy to what you might think of as cautious, add an extra ?
to the quantifier. Now you understand how \((.+?)\)
, the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.
If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.
(As to your confusion, I don't know of any regular-expression dialect where ((.+?))
would do the same thing. I suspect something got lost in transmission somewhere along the way.)
Use the special pattern ^
to match only at the beginning of your input and $
to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.
Say you want to match comments of the form
-- This is a comment --
you'd write ^--\s+(.+)\s+--$
.
Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.
†: The statement above that .
matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n"
, but in practice you rarely expect a pattern such as .+
to cross a newline boundary. Perl regexes have a /s
switch and Java Pattern.DOTALL
, for example, to make .
match any character at all. For languages that don't have such a feature, you can use something like [\s\S]
to match "any whitespace or any non-whitespace", in other words anything.
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
If there may be empty trailing spaces, probably there isn't better solution. COALESCE
is just for problems like yours.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
String header = dataGridView1.Columns[i].HeaderText;
//String cellText = row.Cells[i].Text;
DataGridViewColumn column = dataGridView1.Columns[i]; // column[1] selects the required column
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; // sets the AutoSizeMode of column defined in previous line
int colWidth = column.Width; // store columns width after auto resize
colWidth += 50; // add 30 pixels to what 'colWidth' already is
this.dataGridView1.Columns[i].Width = colWidth; // set the columns width to the value stored in 'colWidth'
}
}
I was trying to fetch table meta data, but had the following error:
Using:
String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";
DatabaseMetaData metaData = connection.getMetaData();
...
metaData.getColumns(...);
returned an empty ResultSet.
But using the following URL instead it worked properly:
String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false";
There was a need to specify: DATABASE_TO_UPPER=false
Based on the most voted answer at below link I came up with the following solution:
declare @mydate date= '2020-11-09';
SELECT DATEADD(month, DATEDIFF(month, 0, @mydate)+1, -1) AS lastOfMonth
You use the ajaxStop to execute code when the ajax are completed:
$(document).ajaxStop(function(){
setTimeout("window.location = 'otherpage.html'",100);
});
FYI, even if an exception is re-raised in the rescue
section, the ensure
block will be executed before the code execution continues to the next exception handler. For instance:
begin
raise "Error!!"
rescue
puts "test1"
raise # Reraise exception
ensure
puts "Ensure block"
end
Without reading your code but just your scenario, I would solve by using localStorage
.
Here's an example, I'll use prompt()
for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
In JQuery 1.12.1, my application uses code:
$('"#raisepay_id"')[0].readOnly=true;
$('"#raisepay_id"')[0].readOnly=false;
and it works.
You can use hash.keys.include?(key)
irb(main):001:0> hash = {"pot" => 1, "tot" => 2, "not" => 3}
=> {"pot"=>1, "tot"=>2, "not"=>3}
irb(main):002:0> key = "not"
=> "not"
irb(main):003:0> hash.keys.include?(key)
=> true
The first line forces a WMI console installation if required on a new build. WMI always returns a consistent string of "Version=x.x.xxxx" so the token parsing is always the same for all Windows versions.
Parsing from the VER output has variable text preceding the version info, making token positions random. Delimiters are only the '=' and '.' characters.
The batch addition allows me to easily check versions as '510' (XP) up to '10000' for Win10. I don't use the Build value.
Setlocal EnableDelayedExpansion
wmic os get version /value 1>nul 2>nul
if %errorlevel% equ 0 (
for /F "tokens=2,3,4 delims==." %%A In ('wmic os get version /value') Do (
(Set /A "_MAJ=%%A")
(Set /A "_MIN=%%B")
(Set /A "_BLD=%%C")
)
(Set /A "_OSVERSION=!_MAJ!*100")
(Set /A "_OSVERSION+=!_MIN!*10")
)
endlocal
Something a bit more functional, without Regex:
public static int count(String s, char c) {
return s.length()==0 ? 0 : (s.charAt(0)==c ? 1 : 0) + count(s.substring(1),c);
}
It's no tail recursive, for the sake of clarity.
This question might still be visited often enough that it's worth offering an addendum to Mr Kassies' answer. The dict
built-in class can be sub-classed so that a default is returned for 'missing' keys. This mechanism works well for pandas. But see below.
In this way it's possible to avoid key errors.
>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> class SurnameMap(dict):
... def __missing__(self, key):
... return ''
...
>>> surnamemap = SurnameMap()
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap[x])
>>> df
ID Surname
0 101 Mohanty
1 201
2 301 Drake
3 401
The same thing can be done more simply in the following way. The use of the 'default' argument for the get
method of a dict object makes it unnecessary to subclass a dict.
>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> surnamemap = {}
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap.get(x, ''))
>>> df
ID Surname
0 101 Mohanty
1 201
2 301 Drake
3 401
We ended up using AWS CloudFront with expiring URLs. The video will load, but by the time the user right clicks and chooses Save As the video url they initially received has expired. Do a search for CloudFront Origin Access Identity.
Producing the video url requires a key pair which can be created in the AWS CLI. FYI this is not my code but it works great!
$resource = 'http://cdn.yourwebsite.com/videos/yourvideourl.mp4';
$timeout = 4;
//This comes from key pair you generated for cloudfront
$keyPairId = "AKAJSDHFKASWERASDF";
$expires = time() + $timeout; //Time out in seconds
$json = '{"Statement":[{"Resource":"'.$resource.'","Condition" {"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';
//Read Cloudfront Private Key Pair
$fp=fopen("/absolute/path/to/your/cloudfront_privatekey.pem","r");
$priv_key=fread($fp,8192);
fclose($fp);
//Create the private key
$key = openssl_get_privatekey($priv_key);
if(!$key)
{
echo "<p>Failed to load private key!</p>";
return;
}
//Sign the policy with the private key
if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1))
{
echo '<p>Failed to sign policy: '.openssl_error_string().'</p>';
return;
}
//Create url safe signed policy
$base64_signed_policy = base64_encode($signed_policy);
$signature = str_replace(array('+','=','/'), array('-','_','~'), $base64_signed_policy);
//Construct the URL
$url = $resource.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;
return '<div class="videowrapper" ><video autoplay controls style="width:100%!important;height:auto!important;"><source src="'.$url.'" type="video/mp4">Your browser does not support the video tag.</video></div>';
Here's an alternate approach to the 'round up' part. Not the most brilliantly coded solution but it gets the job done, and this type of syntax is a bit easier to remember (plus would work for alignment values that aren't a power of 2). The uintptr_t
cast was necessary to appease the compiler; pointer arithmetic isn't very fond of division or multiplication.
void *mem = malloc(1024 + 15);
void *ptr = (void*) ((uintptr_t) mem + 15) / 16 * 16;
memset_16aligned(ptr, 0, 1024);
free(mem);
How to find out what this MySQL Error is trying to say:
#1064 - You have an error in your SQL syntax;
This error has no clues in it. You have to double check all of these items to see where your mistake is:
!@#$%^&*()-_=+[]{}\|;:'",<>/?
select
, into
, or countless others. Take away as much as you can from the broken query until it starts working. And then use PostgreSQL next time that has a sane syntax reporting system.
try adding this to your js function:
var outputvar = document.getElementById("your_div_id_inside_html_form");
outputvar.innerHTML='<input id=id_to_send_to_php value='+your_js_var+'>';
Later in html:
<div id="id_you_choosed_for_outputvar"></div>
this div will contain the js var to be passed through a form to another js function or to php, remember to place it inside your html form!. This solution is working fine for me.
In your specific geolocation case you can try adding the following to function showPosition(position):
var outputlon = document.getElementById("lon1");
outputlon.innerHTML = '<input id=lon value='+lon+'>';
var outputlat = document.getElementById("lat1");
outputlat.innerHTML = '<input id=lat value='+lat+'>';
later add these div to your html form:
<div id=lat1></div>
<div id=lon1></div>
In these div you'll get latitude and longitude as input values for your php form, you would better hide them using css (show only the marker on a map if used) in order to avoid users to change them before to submit, and set your database to accept float values with lenght 10,7.
Hope this will help.
If You are using windows then go to python installation path like.
D:\Python37\Scripts>pip install Flask
it take some movement to download the package.
In spherical geometry shapes are defined by points, lines and angles between those lines. You have only those rudimentary values to work with.
Therefore a circle (in terms of a a shape projected onto a sphere) is something that must be approximated using points. The more points, the more it'll look like a circle.
Having said that, realize that google maps is projecting the earth onto a flat surface (think "unrolling" the earth and stretching+flattening until it looks "square"). And if you have a flat coordinate system you can draw 2D objects on it all you want.
In other words you can draw a scaled vector circle on a google map. The catch is, google maps doesn't give it to you out of the box (they want to stay as close to GIS values as is pragmatically possible). They only give you GPolygon which they want you to use to approximate a circle. However, this guy did it using vml for IE and svg for other browsers (see "SCALED CIRCLES" section).
Now, going back to your question about Google Latitude using a scaled circle image (and this is probably the most useful to you): if you know the radius of your circle will never change (eg it's always 10 miles around some point), then the easiest solution would be to use a GGroundOverlay, which is just an image url + the GLatLngBounds the image represents. The only work you need to do then is cacluate the GLatLngBounds representing your 10 mile radius. Once you have that, the google maps api handles scaling your image as the user zooms in and out.
For me, I had linked v7 appcompat twice. Anyhow, in Eclipse, right click the project name in Package Explorer or Navigator, go to Properties, Android, and uncheck any duplicates in the Library section. You may need to Build --> Clean afterwards.
First we need to find a Button
:
Button mButton = (Button) findViewById(R.id.my_button);
After that, you must implement View.OnClickListener
and there you should find the TextView
and execute the method setText
:
mButton.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
mTextView.setText("Some Text");
}
});
.NET is seeing an invalid SSL certificate on the other end of the connection. There is a workaround for it, but obviously not recommended for production code:
// Put this somewhere that is only once - like an initialization method
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateCertificate);
...
static bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
Go to build path... delete existing maven library u added... click add library ... click maven managed dependencies... then click maven project settings... check resolve maven dependencies check box..it'll download all maven dependencies
using sklearn library preprocessing class
from sklearn.impute import SimpleImputer
missingvalues = SimpleImputer(missing_values = np.nan, strategy = 'mean', axis = 0)
missingvalues = missingvalues.fit(x[:,1:3])
x[:,1:3] = missingvalues.transform(x[:,1:3])
Note: In the recent version parameter missing_values
value change to np.nan
from NaN
I agree with Cat Plus Plus's answer. However, if you know this will only be used on Unix-like OSes, you can use external calls to the shell commands mkdir
, chmod
, and chown
. Make sure to pass extra flags to recursively affect directories:
>>> import subprocess
>>> subprocess.check_output(['mkdir', '-p', 'first/second/third'])
# Equivalent to running 'mkdir -p first/second/third' in a shell (which creates
# parent directories if they do not yet exist).
>>> subprocess.check_output(['chown', '-R', 'dail:users', 'first'])
# Recursively change owner to 'dail' and group to 'users' for 'first' and all of
# its subdirectories.
>>> subprocess.check_output(['chmod', '-R', 'g+w', 'first'])
# Add group write permissions to 'first' and all of its subdirectories.
EDIT I originally used commands
, which was a bad choice since it is deprecated and vulnerable to injection attacks. (For example, if a user gave input to create a directory called first/;rm -rf --no-preserve-root /;
, one could potentially delete all directories).
EDIT 2 If you are using Python less than 2.7, use check_call
instead of check_output
. See the subprocess
documentation for details.
This function does a normal round if the number is bigger than 10**(-decimal_positions), otherwise adds more decimal until the number of meaningful decimal positions is reached:
def smart_round(x, decimal_positions):
dp = - int(math.log10(abs(x))) if x != 0.0 else int(0)
return round(float(x), decimal_positions + dp if dp > 0 else decimal_positions)
Hope it helps.
Use:
IF Var IS NULL THEN
var := 5;
END IF;
Oracle 9i+:
var = COALESCE(Var, 5)
Other alternatives:
var = NVL(var, 5)
Reference:
INTRODUCTION
So far reading through so many answers would give anyone a headache. Anyone trying to know the concept would need to know the following prerequisites.
Function overloading Definition
, Function Length property
, Function argument property
Function overloading
in its simplest form means that a function performs different tasks on the basis of number of arguments that are being passed to it. Notably the TASK1, TASK2 and TASK3 are highlighted below and are being performed on the basis of the number of arguments
being passed to the same function fooYo
.
// if we have a function defined below
function fooYo(){
// do something here
}
// on invoking fooYo with different number of arguments it should be capable to do different things
fooYo(); // does TASK1
fooYo('sagar'); // does TASK2
fooYo('sagar','munjal'); // does TAKS3
NOTE - JS does not provide inbuilt ability of function overloading.
Alternative
John E Resig (creator of JS) has pointed out an alternative which uses the above prerequisites to achieve the ability to implement function overloading.
The code below uses a straightforward but naive approach by using if-else
or switch
statement.
argument-length
property.var ninja = {_x000D_
whatever: function() {_x000D_
switch (arguments.length) {_x000D_
case 0:_x000D_
/* do something */_x000D_
break;_x000D_
case 1:_x000D_
/* do something else */_x000D_
break;_x000D_
case 2:_x000D_
/* do yet something else */_x000D_
break;_x000D_
//and so on ..._x000D_
} _x000D_
}_x000D_
}
_x000D_
Another technique is much more clean and dynamic. The highlight of this technique is the addMethod
generic function.
we define a function addMethod
which is used to add different functions to an object with the same name but different functionalities.
below the addMethod
function accepts three params object name object
, function name name
and the function that we want to be invoked fn
.
addMethod
definition var old
stores the reference to the previous function
being stored by the help of closure - a protective bubble.function addMethod(object, name, fn) {_x000D_
var old = object[name];_x000D_
object[name] = function(){_x000D_
if (fn.length == arguments.length)_x000D_
return fn.apply(this, arguments)_x000D_
else if (typeof old == 'function')_x000D_
return old.apply(this, arguments);_x000D_
};_x000D_
};
_x000D_
addMethod
adds three functions which when invoked using ninja.whatever(x)
with the number of arguments x
which can be anything i.e. either blank or one or more than one invokes different functions as defined while making use of the addMethod
function.var ninja = {};_x000D_
debugger;_x000D_
_x000D_
_x000D_
addMethod(ninja,'whatever',function(){ console.log("I am the one with ZERO arguments supplied") });_x000D_
addMethod(ninja,'whatever',function(a){ console.log("I am the one with ONE arguments supplied") });_x000D_
addMethod(ninja,'whatever',function(a,b){ console.log("I am the one with TWO arguments supplied") });_x000D_
_x000D_
_x000D_
ninja.whatever();_x000D_
ninja.whatever(1,2);_x000D_
ninja.whatever(3);
_x000D_
Heap dumps anytime you wish to see what is being held in memory Out-of-memory errors Heap dumps - picture of in memory objects - used for memory analysis Java cores - also known as thread dumps or java dumps, used for viewing the thread activity inside the JVM at a given time. IBM javacores should a lot of additional information besides just the threads and stacks -- used to determine hangs, deadlocks, and reasons for performance degredation System cores
With SharePoint 2013 new library, I managed to do something like this:
private void UploadToSharePoint(string p, out string newUrl) //p is path to file to load
{
string siteUrl = "https://myCompany.sharepoint.com/site/";
//Insert Credentials
ClientContext context = new ClientContext(siteUrl);
SecureString passWord = new SecureString();
foreach (var c in "mypassword") passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("myUserName", passWord);
Web site = context.Web;
//Get the required RootFolder
string barRootFolderRelativeUrl = "Shared Documents/foo/bar";
Folder barFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl);
//Create new subFolder to load files into
string newFolderName = baseName + DateTime.Now.ToString("yyyyMMddHHmm");
barFolder.Folders.Add(newFolderName);
barFolder.Update();
//Add file to new Folder
Folder currentRunFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl + "/" + newFolderName);
FileCreationInformation newFile = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(@p), Url = Path.GetFileName(@p), Overwrite = true };
currentRunFolder.Files.Add(newFile);
currentRunFolder.Update();
context.ExecuteQuery();
//Return the URL of the new uploaded file
newUrl = siteUrl + barRootFolderRelativeUrl + "/" + newFolderName + "/" + Path.GetFileName(@p);
}
both your conditions are the same:
if(s < f) { calc = f - s; n = s; }else if(f > s){ calc = s - f; n = f; }
so
if(s < f)
and
}else if(f > s){
are the same
change to
}else if(f < s){
Why not just wrap the "osopen" with a try/except and let the underlying OS sort out whether the file is valid?
This seems like much less work and is valid no matter which OS you use.
long millisecond = beginupd.getTime();
Date.getTime()
JavaDoc states:
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
I am running Sierra, and was working on this for a while (trying all recommended solutions). I became confounded so eventually tried restarting my computer! It worked
my conclusion is that sometimes a hard reset is necessary
You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet
of Note
s, where you need to pass in a single Note
.
You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())