Change function file_get_content()
in your code to file_get_contents()
. You are missing 's' at the end of function name. That is why it is giving undefined function error.
Remove last unnecessary comma after $image
filed in line
"INSERT INTO content VALUES ('','','','','','','','','','$image_name','$image',)
<?php
function generate_thumb_now($field_name = '',$target_folder ='',$file_name = '', $thumb = FALSE, $thumb_folder = '', $thumb_width = '',$thumb_height = ''){
//folder path setup
$target_path = $target_folder;
$thumb_path = $thumb_folder;
//file name setup
$filename_err = explode(".",$_FILES[$field_name]['name']);
$filename_err_count = count($filename_err);
$file_ext = $filename_err[$filename_err_count-1];
if($file_name != '')
{
$fileName = $file_name.'.'.$file_ext;
}
else
{
$fileName = $_FILES[$field_name]['name'];
}
//upload image path
$upload_image = $target_path.basename($fileName);
//upload image
if(move_uploaded_file($_FILES[$field_name]['tmp_name'],$upload_image))
{
//thumbnail creation
if($thumb == TRUE)
{
$thumbnail = $thumb_path.$fileName;
list($width,$height) = getimagesize($upload_image);
$thumb_create = imagecreatetruecolor($thumb_width,$thumb_height);
switch($file_ext){
case 'jpg':
$source = imagecreatefromjpeg($upload_image);
break;
case 'jpeg':
$source = imagecreatefromjpeg($upload_image);
break;
case 'png':
$source = imagecreatefrompng($upload_image);
break;
case 'gif':
$source = imagecreatefromgif($upload_image);
break;
default:
$source = imagecreatefromjpeg($upload_image);
}
imagecopyresized($thumb_create, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width,$height);
switch($file_ext){
case 'jpg' || 'jpeg':
imagejpeg($thumb_create,$thumbnail,100);
break;
case 'png':
imagepng($thumb_create,$thumbnail,100);
break;
case 'gif':
imagegif($thumb_create,$thumbnail,100);
break;
default:
imagejpeg($thumb_create,$thumbnail,100);
}
}
return $fileName;
}
else
{
return false;
}
}
if(!empty($_FILES['image']['name'])){
$upload_img = generate_thumb_now('image','uploads/','',TRUE,'uploads /thumbs/','400','320');
//full path of the thumbnail image
$thumb_src = 'uploads/thumbs/'.$upload_img;
//set success and error messages
$message = $upload_img?"<span style='color:#008000;'>Image thumbnail created successfully.</span>":"<span style='color:#F00000;'>Some error occurred, please try again.</span>";
}else{
//if form is not submitted, below variable should be blank
$thumb_src = '';
$message = '';
}
?>
<html>
<head>Image upload and generate thumbnail</head>
<body>
<div class="messages"><?php echo $message; ?></div>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php if($thumb_src != ''){ ?>
<div class="gallery">
<ul>
<li><img src="<?php echo $thumb_src; ?>" alt=""></li>
</ul>
</div>
<?php } ?>
</body>
</html>
I think this may answer your question.
Non-static method ..... should not be called statically
If the method is not static you need to initialize it like so:
$var = new ClassName();
$var->method();
Or, in PHP 5.4+, you can use this syntax:
(new ClassName)->method();
A variation of the function provided by Paolo Bergantino that works directly on String:
String.prototype.addSlashes = function()
{
//no need to do (str+'') anymore because 'this' can only be a string
return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
By adding the code above in your library you will be able to do:
var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());
EDIT:
Following suggestions in the comments, whoever is concerned about conflicts amongst JavaScript libraries can add the following code:
if(!String.prototype.addSlashes)
{
String.prototype.addSlashes = function()...
}
else
alert("Warning: String.addSlashes has already been declared elsewhere.");
It is better to also escape SQL reserved words. For example:
function ms_escape_string($data) {
if (!isset($data) or empty($data))
return '';
if (is_numeric($data))
return $data;
$non_displayables = array(
'/%0[0-8bcef]/', // URL encoded 00-08, 11, 12, 14, 15
'/%1[0-9a-f]/', // url encoded 16-31
'/[\x00-\x08]/', // 00-08
'/\x0b/', // 11
'/\x0c/', // 12
'/[\x0e-\x1f]/', // 14-31
'/\27/'
);
foreach ($non_displayables as $regex)
$data = preg_replace( $regex, '', $data);
$reemplazar = array('"', "'", '=');
$data = str_replace($reemplazar, "*", $data);
return $data;
}
Imagine you've thread A and thread B. They are both synchronised
on the same object and inside this block there's a global variable they are both updating;
static boolean commonVar = false;
Object lock = new Object;
...
void threadAMethod(){
...
while(commonVar == false){
synchornized(lock){
...
commonVar = true
}
}
}
void threadBMethod(){
...
while(commonVar == true){
synchornized(lock){
...
commonVar = false
}
}
}
So, when thread A enters in the while
loop and holds the lock, it does what it has to do and set the commonVar
to true
. Then thread B comes in, enters in the while
loop and since commonVar
is true
now, it is be able to hold the lock. It does so, executes the synchronised
block, and sets commonVar
back to false
. Now, thread A again gets it's new CPU window, it was about to quit the while
loop but thread B has just set it back to false
, so the cycle repeats over again. Threads do something (so they're not blocked in the traditional sense) but for pretty much nothing.
It maybe also nice to mention that livelock does not necessarily have to appear here. I'm assuming that the scheduler favours the other thread once the synchronised
block finish executing. Most of the time, I think it's a hard-to-hit expectation and depends on many things happening under the hood.
I use this code to format floats. It is based on toPrecision()
but it strips unnecessary zeros. I would welcome suggestions for how to simplify the regex.
function round(x, n) {
var exp = Math.pow(10, n);
return Math.floor(x*exp + 0.5)/exp;
}
Usage example:
function test(x, n, d) {
var rounded = rnd(x, d);
var result = rounded.toPrecision(n);
result = result.replace(/\.?0*$/, '');
result = result.replace(/\.?0*e/, 'e');
result = result.replace('e+', 'e');
return result;
}
document.write(test(1.2000e45, 3, 2) + '=' + '1.2e45' + '<br>');
document.write(test(1.2000e+45, 3, 2) + '=' + '1.2e45' + '<br>');
document.write(test(1.2340e45, 3, 2) + '=' + '1.23e45' + '<br>');
document.write(test(1.2350e45, 3, 2) + '=' + '1.24e45' + '<br>');
document.write(test(1.0000, 3, 2) + '=' + '1' + '<br>');
document.write(test(1.0100, 3, 2) + '=' + '1.01' + '<br>');
document.write(test(1.2340, 4, 2) + '=' + '1.23' + '<br>');
document.write(test(1.2350, 4, 2) + '=' + '1.24' + '<br>');
public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
I've added inetAddress
instanceof Inet4Address
to check if it is a ipv4 address.
Use PHP Document Object Model:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
//get all H1
$items = $DOM->getElementsByTagName('h1');
//display all H1 text
for ($i = 0; $i < $items->length; $i++)
echo $items->item($i)->nodeValue . "<br/>";
?>
This outputs as:
T1
T2
T3
[EDIT]: After OP Clarification:
If you want the content like Lorem ipsum. etc, you can directly use this regex:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>
this outputs:
Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG
I came up with the following solution:
SELECT [Str], DecimalParsed = CASE
WHEN ISNUMERIC([Str]) = 1 AND CHARINDEX('.', [Str])=0 AND LEN(REPLACE(REPLACE([Str], '-', ''), '+', '')) < 29 THEN CONVERT(decimal(38,10), [Str])
WHEN ISNUMERIC([Str]) = 1 AND (CHARINDEX('.', [Str])!=0 AND CHARINDEX('.', REPLACE(REPLACE([Str], '-', ''), '+', ''))<=29) THEN
CONVERT(decimal(38,10),
CASE WHEN LEN([Str]) - LEN(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([Str], '0', ''), '1', ''), '2', ''), '3', ''), '4', ''), '5', ''), '6', ''), '7', ''), '8', ''), '9', '')) <= 38
THEN [Str]
ELSE SUBSTRING([Str], 1, 38 + LEN(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([Str], '0', ''), '1', ''), '2', ''), '3', ''), '4', ''), '5', ''), '6', ''), '7', ''), '8', ''), '9', ''))) END)
ELSE NULL END
FROM TestStrToDecimal
I know it looks like an overkill and probably it is, but it works for me (checked both positive, negative, big and small numbers of different precision and scale - everything is converted to decimal(38,10)
or NULL
).
It is hard-coded to decimal(38,10)
type, so if you need different precision, change the constants in the code (38, 10, 29).
How it works? The result is:
each case is separate WHEN statement inthe code above.
Here are few examples of conversion:
I solved this with one code line, as follow: In file index.php, at your template root, after this code line:
defined( '_JEXEC' ) or die( 'Restricted access' );
paste this line: ini_set ('display_errors', 'Off');
Don't worry, be happy...
posted by Jenio.
Use the WINAPI CreateDirectory()
function to create a folder.
You can use this function without checking if the directory already exists as it will fail but GetLastError()
will return ERROR_ALREADY_EXISTS
:
if (CreateDirectory(OutputFolder.c_str(), NULL) ||
ERROR_ALREADY_EXISTS == GetLastError())
{
// CopyFile(...)
}
else
{
// Failed to create directory.
}
The code for constructing the target file is incorrect:
string(OutputFolder+CopiedFile).c_str()
this would produce "D:\testEmploi Nam.docx"
: there is a missing path separator between the directory and the filename. Example fix:
string(OutputFolder+"\\"+CopiedFile).c_str()
You are getting the same random number each time, because you are setting a seed inside the loop. Even though you're using time()
, it only changes once per second, so if your loop completes in a second (which it likely will), you'll get the same seed value each time, and the same initial random number.
Move the srand()
call outside the loop (and call it only once, at the start of your app) and you should get random "random" numbers.
You can simply traverse through the object and return if a match is found.
Here is the code:
returnKeyforValue : function() {
var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
for (key in JsonObj) {
if(JsonObj[key] === "Keyvalue") {
return key;
}
}
}
git-rebase(1) does exactly that.
$ git rebase -i HEAD~5
git awsome-ness [git rebase --interactive] contains an example.
git-rebase
on public (remote) commits.commit
or stash
your current changes).$EDITOR
.pick
before C
and D
by squash
. It will meld C and D into B. If you want to delete a commit then just delete its line.If you are lost, type:
$ git rebase --abort
Use <br/>
. For example:
Change log, upgrade version
Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`
My solution is to write a static method inside the fragment:
public TheFragment setData(TheData data) {
TheFragment tf = new TheFragment();
tf.data = data;
return tf;
}
This way I am sure that all the data I need is inside the Fragment before any other possible operation which could need to work with it. Also it looks cleaner in my opinion.
Are you using MySQL
or PostgreSQL
?
You want to use JOIN syntax, not UNION. For example, using INNER JOIN:
CREATE VIEW V AS
SELECT POP.country, POP.year, POP.pop, FOOD.food, INCOME.income
FROM POP
INNER JOIN FOOD ON (POP.country=FOOD.country) AND (POP.year=FOOD.year)
INNER JOIN INCOME ON (POP.country=INCOME.country) AND (POP.year=INCOME.year)
However, this will only show results when each country and year are present in all three tables. If this is not what you want, look into left outer joins (using the same link above).
Simple way:
directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
<?php
$string = implode('|',$types);
However, Incognito is right, you probably don't want to store it that way -- it's a total waste of the relational power of your database.
If you're dead-set on serializing, you might also consider using json_encode()
All Elements
$('#tabla > tbody > tr').each(function() {
$(this).find("td:gt(0)").each(function(){
alert($(this).html());
});
});
If you only want to check for the presence of abc
in any string in the list, you could try
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in some_list):
# whatever
If you really want to get all the items containing abc
, use
matching = [s for s in some_list if "abc" in s]
For transitions you can use the following to detect the end of a transition via jQuery:
$("#someSelector").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });
Mozilla has an excellent reference:
For animations it's very similar:
$("#someSelector").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });
Note that you can pass all of the browser prefixed event strings into the bind() method simultaneously to support the event firing on all browsers that support it.
Update:
Per the comment left by Duck: you use jQuery's .one()
method to ensure the handler only fires once. For example:
$("#someSelector").one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });
$("#someSelector").one("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });
Update 2:
jQuery bind()
method has been deprecated, and on()
method is preferred as of jQuery 1.7
. bind()
You can also use off()
method on the callback function to ensure it will be fired only once. Here is an example which is equivalent to using one()
method:
$("#someSelector")
.on("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd",
function(e){
// do something here
$(this).off(e);
});
References:
You can use regular expressions in Javascript to do pattern matching of strings.
For example:
var s = "hello world!";
if (s.match(/hello.*/)) {
// do something
}
The match()
test is much like WHERE s LIKE 'hello%'
in SQL.
You can use stem method to get file name.
Here is an example:
from pathlib import Path
p = Path(r"\\some_directory\subdirectory\my_file.txt")
print(p.stem)
# my_file
Anvakas brilliant code is for Windows Desktop applications. If you are like me and needed the same solution for Windows Store apps this code might be handy:
public static class FocusExtension
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool)obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached(
"IsFocused", typeof(bool), typeof(FocusExtension),
new PropertyMetadata(false, OnIsFocusedPropertyChanged));
private static void OnIsFocusedPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
if ((bool)e.NewValue)
{
var uie = d as Windows.UI.Xaml.Controls.Control;
if( uie != null )
{
uie.Focus(FocusState.Programmatic);
}
}
}
}
As Get-Date
returns a DateTime object you are able to compare them directly. An example:
(get-date 2010-01-02) -lt (get-date 2010-01-01)
will return false.
That's probably a requireJS module definition
Check here for more details
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
use the dynamic keyword as return type.
private dynamic getValuesD<T>()
{
if (typeof(T) == typeof(int))
{
return 0;
}
else if (typeof(T) == typeof(string))
{
return "";
}
else if (typeof(T) == typeof(double))
{
return 0;
}
else
{
return false;
}
}
int res = getValuesD<int>();
string res1 = getValuesD<string>();
double res2 = getValuesD<double>();
bool res3 = getValuesD<bool>();
// dynamic keyword is preferable to use in this case instead of an object type
// because dynamic keyword keeps the underlying structure and data type so that // you can directly inspect and view the value.
// in object type, you have to cast the object to a specific data type to view // the underlying value.
regards,
Abhijit
You have configured the auth.php
and used members
table for authentication but there is no user_email
field in the members
table so, Laravel says
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_email' in 'where clause' (SQL: select * from members where user_email = ? limit 1) (Bindings: array ( 0 => '[email protected]', ))
Because, it tries to match the user_email
in the members
table and it's not there. According to your auth
configuration, laravel
is using members
table for authentication not users
table.
Do simple compare > and <.
if (dateA>dateB && dateA<dateC)
//do something
If you care only on time:
if (dateA.TimeOfDay>dateB.TimeOfDay && dateA.TimeOfDay<dateC.TimeOfDay)
//do something
You can give variable names as project files. For instance in you plugin configuration give only one tag as below:-
<projectFile>${projectName}</projectFile>
Then on command line you can pass the project name as parameter:-
mvn [your-command] -DprojectName=[name of project]
You just have to use your local IP address:using the cmd command "ipconfig" and your server port number like this:
String webServiceUrl = "http://192.168.X.X:your_local_server_port/your_web_service_name.php"
And make sure you did set the internet permission in your project manifest
It's working perfectly for me
Good Luck
In my case it was gcc 6 the one missing
sudo apt-get install gcc-6 g++-6 -y
sudo apt-get install gcc-7 g++-7 -y
I have the same problem. I usually resort to String#split
:
"ABCDEFG".split("").each do |i|
puts i
end
I guess you could also implement it yourself like this:
class String
def each_char
self.split("").each { |i| yield i }
end
end
Edit: yet another alternative is String#each_byte
, available in Ruby 1.8.6, which returns the ASCII value of each char in an ASCII string:
"ABCDEFG".each_byte do |i|
puts i.chr # Fixnum#chr converts any number to the ASCII char it represents
end
select[value="value"]{
background-color: red;
padding: 3px;
font-weight:bold;
}
If you want a quick and dirty way of installing the build dependencies, use:
apt-get build-dep
This installs the dependencies. You need sources lines in your sources.list for this:
deb-src http://ftp.nl.debian.org/debian/ squeeze-updates main contrib non-free
If you are backporting packages from testing to stable, please be advised that the dependencies might have changed. The command apt-get build-deb installs dependencies for the source packages in your current repository.
But of course, dpkg-buildpackage -us -uc will show you any uninstalled dependencies.
If you want to compile more often, use cowbuilder.
apt-get install cowbuilder
Then create a build-area:
sudo DIST=squeeze ARCH=amd64 cowbuilder --create
Then compile a source package:
apt-get source cowsay
# do your magic editing
dpkg-source -b cowsay-3.03+dfsg1 # build the new source packages
cowbuilder --build cowsay_3.03+dfsg1-2.dsc # build the packages from source
Watch where cowbuilder puts the resulting package.
Good luck!
https://docs.docker.com/compose/compose-file/#extra_hosts
extra_hosts - Add hostname mappings. Uses the same values as the docker client --add-host parameter.
extra_hosts: - "somehost:162.242.195.82" - "otherhost:50.31.209.229"
An entry with the ip address and hostname will be created in /etc/hosts > inside containers for this service, e.g:
162.242.195.82 somehost 50.31.209.229 otherhost
Just to clarify the answer above:
Now it is possible to use timeout
option and the corresponding request event:
// set the desired timeout in options
const options = {
//...
timeout: 3000,
};
// create a request
const request = http.request(options, response => {
// your callback here
});
// use its "timeout" event to abort the request
request.on('timeout', () => {
request.abort();
});
I just created this and it looks easier. You get these 2 functions:
=GetColorIndex(E5) <- returns color number for the cell
from (cell)
=CountColorIndexInRange(C7:C24,14) <- returns count of cells C7:C24 with color 14
from (range of cells, color number you want to count)
example shows percent of cells with color 14
=ROUND(CountColorIndexInRange(C7:C24,14)/18, 4 )
Create these 2 VBA functions in a Module (hit Alt-F11)
open + folders. double-click on Module1
Just paste this text below in, then close the module window (it must save it then):
Function GetColorIndex(Cell As Range)
GetColorIndex = Cell.Interior.ColorIndex
End Function
Function CountColorIndexInRange(Rng As Range, TestColor As Long)
Dim cnt
Dim cl As Range
cnt = 0
For Each cl In Rng
If GetColorIndex(cl) = TestColor Then
Rem Debug.Print ">" & TestColor & "<"
cnt = cnt + 1
End If
Next
CountColorIndexInRange = cnt
End Function
I would suggest you just write a function to do what you're saying probably using drop
(to delete columns) and insert
to insert columns at a position. There isn't an existing API function to do what you're describing.
Just wrap the button label in an extra span and add class="align-middle"
to both (the icon and the label). This will center your icon with text vertical.
<button id="edit-listing-form-house_Continue"
class="btn btn-large btn-primary"
style=""
value=""
name="Continue"
type="submit">
<span class="align-middle">Continue</span>
<i class="icon-ok align-middle" style="font-size:40px;"></i>
It's as simple as that:
function isMacintosh() {
return navigator.platform.indexOf('Mac') > -1
}
function isWindows() {
return navigator.platform.indexOf('Win') > -1
}
You can do funny things then like:
var isMac = isMacintosh();
var isPC = !isMacintosh();
You can get maximum column value and increment it:
InnoDB uses the following algorithm to initialize the auto-increment counter for a table t that contains an AUTO_INCREMENT column named ai_col: After a server startup, for the first insert into a table t, InnoDB executes the equivalent of this statement:
SELECT MAX(ai_col) FROM t FOR UPDATE;
InnoDB increments by one the value retrieved by the statement and assigns it to the column and to the auto-increment counter for the table. If the table is empty, InnoDB uses the value 1.
Also you can use SHOW TABLE STATUS and its "Auto_increment" value.
So In my case, After trying all the above options, I realized it was VPN (company firewall).once connected and ran cmd: clean install spring-boot:run. Issue is resolved. Step 1: check maven is configured correctly or not. Step 2: check settings.xml is mapped correctly or not. Step 3: verify if you are behind any firewall then map your repo urls accordingly. Step 4:run clean install spring-boot:run step 5: issue is resolved.
1) A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.
2) $( elem ).attr( "checked" ) (1.6.1+) "checked" (String) Will change with checkbox state
3) $( elem ).attr( "checked" ) (pre-1.6) true (Boolean) Changed with checkbox state
Mostly we want to use for DOM object rather then custom attribute
like data-img, data-xyz
.
Also some of difference when accessing checkbox
value and href
with attr()
and prop()
as thing change with DOM output with
prop()
as full link from origin
and Boolean
value for checkbox
(pre-1.6)
We can only access DOM elements with prop
other then it gives undefined
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>prop demo</title>_x000D_
<style>_x000D_
p {_x000D_
margin: 20px 0 0;_x000D_
}_x000D_
b {_x000D_
color: blue;_x000D_
}_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<input id="check1" type="checkbox" checked="checked">_x000D_
<label for="check1">Check me</label>_x000D_
<p></p>_x000D_
_x000D_
<script>_x000D_
$("input").change(function() {_x000D_
var $input = $(this);_x000D_
$("p").html(_x000D_
".attr( \"checked\" ): <b>" + $input.attr("checked") + "</b><br>" +_x000D_
".prop( \"checked\" ): <b>" + $input.prop("checked") + "</b><br>" +_x000D_
".is( \":checked\" ): <b>" + $input.is(":checked")) + "</b>";_x000D_
}).change();_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
You will have to annotate your service with @Service
since you have said I am using annotations for mapping
Another way to use Linq, but without having to return everything and filter on that in memory.
var files = Directory.GetFiles("C:\\path", "*.mp3", SearchOption.AllDirectories).Union(Directory.GetFiles("C:\\path", "*.jpg", SearchOption.AllDirectories));
It's actually 2 calls to GetFiles()
, but I think it's consistent with the spirit of the question and returns them in one enumerable.
I had the same issue and was able to resolve it by manually removing the MapFragment
in the onDestroy()
method of the Fragment
class. Here is code that works and references the MapFragment
by ID in the XML:
@Override
public void onDestroyView() {
super.onDestroyView();
MapFragment f = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
if (f != null)
getFragmentManager().beginTransaction().remove(f).commit();
}
If you don't remove the MapFragment
manually, it will hang around so that it doesn't cost a lot of resources to recreate/show the map view again. It seems that keeping the underlying MapView
is great for switching back and forth between tabs, but when used in fragments this behavior causes a duplicate MapView
to be created upon each new MapFragment
with the same ID. The solution is to manually remove the MapFragment
and thus recreate the underlying map each time the fragment is inflated.
I also noted this in another answer [1].
System.Drawing.Image FileUploadPhoto = System.Drawing.Image.FromFile(location1);
FileUploadPhoto.Save(location2);
FileUploadPhoto.Dispose();
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
From react-native --help
uninstall [options] uninstall and unlink native dependencies
Ex:
react-native uninstall react-native-vector-icons
It will uninstall and unlink its dependencies.
To make the answer more re-usable for things other than just the datepicker change function you can create a prototype to handle this for you.
// safety check to see if the prototype name is already defined
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
return this;
}
};
Date.method('inPast', function () {
return this < new Date($.now());// the $.now() requires jQuery
});
// including this prototype as using in example
Date.method('addDays', function (days) {
var date = new Date(this);
date.setDate(date.getDate() + (days));
return date;
});
If you dont like the safety check you can use the conventional way to define prototypes:
Date.prototype.inPast = function(){
return this < new Date($.now());// the $.now() requires jQuery
}
Example Usage
var dt = new Date($.now());
var yesterday = dt.addDays(-1);
var tomorrow = dt.addDays(1);
console.log('Yesterday: ' + yesterday.inPast());
console.log('Tomorrow: ' + tomorrow.inPast());
In the second image it looks like you want the image to fill the box, but the example you created DOES keep the aspect ratio (the pets look normal, not slim or fat).
I have no clue if you photoshopped those images as example or the second one is "how it should be" as well (you said IS, while the first example you said "should")
Anyway, I have to assume:
If "the images are not resized keeping the aspect ration" and you show me an image which DOES keep the aspect ratio of the pixels, I have to assume you are trying to accomplish the aspect ratio of the "cropping" area (the inner of the green) WILE keeping the aspect ratio of the pixels. I.e. you want to fill the cell with the image, by enlarging and cropping the image.
If that's your problem, the code you provided does NOT reflect "your problem", but your starting example.
Given the previous two assumptions, what you need can't be accomplished with actual images if the height of the box is dynamic, but with background images. Either by using "background-size: contain" or these techniques (smart paddings in percents that limit the cropping or max sizes anywhere you want): http://fofwebdesign.co.uk/template/_testing/scale-img/scale-img.htm
The only way this is possible with images is if we FORGET about your second iimage, and the cells have a fixed height, and FORTUNATELY, judging by your sample images, the height stays the same!
So if your container's height doesn't change, and you want to keep your images square, you just have to set the max-height of the images to that known value (minus paddings or borders, depending on the box-sizing property of the cells)
Like this:
<div class="content">
<div class="row">
<div class="cell">
<img src="http://lorempixel.com/output/people-q-c-320-320-2.jpg"/>
</div>
<div class="cell">
<img src="http://lorempixel.com/output/people-q-c-320-320-7.jpg"/>
</div>
</div>
</div>
And the CSS:
.content {
background-color: green;
}
.row {
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-orient: horizontal;
-moz-box-orient: horizontal;
box-orient: horizontal;
flex-direction: row;
-webkit-box-pack: center;
-moz-box-pack: center;
box-pack: center;
justify-content: center;
-webkit-box-align: center;
-moz-box-align: center;
box-align: center;
align-items: center;
}
.cell {
-webkit-box-flex: 1;
-moz-box-flex: 1;
box-flex: 1;
-webkit-flex: 1 1 auto;
flex: 1 1 auto;
padding: 10px;
border: solid 10px red;
text-align: center;
height: 300px;
display: flex;
align-items: center;
box-sizing: content-box;
}
img {
margin: auto;
width: 100%;
max-width: 300px;
max-height:100%
}
Your code is invalid (opening tags are instead of closing ones, so they output NESTED cells, not siblings, he used a SCREENSHOT of your images inside the faulty code, and the flex box is not holding the cells but both examples in a column (you setup "row" but the corrupt code nesting one cell inside the other resulted in a flex inside a flex, finally working as COLUMNS. I have no idea what you wanted to accomplish, and how you came up with that code, but I'm guessing what you want is this.
I added display: flex to the cells too, so the image gets centered (I think display: table
could have been used here as well with all this markup)
public int GetCpuUsage()
{
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", Environment.MachineName);
cpuCounter.NextValue();
System.Threading.Thread.Sleep(1000); //This avoid that answer always 0
return (int)cpuCounter.NextValue();
}
Original information in this link https://gavindraper.com/2011/03/01/retrieving-accurate-cpu-usage-in-c/
In addition to all the previous answers, a possible fix to this problem in a large scale project, if your using a Value Object for your classes don't set the id attribute in the VO Transformer class.
<br>
worked for me.
You can use Buffer Reader from request to read
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append(System.lineSeparator());
}
String data = buffer.toString()
I had a similar problem when trying to operate on a rooted Samsung Galaxy S. Issuing a command from the computer shell
> adb root
fails with a message "cannot run as root in production builds". Here is a simple method that allows to become root.
Instead of the previous, issue the following two commands one after the other
> adb shell
$ su
After the first command, if the prompt has changed from '>' to '$' as shown above, it means that you have entered the adb shell environment. If subsequently the prompt has changed to '#' after issuing the second command, that means that you are now root. Now, as root, you can do anything you want with your device.
To switch back to 'safe' shell, issue
# exit
You will see that the prompt '$' reappears which means you are in the adb shell as a user and not as root.
On some mobiles like mine (MIUI Redmi 3) you can just add specific Application on list where application doesnt stop when you terminate applactions in Task Manager (It will stop but it will start again)
Just go to Settings>PermissionsAutostart
try this,
$("document").ready(function(){
$("your id here").trigger("click");
});
When you need cookies from session to session, there is another way to do it. Use the Chrome options user-data-dir in order to use folders as profiles. I run:
# You need to: from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")
Here you can do the logins that check for human interaction. I do this and then the cookies I need now every time I start the Webdriver with that folder everything is in there. You can also manually install the Extensions and have them in every session.
The second time I run, all the cookies are there:
# You need to: from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") # Now you can see the cookies, the settings, extensions, etc., and the logins done in the previous session are present here.
The advantage is you can use multiple folders with different settings and cookies, Extensions without the need to load, unload cookies, install and uninstall Extensions, change settings, change logins via code, and thus no way to have the logic of the program break, etc.
Also, this is faster than having to do it all by code.
If you mean to change the directory in which the program execution will occur, go to "Run configurations" in the Run tab.
Then select your project and go to the "Arguments" tab, you can change the directory there. By default it is the root directory of your project.
The :active pseudo-class is not the same as adding a class to style the element.
The :active CSS pseudo-class represents an element (such as a button) that is being activated by the user. When using a mouse, "activation" typically starts when the mouse button is pressed down and ends when it is released.
What we are looking for is a class, such as .active
, which we can use to style the navigation item.
For a clearer example of the difference between :active
and .active
see the following snippet:
li:active {_x000D_
background-color: #35495E;_x000D_
}_x000D_
_x000D_
li.active {_x000D_
background-color: #41B883;_x000D_
}
_x000D_
<ul>_x000D_
<li>:active (pseudo-class) - Click me!</li>_x000D_
<li class="active">.active (class)</li>_x000D_
</ul>
_x000D_
vue-router
automatically applies two active classes, .router-link-active
and .router-link-exact-active
, to the <router-link>
component.
router-link-active
This class is applied automatically to the <router-link>
component when its target route is matched.
The way this works is by using an inclusive match behavior. For example, <router-link to="/foo">
will get this class applied as long as the current path starts with /foo/
or is /foo
.
So, if we had <router-link to="/foo">
and <router-link to="/foo/bar">
, both components would get the router-link-active
class when the path is /foo/bar
.
router-link-exact-active
This class is applied automatically to the <router-link>
component when its target route is an exact match. Take into consideration that both classes, router-link-active
and router-link-exact-active
, will be applied to the component in this case.
Using the same example, if we had <router-link to="/foo">
and <router-link to="/foo/bar">
, the router-link-exact-active
class would only be applied to <router-link to="/foo/bar">
when the path is /foo/bar
.
Lets say we have <router-link to="/">
, what will happen is that this component will be active for every route. This may not be something that we want, so we can use the exact
prop like so: <router-link to="/" exact>
. Now the component will only get the active class applied when it is an exact match at /
.
We can use these classes to style our element, like so:
nav li:hover,
nav li.router-link-active,
nav li.router-link-exact-active {
background-color: indianred;
cursor: pointer;
}
The <router-link>
tag was changed using the tag
prop, <router-link tag="li" />
.
If we wish to change the default classes provided by vue-router
globally, we can do so by passing some options to the vue-router
instance like so:
const router = new VueRouter({
routes,
linkActiveClass: "active",
linkExactActiveClass: "exact-active",
})
<router-link>
)If instead we want to change the default classes per <router-link>
and not globally, we can do so by using the active-class
and exact-active-class
attributes like so:
<router-link to="/foo" active-class="active">foo</router-link>
<router-link to="/bar" exact-active-class="exact-active">bar</router-link>
Vue Router 3.1.0+ offers low level customization through a scoped slot. This comes handy when we wish to style the wrapper element, like a list element <li>
, but still keep the navigation logic in the anchor element <a>
.
<router-link
to="/foo"
v-slot="{ href, route, navigate, isActive, isExactActive }"
>
<li
:class="[isActive && 'router-link-active', isExactActive && 'router-link-exact-active']"
>
<a :href="href" @click="navigate">{{ route.fullPath }}</a>
</li>
</router-link>
<asp:GridView ID="grdGroup" EmptyDataText="No Records Found" ShowHeaderWhenEmpty="True" runat="server">
This is a basic example of Gridview with EmptyDataText and ShowHeaderWhenEmpty
Try this:
int lowIndex = 0;
int highIndex = elements.length-1;
while(lowIndex < highIndex) {
T lowVal = elements[lowIndex];
T highVal = elements[highIndex];
elements[lowIndex] = highVal;
elements[highIndex] = lowVal;
lowIndex += 1;
highIndex -=1;
}
Could use sprintf
to accomplish this:
awk '{str = sprintf("%s %s", $1, $2)} END {print str}' file
Assuming one has a simple setup (CentOS 7, Apache 2.4.x, and PHP 5.6.20) and only one website (not assuming virtual hosting) ...
In the PHP sense, $_SERVER['SERVER_NAME']
is an element PHP registers in the $_SERVER
superglobal based on your Apache configuration (**ServerName**
directive with UseCanonicalName On
) in httpd.conf (be it from an included virtual host configuration file, whatever, etc ...). HTTP_HOST is derived from the HTTP host
header. Treat this as user input. Filter and validate before using.
Here is an example of where I use $_SERVER['SERVER_NAME']
as the basis for a comparison. The following method is from a concrete child class I made named ServerValidator
(child of Validator
). ServerValidator
checks six or seven elements in $_SERVER before using them.
In determining if the HTTP request is POST, I use this method.
public function isPOST()
{
return (($this->requestMethod === 'POST') && // Ignore
$this->hasTokenTimeLeft() && // Ignore
$this->hasSameGETandPOSTIdentities() && // Ingore
($this->httpHost === filter_input(INPUT_SERVER, 'SERVER_NAME')));
}
By the time this method is called, all filtering and validating of relevant $_SERVER elements would have occurred (and relevant properties set).
The line ...
($this->httpHost === filter_input(INPUT_SERVER, 'SERVER_NAME')
... checks that the $_SERVER['HTTP_HOST']
value (ultimately derived from the requested host
HTTP header) matches $_SERVER['SERVER_NAME']
.
Now, I am using superglobal speak to explain my example, but that is just because some people are unfamiliar with INPUT_GET
, INPUT_POST
, and INPUT_SERVER
in regards to filter_input_array()
.
The bottom line is, I do not handle POST requests on my server unless all four conditions are met. Hence, in terms of POST requests, failure to provide an HTTP host
header (presence tested for earlier) spells doom for strict HTTP 1.0 browsers. Moreover, the requested host must match the value for ServerName
in the httpd.conf, and, by extention, the value for $_SERVER('SERVER_NAME')
in the $_SERVER
superglobal. Again, I would be using INPUT_SERVER
with the PHP filter functions, but you catch my drift.
Keep in mind that Apache frequently uses ServerName
in standard redirects (such as leaving the trailing slash off a URL: Example, http://www.example.com becoming http://www.example.com/), even if you are not using URL rewriting.
I use $_SERVER['SERVER_NAME']
as the standard, not $_SERVER['HTTP_HOST']
. There is a lot of back and forth on this issue. $_SERVER['HTTP_HOST']
could be empty, so this should not be the basis for creating code conventions such as my public method above. But, just because both may be set does not guarantee they will be equal. Testing is the best way to know for sure (bearing in mind Apache version and PHP version).
You can create these easily using the floating ability of CSS, for example. I have created a small example on Jsfiddle over here, all the related css and html is also provided there.
.foo {_x000D_
float: left;_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
margin: 5px;_x000D_
border: 1px solid rgba(0, 0, 0, .2);_x000D_
}_x000D_
_x000D_
.blue {_x000D_
background: #13b4ff;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
background: #ab3fdd;_x000D_
}_x000D_
_x000D_
.wine {_x000D_
background: #ae163e;_x000D_
}
_x000D_
<div class="foo blue"></div>_x000D_
<div class="foo purple"></div>_x000D_
<div class="foo wine"></div>
_x000D_
Think about it: the database really has to go to every row to do that. In a multi-user environment my COUNT(*)
could be different from your COUNT(*)
. It would be impractical to have a different counter for each and every session so you have literally to count the rows. Most of the time anyway you would have a WHERE clause or a JOIN in your query so your hypothetical counter would be of litte practical value.
There are ways to speed up things however: if you have an INDEX on a NOT NULL column Oracle will count the rows of the index instead of the table. In a proper relational model all tables have a primary key so the COUNT(*)
will use the index of the primary key.
Bitmap index have entries for NULL rows so a COUNT(*) will use a bitmap index if there is one available.
Try using cmake itself. In the build directory, run:
cmake --build .
This is how I did it.
Step 1: Install Java 11
You can download Java 11 dmg for mac from here: https://www.oracle.com/technetwork/java/javase/downloads/jdk11-downloads-5066655.html
Step 2: After installation of Java 11. Confirm installation of all versions. Type the following command in your terminal.
/usr/libexec/java_home -V
Step 3: Edit .bash_profile
sudo nano ~/.bash_profile
Step 4: Add 11.0.1 as default. (Add below line to bash_profile file).
export JAVA_HOME=$(/usr/libexec/java_home -v 11.0.1)
to switch to any version
export JAVA_HOME=$(/usr/libexec/java_home -v X.X.X)
Now Press CTRL+X to exit the bash. Press 'Y' to save changes.
Step 5: Reload bash_profile
source ~/.bash_profile
Step 6: Confirm current version of Java
java -version
Try Handle. Filemon & Regmon are also great for trying to figure out what the duce program foo is doing to your system.
The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.
The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.
The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.
Edit: Also worth a look - kashif's comment about json-streamer
and Henrik Heino's comment about bigjson
.
Test t;
, calls the default constructor, which allocates a new array of integers. This is fine, and your expected behavior.
Trouble comes when you push t
into your queue using q.push(t)
. If you're familiar with Java, C#, or almost any other object-oriented language, you might expect the object you created earler to be added to the queue, but C++ doesn't work that way.
When we take a look at std::queue::push
method, we see that the element that gets added to the queue is "initialized to a copy of x." It's actually a brand new object that uses the copy constructor to duplicate every member of your original Test
object to make a new Test
.
Your C++ compiler generates a copy constructor for you by default! That's pretty handy, but causes problems with pointer members. In your example, remember that int *myArray
is just a memory address; when the value of myArray
is copied from the old object to the new one, you'll now have two objects pointing to the same array in memory. This isn't intrinsically bad, but the destructor will then try to delete the same array twice, hence the "double free or corruption" runtime error.
The first step is to implement a copy constructor, which can safely copy the data from one object to another. For simplicity, it could look something like this:
Test(const Test& other){
myArray = new int[10];
memcpy( myArray, other.myArray, 10 );
}
Now when you're copying Test objects, a new array will be allocated for the new object, and the values of the array will be copied as well.
We're not completely out trouble yet, though. There's another method that the compiler generates for you that could lead to similar problems - assignment. The difference is that with assignment, we already have an existing object whose memory needs to be managed appropriately. Here's a basic assignment operator implementation:
Test& operator= (const Test& other){
if (this != &other) {
memcpy( myArray, other.myArray, 10 );
}
return *this;
}
The important part here is that we're copying the data from the other array into this object's array, keeping each object's memory separate. We also have a check for self-assignment; otherwise, we'd be copying from ourselves to ourselves, which may throw an error (not sure what it's supposed to do). If we were deleting and allocating more memory, the self-assignment check prevents us from deleting memory from which we need to copy.
When you're launching tomcat server from netbeans IDE you need to check in menu "tools->servers" on connection tab for tomcat server - there is catalina base directory. And you need to include something like:
<role rolename="manager"/>
<user username="admin" password="admin" roles="manager"/>
at file
\CATALINA_BASE\conf\tomcat-users.xml
or use username automatically generated by IDE with description already placed in this file or on connection tab
For Manager Apps : GUI access:
<role rolename="manager-gui"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>
I would advice you to learn using ant, which is very-well suited for this task and is very easy to grasp and well documented.
You would just have to define a target like this in the build.xml file:
<target name="compile">
<javac srcdir="your/source/directory"
destdir="your/output/directory"
classpath="xyz.jar" />
</target>
It isn't valid to have the same ID twice, that's why #name
only finds the first one.
You can try:
$("#form2 input").val('Hello World!');
Or,
$("#form2 input[name=name]").val('Hello World!');
If you're stuck with an invalid page and want to select all #name
s, you can use the attribute selector on the id:
$("input[id=name]").val('Hello World!');
This is how I did it with Kotlin to show progress with percentage.
My fragment layout.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ProgressBar
android:layout_marginLeft="32dp"
android:layout_marginRight="32dp"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/progressBar"/>
</FrameLayout>
My kotlin fragment in onViewCreated
progressBar.max = 100;
webView.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
progressBar.progress = newProgress;
}
}
webView!!.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
progressBar.visibility = View.VISIBLE
progressBar.progress = 0;
super.onPageStarted(view, url, favicon)
}
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
view?.loadUrl(url)
return true
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view?.loadUrl(request?.url.toString())
}
return true
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
progressBar.visibility = View.GONE
}
}
webView.loadUrl(url)
Place the strings you want to grep for into a file
echo who > find.txt
echo Roger >> find.txt
echo [44][0-9]{9,} >> find.txt
Then search using -f
grep -f find.txt BIG_FILE_TO_SEARCH.txt
ports:
expose:
For Microsoft SQL Server you can return the @@ROWCOUNT
variable to return the number of rows affected by the last statement in the stored procedure.
that's why Idon't like NULL values in the database at all.
I hope you are having it for a reason.
if ($_POST['location_id'] === '') {
$location_id = 'NULL';
} else {
$location_id = "'".$_POST['location_id']."'";
}
$notes = mysql_real_escape_string($_POST['notes']);
$ipid = mysql_real_escape_string($_POST['ipid']);
$sql="UPDATE addresses
SET notes='$notes', location_id=$location_id
WHERE ipid = '$ipid'";
echo $sql; //to see different queries this code produces
// and difference between NULL and 'NULL' in the query
I don't fully understand what was the problem with the "update current of cursor" but it is solved by using the fetch statement twice for the inner cursor:
FETCH NEXT FROM INNER_CURSOR
WHILE (@@FETCH_STATUS <> -1)
BEGIN
UPDATE CONTACTS
SET INDEX_NO = @COUNTER
WHERE CURRENT OF INNER_CURSOR
SET @COUNTER = @COUNTER + 1
FETCH NEXT FROM INNER_CURSOR
FETCH NEXT FROM INNER_CURSOR
END
This solution will play the video upon clicking. You'll need to edit your picture to add a button image yourself.
You're going to need the URL of your picture and the YouTube video ID. The YouTube video id is the part of the URL after the v=
parameter, so for https://www.youtube.com/watch?v=DODLEX4zzLQ the ID would be DODLEX4zzLQ
.
<div width="560px" height="315px" style="position: static; clear: both; width: 560px; height: 315px;"> <div style="position: relative"><img id="vidimg" width="560px" height="315px" src="URL_TO_PICTURE" style="position: absolute; top: 0; left: 0; cursor: pointer; pointer-events: none; z-index: 2;" /><iframe id="unlocked-video" style="position: absolute; top: 0; left: 0; z-index: 1;" src="https://www.youtube.com/embed/YOUTUBE_VIDEO_ID" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe></div></div>
<script type="application/javascript">
// Adapted from https://stackoverflow.com/a/32138108
var monitor = setInterval(function(){
var elem = document.activeElement;
if(elem && elem.id == 'unlocked-video'){
document.getElementById('vidimg').style.display='none';
clearInterval(monitor);
}
}, 100);
</script>
Be sure to replace URL_TO_PICTURE and YOUTUBE_VIDEO_ID in the above snippet.
To clarify what's going on here, this displays the image on top of the video, but allows clicks to pass through the image. The script monitors for clicks in the video iframe, and then hides the image if a click occurs. You may not need the float: clear
.
I haven't compared this to the other answers here, but this is what I have used.
var cumulativeOffset = function(element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
};
(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)
And if you just want to create the constraint on its own, you can use ALTER TABLE
alter table MyTable
add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn ) references MyOtherTable(PKColumn)
I wouldn't recommend the syntax mentioned by Sara Chipps for inline creation, just because I would rather name my own constraints.
Had the same problem . Fixed it by installing Microsoft Foundation Classes for C++.
From the documentation
NOTE: On the JVM, if all of the parameters of the primary constructor have default values, the compiler will generate an additional parameterless constructor which will use the default values. This makes it easier to use Kotlin with libraries such as Jackson or JPA that create class instances through parameterless constructors.
When you include jQuery the first time:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
The second script plugs itself into jQuery, and "adds" $(...).datepicker
.
But then you are including jQuery once again:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
It undoes the plugging in and therefore $(...).datepicker
becomes undefined.
Although the first $(document).ready
block appears before that, the anonymous callback function body is not executed until all scripts are loaded, and by then $(...)
(window.$
to be precise) is referring to the most recently loaded jQuery.
You would not run into this if you called $('.dateinput').datepicker
immediately rather than in $(document).ready
callback, but then you'd need to make sure that the target element (with class dateinput
) is already in the document before the script, and it's generally advised to use the ready
callback.
If you want to use datepicker
from jquery-ui, it would probably make most sense to include the jquery-ui script after bootstrap. jquery-ui 1.11.4 is compatible with jquery 1.6+ so it will work fine.
Alternatively (in particular if you are not using jquery-ui for anything else), you could try bootstrap-datepicker.
I created a small class to grab data from the provided url, then extract html elements of your choice. The class makes use of CURL and DOMDocument.
php class:
class crawler {
public static $timeout = 2;
public static $agent = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
public static function http_request($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, self::$agent);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, self::$timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
public static function strip_whitespace($data) {
$data = preg_replace('/\s+/', ' ', $data);
return trim($data);
}
public static function extract_elements($tag, $data) {
$response = array();
$dom = new DOMDocument;
@$dom->loadHTML($data);
foreach ( $dom->getElementsByTagName($tag) as $index => $element ) {
$response[$index]['text'] = self::strip_whitespace($element->nodeValue);
foreach ( $element->attributes as $attribute ) {
$response[$index]['attributes'][strtolower($attribute->nodeName)] = self::strip_whitespace($attribute->nodeValue);
}
}
return $response;
}
}
example usage:
$data = crawler::http_request('https://stackoverflow.com/questions/2313107/how-do-i-make-a-simple-crawler-in-php');
$links = crawler::extract_elements('a', $data);
if ( count($links) > 0 ) {
file_put_contents('links.json', json_encode($links, JSON_PRETTY_PRINT));
}
example response:
[
{
"text": "Stack Overflow",
"attributes": {
"href": "https:\/\/stackoverflow.com",
"class": "-logo js-gps-track",
"data-gps-track": "top_nav.click({is_current:false, location:2, destination:8})"
}
},
{
"text": "Questions",
"attributes": {
"id": "nav-questions",
"href": "\/questions",
"class": "-link js-gps-track",
"data-gps-track": "top_nav.click({is_current:true, location:2, destination:1})"
}
},
{
"text": "Developer Jobs",
"attributes": {
"id": "nav-jobs",
"href": "\/jobs?med=site-ui&ref=jobs-tab",
"class": "-link js-gps-track",
"data-gps-track": "top_nav.click({is_current:false, location:2, destination:6})"
}
}
]
SELECT DISTINCT(salary) FROM emp order by salary asc limit 0 ,3
Above query gives three highest salary with DISTINCT.
Here is a recursive function to set the innerHTML of an element that I use in our ad server:
// o: container to set the innerHTML
// html: html text to set.
// clear: if true, the container is cleared first (children removed)
function setHTML(o, html, clear) {
if (clear) o.innerHTML = "";
// Generate a parseable object with the html:
var dv = document.createElement("div");
dv.innerHTML = html;
// Handle edge case where innerHTML contains no tags, just text:
if (dv.children.length===0){ o.innerHTML = html; return; }
for (var i = 0; i < dv.children.length; i++) {
var c = dv.children[i];
// n: new node with the same type as c
var n = document.createElement(c.nodeName);
// copy all attributes from c to n
for (var j = 0; j < c.attributes.length; j++)
n.setAttribute(c.attributes[j].nodeName, c.attributes[j].nodeValue);
// If current node is a leaf, just copy the appropriate property (text or innerHTML)
if (c.children.length == 0)
{
switch (c.nodeName)
{
case "SCRIPT":
if (c.text) n.text = c.text;
break;
default:
if (c.innerHTML) n.innerHTML = c.innerHTML;
break;
}
}
// If current node has sub nodes, call itself recursively:
else setHTML(n, c.innerHTML, false);
o.appendChild(n);
}
}
You can see the demo here.
All you need to do to make this work is the following code:
@ComponentScan
public class PriceWatchTest{
@Autowired
private PriceWatchJpaRepository priceWatchJpaRepository;
...
...
}
Using index
:
>>> string = "Username: How are you today?"
>>> string[:string.index(":")]
'Username'
The index will give you the position of :
in string, then you can slice it.
If you want to use regex:
>>> import re
>>> re.match("(.*?):",string).group()
'Username'
match
matches from the start of the string.
you can also use itertools.takewhile
>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))
'Username'
No siblings solution:
var x = $('#xxx').parent().html();
alert(x);
Universal solution:
// no cloning necessary
var x = $('#xxx').wrapAll('<div>').parent().html();
alert(x);
Fiddle here: http://jsfiddle.net/ezmilhouse/Mv76a/
Use a for..in
loop to enumerate an object's properties, but be careful. The enumeration will return properties not just of the object being enumerated, but also from the prototypes of any parent objects.
var myObject = {foo: 'bar'};
for (var name in myObject) {
alert(name);
}
// results in a single alert of 'foo'
Object.prototype.baz = 'quux';
for (var name in myObject) {
alert(name);
}
// results in two alerts, one for 'foo' and one for 'baz'
To avoid including inherited properties in your enumeration, check hasOwnProperty()
:
for (var name in myObject) {
if (myObject.hasOwnProperty(name)) {
alert(name);
}
}
Edit: I disagree with JasonBunting's statement that we don't need to worry about enumerating inherited properties. There is danger in enumerating over inherited properties that you aren't expecting, because it can change the behavior of your code.
It doesn't matter whether this problem exists in other languages; the fact is it exists, and JavaScript is particularly vulnerable since modifications to an object's prototype affects child objects even if the modification takes place after instantiation.
This is why JavaScript provides hasOwnProperty()
, and this is why you should use it in order to ensure that third party code (or any other code that might modify a prototype) doesn't break yours. Apart from adding a few extra bytes of code, there is no downside to using hasOwnProperty()
.
One option is just to use the regex |
character to try to match each of the substrings in the words in your Series s
(still using str.contains
).
You can construct the regex by joining the words in searchfor
with |
:
>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0 cat
1 hat
2 dog
3 fog
dtype: object
As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $
and ^
which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.
You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape
:
>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']
The strings with in this new list will match each character literally when used with str.contains
.
This method worked for me without flexbox:
#blockA,_x000D_
#blockB,_x000D_
#blockC {_x000D_
border: 1px solid black;_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
_x000D_
.reverseOrder,_x000D_
#blockA,_x000D_
#blockB,_x000D_
#blockC {_x000D_
-webkit-transform: rotate(180deg);_x000D_
-moz-transform: rotate(180deg);_x000D_
-ms-transform: rotate(180deg);_x000D_
-o-transform: rotate(180deg);_x000D_
transform: rotate(180deg);_x000D_
}
_x000D_
<div class="reverseOrder">_x000D_
<div id="blockA">Block A</div>_x000D_
<div id="blockB">Block B</div>_x000D_
<div id="blockC">Block C</div>_x000D_
</div>
_x000D_
on Windows I have python 3.7 installed and I still couldn't activate virtualenv
from Gitbash with ./Scripts/activate
although it worked from Powershell after running Set-ExecutionPolicy Unrestricted
in Powershell and changing the setting to "Yes To All".
I don't like Powershell and I like to use Gitbash, so to activate virtualenv
in Gitbash first navigate to your project folder, use ls
to list the contents of the folder and be sure you see "Scripts". Change directory to "Scripts" using cd Scripts
, once you're in the "Scripts" path use . activate
to activate virtualenv
. Don't forget the space after the dot.
I tested 2 set based randomization methods against RAND() by generating 100,000,000 rows with each. To level the field the output is a float between 0-1 to mimic RAND(). Most of the code is testing infrastructure so I summarize the algorithms here:
-- Try #1 used
(CAST(CRYPT_GEN_RANDOM(8) AS BIGINT)%500000000000000000+500000000000000000.0)/1000000000000000000 AS Val
-- Try #2 used
RAND(Checksum(NewId()))
-- and to have a baseline to compare output with I used
RAND() -- this required executing 100000000 separate insert statements
Using CRYPT_GEN_RANDOM was clearly the most random since there is only a .000000001% chance of seeing even 1 duplicate when plucking 10^8 numbers FROM a set of 10^18 numbers. IOW we should not have seen any duplicates and this had none! This set took 44 seconds to generate on my laptop.
Cnt Pct
----- ----
1 100.000000 --No duplicates
SQL Server Execution Times: CPU time = 134795 ms, elapsed time = 39274 ms.
IF OBJECT_ID('tempdb..#T0') IS NOT NULL DROP TABLE #T0;
GO
WITH L0 AS (SELECT c FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS D(c)) -- 2^4
,L1 AS (SELECT 1 AS c FROM L0 AS A CROSS JOIN L0 AS B) -- 2^8
,L2 AS (SELECT 1 AS c FROM L1 AS A CROSS JOIN L1 AS B) -- 2^16
,L3 AS (SELECT 1 AS c FROM L2 AS A CROSS JOIN L2 AS B) -- 2^32
SELECT TOP 100000000 (CAST(CRYPT_GEN_RANDOM(8) AS BIGINT)%500000000000000000+500000000000000000.0)/1000000000000000000 AS Val
INTO #T0
FROM L3;
WITH x AS (
SELECT Val,COUNT(*) Cnt
FROM #T0
GROUP BY Val
)
SELECT x.Cnt,COUNT(*)/(SELECT COUNT(*)/100 FROM #T0) Pct
FROM X
GROUP BY x.Cnt;
At almost 15 orders of magnitude less random this method was not quite twice as fast, taking only 23 seconds to generate 100M numbers.
Cnt Pct
---- ----
1 95.450254 -- only 95% unique is absolutely horrible
2 02.222167 -- If this line were the only problem I'd say DON'T USE THIS!
3 00.034582
4 00.000409 -- 409 numbers appeared 4 times
5 00.000006 -- 6 numbers actually appeared 5 times
SQL Server Execution Times: CPU time = 77156 ms, elapsed time = 24613 ms.
IF OBJECT_ID('tempdb..#T1') IS NOT NULL DROP TABLE #T1;
GO
WITH L0 AS (SELECT c FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS D(c)) -- 2^4
,L1 AS (SELECT 1 AS c FROM L0 AS A CROSS JOIN L0 AS B) -- 2^8
,L2 AS (SELECT 1 AS c FROM L1 AS A CROSS JOIN L1 AS B) -- 2^16
,L3 AS (SELECT 1 AS c FROM L2 AS A CROSS JOIN L2 AS B) -- 2^32
SELECT TOP 100000000 RAND(Checksum(NewId())) AS Val
INTO #T1
FROM L3;
WITH x AS (
SELECT Val,COUNT(*) Cnt
FROM #T1
GROUP BY Val
)
SELECT x.Cnt,COUNT(*)*1.0/(SELECT COUNT(*)/100 FROM #T1) Pct
FROM X
GROUP BY x.Cnt;
RAND() alone is useless for set-based generation so generating the baseline for comparing randomness took over 6 hours and had to be restarted several times to finally get the right number of output rows. It also seems that the randomness leaves a lot to be desired although it's better than using checksum(newid()) to reseed each row.
Cnt Pct
---- ----
1 99.768020
2 00.115840
3 00.000100 -- at least there were comparitively few values returned 3 times
Because of the restarts, execution time could not be captured.
IF OBJECT_ID('tempdb..#T2') IS NOT NULL DROP TABLE #T2;
GO
CREATE TABLE #T2 (Val FLOAT);
GO
SET NOCOUNT ON;
GO
INSERT INTO #T2(Val) VALUES(RAND());
GO 100000000
WITH x AS (
SELECT Val,COUNT(*) Cnt
FROM #T2
GROUP BY Val
)
SELECT x.Cnt,COUNT(*)*1.0/(SELECT COUNT(*)/100 FROM #T2) Pct
FROM X
GROUP BY x.Cnt;
I had a similar problem when developing a Django project. I couldn't use OrderedDict, because I was running an old version of python, so the solution was to use Django's SortedDict class:
https://code.djangoproject.com/wiki/SortedDict
e.g.,
from django.utils.datastructures import SortedDict
d2 = SortedDict()
d2['b'] = 1
d2['a'] = 2
d2['c'] = 3
Note: This answer is originally from 2011. If you have access to Python version 2.7 or higher, then you should have access to the now standard collections.OrderedDict
, of which many examples have been provided by others in this thread.
Using functools.partial to create a new function called printf
>>> import functools
>>> printf = functools.partial(print, end="")
>>> printf("Hello world\n")
Hello world
Easy way to wrap a function with default parameters.
U can use mysql dump or query to export data to csv file
SELECT *
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM products
Short answer: You should to use "weak references" between collections, using ObjectId properties:
References store the relationships between data by including links or references from one document to another. Applications can resolve these references to access the related data. Broadly, these are normalized data models.
https://docs.mongodb.com/manual/core/data-modeling-introduction/#references
This will of course not check any referential integrity. You need to handle "dead links" on your side (application level).
The '\r'
character is the carriage return, and the carriage return-newline pair is both needed for newline in a network virtual terminal session.
From the old telnet specification (RFC 854) (page 11):
The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").
However, from the latest specification (RFC5198) (page 13):
...
In Net-ASCII, CR MUST NOT appear except when immediately followed by either NUL or LF, with the latter (CR LF) designating the "new line" function. Today and as specified above, CR should generally appear only when followed by LF. Because page layout is better done in other ways, because NUL has a special interpretation in some programming languages, and to avoid other types of confusion, CR NUL should preferably be avoided as specified above.
LF CR SHOULD NOT appear except as a side-effect of multiple CR LF sequences (e.g., CR LF CR LF).
So newline in Telnet should always be '\r\n'
but most implementations have either not been updated, or keeps the old '\n\r'
for backwards compatibility.
There are two approaches in the standard library. One is to use java.text.DecimalFormat. The other more cryptic methods (String.format, PrintStream.printf, etc) based around java.util.Formatter should keep C programmers happy(ish).
Here you can find solutions for both your problems.
document.body.style.height = '500px';
document.body.addEventListener('click', function(e){
var self = this,
old_bg = this.style.background;
this.style.background = this.style.background=='green'? 'blue':'green';
setTimeout(function(){
self.style.background = old_bg;
}, 1000);
})
You need to instruct the console to clear.
For serial terminals this was typically done through so called "escape sequences", where notably the vt100 set has become very commonly supported (and its close ANSI-cousin).
Windows has traditionally not supported such sequences "out-of-the-box" but relied on API-calls to do these things. For DOS-based versions of Windows, however, the ANSI.SYS driver could be installed to provide such support.
So if you are under Windows, you need to interact with the appropriate Windows API. I do not believe the standard Java runtime library contains code to do so.
At least on Debian the nginx startup script has a reload function which does:
reload)
log_daemon_msg "Reloading $DESC configuration" "$NAME"
test_nginx_config
start-stop-daemon --stop --signal HUP --quiet --pidfile $PID \
--oknodo --exec $DAEMON
log_end_msg $?
;;
Seems like all you'd need to do is call service nginx reload
instead of restart
since it calls test_nginx_config
.
feedgnuplot is another front end to gnuplot, which handles piping in data.
$ seq 5 | awk '{print 2*$1, $1*$1}' |
feedgnuplot --lines --points --legend 0 "data 0" --title "Test plot" --y2 1
--terminal 'dumb 80,40' --exit
Test plot
10 ++------+--------+-------+-------+-------+--------+-------+------*A 25
+ + + + + + + + **#+
| : : : : : : data 0+**A*** |
| : : : : : : :** # |
9 ++.......................................................**.##....|
| : : : : : : ** :# |
| : : : : : : ** # |
| : : : : : :** ##: ++ 20
8 ++................................................A....#..........|
| : : : : : **: # : |
| : : : : : ** : ## : |
| : : : : : ** :# : |
| : : : : :** B : |
7 ++......................................**......##................|
| : : : : ** : ## : : ++ 15
| : : : : ** : # : : |
| : : : :** : ## : : |
6 ++..............................*A.......##.......................|
| : : : ** : ##: : : |
| : : : ** : # : : : |
| : : :** : ## : : : ++ 10
5 ++......................**........##..............................|
| : : ** : #B : : : |
| : : ** : ## : : : : |
| : :** : ## : : : : |
4 ++...............A.......###......................................|
| : **: ##: : : : : |
| : ** : ## : : : : : ++ 5
| : ** : ## : : : : : |
| :** ##B# : : : : : |
3 ++.....**..####...................................................|
| **#### : : : : : : |
| **## : : : : : : : |
B** + + + + + + + +
2 A+------+--------+-------+-------+-------+--------+-------+------++ 0
1 1.5 2 2.5 3 3.5 4 4.5 5
All the answers are way too long. The easiest way to add border radius to a table element that accepts border as a property, is doing border radius with overflow: hidden.
border: xStyle xColor xSize;
border-collapse: collapse;
border-radius: 1em;
overflow: hidden;
Expanding on the answer by @gordon, here's an example of readable syntax and argument passing with shell/command module (these differ from the git module in that there are required but free-form arguments, as noted by @ander)
- name: "release tarball is generated" local_action: module: shell _raw_params: git archive --format zip --output release.zip HEAD chdir: "files/clones/webhooks"
I would like to answer your question, as there are various methods - here I’ll talk about the code that is widely used.
So, for hiding the sheet:
Sub try()
Worksheets("Sheet1").Visible = xlSheetHidden
End Sub
There are other methods also if you want to learn all Methods Click here
i got the same problem and i notice that my security config has diferent TAGS like the @Xenolion answer says
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">localhost</domain>
</domain-config>
</network-security-config>
so i change the TAGS "domain-config" for "base-config" and works, like this:
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">localhost</domain>
</base-config>
</network-security-config>
I've successfully used OpenPop.NET to access emails via POP3.
I just wanted to add this to the answer from Kimberly. Maybe it can save some time and avoid compilation errors for not implementing all methods that the IEndpointBehaviour interface requires.
Best regards
Nicki
/*
// This is just to illustrate how it can be implemented on an imperative declarared binding, channel and client.
string url = "SOME WCF URL";
BasicHttpBinding wsBinding = new BasicHttpBinding();
EndpointAddress endpointAddress = new EndpointAddress(url);
ChannelFactory<ISomeService> channelFactory = new ChannelFactory<ISomeService>(wsBinding, endpointAddress);
channelFactory.Endpoint.Behaviors.Add(new InspectorBehavior());
ISomeService client = channelFactory.CreateChannel();
*/
public class InspectorBehavior : IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
// No implementation necessary
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new MyMessageInspector());
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
// No implementation necessary
}
public void Validate(ServiceEndpoint endpoint)
{
// No implementation necessary
}
}
public class MyMessageInspector : IClientMessageInspector
{
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
// Do something with the SOAP request
string request = request.ToString();
return null;
}
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
// Do something with the SOAP reply
string replySoap = reply.ToString();
}
}
I'm going to assume you want to build a the regex dynamically to contain other words than part1 and part2, and that you want order not to matter. If so you can use something like this:
((^|, )(part1|part2|part3))+$
Positive matches:
part1
part2, part1
part1, part2, part3
Negative matches:
part1, //with and without trailing spaces.
part3, part2,
otherpart1
split takes regex as a parameter.|
has special meaning in regex.. use \\|
instead of |
to escape it.
As Simon Mourier mentioned, it's possible to use ConnectAsync
TcpClient's method with Task
in addition and stop operation as soon as possible.
For example:
// ...
client = new TcpClient(); // Initialization of TcpClient
CancellationToken ct = new CancellationToken(); // Required for "*.Task()" method
if (client.ConnectAsync(this.ip, this.port).Wait(1000, ct)) // Connect with timeout of 1 second
{
// ... transfer
if (client != null) {
client.Close(); // Close the connection and dispose a TcpClient object
Console.WriteLine("Success");
ct.ThrowIfCancellationRequested(); // Stop asynchronous operation after successull connection(...and transfer(in needed))
}
}
else
{
Console.WriteLine("Connetion timed out");
}
// ...
Also, I would recommended checking the AsyncTcpClient C# library with some examples provided like Server <> Client
.
You have mostly the right idea, it's just the sending of the form that is wrong. The form belongs in the body of the request.
req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))
making a dynamycal width with mobile devices support
http://www.codeography.com/2011/06/14/dynamic-fixed-width-layout-with-css.html
The second parameter of axios.post
is data
(not config
). config
is the third parameter. Please see this for details: https://github.com/mzabriskie/axios#axiosposturl-data-config
You could use the LINQ select
clause and reference the property that relates to your Name column.
Stored Procedures are used as scripts. They run a series of commands for you and you can schedule them to run at certain times. Usually runs multiples DML statements like INSERT, UPDATE, DELETE, etc. or even SELECT.
Functions are used as methods. You pass it something and it returns a result. Should be small and fast - does it on the fly. Usually used in a SELECT statement.
we developed a module on GitHub that has hooks for fetching data so you can use it like this for your purpose:
import { useFetching } from "react-concurrent";
const app = () => {
const { data, isLoading, error , refetch } = useFetching(() =>
fetch("http://example.com"),
);
};
You can fork that out, but any PRs are welcome. https://github.com/hosseinmd/react-concurrent#react-concurrent
As per this link you may also have to prefix your param with &rp if not using proxy syntax
If you intend to write your own daemon, then I recommend calling setuid(). This way, your process can
The best way to Load JSON Data into Dictionary is You can user the inbuilt json loader.
Below is the sample snippet that can be used.
import json
f = open("data.json")
data = json.load(f))
f.close()
type(data)
print(data[<keyFromTheJsonFile>])
Took me a while to find this out but if you a number stored in a variable, say x and you want to select it, use
document.querySelector('a[data-a= + CSS.escape(x) + ']').
This is due to some attribute naming specifications that I'm not yet very familiar with. Hope this will help someone.
You should never be writing code that looks like this:
private void DoGUISwitch() {
if (object1.InvokeRequired) {
object1.Invoke(new MethodInvoker(() => { DoGUISwitch(); }));
} else {
object1.Visible = true;
object2.Visible = false;
}
}
If you do have code that looks like this then your application is not thread-safe. It means that you have code which is already calling DoGUISwitch() from a different thread. It's too late to be checking to see if it's in a different thread. InvokeRequire must be called BEFORE you make a call to DoGUISwitch. You should not access any method or property from a different thread.
Reference: Control.InvokeRequired Property where you can read the following:
In addition to the InvokeRequired property, there are four methods on a control that are thread safe to call: Invoke, BeginInvoke, EndInvoke and CreateGraphics if the handle for the control has already been created.
In a single CPU architecture there's no problem, but in a multi-CPU architecture you can cause part of the UI thread to be assigned to the processor where the calling code was running...and if that processor is different from where the UI thread was running then when the calling thread ends Windows will think that the UI thread has ended and will kill the application process i.e. your application will exit without error.
From GC Performance Tuning training documents of Oracle:
-Xmn[size]: Size of young generation heap space.
Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.
In short, it sets the NewSize and MaxNewSize values of New generation to the same value.
Try this query:
SELECT SUBSTRING(CONVERT(VARCHAR,JOINGDATE,103),7,4)AS
YEAR,SUBSTRING(CONVERT(VARCHAR,JOINGDATE,100),1,2)AS
MONTH,SUBSTRING(CONVERT(VARCHAR,JOINGDATE,100),4,3)AS DATE FROM EMPLOYEE1
Result:
2014 Ja 1
2015 Ja 1
2014 Ja 1
2015 Ja 1
2012 Ja 1
2010 Ja 1
2015 Ja 1
Check if you are importing the same packages in your .m and in your .h Example given: I had this very problem with the init method and it was caused by missing the "#import " on the .m file
Faced same issue. In my case the reason was pretty stupid - github token I used for authorization was issued for the organization that doesn't own the repo I tried to publish into. So check repo title and ownership.
EntityManagerFactory is the standard implementation, it is the same across all the implementations. If you migrate your ORM for any other provider like EclipseLink, there will not be any change in the approach for handling the transaction. In contrast, if you use hibernate’s session factory, it is tied to hibernate APIs and cannot migrate to new vendor.
I guess the main thing here is:
Never user:
@anything = NULL
@anything <> NULL
@anything != null
Always use:
@anything IS NULL
@anything IS NOT NULL
There are different eclipse plugins available to manage Tomcat server and create war file.
For example you can use tomcatPlugin. It permits to start/stop and build the war simply. You can read this tutorial.
Linked list does guarantee sequential order.
Don't use linkedList.get(i), especially inside a sequential loop since it defeats the purpose of having a linked list and will be inefficient code.
Use ListIterator
ListIterator<Object> iterator = myLinkedList.listIterator();
while( iterator.hasNext()) {
System.out.println(iterator.next());
}
You could use a Data URI to supply the image data, for example:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image width="20" height="20" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>
</svg>
The image will go through all normal svg transformations.
But this technique has disadvantages, for example the image will not be cached by the browser
This code works even with file input
$(document).on("submit", "form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
Blank=False # this field is required.
Null=False # this field should not be null
Blank=True # this field is optional.
Null=True # Django uses empty string (''), not NULL.
Note:
Avoid using null=True
on string-based fields such as CharField
and TextField
and FileField
/ImageField
.
Ref: Django null , Django blank
A solution using the curses module. Printing a numeric value corresponding to each key pressed:
import curses
def main(stdscr):
# do not wait for input when calling getch
stdscr.nodelay(1)
while True:
# get keyboard input, returns -1 if none available
c = stdscr.getch()
if c != -1:
# print numeric value
stdscr.addstr(str(c) + ' ')
stdscr.refresh()
# return curser to start position
stdscr.move(0, 0)
if __name__ == '__main__':
curses.wrapper(main)
Here is a simple way to enable them. In mysql we need to see often 3 logs which are mostly needed during any project development.
The Error Log
. It contains information about errors that occur while
the server is running (also server start and stop)
The General Query Log
. This is a general record of what mysqld is
doing (connect, disconnect, queries)
The Slow Query Log
. ?t consists of "slow" SQL statements (as
indicated by its name).
By default no log files are enabled in MYSQL. All errors will be shown in the syslog (/var/log/syslog
).
To Enable them just follow below steps:
step1: Go to this file (/etc/mysql/conf.d/mysqld_safe_syslog.cnf) and remove or comment those line.
step2: Go to mysql conf file (/etc/mysql/my.cnf
) and add following lines
To enable error log add following
[mysqld_safe]
log_error=/var/log/mysql/mysql_error.log
[mysqld]
log_error=/var/log/mysql/mysql_error.log
To enable general query log add following
general_log_file = /var/log/mysql/mysql.log
general_log = 1
To enable Slow Query Log add following
log_slow_queries = /var/log/mysql/mysql-slow.log
long_query_time = 2
log-queries-not-using-indexes
step3: save the file and restart mysql using following commands
service mysql restart
To enable logs at runtime, login to mysql client (mysql -u root -p
) and give:
SET GLOBAL general_log = 'ON';
SET GLOBAL slow_query_log = 'ON';
Finally one thing I would like to mention here is I read this from a blog. Thanks. It works for me.
Click here to visit the blog
Helpfull for usage in unit tests:
This is a simple version which can be extended to different use cases (e.g. with the use of tableNames).
public func NSLocalizedString(key: String, referenceClass: AnyClass, comment: String = "") -> String
{
let bundle = NSBundle(forClass: referenceClass)
return NSLocalizedString(key, tableName:nil, bundle: bundle, comment: comment)
}
Use it like this:
NSLocalizedString("YOUR-KEY", referenceClass: self)
Or like this with a comment:
NSLocalizedString("YOUR-KEY", referenceClass: self, comment: "usage description")
In Python, there is a distinction between bound and unbound methods.
Basically, a call to a member function (like method_one
), a bound function
a_test.method_one()
is translated to
Test.method_one(a_test)
i.e. a call to an unbound method. Because of that, a call to your version of method_two
will fail with a TypeError
>>> a_test = Test()
>>> a_test.method_two()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)
You can change the behavior of a method using a decorator
class Test(object):
def method_one(self):
print "Called method_one"
@staticmethod
def method_two():
print "Called method two"
The decorator tells the built-in default metaclass type
(the class of a class, cf. this question) to not create bound methods for method_two
.
Now, you can invoke static method both on an instance or on the class directly:
>>> a_test = Test()
>>> a_test.method_one()
Called method_one
>>> a_test.method_two()
Called method_two
>>> Test.method_two()
Called method_two
JOIN with different tables
SELECT COUNT(*) FROM (
SELECT DISTINCT table_a.ID FROM table_a JOIN table_c ON table_a.ID = table_c.ID );
Further to what Steve Baker has said, you can find a description of the SIOCGIFCONF ioctl in the netdevice(7) man page.
Once you have the list of all the IP addresses on the host, you will have to use application specific logic to filter out the addresses you do not want and hope you have one IP address left.
model.update({"_id": 1, "items.id": "2"},
{$set: {"items.$.name": "yourValue","items.$.value": "yourvalue"}})
I also came across the same problem, what I did was
1) Open your cmd
2) Navigate to C:\Program Files\MySQL\MySQL Server 8.0\bin> (where MySQL Server 8.0 may be different depending on the server you installed)
3) Then put the following command mysql -u root -p
4) I will prompt for the password... simply hit enter, as sometimes the password you entered while installing is changed by to blank.
now you can simply access the database
This solution worked for me on windows platform
First of all, Thanks to code author!
I found the below link while googling and it is very simple and works best. Would never fail unless SVG is deprecated.
https://codepen.io/moistpaint/pen/ywFDe/
There is some js loading error in the code here but its perfectly working on the codepen.io link provided.
var mapOptions = {_x000D_
zoom: 16,_x000D_
center: new google.maps.LatLng(-37.808846, 144.963435)_x000D_
};_x000D_
map = new google.maps.Map(document.getElementById('map-canvas'),_x000D_
mapOptions);_x000D_
_x000D_
_x000D_
var pinz = [_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.807817,_x000D_
'lon' : 144.958377_x000D_
},_x000D_
'lable' : 2_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.807885,_x000D_
'lon' : 144.965415_x000D_
},_x000D_
'lable' : 42_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.811377,_x000D_
'lon' : 144.956596_x000D_
},_x000D_
'lable' : 87_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.811293,_x000D_
'lon' : 144.962883_x000D_
},_x000D_
'lable' : 145_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.808089,_x000D_
'lon' : 144.962089_x000D_
},_x000D_
'lable' : 999_x000D_
},_x000D_
];_x000D_
_x000D_
_x000D_
_x000D_
for(var i = 0; i <= pinz.length; i++){_x000D_
var image = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2238%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23808080%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate%2819%2018.5%29%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + pinz[i].lable + '%3C%2Ftext%3E%3C%2Fsvg%3E';_x000D_
_x000D_
_x000D_
var myLatLng = new google.maps.LatLng(pinz[i].location.lat, pinz[i].location.lon);_x000D_
var marker = new google.maps.Marker({_x000D_
position: myLatLng,_x000D_
map: map,_x000D_
icon: image_x000D_
});_x000D_
}
_x000D_
html, body, #map-canvas {_x000D_
height: 100%;_x000D_
margin: 0px;_x000D_
padding: 0px_x000D_
}
_x000D_
<div id="map-canvas"></div>_x000D_
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDtc3qowwB96ObzSu2vvjEoM2pVhZRQNSA&signed_in=true&callback=initMap&libraries=drawing,places"></script>
_x000D_
You just need to uri-encode your SVG html and replace the one in the image variable after "data:image/svg+xml" in the for loop.
For uri encoding you can use uri-encoder-decoder
You can decode the existing svg code first to get a better understanding of what is written.
Use onclick="foo(document.getElementById('formValueId').value)"
if (myReader.HasRows) //The key Word is **.HasRows**
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null Or Empty";
}
I need to make a POST request via Curl from the command line. Data for this request is located in a file...
All you need to do is have the --data
argument start with a @
:
curl -H "Content-Type: text/xml" --data "@path_of_file" host:port/post-file-path
For example, if you have the data in a file called stuff.xml
then you would do something like:
curl -H "Content-Type: text/xml" --data "@stuff.xml" host:port/post-file-path
The stuff.xml
filename can be replaced with a relative or full path to the file: @../xml/stuff.xml
, @/var/tmp/stuff.xml
, ...
In eclipse help documentation, we can all icons information as follows. Common path for all eclipse versions except eclipse version:
class Program
{
static void Main(string[] args)
{
//Load XML from local
string sourceFileName="";
string element=string.Empty;
var FolderPath=@"D:\Test\RenameFileWithXmlAttribute";
string[] files = Directory.GetFiles(FolderPath, "*.xml");
foreach (string xmlfile in files)
{
try
{
sourceFileName = xmlfile;
XElement xele = XElement.Load(sourceFileName);
string convertToString = xele.ToString();
XElement parseXML = XElement.Parse(convertToString);
element = parseXML.Descendants("Meta").Where(x => (string)x.Attribute("name") == "XMLTAG").Last().Value;
DirectoryInfo CurrentDate = Directory.CreateDirectory(DateTime.Now.ToString("yyyy-MM-dd"));
string saveWithThisName= Path.Combine(CurrentDate.FullName, element);
File.Copy(sourceFileName, saveWithThisName,true);
}
catch(Exception ex)
{
}
}
}
}
If using Python 2.5, you may need to import simplejson
:
try:
import json
except ImportError:
import simplejson as json
See java.beans.ConstructorProperties, it's an annotation designed for doing exactly this.
Because this post is the top one found on stackoverflow when searching for "ORA-00942: table or view does not exist insert", I want to mention another possible cause of this error (at least in Oracle 12c): a table uses a sequence to set a default value and the user executing the insert query does not have select privilege on the sequence. This was my problem and it took me an unnecessarily long time to figure it out.
To reproduce the problem, execute the following SQL as user1
:
create sequence seq_customer_id;
create table customer (
c_id number(10) default seq_customer_id.nextval primary key,
name varchar(100) not null,
surname varchar(100) not null
);
grant select, insert, update, delete on customer to user2;
Then, execute this insert statement as user2
:
insert into user1.customer (name,surname) values ('michael','jackson');
The result will be "ORA-00942: table or view does not exist" even though user2
does have insert and select privileges on user1.customer
table and is correctly prefixing the table with the schema owner name. To avoid the problem, you must grant select privilege on the sequence:
grant select on seq_customer_id to user2;
Use this
<input type="checkbox" onclick="onClickHandler()" id="box" />
<script>
function onClickHandler(){
var chk=document.getElementById("box").value;
//use this value
}
</script>
You need to manually create a symlink /usr/bin/node
. Shortcut for bash compatible shells:
sudo ln -s `which nodejs` /usr/bin/node
Or if you use non-standard shells, just hardcode the path you find with which nodejs
:
sudo ln -s /usr/bin/nodejs /usr/bin/node
Later edit
I found this explanation in the link you posted
There is a naming conflict with the node package (Amateur Packet Radio Node Program), and the nodejs binary has been renamed from node to nodejs. You'll need to symlink /usr/bin/node to /usr/bin/nodejs or you could uninstall the Amateur Packet Radio Node Program to avoid that conflict.
Later later edit
It's been a while since I answered this. Although the solution I posted up here worked for me several times, users have reported a few more solutions within the comments:
From @user229115
sudo update-alternatives --install /usr/bin/node node /usr/bin/nodejs 10
From AskUbuntu (user leftium)
sudo apt-get --purge remove node
sudo apt-get --purge remove nodejs
sudo apt-get install nodejs
For Bootstrap v4.1
Add the data-parent
attribute to the collapse
elements instead on the button
.
<div id="myGroup">
<button class="btn dropdown" data-toggle="collapse" data-target="#keys"><i class="icon-chevron-right"></i> Keys <span class="badge badge-info pull-right">X</span></button>
<button class="btn dropdown" data-toggle="collapse" data-target="#attrs"><i class="icon-chevron-right"></i> Attributes</button>
<button class="btn dropdown" data-toggle="collapse" data-target="#edit"><i class="icon-chevron-right"></i> Edit Details</button>
<div class="accordion-group">
<div class="collapse indent" id="keys" data-parent="#myGroup">
keys
</div>
<div class="collapse indent" id="attrs" data-parent="#myGroup">
attrs
</div>
<div class="collapse" id="edit" data-parent="#myGroup">
edit
</div>
</div>
The _t data types are typedef types in the stdint.h header, while int is an in built fundamental data type. This make the _t available only if stdint.h exists. int on the other hand is guaranteed to exist.
Converting it to integer worked for me:
int(sub_df.iloc[0])
Just throwing in my two bits here, but I found ArgoUML to be very useful. It takes a little while to get used to it and its a bit buggy (last I checked it was in version .29 or so) but it works pretty well once you get used to it. It handles all types of UML diagrams, which is why I prefer it. Also, its made by tigris, the same people who made subclipse, an SVN repository plug-in for Eclipse.
var jqueryFunction;
$().ready(function(){
//jQuery function
jqueryFunction = function( _msg )
{
alert( _msg );
}
})
//javascript function
function jsFunction()
{
//Invoke jQuery Function
jqueryFunction("Call from js to jQuery");
}
http://www.designscripting.com/2012/08/call-jquery-function-from-javascript/
If you have multiple source files, you probably actually want to use link-time-optimization to output one bitcode file for the entire program. The other answers given will cause you to end up with a bitcode file for every source file.
Instead, you want to compile with link-time-optimization
clang -flto -c program1.c -o program1.o
clang -flto -c program2.c -o program2.o
and for the final linking step, add the argument -Wl,-plugin-opt=also-emit-llvm
clang -flto -Wl,-plugin-opt=also-emit-llvm program1.o program2.o -o program
This gives you both a compiled program and the bitcode corresponding to it (program.bc). You can then modify program.bc in any way you like, and recompile the modified program at any time by doing
clang program.bc -o program
although be aware that you need to include any necessary linker flags (for external libraries, etc) at this step again.
Note that you need to be using the gold linker for this to work. If you want to force clang to use a specific linker, create a symlink to that linker named "ld" in a special directory called "fakebin" somewhere on your computer, and add the option
-B/home/jeremy/fakebin
to any linking steps above.
This is not really a shortcut but just a quick access to the control menu: Alt-space E P
If you can use your mouse, right click on the cmd window works as paste when I tried it.
IF CHARINDEX('TextToSearch',@TextWhereISearch, 0) > 0 => TEXT EXISTS
IF PATINDEX('TextToSearch', @TextWhereISearch) > 0 => TEXT EXISTS
Additionally we can also use LIKE but I usually don't use LIKE.
var oldString = "stackoverflow";
var str=oldString.replace(/stackover/g,"NO");
$scope.newString= str;
It works for me. Use an intermediate variable.
Forward declaration should have complete template arguments list specified.
My solution was to not use the id of an anchor element: <a id='star_wars'>Place to jump to</a>
. Apparently blazor and other spa frameworks have issues jumping to anchors on the same page. To get around that I had to use document.getElementById('star_wars')
. However this didn't work until I put the id in a paragraph element instead: <p id='star_wars'>Some paragraph<p>
.
Example using bootstrap:
<button class="btn btn-link" onclick="document.getElementById('star_wars').scrollIntoView({behavior:'smooth'})">Star Wars</button>
... lots of other text
<p id="star_wars">Star Wars is an American epic...</p>
You can use as many colors and images as you desire.
Please note that the priority with which the background images are rendered is FILO, the first specified image is on the top layer, the last specified image is on the bottom layer (see the snippet).
#composition {_x000D_
width: 400px;_x000D_
height: 200px;_x000D_
background-image:_x000D_
linear-gradient(to right, #FF0000, #FF0000), /* gradient 1 as solid color */_x000D_
linear-gradient(to right, #00FF00, #00FF00), /* gradient 2 as solid color */_x000D_
linear-gradient(to right, #0000FF, #0000FF), /* gradient 3 as solid color */_x000D_
url('http://lorempixel.com/400/200/'); /* image */_x000D_
background-repeat: no-repeat; /* same as no-repeat, no-repeat, no-repeat */_x000D_
background-position:_x000D_
0 0, /* gradient 1 */_x000D_
20px 0, /* gradient 2 */_x000D_
40px 0, /* gradient 3 */_x000D_
0 0; /* image position */_x000D_
background-size:_x000D_
30px 30px,_x000D_
30px 30px,_x000D_
30px 30px,_x000D_
100% 100%;_x000D_
}
_x000D_
<div id="composition">_x000D_
</div>
_x000D_
If you have pandas
installed, you can convert the ordered dict to a pandas Series
. This will allow random access to the dictionary elements.
>>> import collections
>>> import pandas as pd
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> s = pd.Series(d)
>>> s['bar']
spam
>>> s.iloc[1]
spam
>>> s.index[1]
bar
Get the field value through the id and send with ajax
var field = $("#field").val();
$.ajax({
type: "POST",
url: "db.php",
data: {variable_name:field},
async:false,
dataType:"json",
success: function(response) {
alert(response);
}
});
At db.php file get the variable name
$variable_name = $_GET['variable_name'];
mysql_query("SELECT password FROM table_name WHERE password='".md5($variable_name)."'");
Another approach that may be more readable is simple type conversion. I've added a replacement function to cover instances where people may enter European decimals:
>>> for possibility in "Current Level: -13.2 db or 14,2 or 3".split():
... try:
... str(float(possibility.replace(',', '.')))
... except ValueError:
... pass
'-13.2'
'14.2'
'3.0'
This has disadvantages too however. If someone types in "1,000", this will be converted to 1. Also, it assumes that people will be inputting with whitespace between words. This is not the case with other languages, such as Chinese.
If what you want to find is already in a string, and you don't have a regex escaper handy, you can use join/split:
function replaceMulti(haystack, needle, replacement)_x000D_
{_x000D_
return haystack.split(needle).join(replacement);_x000D_
}_x000D_
_x000D_
someString = 'the cat looks like a cat';_x000D_
console.log(replaceMulti(someString, 'cat', 'dog'));
_x000D_
I'm using ubuntu 13.04 as host. This clear tutorial works:
To add more resolutions, do the following:
Execute at terminal:
~# VBoxManage list runningvms
Check your VM name
Add a new resolution:
~# VBoxManage setextradata "[YourVmNameHere]" "CustomVideoMode1" "800x480x16"
Find in above tutorial: "Test different screen size and resolution"
You could use .test() which returns a boolean value when is find what your looking for in another string:
var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/'];
var thisString = new RegExp('\\b' + 'else' + '\\b', 'i');
var FoundIt = thisString.test(thisExpressions);
if (FoundIt) { /* DO STUFF */ }
The answer by EdChum provides you with a lot of flexibility but if you just want to concateate strings into a column of list objects you can also:
output_series = df.groupby(['name','month'])['text'].apply(list)
Also make sure the div is currently appended to the DOM and visible.
Technically what you are looking for is the unset value in combination with the shorthand property all:
The unset CSS keyword resets a property to its inherited value if it inherits from its parent, and to its initial value if not. In other words, it behaves like the inherit keyword in the first case, and like the initial keyword in the second case. It can be applied to any CSS property, including the CSS shorthand all.
.customClass {
/* specific attribute */
color: unset;
}
.otherClass{
/* unset all attributes */
all: unset;
/* then set own attributes */
color: red;
}
You can use the initial value as well, this will default to the initial browser value.
.otherClass{
/* unset all attributes */
all: initial;
/* then set own attributes */
color: red;
}
As an alternative:
If possible it is probably good practice to encapsulate the class or id in a kind of namespace:
.namespace .customClass{
color: red;
}
<div class="namespace">
<div class="customClass"></div>
</div>
because of the specificity of the selector this will only influence your own classes
It is easier to accomplish this in "preprocessor scripting languages" like SASS with nesting capabilities:
.namespace{
.customClass{
color: red
}
}
There is no CSS property like background-opacity that you can use only for changing the opacity or transparency of an element's background without affecting the child elements, on the other hand if you will try to use the CSS opacity property it will not only changes the opacity of background but changes the opacity of all the child elements as well. In such situation you can use RGBA color introduced in CSS3 that includes alpha transparency as part of the color value. Using RGBA color you can set the color of the background as well as its transparency.
F5 and the refresh button will look at your browser cache before asking the server for content.
Ctrl + F5 forces a load from the server.
You can set content expiration headers and/or meta tags to ensure the browser doesn't cache anything (perhaps something you can do only for the development environment).
In Bash you can also explicitly specify your redirects to different files:
cmd >log.out 2>log_error.out
Appending would be:
cmd >>log.out 2>>log_error.out
Try asmcrypto.js — it's really fast.
PS: I'm an author and I can answer your questions if any. Also I'd be glad to get some feedback :)
1st put "yourmp3file".mp3 file in the raw folder(ie inside Res folder)
2nd in your code put..
Notification noti = new Notification.Builder(this)
.setSound(Uri.parse("android.resource://" + v.getContext().getPackageName() + "/" + R.raw.yourmp3file))//*see note
This is what i put inside my onClick(View v) as only "context().getPackageName()" wont work from there as it wont get any context
Partly based on StevenOjo's answer. I've tested this using a horizontal scrolling and no Bounce UICollectionView. cellSize is CollectionViewCell size. You can tweak factor to modify scrolling sensitivity.
override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
targetContentOffset.pointee = scrollView.contentOffset
var factor: CGFloat = 0.5
if velocity.x < 0 {
factor = -factor
}
let indexPath = IndexPath(row: (scrollView.contentOffset.x/cellSize.width + factor).int, section: 0)
collectionView?.scrollToItem(at: indexPath, at: .left, animated: true)
}
Month
enumYou could use the Month
enum. This enum is defined as part of the new java.time framework built into Java 8 and later.
int monthNumber = 10;
Month.of(monthNumber).name();
The output would be:
OCTOBER
Localize to a language beyond English by calling getDisplayName
on the same Enum.
String output = Month.OCTOBER.getDisplayName ( TextStyle.FULL , Locale.CANADA_FRENCH );
output:
octobre
Base url set in CodeIgniter for all url
$config['base_url'] = "http://".$_SERVER['HTTP_HOST']."/";
SELECT
(select count(*) from foo1 where ID = '00123244552000258')
+
(select count(*) from foo2 where ID = '00123244552000258')
+
(select count(*) from foo3 where ID = '00123244552000258')
This is an easy way.
This is another option to write a pandas dataframe directly into a matplotlib table:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# hide axes
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')
df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
ax.table(cellText=df.values, colLabels=df.columns, loc='center')
fig.tight_layout()
plt.show()
Action
is a Type of Delegate provided by the .NET framework. The Action
points to a method with no parameters and does not return a value.
() =>
is lambda expression syntax. Lambda expressions are not of Type Delegate
. Invoke requires Delegate
so Action
can be used to wrap the lambda expression and provide the expected Type
to Invoke()
Invoke
causes said Action
to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions
. For example, if one tries to set the Rtf
property on a RichTextBox
when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid
exception will be thrown. Check Control.InvokeRequired
before calling Invoke.
BeginInvoke
is the Asynchronous version of Invoke
. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.
or //div[@id='id-74385'][@class='guest clearfix']
shutil.copy
and shutil.copy2
are copying files.
shutil.copytree
copies a folder with all the files and all subfolders. shutil.copytree
is using shutil.copy2
to copy the files.
So the analog to cp -r
you are saying is the shutil.copytree
because cp -r
targets and copies a folder and its files/subfolders like shutil.copytree
. Without the -r
cp
copies files like shutil.copy
and shutil.copy2
do.
background.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:width="3dp"
android:color="#0FECFF" />
//specify gradient
<gradient
android:startColor="#ffffffff"
android:endColor="#110000FF"
android:angle="90"/>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical"
android:layout_marginBottom="10dp"
android:background="@drawable/background">
Just Go To the Genymotion Installation Directory and then in folder tools you will see adb.exe there open command prompt here and run adb commands
Thanks for the info user 'user712934'
You can also look up the sql,username,machine,port information and get to the actual process which holds the connection
SELECT O.OBJECT_NAME, S.SID, S.SERIAL#, P.SPID, S.PROGRAM,S.USERNAME,
S.MACHINE,S.PORT , S.LOGON_TIME,SQ.SQL_FULLTEXT
FROM V$LOCKED_OBJECT L, DBA_OBJECTS O, V$SESSION S,
V$PROCESS P, V$SQL SQ
WHERE L.OBJECT_ID = O.OBJECT_ID
AND L.SESSION_ID = S.SID AND S.PADDR = P.ADDR
AND S.SQL_ADDRESS = SQ.ADDRESS;
Use FileSystemView
private FileSystemView fileSystemView;
fileSystemView = FileSystemView.getFileSystemView();
currentDirectory = new File(".");
//listing currentDirectory
File[] filesAndDirs = fileSystemView.getFiles(currentDirectory, false);
fileList = new ArrayList<File>();
dirList = new ArrayList<File>();
for (File file : filesAndDirs) {
if (file.isDirectory())
dirList.add(file);
else
fileList.add(file);
}
Collections.sort(dirList);
if (!fileSystemView.isFileSystemRoot(currentDirectory))
dirList.add(0, new File(".."));
Collections.sort(fileList);
//change
currentDirectory = fileSystemView.getParentDirectory(currentDirectory);
i have used this and solved my
-webkit-appearance:none;
Your update syntax is incorrect. Please check Update Syntax for the correct syntax.
$sql = "UPDATE `access_users` set `contact_first_name` = :firstname, `contact_surname` = :surname, `contact_email` = :email, `telephone` = :telephone";
Another way ..
<img ng-src="{{!video.playing ? 'img/icons/play-rounded-button-outline.svg' : 'img/icons/pause-thin-rounded-button.svg'}}" />
Run your program with
python -t script.py
This will warn you if you have mixed tabs and spaces.
On *nix systems, you can see where the tabs are by running
cat -A script.py
and you can automatically convert tabs to 4 spaces with the command
expand -t 4 script.py > fixed_script.py
PS. Be sure to use a programming editor (e.g. emacs, vim), not a word processor, when programming. You won't get this problem with a programming editor.
PPS. For emacs users, M-x whitespace-mode
will show the same info as cat -A
from within an emacs buffer!
String name = "\"john\"";
You have to escape the second pair of quotation marks using the \ character in front. It might be worth looking at this link, which explains in some detail.
Other scenario where you set variable:
String name2 = "\""+name+"\"";
Sequence in console:
> String name = "\"john\"";
> name
""john""
> String name2 = "\""+name+"\"";
> name2
"""john"""