Your understanding is mostly correct. You use select_related
when the object that you're going to be selecting is a single object, so OneToOneField
or a ForeignKey
. You use prefetch_related
when you're going to get a "set" of things, so ManyToManyField
s as you stated or reverse ForeignKey
s. Just to clarify what I mean by "reverse ForeignKey
s" here's an example:
class ModelA(models.Model):
pass
class ModelB(models.Model):
a = ForeignKey(ModelA)
ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship
The difference is that select_related
does an SQL join and therefore gets the results back as part of the table from the SQL server. prefetch_related
on the other hand executes another query and therefore reduces the redundant columns in the original object (ModelA
in the above example). You may use prefetch_related
for anything that you can use select_related
for.
The tradeoffs are that prefetch_related
has to create and send a list of IDs to select back to the server, this can take a while. I'm not sure if there's a nice way of doing this in a transaction, but my understanding is that Django always just sends a list and says SELECT ... WHERE pk IN (...,...,...) basically. In this case if the prefetched data is sparse (let's say U.S. State objects linked to people's addresses) this can be very good, however if it's closer to one-to-one, this can waste a lot of communications. If in doubt, try both and see which performs better.
Everything discussed above is basically about the communications with the database. On the Python side however prefetch_related
has the extra benefit that a single object is used to represent each object in the database. With select_related
duplicate objects will be created in Python for each "parent" object. Since objects in Python have a decent bit of memory overhead this can also be a consideration.
The nil pointer dereference is in line 65 which is the defer in
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
return nil, err
}
If err!= nil then res==nil and res.Body panics. Handle err before defering the res.Body.Close().
Do this for your database. I have the same issue - it works fine in one database but when I copy this database to another using SSIS Import (not the usual restore), this issue happens to most of my stored procedures. So after googling some more, I found the blog of Pinal Dave (which btw, I encountered most of his post and did help me a lot so thanks Pinal Dave).
I execute the below query on my database and it corrected my issue:
EXEC sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?', ' ', 80)"
GO
EXEC sp_updatestats
GO
Hope this helps. Just passing the help from others that helped me.
I am using spyder 3.3.1 - windows 7 - python 3.6 although flush may not be needed. based on this posting - https://github.com/spyder-ide/spyder/issues/3437
#works in spyder ipython console - \r at start of string , end=""
import time
import sys
for i in range(20):
time.sleep(0.5)
print(f"\rnumber{i}",end="")
sys.stdout.flush()
Check out:
var crypto = require('crypto');
crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0,length);
I think this is the syntax you are looking for:
if [ -z != $errorstatus ]
then
commands
else
commands
fi
I finally solved this problem. I used Samsung Galaxy S with Froyo. The "port" below is the same port what you use for the emulator (10.0.2.2:port). What I did:
http://192.168.x.x:port/test.php
It should now work.
I'm fairly certain that the ls
command is for Linux, not Windows (I'm assuming you're using Windows as you referred to cmd
, which is the command line for the Windows OS).
You should use dir
instead, which is the Windows equivalent of ls
.
Edit (since this post seems to be getting so many views :) ):
You can't use ls
on cmd
as it's not shipped with Windows
, but you can use it on other terminal programs (such as GitBash). Note, ls
might work on some FTP
servers if the servers are linux
based and the FTP
is being used from cmd
.
dir
on Windows
is similar to ls
. To find out the various options available, just do dir/?
.
If you really want to use ls
, you could install 3rd party tools to allow you to run unix
commands on Windows
. Such a program is Microsoft Windows Subsystem for Linux
(link to docs).
From Dive Into Python:
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5
I'm relatively new to c# and brand new to stackoverflow. Anyway, regarding the question on how to access controls on a form from a class: I just used the ControlCollection (Controls) class of the form.
//Add a new form called frmEditData to project.
//Draw a textbox on it named txtTest; set the text to
//something in design as a test.
Form frmED = new frmEditData();
MessageBox.Show(frmED.Controls["txtTest"].Text);
Worked for me, maybe it will be of assistance in both questions.
The PID is stored in $$
.
Example: kill -9 $$
will kill the shell instance it is called from.
From the menu bar: Project -> Properties -> Java Compiler
Enable project specific settings (checked) Uncheck "use Compliance from execution environment '.... Select the desired "compiler compliance level"
That will allow you to compile "1.5" code using a "1.6" JDK.
If you want to acutally use a 1.5 JDK to produce "1.5" compliant code, then install a suitable 1.5 JDK and tell eclipse where it is installed via:
Window -> preferences -> Installed JREs
And then go back to your project
Project -> properties -> Java Build Path -> libraries
remove the 1.6 system libaries, and: add library... -> JRE System LIbrary -> Alternate JRE -> The JRE you want.
Verify that the correct JRE is on the project's build path, save everything, and enjoy!
You can use equals()
.
enum.equals(String)
Use subprocess.Popen:
import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)
Note that communicate blocks until the process terminates. You could use process.stdout.readline() if you need the output before it terminates. For more information see the documentation.
File sourceFile = new File("C:\\Users\\Demo\\Downloads\\employee\\"+img);
File destinationFile = new File("\\images\\" + sourceFile.getName());
FileInputStream fileInputStream = new FileInputStream(sourceFile);
FileOutputStream fileOutputStream = new FileOutputStream(
destinationFile);
int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
fileOutputStream.write(bufffer, 0, bufferSize);
}
fileInputStream.close();
fileOutputStream.close();
SELECT name, phone_number FROM Call a
WHERE a.phone_number NOT IN (SELECT b.phone_number FROM Phone_book b)
The other answers are correct: You don't have a default value. However, you have another problem in your logic:
You read the same file twice. After reading it once, the cursor is at the end of the file. To solve this, you can do two things: Either open/close the file upon each function call:
def temp_sky(lreq, breq):
with open("/home/path/to/file",'r') as tfile:
# do your stuff
This hase the disadvantage of having to open the file each time. The better way would be:
tfile.seek(0)
You do this after your for line in tfile:
loop. It resets the cursor to the beginning to the next call will start from there again.
From the mysql console:
mysql> use DATABASE_NAME;
mysql> source path/to/file.sql;
make sure there is no slash before path if you are referring to a relative path... it took me a while to realize that! lol
You want to do #include <string>
instead of string.h
and then the type string
lives in the std
namespace, so you will need to use std::string
to refer to it.
Try below code:
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
return resources.getDimensionPixelSize(resourceId);
}
return 0;
you can use the following
private async Task<List<string>> GetItems()
{
return await Task.FromResult(new List<string>
{
"item1", "item2", "item3"
});
}
Setting this:
style="min-width:100px;"
Worked for me.
Are you applying a RowFilter to your DefaultView later in the code? This could change the results returned.
I would also avoid using the string as the display member if you have a direct reference the the data column I would use the object properties:
mnuActionLanguage.ComboBox.DataSource = lTable.DefaultView;
mnuActionLanguage.ComboBox.DisplayMember = lName.ColumnName;
I have tried this with a blank form and standard combo, and seems to work for me.
You can do this using cross apply
SELECT c.BalanceDue AS BalanceDue
FROM Invoices
cross apply (select (InvoiceTotal - PaymentTotal - CreditTotal) as BalanceDue) as c
WHERE c.BalanceDue > 0;
In addition to Ctrl+Shift+F (Cmd+Option+F on Mac) as suggested in this answer, you can right click on the top tree node in the sources tab and select "Search in All Files":
From the first search result on google:
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
JavaScriptSerializer Class
Provides serialization and deserialization functionality for AJAX-enabled applications.
Inheritance Hierarchy
System.Object
System.Web.Script.Serialization.JavaScriptSerializer
Namespace: System.Web.Script.Serialization
Assembly: System.Web.Extensions (in System.Web.Extensions.dll)
So, include System.Web.Extensions.dll
as a reference.
Please have a look on the following page https://varvy.com/pagespeed/render-blocking-css.html . This helped me to get rid of "Render Blocking CSS". I used the following code in order to remove "Render Blocking CSS". Now in google page speed insight I am not getting issue related with render blocking css.
<!-- loadCSS -->
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/cssrelpreload.js"></script>
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/loadCSS.js"></script>
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/onloadCSS.js"></script>
<script>
/*!
loadCSS: load a CSS file asynchronously.
*/
function loadCSS(href){
var ss = window.document.createElement('link'),
ref = window.document.getElementsByTagName('head')[0];
ss.rel = 'stylesheet';
ss.href = href;
// temporarily, set media to something non-matching to ensure it'll
// fetch without blocking render
ss.media = 'only x';
ref.parentNode.insertBefore(ss, ref);
setTimeout( function(){
// set media back to `all` so that the stylesheet applies once it loads
ss.media = 'all';
},0);
}
loadCSS('styles.css');
</script>
<noscript>
<!-- Let's not assume anything -->
<link rel="stylesheet" href="styles.css">
</noscript>
If your requirement is really
.ToString() would result in a string containing digits and +,-,.
and you want to use double.TryParse then you need to use the overload that takes a NumberStyles parameter, and make sure you are using the invariant culture.
For example for a number which may have a leading sign, no leading or trailing whitespace, no thousands separator and a period decimal separator, use:
NumberStyles style =
NumberStyles.AllowLeadingSign |
NumberStyles.AllowDecimalPoint |
double.TryParse(input, style, CultureInfo.InvariantCulture, out result);
The scope <scope>provided</scope>
gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.
Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.
Change groupId
to <groupId>net.sourceforge.ant4x</groupId>
to get the latest jar.
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
Another solution for this problem is:
Where http://localhost/repo is your local repo URL:
<repositories>
<repository>
<id>wmc-central</id>
<url>http://localhost/repo</url>
</repository>
<-- Other repository config ... -->
</repositories>
in my case this was the solution = () => {}
methodName = (params) => {
//your code here with this.something
}
commands
also works.
import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result
It works on linux, python 2.7.
You can try with this:
function doParseCSVFile($filesArray)
{
if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) {
$strFilePath = $filesArray['frmUpload']['tmp_name'];
$strFileHandle = fopen($strFilePath,"r");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
do {
if ($line_of_text[0]) {
$strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
ExecuteQry($strInsertSql);
}
} while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);
} else {
return FALSE;
}
}
If you want to guarantee the same order regardless of the order of elements in the input array, here is a stable sorting:
myArray.sort(function(a, b) {
/* Storing case insensitive comparison */
var comparison = a.toLowerCase().localeCompare(b.toLowerCase());
/* If strings are equal in case insensitive comparison */
if (comparison === 0) {
/* Return case sensitive comparison instead */
return a.localeCompare(b);
}
/* Otherwise return result */
return comparison;
});
My educated guess is that the memory use you are seeing is not from the page content, but rather from loading UIWebView and all of it's supporting WebKit libraries. I love the UIWebView control, but it is a 'heavy' control that pulls in a very large block of code.
This code is a large sub-set of the iOS Safari browser, and likely initializes a large body of static structures.
From Ubuntu Terminal, below works for me.
./adb push '/home/hardik.trivedi/Downloads/one.jpg' '/data/local/'
I believe this is an old question, and the Traffic was introduced by Github in 2014. Here is the link to the description of Traffic, that tells you the views on your repositories.
Another way to do simultaneous animations if you want to call them separately (eg. from different code) is to use queue
. Again, as with Tinister's answer you would have to use animate for this and not fadeIn:
$('.tooltip').css('opacity', 0);
$('.tooltip').show();
...
$('.tooltip').animate({opacity: 1}, {queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');
you can use raiserror
. Read more details here
--from MSDN
BEGIN TRY
-- RAISERROR with severity 11-19 will cause execution to
-- jump to the CATCH block.
RAISERROR ('Error raised in TRY block.', -- Message text.
16, -- Severity.
1 -- State.
);
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH;
EDIT
If you are using SQL Server 2012+ you can use throw
clause. Here are the details.
You could use a script like the below. You would just need to change the date options to match the format you wanted.
#!/bin/bash
for i in `ls -l /directroy`
do
cp $i /newDirectory/$i.`date +%m%d%Y`
done
It might help you!
AngularJs Code-sample
var app = angular.module('urlApp', []);
app.controller('urlCtrl', function ($scope, $log, $window) {
$scope.ClickMeToRedirect = function () {
var url = "http://" + $window.location.host + "/Account/Login";
$log.log(url);
$window.location.href = url;
};
});
HTML Code-sample
<div ng-app="urlApp">
<div ng-controller="urlCtrl">
Redirect to <a href="#" ng-click="ClickMeToRedirect()">Click Me!</a>
</div>
</div>
If you actually want to change the number itself instead of only displaying it differently use format()
Format it to 2 decimal places:
format(value, '.2f')
example:
>>> format(5.00000, '.2f')
'5.00'
In Eztrieve it's really easy, below is an example how you could code it:
//STEP01 EXEC PGM=EZTPA00
//FILEA DD DSN=FILEA,DISP=SHR
//FILEB DD DSN=FILEB,DISP=SHR
//FILEC DD DSN=FILEC.DIF,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(100,50),RLSE),
// UNIT=PRMDA,
// DCB=(RECFM=FB,LRECL=5200,BLKSIZE=0)
//SYSOUT DD SYSOUT=*
//SRTMSG DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SYSIN DD *
FILE FILEA
FA-KEY 1 7 A
FA-REC1 8 10 A
FA-REC2 18 5 A
FILE FILEB
FB-KEY 1 7 A
FB-REC1 8 10 A
FB-REC2 18 5 A
FILE FILEC
FILE FILED
FD-KEY 1 7 A
FD-REC1 8 10 A
FD-REC2 18 5 A
JOB INPUT (FILEA KEY FA-KEY FILEB KEY FB-KEY)
IF MATCHED
FD-KEY = FB-KEY
FD-REC1 = FA-REC1
FD-REC2 = FB-REC2
PUT FILED
ELSE
IF FILEA
PUT FILEC FROM FILEA
ELSE
PUT FILEC FROM FILEB
END-IF
END-IF
/*
I've written the tests that compare using regular expressions (as per other answers) against not using regular expressions. Tests done on a quad core OSX10.8 machine running Java 1.6
Interestingly using regular expressions turns out to be about 5-10 times slower than manually iterating over a string. Furthermore the isAlphanumeric2()
function is marginally faster than isAlphanumeric()
. One supports the case where extended Unicode numbers are allowed, and the other is for when only standard ASCII numbers are allowed.
public class QuickTest extends TestCase {
private final int reps = 1000000;
public void testRegexp() {
for(int i = 0; i < reps; i++)
("ab4r3rgf"+i).matches("[a-zA-Z0-9]");
}
public void testIsAlphanumeric() {
for(int i = 0; i < reps; i++)
isAlphanumeric("ab4r3rgf"+i);
}
public void testIsAlphanumeric2() {
for(int i = 0; i < reps; i++)
isAlphanumeric2("ab4r3rgf"+i);
}
public boolean isAlphanumeric(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (!Character.isLetterOrDigit(c))
return false;
}
return true;
}
public boolean isAlphanumeric2(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
return false;
}
return true;
}
}
I'm using Ubuntu 16.04 and PHP 5.6.20
After too many problems, the below steps solved this for me:
find php.ini
path via phpinfo()
uncomment
extension=php_pdo_mysql.dll
add this line
extension=pdo_mysql.so
then run
sudo apt-get install php-mysql
One of these should work:
import math
math.trunc(1.5)
> 1
math.trunc(-1.5)
> -1
math.floor(1.5)
> 1
math.floor(-1.5)
> -2
You need to create a popover instance that has the html option enabled (place this in your javascript file after the popover JS code):
$('.popover-with-html').popover({ html : true });
I would suggest mine solution that you can find in this GitHub repo. This works also for IE8 and IE9 with a custom arrow that comes from an icon font.
Examples of Custom Cross Browser Drop-down in action: check them with all your browsers to see the cross-browser feature.
Anyway, let's start with the modern browsers and then we will see the solution for the older ones.
For these browser, it is easy to set the same background image for the drop-down in order to have the same arrow.
To do so, you have to reset the browser's default style for the select
tag and set new background rules (like suggested before).
select {
/* you should keep these firsts rules in place to maintain cross-browser behaviour */
-webkit-appearance: none;
-moz-appearance: none;
-o-appearance: none;
appearance: none;
background-image: url('<custom_arrow_image_url_here>');
background-position: 98% center;
background-repeat: no-repeat;
outline: none;
...
}
The appearance
rules are set to none to reset browsers default ones, if you want to have the same aspect for each arrow, you should keep them in place.
The background
rules in the examples are set with SVG inline images that represent different arrows. They are positioned 98% from left to keep some margin to the right border (you can easily modify the position as you wish).
In order to maintain the correct cross-browser behavior, the only other rule that have to be left in place is the outline
. This rule resets the default border that appears (in some browsers) when the element is clicked. All the others rules can be easily modified if needed.
This is the harder part... Or maybe not.
There is no standard rule to hide the default arrows for these browsers (like the select::-ms-expand
for IE10+). The solution is to hide the part of the drop-down that contains the default arrow and insert an arrow icon font (or a SVG, if you prefer) similar to the SVG that is used in the other browsers (see the select
CSS rule for more details about the inline SVG used).
The very first step is to set a class that can recognize the browser: this is the reason why I have used the conditional IE IFs at the beginning of the code. These IFs are used to attach specific classes to the html
tag to recognize the older IE browser.
After that, every select
in the HTML have to be wrapped by a div
(or whatever tag that can wraps an element). At this wrapper just add the class that contains the icon font.
<div class="selectTagWrapper prefix-icon-arrow-down-fill">
...
</div>
In easy words, this wrapper is used to simulate the select
tag.
To act like a drop-down, the wrapper must have a border, because we hide the one that comes from the select
.
Notice that we cannot use the select
border because we have to hide the default arrow lengthening it 25% more than the wrapper. Consequently its right border should not be visible because we hide this 25% more by the overflow: hidden
rule applied to the select
itself.
The custom arrow icon-font is placed in the pseudo class :before
where the rule content
contains the reference for the arrow (in this case it is a right parenthesis).
We also place this arrow in an absolute position to center it as much as possible (if you use different icon fonts, remember to adjust them opportunely by changing top and left values and the font size).
.ie8 .prefix-icon-arrow-down-fill:before,
.ie9 .prefix-icon-arrow-down-fill:before {
content: ")";
position: absolute;
top: 43%;
left: 93%;
font-size: 6px;
...
}
You can easily create and substitute the background arrow or the icon font arrow, with every one that you want simply changing it in the background-image
rule or making a new icon font file by yourself.
Here is the code for any number :
import java.math.BigInteger;
public class Testing {
/**
* @param args
*/
static String arr[] ={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
public static void main(String[] args) {
String value = "214";
System.out.println(value + " : " + getHex(value));
}
public static String getHex(String value) {
String output= "";
try {
Integer.parseInt(value);
Integer number = new Integer(value);
while(number >= 16){
output = arr[number%16] + output;
number = number/16;
}
output = arr[number]+output;
} catch (Exception e) {
BigInteger number = null;
try{
number = new BigInteger(value);
}catch (Exception e1) {
return "Not a valid numebr";
}
BigInteger hex = new BigInteger("16");
BigInteger[] val = {};
while(number.compareTo(hex) == 1 || number.compareTo(hex) == 0){
val = number.divideAndRemainder(hex);
output = arr[val[1].intValue()] + output;
number = val[0];
}
output = arr[number.intValue()] + output;
}
return output;
}
}
If you use echo inside an if with other commands, like "read", it might ignore the setting and it will jump to a new line anyway.
Just use Control.Invoke Method or Control.BeginInvoke Method.
Great example: How to: Make Thread-Safe Calls to Windows Forms Controls.
$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
'method' => 'POST',
'content' => 'username=admin195&password=d123456789'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if($response === false) {
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
Application pools are used to separate sets of IIS worker processes that share the same configuration and application boundaries.
Application pools used to isolate our web application for better security, reliability, and availability and performance and keep running without impacting each other . The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. One Application Pool can have multiple worker process Also.
Or we can simply say that, An application pool is a group of one or more URLs that are served by a worker process or set of worker processes. Any Web directory or virtual directory can be assigned to an application pool. So that one website cannot be affected by other, if u used separated application pool.
Source : Interviewwiz
For me, this was solved by reverting the commit I had pushed, then cherry-picking that commit to the other branch.
git checkout branch_that_had_the_commit_originally
git revert COMMIT-HASH
git checkout branch_that_was_supposed_to_have_the_commit
git cherry pick COMMIT-HASH
You can use git log
to find the correct hash, and you can push these changes whenever you like!
After uncommenting disable_overscan=1 follow my lead. In the link, http://elinux.org/RPiconfig when you search for Video options, you'll also get hdmi_group and hdmi_mode. For, hdmi_group choose 1 if you're using you TV as an video output or choose 2 for monitors. Then in hdmi_mode, you can select the resolution you want from the list. I chose :- hdmi_group=2 hdmi_mode=23 And it worked.
Make sure your compiler is set to x86 if you are trying to reference an x86 dll...
I was having similar issues... as mentioned above, trying to use OLEDB to access an Excel file from my C# code in Visual Studio 2012.
I kept getting errors about the Access library not being accessible but I knew that I had loaded it.
During Debug, it dawned on me that I am compiling for 64 bit but have Office x86 loaded. Even though I loaded the Access library for 32 bit, it was never being used by the app... and was, therefore, not accessible.
Here is what I was using in C#:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strFilePath + ";Extended Properties='Excel 12.0 Xml;HDR=Yes'";
...I was getting an error
As soon as I switched the compiler to x86 it worked
If you are just getting started with a new project then I would suggest that you use PDO instead of the old odbc_exec()
approach. Here is a simple example:
<?php
$bits = 8 * PHP_INT_SIZE;
echo "(Info: This script is running as $bits-bit.)\r\n\r\n";
$connStr =
'odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .
'Dbq=C:\\Users\\Gord\\Desktop\\foo.accdb;';
$dbh = new PDO($connStr);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql =
"SELECT AgentName FROM Agents " .
"WHERE ID < ? AND AgentName <> ?";
$sth = $dbh->prepare($sql);
// query parameter value(s)
$params = array(
5,
'Homer'
);
$sth->execute($params);
while ($row = $sth->fetch()) {
echo $row['AgentName'] . "\r\n";
}
NOTE: The above approach is sufficient if you do not need to support Unicode characters above U+00FF
. If you do need to support such characters then neither PDO_ODBC
nor the old odbc_
functions will work; you'll need to use the solution described in this answer.
ALTER TABLE `0_ms_labdip_details` DROP INDEX column_tcx
Run this code in phpmyadmin and remove unique of column
I found a very good jquery plugin that can ease your life with this type of operation. You can checkout https://github.com/ocombe/jQuery-keepAlive.
$.fn.keepAlive({url: 'your-route/filename', timer: 'time'}, function(response) {
console.log(response);
});//
Simply put, you need to rewrite all of your database connections and queries.
You are using mysql_*
functions which are now deprecated and will be removed from PHP in the future. So you need to start using MySQLi or PDO instead, just as the error notice warned you.
A basic example of using PDO (without error handling):
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();
?>
A basic example of using MySQLi (without error handling):
$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$result = $db->query("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
Here's a handy little PDO tutorial to get you started. There are plenty of others, and ones about the PDO alternative, MySQLi.
echo You must invoke st from within branch directory
SvnUrl=`svn info | grep URL | sed 's/URL: //'`
SvnVer=`svn info | grep Revision | sed 's/Revision: //'`
svn diff -r $SvnVer --summarize $SvnUrl
You can use format strings as well.
string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros
or some shortcuts if the format works for you
string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();
Either should work.
Check the contents of SpringExample/target/classes. Is spring-config.xml there? If not, try manually removing the SpringExample/target/ directory, and force a rebuild with Project=>Clean... in Eclipse.
Similar to several answers like Alex V's and NDavis, but none of them are quite the same.
When already in the branch in question
Using:
git diff master...
Which combines several features:
Update:
This should probably be git diff master
, but also this shows the diff, not the commits as the question specified.
Extending on @isaac-pak's answer, if you want to pass the default value to your component in a prop, you can save it in state in the componentDidMount() lifecycle method to ensure the default is selected the first time.
Note, I've updated the following code to make it more complete and to use an empty string as the initial value per the comment.
export default class MySelect extends Component {
constructor(props) {
super(props);
this.state = {
selectedValue: '',
};
this.handleChange = this.handleChange.bind(this);
this.options = [
{value: 'foo', label: 'Foo'},
{value: 'bar', label: 'Bar'},
{value: 'baz', label: 'Baz'}
];
}
componentDidMount() {
this.setState({
selectedValue: this.props.defaultValue,
})
}
handleChange(selectedOption) {
this.setState({selectedValue: selectedOption.target.value});
}
render() {
return (
<Select
value={this.options.filter(({value}) => value === this.state.selectedValue)}
onChange={this.handleChange}
options={this.options}
/>
)
}
}
MySelect.propTypes = {
defaultValue: PropTypes.string.isRequired
};
Is simple:
Example:https://jsfiddle.net/RainStudios/mw786v1w/
var element = document.getElementById('element');
//create box in bottom-left
var resizer = document.createElement('div');
resizer.style.width = '10px';
resizer.style.height = '10px';
resizer.style.background = 'red';
resizer.style.position = 'absolute';
resizer.style.right = 0;
resizer.style.bottom = 0;
resizer.style.cursor = 'se-resize';
//Append Child to Element
element.appendChild(resizer);
//box function onmousemove
resizer.addEventListener('mousedown', initResize, false);
//Window funtion mousemove & mouseup
function initResize(e) {
window.addEventListener('mousemove', Resize, false);
window.addEventListener('mouseup', stopResize, false);
}
//resize the element
function Resize(e) {
element.style.width = (e.clientX - element.offsetLeft) + 'px';
element.style.height = (e.clientY - element.offsetTop) + 'px';
}
//on mouseup remove windows functions mousemove & mouseup
function stopResize(e) {
window.removeEventListener('mousemove', Resize, false);
window.removeEventListener('mouseup', stopResize, false);
}
input[type=text]
or, to restrict to text inputs inside forms
form input[type=text]
or, to restrict further to a certain form, assuming it has id myForm
#myForm input[type=text]
Notice: This is not supported by IE6, so if you want to develop for IE6 either use IE7.js (as Yi Jiang suggested) or start adding classes to all your text inputs.
Reference: http://www.w3.org/TR/CSS2/selector.html#attribute-selectors
Because it is specified that default attribute values may not always be selectable with attribute selectors, one could try to cover other cases of markup for which text inputs are rendered:
input:not([type]), // type attribute not present in markup
input[type=""], // type attribute present, but empty
input[type=text] // type is explicitly defined as 'text'
Still this leaves the case when the type is defined, but has an invalid value and that still falls back to type="text". To cover that we could use select all inputs that are not one of the other known types
input:not([type=button]):not([type=password]):not([type=submit])...
But this selector would be quite ridiculous and also the list of possible types is growing with new features being added to HTML.
Notice: the :not
pseudo-class is only supported starting with IE9.
Suppose your existing reporting query is
Select EmployeeId,EmployeeName
from Employee
Where EmployeeId>101 order by EmployeeName
and you have to save this data into temparory table then you query goes to
Select EmployeeId,EmployeeName
into #MyTempTable
from Employee
Where EmployeeId>101 order by EmployeeName
[EDIT]
This answer has been edited. I'm leaving the original answer below for context (otherwise the comments wouldn't make sense).
When this question was originally asked, JSLint was the main linting tool for JavaScript. JSHint was a new fork of JSLint, but had not yet diverged much from the original.
Since then, JSLint has remained pretty much static, while JSHint has changed a great deal - it has thrown away many of JSLint's more antagonistic rules, has added a whole load of new rules, and has generally become more flexible. Also, another tool ESLint is now available, which is even more flexible and has more rule options.
In my original answer, I said that you should not force yourself to stick to JSLint's rules; as long as you understood why it was throwing a warning, you could make a judgement for yourself about whether to change the code to resolve the warning or not.
With the ultra-strict ruleset of JSLint from 2011, this was reasonable advice -- I've seen very few JavaScript codesets that could pass a JSLint test. However with the more pragmatic rules available in today's JSHint and ESLint tools, it is a much more realistic proposition to try to get your code passing through them with zero warnings.
There may still occasionally be cases where a linter will complain about something that you've done intentionally -- for example, you know that you should always use ===
but just this one time you have a good reason to use ==
. But even then, with ESLint you have the option to specify eslint-disable
around the line in question so you can still have a passing lint test with zero warnings, with the rest of your code obeying the rule. (just don't do that kind of thing too often!)
[ORIGINAL ANSWER FOLLOWS]
By all means use JSLint. But don't get hung up on the results and on fixing everything that it warns about. It will help you improve your code, and it will help you find potential bugs, but not everything that JSLint complains about turns out to be a real problem, so don't feel like you have to complete the process with zero warnings.
Pretty much any Javascript code with any significant length or complexity will produce warnings in JSLint, no matter how well written it is. If you don't believe me, try running some popular libraries like JQuery through it.
Some JSLint warnings are more valuable than others: learn which ones to watch out for, and which ones are less important. Every warning should be considered, but don't feel obliged to fix your code to clear any given warning; it's perfectly okay to look at the code and decide you're happy with it; there are times when things that JSlint doesn't like are actually the right thing to do.
Annoyingly Javascript's date.getSeconds()
et al will not pad the result with zeros 11:0:0
instead of 11:00:00
.
So I like to use
date.toLocaleTimestring()
Which renders 11:00:00 AM
. Just beware when using the extra options, some browsers don't support them (Safari)
Had a similar question and had difficulty finding an answer. The following function allows you to paste an image with a transparency parameter over another image at a specific offset.
import Image
def trans_paste(fg_img,bg_img,alpha=1.0,box=(0,0)):
fg_img_trans = Image.new("RGBA",fg_img.size)
fg_img_trans = Image.blend(fg_img_trans,fg_img,alpha)
bg_img.paste(fg_img_trans,box,fg_img_trans)
return bg_img
bg_img = Image.open("bg.png")
fg_img = Image.open("fg.png")
p = trans_paste(fg_img,bg_img,.7,(250,100))
p.show()
getCurrentItem()
, doesn't actually give the right position for the first and the last page I fixed it adding this code:
public void CalcPostion() {
current = viewPager.getCurrentItem();
if ((last == current) && (current != 1) && (current != 0)) {
current = current + 1;
viewPager.setCurrentItem(current);
}
if ((last == 1) && (current == 1)) {
last = 0;
current = 0;
}
display();
last = current;
}
I've used encodeURIComponent() and decodeURIComponent() too.
defined?(your_var)
will work. Depending on what you're doing you can also do something like your_var.nil?
You can return
only if !something2
or use else return
:
public void Method()
{
if(something)
{
//some code
if(something2)
{
//now I should break from ifs and go to te code outside ifs
}
if(!something2) // or else
return;
}
// The code i want to go if the second if is true
}
According to the PHP manual, data passed to cURL as a string should be URLencoded. See the page for curl_setopt() and search for CURLOPT_POSTFIELDS
.
One line solution
var id = request.Headers.GetValues("MyCustomID").FirstOrDefault();
First, what you are looking for is a column or bar diagram, not really a histogram. A histogram is made from a frequency distribution of a continuous variable that is separated into bins. Here you have a column against separate labels.
To make a bar diagram with matplotlib, use the matplotlib.pyplot.bar()
method. Have a look at this page of the matplotlib documentation that explains very well with examples and source code how to do it.
If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better. If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'. The following is the plot of your data in Excel:
I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.
No, there's no way to do it, since what would happen when you called Object::GetTypeInformation()
? It can't know which derived class version to call since there's no object associated with it.
You'll have to make it a non-static virtual function to work properly; if you also want to be able to call a specific derived class's version non-virtually without an object instance, you'll have to provide a second redunduant static non-virtual version as well.
Since you mention you have a proxy connection I will tell you what worked for me: I went to properties (as friedrich mentioned) ensuring the Offline Work was unchecked. I opened up the gradle.properties file in the IDE and added my proxy settings. Here's a generic version:
systemProp.http.proxyHost=www.somehost.org
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost
Then at the top of the properties file in the IDE there was a "Try Again" link which I clicked. That did it.
Try https://github.com/voidcosmos/npkill
npx npkill
it will find all node_modules and let you remove them.
sometimes you need to check the rightfulness of the IP, firewall, port forwarding, etc, if your target database is in other machines.
I can't think about an easier way to efficiently remove all diacritics from a string than using this amazing solution.
See it in action:
var string = "öäüÖÄÜ";_x000D_
_x000D_
var string_norm = string.normalize('NFD').replace(/[\u0300-\u036f]/g, '');_x000D_
console.log(string_norm);
_x000D_
NVL will do an implicit conversion to the datatype of the first parameter, so the following does not error
select nvl('a',sysdate) from dual;
COALESCE expects consistent datatypes.
select coalesce('a',sysdate) from dual;
will throw a 'inconsistent datatype error'
just set -config
parameter location correctly, i.e :
openssl .................... -config C:\bin\apache\apache2.4.9\conf\openssl.cnf
Miss Clone: I get a fresh copy to local.
Mr Pull: I already have it locally, I just update it.
Miss Clone: I can do what you do! You are just my subset.
Mr Pull: Ditto!
Miss Clone: No, you don't create. This is what I do:
You only do #3, and then you merge, which I do not need to do(mine is fresh).
Mr Pull: Smarty pants, no big deal, I will do a "git init" first! Then we are the same.
Miss Clone: No dear, don't you need a 'checked-out branch'... the git checkout
? Who will do it? me!
Mr Pull: Oh right, that is needed. I need a default branch to act on. But..but I have the extra 'merge' capability on existing repo! Which makes me the most used command in Git ;)
Git creators: Hold your horses Mr Pull, if --bare or --mirror is used with clone or init, your merge won't happen. It remains read-only. And for you Miss Clone, git checkout
can be replaced with a git fetch <remote> <srcBranch>:<destBranch>
unless you want to use a -s <strategy>
with pull which is missing in fetch.
Miss Clone: Somehow I feel like a winner already but let me drop this too: my command applies to all the branches in the repository. Are you that broad minded Mr. Pull?
Mr. Pull: I am broad minded when it comes to fetching all the branch names from the repo. But the merge will happen only on the current checked out branch. Exclusivity is the name! And in your case too, you only check-out one branch.
@kajetons' answer is fully functional.
You can also pass multiple variables by passing them like: use($var1, $var2)
DB::table('users')->where(function ($query) use ($activated,$var2) {
$query->where('activated', '=', $activated);
$query->where('var2', '>', $var2);
})->get();
Here is a generic wrapper which can be used to convert a binary function to multi-parameters function. The benefit of this solution is that it is very generic and can be applied to any binary functions. You just need to do it once and then you can apply it any where.
To demo the idea, I use simple recursion to implement. It can be of course implemented with more elegant way that benefits from R's good support for functional paradigm.
fold_left <- function(f) {
return(function(...) {
args <- list(...)
return(function(...){
iter <- function(result,rest) {
if (length(rest) == 0) {
return(result)
} else {
return(iter(f(result, rest[[1]], ...), rest[-1]))
}
}
return(iter(args[[1]], args[-1]))
})
})}
Then you can simply wrap any binary functions with it and call with positional parameters (usually data.frames) in the first parentheses and named parameters in the second parentheses (such as by =
or suffix =
). If no named parameters, leave second parentheses empty.
merge_all <- fold_left(merge)
merge_all(df1, df2, df3, df4, df5)(by.x = c("var1", "var2"), by.y = c("var1", "var2"))
left_join_all <- fold_left(left_join)
left_join_all(df1, df2, df3, df4, df5)(c("var1", "var2"))
left_join_all(df1, df2, df3, df4, df5)()
A method that doesn't need a LayoutListener
In my case, I would like to save the state of the keyboard before replacing my Fragment. I call the method hideSoftInputFromWindow from onSaveInstanceState
, which closes the keyboard and returns me whether the keyboard was visible or not.
This method is straightforward but may change the state of your keyboard.
There are many possible ways to cause a docker to exit immediately. For me, it was the problem with my Dockerfile
. There was a bug in that file. I had ENTRYPOINT ["dotnet", "M4Movie_Api.dll]
instead of ENTRYPOINT ["dotnet", "M4Movie_Api.dll"]
. As you can see I had missed one quotation(") at the end.
To analyze the problem I started my container and quickly attached my container so that I could see what was the exact problem.
C:\SVenu\M4Movie\Api\Api>docker start 4ea373efa21b
C:\SVenu\M4Movie\Api\Api>docker attach 4ea373efa21b
Where 4ea373efa21b is my container id. This drives me to the actual issue.
After finding the issue, I had to build, restore, publish my container again.
Semicolon (";") is only needed for separation of statements within a same block, such as if we have the following C code:
if(a>b)
{
largest=a; //here largest and count are integer variables
count+=1;
}
It can be written in Python in either of the two forms:
if a>b:
largest=a
count=count+1
Or
if a>b: largest=a;count=count+1
In the above example you could have any number of statements within an if
block and can be separated by ";" instead.
Hope that nothing is as simple as above explanation.
Check the Debug
class. http://developer.android.com/reference/android/os/Debug.html
i.e. Debug.getNativeHeapAllocatedSize()
It has methods to get the used native heap, which is i.e. used by external bitmaps in your app. For the heap that the app is using internally, you can see that in the DDMS tool that comes with the Android SDK and is also available via Eclipse.
The native heap + the heap as indicated in the DDMS make up the total heap that your app is allocating.
For CPU usage I'm not sure if there's anything available via API/SDK.
You can add atom beauty package for formatting text in atom..
file --> setting --> Install
then you type atom-beautify in search area.
then click Package button.. select atom beuty and install it.
next you can format your text using (Alt + ctrl + b) or right click and select beautify editor contents
Its best practice to have TOP 1 1
always.
What if I use SELECT 1
-> If condition matches more than one record then your query will fetch all the columns records and returns 1.
What if I use SELECT TOP 1 1
-> If condition matches more than one record also, it will just fetch the existence of any row (with a self 1-valued column) and returns 1.
IF EXISTS (SELECT TOP 1 1 FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx')
BEGIN
SELECT 1
END
ELSE
BEGIN
SELECT 2
END
The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:
Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();
This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.
If you do not want to use the Array function.
public class GArray
{
int[] mainArray;
int index;
int i = 0;
public GArray()
{
index = 0;
mainArray = new int[4];
}
public void add(int addValue)
{
if (index == mainArray.Length)
{
int newSize = index * 2;
int[] temp = new int[newSize];
for (int i = 0; i < mainArray.Length; i++)
{
temp[i] = mainArray[i];
}
mainArray = temp;
}
mainArray[index] = addValue;
index++;
}
public void print()
{
for (int i = 0; i < index; i++)
{
Console.WriteLine(mainArray[i]);
}
}
}
class Program
{
static void Main(string[] args)
{
GArray myArray = new GArray();
myArray.add(1);
myArray.add(2);
myArray.add(3);
myArray.add(4);
myArray.add(5);
myArray.add(6);
myArray.print();
Console.ReadKey();
}
}
X-Frame-Options
is deprecated. From MDN:
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
The modern alternative is the Content-Security-Policy
header, which along many other policies can white-list what URLs are allowed to host your page in a frame, using the frame-ancestors
directive.
frame-ancestors
supports multiple domains and even wildcards, for example:
Content-Security-Policy: frame-ancestors 'self' example.com *.example.net ;
Unfortunately, for now, Internet Explorer does not fully support Content-Security-Policy.
UPDATE: MDN has removed their deprecation comment. Here's a similar comment from W3C's Content Security Policy Level
The
frame-ancestors
directive obsoletes theX-Frame-Options
header. If a resource has both policies, theframe-ancestors
policy SHOULD be enforced and theX-Frame-Options
policy SHOULD be ignored.
1- You need to save scroll position like this
rvProduct.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
recyclerViewState = rvProduct.getLayoutManager().onSaveInstanceState(); // save recycleView state
}
});
2- And after you call notifyDataSetChanged then onRestoreInstanceState like this example
productsByBrandAdapter.addData(productCompareList);
productsByBrandAdapter.notifyDataSetChanged();
rvProduct.getLayoutManager().onRestoreInstanceState(recyclerViewState); // restore recycleView state
I've just found this solution:
if(@getimagesize($remoteImageURL)){
//image exists!
}else{
//image does not exist.
}
Source: http://www.dreamincode.net/forums/topic/11197-checking-if-file-exists-on-remote-server/
The issue with the "one thread per request" model for a server is that they don't scale well for several scenarios compared to the event loop thread model.
Typically, in I/O intensive scenarios the requests spend most of the time waiting for I/O to complete. During this time, in the "one thread per request" model, the resources linked to the thread (such as memory) are unused and memory is the limiting factor. In the event loop model, the loop thread selects the next event (I/O finished) to handle. So the thread is always busy (if you program it correctly of course).
The event loop model as all new things seems shiny and the solution for all issues but which model to use will depend on the scenario you need to tackle. If you have an intensive I/O scenario (like a proxy), the event base model will rule, whereas a CPU intensive scenario with a low number of concurrent processes will work best with the thread-based model.
In the real world most of the scenarios will be a bit in the middle. You will need to balance the real need for scalability with the development complexity to find the correct architecture (e.g. have an event base front-end that delegates to the backend for the CPU intensive tasks. The front end will use little resources waiting for the task result.) As with any distributed system it requires some effort to make it work.
If you are looking for the silver bullet that will fit with any scenario without any effort, you will end up with a bullet in your foot.
It works for me when I define the complete border
property. (JSFiddle here)
.field_set{
border: 1px #F00 solid;
}?
the reason is the border-style
that is set to none
by default for fieldsets. You need to override that as well.
Addition to Alex' answer:
$(function() {
$('input[type="submit"]').prop('disabled', true);
$('#check').on('input', function(e) {
if(this.value.length === 6) {
$('input[type="submit"]').prop('disabled', false);
} else {
$('input[type="submit"]').prop('disabled', true);
}
});
});
<input type="text" maxlength="6" id="check" data-minlength="6" /><br />
<input type="submit" value="send" />
But: You should always remember to validate the user input on the server side again. The user could modify the local HTML or disable JavaScript.
If you're a FP (functional programming) fan, Ramda has a neat helper function for this called defaultTo :
usage:
const result = defaultTo(30)(value)
It's more useful when dealing with undefined
boolean values:
const result2 = defaultTo(false)(dashboard.someValue)
You should use POST for partial updates.
To update fields for customer 123, make a POST to /customer/123.
If you want to update just the status, you could also PUT to /customer/123/status.
Generally, GET requests should not have any side effects, and PUT is for writing/replacing the entire resource.
This follows directly from HTTP, as seen here: http://en.wikipedia.org/wiki/HTTP_PUT#Request_methods
Use a cast:
public enum MyEnum : int {
A = 0,
B = 1,
AB = 2,
}
int val = (int)MyEnum.A;
@robert-hurst has a cleaner approach.
However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.
// select canvas elements
var sourceCanvas = document.getElementById("some-unique-id");
var destCanvas = document.getElementsByClassName("some-class-selector")[0];
//copy canvas by DataUrl
var sourceImageData = sourceCanvas.toDataURL("image/png");
var destCanvasContext = destCanvas.getContext('2d');
var destinationImage = new Image;
destinationImage.onload = function(){
destCanvasContext.drawImage(destinationImage,0,0);
};
destinationImage.src = sourceImageData;
sudo ln -sf /usr/lib/...."adapt-it"..../qt5/plugins/platforms/ /usr/bin/
It creates the symbolic link it's missed. Good for QT ! Good for VLC !!
CSS3 has a nice little attribute called background-size:cover
.
This scales the image so that the background area is completely covered by the background image while maintaining the aspect ratio. The entire area will be covered. However, part of the image may not be visible if the width/height of the resized image is too great.
You can use the Search & Replace feature with this regex ^([\w\d\_\.\s\-]*)$
to find text and the replaced text is "$1"
.
$before = microtime(true);
$n = 1000;
$numbers = range(1,$n);
$cube_numbers = array_map('cube',$numbers);
function cube($n){
$msg ='even';
if($n%2 !=0){
$msg = 'odd';
}
return "The Number is $n is ".$msg;
}
foreach($cube_numbers as $cube){
echo $cube . "<br/>";
}
$after = microtime(true);
echo $after-$before. 'seconds';
Unless you are doing a DB to track historical times more than a century ago, using
Modified datetime DEFAULT ((0))
is perfectly safe and sound and allows more elegant queries than '1753-01-01' and more efficient queries than NULL
.
However, since first Modified datetime
is the time at which the record was inserted, you can use:
Modified datetime NOT NULL DEFAULT (GETUTCDATE())
which avoids the whole issue and makes your inserts easier and safer - as in you don't insert it at all and SQL does the housework :-)
With that in place you can still have elegant and fast queries by using 0 as a practical minimum since it's guranteed to always be lower than any insert-generated GETUTCDATE()
.
The easiest way to do this, is to install a JDK and tell Eclipse to use it as the default JRE. Use the default install.
(from memory)
Open Window -> Prefences. Select Installed Java runtimes, and choose Add. Navigate to root of your JDK (\Programs...\Java) and click Ok. Then select it to be the default JRE (checkmark).
After a workspace rebuild, you should have source attached to all JRE classes.
With PostgreSQL there are a number of date/time functions available, see here.
In your example, you could use:
SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';
If you are running this query regularly, it is possible to create an index using the date_trunc
function as well:
CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );
One advantage of this is there is some more flexibility with timezones if required, for example:
CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';
Web Sockets - It is a protocol which provides a full-duplex communication channel over a single TCP connection.
For instance a two-way communication between the Server and Browser
Since the protocol is more complicated, the server and the browser has to rely on library of websocket
which is socket.io
Example - Online chat application.
SSE(Server-Sent Event) -
In case of server sent event the communication is carried out from server to browser only and browser cannot send any data to the server. This kind of communication is mainly used
when the need is only to show the updated data, then the server sends the message whenever the data gets updated.
For instance a one-way communication between the Server to Browser.
This protocol is less complicated, so no need to rely on the external library JAVASCRIPT itself provides the EventSource
interface to receive the server sent messages.
Example - Online stock quotes or cricket score website.
This rule
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o
is wrong. It says to create a file named producer.o (with -o producer.o
), but you want to create a file named main
. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o
As Shahbaz rightly points out, the gmake professionals would also use $^
which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ $^
If you're using a std::string
, call length()
:
std::string str = "hello";
std::cout << str << ":" << str.length();
// Outputs "hello:5"
If you're using a c-string, call strlen()
.
const char *str = "hello";
std::cout << str << ":" << strlen(str);
// Outputs "hello:5"
Or, if you happen to like using Pascal-style strings (or f***** strings as Joel Spolsky likes to call them when they have a trailing NULL), just dereference the first character.
const char *str = "\005hello";
std::cout << str + 1 << ":" << *str;
// Outputs "hello:5"
For Android development targeting API < 19, Vitalii Fedorenko one-to-one relationship solution doesn't work because Objects.equals
isn't implemented. Here's a simple alternative:
public <K, V> K getKeyByValue(Map<K, V> map, V value) {
for (Map.Entry<K, V> entry : map.entrySet()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
Using only CSS it is not possible at all to add links :) It is not possible to link a background-image, nor a part of it, using HTML/CSS. However, it can be staged using this method:
<div class="wrapWithBackgroundImage">
<a href="#" class="invisibleLink"></a>
</div>
.wrapWithBackgroundImage {
background-image: url(...);
}
.invisibleLink {
display: block;
left: 55px; top: 55px;
position: absolute;
height: 55px width: 55px;
}
Also, while installing Visual Studio 2013, ensure that you have checked "Web Developer Tools"
I have been using:
<a href=".">link</a>
Have yet to find a case and/or browser where it does not work as intended.
Period means the current path. You can also use ..
to refer to the folder above the current path, for instance, if you have this file structure:
page1.html
folder1
page2.html
You can then in page2.html
write:
<a href="../page1.html">link to page 1</a>
EDIT:
I'm not sure if the behaviour has changed or if it was always like this, but Chrome (and maybe others) will treat periods as described above as regarding directories, not files. This means that if you are at http://example.com/foo/bar.html
you are really in the directory /foo/
and a href
value of .
in bar.html
will refer to /foo/
rather than bar.html
Think of it as navigating the file system in a terminal; you can never cd
into a file :)
EDIT 2:
It seems like the behaviour of using href="."
is not as predictable anymore, both Firefox and Chrome might have changed how they handle these. I wouldn't rely entirely on my original answer, but rather try both the empty string and the period in different browsers for your specific use and make sure you get the desired behaviour.
There are two options here. First, you can store the path unquoted and just quote it later:
set MyPath=C:\Program Files\Foo
"%MyPath%\foo with spaces.exe" something
Another option you could use is a subroutine which alles for un-quoting strings (but in this case it's actually not a very good idea since you're adding quotes, stripping them away and re-adding them again without benefit):
set MyPath="C:\Program Files\Foo"
call :foo %MyPath%
goto :eof
:foo
"%~1\foo.exe"
goto :eof
The %~1
removes quotation marks around the argument. This comes in handy when passing folder names around quoted but, as said before, in this particular case it's not the best idea :-)
This won't work if the data is not sequential (1 2 3 4 but 5 7 3 1 5) as in that case you can't sort it.
Here is how I solve that issue for me:
Column A initial data that needs to contain 5 rows between each number - 5 4 6 8 9
Column B - 1 2 3 4 5 (final number represents the number of empty rows that you need to be between numbers in column A) copy-paste 1-5 in column B as long as you have numbers in column A.
Jump to D column, in D1 type 1. In D2 type this formula - =IF(B2=1,1+D1,D1)
Drag it to the same length as column B.
Back to Column C - at C1 cell type this formula - =IF(B1=1,INDIRECT("a"&(D1)),"")
. Drag it down and we done. Now in column C we have same sequence of numbers as in column A distributed separately by 4 rows.
Use a "Here-String" and cast to XML.
[xml]$myxml = @"
<stuff>
<item name="Joe" age="32">
<info>something about him</info>
</item>
<item name="Sue" age="29">
<info>something about her</info>
</item>
<item name="Cat" age="12">
<info>something else</info>
</item>
</stuff>
"@
[array]$myitems = $myxml.stuff.Item
$myitems
just delete the settings.xml and try againn to setup smartgitHg
You should capitalize names of your classes. After doing that do this in your school class,
Classroom cls = new Classroom();
cls.setTeacherName(newTeacherName);
Also I'd recommend you use some kind of IDE such as eclipse, which can help you with your code for instance generate getters and setters for you. Ex: right click Source -> Generate getters and setters
You can convert both the values to lower case and compare.
Here is an example:
If LCase(Range("J6").Value) = LCase("Tawi") Then
Range("J6").Value = "Tawi-Tawi"
End If
- Where does
user.id
go afterpassport.serializeUser
has been called?
The user id (you provide as the second argument of the done
function) is saved in the session and is later used to retrieve the whole object via the deserializeUser
function.
serializeUser
determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}
. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}
- We are calling
passport.deserializeUser
right after it where does it fit in the workflow?
The first argument of deserializeUser
corresponds to the key of the user object that was given to the done
function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc).
In deserializeUser
that key is matched with the in memory array / database or any data resource.
The fetched object is attached to the request object as req.user
Visual Flow
passport.serializeUser(function(user, done) {
done(null, user.id);
}); ¦
¦
¦
+--------------------? saved to session
¦ req.session.passport.user = {id: '..'}
¦
?
passport.deserializeUser(function(id, done) {
+---------------+
¦
?
User.findById(id, function(err, user) {
done(err, user);
}); +--------------? user object attaches to the request as req.user
});
I tried about three different ways of intercepting the construction of the Ajax object:
xhrFields
, but that only allows for one listener, only attaches to download (not upload) progress, and requires what seems like unnecessary copy-and-paste. progress
function to the returned promise, but I had to maintain my own array of handlers. I could not find a good object to attach the handlers because one place I'd access to the XHR and another I'd have access to the jQuery XHR, but I never had access to the deferred object (only its promise). ajax
with my own. The only potential shortcoming is you can no longer use your own xhr()
setting. You can allow for that by checking to see whether options.xhr
is a function.I actually call my promise.progress
function xhrProgress
so I can easily find it later. You might want to name it something else to separate your upload and download listeners. I hope this helps someone even if the original poster already got what he needed.
(function extend_jQuery_ajax_with_progress( window, jQuery, undefined )
{
var $originalAjax = jQuery.ajax;
jQuery.ajax = function( url, options )
{
if( typeof( url ) === 'object' )
{options = url;url = undefined;}
options = options || {};
// Instantiate our own.
var xmlHttpReq = $.ajaxSettings.xhr();
// Make it use our own.
options.xhr = function()
{return( xmlHttpReq );};
var $newDeferred = $.Deferred();
var $oldPromise = $originalAjax( url, options )
.done( function done_wrapper( response, text_status, jqXHR )
{return( $newDeferred.resolveWith( this, arguments ));})
.fail( function fail_wrapper( jqXHR, text_status, error )
{return( $newDeferred.rejectWith( this, arguments ));})
.progress( function progress_wrapper()
{
window.console.warn( "Whoa, jQuery started actually using deferred progress to report Ajax progress!" );
return( $newDeferred.notifyWith( this, arguments ));
});
var $newPromise = $newDeferred.promise();
// Extend our own.
$newPromise.progress = function( handler )
{
xmlHttpReq.addEventListener( 'progress', function download_progress( evt )
{
//window.console.debug( "download_progress", evt );
handler.apply( this, [evt]);
}, false );
xmlHttpReq.upload.addEventListener( 'progress', function upload_progress( evt )
{
//window.console.debug( "upload_progress", evt );
handler.apply( this, [evt]);
}, false );
return( this );
};
return( $newPromise );
};
})( window, jQuery );
Use this instead:
$('#save').click(function () {
$('#mytable').find('input[type="checkbox"]:checked') //...
});
Let me explain you what the selector does:
input[type="checkbox"]
means that this will match each <input />
with type attribute type
equals to checkbox
After that: :checked
will match all checked checkboxes.
You can loop over these checkboxes with:
$('#save').click(function () {
$('#mytable').find('input[type="checkbox"]:checked').each(function () {
//this is the current checkbox
});
});
Here is demo in JSFiddle.
And here is a demo which solves exactly your problem http://jsfiddle.net/DuE8K/1/.
$('#save').click(function () {
$('#mytable').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked') &&
row.find('textarea').val().length <= 0) {
alert('You must fill the text area!');
}
});
});
You can create an extension function similar to java.util.Random.nextInt(int)
but one that takes an IntRange
instead of an Int
for its bound:
fun Random.nextInt(range: IntRange): Int {
return range.start + nextInt(range.last - range.start)
}
You can now use this with any Random
instance:
val random = Random()
println(random.nextInt(5..9)) // prints 5, 6, 7, 8, or 9
If you don't want to have to manage your own Random
instance then you can define a convenience method using, for example, ThreadLocalRandom.current()
:
fun rand(range: IntRange): Int {
return ThreadLocalRandom.current().nextInt(range)
}
Now you can get a random integer as you would in Ruby without having to first declare a Random
instance yourself:
rand(5..9) // returns 5, 6, 7, 8, or 9
I had similar experience and it took me time to solve the problem. Though, my own case was ASP.Net MVC Core
and Core
framework. Setting Trusted_Connection=False;
solved my problem.
Inside appsettings.json
file
"ConnectionStrings": {
"DefaultConnection": "Server=servername; Database=databasename; User Id=userid; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true",
},
ALTER TABLE foobar_data MODIFY COLUMN col VARCHAR(255) NOT NULL DEFAULT '{}';
A second possibility which does the same (thanks to juergen_d):
ALTER TABLE foobar_data CHANGE COLUMN col col VARCHAR(255) NOT NULL DEFAULT '{}';
DECLARE @FromDate DATETIME
SET @FromDate = 'Jan 10 2016 12:00AM'
DECLARE @ToDate DATETIME
SET @ToDate = 'Jan 10 2017 12:00AM'
DECLARE @Dynamic_Qry nvarchar(Max) =''
SET @Dynamic_Qry='SELECT
(CONVERT(DATETIME,(SELECT
CASE WHEN ( ''IssueDate'' =''IssueDate'') THEN
EMP_DOCUMENT.ISSUE_DATE
WHEN (''IssueDate'' =''ExpiryDate'' ) THEN
EMP_DOCUMENT.EXPIRY_DATE ELSE EMP_DOCUMENT.APPROVED_ON END
CHEKDATE ), 101)
)FROM CR.EMP_DOCUMENT as EMP_DOCUMENT WHERE 1=1
AND (
CONVERT(DATETIME,(SELECT
CASE WHEN ( ''IssueDate'' =''IssueDate'') THEN
EMP_DOCUMENT.ISSUE_DATE
WHEN (''IssueDate'' =''ExpiryDate'' ) THEN EMP_DOCUMENT.EXPIRY_DATE
ELSE EMP_DOCUMENT.APPROVED_ON END
CHEKDATE ), 101)
) BETWEEN '''+ CONVERT(CHAR(10), @FromDate, 126) +''' AND '''+CONVERT(CHAR(10), @ToDate , 126
)
+'''
'
print @Dynamic_Qry
EXEC(@Dynamic_Qry)
I'm not sure if I'm right, or I'm missing something, but as for now (2016-07-11, running Win7 Enterprise SP1) a LNK file adapts itself on moving or even changing the drive letter after it is run at a new place! I created a new shortcut on my USB drive and tried moving the shortcut and its target in a way that the relative position stayed unchanged, then I changed the drive letter. The shortcut worked in both cases and the target field was adapted after I double-clicked it.
It looks like Microsoft has addressed this issue in one of the past updates.
Please somebody confirm this.
add a inner view to the cell then add your own views to it.
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
The preceding 0 is used to indicate a number in base 2, 8, or 16.
In my opinion, 0x was chosen to indicate hex because 'x' sounds like hex.
Just my opinion, but I think it makes sense.
Good Day!
This Error can occur if the physical machine has run out of memory. In my case i was hosting a site on IIS trying to access the AD, but the server had run out of memory.
If you want more control over the size
that you want to list the directories over, you can use the threshold
(-t
) switch as in:
$ du -ht 1000000000 | sort --reverse
du
- d
isk u
sage
h
- human readable format
t
- threshold size
Here, we want to list all directories which are greater than 1GB in size.
$ du -ht 1G | sort --reverse
Explanation:
Units that are described in wiki follows:
K, M, G, T, P, E, Z, Y (powers of 1024) or
KB, MB, GB, TB, PB, EB, ZB, YB (powers of 1000).
Calling the destructor manually is required if the object was constructed using an overloaded form of operator new()
, except when using the "std::nothrow
" overloads:
T* t0 = new(std::nothrow) T();
delete t0; // OK: std::nothrow overload
void* buffer = malloc(sizeof(T));
T* t1 = new(buffer) T();
t1->~T(); // required: delete t1 would be wrong
free(buffer);
Outside managing memory on a rather low level as above calling destructors explicitly, however, is a sign of bad design. Probably, it is actually not just bad design but outright wrong (yes, using an explicit destructor followed by a copy constructor call in the assignment operator is a bad design and likely to be wrong).
With C++ 2011 there is another reason to use explicit destructor calls: When using generalized unions, it is necessary to explicitly destroy the current object and create a new object using placement new when changing the type of the represented object. Also, when the union is destroyed, it is necessary to explicitly call the destructor of the current object if it requires destruction.
You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The following table shows several examples of using the LIKE keyword and the [ ] wildcard characters.
For your case:
... LIKE '%[_]d'
try:
SELECT * FROM service s WHERE s.service_id = ?;
IF @@ROWCOUNT=0
BEGIN
PRINT 'no rows!'
END
CAUTION:
The begin <code> end while <condition>
is rejected by Ruby's author Matz. Instead he suggests using Kernel#loop
, e.g.
loop do
# some code here
break if <condition>
end
Here's an email exchange in 23 Nov 2005 where Matz states:
|> Don't use it please. I'm regretting this feature, and I'd like to
|> remove it in the future if it's possible.
|
|I'm surprised. What do you regret about it?
Because it's hard for users to tell
begin <code> end while <cond>
works differently from
<code> while <cond>
RosettaCode wiki has a similar story:
During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.
Using SourceTree I was able to do this all from the UI
FILE.ext
to whatever.ext
whatever.ext
to file.ext
It's a bit tedious, but if you only need to do it to a few files it's pretty quick
you have to use rewrite to pass params using proxy_pass here is example I did for angularjs app deployment to s3
S3 Static Website Hosting Route All Paths to Index.html
adopted to your needs would be something like
location /service/ {
rewrite ^\/service\/(.*) /$1 break;
proxy_pass http://apache;
}
if you want to end up in http://127.0.0.1:8080/query/params/
if you want to end up in http://127.0.0.1:8080/service/query/params/ you'll need something like
location /service/ {
rewrite ^\/(.*) /$1 break;
proxy_pass http://apache;
}
Use the built-in function round()
:
>>> round(1.2345,2)
1.23
>>> round(1.5145,2)
1.51
>>> round(1.679,2)
1.68
Or built-in function format()
:
>>> format(1.2345, '.2f')
'1.23'
>>> format(1.679, '.2f')
'1.68'
Or new style string formatting:
>>> "{:.2f}".format(1.2345)
'1.23
>>> "{:.2f}".format(1.679)
'1.68'
Or old style string formatting:
>>> "%.2f" % (1.679)
'1.68'
help on round
:
>>> print round.__doc__
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
Simply ROUND(x/5)*5 should do the job.
It depends. The System.Timers.Timer
has two modes of operation.
If SynchronizingObject
is set to an ISynchronizeInvoke
instance then the Elapsed
event will execute on the thread hosting the synchronizing object. Usually these ISynchronizeInvoke
instances are none other than plain old Control
and Form
instances that we are all familiar with. So in that case the Elapsed
event is invoked on the UI thread and it behaves similar to the System.Windows.Forms.Timer
. Otherwise, it really depends on the specific ISynchronizeInvoke
instance that was used.
If SynchronizingObject
is null then the Elapsed
event is invoked on a ThreadPool
thread and it behaves similar to the System.Threading.Timer
. In fact, it actually uses a System.Threading.Timer
behind the scenes and does the marshaling operation after it receives the timer callback if needed.
Alternatively, you can use evals
from my pander
package to capture output and all warnings, errors and other messages along with the raw results:
> pander::evals("5+5")
[[1]]
$src
[1] "5 + 5"
$result
[1] 10
$output
[1] "[1] 10"
$type
[1] "numeric"
$msg
$msg$messages
NULL
$msg$warnings
NULL
$msg$errors
NULL
$stdout
NULL
attr(,"class")
[1] "evals"
Go to installed updates and just uninstall Internet Explorer 11 Windows update. It works for me.
This answer builds on that of Sourabh, who pointed out an HTML/CSS/JavaScript combo at https://codepen.io/hoanghals/pen/dZrWLZ that did the job. I tried this, and made a complete web page including the CSS and JavaScript, which I tried on my site. As CodePens have a habit of disappearing, I decided to show it here. I'm also showing a simplified stripped-to-essentials version, to demonstrate the minimum that one needs to do.
I must also note one thing. The code at the above link, whose JavaScript Sourabh copies, refers to a JavaScript constructor SuperGif()
. I don't think Sourabh explained that, and neither does the CodePen. An easy search showed that it's defined in buzzfeed /
libgif-js , which can be downloaded from https://github.com/buzzfeed/libgif-js#readme . Look for the control that the red arrow below is pointing at, then click on the green "Code" button. (N.B. You won't see the red arrow: that's me showing you where to look.)
A menu will pop up offering various options including to download a zip file. Download it, and extract it into your HTML directory or a subdirectory thereof.
Next, I'm going to show the two pages that I made. The first is derived from the CodePen. The second is stripped to its essentials, and shows the minimum you need in order to use SuperGif.
So here's the complete HTML, CSS, and JavaScript for the first page. In the head of the HTML is a link to libgif.js , which is the file you need from the zip file. Then, the body of the HTML starts with some text about cat pictures, and follows it with a link to an animated cat GIF at https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif .
It then continues with some CSS. The CodePen uses SCSS, which for anyone who doesn't know, has to be preprocessed into CSS. I've done that, so what's in the code below is genuine CSS.
Finally, there's the JavaScript.
<html>
<head>
<script src="libgif-js-master/libgif.js"></script>
</head>
<body>
<div style="width: 600px; margin: auto; text-align: center; font-family: arial">
<p>
And so, the unwritten law of the internet, that any
experiment involving video/images must involve cats in
one way or another, reared its head again. When would
the internet's fascination with cats come to an end?
Never. The answer is "Never".
</p>
<img src='https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif' class='gif' />
</div>
<style>
img.gif {
visibility: hidden;
}
.jsgif {
position: relative;
}
.gifcontrol {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
cursor: pointer;
transition: background 0.25s ease-in-out;
z-index: 100;
}
.gifcontrol:after {
transition: background 0.25s ease-in-out;
position: absolute;
content: "";
display: block;
left: calc(50% - 25px);
top: calc(50% - 25px);
}
.gifcontrol.loading {
background: rgba(255, 255, 255, 0.75);
}
.gifcontrol.loading:after {
background: #FF9900;
width: 50px;
height: 50px;
border-radius: 50px;
}
.gifcontrol.playing {
/* Only show the 'stop' button on hover */
}
.gifcontrol.playing:after {
opacity: 0;
transition: opacity 0.25s ease-in-out;
border-left: 20px solid #FF9900;
border-right: 20px solid #FF9900;
width: 50px;
height: 50px;
box-sizing: border-box;
}
.gifcontrol.playing:hover:after {
opacity: 1;
}
.gifcontrol.paused {
background: rgba(255, 255, 255, 0.5);
}
.gifcontrol.paused:after {
width: 0;
height: 0;
border-style: solid;
border-width: 25px 0 25px 50px;
border-color: transparent transparent transparent #ff9900;
}
</style>
<script>
var gifElements = document.querySelectorAll('img.gif');
for(var e in gifElements) {
var element = gifElements[e];
if(element.nodeName == 'IMG') {
var supergif = new SuperGif({
gif: element,
progressbar_height: 0,
auto_play: false,
});
var controlElement = document.createElement("div");
controlElement.className = "gifcontrol loading g"+e;
supergif.load((function(controlElement) {
controlElement.className = "gifcontrol paused";
var playing = false;
controlElement.addEventListener("click", function(){
if(playing) {
this.pause();
playing = false;
controlElement.className = "gifcontrol paused";
} else {
this.play();
playing = true;
controlElement.className = "gifcontrol playing";
}
}.bind(this, controlElement));
}.bind(supergif))(controlElement));
var canvas = supergif.get_canvas();
controlElement.style.width = canvas.width+"px";
controlElement.style.height = canvas.height+"px";
controlElement.style.left = canvas.offsetLeft+"px";
var containerElement = canvas.parentNode;
containerElement.appendChild(controlElement);
}
}
</script>
</body>
</html>
When I put the page on my website and displayed it, the top looked like this:
And when I pressed the pink button, the page changed to this, and the GIF started animating. (The cat laps water falling from a tap.)
To end, here's the second, simple, page. Unlike the first, this doesn't have a fancy Play/Pause control that changes shape: it just has two buttons. The only thing the code does that isn't essential is to disable whichever button is not relevant, and to insert some space between the buttons.
<html>
<head>
<script src="libgif-js-master/libgif.js"></script>
</head>
<body>
<button type="button" onclick="play()"
id="play_button"
style="margin-right:9px;"
>
Play
</button>
<button type="button" onclick="pause()"
id="pause_button"
>
Pause
</button>
<img src="https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif"
id="gif"
/>
<script>
var gif_element = document.getElementById( "gif" );
var supergif = new SuperGif( {
gif: gif_element,
progressbar_height: 0,
auto_play: false
} );
supergif.load();
function play()
{
var play_button = document.getElementById( "play_button" );
play_button.disabled = true;
var pause_button = document.getElementById( "pause_button" );
pause_button.disabled = false;
supergif.play();
}
function pause()
{
var play_button = document.getElementById( "play_button" );
play_button.disabled = false;
var pause_button = document.getElementById( "pause_button" );
pause_button.disabled = true;
supergif.pause();
}
pause_button.disabled = true;
</script>
</body>
</html>
This, plus the example.html file in libgif-js, should be enough to get anyone started.
I used to write my own error logging until I discovered ELMAH. I've never been able to get the emailing part down quite as perfectly as ELMAH does.
var myString = 'sample String'; var length = myString.length ;
first you need to defined a keypressed handler or some kind of a event trigger to listen , btw , getting the length is really simple like mentioned above
I think you have found an example where auto-boxing doesn't really work. Because Arrays.asList(T... a)
has a varargs parameter the compiler apparently considers the int[] and returns a List<int[]>
with a single element in it.
You should change the method into this:
public int getTheNumber(Integer[] factors) {
ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(factors));
Collections.sort(f);
return f.get(0) * f.get(f.size() - 1);
}
and possibly add this for compatibility
public int getTheNumber(int[] factors) {
Integer[] factorsInteger = new Integer[factors.length];
for(int ii=0; ii<factors.length; ++ii) {
factorsInteger[ii] = factors[ii];
}
return getTheNumber(factorsInteger);
}
In SQL Server
You can do this using With CTE
WITH common_table_expression (Transact-SQL)
CREATE TABLE tab(ColumnA DECIMAL(10,2), ColumnB DECIMAL(10,2), ColumnC DECIMAL(10,2))
INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (2, 10, 2),(3, 15, 6),(7, 14, 3)
WITH tab_CTE (ColumnA, ColumnB, ColumnC,calccolumn1)
AS
(
Select
ColumnA,
ColumnB,
ColumnC,
ColumnA + ColumnB As calccolumn1
from tab
)
SELECT
ColumnA,
ColumnB,
calccolumn1,
calccolumn1 / ColumnC AS calccolumn2
FROM tab_CTE
Had the same problem and the solution was to reauthorize the user. Check it here:
<?php
require_once("src/facebook.php");
$config = array(
'appId' => '1424980371051918',
'secret' => '2ed5c1260daa4c44673ba6fbc348c67d',
'fileUpload' => false // optional
);
$facebook = new Facebook($config);
//Authorizing app:
?>
<a href="<?php echo $facebook->getLoginUrl(); ?>">Login con fb</a>
Saved project and opened on my test enviroment and it worked again. As I did, you can comment your previous code and try.
I didn't find find the correct jsonpath filter syntax to extract a value from a name-value pair in json.
Here's the syntax and an abbreviated sample twitter document below.
This site was useful for testing:
The jsonpath filter expression:
.events[0].attributes[?(@.name=='screen_name')].value
Test document:
{
"title" : "test twitter",
"priority" : 5,
"events" : [ {
"eventId" : "150d3939-1bc4-4bcb-8f88-6153053a2c3e",
"eventDate" : "2015-03-27T09:07:48-0500",
"publisher" : "twitter",
"type" : "tweet",
"attributes" : [ {
"name" : "filter_level",
"value" : "low"
}, {
"name" : "screen_name",
"value" : "_ziadin"
}, {
"name" : "followers_count",
"value" : "406"
} ]
} ]
}
I think this need to be run from the Management Shell rather than the console, it sounds like the module isn't being imported into the Powershell console. You can add the module by running:
Add-PSSnapin Microsoft.Sharepoint.Powershell
in the Powershell console.
this is the most general solution
$('body').on('shown.bs.modal', '.modal', function () {
$(this).find(":input:not(:button):visible:enabled:not([readonly]):first").focus();
});
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
File file = getYourFile();
Path path = file.toPath();
byte[] data = Files.readAllBytes(path);
NULL is not anything...it is unknown. NULL does not equal anything. That is why you have to use the magic phrase IS NULL instead of = NULL in your SQL queries
You can refer this: http://weblogs.sqlteam.com/markc/archive/2009/06/08/60929.aspx
Probably the most elegant way of doing this is to do it in one step. See val()
.
$("#text").val(function(i, val) {
return val.replace('.', ':');
});
compared to:
var val = $("#text").val();
$("#text").val(val.replace('.', ':'));
From the docs:
.val( function(index, value) )
function(index, value)A function returning the value to set.
This method is typically used to set the values of form fields. For
<select multiple="multiple">
elements, multiple s can be selected by passing in an array.The
.val()
method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:$('input:text.items').val(function(index, value) { return value + ' ' + this.className; });
This example appends the string " items" to the text inputs' values.
This requires jQuery 1.4+.
DISCLAIMER: This solution is not 100% accurate in terms of determining the minimal width.
I was also figuring out how to measure text on a canvas. After reading the great post from mice i had some problems on how to measure multiline text. There is no obvious way from these contributions but after some research i cam across the StaticLayout class. It allows you to measure multiline text (text with "\n") and configure much more properties of your text via the associated Paint.
Here is a snippet showing how to measure multiline text:
private StaticLayout measure( TextPaint textPaint, String text, Integer wrapWidth ) {
int boundedWidth = Integer.MAX_VALUE;
if (wrapWidth != null && wrapWidth > 0 ) {
boundedWidth = wrapWidth;
}
StaticLayout layout = new StaticLayout( text, textPaint, boundedWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false );
return layout;
}
The wrapwitdh is able to determin if you want to limit your multiline text to a certain width.
Since the StaticLayout.getWidth() only returns this boundedWidth you have to take another step to get the maximum width required by your multiline text. You are able to determine each lines width and the max width is the highest line width of course:
private float getMaxLineWidth( StaticLayout layout ) {
float maxLine = 0.0f;
int lineCount = layout.getLineCount();
for( int i = 0; i < lineCount; i++ ) {
if( layout.getLineWidth( i ) > maxLine ) {
maxLine = layout.getLineWidth( i );
}
}
return maxLine;
}
It seems jQuery's :visible
selector does not work for some inline elements in Chrome. The solution is to add a display style, like "block"
or "inline-block"
to make it work.
Also note that jQuery has a somewhat different definition of what is visible than many developers:
Elements are considered visible if they consume space in the document.
Visible elements have a width or height that is greater than zero.
In other words, an element must have a non-zero width and height to consume space and be visible.
Elements with
visibility: hidden
oropacity: 0
are considered visible, since they still consume space in the layout.
On the other hand, even if its visibility
is set to hidden
or the opacity is zero, it's still :visible
to jQuery as it consumes space, which can be confusing when the CSS explicitly says its visibility is hidden.
Elements that are not in a document are considered hidden; jQuery does not have a way to know if they will be visible when appended to a document since it depends on the applicable styles.
All option elements are considered hidden, regardless of their selected state.
During animations that hide an element, the element is considered visible until the end of the animation. During animations to show an element, the element is considered visible at the start at the animation.
The easy way to look at it, is that if you can see the element on the screen, even if you can't see its content, it's transparent etc., it's visible, i.e. it takes up space.
I cleaned up your markup a little and added a display style (i.e. setting the elements display to "block" etc), and this works for me:
Official API reference for :visible
As of jQuery 3, the definition of :visible
has changed slightly
jQuery 3 slightly modifies the meaning of
:visible
(and therefore of:hidden
).
Starting with this version, elements will be considered:visible
if they have any layout boxes, including those of zero width and/or height. For example,br
elements and inline elements with no content will be selected by the:visible
selector.
I dont know if you want to achieve that in js or java, in js the simplest way to get the unix timestampt (this is time in seconds from 1/1/1970) it's as follows:
var myDate = new Date();
console.log(+myDate); // +myDateObject give you the unix from that date
You can enable/disable a button using isEnabled
or isUserInteractionEnabled
property.
The difference between two is :
isEnabled
is a property of UIControl (super class of UIButton) and it has visual effects (i.e. grayed out) of enable/disable
isUserInteractionEnabled
is a property of UIView (super class of UIControl) and has no visual effect although but achieves the purpose
Usage :
myButton.isEnabled = false // Recommended approach
myButton.isUserInteractionEnabled = false // Alternative approach
np.array()
is even more powerful than what unutbu said above.
You also could use it to convert a list of np arrays to a higher dimention array, the following is a simple example:
aArray=np.array([1,1,1])
bArray=np.array([2,2,2])
aList=[aArray, bArray]
xArray=np.array(aList)
xArray's shape is (2,3), it's a standard np array. This operation avoids a loop programming.
I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):
aptitude install debian-archive-keyring
In case it is some other keyring you need, check out
apt-cache search keyring | grep debian
My squeeze system shows all these:
debian-archive-keyring - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring - GnuPG archive keys of the Debian Edu archive
debian-keyring - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring - GnuPG archive keys for the emdebian repository
You can also search the DOM using ClassName. For example:
document.getElementsByClassName("myDiv")
This will return an array. If there is one particular property you are interested in. For example:
var divWidth = document.getElementsByClassName("myDiv")[0].clientWidth;
divWidth
will now be equal to the the width of the first element in your div array.
Just use arr.slice(startingIndex, endingIndex)
.
If you do not specify the endingIndex
, it returns all the items starting from the index provided.
In your case arr=arr.slice(1)
.
Won't simply concatenating the part of your path accomplish what you want?
$ base="/home/user1/MyFolder/"
$ subdir="subFold1"
$ new_path=$base$subdir
$ echo $new_path
/home/user1/MyFolder/subFold1
You can then create the folders/directories as needed.
One convention is to end directory paths with /
(e.g. /home/
) because paths starting with a / could be confused with the root directory. If a double slash (//
) is used in a path, it is also still correct. But, if no slash is used on either variable, it would be incorrect (e.g. /home/user1/MyFoldersubFold1
).
You almost always want autocrlf=input
unless you really know what you are doing.
Some additional context below:
It should be either
core.autocrlf=true
if you like DOS ending orcore.autocrlf=input
if you prefer unix-newlines. In both cases, your Git repository will have only LF, which is the Right Thing. The only argument forcore.autocrlf=false
was that automatic heuristic may incorrectly detect some binary as text and then your tile will be corrupted. So,core.safecrlf
option was introduced to warn a user if a irreversable change happens. In fact, there are two possibilities of irreversable changes -- mixed line-ending in text file, in this normalization is desirable, so this warning can be ignored, or (very unlikely) that Git incorrectly detected your binary file as text. Then you need to use attributes to tell Git that this file is binary.
The above paragraph was originally pulled from a thread on gmane.org, but it has since gone down.
textTitle.replace(/ /g, '%20');
try this:
psql -U <username> -d <dbname> -f <filename>.sql
Restore DB psql from .sql file
You can simply use Arrays.sort()
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));
Working Example :
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_
_x000D_
console.log(array);
_x000D_
This is one example where using prepared statements really saves you some trouble.
In MySQL, in order to insert a null value, you must specify it at INSERT
time or leave the field out which requires additional branching:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', NULL);
However, if you want to insert a value in that field, you must now branch your code to add the single quotes:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', 'String Value');
Prepared statements automatically do that for you. They know the difference between string(0) ""
and null
and write your query appropriately:
$stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)");
$stmt->bind_param('ss', $field1, $field2);
$field1 = "String Value";
$field2 = null;
$stmt->execute();
It escapes your fields for you, makes sure that you don't forget to bind a parameter. There is no reason to stay with the mysql
extension. Use mysqli
and it's prepared statements instead. You'll save yourself a world of pain.
If you're using Express, you can use this:
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({key:"value"}));
or just this
res.json({key:"value"});
Try this:
yAxis: {min: 0, max: 100}
See this jsfiddle example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using Microsoft.Office.Interop.Excel;
namespace trg.satmap.portal.ParseAgentSkillMapping
{
class ConvertXLStoDT
{
private StringBuilder errorMessages;
public StringBuilder ErrorMessages
{
get { return errorMessages; }
set { errorMessages = value; }
}
public ConvertXLStoDT()
{
ErrorMessages = new StringBuilder();
}
public System.Data.DataTable XLStoDTusingInterOp(string FilePath)
{
#region Excel important Note.
/*
* Excel creates XLS and XLSX files. These files are hard to read in C# programs.
* They are handled with the Microsoft.Office.Interop.Excel assembly.
* This assembly sometimes creates performance issues. Step-by-step instructions are helpful.
*
* Add the Microsoft.Office.Interop.Excel assembly by going to Project -> Add Reference.
*/
#endregion
Microsoft.Office.Interop.Excel.Application excelApp = null;
Microsoft.Office.Interop.Excel.Workbook workbook = null;
System.Data.DataTable dt = new System.Data.DataTable(); //Creating datatable to read the content of the Sheet in File.
try
{
excelApp = new Microsoft.Office.Interop.Excel.Application(); // Initialize a new Excel reader. Must be integrated with an Excel interface object.
//Opening Excel file(myData.xlsx)
workbook = excelApp.Workbooks.Open(FilePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range excelRange = ws.UsedRange; //gives the used cells in sheet
ws = null; // now No need of this so should expire.
//Reading Excel file.
object[,] valueArray = (object[,])excelRange.get_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault);
excelRange = null; // you don't need to do any more Interop. Now No need of this so should expire.
dt = ProcessObjects(valueArray);
}
catch (Exception ex)
{
ErrorMessages.Append(ex.Message);
}
finally
{
#region Clean Up
if (workbook != null)
{
#region Clean Up Close the workbook and release all the memory.
workbook.Close(false, FilePath, Missing.Value);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
#endregion
}
workbook = null;
if (excelApp != null)
{
excelApp.Quit();
}
excelApp = null;
#endregion
}
return (dt);
}
/// <summary>
/// Scan the selected Excel workbook and store the information in the cells
/// for this workbook in an object[,] array. Then, call another method
/// to process the data.
/// </summary>
private void ExcelScanIntenal(Microsoft.Office.Interop.Excel.Workbook workBookIn)
{
//
// Get sheet Count and store the number of sheets.
//
int numSheets = workBookIn.Sheets.Count;
//
// Iterate through the sheets. They are indexed starting at 1.
//
for (int sheetNum = 1; sheetNum < numSheets + 1; sheetNum++)
{
Worksheet sheet = (Worksheet)workBookIn.Sheets[sheetNum];
//
// Take the used range of the sheet. Finally, get an object array of all
// of the cells in the sheet (their values). You can do things with those
// values. See notes about compatibility.
//
Range excelRange = sheet.UsedRange;
object[,] valueArray = (object[,])excelRange.get_Value(XlRangeValueDataType.xlRangeValueDefault);
//
// Do something with the data in the array with a custom method.
//
ProcessObjects(valueArray);
}
}
private System.Data.DataTable ProcessObjects(object[,] valueArray)
{
System.Data.DataTable dt = new System.Data.DataTable();
#region Get the COLUMN names
for (int k = 1; k <= valueArray.GetLength(1); k++)
{
dt.Columns.Add((string)valueArray[1, k]); //add columns to the data table.
}
#endregion
#region Load Excel SHEET DATA into data table
object[] singleDValue = new object[valueArray.GetLength(1)];
//value array first row contains column names. so loop starts from 2 instead of 1
for (int i = 2; i <= valueArray.GetLength(0); i++)
{
for (int j = 0; j < valueArray.GetLength(1); j++)
{
if (valueArray[i, j + 1] != null)
{
singleDValue[j] = valueArray[i, j + 1].ToString();
}
else
{
singleDValue[j] = valueArray[i, j + 1];
}
}
dt.LoadDataRow(singleDValue, System.Data.LoadOption.PreserveChanges);
}
#endregion
return (dt);
}
}
}
If your administrator changed your password, and Windows 10 still stores your old password you will not be asked for a new password. Windows 10 will use the stored old password, and authentication will fail.
You can delete your old password by
If you delete a password, when you try to use SVN, you will be asked for the new password.
# This is a regex solution.
import re
def removeHtml(html):
if not html: return html
# Remove comments first
innerText = re.compile('<!--[\s\S]*?-->').sub('',html)
while innerText.find('>')>=0: # Loop through nested Tags
text = re.compile('<[^<>]+?>').sub('',innerText)
if text == innerText:
break
innerText = text
return innerText.strip()
Vanilla JavaScript solution:
document.body.innerHTML = document.body.innerHTML.replace(/Original/g, "New")
For all practical purposes, and with no import at all, one can use:
x = float("inf")
More detail on this related question: How can I represent an infinite number in Python?
def updateJsonFile():
jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
data = json.load(jsonFile) # Read the JSON into the buffer
jsonFile.close() # Close the JSON file
## Working with buffered content
tmp = data["location"]
data["location"] = path
data["mode"] = "replay"
## Save our changes to JSON file
jsonFile = open("replayScript.json", "w+")
jsonFile.write(json.dumps(data))
jsonFile.close()
It depends where you put this initialisation.
If the array is static as in
char array[100] = {0};
int main(void)
{
...
}
then it is the compiler that reserves the 100 0 bytes in the data segement of the program. In this case you could have omitted the initialiser.
If your array is auto, then it is another story.
int foo(void)
{
char array[100] = {0};
...
}
In this case at every call of the function foo you will have a hidden memset.
The code above is equivalent to
int foo(void)
{
char array[100];
memset(array, 0, sizeof(array));
....
}
and if you omit the initializer your array will contain random data (the data of the stack).
If your local array is declared static like in
int foo(void)
{
static char array[100] = {0};
...
}
then it is technically the same case as the first one.
It depends on your Linux distibution and your preference of editors etc. but I would recommend to start with Kile (a KDE app) as it is easy to learn and installing it should install most of the needed packages for LaTex and PDF generation. Just have a look at the screenshots.
In summary: I would be careful as to what code you copy. It is possible you are copying code which happens to work, rather than well chosen code.
In intnumber, parseInt is used and in floatnumber valueOf is used why so?
There is no good reason I can see. It's an inconsistent use of the APIs as you suspect.
Java is case sensitive, and there isn't any Readline()
method. Perhaps you mean readLine().
DataInputStream.readLine() is deprecated in favour of using BufferedReader.readLine();
However, for your case, I would use the Scanner class.
Scanner sc = new Scanner(System.in);
int intNum = sc.nextInt();
float floatNum = sc.nextFloat();
If you want to know what a class does I suggest you have a quick look at the Javadoc.
So none of the above stuff worked for me. Except this: edit httpd.conf,
find the line
Listen 80
and change to
listen 0.0.0.0:80
if you are running windows 8, its got something to do with using ipv6 instead of ipv4
It is clear that most people who haven't used SQL Server Enterprise Manager don't understand the question (i.e. Justin Cave).
I came upon this post when I wanted to know the same thing.
Using SQL Server, when you are editing your data through the MS SQL Server GUI Tools, you can use a KEYBOARD SHORTCUT to insert a NULL rather than having just an EMPTY CELL, as they aren't the same thing. An empty cell can have a space in it, rather than being NULL, even if it is technically empty. The difference is when you intentionally WANT to put a NULL in a cell rather than a SPACE or to empty it and NOT using a SQL statement to do so.
So, the question really is, how do I put a NULL value in the cell INSTEAD of a space to empty the cell?
I think the answer is, that the way the Oracle Developer GUI works, is as Laniel indicated above, And THAT should be marked as the answer to this question.
Oracle Developer seems to default to NULL when you empty a cell the way the op is describing it.
Additionally, you can force Oracle Developer to change how your null cells look by changing the color of the background color to further demonstrate when a cell holds a null:
Tools->Preferences->Advanced->Display Null Using Background Color
or even the VALUE it shows when it's null:
Tools->Preferences->Advanced->Display Null Value As
Hope that helps in your transition.
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session
(cookie) variable before redirecting and then get the variable before rendering the template. For example:
from flask import session, url_for
def do_baz():
messages = json.dumps({"main":"Condition failed on page baz"})
session['messages'] = messages
return redirect(url_for('.do_foo', messages=messages))
@app.route('/foo')
def do_foo():
messages = request.args['messages'] # counterpart for url_for()
messages = session['messages'] # counterpart for session
return render_template("foo.html", messages=json.loads(messages))
(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)
Or you could probably just use Flask Message Flashing if you just need to show simple messages.
Use Context.getDatabasePath(databasename). The context can be obtained from your application.
If you get previous data back it can be either a) the data was stored in an unconventional location and therefore not deleted with uninstall or b) Titanium backed up the data with the app (it can do that).
If you are using the Spring Boot Maven Plugin, run:
mvn spring-boot:run -Dspring-boot.run.profiles=foo,bar
(https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-profiles.html)
This worked for me: To wrap the contents of the second file into a function, as follows:
<?php
include("secondFile.php");
echoFunction("message");
<?php
function echoFunction($variable)
{
echo $variable;
}
You must create a new date object and set it as minDate
when you initialize the datepickers
<label for="from">From</label> <input type="text" id="from" name="from"/> <label for="to">to</label> <input type="text" id="to" name="to"/>
var dateToday = new Date();
var dates = $("#from, #to").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
minDate: dateToday,
onSelect: function(selectedDate) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
dates.not(this).datepicker("option", option, date);
}
});
Edit - from your comment now it works as expected http://jsfiddle.net/nicolapeluchetti/dAyzq/1/
Make sure to target x86 on your project in Visual Studio. This should fix your trouble.
You can reset the index using reset_index
to get back a default index of 0, 1, 2, ..., n-1 (and use drop=True
to indicate you want to drop the existing index instead of adding it as an additional column to your dataframe):
In [19]: df2 = df2.reset_index(drop=True)
In [20]: df2
Out[20]:
x y
0 0 0
1 0 1
2 0 2
3 1 0
4 1 1
5 1 2
6 2 0
7 2 1
8 2 2
From your local machine:
rsync -chavzP --stats [email protected]:/path/to/copy /path/to/local/storage
From your local machine with a non standard ssh port:
rsync -chavzP -e "ssh -p $portNumber" [email protected]:/path/to/copy /local/path
Or from the remote host, assuming you really want to work this way and your local machine is listening on SSH:
rsync -chavzP --stats /path/to/copy [email protected]:/path/to/local/storage
See man rsync
for an explanation of my usual switches.
The below code is a solution to the question in Python 3. Before running the code, make sure you have installed the PyPDF2
library in your environment. If not installed, open the command prompt and run the following command:
pip3 install PyPDF2
Solution Code:
import PyPDF2
pdfFileObject = open('sample.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObject)
count = pdfReader.numPages
for i in range(count):
page = pdfReader.getPage(i)
print(page.extractText())
Read your reference more carefully:
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.
. . .
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.