If your blog outputs an RSS feed you can use Facebook's "RSS Graffiti" application to post that feed to your wall in Facebook. There are other RSS Facebook apps as well; just search "Facebook for RSS apps"...
We just released an experimental GitHub repository which should ease the process of using NVIDIA GPUs inside Docker containers.
Alternative to killing TortoiseGit:
rmdir /S /Q
)You were almost right, there's just need one little fix to be made:
var a = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
.AddMilliseconds(1310522400000)
.ToLocalTime();
I may be simplifying the issue, but does td {border-right: 1px solid red;} work for your table setup?
Example: Display different output depending on whether the user is logged in or not.
<?php
if ( is_user_logged_in() ) {
echo 'Welcome, registered user!';
} else {
echo 'Welcome, visitor!';
}
?>
from the terminal u can simply say
expoort FLASK_APP=app_name.py
export FLASK_ENV=development
flask run
or in ur file
if __name__ == "__main__":
app.run(debug=True)
I love the fully featured, language-agnostic answers from folks like @Arak. Since this question was tagged JavaScript though, I'd like to chip in some notes very specific to this language.
In JavaScript our choices for scoping are:
var _this = this; function callback(){ console.log(_this); }
callback.bind(this)
It's worth noting, I think, that JavaScript doesn't really have dynamic scoping. .bind
adjusts the this
keyword, and that's close, but not technically the same.
Here is an example demonstrating both approaches. You do this every time you make a decision about how to scope callbacks so this applies to promises, event handlers, and more.
Here is what you might term Lexical Scoping
of callbacks in JavaScript:
var downloadManager = {
initialize: function() {
var _this = this; // Set up `_this` for lexical access
$('.downloadLink').on('click', function () {
_this.startDownload();
});
},
startDownload: function(){
this.thinking = true;
// Request the file from the server and bind more callbacks for when it returns success or failure
}
//...
};
Another way to scope is to use Function.prototype.bind
:
var downloadManager = {
initialize: function() {
$('.downloadLink').on('click', function () {
this.startDownload();
}.bind(this)); // Create a function object bound to `this`
}
//...
These methods are, as far as I know, behaviorally equivalent.
zxing does not (only) provide a web API; really, that is Google providing the API, from source code that was later open-sourced in the project.
As Rob says here you can use the Java source code for the QR code encoder to create a raw barcode and then render it as a Bitmap.
I can offer an easier way still. You can call Barcode Scanner by Intent to encode a barcode. You need just a few lines of code, and two classes from the project, under android-integration
. The main one is IntentIntegrator. Just call shareText()
.
See Java tools documentation for:
- The
java
tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class'smain
method.- The
javaw
command is identical tojava
, except that withjavaw
there is no associated console window. Usejavaw
when you don't want a command prompt window to appear.
javaws
command, the "Java Web Start command"The
javaws
command launches Java Web Start, which is the reference implementation of the Java Network Launching Protocol (JNLP). Java Web Start launches Java applications/applets hosted on a network.
If a JNLP file is specified,javaws
will launch the Java application/applet specified in the JNLP file.
Thejavaws
launcher has a set of options that are supported in the current release. However, the options may be removed in a future release.
See also JDK 9 Release Notes Deprecated APIs, Features, and Options:
Java Deployment Technologies are deprecated and will be removed in a future release
Java Applet and WebStart functionality, including the Applet API, the Java plug-in, the Java Applet Viewer, JNLP and Java Web Start, including thejavaws
tool, are all deprecated in JDK 9 and will be removed in a future release.
The question has been asked on serverfault too.
You may want to take a look at this article which explains a lot about MySQL row sizes. It's important to note that even if you use TEXT or BLOB fields, your row size could still be over 8K (limit for InnoDB) because it stores the first 768 bytes for each field inline in the page.
The simplest way to fix this is to use the Barracuda file format with InnoDB. This basically gets rid of the problem altogether by only storing the 20 byte pointer to the text data instead of storing the first 768 bytes.
The method that worked for the OP there was:
Add the following to the my.cnf
file under [mysqld]
section.
innodb_file_per_table=1
innodb_file_format = Barracuda
ALTER
the table to use ROW_FORMAT=COMPRESSED
.
ALTER TABLE nombre_tabla
ENGINE=InnoDB
ROW_FORMAT=COMPRESSED
KEY_BLOCK_SIZE=8;
There is a possibility that the above still does not resolve your issues. It is a known (and verified) bug with the InnoDB engine, and a temporary fix for now is to fallback to MyISAM engine as temporary storage. So, in your my.cnf
file:
internal_tmp_disk_storage_engine=MyISAM
To make sure you have the application's path (and not just the current directory), use this:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getcurrentprocess.aspx
Now you have a Process
object that represents the process that is running.
Then use Process.MainModule.FileName
:
http://msdn.microsoft.com/en-us/library/system.diagnostics.processmodule.filename.aspx
Finally, use Path.GetDirectoryName
to get the folder containing the .exe:
http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname.aspx
So this is what you want:
string folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\Archive\";
string filter = "*.zip";
string[] files = Directory.GetFiles(folder, filter);
(Notice that "\Archive\"
from your question is now @"\Archive\"
: you need the @ so that the \
backslashes aren't interpreted as the start of an escape sequence)
Hope that helps!
If you are trying to create a self signed certificate that lets you go http://localhost/mysite
Then here is a way to create it
makecert -r -n "CN=localhost" -b 01/01/2000 -e 01/01/2099 -eku 1.3.6.1.5.5.7.3.1 -sv localhost.pvk localhost.cer
cert2spc localhost.cer localhost.spc
pvk2pfx -pvk localhost.pvk -spc localhost.spc -pfx localhost.pfx
From http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/32bc5a61-1f7b-4545-a514-a11652f11200
Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Then you could use
Call fso.CopyFile(source, destination[, overwrite] )
where source and destination are the full names (including paths) of the file.
See https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method
I was trying to copy the size data measured from Chrome Network and stumbled on this post. I just found an easier way to "export" the data out to excel which is to copy the table and paste to excel.
The trick is click Control + A (select all) and once the entire table will be highlighted, paste it to Microsoft Excel. The only issue is if there are too many fields, not all rows are copied and you might have to copy and paste several times.
UPDATED: I found that copying the data only works when I turn off the filter options (the funnel-looking button above the table). – bendur
If you want to restore an SQL Server database from a backup file, you can use the following script:
RESTORE DATABASE [MyDatabase] -- which database to restore
FROM DISK = N'X:\MyDatabase.bak' -- location of the database backup
WITH
FILE = 1, -- restore from a backup file
-- declare where the file groups should be located (can be more than two)
MOVE N'MyDatabase_Data' TO N'D:\SSDPATH\MyDatabase.mdf',
MOVE N'MyDatabase_Log' TO N'E:\HDDPATH\MyDatabase.ldf',
-- Tape option; only relevant if you backup from magnetic tape
NOUNLOAD,
-- brings the database online after the database got restored
-- use this option when you don't want to restore incremental backups
-- use NORECOVERY when you want to restore differential and incremental backup files
RECOVERY,
-- replace existing database with the backup
-- deletes the existing database
REPLACE,
-- print log message for every 1 percent of restore
STATS = 1;
The issue of erroneous leftover entries in the .csproj file still occurs with VS2015update3 and can also occur if you try to change the signing certificate for a different one (even if that is one generated using the 'new' option in the certificate selection dropdown). The advice in the accepted answer (mark as not signed, save, unload project, edit .csproj, remove the properties relating to the old certificates/thumbprints/keys & reload project, set certificate) is reliable.
Another way to get all change log in a specified period of time
git log --author="Tri Nguyen" --oneline --shortstat --before="2017-03-20" --after="2017-03-10"
Output:
2637cc736 Revert changed code
1 file changed, 5 insertions(+), 5 deletions(-)
ba8d29402 Fix review
2 files changed, 4 insertions(+), 11 deletions(-)
With a long output content, you can export to file for more readable
git log --author="Tri Nguyen" --oneline --shortstat --before="2017-03-20" --after="2017-03-10" > /mnt/MyChangeLog.txt
A sample - write multiple rows with boolean column (using example above by GaretJax and Eran?).
import csv
RESULT = [['IsBerry','FruitName'],
[False,'apple'],
[True, 'cherry'],
[False,'orange'],
[False,'pineapple'],
[True, 'strawberry']]
with open("../datasets/dashdb.csv", 'wb') as resultFile:
wr = csv.writer(resultFile, dialect='excel')
wr.writerows(RESULT)
Result:
df_data_4 = pd.read_csv('../datasets/dashdb.csv')
df_data_4.head()
Output:
IsBerry FruitName
0 False apple
1 True cherry
2 False orange
3 False pineapple
4 True strawberry
PostreSQL apparently converts column names to lower case in a sql query - I've seen issues where mixed case column names will give that error. You can fix it by putting the column name in quotation marks:
SELECT * FROM table_name where "Foo" IS NULL
DECLARE @date nvarchar(20)
SET @date ='2012-02-09 00:00:00'
SELECT DATEDIFF(day,cast(replace(cast(YEAR(@date) as char)+'-'+cast(MONTH(@date) as char)+'-01',' ','')+' 00:00:00' as datetime),dateadd(month,1,cast(replace(cast(YEAR(@date) as char)+'-'+cast(MONTH(@date) as char)+'-01',' ','')+' 00:00:00' as datetime)))
You can download whatever versions of PHP you need and place them into their own directories, e.g.
c:\php5\
c:\php7\
All you need to do is tell your web server (Apache) which version of PHP to use, which you do by loading the appropriate module. In Apache you can do this by finding the file httpd.conf
and then editing the appropriate line:
LoadModule php7_module c:\php7\libphp7.so
You'll have to figure out the correct paths of course - this is just for illustration.
Save httpd.conf
and restart your server. Note, if you don't restart it, the changes won't take effect.
There's no GUI switch to be able to do this, you need to edit the .conf
file and then restart Apache. Doing this only takes a couple of seconds and you could even comment out a version so "switching" only takes a couple of keystrokes, e.g.
Use PHP 5:
LoadModule php5_module c:\php5\libphp5.so
#LoadModule php7_module c:\php7\libphp7.so
Use PHP 7:
#LoadModule php5_module c:\php5\libphp5.so
LoadModule php7_module c:\php7\libphp7.so
You do not need multiple versions of XAMPP, or to dual boot, or use a different machine, or any of the other "solutions" that have suggested convoluted workarounds. The OP wants to use XAMPP and tell it which version of PHP to use. This is the quickest and most efficient way of doing it, and only requires one XAMPP installation.
Edit 1-Nov-2017: Apparently some people are saying there's no .so
files on Windows. The answer I gave was adapted from how I have things set up on my Mac (which does use .so
files instead of .dll
). The principle of the answer however is still exactly correct. You are using Apache's configuration file, httpd.conf
to specify where the PHP module (.so
or .dll
) is located on your system. So the only difference for Windows would be the file name and/or path location. The answer I've given is also correct for a vanilla installation of Apache/PHP (without XAMPP at all).
in sed you can reference groups in your pattern with "\1", "\2", .... so if the pattern you're looking for is "PATTERN", and you want to insert "BEFORE" in front of it, you can use, sans escaping
sed 's/(PATTERN)/BEFORE\1/g'
i.e.
sed 's/\(PATTERN\)/BEFORE\1/g'
After spending days on the subject, I managed to solve it finally. Unfortunately we need it if we want to use expansion files. The solution has been provided by a few people here, but for me the answers were missing a few minor detail that could have saved a lot of time for me. Here is the sequence of events for novices like me to save your precious time.
First I imported the "library" folder from D:\Users\Imre\AppData\Local\Android\sdk1\extras\google\play_licensing to the project by going into File, New, Import Module and navigating to the "library" folder. If you open the SDK Manager and click on "Launch Standalone SDK Manager" in the bottom of the popup screen, you can hover your pointer over the "Extras" folder down in the bottom and the small yellow info will tell you where you will find the package that you need to import.
Once that is done, go down to the "library" section in the left pane with "Project" and within it the "Android" tab open. Open the java section of the library and open the APKExpansionPolicy class. If you have errors and the import org.apache.http.NameValuePair and the import org.apache.http.client.utils.URLEncodedUtils are pale grey, open the build.gradle(Project:whatever) and make sure that in "buildscript" under "dependancies" you have the "classpath 'com.android.tools.build:gradle:1.5.0" included. The 1.5.0 might be different in your case. I guess it depends on your Studio version. Mine is 1.5.1. If yours is newer, you will be reminded to update the numbers.
After that, go to "build.gradle(Module:library) and include the "useLibrary 'org.apache.http.legacy' into the "android"section. Sync Now (R/H top corner) should be offered. Do it.
If you get further error messages (I wouldn't know it because I did it the other way round), the Apache files might be missing from your project, as apache is not supported anymore. Find them in C/D:Users/Yourname/AppData/Local/Android/Sdk/platforms/android-23/optional and copy/paste them into yourproject/app/libs folder. You should have an optional.json and an org.apache.http.legacy.jar file in there. You might be better off going to apache's website and dowloading the newest version: http://hc.apache.org/downloads.cgi Unzip it anywhere you want, open it, go to "lib", copy the httpclient-4.5.1.jar file and replace the org.apache.http.legacy.jar file with it.
Sync and rebuild/clean your project and it should be good to go.
Just in case, open your terminal (L/H bottom of Android Studio) and type in "gradlew clean". It will install a few things. Once it is done, type in "gradlew assemble". It will take a few minutes to finish, but it will give you the errors if you have any of course. If you cannot type in anything in the Terminal, launch command prompt (Windows button+R), type in cmd, hit OK, right click on the title of the small black popup screen (C:\WINDOWS\system32\cmd.exe), Properties, Options, in the bottom of the window check that "Use legacy console" is thicked. Restart A.Studio.
Good luck!
Heres how to change all databases/tables/columns. Run these queries and they will output all of the subsequent queries necessary to convert your entire schema to utf8. Hope this helps!
-- Change DATABASE Default Collation
SELECT DISTINCT concat('ALTER DATABASE `', TABLE_SCHEMA, '` CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.tables
where TABLE_SCHEMA like 'database_name';
-- Change TABLE Collation / Char Set
SELECT concat('ALTER TABLE `', TABLE_SCHEMA, '`.`', table_name, '` CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.tables
where TABLE_SCHEMA like 'database_name';
-- Change COLUMN Collation / Char Set
SELECT concat('ALTER TABLE `', t1.TABLE_SCHEMA, '`.`', t1.table_name, '` MODIFY `', t1.column_name, '` ', t1.data_type , '(' , t1.CHARACTER_MAXIMUM_LENGTH , ')' , ' CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.columns t1
where t1.TABLE_SCHEMA like 'database_name' and t1.COLLATION_NAME = 'old_charset_name';
Whenever is possible is preferable to use class .myclass{}
and identifier #myclass{}
, so use a dedicated css file or tag <style></style>
within an html.
Inline style is good to change css option dynamically with javascript.
Try doing SHIFT + G
and you will be at the end of the page, but you can't edit yet. Go to the top by doing G + G
After you've run the Inspect by Name, select all the locations, and make use of the Apply quick fixes to all the problems drop-down, and use either (or both) of Delete unused parameter(s) and Safe Delete.
Don't forget to hit Do Refactor afterwards.
Then you'll need to run another analysis, as the refactored code will no doubt reveal more unused declarations.
Why Map.Entry
? I guess something like a key-value pair is fit for the case.
Use java.util.AbstractMap.SimpleImmutableEntry
or java.util.AbstractMap.SimpleEntry
To fix this problem on specific page need to set some validation settings when page loading. Write code below in Page_Load()
method:
protected void Page_Load(object sender, EventArgs e)
{
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
}
Its work for me in .NET 4.5
public void GetDefaultLanguage( ) {
try {
String langue = Locale.getDefault().toString(); // ---> en_US
/*
Log.i("TAG", Locale.getDefault().getLanguage() ); // ---> en
Log.i("TAG", Locale.getDefault().getISO3Language() ); // ---> eng
Log.i("TAG", Locale.getDefault().getCountry() ); // ---> US
Log.i("TAG", Locale.getDefault().getISO3Country() ); // ---> USA
Log.i("TAG", Locale.getDefault().getDisplayCountry() ); // ---> United States
Log.i("TAG", Locale.getDefault().getDisplayName() ); // ---> English (United States)
Log.i("TAG", Locale.getDefault().toString() ); // ---> en_US
Log.i("TAG", Locale.getDefault().getDisplayLanguage() ); //---> English
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
langue = Locale.getDefault().toLanguageTag(); // ---> en-US
url_Api = getUrlMicrosoftLearn(langue);
Log.i("TAG", url_Api );
Log.i("TAG", langue );
}else{
langue = langue.replace("_","-"); // ---> en-US
url_Api = getUrlMicrosoftLearn(langue);
Log.i("TAG", url_Api );
Log.i("TAG", langue );
}
}catch (Exception ex) {
Log.i("TAG", "Exception:GetDefaultLanguage()", ex);
}
}
public String getUrlMicrosoftLearn(String langue) {
return "https://docs.microsoft.com/"+langue+"/learn";
}
For anyone who is still stumbling with this after using all of the possible MIME types listed in the question:
I have found that iMacs tend to also throw a MIME type of "text/xls" for XLS Excel files, hope this helps.
<style>
.demo-ele{display:inline-block}
</style>
<div class="demo-ele" style="display:none">...</div>
<script>
$(".demo-ele").show(1000);//hide first, show with inline-block
<script>
Application.Sum often does not work well in my experience (or at least the VBA developer environment does not like it for whatever reason).
The function that works best for me is Excel.WorksheetFunction.Sum()
Example:
Dim Report As Worksheet 'Set up your new worksheet variable.
Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.
Report.Cells(11, 1).Value = Excel.WorksheetFunction.Sum(Report.Range("A1:A10")) 'Add the function result.
The other method which you were looking for I think is to place the function directly into the cell. This can be done by inputting the function string into the cell value. Here is an example that provides the same result as above, except the cell value is given the function and not the result of the function:
Dim Report As Worksheet 'Set up your new worksheet variable.
Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.
Report.Cells(11, 1).Value = "=Sum(A1:A10)" 'Add the function.
As something of an aside, MAXDOP can apparently be used as a workaround to a potentially nasty bug:
you can get the index via grep
and colnames
:
grep("B", colnames(df))
[1] 2
or use
grep("^B$", colnames(df))
[1] 2
to only get the columns called "B" without those who contain a B e.g. "ABC".
Another way of achieving it would be to temporary edit the gitignore file, add the file and then revert back the gitignore. A bit hacky i feel
Yes, it is legal to have a primary key being a foreign key. This is a rare construct, but it applies for:
a 1:1 relation. The two tables cannot be merged in one because of different permissions and privileges only apply at table level (as of 2017, such a database would be odd).
a 1:0..1 relation. Profile may or may not exist, depending on the user type.
performance is an issue, and the design acts as a partition: the profile table is rarely accessed, hosted on a separate disk or has a different sharding policy as compared to the users table. Would not make sense if the underlining storage is columnar.
In the spirit of changing the rendering instead of changing the content, the following CSS makes each newline behave like a <br>
:
white-space: pre;
white-space: pre-line;
Why two rules: pre-line
only affects newlines (thanks for the clue, @KevinPauli). IE6-7 and other old browsers fall back to the more extreme pre
which also includes nowrap
and renders multiple spaces. Details on these and other settings (pre-wrap
) at mozilla and css-tricks (thanks @Sablefoste).
While I'm generally averse to the S.O. predilection for second-guessing the question rather than answering it, in this case replacing newlines with <br>
markup may increase vulnerability to injection attack with unwashed user input. You're crossing a bright red line whenever you find yourself changing .text()
calls to .html()
which the literal question implies would have to be done. (Thanks @AlexS for highlighting this point.) Even if you rule out a security risk at the time, future changes could unwittingly introduce it. Instead, this CSS allows you to get hard line breaks without markup using the safer .text()
.
Actually there is no way to do this through JavaScript, unless you use some external source. Even then, it might not be 100% correct.
You can try this:
au BufWinEnter * if &textwidth > 8
\ | let w:m1=matchadd('MatchParen', printf('\%%<%dv.\%%>%dv', &textwidth+1, &textwidth-8), -1)
\ | let w:m2=matchadd('ErrorMsg', printf('\%%>%dv.\+', &textwidth), -1)
\ | endif
That will set up two highlights in every buffer, one for characters in the 8 columns prior to whatever your &textwidth
is set to, and one for characters beyond that column. That way you have some extent of anticipation. Of course you can tweak it to use a different width if you want more or less anticipation (which you pay for in the form of loss of syntax highlighting in those columns).
Short version: by undoing the undo. If you undo, and then do a non-editing command such as C-f, then the next undo will undo the undo, resulting in a redo.
Longer version:
You can think of undo as operating on a stack of operations. If you perform some command (even a navigation command such as C-f) after a sequence of undo operations, all the undos are pushed on to the operation stack. So the next undo undoes the last command. Suppose you do have an operation sequence that looks like this:
Now, you undo. It undoes the last action, resulting in the following list:
If you do something other than undo at this point - say, C-f, the operation stack looks like this:
Now, when you undo, the first thing that is undone is the undo. Resulting in your original stack (and document state):
If you do a modifying command to break the undo sequence, that command is added after the undo and is thus the first thing to be undone afterwards. Suppose you backspaced over "bar" instead of hitting C-f. Then you would have had
This adding/re-adding happens ad infinitum. It takes a little getting used to, but it really does give Emacs a highly flexible and powerful undo/redo mechanism.
Because I recently needed this, I looked at the source of the answer in:
c# extend class by adding properties
and created a more dynamic version:
public static class ObjectExtenders
{
static readonly ConditionalWeakTable<object, List<stringObject>> Flags = new ConditionalWeakTable<object, List<stringObject>>();
public static string GetFlags(this object objectItem, string key)
{
return Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value;
}
public static void SetFlags(this object objectItem, string key, string value)
{
if (Flags.GetOrCreateValue(objectItem).Any(x => x.Key == key))
{
Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value = value;
}
else
{
Flags.GetOrCreateValue(objectItem).Add(new stringObject()
{
Key = key,
Value = value
});
}
}
class stringObject
{
public string Key;
public string Value;
}
}
It can probably be improved a lot (naming, dynamic instead of string), I currently use this in CF 3.5 together with a hacky ConditionalWeakTable (https://gist.github.com/Jan-WillemdeBruyn/db79dd6fdef7b9845e217958db98c4d4)
I think that substitution is an indirect way of getting to the solution. If you want to retrieve all the numbers, I recommend gregexpr
:
matches <- regmatches(years, gregexpr("[[:digit:]]+", years))
as.numeric(unlist(matches))
If you have multiple matches in a string, this will get all of them. If you're only interested in the first match, use regexpr
instead of gregexpr
and you can skip the unlist
.
$('#my_select option:selected').attr('id');
The final
keyword on a method parameter means absolutely nothing to the caller. It also means absolutely nothing to the running program, since its presence or absence doesn't change the bytecode. It only ensures that the compiler will complain if the parameter variable is reassigned within the method. That's all. But that's enough.
Some programmers (like me) think that's a very good thing and use final
on almost every parameter. It makes it easier to understand a long or complex method (though one could argue that long and complex methods should be refactored.) It also shines a spotlight on method parameters that aren't marked with final
.
I found this code at Microsoft.AspNet.Identity.Core component, and it works.
private static readonly TaskFactory _myTaskFactory = new
TaskFactory(CancellationToken.None, TaskCreationOptions.None,
TaskContinuationOptions.None, TaskScheduler.Default);
// Microsoft.AspNet.Identity.AsyncHelper
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
{
CultureInfo cultureUi = CultureInfo.CurrentUICulture;
CultureInfo culture = CultureInfo.CurrentCulture;
return AsyncHelper._myTaskFactory.StartNew<Task<TResult>>(delegate
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = cultureUi;
return func();
}).Unwrap<TResult>().GetAwaiter().GetResult();
}
I think buffers are e.g. useful when interfacing python to native libraries. (Guido van Rossum explains buffer
in this mailinglist post).
For example, numpy seems to use buffer for efficient data storage:
import numpy
a = numpy.ndarray(1000000)
the a.data
is a:
<read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>
The answer I was searching for was answered here: How to use python argparse with args other than sys.argv?
If main.py
and parse_args()
is written in this way, then the parsing can be done nicely
# main.py
import argparse
def parse_args():
parser = argparse.ArgumentParser(description="")
parser.add_argument('--input', default='my_input.txt')
return parser
def main(args):
print(args.input)
if __name__ == "__main__":
parser = parse_args()
args = parser.parse_args()
main(args)
Then you can call main()
and parse arguments with parser.parse_args(['--input', 'foobar.txt'])
to it in another python script:
# temp.py
from main import main, parse_args
parser = parse_args()
args = parser.parse_args([]) # note the square bracket
# to overwrite default, use parser.parse_args(['--input', 'foobar.txt'])
print(args) # Namespace(input='my_input.txt')
main(args)
Visual Studio 2017
You can only match to constants in switch statements.
Example:
switch (variable1)
{
case 1: // A hard-coded value
// Code
break;
default:
// Code
break;
}
Successful!
switch (variable1)
{
case variable2:
// Code
break;
default:
// Code
break;
}
CS0150 A constant value is expected.
I wanted to implement myself this, i ended up reading the Wikipedia page on Great-circle distance formula, because no code was readable enough for me to use as basis.
C# example
/// <summary>
/// Calculates the distance between two locations using the Great Circle Distance algorithm
/// <see cref="https://en.wikipedia.org/wiki/Great-circle_distance"/>
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
private static double DistanceBetween(GeoLocation first, GeoLocation second)
{
double longitudeDifferenceInRadians = Math.Abs(ToRadians(first.Longitude) - ToRadians(second.Longitude));
double centralAngleBetweenLocationsInRadians = Math.Acos(
Math.Sin(ToRadians(first.Latitude)) * Math.Sin(ToRadians(second.Latitude)) +
Math.Cos(ToRadians(first.Latitude)) * Math.Cos(ToRadians(second.Latitude)) *
Math.Cos(longitudeDifferenceInRadians));
const double earthRadiusInMeters = 6357 * 1000;
return earthRadiusInMeters * centralAngleBetweenLocationsInRadians;
}
private static double ToRadians(double degrees)
{
return degrees * Math.PI / 180;
}
Note : This answer was given in 2011. Please check the updated documentation on HTML5 video before proceeding.
If you just want to know whether the video is paused, use the flag stream.paused
.
There is no property for video element for getting the playing status. But there is one event "playing" which will be triggered when it starts to play. Event "ended" is triggered when it stops playing.
So the solution is
This page will give you a better idea about video events. Play the video on this page and see how events are triggered.
http://www.w3.org/2010/05/video/mediaevents.html
I'm going to take a chance here and actually advise against this. I suspect that people wanting to view your PDFs will already have their viewers set up the way they want, and will not take kindly to you taking that choice away from them :-)
Why not just stream down the content with the correct content specifier?
That way, newbies will get whatever their browser developer has a a useful default, and those of us that know how to configure such things will see it as we want to.
you declare like this
private boolean isSelectionRight;
write
out.writeInt(isSelectionRight ? 1 : 0);
read
isSelectionRight = in.readInt() != 0;
boolean type needs to be converted to something that Parcel supports and so we can convert it to int.
Assuming you mean "list" where you say "array", you can do
if item in my_list:
# whatever
This works for any collection, not just for lists. For dictionaries, it checks whether the given key is present in the dictionary.
Its more than just setting the connection to null. That may be what the documentation says, but that is not the truth for mysql. The connection will stay around for a bit longer (Ive heard 60s, but never tested it)
If you want to here the full explanation see this comment on the connections https://www.php.net/manual/en/pdo.connections.php#114822
To force the close the connection you have to do something like
$this->connection = new PDO();
$this->connection->query('KILL CONNECTION_ID()');
$this->connection = null;
Using JODA:
PeriodFormatter periodFormat = new PeriodFormatterBuilder()
.minimumParsedDigits(2)
.appendHour() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendMinute() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendSecond()
.appendSeparator(".")
.appendMillis3Digit()
.toFormatter();
Period result = Period.parse(string, periodFormat);
return result.toStandardDuration().getMillis();
MuSTaNG's answer says it all, but I am still adding it to make it a little more elaborate, with links and all.
The conventional operators
are available for DateTime
since .NET Framework 1.1. Also, addition and subtraction of DateTime
objects are also possible using conventional operators +
and -
.
One example from MSDN:
Equality:System.DateTime april19 = new DateTime(2001, 4, 19);
System.DateTime otherDate = new DateTime(1991, 6, 5);
// areEqual gets false.
bool areEqual = april19 == otherDate;
otherDate = new DateTime(2001, 4, 19);
// areEqual gets true.
areEqual = april19 == otherDate;
Other operators can be used likewise.
Here is the list all operators available for DateTime
.
I know it is not answer but added if someone looking same in Qt
In Qt
https://wiki.qt.io/Get-OS-name-in-Qt
QString Get::osName()
{
#if defined(Q_OS_ANDROID)
return QLatin1String("android");
#elif defined(Q_OS_BLACKBERRY)
return QLatin1String("blackberry");
#elif defined(Q_OS_IOS)
return QLatin1String("ios");
#elif defined(Q_OS_MAC)
return QLatin1String("osx");
#elif defined(Q_OS_WINCE)
return QLatin1String("wince");
#elif defined(Q_OS_WIN)
return QLatin1String("windows");
#elif defined(Q_OS_LINUX)
return QLatin1String("linux");
#elif defined(Q_OS_UNIX)
return QLatin1String("unix");
#else
return QLatin1String("unknown");
#endif
}
From Here you can deserialize an object from file in two way.
string json = File.ReadAllText(@"c:\myObj.json");
MyObject myObj = JsonConvert.DeserializeObject<MyObject>(json);
using (StreamReader file = File.OpenText(@"c:\myObj.json"))
{
JsonSerializer serializer = new JsonSerializer();
MyObject myObj2 = (MyObject)serializer.Deserialize(file, typeof(MyObject));
}
from here you can serialize an object to file in two way.
string json = JsonConvert.SerializeObject(myObj);
File.WriteAllText(@"c:\myObj.json", json);
using (StreamWriter file = File.CreateText(@"c:\myObj.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, myObj);
}
You can download Newtonsoft.Json from NuGet by following command
Install-Package Newtonsoft.Json
git add --all
or git add -A
or git add -A .
Stages All
git add .
Stages New & Modified But Without Deleted
git add -u
Stages Modified & Deleted But Without New
git commit -a
Means git add -u
And git commit -m "message"
After writing this command follow these steps:-
git add <list of files>
add specific file
git add *.txt
add all the txt files in current directory
git add docs/*/txt
add all txt files in docs directory
git add docs/
add all files in docs directory
git add "*.txt"
or git add '*.txt'
add all the files in the whole project
To add to DSM's answer and building on this associated question, I'd split the approach into two cases:
Adding a single column: Just assign empty values to the new columns, e.g. df['C'] = np.nan
Adding multiple columns: I'd suggest using the .reindex(columns=[...])
method of pandas to add the new columns to the dataframe's column index. This also works for adding multiple new rows with .reindex(rows=[...])
. Note that newer versions of Pandas (v>0.20) allow you to specify an axis
keyword rather than explicitly assigning to columns
or rows
.
Here is an example adding multiple columns:
mydf = mydf.reindex(columns = mydf.columns.tolist() + ['newcol1','newcol2'])
or
mydf = mydf.reindex(mydf.columns.tolist() + ['newcol1','newcol2'], axis=1) # version > 0.20.0
You can also always concatenate a new (empty) dataframe to the existing dataframe, but that doesn't feel as pythonic to me :)
Try these (reference):
clear linenum
clear filename:linenum
Open Chrome Developer Tools, go to Network tab, make your request (you may need to check "Preserve Log" if the page refreshes). Find the request on the left, right-click, "Copy as cURL".
Assuming you are using this plugin, you are misusing the .set
method. .set
must be passed the name of the key as a string as well as the value. I suppose you meant to write:
$.session.set("userName", $("#uname").val());
This sets the userName
key in session storage to the value of the input, and allows you to retrieve it using:
$.session.get('userName');
With @Lob
I always end up with a LONGTEXT
in MySQL.
To get TEXT
I declare it that way (JPA 2.0):
@Column(columnDefinition = "TEXT")
private String text
Find this better, because I can directly choose which Text-Type the column will have in database.
For columnDefinition
it is also good to read this.
EDIT: Please pay attention to Adam Siemions comment and check the database engine you are using, before applying columnDefinition = "TEXT"
.
In Visual Studio 2019 WinForm Projects, it is available under
Project Properties -> Application -> View Windows Settings (button)
ES6 allows you to use a backtick to specify a string on multiple lines. It's called a Template Literal. Like this:
var multilineString = `One line of text
second line of text
third line of text
fourth line of text`;
Using the backtick works in NodeJS, and it's supported by Chrome, Firefox, Edge, Safari, and Opera.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Before your </form>
tag put:
{{ form_rest(form) }}
It will automatically insert other important (hidden) inputs.
Use ng-value
for set value of input box after clicking on a button
:
"input type="email" class="form-control" id="email2" ng-value="myForm.email2" placeholder="Email"
and
Set Value as:
$scope.myForm.email2 = $scope.names[0].success;
You might as well give a try to Tim Ruffle's drag-n-drop polyfill, certainly similar to Bernardo Castilho's one (see @remdevtec answer).
Simply do npm install mobile-drag-drop --save
(other installation methods available, e.g. with bower)
Then, any element interface relying on touch detection should work on mobile (e.g. dragging only an element, instead of scrolling + dragging at the same time).
It looks like the best way is to first do:
git clean
To delete all untracked files and then continue with the usual git pull
...
Situations where you want to insert a lot of items into anywhere but the end of a sequence repeatedly.
Check out the complexity guarantees for each different type of container:
What are the complexity guarantees of the standard containers?
Based on the link provided by @better_use_mkstemp, here's a fiddle where nested iframe resizes to fill parent div: http://jsfiddle.net/orlenko/HNyJS/
Html:
<div id="content">
<iframe src="http://www.microsoft.com" name="frame2" id="frame2" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto" onload="" allowtransparency="false"></iframe>
</div>
<div id="block"></div>
<div id="header"></div>
<div id="footer"></div>
Relevant parts of CSS:
div#content {
position: fixed;
top: 80px;
left: 40px;
bottom: 25px;
min-width: 200px;
width: 40%;
background: black;
}
div#content iframe {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
width: 100%;
}
If you use SQL authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"User Id=UserName;" +
"Password=Secret;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
If you use Windows authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
HTML:
<video
id="video-active"
class="video-active"
width="640"
height="390"
controls="controls">
<source src="myvideo.mp4" type="video/mp4">
</video>
<div id="current">0:00</div>
<div id="duration">0:00</div>
JavaScript:
$(document).ready(function(){
$("#video-active").on(
"timeupdate",
function(event){
onTrackedVideoFrame(this.currentTime, this.duration);
});
});
function onTrackedVideoFrame(currentTime, duration){
$("#current").text(currentTime); //Change #current to currentTime
$("#duration").text(duration)
}
Notes:
Every 15 to 250ms, or whenever the MediaController's media controller position changes, whichever happens least often, the user agent must queue a task to fire a simple event named timeupdate at the MediaController.
http://www.w3.org/TR/html5/embedded-content-0.html#media-controller-position
There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).
So use just font-family: Calibri
or, better, font-family: Calibri, sans-serif
. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)
It's actually something that can be done using a combination of the current stack-trace data, and reflection.
public void MyMethod()
{
StackTrace stackTrace = new System.Diagnostics.StackTrace();
StackFrame frame = stackTrace.GetFrames()[1];
MethodInfo method = frame.GetMethod();
string methodName = method.Name;
Type methodsClass = method.DeclaringType;
}
The 1
index on the StackFrame
array will give you the method which called MyMethod
Although some answers here maybe great, none helped my case (which is very similar to OP's error message).
This error needed fixing because even though my components rendered with their data (pulled from API), when deployed to firebase hosting, it did not render some of my components (the components that rely on data).
To fix it (and given you followed the suggestions in the accepted answer), in the Parent component (the ones pulling data and passing to child component), I did:
// pulled data in this life cycle hook, saving it to my store
created() {
FetchData.getProfile()
.then(myProfile => {
const mp = myProfile.data;
console.log(mp)
this.$store.dispatch('dispatchMyProfile', mp)
this.propsToPass = mp;
})
.catch(error => {
console.log('There was an error:', error.response)
})
}
// called my store here
computed: {
menu() {
return this.$store.state['myProfile'].profile
}
},
// then in my template, I pass this "menu" method in child component
<LeftPanel :data="menu" />
_x000D_
This cleared that error away. I deployed it again to firebase hosting, and viola!
Hope this bit helps you.
Thread.sleep()
takes in the number of milliseconds to sleep, not seconds.
Sleeping for one millisecond is not noticeable. Try Thread.sleep(1000)
to sleep for one second.
You can also use pytiff of which I'm the author.
import pytiff
with pytiff.Tiff("filename.tif") as handle:
part = handle[100:200, 200:400]
# multipage tif
with pytiff.Tiff("multipage.tif") as handle:
for page in handle:
part = page[100:200, 200:400]
It's a fairly small module and may not have as many features as other modules, but it supports tiled tiffs and bigtiff, so you can read parts of large images.
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
Usefull fallback here: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation
function orientationhandler(evt){
// For FF3.6+
if (!evt.gamma && !evt.beta) {
evt.gamma = -(evt.x * (180 / Math.PI));
evt.beta = -(evt.y * (180 / Math.PI));
}
// use evt.gamma, evt.beta, and evt.alpha
// according to dev.w3.org/geo/api/spec-source-orientation
}
window.addEventListener('deviceorientation', orientationhandler, false);
window.addEventListener('MozOrientation', orientationhandler, false);
in angular-2 attribute syntax is
<div [attr.role]="myAriaRole">
Binds attribute role to the result of expression myAriaRole.
so can use like
[attr.role]="myAriaRole ? true: null"
You can try disabling the "VirtualBox NDIS6 Bridged Networking Driver" on all but your actual physical network adapter(s) before attempting to create the VirtualBox host-only adapter again.
See this answer.
Simple Pass Intent first
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
And u will get picture path on u onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
if you are in Linux server exit from the server and re ssh
If the issue is a missing intermediate certificate, you can enable Oracle JRE to automatically download the missing intermediate certificate as explained in this answer.
Just set the Java system property -Dcom.sun.security.enableAIAcaIssuers=true
For this to work the server's certificate must provide the URI to the intermediate certificate (the certificate's issuer). As far as I can tell, this is what browsers do as well and should be just as secure - I'm not a security expert though.
Edit: If I recall correctly, this seems to work at least with Java 8 and is documented here for Java 9.
There are a few other choices in case the Adobe ActiveX isn't what you're looking for (since Acrobat must be present on the user machine and you can't ship it yourself).
For creating the PDF preview, first have a look at some other discussions on the subject on StackOverflow:
In the last two I talk about a few things you can try:
You can get a commercial renderer (PDFViewForNet, PDFRasterizer.NET, ABCPDF, ActivePDF, XpdfRasterizer and others in the other answers...).
Most are fairly expensive though, especially if all you care about is making a simple preview/thumbnails.
In addition to Omar Shahine's code snippet, there is a CodeProject article that shows how to use the Adobe ActiveX, but it may be out of date, easily broken by new releases and its legality is murky (basically it's ok for internal use but you can't ship it and you can't use it on a server to produce images of PDF).
You could have a look at the source code for SumatraPDF, an OpenSource PDF viewer for windows.
There is also Poppler, a rendering engine that uses Xpdf as a rendering engine. All of these are great but they will require a fair amount of commitment to make make them work and interface with .Net and they tend to be be distributed under the GPL.
You may want to consider using GhostScript as an interpreter because rendering pages is a fairly simple process.
The drawback is that you will need to either re-package it to install it with your app, or make it a pre-requisite (or at least a part of your install process).
It's not a big challenge, and it's certainly easier than having to massage the other rendering engines into cooperating with .Net.
I did a small project that you will find on the Developer Express forums as an attachment.
Be careful of the license requirements for GhostScript through.
If you can't leave with that then commercial software is probably your only choice.
Yes, the syntax is accurate and it should be fine.
Here is the SQL Fiddle Demo I created for your particular case
create table sample2
(
id int primary key,
created_date date,
data varchar(10)
)
insert into sample2 values (1,'2012-01-01','testing');
And here is how to select the data
SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())
This will work.
USE INFORMATION_SCHEMA;
SELECT TABLE_SCHEMA, TABLE_NAME
FROM information_schema.tables
WHERE TABLE_TYPE LIKE 'VIEW';
The two structs are different. When you initialize the first struct, about 40 bytes of memory are allocated. When you initialize the second struct, about 10 bytesof memory are allocated. (Actual amount is architecture dependent)
You can use the string literals (string constants) to initalize character arrays. This is why
person p = {"John", "Doe",30};
works in the first example.
You cannot assign (in the conventional sense) a string in C.
The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location. In your second example, you are merely copying the pointer to (location of) the string literal. Doing something like:
char* string = "Hello";
*string = 'C'
might cause compile or runtime errors (I am not sure.) It is a bad idea because you are modifying the literal string "Hello" which, for example on a microcontroler, could be located in read-only memory.
Your table will need to be created with a unique ID field that will ideally have the AUTO_INCREMENT attribute. example:
CREATE TABLE Persons
(
P_Id int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
PRIMARY KEY (P_Id)
)
Then you can access the 3rd record in this table with:
SELECT * FROM Persons WHERE P_Id = 3
Rising to @Ankan-Zerob's challenge, this is my estimate of the maximum length which can be stored in each text type measured in words:
Type | Bytes | English words | Multi-byte words
-----------+---------------+---------------+-----------------
TINYTEXT | 255 | ±44 | ±23
TEXT | 65,535 | ±11,000 | ±5,900
MEDIUMTEXT | 16,777,215 | ±2,800,000 | ±1,500,000
LONGTEXT | 4,294,967,295 | ±740,000,000 | ±380,000,000
In English, 4.8 letters per word is probably a good average (eg norvig.com/mayzner.html), though word lengths will vary according to domain (e.g. spoken language vs. academic papers), so there's no point being too precise. English is mostly single-byte ASCII characters, with very occasional multi-byte characters, so close to one-byte-per-letter. An extra character has to be allowed for inter-word spaces, so I've rounded down from 5.8 bytes per word. Languages with lots of accents such as say Polish would store slightly fewer words, as would e.g. German with longer words.
Languages requiring multi-byte characters such as Greek, Arabic, Hebrew, Hindi, Thai, etc, etc typically require two bytes per character in UTF-8. Guessing wildly at 5 letters per word, I've rounded down from 11 bytes per word.
CJK scripts (Hanzi, Kanji, Hiragana, Katakana, etc) I know nothing of; I believe characters mostly require 3 bytes in UTF-8, and (with massive simplification) they might be considered to use around 2 characters per word, so they would be somewhere between the other two. (CJK scripts are likely to require less storage using UTF-16, depending).
This is of course ignoring storage overheads etc.
To solve this, I opened httpd.conf
and changed the following line:
Allow from 127.0.0.1
to:
Allow from 127.0.0.1 ::1
The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.
Try using %lx
or %llx
. For more portability, include inttypes.h
and use the PRIx64
macro.
For example: printf("val = 0x%" PRIx64 "\n", val);
(note that it's string concatenation)
A COUNT query is faster, although maybe not noticeably, but as far as getting the desired result, both should be sufficient.
I am working on Win 8, use this code. It works for IE and FF, Opera, etc. What I understood are : woff font is light et common on Google fonts.
Go here to convert your ttf font to woff before.
@font-face
{
font-family:'Open Sans';
src:url('OpenSans-Regular.woff');
}
// GET: api/GetStudent
public Response Get() {
return StoredProcedure.GetStudent();
}
public static Response GetStudent() {
using (var db = new dal()) {
var student = db.Database.SqlQuery<GetStudentVm>("GetStudent").ToList();
return new Response {
Sucess = true,
Message = student.Count() + " Student found",
Data = student
};
}
}
Below you'll find a complete example that covers both iOS8 and iOS7 (and lower versions). Please note that prior to iOS8 you can't distinguish between "remote notifications disabled" and "only View in lockscreen enabled".
BOOL remoteNotificationsEnabled = false, noneEnabled,alertsEnabled, badgesEnabled, soundsEnabled;
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
// iOS8+
remoteNotificationsEnabled = [UIApplication sharedApplication].isRegisteredForRemoteNotifications;
UIUserNotificationSettings *userNotificationSettings = [UIApplication sharedApplication].currentUserNotificationSettings;
noneEnabled = userNotificationSettings.types == UIUserNotificationTypeNone;
alertsEnabled = userNotificationSettings.types & UIUserNotificationTypeAlert;
badgesEnabled = userNotificationSettings.types & UIUserNotificationTypeBadge;
soundsEnabled = userNotificationSettings.types & UIUserNotificationTypeSound;
} else {
// iOS7 and below
UIRemoteNotificationType enabledRemoteNotificationTypes = [UIApplication sharedApplication].enabledRemoteNotificationTypes;
noneEnabled = enabledRemoteNotificationTypes == UIRemoteNotificationTypeNone;
alertsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeAlert;
badgesEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeBadge;
soundsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeSound;
}
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
NSLog(@"Remote notifications enabled: %@", remoteNotificationsEnabled ? @"YES" : @"NO");
}
NSLog(@"Notification type status:");
NSLog(@" None: %@", noneEnabled ? @"enabled" : @"disabled");
NSLog(@" Alerts: %@", alertsEnabled ? @"enabled" : @"disabled");
NSLog(@" Badges: %@", badgesEnabled ? @"enabled" : @"disabled");
NSLog(@" Sounds: %@", soundsEnabled ? @"enabled" : @"disabled");
I had the same problem and just solved it. I had posted my own question on stackoverflow:
Can't PUT to my IHttpHandler, GET works fine
The solution was to set runManagedModulesForWebDavRequests to true in the modules element. My guess is that once you install WebDAV then all PUT requests are associated with it. If you need the PUT to go to your handler, you need to remove the WebDAV module and set this attribute to true.
<modules runManagedModulesForWebDavRequests="true">
...
</modules>
So if you're running into the problem when you use the PUT verb and you have installed WebDAV then hopefully this solution will fix your problem.
It's a little troublesome for retina screen, i use tkinter to get the fake size, use pilllow grab to get real size :
import tkinter
root = tkinter.Tk()
resolution_width = root.winfo_screenwidth()
resolution_height = root.winfo_screenheight()
image = ImageGrab.grab()
real_width, real_height = image.width, image.height
ratio_width = real_width / resolution_width
ratio_height = real_height/ resolution_height
There is a simple trick for this. After you constructed the frame with all it buttons do this:
frame.getRootPane().setDefaultButton(submitButton);
For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). When you hit enter in that frame, the ActionListeners their actionPerformed()
method will be invoked.
And the problem with your code as far as I see is that your dialog pops up every time you hit a key, because you didn't put it in the if-body. Try changing it to this:
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
System.out.println("Hello");
JOptionPane.showMessageDialog(null , "You've Submitted the name " + nameInput.getText());
}
}
UPDATE: I found what is wrong with your code. You are adding the key listener to the Submit button instead of to the TextField. Change your code to this:
SubmitButton listener = new SubmitButton(textBoxToEnterName);
textBoxToEnterName.addActionListener(listener);
submit.addKeyListener(listener);
You want to use:
Collections.<String>emptyList();
If you look at the source for what emptyList does you see that it actually just does a
return (List<T>)EMPTY_LIST;
std::cout.precision(2);
std::cout<<std::fixed;
when you are using operator overloading try this.
try using begin.startOf('isoWeek');
instead of begin.startOf('week');
With the multiplication, I recommend using the modulo operator (%) to determine which numbers divide evenly into the target number like:
$factors = array();
for($i = 0; $i < $target; $i++){
if($target % $i == 0){
$temp = array()
$a = $i;
$b = $target / $i;
$temp["a"] = $a;
$temp["b"] = $b;
$temp["index"] = $i;
array_push($factors, $temp);
}
}
This would leave you with an array of factors of the target number.
Assuming that you have access to Prototype, this could work. I wrote this code for myself just a few minutes ago; I only needed a single key at a time, so this isn't time efficient for big lists of key:value pairs or for spitting out multiple key names.
function key(int) {
var j = -1;
for(var i in this) {
j++;
if(j==int) {
return i;
} else {
continue;
}
}
}
Object.prototype.key = key;
This is numbered to work the same way that arrays do, to save headaches. In the case of your code:
buttons.key(0) // Should result in "button1"
I had a similar issue and ended up hooking and event
ng-change="changeCount()"
then:
self.changeCount = function () {
if (!self.info.itemcount) {
self.info.itemcount = 1;
}
};
So the user is defaulted to 1 if a invalid number is inserted.
The script element that loads the API is missing the required authentication parameter. If you are using the standard Maps JavaScript API, you must use a key parameter with a valid API key. If you are a Premium Plan customer, you must use either a client parameter with your client ID or a key parameter with a valid API key.
See the guide to API keys and client IDs.
Another trigger for this error is leaving the "." out before your "otherwise" or any other route in your route definition:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/view1', {
templateUrl: 'partials/view1.html',
controller: 'Ctrl1'
}).
otherwise({
redirectTo: '/viewCounts'
});
}]);
Mortified by a full-stop, yet again. Gotta love JS!
Using only "native" Windows utilities, try the following, where "516" is the process ID that you want the image name for:
for /f "delims=," %a in ( 'tasklist /fi "PID eq 516" /nh /fo:csv' ) do ( echo %~a )
for /f %a in ( 'tasklist /fi "PID eq 516" ^| findstr "516"' ) do ( echo %a )
Or you could use wmic (the Windows Management Instrumentation Command-line tool) and get the full path to the executable:
wmic process where processId=516 get name
wmic process where processId=516 get ExecutablePath
Or you could download Microsoft PsTools, or specifically download just the pslist utility, and use PsList:
for /f %a in ( 'pslist 516 ^| findstr "516"' ) do ( echo %a )
<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic"
ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>
One should definitely prefer the solutions already posted, but since no one mentioned this solution yet, I think it is worth mentioning for completeness.
The @classmethod
approach can be modified to provide an alternative constructor which does not invoke the default constructor (__init__
). Instead, an instance is created using __new__
.
This could be used if the type of initialization cannot be selected based on the type of the constructor argument, and the constructors do not share code.
Example:
class MyClass(set):
def __init__(self, filename):
self._value = load_from_file(filename)
@classmethod
def from_somewhere(cls, somename):
obj = cls.__new__(cls) # Does not call __init__
super(MyClass, obj).__init__() # Don't forget to call any polymorphic base class initializers
obj._value = load_from_somewhere(somename)
return obj
The answer of Bas can get you in memorytrouble theoretically, since ShowDialog won't be disposed. I think this is a more proper way. Also mention the textLabel being readable with longer text.
public class Prompt : IDisposable
{
private Form prompt { get; set; }
public string Result { get; }
public Prompt(string text, string caption)
{
Result = ShowDialog(text, caption);
}
//use a using statement
private string ShowDialog(string text, string caption)
{
prompt = new Form()
{
Width = 500,
Height = 150,
FormBorderStyle = FormBorderStyle.FixedDialog,
Text = caption,
StartPosition = FormStartPosition.CenterScreen,
TopMost = true
};
Label textLabel = new Label() { Left = 50, Top = 20, Text = text, Dock = DockStyle.Top, TextAlign = ContentAlignment.MiddleCenter };
TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.OK };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.AcceptButton = confirmation;
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
}
public void Dispose()
{
//See Marcus comment
if (prompt != null) {
prompt.Dispose();
}
}
}
Implementation:
using(Prompt prompt = new Prompt("text", "caption")){
string result = prompt.Result;
}
Maybe you can use arrow function (ES6+) or the simple old function declaration.
Normal function declaration type (Not ES6+):
<link href="#" onClick={function(event){ func1(event); func2();}}>Trigger here</link>
Anonymous function or arrow function type (ES6+)
<link href="#" onClick={(event) => { func1(event); func2();}}>Trigger here</link>
The second one is the shortest road that I know. Hope it helps you!
directry cannot simply delete if it has the files so you may need to delete the files inside first and then directory
public class DeleteFileFolder {
public DeleteFileFolder(String path) {
File file = new File(path);
if(file.exists())
{
do{
delete(file);
}while(file.exists());
}else
{
System.out.println("File or Folder not found : "+path);
}
}
private void delete(File file)
{
if(file.isDirectory())
{
String fileList[] = file.list();
if(fileList.length == 0)
{
System.out.println("Deleting Directory : "+file.getPath());
file.delete();
}else
{
int size = fileList.length;
for(int i = 0 ; i < size ; i++)
{
String fileName = fileList[i];
System.out.println("File path : "+file.getPath()+" and name :"+fileName);
String fullPath = file.getPath()+"/"+fileName;
File fileOrFolder = new File(fullPath);
System.out.println("Full Path :"+fileOrFolder.getPath());
delete(fileOrFolder);
}
}
}else
{
System.out.println("Deleting file : "+file.getPath());
file.delete();
}
}
Go to app.module.ts
import import { HttpClientModule } from '@angular/common/http';
AND
Add HttpClientModule
under imports
should look like this
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,HttpClientModule]
I am using Jupyter-notebook. And in my case, it was showing the file in the wrong format. The 'encoding' option was not working. So I save the csv in utf-8 format, and it works.
I don't think there is anything built-in, but you can do it by leaving more space above your axes and using figtext
:
axes([.1,.1,.8,.7])
figtext(.5,.9,'Foo Bar', fontsize=18, ha='center')
figtext(.5,.85,'Lorem ipsum dolor sit amet, consectetur adipiscing elit',fontsize=10,ha='center')
ha
is short for horizontalalignment
.
I am using below script to extact all folder path:
Get-ChildItem -path "C:\" -Recurse -Directory -Force -ErrorAction SilentlyContinue | Select-Object FullName | Out-File "Folder_List.csv"
Full folder path is not coming. After 113 characters, is coming:
Example - C:\ProgramData\Microsoft\Windows\DeviceMetadataCache\dmrccache\en-US\ec4d5fdd-aa12-400f-83e2-7b0ea6023eb7\Windows...
Look in the file Microsoft.Common.targets
The answer to the question is in the file Microsoft.Common.targets
for your target framework version.
For .Net Framework version 4.0 (and 4.5 !) the AssemblySearchPaths-element is defined like this:
<!--
The SearchPaths property is set to find assemblies in the following order:
(1) Files from current project - indicated by {CandidateAssemblyFiles}
(2) $(ReferencePath) - the reference path property, which comes from the .USER file.
(3) The hintpath from the referenced item itself, indicated by {HintPathFromItem}.
(4) The directory of MSBuild's "target" runtime from GetFrameworkPath.
The "target" runtime folder is the folder of the runtime that MSBuild is a part of.
(5) Registered assembly folders, indicated by {Registry:*,*,*}
(6) Legacy registered assembly folders, indicated by {AssemblyFolders}
(7) Resolve to the GAC.
(8) Treat the reference's Include as if it were a real file name.
(9) Look in the application's output folder (like bin\debug)
-->
<AssemblySearchPaths Condition=" '$(AssemblySearchPaths)' == ''">
{CandidateAssemblyFiles};
$(ReferencePath);
{HintPathFromItem};
{TargetFrameworkDirectory};
{Registry:$(FrameworkRegistryBase),$(TargetFrameworkVersion),$(AssemblyFoldersSuffix)$(AssemblyFoldersExConditions)};
{AssemblyFolders};
{GAC};
{RawFileName};
$(OutDir)
</AssemblySearchPaths>
For .Net Framework 3.5 the definition is the same, but the comment is wrong. The 2.0 definition is slightly different, it uses $(OutputPath) instead of $(OutDir).
On my machine I have the following versions of the file Microsoft.Common.targets:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework64\v3.5\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Common.targets
This is with Visual Studio 2008, 2010 and 2013 installed on Windows 7.
The fact that the output directory is searched can be a bit frustrating (as the original poster points out) because it may hide an incorrect HintPath. The solution builds OK on your local machine, but breaks when you build on in a clean folder structure (e.g. on the build machine).
Just FYI:
html should be table & width:100%. span should be margin: auto;
C and C++ take a very abstract view of I/O, and there is no standard way of doing what you want. There are standard ways to get characters from the standard input stream, if there are any to get, and nothing else is defined by either language. Any answer will therefore have to be platform-specific, perhaps depending not only on the operating system but also the software framework.
There's some reasonable guesses here, but there's no way to answer your question without knowing what your target environment is.
As I understand it, loadData()
simply generates a data:
URL with the data provide it.
Read the javadocs for loadData()
:
If the value of the encoding parameter is 'base64', then the data must be encoded as base64. Otherwise, the data must use ASCII encoding for octets inside the range of safe URL characters and use the standard %xx hex encoding of URLs for octets outside that range. For example, '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.
The 'data' scheme URL formed by this method uses the default US-ASCII charset. If you need need to set a different charset, you should form a 'data' scheme URL which explicitly specifies a charset parameter in the mediatype portion of the URL and call loadUrl(String) instead. Note that the charset obtained from the mediatype portion of a data URL always overrides that specified in the HTML or XML document itself.
Therefore, you should either use US-ASCII and escape any special characters yourself, or just encode everything using Base64. The following should work, assuming you use UTF-8 (I haven't tested this with latin1):
String data = ...; // the html data
String base64 = android.util.Base64.encodeToString(data.getBytes("UTF-8"), android.util.Base64.DEFAULT);
webView.loadData(base64, "text/html; charset=utf-8", "base64");
Django database objects use the same save() method for creating and changing objects.
obj = Product.objects.get(pk=pk)
obj.name = "some_new_value"
obj.save()
How Django knows to UPDATE vs. INSERT
If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT.
Ref.: https://docs.djangoproject.com/en/1.9/ref/models/instances/
By exporting the SPARK path and the Py4j path, it started to work:
export SPARK_HOME=/usr/local/Cellar/apache-spark/1.5.1
export PYTHONPATH=$SPARK_HOME/libexec/python:$SPARK_HOME/libexec/python/build:$PYTHONPATH
PYTHONPATH=$SPARK_HOME/python/lib/py4j-0.8.2.1-src.zip:$PYTHONPATH
export PYTHONPATH=$SPARK_HOME/python:$SPARK_HOME/python/build:$PYTHONPATH
So, if you don't want to type these everytime you want to fire up the Python shell, you might want to add it to your .bashrc
file
To stop executing java code just use this command:
System.exit(1);
After this command java stops immediately!
for example:
int i = 5;
if (i == 5) {
System.out.println("All is fine...java programm executes without problem");
} else {
System.out.println("ERROR occured :::: java programm has stopped!!!");
System.exit(1);
}
$('#divId > input, #divId > select, #divId > textarea').serialize();
If APEX_UTIL
is not available, you have a solution using REGEXP_SUBSTR()
.
Inspired from http://nuijten.blogspot.fr/2009/07/splitting-comma-delimited-string-regexp.html :
DECLARE
I INTEGER;
TYPE T_ARRAY_OF_VARCHAR IS TABLE OF VARCHAR2(2000) INDEX BY BINARY_INTEGER;
MY_ARRAY T_ARRAY_OF_VARCHAR;
MY_STRING VARCHAR2(2000) := '123,456,abc,def';
BEGIN
FOR CURRENT_ROW IN (
with test as
(select MY_STRING from dual)
select regexp_substr(MY_STRING, '[^,]+', 1, rownum) SPLIT
from test
connect by level <= length (regexp_replace(MY_STRING, '[^,]+')) + 1)
LOOP
DBMS_OUTPUT.PUT_LINE(CURRENT_ROW.SPLIT);
MY_ARRAY(MY_ARRAY.COUNT) := CURRENT_ROW.SPLIT;
END LOOP;
END;
/
I am using phpMyAdmin Server version: 5.1.41.
It offers possibility for view sql history through phpmyadmin.pma_history
table.
You can search your query in this table.
pma_history
table has below structure:
There is another solution, if you have binary logs active on your server you can use mysqlbinlog
generate a sql file with it
mysqlbinlog binary_log_file > query_log.sql
then search for your missing rows. If you don't have it active, no other solution. Make backups next time.
As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:
TSKILL processName
or
TSKILL PID
Have on mind that processName
should not have the .exe
suffix and is limited to 18 characters.
Another option is WMIC
:
wmic Path win32_process Where "Caption Like 'MyProcess.exe'" Call Terminate
wmic offer even more flexibility than taskkill .With wmic Path win32_process get
you can see the available fileds you can filter.
This is how you do it:
function view($view)
{
$ms = Person::where('name', '=', 'Foo Bar')->first();
$persons = Person::order_by('list_order', 'ASC')->get();
return $view->with('persons', $persons)->with('ms', $ms);
}
You can also use compact():
function view($view)
{
$ms = Person::where('name', '=', 'Foo Bar')->first();
$persons = Person::order_by('list_order', 'ASC')->get();
return $view->with(compact('persons', 'ms'));
}
Or do it in one line:
function view($view)
{
return $view
->with('ms', Person::where('name', '=', 'Foo Bar')->first())
->with('persons', Person::order_by('list_order', 'ASC')->get());
}
Or even send it as an array:
function view($view)
{
$ms = Person::where('name', '=', 'Foo Bar')->first();
$persons = Person::order_by('list_order', 'ASC')->get();
return $view->with('data', ['ms' => $ms, 'persons' => $persons]));
}
But, in this case, you would have to access them this way:
{{ $data['ms'] }}
You can use mmc:
At that point you will be able to manage services as if they were on your local machine.
As an illustration
import fs from 'fs';
import http from 'http';
const options = {
host: 'www.stackoverflow.com',
port: 80,
path: '/index.html'
};
describe('deferredExecution', () => {
it('deferredExecution', (done) => {
console.log('Start');
setTimeout(() => console.log('TO1'), 0);
setImmediate(() => console.log('IM1'));
process.nextTick(() => console.log('NT1'));
setImmediate(() => console.log('IM2'));
process.nextTick(() => console.log('NT2'));
http.get(options, () => console.log('IO1'));
fs.readdir(process.cwd(), () => console.log('IO2'));
setImmediate(() => console.log('IM3'));
process.nextTick(() => console.log('NT3'));
setImmediate(() => console.log('IM4'));
fs.readdir(process.cwd(), () => console.log('IO3'));
console.log('Done');
setTimeout(done, 1500);
});
});
will give the following output
Start
Done
NT1
NT2
NT3
TO1
IO2
IO3
IM1
IM2
IM3
IM4
IO1
I hope this can help to understand the difference.
Updated:
Callbacks deferred with
process.nextTick()
run before any other I/O event is fired, while with setImmediate(), the execution is queued behind any I/O event that is already in the queue.Node.js Design Patterns, by Mario Casciaro (probably the best book about node.js/js)
HTML input number type allows "e/E" because "e" stands for exponential which is a numeric symbol.
Example 200000 can also be written as 2e5. I hope this helps thank you for the question.
The big difference is perfectly explained here.
Basically, lightweight tags are just pointers to specific commits. No further information is saved; on the other hand, annotated tags are regular objects, which have an author and a date and can be referred because they have their own SHA key.
If knowing who tagged what and when is relevant for you, then use annotated tags. If you just want to tag a specific point in your development, no matter who and when did that, then lightweight tags are good enough.
Normally you'd go for annotated tags, but it is really up to the Git master of the project.
actually you shouldn't specify port in the host name. Mysql has special option for port (if port differs from default)
kind of
mysql --host=192.168.1.2 --port=3306
This change only first handle in multihandle slider. In apiDoc you can see:"For example, if you specify values: [ 1, 5, 18 ] and create one custom handle, the plugin will create the other two."
You cannot do the reversal without at least some extra data structure. I think the smallest structure would be a single character as a buffer while you swap letters. It can still be considered "in place", but it's not completely "extra data structure free".
Below is code implementing what Bill the Lizard describes:
string words = "this is a test";
// Reverse the entire string
for(int i = 0; i < strlen(words) / 2; ++i) {
char temp = words[i];
words[i] = words[strlen(words) - i];
words[strlen(words) - i] = temp;
}
// Reverse each word
for(int i = 0; i < strlen(words); ++i) {
int wordstart = -1;
int wordend = -1;
if(words[i] != ' ') {
wordstart = i;
for(int j = wordstart; j < strlen(words); ++j) {
if(words[j] == ' ') {
wordend = j - 1;
break;
}
}
if(wordend == -1)
wordend = strlen(words);
for(int j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
char temp = words[j];
words[j] = words[wordend - (j - wordstart)];
words[wordend - (j - wordstart)] = temp;
}
i = wordend;
}
}
.label:after{_x000D_
content:'ADD';_x000D_
}_x000D_
.label:hover:after{_x000D_
content:'NEW';_x000D_
}
_x000D_
<span class="label"></span>
_x000D_
psql -U username -d mydatabase -c 'SELECT * FROM mytable'
If you're new to postgresql and unfamiliar with using the command line tool psql
then there is some confusing behaviour you should be aware of when you've entered an interactive session.
For example, initiate an interactive session:
psql -U username mydatabase
mydatabase=#
At this point you can enter a query directly but you must remember to terminate the query with a semicolon ;
For example:
mydatabase=# SELECT * FROM mytable;
If you forget the semicolon then when you hit enter you will get nothing on your return line because psql
will be assuming that you have not finished entering your query. This can lead to all kinds of confusion. For example, if you re-enter the same query you will have most likely create a syntax error.
As an experiment, try typing any garble you want at the psql prompt then hit enter. psql
will silently provide you with a new line. If you enter a semicolon on that new line and then hit enter, then you will receive the ERROR:
mydatabase=# asdfs
mydatabase=# ;
ERROR: syntax error at or near "asdfs"
LINE 1: asdfs
^
The rule of thumb is:
If you received no response from psql
but you were expecting at least SOMETHING, then you forgot the semicolon ;
You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:
ErrorDocument 404 /index.php
An error page redirect must be relative to root so you cannot use www.mydomain.com.
If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.
Mod Rewrite Reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
Lets go through basic definition of typedef. typedef use to define an alias to an existing data type either it is user defined or inbuilt.
typedef <data_type> <alias>;
for example
typedef int scores;
scores team1 = 99;
Confusion here is with the self referential structure, due to a member of same data type which is not define earlier. So In standard way you can write your code as :-
//View 1
typedef struct{ bool isParent; struct Cell* child;} Cell;
//View 2
typedef struct{
bool isParent;
struct Cell* child;
} Cell;
//Other Available ways, define stucture and create typedef
struct Cell {
bool isParent;
struct Cell* child;
};
typedef struct Cell Cell;
But last option increase some extra lines and words with usually we don't want to do (we are so lazy you know ;) ) . So prefer View 2.
Literal 0
is of type int
and you can't assign int
to std::string
. Use mValue.clear()
or assign an empty string mValue=""
.
On the i/o 2019 the following solution was presented:
/**
* Blurs the given Bitmap image
* @param bitmap Image to blur
* @param applicationContext Application context
* @return Blurred bitmap image
*/
@WorkerThread
fun blurBitmap(bitmap: Bitmap, applicationContext: Context): Bitmap {
lateinit var rsContext: RenderScript
try {
// Create the output bitmap
val output = Bitmap.createBitmap(
bitmap.width, bitmap.height, bitmap.config)
// Blur the image
rsContext = RenderScript.create(applicationContext, RenderScript.ContextType.DEBUG)
val inAlloc = Allocation.createFromBitmap(rsContext, bitmap)
val outAlloc = Allocation.createTyped(rsContext, inAlloc.type)
val theIntrinsic = ScriptIntrinsicBlur.create(rsContext, Element.U8_4(rsContext))
theIntrinsic.apply {
setRadius(10f)
theIntrinsic.setInput(inAlloc)
theIntrinsic.forEach(outAlloc)
}
outAlloc.copyTo(output)
return output
} finally {
rsContext.finish()
}
}
dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
dicts[i] = values[i]
print(dicts)
alternatively
In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
This works if you are on ubuntu/trusty64 box:
vagrant ssh
Once you are in the ubuntu box:
sudo su
Now you are root user. You can update root password as shown below:
sudo -i
passwd
Now edit the below line in the file /etc/ssh/sshd_config
PermitRootLogin yes
Also, it is convenient to create your own alternate username:
adduser johndoe
Wait until it asks for password.
This should work with this :
var cnt = $("#div1 p").length;
switch (true) {
case (cnt >= 10 && cnt <= 20):
alert('10');
break;
case (cnt >= 21 && cnt <= 30):
alert('21');
break;
case (cnt >= 31 && cnt <= 40):
break;
default:
alert('>41');
}
For percise time measurements (like GetTickCount), also take a look at mach_absolute_time and this Apple Q&A: http://developer.apple.com/qa/qa2004/qa1398.html.
You can extend jQuery functionalities like this:
jQuery.fn.extend({
scrollToMe: function () {
var x = jQuery(this).offset().top - 100;
jQuery('html,body').animate({scrollTop: x}, 500);
}});
and then:
$('...').scrollToMe();
easy ;-)
If your <option>
elements don't have value
attributes, then you can just use .val
:
$selectElement.val("text_you're_looking_for")
However, if your <option>
elements have value attributes, or might do in future, then this won't work, because whenever possible .val
will select an option by its value
attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value
attributes, so we'll have to add one ourselves with a simple plugin:
/*
Source: https://stackoverflow.com/a/16887276/1709587
Usage instructions:
Call
jQuery('#mySelectElement').selectOptionWithText('target_text');
to select the <option> element from within #mySelectElement whose text content
is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
return this.each(function () {
var $selectElement, $options, $targetOption;
$selectElement = jQuery(this);
$options = $selectElement.find('option');
$targetOption = $options.filter(
function () {return jQuery(this).text() == targetText}
);
// We use `.prop` if it's available (which it should be for any jQuery
// versions above and including 1.6), and fall back on `.attr` (which
// was used for changing DOM properties in pre-1.6) otherwise.
if ($targetOption.prop) {
$targetOption.prop('selected', true);
}
else {
$targetOption.attr('selected', 'true');
}
});
}
Just include this plugin somewhere after you add jQuery onto the page, and then do
jQuery('#someSelectElement').selectOptionWithText('Some Target Text');
to select options.
The plugin method uses filter
to pick out only the option
matching the targetText, and selects it using either .attr
or .prop
, depending upon jQuery version (see .prop() vs .attr() for explanation).
Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/
Read about the super keyword (Scroll down the Subclass Constructors). If I understand your question, you probably want to call a superclass constructor?
It is worth noting that the Java compiler will automatically put in a no-arg constructor call to the superclass if you do not explicitly invoke a superclass constructor.
For people searching for 403 forbidden issue while trying to upload in multipart form the below might help as there is a case depending on the server configuration that you will get MULTIPART_STRICT_ERROR "!@eq 0" due to incorrect MultipartFormDataContent headers. Please note that both imagetag/filename variables include quotations (\") eg filename="\"myfile.png\"" .
MultipartFormDataContent form = new MultipartFormDataContent();
ByteArrayContent imageContent = new ByteArrayContent(fileBytes, 0, fileBytes.Length);
imageContent.Headers.TryAddWithoutValidation("Content-Disposition", "form-data; name="+imagetag+"; filename="+filename);
imageContent.Headers.TryAddWithoutValidation("Content-Type", "image / png");
form.Add(imageContent, imagetag, filename);
If you don't want to open Android Studio just to modify your path...
${HOME}/Library/Android/sdk/tools
${HOME}/Library/Android/sdk/platform-tools
.bashwhatever
export PATH="${HOME}/Library/Android/sdk/tools:${HOME}/Library/Android/sdk/platform-tools:${PATH}"
Here is a simple mathed to pass values from a route provider
//Route Provider
$routeProvider.when("/page/:val1/:val2/:val3",{controller:pageCTRL, templateUrl: 'pages.html'});
//Controller
$http.get( 'page.php?val1='+$routeParams.val1 +'&val2='+$routeParams.val2 +'&val3='+$routeParams.val3 , { cache: true})
.then(function(res){
//....
})
Write a new function for settimeout. Pls try this.
class CowtanApp extends Component {
constructor(props){
super(props);
this.state = {
timePassed: false
};
}
componentDidMount() {
this.setTimeout( () => {
this.setTimePassed();
},1000);
}
setTimePassed() {
this.setState({timePassed: true});
}
render() {
if (!this.state.timePassed){
return <LoadingPage/>;
}else{
return (
<NavigatorIOS
style = {styles.container}
initialRoute = {{
component: LoginPage,
title: 'Sign In',
}}/>
);
}
}
}
This seems like a protocol version mismatch, this exception normally happens when there is a mismatch between SSL protocol version used by the client and the server. your clients should use a proctocol version supported by the server.
Use the following function
window.scrollTo(xpos, ypos)
Here xpos is Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels
ypos is also Required. The coordinate to scroll to, along the y-axis (vertical), in pixels
//prompts for input in javascript
test=prompt("Enter a value?","some string");
//passes javascript to a hidden field.
document.getElementById('myField').value = test;
//prompts for input in javascript
test2=prompt("Enter a value?","some string2");
//passes javascript to a hidden field
document.getElementById('myField').value = test2;
//prints output
document.write("hello, "+test+test2;
now this is confusing but this should work...
Please find below example to load image using JavaFX.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class LoadImage extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Load Image");
StackPane sp = new StackPane();
Image img = new Image("javafx.jpg");
ImageView imgView = new ImageView(img);
sp.getChildren().add(imgView);
//Adding HBox to the scene
Scene scene = new Scene(sp);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Create one source folder with name Image in your project and add your image to that folder otherwise you can directly load image from external URL like following.
Image img = new Image("http://mikecann.co.uk/wp-content/uploads/2009/12/javafx_logo_color_1.jpg");
If your only goal by removing the listeners is to stop them from running, you can add an event listener to the window capturing and canceling all events of the given type:
window.addEventListener(type, function (event) {
event.stopPropagation();
}, true);
Passing in true
for the third parameter causes the event to be captured on the way down. Stopping propagation means that the event never reaches the listeners that are listening for it.
Keep in mind though that this has very limited use as you can't add new listeners for the given type (they will all be blocked). There are ways to get around this somewhat, e.g., by firing a new kind of event that only your listeners would know to listen for. Here is how you can do that:
window.addEventListener('click', function (event) {
// (note: not cross-browser)
var event2 = new CustomEvent('click2', {detail: {original: event}});
event.target.dispatchEvent(event2);
event.stopPropagation();
}, true);
element.addEventListener('click2', function(event) {
event = event.detail && event.detail.original ?
event.detail.original :
event;
// ... do something with event ...
});
However, note that this may not work as well for fast events like mousemove, given that the re-dispatching of the event introduces a delay.
Better would be to just keep track of the listeners added in the first place, as outlined in Martin Wantke's answer, if you need to do this.
I was finally able to get this to work for my needs.
The old voted up code does not run on windows 10 system (at least not mine). The referenced MS library link below provides current examples on how to make this work. My example uses them with late bindings.
https://docs.microsoft.com/en-us/windows/win32/shell/folder-getdetailsof.
The attribute codes were different on my computer and like someone mentioned above most return blank values even if they are not. I used a for loop to cycle through all of them and found out that Title and Subject can still be accessed which is more then enough for my purposes.
Private Sub MySubNamek()
Dim objShell As Object 'Shell
Dim objFolder As Object 'Folder
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace("E:\MyFolder")
If (Not objFolder Is Nothing) Then
Dim objFolderItem As Object 'FolderItem
Set objFolderItem = objFolder.ParseName("Myfilename.txt")
For i = 0 To 288
szItem = objFolder.GetDetailsOf(objFolderItem, i)
Debug.Print i & " - " & szItem
Next
Set objFolderItem = Nothing
End If
Set objFolder = Nothing
Set objShell = Nothing
End Sub
In Java, all strings are immutable. When you are trying to modify a String
, what you are really doing is creating a new one. However, when you use a StringBuilder
, you are actually modifying the contents, instead of creating a new one.
Use a normal blue border
, a medium border-radius
, and a blue box-shadow
with position 0 0
.
Just use:
<TextBlock Text="{Binding Date, StringFormat=\{0:d\}}" />
onchange
will work only if the value of the textbox changed compared to the value it had before, so for the first time it won't work because the state didn't change.
So it is better to use onblur
event or on submitting the form.
function checkTextField(field) {_x000D_
document.getElementById("error").innerText =_x000D_
(field.value === "") ? "Field is empty." : "Field is filled.";_x000D_
}
_x000D_
<input type="text" onblur="checkTextField(this);" />_x000D_
<p id="error"></p>
_x000D_
I would recommend using https://quickconverter.codeplex.com/
Inverting a boolean is then as simple as:
<Button IsEnabled="{qc:Binding '!$P', P={Binding IsReadOnly}}" />
That speeds the time normally needed to write converters.
You can do it quite easily with (introduced in PostgreSQL 8.2) VALUES (), ().
Syntax will be like this:
select c.*
from comments c
join (
values
(1,1),
(3,2),
(2,3),
(4,4)
) as x (id, ordering) on c.id = x.id
order by x.ordering
Set the CSS position: relative;
on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:
position: absolute;
bottom: 0;
right: 0;
If you need to space the text farther away from the edge, you could change 0
to 2px
or similar.
do like this simply: (as said in comment here is with example with two methods)
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: `
<button (click)="checkEvent($event,'a')" id="abc" class="def">Display Toastr</button>
<button (click)="checkEvent($event,'b')" id="abc1" class="def1">Display Toastr1</button>
`
})
export class AppComponent {
checkEvent(event, id){
console.log(event, id, event.srcElement.attributes.id);
}
}
If you could provide some reason as to why you need to replace the label with a div, that would certainly help...
Also, could you paste a sample that'd be helpful ( http://dpaste.com/ or http://pastebin.com/)
I was using Spring Tool Suite 4. Not able to figure out the issue. The directory structure was according to the package name.
But cleaning the project helped me.
It is not related with Firewall. I had the same issue accessing from office and from mobile. I cleaned the cookies and worked fine. You can read more at https://support.google.com/chromebook/answer/1085581?hl=en
How about this:
import unicodedata
def strip_accents(s):
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
This works on greek letters, too:
>>> strip_accents(u"A \u00c0 \u0394 \u038E")
u'A A \u0394 \u03a5'
>>>
The character category "Mn" stands for Nonspacing_Mark
, which is similar to unicodedata.combining in MiniQuark's answer (I didn't think of unicodedata.combining, but it is probably the better solution, because it's more explicit).
And keep in mind, these manipulations may significantly alter the meaning of the text. Accents, Umlauts etc. are not "decoration".
I think this is what you're looking for...
>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy
>>> dt
datetime.datetime(2011, 3, 29, 0, 0)
But if you really don't care about the time aspect of things, then you should really only be passing around date
objects...
>>> d_truncated = datetime.date(dt.year, dt.month, dt.day)
>>> d_truncated
datetime.date(2011, 3, 29)
As far as I understand, you have more than one form tag in your web page that causes the problem. Make sure you have only one server-side form tag for each page.
One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get
public class PageViewModel : IHandle<SomeMessage>
{
...
public async void Handle(SomeMessage message)
{
ShowLoadingAnimation();
// makes UI very laggy, but still not dead
await this.contentLoader.LoadContentAsync();
HideLoadingAnimation();
}
}
public class ContentLoader
{
public async Task LoadContentAsync()
{
var tasks = new List<Task>();
tasks.Add(DoCpuBoundWorkAsync());
tasks.Add(DoIoBoundWorkAsync());
tasks.Add(DoCpuBoundWorkAsync());
tasks.Add(DoSomeOtherWorkAsync());
await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.
You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?
Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.
No multi-line comments in R as of version 2.12 and unlikely to change. In most environments, you can comment blocks by highlighting and toggle-comment. In emacs, this is 'M-x ;'.
You may want to use the Continue
statement to continue with the innermost loop.
Excerpt from PowerShell
help file:
In a script, the
continue
statement causes program flow to move immediately to the top of the innermost loop controlled by any of these statements:
for
foreach
while
Also for anyone using properties such as Props or Refs without your "DocgetId's" then you can:
("" as HTMLInputElement).value;
Where the inverted quotes is your props value so an example would be like so:
var val = (this.refs.newText as HTMLInputElement).value;
alert("Saving this:" + val);
Definitely Docker for the win!
As you may know Vagrant is for virtual machine management whereas Docker is for software containers management. If you are not aware of the difference, here is: A software container can share the same machine and kernel with other software containers. Using containers you save money because you don't waste resources on multiple operating systems (kernels), you can pack more software per server keeping a good degree of isolation.
Of course is a new discipline to care with its own pitfals and challenges.
Go for Docker Swarm if your requirements cross the single machine resources limit.
Sometimes you don't want to join multiple filters together like this:
def your_dynamic_query_generator(self, event: Event):
qs \
.filter(shiftregistrations__event=event) \
.filter(shiftregistrations__shifts=False)
And the following code would actually not return the correct thing.
def your_dynamic_query_generator(self, event: Event):
return Q(shiftregistrations__event=event) & Q(shiftregistrations__shifts=False)
What you can do now is to use an annotation count-filter.
In this case we count all shifts which belongs to a certain event.
qs: EventQuerySet = qs.annotate(
num_shifts=Count('shiftregistrations__shifts', filter=Q(shiftregistrations__event=event))
)
Afterwards you can filter by annotation.
def your_dynamic_query_generator(self):
return Q(num_shifts=0)
This solution is also cheaper on large querysets.
Hope this helps.
Use \1
instead of $1
.
\number Matches the contents of the group of the same number.
http://docs.python.org/library/re.html#regular-expression-syntax
Always use the prop()
method to enable or disable elements when using jQuery (see below for why).
In your case, it would be:
$("#edit").click(function(event){
event.preventDefault();
$('.inputDisabled').prop("disabled", false); // Element(s) are now enabled.
});
Why use
prop()
when you could useattr()
/removeAttr()
to do this?
Basically, prop()
should be used when getting or setting properties (such as autoplay
, checked
, disabled
and required
amongst others).
By using removeAttr()
, you are completely removing the disabled
attribute itself - while prop()
is merely setting the property's underlying boolean value to false.
While what you want to do can be done using attr()
/removeAttr()
, it doesn't mean it should be done (and can cause strange/problematic behaviour, as in this case).
The following extracts (taken from the jQuery documentation for prop()) explain these points in greater detail:
"The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the
.attr()
method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the.prop()
method provides a way to explicitly retrieve property values, while.attr()
retrieves attributes.""Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the
value
property of input elements, thedisabled
property of inputs and buttons, or thechecked
property of a checkbox. The.prop()
method should be used to setdisabled
andchecked
instead of the.attr()
method. The.val()
method should be used for getting and settingvalue
."
Use the following
recognizer = **cv2.face.LBPHFaceRecognizer_create()**
After you install:
pip install opencv-contrib-python
If using anaconda then in anaconda prompt:
conda install pip
then
pip install opencv-contrib-python
Separate your rules with a semi colon in a single declaration:
<span style="color:blue;font-style:italic">Test</span>
As mentioned in other answers, you'll always get the QuotaExceededError in Safari Private Browser Mode on both iOS and OS X when localStorage.setItem
(or sessionStorage.setItem
) is called.
One solution is to do a try/catch or Modernizr check in each instance of using setItem
.
However if you want a shim that simply globally stops this error being thrown, to prevent the rest of your JavaScript from breaking, you can use this:
https://gist.github.com/philfreo/68ea3cd980d72383c951
// Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem
// throw QuotaExceededError. We're going to detect this and just silently drop any calls to setItem
// to avoid the entire page breaking, without having to do a check at each usage of Storage.
if (typeof localStorage === 'object') {
try {
localStorage.setItem('localStorage', 1);
localStorage.removeItem('localStorage');
} catch (e) {
Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function() {};
alert('Your web browser does not support storing settings locally. In Safari, the most common cause of this is using "Private Browsing Mode". Some settings may not save or some features may not work properly for you.');
}
}
use \r\n
combination to append a new line in node js
var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
stream.once('open', function(fd) {
stream.write(msg+"\r\n");
});
An alternative way, but I believe bdukes's answer is best.
var myString = 'hello';
if(myString.charAt(0)){
alert('no empty');
}
alert('empty');
RegEx is the way to go in most cases.
In some cases, it may be faster to specify more elements or the specific element to perform the replace on:
$(document).ready(function () {
$('.myclass').each(function () {
$('img').each(function () {
$(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));
})
})
});
This does the replace once on each string, but it does it using a more specific selector.
just use file_put_contents('file',$myarray);
file_put_contents() works with arrays too.
git cherry branch [newbranch]
does exactly what you are asking, when you are in the master
branch.
I am also very fond of:
git diff --name-status branch [newbranch]
Which isn't exactly what you're asking, but is still very useful in the same context.
Adding to this. If you use both INSERT IGNORE
and ON DUPLICATE KEY UPDATE
in the same statement, the update will still happen if the insert finds a duplicate key. In other words, the update takes precedence over the ignore. However, if the ON DUPLICATE KEY UPDATE
clause itself causes a duplicate key error, that error will be ignored.
This can happen if you have more than one unique key, or if your update attempts to violate a foreign key constraint.
CREATE TABLE test
(id BIGINT (20) UNSIGNED AUTO_INCREMENT,
str VARCHAR(20),
PRIMARY KEY(id),
UNIQUE(str));
INSERT INTO test (str) VALUES('A'),('B');
/* duplicate key error caused not by the insert,
but by the update: */
INSERT INTO test (str) VALUES('B')
ON DUPLICATE KEY UPDATE str='A';
/* duplicate key error is suppressed */
INSERT IGNORE INTO test (str) VALUES('B')
ON DUPLICATE KEY UPDATE str='A';
I am not sure about DO-WHILE IN MS SQL Server 2008 but you can change your WHILE loop logic, so as to USE like DO-WHILE loop.
Examples are taken from here: http://blog.sqlauthority.com/2007/10/24/sql-server-simple-example-of-while-loop-with-continue-and-break-keywords/
Example of WHILE Loop
DECLARE @intFlag INT SET @intFlag = 1 WHILE (@intFlag <=5) BEGIN PRINT @intFlag SET @intFlag = @intFlag + 1 END GO
ResultSet:
1 2 3 4 5
Example of WHILE Loop with BREAK keyword
DECLARE @intFlag INT SET @intFlag = 1 WHILE (@intFlag <=5) BEGIN PRINT @intFlag SET @intFlag = @intFlag + 1 IF @intFlag = 4 BREAK; END GO
ResultSet:
1 2 3
Example of WHILE Loop with CONTINUE and BREAK keywords
DECLARE @intFlag INT SET @intFlag = 1 WHILE (@intFlag <=5) BEGIN PRINT @intFlag SET @intFlag = @intFlag + 1 CONTINUE; IF @intFlag = 4 -- This will never executed BREAK; END GO
ResultSet:
1 2 3 4 5
But try to avoid loops at database level. Reference.
To answer your first question: yes, if the file is not there Python will create it.
Secondly, the user (yourself) running the python script doesn't have write privileges to create a file in the directory.