Strictly speaking, if you only want to print "Blah" here is the solution :
find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 'BLAH' -quit
Here is another way :
doesFirstFileExist(){
test -e "$1"
}
if doesFirstFileExist xorg-x11-fonts*
then printf "BLAH"
fi
But I think the most optimal is as follow, because it won't try to sort file names :
if [ -z `find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 1 -quit` ]
then printf "BLAH"
fi
EDIT: Peter Lawrey is completely right: it's not as simple as interrupting a thread (my original suggestion), and Executors & Callables are very useful ...
Rather than interrupting threads, you could set a variable on the Callable once the timeout is reached. The callable should check this variable at appropriate points in task execution, to know when to stop.
Callables return Futures, with which you can specify a timeout when you try to 'get' the future's result. Something like this:
try {
future.get(timeoutSeconds, TimeUnit.SECONDS)
} catch(InterruptedException e) {
myCallable.setStopMeAtAppropriatePlace(true);
}
See Future.get, Executors, and Callable ...
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html
In Ubuntu if you execute the script with sh scriptname.sh
you get this problem.
Try executing the script with ./scriptname.sh
instead.
Nothing helped until I found this solution : https://stackoverflow.com/a/39068538/3995091
In Android SDK, the build tools with the correct version where shown as installed, but still I got the same error saying they couldn't be found. When I used the above solution, I found out they were indeed not installed, although Android SDK thought they were. Installing them solved it for me.
Your code is
urlpatterns = [
url(r'^$', 'myapp.views.home'),
url(r'^contact/$', 'myapp.views.contact'),
url(r'^login/$', 'django.contrib.auth.views.login'),
]
change it to following as you're importing include()
function :
urlpatterns = [
url(r'^$', views.home),
url(r'^contact/$', views.contact),
url(r'^login/$', views.login),
]
By using convertedDate.getMonth().length(convertedDate.isLeapYear())
where convertedDate
is an instance of LocalDate
.
String date = "1/13/2012";
LocalDate convertedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/yyyy"));
convertedDate = convertedDate.withDayOfMonth(
convertedDate.getMonth().length(convertedDate.isLeapYear()));
By using getActualMaximum
method of java.util.Calendar
:
String date = "1/13/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(convertedDate);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
you can always convert your varchar-column to bigint as integer might be too short...
select cast([yourvarchar] as BIGINT)
but you should always care for alpha characters
where ISNUMERIC([yourvarchar] +'e0') = 1
the +'e0' comes from http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/isnumeric-isint-isnumber
this would lead to your statement
SELECT
*
FROM
Table
ORDER BY
ISNUMERIC([yourvarchar] +'e0') DESC
, LEN([yourvarchar]) ASC
the first sorting column will put numeric on top. the second sorts by length, so 10 will preceed 0001 (which is stupid?!)
this leads to the second version:
SELECT
*
FROM
Table
ORDER BY
ISNUMERIC([yourvarchar] +'e0') DESC
, RIGHT('00000000000000000000'+[yourvarchar], 20) ASC
the second column now gets right padded with '0', so natural sorting puts integers with leading zeros (0,01,10,0100...) in correct order (correct!) - but all alphas would be enhanced with '0'-chars (performance)
so third version:
SELECT
*
FROM
Table
ORDER BY
ISNUMERIC([yourvarchar] +'e0') DESC
, CASE WHEN ISNUMERIC([yourvarchar] +'e0') = 1
THEN RIGHT('00000000000000000000' + [yourvarchar], 20) ASC
ELSE LTRIM(RTRIM([yourvarchar]))
END ASC
now numbers first get padded with '0'-chars (of course, the length 20 could be enhanced) - which sorts numbers right - and alphas only get trimmed
On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.
BTW: The correct way to do this is to use TryGetValue
obj item;
if(!dict.TryGetValue(name, out item))
return null;
return item;
This accesses the dictionary only once instead of twice.
If you really want to just return null
if the key doesn't exist, the above code can be simplified further:
obj item;
dict.TryGetValue(name, out item);
return item;
This works, because TryGetValue
sets item
to null
if no key with name
exists.
My iPad was 8.0, but i had deployment target set to 8.1. I changed the deployment target in build settings, and immediately, the ipad moved out of the "ineligible" category. (I am on Yosemite and XCode 6.1)
For me, general_log didn't worked. But adding this to my.ini worked
[mysqld]
log-output=FILE
slow_query_log = 1
slow_query_log_file = "d:/temp/developer.log"
Let me share a Linux shell script to copy your table data from one server to another PostgreSQL server.
Reference taken from this blog:
Linux Bash Shell Script for data migration between PostgreSQL Servers:
#!/bin/bash
psql \
-X \
-U user_name \
-h host_name1 \
-d database_name \
-c "\\copy tbl_Students to stdout" \
| \
psql \
-X \
-U user_name \
-h host_name2 \
-d database_name \
-c "\\copy tbl_Students from stdin"
I am just migrating the data; please create a blank table at your destination/second database server.
This is a utility script. Further, you can modify the script for generic use something like by adding parameters for host_name, database_name, table_name and others
Try this:
public ActionResult CreatePerson(int id) //controller
window.location.href = "@Url.Action("CreatePerson", "Person")?Id='+Id+'";
it's working fine passing parameter.
You can create your own custom validation method using the addMethod
function. Say you wanted to validate "dd/mm/yyyy":
$.validator.addMethod(
"australianDate",
function(value, element) {
// put your own logic here, this is just a (crappy) example
return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
},
"Please enter a date in the format dd/mm/yyyy."
);
And then on your form add:
$('#myForm')
.validate({
rules : {
myDate : {
australianDate : true
}
}
})
;
In insert()
public void insert(String tableImg, Object object,
ContentValues dataToInsert) {
db.insert(tablename, null, dataToInsert);
}
Hope it helps you.
From SQL Server 2012 you can use a native pagination in order to have semplicity and best performance:
Your query become:
SELECT * FROM Reflow
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC;
OFFSET 20 ROWS
FETCH NEXT 20 ROWS ONLY;
Actually, you have to explicitly compare it to true. If the dialog doesn't exist yet, it will not return false (as you would expect), it will return a DOM object.
if ($('#mydialog').dialog('isOpen') === true) {
// true
} else {
// false
}
by typing yes it wont charge taxes, by typing no it will charge taxes.
=IF(C39="Yes","0",IF(C39="no",PRODUCT(G36*0.0825)))
You can use \t
to create a tab in a file.
Changing XAMPP Default Port: If you want to get XAMPP up and running, you should consider changing the port from the default 80 to say 7777.
In the XAMPP Control Panel, click on the Apache – Config button which is located next to the ‘Logs’ button.
Select ‘Apache (httpd.conf)’ from the drop down. (Notepad should open)
Do Ctrl+F to find ’80’ and change line Listen 80 to Listen 7777
Find again and change line ServerName localhost:80 to ServerName localhost:7777
Save and re-start Apache. It should be running by now.
The only demerit to this technique is, you have to explicitly include the port number in the localhost url. Rather than http://localhost
it becomes http://localhost:7777
.
Yes. Problem is in wrong notation. Use:
$this->sendRequest($uri)
Instead. Or
self::staticMethod()
for static methods. Also read this for getting idea of OOP - http://www.php.net/manual/en/language.oop5.basic.php
Based on the comment marked as answer and patch recommended , as well as -> This version wants to convert the Days to Business-Hours ... Considers Same day hours as well.
/// <summary>
/// Calculates number of business days, taking into account:
/// - weekends (Saturdays and Sundays)
/// - bank holidays in the middle of the week
/// </summary>
/// <param name="firstDay">First day in the time interval</param>
/// <param name="lastDay">Last day in the time interval</param>
/// <param name="bankHolidays">List of bank holidays excluding weekends</param>
/// <returns>Number of business hours during the 'span'</returns>
public static int BusinessHoursUntil(DateTime firstDay, DateTime lastDay, params DateTime[] bankHolidays)
{
var original_firstDay = firstDay;
var original_lastDay = lastDay;
firstDay = firstDay.Date;
lastDay = lastDay.Date;
if (firstDay > lastDay)
return -1; //// throw new ArgumentException("Incorrect last day " + lastDay);
TimeSpan span = lastDay - firstDay;
int businessDays = span.Days + 1;
int fullWeekCount = businessDays / 7;
// find out if there are weekends during the time exceedng the full weeks
if (businessDays > fullWeekCount * 7)
{
// we are here to find out if there is a 1-day or 2-days weekend
// in the time interval remaining after subtracting the complete weeks
int firstDayOfWeek = firstDay.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)firstDay.DayOfWeek;
int lastDayOfWeek = lastDay.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)lastDay.DayOfWeek;
if (lastDayOfWeek < firstDayOfWeek)
lastDayOfWeek += 7;
if (firstDayOfWeek <= 6)
{
if (lastDayOfWeek >= 7)// Both Saturday and Sunday are in the remaining time interval
businessDays -= 2;
else if (lastDayOfWeek >= 6)// Only Saturday is in the remaining time interval
businessDays -= 1;
}
else if (firstDayOfWeek <= 7 && lastDayOfWeek >= 7)// Only Sunday is in the remaining time interval
businessDays -= 1;
}
// subtract the weekends during the full weeks in the interval
businessDays -= fullWeekCount + fullWeekCount;
if (bankHolidays != null && bankHolidays.Any())
{
// subtract the number of bank holidays during the time interval
foreach (DateTime bankHoliday in bankHolidays)
{
DateTime bh = bankHoliday.Date;
if (firstDay <= bh && bh <= lastDay)
--businessDays;
}
}
int total_business_hours = 0;
if (firstDay.Date == lastDay.Date)
{//If on the same day, go granular with Hours from the Orginial_*Day values
total_business_hours = (int)(original_lastDay - original_firstDay).TotalHours;
}
else
{//Convert Business-Days to TotalHours
total_business_hours = (int)(firstDay.AddDays(businessDays).AddHours(firstDay.Hour) - firstDay).TotalHours;
}
return total_business_hours;
}
for method parameters you can use Objects.requireNonNull() like this:
test(String str) {
Objects.requireNonNull(str);
}
But this is only checked at runtime and throws an NPE if null. It is like a preconditions check. But that might be what you are looking for.
For windows run gradle task with jdk 11 path parameter in quotes
gradlew clean build -Dorg.gradle.java.home="c:/Program Files/Java/jdk-11"
I know, I am late at this party. Let me show you what I have got.
This is a simple reading of text file
var path = "C:\\path\\filename.txt"
var fs = require('fs')
fs.readFile(path , 'utf8', function(err, data) {
if (err) throw err;
console.log('OK: ' + filename);
console.log(data)
});
I hope this helps.
The following POSIX program will print the names of the files in the current directory:
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
return 0;
}
Credit: http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html
Tested in Ubuntu 16.04.
If you want to send a custom HTTP Header (not a SOAP Header) then you need to use the HttpWebRequest class the code would look like:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("Authorization", token);
You cannot add HTTP headers using the visual studio generated proxy, which can be a real pain.
My English is not good so I'll just write a simple example here.
double a = 0.02;
double b = 0.03;
double c = b - a;
System.out.println(c);
BigDecimal _a = new BigDecimal("0.02");
BigDecimal _b = new BigDecimal("0.03");
BigDecimal _c = _b.subtract(_a);
System.out.println(_c);
Program output:
0.009999999999999998
0.01
Somebody still want to use double? ;)
input.split(/\s*[\s,]\s*/)
… \s*
matches zero or more white space characters (not just spaces, but also tabs and newlines).
... [\s,]
matches one white space character or one comma
If you want to avoid blank elements from input like "foo,bar,,foobar"
, this will do the trick:
input.split(/(\s*,?\s*)+/)
The +
matches one or more of the preceding character or group.
Edit:
Added ?
after comma which matches zero or one comma.
Edit 2:
Turns out edit 1 was a mistake. Fixed it. Now there has to be at least one comma or one space for the expression to find a match.
I don't believe there is a way to get the value of the current iteration of a foreach loop. Counting yourself, seems to be the best way.
May I ask, why you would want to know?
It seems that you would most likley be doing one of three things:
1) Getting the object from the collection, but in this case you already have it.
2) Counting the objects for later post processing...the collections have a Count property that you could make use of.
3) Setting a property on the object based on its order in the loop...although you could easily be setting that when you added the object to the collection.
For any sub domain request, use this:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.band\.s\.co
RewriteCond %{HTTP_HOST} ^(.*)\.band\.s\.co
RewriteCond %{REQUEST_URI} !^/([a-zA-Z0-9-z\-]+)
RewriteRule ^(.*)$ /%1/$1 [L]
Just make some folder same as sub domain name you need. Folder must be exist like this: domain.com/sub for sub.domain.com.
Using html5 doctype at the beginning of the page.
<!DOCTYPE html>
Force IE to use the latest render mode
<meta http-equiv="X-UA-Compatible" content="IE=edge">
If your target browser is ie8, then check your compatible settings in IE8
The 2
in Anaconda2
means that the main version of Python will be 2.x rather than the 3.x installed in Anaconda3
. The current release has Python 2.7.13.
The 4.4.0.1
is the version number of Anaconda. The current advertised version is 4.4.0
and I assume the .1
is a minor release or for other similar use. The Windows releases, which I use, just say 4.4.0
in the file name.
Others have now explained the difference between Anaconda and Miniconda, so I'll skip that.
public static void SendMail(MailMessage Message)
{
SmtpClient client = new SmtpClient();
client.Host = "smtp.googlemail.com";
client.Port = 587;
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("[email protected]", "password");
client.Send(Message);
}
Your PHP was compiled with MySQL 5.1 but now it is linking a mysql library of 5.5.X family. You have to upgrade PHP to a version compiled with MySQL 5.5 or revert back mysql client libraries to 5.1.x.
When you want to create an external_table, all field's name must be written in UPPERCASE.
Done.
I know this has already been answered in several forms but here is my bit of code with a look to go through all the characters.
Here is the code, started with the class
public class CheckChValue { // Class name
public static void main(String[] args) { // class main
String name = "admin"; // String to check it's value
int nameLenght = name.length(); // length of the string used for the loop
for(int i = 0; i < nameLenght ; i++){ // while counting characters if less than the length add one
char character = name.charAt(i); // start on the first character
int ascii = (int) character; //convert the first character
System.out.println(character+" = "+ ascii); // print the character and it's value in ascii
}
}
}
Using This Method To Get All Range Without Error
public List<T> GetTsRate( List<T> AllT,int Index,int Count)
{
List<T> Ts = null;
try
{
Ts = AllT.ToList().GetRange(Index, Count);
}
catch (Exception ex)
{
Ts = AllT.Skip(Index).ToList();
}
return Ts ;
}
What am I doing incorrectly?
You have to convert html to javascript object, and then as a second step to json throug JSON.Stringify.
How can I receive a json object in the controller?
View:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://raw.githubusercontent.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializejson.js"></script>
var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
$.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });
<form id="form1" method="post">
<input name="OrderDate" type="text" /><br />
<input name="Item[0][Id]" type="text" /><br />
<input name="Item[1][Id]" type="text" /><br />
<button id="btn" onclick="btnClick()">Button</button>
</form>
Controller:
public void PostRawJson(string json)
{
var order = System.Web.Helpers.Json.Decode(json);
var orderDate = order.OrderDate;
var secondOrderId = order.Item[1].Id;
}
Depending on what arguments you need to pass, especially for custom event handlers, you can do something like this:
<div @customEvent='(arg1) => myCallback(arg1, arg2)'>Hello!</div>
If you're opening a big file, you probably want to use Generators alongside fgets() to avoid loading the whole file into memory:
/**
* @return Generator
*/
$fileData = function() {
$file = fopen(__DIR__ . '/file.txt', 'r');
if (!$file)
die('file does not exist or cannot be opened');
while (($line = fgets($file)) !== false) {
yield $line;
}
fclose($file);
};
Use it like this:
foreach ($fileData() as $line) {
// $line contains current line
}
This way you can process individual file lines inside the foreach().
Note: Generators require >= PHP 5.5
var getKeyByDinner = function(obj, dinner) {
var returnKey = -1;
$.each(obj, function(key, info) {
if (info.dinner == dinner) {
returnKey = key;
return false;
};
});
return returnKey;
}
So long as -1
isn't ever a valid key.
Had to install VS 2010 SP1 in order to get it to work again for myself. Lame microsoft.
You need to look at the return value of the call to showConfirmDialog
. I.E.:
int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){
// Saving code here
}
You were testing against dialogButton
, which you were using to set the buttons that should be displayed by the dialog, and this variable was never updated - so dialogButton
would never have been anything other than JOptionPane.YES_NO_OPTION
.
Per the Javadoc for showConfirmDialog
:
Returns: an integer indicating the option selected by the user
Late to the party, but recently found another way to get the summary statistics.
library(psych)
describe(data)
Will output: mean, min, max, standard deviation, n, standard error, kurtosis, skewness, median, and range for each variable.
The SetEnv.cmd
script that the "SDK command prompt" shortcut runs checks for cl.exe
in various places before setting up entries to add to PATH
. So it fails to add anything if a native C compiler is not installed.
To fix that, apply the following patch to <SDK install dir>\Bin\SetEnv.cmd
. This will also fix missing paths to other tools located in <SDK install dir>\Bin
and subfolders. Of course, you can install the C compiler instead to work around this bug.
--- SetEnv.Cmd_ 2010-04-27 19:52:00.000000000 +0400
+++ SetEnv.Cmd 2013-12-02 15:05:30.834400000 +0400
@@ -228,10 +228,10 @@
IF "%CURRENT_CPU%" =="x64" (
IF "%TARGET_CPU%" == "x64" (
+ SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\amd64\cl.exe" (
SET "VCTools=%VCTools%\amd64;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The x64 compilers are not currently installed.
@@ -239,10 +239,10 @@
ECHO .
)
) ELSE IF "%TARGET_CPU%" == "IA64" (
+ SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\x86_ia64\cl.exe" (
SET "VCTools=%VCTools%\x86_ia64;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The IA64 compilers are not currently installed.
@@ -250,10 +250,10 @@
ECHO .
)
) ELSE IF "%TARGET_CPU%" == "x86" (
+ SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\cl.exe" (
SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The x86 compilers are not currently installed.
@@ -263,10 +263,10 @@
)
) ELSE IF "%CURRENT_CPU%" =="IA64" (
IF "%TARGET_CPU%" == "IA64" (
+ SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\IA64\cl.exe" (
SET "VCTools=%VCTools%\IA64;%VCTools%;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The IA64 compilers are not currently installed.
@@ -274,10 +274,10 @@
ECHO .
)
) ELSE IF "%TARGET_CPU%" == "x64" (
+ SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\x86_amd64\cl.exe" (
SET "VCTools=%VCTools%\x86_amd64;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The VC compilers are not currently installed.
@@ -285,10 +285,10 @@
ECHO .
)
) ELSE IF "%TARGET_CPU%" == "x86" (
+ SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\cl.exe" (
SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The x86 compilers are not currently installed.
@@ -298,10 +298,10 @@
)
) ELSE IF "%CURRENT_CPU%"=="x86" (
IF "%TARGET_CPU%" == "x64" (
+ SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\x86_amd64\cl.exe" (
SET "VCTools=%VCTools%\x86_amd64;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The x64 cross compilers are not currently installed.
@@ -309,10 +309,10 @@
ECHO .
)
) ELSE IF "%TARGET_CPU%" == "IA64" (
+ SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\x86_IA64\cl.exe" (
SET "VCTools=%VCTools%\x86_IA64;%VCTools%;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The IA64 compilers are not currently installed.
@@ -320,10 +320,10 @@
ECHO .
)
) ELSE IF "%TARGET_CPU%" == "x86" (
+ SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\cl.exe" (
SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The x86 compilers are not currently installed. x86-x86
@@ -331,15 +331,17 @@
ECHO .
)
)
-) ELSE IF EXIST "%VCTools%\cl.exe" (
- SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
- SET VCTools=
- ECHO The x86 compilers are not currently installed. default
- ECHO Please go to Add/Remove Programs to update your installation.
- ECHO .
+ SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
+ IF EXIST "%VCTools%\cl.exe" (
+ SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
+ ) ELSE (
+ SET VCTools=
+ ECHO The x86 compilers are not currently installed. default
+ ECHO Please go to Add/Remove Programs to update your installation.
+ ECHO .
+ )
)
:: --------------------------------------------------------------------------------------------
You can add + behind the variable and it will force it to be an integer
var dots = 5
function increase(){
dots = +dots + 5;
}
Yes, safari will detect the *.ipa and will try to install it, but the ipa needs to be correctly signed and only allowed devices would be able to install it.
http://www.diawi.com is a service that will help you with this process.
All of this is for Ad-hoc distribution, not for production apps.
More information on below link : Is there a way to install iPhone App via browser?
Hope this will help you .
Here is Html code:-
<body>
<div ng-controller="MyController" class="container">
<h1>Modal example</h1>
<button ng-click="open()" class="btn btn-primary">Test Modal</button>
<modal title="Login form" visible="showModal">
<form role="form">
</form>
</modal>
</div>
</body>
AngularJs code:-
var mymodal = angular.module('mymodal', []);
mymodal.controller('MyController', function ($scope) {
$scope.showModal = false;
$scope.open = function(){
$scope.showModal = !$scope.showModal;
};
});
mymodal.directive('modal', function () {
return {
template: '<div class="modal fade">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
'<h4 class="modal-title">{{ title }}</h4>' +
'</div>' +
'<div class="modal-body" ng-transclude></div>' +
'</div>' +
'</div>' +
'</div>',
restrict: 'E',
transclude: true,
replace:true,
scope:true,
link: function postLink(scope, element, attrs) {
scope.title = attrs.title;
scope.$watch(attrs.visible, function(value){
if(value == true)
$(element).modal('show');
else
$(element).modal('hide');
});
$(element).on('shown.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
});
}
};
});
Check this--jsfiddle
First of all, REST is not a religion and should not be approached as such. While there are advantages to RESTful services, you should only follow the tenets of REST as far as they make sense for your application.
That said, authentication and client side state do not violate REST principles. While REST requires that state transitions be stateless, this is referring to the server itself. At the heart, all of REST is about documents. The idea behind statelessness is that the SERVER is stateless, not the clients. Any client issuing an identical request (same headers, cookies, URI, etc) should be taken to the same place in the application. If the website stored the current location of the user and managed navigation by updating this server side navigation variable, then REST would be violated. Another client with identical request information would be taken to a different location depending on the server-side state.
Google's web services are a fantastic example of a RESTful system. They require an authentication header with the user's authentication key to be passed upon every request. This does violate REST principles slightly, because the server is tracking the state of the authentication key. The state of this key must be maintained and it has some sort of expiration date/time after which it no longer grants access. However, as I mentioned at the top of my post, sacrifices must be made to allow an application to actually work. That said, authentication tokens must be stored in a way that allows all possible clients to continue granting access during their valid times. If one server is managing the state of the authentication key to the point that another load balanced server cannot take over fulfilling requests based on that key, you have started to really violate the principles of REST. Google's services ensure that, at any time, you can take an authentication token you were using on your phone against load balance server A and hit load balance server B from your desktop and still have access to the system and be directed to the same resources if the requests were identical.
What it all boils down to is that you need to make sure your authentication tokens are validated against a backing store of some sort (database, cache, whatever) to ensure that you preserve as many of the REST properties as possible.
I hope all of that made sense. You should also check out the Constraints section of the wikipedia article on Representational State Transfer if you haven't already. It is particularly enlightening with regard to what the tenets of REST are actually arguing for and why.
Here's a way to do this as a JQuery plugin (in case you want to re-use the functionality):
$.fn.onEnterKey =
function( closure ) {
$(this).keypress(
function( event ) {
var code = event.keyCode ? event.keyCode : event.which;
if (code == 13) {
closure();
return false;
}
} );
}
Now if you want to decorate an <input>
element with this type of functionality it's as simple as this:
$('#your-input-id').onEnterKey(
function() {
// Do stuff here
} );
You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).
You must login to have a valid session before downloading anything below.
*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)
*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.
Xcode 12
12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)
12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)
12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)
Xcode 11
11.7 (Latest as of Sept 02 2020)
11.4.1 (Requires macOS 10.15.2 or later)
11 (Requires macOS 10.14.4 or later)
Xcode 10 (unsupported for iTunes Connect)
Xcode 9
Xcode 8
Xcode 7
Xcode 6
Even Older Versions (unsupported for iTunes Connect)
Python 3.5 + Use io module
import json
import io
my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'
fix_bytes_value = my_bytes_value.replace(b"'", b'"')
my_json = json.load(io.BytesIO(fix_bytes_value))
var dates = dates_as_int.map(function(dateStr) {
return new Date(dateStr).getTime();
});
=>
[1468959781804, 1469029434776, 1469199218634, 1469457574527]
Update: ES6 version:
const dates = dates_as_int.map(date => new Date(date).getTime())
Try \r\n
in place of \n
The difference between \n and \r\n
It should be noted that this is applicable to line returns in emails. For other scenarios, please refer to rokjarc's answer.
Window > Preferences > Validation > uncheck XML Validator Manual and Build
There are different way:
global service
service shared by parent and injected to the child
providers
or viewProviders
in the parent instead of boostrap(...)
and only available to children of parent.parent injected to the child and accessed directly by the child
export class Profile implements OnInit {
constructor(@Host() parent: App) {
parent.userStatus ...
}
export class Profile implements OnInit {
@Input() userStatus:UserStatus;
...
}
<profile [userStatus]="userStatus">
Another example why SQL isn't really portable.
For MySQL it would be:
update ud, sale
set ud.assid = sale.assid
where sale.udid = ud.id;
For more info read multiple table update: http://dev.mysql.com/doc/refman/5.0/en/update.html
UPDATE [LOW_PRIORITY] [IGNORE] table_references
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
1. We can use aggregate function with HAVING clause not by WHERE clause e.g. min,max,avg.
2. WHERE clause eliminates the record tuple by tuple HAVING clause eliminates entire group from the collection of group
Mostly HAVING is used when you have groups of data and WHERE is used when you have data in rows.
This code worked for me with Python 3.5.2. It opens and saves and excel. I am currently working on how to save data into the file but this is the code:
import csv
excel = csv.writer(open("file1.csv", "wb"))
Just look at MDN Web Docs.
Here is a list of MIME types, associated by type of documents, ordered by their common extensions:
In my case, the command that best suited me was:
jupyter nbconvert --execute --clear-output <notebook>.ipynb
Why? This command does not create extra files (just like a .py
file) and the output of the cells is overwritten everytime the notebook is executed.
If you run:
jupyter nbconvert --help
--clear-output Clear output of current file and save in place, overwriting the existing notebook.
-ArgumentList
is based on use with scriptblock commands, like:
Invoke-Command -Cn (gc Servers.txt) {param($Debug=$False, $Clear=$False) C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 } -ArgumentList $False,$True
When you call it with a -File
it still passes the parameters like a dumb splatted array. I've submitted a feature request to have that added to the command (please vote that up).
So, you have two options:
If you have a script that looked like this, in a network location accessible from the remote machine (note that -Debug
is implied because when I use the Parameter
attribute, the script gets CmdletBinding implicitly, and thus, all of the common parameters):
param(
[Parameter(Position=0)]
$one
,
[Parameter(Position=1)]
$two
,
[Parameter()]
[Switch]$Clear
)
"The test is for '$one' and '$two' ... and we $(if($DebugPreference -ne 'SilentlyContinue'){"will"}else{"won't"}) run in debug mode, and we $(if($Clear){"will"}else{"won't"}) clear the logs after."
Without getting hung up on the meaning of $Clear
... if you wanted to invoke that you could use either of the following Invoke-Command
syntaxes:
icm -cn (gc Servers.txt) {
param($one,$two,$Debug=$False,$Clear=$False)
C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 @PSBoundParameters
} -ArgumentList "uno", "dos", $false, $true
In that one, I'm duplicating ALL the parameters I care about in the scriptblock so I can pass values. If I can hard-code them (which is what I actually did), there's no need to do that and use PSBoundParameters
, I can just pass the ones I need to. In the second example below I'm going to pass the $Clear one, just to demonstrate how to pass switch parameters:
icm -cn $Env:ComputerName {
param([bool]$Clear)
C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $(Test-Path $Profile)
If the script is on your local machine, and you don't want to change the parameters to be positional, or you want to specify parameters that are common parameters (so you can't control them) you will want to get the content of that script and embed it in your scriptblock:
$script = [scriptblock]::create( @"
param(`$one,`$two,`$Debug=`$False,`$Clear=`$False)
&{ $(Get-Content C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -delimiter ([char]0)) } @PSBoundParameters
"@ )
Invoke-Command -Script $script -Args "uno", "dos", $false, $true
If you really need to pass in a variable for the script name, what you'd do will depend on whether the variable is defined locally or remotely. In general, if you have a variable $Script
or an environment variable $Env:Script
with the name of a script, you can execute it with the call operator (&): &$Script
or &$Env:Script
If it's an environment variable that's already defined on the remote computer, that's all there is to it. If it's a local variable, then you'll have to pass it to the remote script block:
Invoke-Command -cn $Env:ComputerName {
param([String]$Script, [bool]$Clear)
& $ScriptPath "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $ScriptPath, (Test-Path $Profile)
Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used
watch -n 5 -d "ps -eL <java_pid> | wc -l"
to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.
I have similar problem but I solved it by removing all the foreign key in my Postgresql
follow this thread for more information
CSS Attribute Selector: Apply class if custom attribute has value? Also, will it work in IE7+?
and learn css attribute selector
type
%matplotlib qt
when you want graphs in a separate window and
%matplotlib inline
when you want an inline plot
onNewIntent()
is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate()
. From activities lifecycle point of view it's therefore needed to call onPause()
before onNewIntent()
. I suggest you to rewrite your activity to not use these listeners inside of onNewIntent()
. For example most of the time my onNewIntent()
methods simply looks like this:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
}
With all setup logic happening in onResume()
by utilizing getIntent()
.
Here is one possible flex-based solution (SCSS):
dl {
display: flex;
flex-wrap: wrap;
width: 100%;
dt {
width: 150px;
}
dd {
margin: 0;
flex: 1 0 calc(100% - 150px);
}
}
that works for the following HTML (pug)
dl
dt item 1
dd desc 1
dt item 2
dd desc 2
Not sure what isn't working in your case, but the following code will put a formula into cell A1 that will retrieve the value in the cell G2.
strProjectName = "Sheet1"
Cells(1, 1).Formula = "=" & strProjectName & "!" & Cells(2, 7).Address
The workbook and worksheet that strProjectName
references must exist at the time that this formula is placed. Excel will immediately try to evaluate the formula. You might be able to stop that from happening by turning off automatic recalculation until the workbook does exist.
To determine if the array is sparse, it may help to get a proportion of nan values
np.isnan(ndarr).sum() / ndarr.size
If that proportion exceeds a threshold, then use a sparse array, e.g. - https://sparse.pydata.org/en/latest/
I solved this by using the /sm
flag to specify to look in the machine store instead of the default, which is My (Local User) store. Also, it can help to turn on debug for signtool by using /debug
.
it's easier to check first if the channel has elements, that would ensure the channel is alive.
func isChanClosed(ch chan interface{}) bool {
if len(ch) == 0 {
select {
case _, ok := <-ch:
return !ok
}
}
return false
}
Here is a simple explanation about how to create a temp dir using templates.
PARENT_DIR=./temp_dirs # (optional) specify a dir for your tempdirs
mkdir $PARENT_DIR
TEMPLATE_PREFIX='tmp' # prefix of your new tempdir template
TEMPLATE_RANDOM='XXXX' # Increase the Xs for more random characters
TEMPLATE=${PARENT_DIR}/${TEMPLATE_PREFIX}.${TEMPLATE_RANDOM}
# create the tempdir using your custom $TEMPLATE, which may include
# a path such as a parent dir, and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -d $TEMPLATE)
echo $NEW_TEMP_DIR_PATH
# create the tempdir in parent dir, using default template
# 'tmp.XXXXXXXXXX' and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -p $PARENT_DIR)
echo $NEW_TEMP_DIR_PATH
# create a tempdir in your systems default tmp path e.g. /tmp
# using the default template 'tmp.XXXXXXXXXX' and assign path to var
NEW_TEMP_DIR_PATH=$(mktemp -d)
echo $NEW_TEMP_DIR_PATH
# Do whatever you want with your generated temp dir and var holding its path
If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");
// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form);
// creating the 'formresult' window with custom features prior to submitting the form
window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
form.submit();
To get the Unix time (seconds since January 1, 1970):
>>> import datetime, time
>>> t = datetime.datetime(2011, 10, 21, 0, 0)
>>> time.mktime(t.timetuple())
1319148000.0
An md5 encryption is one of the worst, because you have to turn the code and it is already decrypted. I would recommend you the SHA256. I'm programming a bit longer and have had a good experience. Below would also be an encryption.
password_hash() example using Argon2i
<?php
echo 'Argon2i hash: ' . password_hash('rasmuslerdorf', PASSWORD_ARGON2I);
?>
The above example will output something similar to:
Argon2i hash: $argon2i$v=19$m=1024,t=2,p=2$YzJBSzV4TUhkMzc3d3laeg$zqU/1IN0/AogfP4cmSJI1vc8lpXRW9/S0sYY2i2jHT0
It is possible to write to an excel file without opening it using the Microsoft.Jet.OLEDB.4.0
and OleDb
. Using OleDb
, it behaves as if you were writing to a table using sql.
Here is the code I used to create and write to an new excel file. No extra references are needed
var connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SomePath\ExcelWorkBook.xls;Extended Properties=Excel 8.0";
using (var excelConnection = new OleDbConnection(connectionString))
{
// The excel file does not need to exist, opening the connection will create the
// excel file for you
if (excelConnection.State != ConnectionState.Open) { excelConnection.Open(); }
// data is an object so it works with DBNull.Value
object propertyOneValue = "cool!";
object propertyTwoValue = "testing";
var sqlText = "CREATE TABLE YourTableNameHere ([PropertyOne] VARCHAR(100), [PropertyTwo] INT)";
// Executing this command will create the worksheet inside of the workbook
// the table name will be the new worksheet name
using (var command = new OleDbCommand(sqlText, excelConnection)) { command.ExecuteNonQuery(); }
// Add (insert) data to the worksheet
var commandText = $"Insert Into YourTableNameHere ([PropertyOne], [PropertyTwo]) Values (@PropertyOne, @PropertyTwo)";
using (var command = new OleDbCommand(commandText, excelConnection))
{
// We need to allow for nulls just like we would with
// sql, if your data is null a DBNull.Value should be used
// instead of null
command.Parameters.AddWithValue("@PropertyOne", propertyOneValue ?? DBNull.Value);
command.Parameters.AddWithValue("@PropertyTwo", propertyTwoValue ?? DBNull.Value);
command.ExecuteNonQuery();
}
}
sys.executable
contains full path of the currently running Python interpreter.
import sys
print(sys.executable)
which is now documented here
preferred way, using MySQLi extension:
$mysqli = new mysqli(SERVER, DBUSER, DBPASS, DATABASE);
$result = $mysqli->query("SELECT id FROM mytable WHERE city = 'c7'");
if($result->num_rows == 0) {
// row not found, do stuff...
} else {
// do other stuff...
}
$mysqli->close();
deprecated:
$result = mysql_query("SELECT id FROM mytable WHERE city = 'c7'");
if(mysql_num_rows($result) == 0) {
// row not found, do stuff...
} else {
// do other stuff...
}
I know this is a bit late but for those that are interested you can use a runtime check.
typeof(T).IsInterface
By doing so you'd be able to control any action of the framed page, which you cannot. Same-domain origin policy applies.
The setCustomValidity let you change the default validation message.Here is a simple exmaple of how to use it.
var age = document.getElementById('age');
age.form.onsubmit = function () {
age.setCustomValidity("This is not a valid age.");
};
Fields in interfaces are implicitly public static final
. (Also methods are implicitly public, so you can drop the public
keyword.) Even if you use an abstract class instead of an interface, I strongly suggest making all non-constant (public static final
of a primitive or immutable object reference) private
. More generally "prefer composition to inheritance" - a Tile
is-not-a Rectangle
(of course, you can play word games with "is-a" and "has-a").
For Django versions > 1.10, according to the documentation, a custom MIDDLEWARE can be written as a function, let's say in the file: yourproject/middleware.py
(as a sibling of settings.py
):
def open_access_middleware(get_response):
def middleware(request):
response = get_response(request)
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Headers"] = "*"
return response
return middleware
and finally, add the python path of this function (w.r.t. the root of your project) to the MIDDLEWARE list in your project's settings.py
:
MIDDLEWARE = [
.
.
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'yourproject.middleware.open_access_middleware'
]
Easy peasy!
Your example is correct but not very portable. There is also a slightly cleaner syntax that can be used (as pointed out by @namespace-sid, among others).
However, suppose the templated class is part of some library that is to be shared...
Should other versions of the templated class be compiled?
Is the library maintainer supposed to anticipate all possible templated uses of the class?
Add a third file that is the template implementation/instantiation file in your sources.
lib/foo.hpp
in/from library
#pragma once
template <typename T>
class foo
{
public:
void bar(const T&);
};
lib/foo.cpp
compiling this file directly just wastes compilation time
// Include guard here, just in case
#pragma once
#include "foo.hpp"
template <typename T>
void foo::bar(const T& arg)
{
// Do something with `arg`
}
foo.MyType.cpp
using the library, explicit template instantiation of foo<MyType>
// Consider adding "anti-guard" to make sure it's not included in other translation units
#if __INCLUDE_LEVEL__ != 0
#error "Don't include this file"
#endif
// Yes, we include the .cpp file
#include <lib/foo.cpp>
#include "MyType.hpp"
template class foo<MyType>;
Of course, you can have multiple implementations in the third file. Or you might want multiple implementation files, one for each type (or set of types) you'd like to use, for instance.
This setup should reduce compile times, especially for heavily used complicated templated code, because you're not recompiling the same header file in each translation unit. It also enables better detection of which code needs to be recompiled, by compilers and build scripts, reducing incremental build burden.
foo.declarations.hpp
needs to know about foo<MyType>
's public interface but not .cpp
sources
#pragma once
#include <lib/foo.hpp>
#include "MyType.hpp"
// Declare `temp`. Doesn't need to include `foo.cpp`
extern foo<MyType> temp;
examples.cpp
can reference local declaration but also doesn't recompile foo<MyType>
#include "foo.declarations.hpp"
MyType instance;
// Define `temp`. Doesn't need to include `foo.cpp`
foo<MyType> temp;
void example_1() {
// Use `temp`
temp.bar(instance);
}
void example_2() {
// Function local instance
foo<MyType> temp2;
// Use templated library function
temp2.bar(instance);
}
error.cpp
example that would work with pure header templates but doesn't here
#include <lib/foo.hpp>
// Causes compilation errors at link time since we never had the explicit instantiation:
// template class foo<int>;
// GCC linker gives an error: "undefined reference to `foo<int>::bar()'"
void linkerError()
{
foo<int> nonExplicitlyInstantiatedTemplate;
}
Note that most compilers/linters/code helpers won't detect this as an error, since there is no error according to C++ standard.
But when you go to link this translation unit into a complete executable, the linker won't find a defined version of foo<int>
.
String convert(int i){
String ones = "";
String tens = "";
String hundreds = "";
String thousands = "";
String result ;
boolean error = false;
Vector v = new Vector();
//assign passed integer to temporary value temp
int temp=i;
//flags an error if number is greater than 3999
if (temp >=4000) {
error = true;
}
/*loops while temp can no more be divided by 10.
Lets say i = 3254, then temp is also 3254 at line 14.
3254
3254/10 = 25 / \ 3254%10 = 4
/ \
now temp = 25 325 4 - here 4 is added to the vector v's 0th index.
/ \
now temp = 32 32 5 - here 5 is added to the vector v's 1st index.
/ \
now temp = 3 3 2 - here 2 is added to the vector v's 2nd index, and loop exits
/ \ since temp/10 = 0
0 3 - here 3 is not added to the vector v's 3rd index as loop exits when
temp/10 = 0.
*/
while (temp/10 != 0) {
if (temp / 10 != 0 && temp <4000) {
v.add(temp%10);
temp = temp / 10;
}else {
break;
}
}
//therefore you have to add temp one last time to the vector
v.add(temp);
//as in the example now you have 4,5,2,3 respectively in v's 0,1,2,3 indices.
for (int j = 0; j < v.size(); j++) {
//you see that v's 0th index has number of ones. So make them roman ones here.
if (j==0) {
switch (v.get(0).toString()){
case "0" : ones = ""; break;
case "1" : ones = "I"; break;
case "2" : ones = "II"; break;
case "3" : ones = "III"; break;
case "4" : ones = "IV"; break;
case "5" : ones = "V"; break;
case "6" : ones = "VI"; break;
case "7" : ones = "VII"; break;
case "8" : ones = "VIII"; break;
case "9" : ones = "IX"; break;
}
//in the second iteration of the loop (when j==1)
//index 1 of v is checked. Now you understand that v's 1st index
//has the tens
} else if (j == 1) {
switch (v.get(1).toString()){
case "0" : tens = ""; break;
case "1" : tens = "X"; break;
case "2" : tens = "XX"; break;
case "3" : tens = "XXX"; break;
case "4" : tens = "XL"; break;
case "5" : tens = "L"; break;
case "6" : tens = "LX"; break;
case "7" : tens = "LXX"; break;
case "8" : tens = "LXXX"; break;
case "9" : tens = "XC"; break;
}
} else if(j == 2){ //and hundreds
switch (v.get(2).toString()){
case "0" : hundreds = ""; break;
case "1" : hundreds = "C"; break;
case "2" : hundreds = "CC"; break;
case "3" : hundreds = "CCC"; break;
case "4" : hundreds = "CD"; break;
case "5" : hundreds = "D"; break;
case "6" : hundreds = "DC"; break;
case "7" : hundreds = "DCC"; break;
case "8" : hundreds = "DCCC"; break;
case "9" : hundreds = "CM"; break;
}
} else if(j == 3){ //and finally thousands.
switch (v.get(3).toString()){
case "0" : thousands = ""; break;
case "1" : thousands = "M"; break;
case "2" : thousands = "MM"; break;
case "3" : thousands = "MMM"; break;
}
}
}
if (error) {
result = "Error!";
}else{
result = thousands + hundreds + tens + ones;
}
return result;
}
You can use the following:
$regex = '#<\s*?code\b[^>]*>(.*?)</code\b[^>]*>#s';
\b
ensures that a typo (like <codeS>
) is not captured.[^>]*
captures the content of a tag with attributes (eg a class).s
capture content with newlines.See the result here : http://lumadis.be/regex/test_regex.php?id=1081
I find that the accepted answer here is overly complicated for most use cases. This code does the job well (using jQuery) and differentiates between fully visible and partially visible elements:
var element = $("#element");
var topOfElement = element.offset().top;
var bottomOfElement = element.offset().top + element.outerHeight(true);
var $window = $(window);
$window.bind('scroll', function() {
var scrollTopPosition = $window.scrollTop()+$window.height();
var windowScrollTop = $window.scrollTop()
if (windowScrollTop > topOfElement && windowScrollTop < bottomOfElement) {
// Element is partially visible (above viewable area)
console.log("Element is partially visible (above viewable area)");
} else if (windowScrollTop > bottomOfElement && windowScrollTop > topOfElement) {
// Element is hidden (above viewable area)
console.log("Element is hidden (above viewable area)");
} else if (scrollTopPosition < topOfElement && scrollTopPosition < bottomOfElement) {
// Element is hidden (below viewable area)
console.log("Element is hidden (below viewable area)");
} else if (scrollTopPosition < bottomOfElement && scrollTopPosition > topOfElement) {
// Element is partially visible (below viewable area)
console.log("Element is partially visible (below viewable area)");
} else {
// Element is completely visible
console.log("Element is completely visible");
}
});
Similar to some answers here, but maybe a little more lightweight
void MyClass::sleepFor(qint64 milliseconds){
qint64 timeToExitFunction = QDateTime::currentMSecsSinceEpoch()+milliseconds;
while(timeToExitFunction>QDateTime::currentMSecsSinceEpoch()){
QApplication::processEvents(QEventLoop::AllEvents, 100);
}
}
If you really want to micro optimise your code your best approach is always benchmarking.
The .net framework has an excellent stopwatch implementation - System.Diagnostics.Stopwatch
if someone have problem with openssl , follow this instructions:
That's it
https://sourceforge.net/projects/openssl/files/latest/download
given you have a div element you need to scroll inside, try this piece of code
document.querySelector('div').scroll(x,y)
this works with me inside a div with a scroll, this should work with you in case you pointed the mouse over this element and then tried to scroll down or up. If it manually works, it should work too
Just create a folder Files
under src
and put your file there.
This will look like src/Files/myFile.txt
Note:
In your code you need to specify like this Files/myFile.txt
e.g.
getResource("Files/myFile.txt");
So when you build your project and run the .jar file this should be able to work.
Strings are just as iterable as arrays, so just convert it to string:
str(12345)
DataSet ds = new DataSet();
ds.ReadXml(fileNamePath);
This is due to spring-config.xml is not in classpath.
Add complete path of spring-config.xml to your classpath.
Also write command you execute to run your project. You can check classpath in command.
Using generators:
def flat_dic_helper(prepand,d):
if len(prepand) > 0:
prepand = prepand + "_"
for k in d:
i=d[k]
if type(i).__name__=='dict':
r = flat_dic_helper(prepand+k,i)
for j in r:
yield j
else:
yield (prepand+k,i)
def flat_dic(d): return dict(flat_dic_helper("",d))
d={'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}
print(flat_dic(d))
>> {'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}
Use toCharArray() method. It splits the string into an array of characters:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#toCharArray%28%29
String str = "aabbab";
char[] chs = str.toCharArray();
Kotlin?
val dialogBuilder = AlertDialog.Builder(this.context)
dialogBuilder.setTitle("Alert")
.setMessage(message)
.setPositiveButton("OK", null)
.create()
.show()
I had a similar problem with the jQuery Thickbox (a lightbox-style dialog widget). The way I fixed my problem is as follows:
function setFocusThickboxIframe() {
var iframe = $("#TB_iframeContent")[0];
iframe.contentWindow.focus();
}
$(document).ready(function(){
$("#id_cmd_open").click(function(){
/*
run thickbox code here to open lightbox,
like tb_show("google this!", "http://www.google.com");
*/
setTimeout(setFocusThickboxIframe, 100);
return false;
});
});
The code doesn't seem to work without the setTimeout(). Based on my testing, it works in Firefox3.5, Safari4, Chrome4, IE7 and IE6.
Here is another version if you have to reference a specific docker file:
version: "3"
services:
nginx:
container_name: nginx
build:
context: ../..
dockerfile: ./docker/nginx/Dockerfile
image: my_nginx:latest
Then you just run
docker-compose build
Use:
select convert(nvarchar(10), CREATED_TS, 101)
or
select format(cast(CREATED_TS as date), 'MM/dd/yyyy') -- MySQL 3.23 and above
If you want to are faced with a very large / huge file and want to read faster (imagine you are in a Topcoder/Hackerrank coding competition), you might read a considerably bigger chunk of lines into a memory buffer at one time, rather than just iterate line by line at file level.
buffersize = 2**16
with open(path) as f:
while True:
lines_buffer = f.readlines(buffersize)
if not lines_buffer:
break
for line in lines_buffer:
process(line)
Using VueJS I tried every method in this question but none worked. So in case somebody is struggling whit the same:
mounted() {
$(document).ready(function() { //<<====== wont work without this
$(window).scroll(function() {
console.log('logging');
});
});
},
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>`enter code here`
$(document).ready(function () {
var result=1;
$('input').keyup(function(){`enter code here`
$('tr').each(function () {
var sum = $(this).find('td.combat').text();
var combat = $(this).find('input.combat').val();
if (!isNaN(sum) && sum.length !== 0 && !isNaN(combat) && combat.length !== 0) {
result = parseFloat(sum)*parseFloat(combat);
}
$(this).find('.total-combat').html(result);
});
});
$('.add').click(function(){
var sno = $(this).parent().siblings('.sno').text();
var cust = $(this).parent().siblings('.cust').text();
var price = $(this).parent().siblings('td.combat').text();
var rowValue = [];
$(this).closest('tr').find("input").each(function() {
rowValue.push($(this).val());
return $(this).val();
});
var rowValue1 = [];
$(this).closest('tr').find("span").each(function() {
rowValue1.push($(this).text());
return $(this).val();
});
var markup = "<tr><td class='sno'>" + sno + "</td><td class='custname'>" + cust +"</td><td class='price'>" + price +"</td><td><input type='text' class='newtext' value="+ rowValue[0] +"></td><td class='total'>" + rowValue1[0] +"</td><td><input type='submit' class='update' value='upd'><input type='button' class='del' value='del'></td></tr>";
var rightcol = $(this).closest('tr').find(".cust");
var row_count = $('.tbl1 tbody tr').length;
alert(row_count);
if (row_count == 0) {
$(".tbl1 tbody").append(markup);
}
else
{
var tes=0;
$('.tbl1 tbody tr').each(function(){
var leftcol = $(this).find(".custname");
if(rightcol.html() == leftcol.html()) {
alert(leftcol.html()+"-----------------"+rightcol.html());
$(this).find('.sno').text(sno);
$(this).find('.custname').text(cust);
$(this).find('.price').text(price);
$(this).find('.newtext').val(rowValue[0]);
$(this).find('.total').text(rowValue1[0]);
tes++;
}
});
if(tes==0){
$(".tbl1 tbody").append(markup);
}
}
});
$(".tb").on("click", ".update", function(e) {
var rowValues = [];
$(this).closest('tr').find("input").each(function() {
rowValues.push($(this).val());
return $(this).val();
});
var total=$(this).closest('tr').find('.total').text();
var right_cols = $(this).closest('tr').find(".custname");
$('.tbl tbody tr').each(function(){
var row = $(this);
var left_cols = $(this).find(".cust");
if(left_cols.html() == right_cols.html()) {
$(this).find('.text').val(rowValues[0]);
$(this).find('.total-combat').text(total);
}
});
});
$(".tb").on("keyup", "input", function() {
$('tr').each(function () {
var sum = $(this).find('td.price').text();
var combat = $(this).find('input.newtext').val();
if (!isNaN(sum) && sum.length !== 0 && !isNaN(combat) && combat.length !== 0) {
result = parseFloat(sum)*parseFloat(combat);
}
$(this).find('.total').html(result);
});
});
$(".tb").on("click", ".del", function() {
$(this).closest('tr').remove();
});
});
</script>
<style>
.table_style {
width: 500px;
margin: 0px auto;
}
table{
width: 100%;
border-collapse: collapse;
}
table tr td{
width: 50%;
border: 5px solid #ff751a;
padding: 5px;
}
table tr th{
border: 5px solid #79ff4d;
padding: 5px;
}
input{
width:35px;
}
.tbl1{
margin-top: 50px;
border: 0px solid #cdcdcd;
}
.btn{
float:left;
}
</style>
<title>E-Commerce-Table</title>
</head>
<body>
<div class="table_style">
<caption>Price-List</caption>
<table class="tbl">
<tr>
<th>S.No</th>
<th>P.Name</th>
<th>Price</th>
<th>Qnty</th>
<th>Rate</th>
<th>action</th>
</tr>
<tbody>
<tr>
<td class="sno">1</td>
<td class="cust">A</td>
<td class="combat">5</td>
<td class="tester"><input type="number" id="qnty1" name="Qnty" value="0" class="combat text"></td>
<td><span class="total-combat"></span></td>
<td><input type="submit" name="submit" value="Add" class="add"></td>
</tr>
<tr>
<td class="sno">2</td>
<td class="cust">B</td>
<td class="combat">8</td>
<td><input type="number" id="qnty2" name="Qnty" value="0" class="combat text"></td>
<td><span class="total-combat"></span></td>
<td><input type="submit" name="submit" value="Add" class="add"></td>
</tr>
<tr>
<td class="sno">3</td>
<td class="cust">C</td>
<td class="combat">7</td>
<td><input type="number" id="qnty3" name="Qnty" value="0" class="combat text"></td>
<td><span class="total-combat"></span></td>
<td><input type="submit" name="submit" value="Add" class="add"></td>
</tr>
<tr>
<td class="sno">4</td>
<td class="cust">D</td>
<td class="combat">2</td>
<td><input type="number" id="qnty4" name="Qnty" value="0" class="combat text"></td>
<td><span class="total-combat"></span></td>
<td><input type="submit" name="submit" value="Add" class="add"></td>
</tr>
</tbody>
</table>
<table class="tbl1">
<thead>
<tr>
<th>S.No</th>
<th>P.Name</th>
<th>Price</th>
<th>Qnty</th>
<th>Rate</th>
<th>action</th>
</tr>
</thead>
<tbody class="tb">
</tbody>
</table>
<button type="submit" name="addtocart" id="btn">Add-to-cart</button>
</div>
</body>
</html>
In 2020, this is still not possible on Mobile Safari.
The next best solution is to show instructions on the steps to adding your page to the homescreen.
Picture is from this great article which covers that an many other tips on how to make your PWA feel iOS native.
Add Following dependency in pom.xml
<dependency>
<groupId>com.oracle</groupId>
<artifactId>oracle</artifactId>
<version>10.2.0.2.0</version>
</dependency>
For using the FileOutputStream try this :
public class Main01{
public static void main(String[] args) throws FileNotFoundException{
FileOutputStream f = new FileOutputStream("file.txt");
PrintStream p = new PrintStream(f);
p.println("George.........");
p.println("Alain..........");
p.println("Gerard.........");
p.close();
f.close();
}
}
I ran into this same problem when I wanted to enable SSL to a project hosted on IIS 8. Finally the tool I used was OpenSSL, after many days fighting with makecert commands.The certificate is generated in Debian, but I could import it seamlessly into IIS 7 and 8.
Download the OpenSSL compatible with your OS and this configuration file. Set the configuration file as default configuration of OpenSSL.
First we will generate the private key and certificate of Certification Authority (CA). This certificate is to sign the certificate request (CSR).
You must complete all fields that are required in this process.
openssl req -new -x509 -days 3650 -extensions v3_ca -keyout root-cakey.pem -out root-cacert.pem -newkey rsa:4096
You can create a configuration file with default settings like this: Now we will generate the certificate request, which is the file that is sent to the Certification Authorities.
The Common Name must be set the domain of your site, for example: public.organization.com.
openssl req -new -nodes -out server-csr.pem -keyout server-key.pem -newkey rsa:4096
Now the certificate request is signed with the generated CA certificate.
openssl x509 -req -days 365 -CA root-cacert.pem -CAkey root-cakey.pem -CAcreateserial -in server-csr.pem -out server-cert.pem
The generated certificate must be exported to a .pfx file that can be imported into the IIS.
openssl pkcs12 -export -out server-cert.pfx -inkey server-key.pem -in server-cert.pem -certfile root-cacert.pem -name "Self Signed Server Certificate"
In this step we will import the certificate CA.
In your server must import the CA certificate to the Trusted Root Certification Authorities, for IIS can trust the certificate to be imported. Remember that the certificate to be imported into the IIS, has been signed with the certificate of the CA.
With this step, the IIS trust on the authenticity of our certificate.
In our last step we will import the certificate to IIS and add the binding site.
Now go to your site on IIS Manager and select Bindings... and Add a new binding.
Select https as the type of binding and you should be able to see the imported certificate.
Most of the answers above are either deprecated or the zoom works by retaining the current latitude and longitude and does not zoom to the exact location you want it to. Add the following code to your onMapReady() method.
@Override
public void onMapReady(GoogleMap googleMap) {
//Set marker on the map
googleMap.addMarker(new MarkerOptions().position(new LatLng(0.0000, 0.0000)).title("Marker"));
//Create a CameraUpdate variable to store the intended location and zoom of the camera
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(0.0000, 0.0000), 13);
//Animate the zoom using the animateCamera() method
googleMap.animateCamera(cameraUpdate);
}
Yet another adaptation because non of the answers would suffice my needs. First of all if rand() is used to generate random numbers you will get the same output at each run. The seed for random number generator has to be some sort of random. With C++11 you can include "random" library and you can initialize the seed with random_device and mt19937. This seed will be supplied by the OS and it will be random enough for us(for ex: clock). You can give a range boundaries are included [0,25] in my case. And last but not least I only needed random string of lowercase letters so I utilized char addition. With a pool of characters approach did not work out for me.
#include <random>
void gen_random(char *s, const int len){
static std::random_device rd;
static std::mt19937 mt(rd());
static std::uniform_int_distribution<int> dist(0, 25);
for (int i = 0; i < len; ++i) {
s[i] = 'a' + dist(mt);
}
s[len] = 0;
}
To add a Visual Studio GUI reference, you can find the DropDownStyle
options under the Properties of the selected ComboBox:
Which will automatically add the line mentioned in the first answer to the Form.Designer.cs InitializeComponent()
, like so:
this.comboBoxBatch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
There is another option that does not introduce global gotchas when trying to initialize multiple variables to the same value. Whether or not it is preferable to the long way is a judgement call. It will likely be slower and may or may not be more readable. In your specific case, I think that the long way is probably more readable and maintainable as well as being faster.
The other way utilizes Destructuring assignment.
let [moveUp, moveDown,_x000D_
moveLeft, moveRight,_x000D_
mouseDown, touchDown] = Array(6).fill(false);_x000D_
_x000D_
console.log(JSON.stringify({_x000D_
moveUp, moveDown,_x000D_
moveLeft, moveRight,_x000D_
mouseDown, touchDown_x000D_
}, null, ' '));_x000D_
_x000D_
// NOTE: If you want to do this with objects, you would be safer doing this_x000D_
let [obj1, obj2, obj3] = Array(3).fill(null).map(() => ({}));_x000D_
console.log(JSON.stringify({_x000D_
obj1, obj2, obj3_x000D_
}, null, ' '));_x000D_
// So that each array element is a unique object_x000D_
_x000D_
// Or another cool trick would be to use an infinite generator_x000D_
let [a, b, c, d] = (function*() { while (true) yield {x: 0, y: 0} })();_x000D_
console.log(JSON.stringify({_x000D_
a, b, c, d_x000D_
}, null, ' '));_x000D_
_x000D_
// Or generic fixed generator function_x000D_
function* nTimes(n, f) {_x000D_
for(let i = 0; i < n; i++) {_x000D_
yield f();_x000D_
}_x000D_
}_x000D_
let [p1, p2, p3] = [...nTimes(3, () => ({ x: 0, y: 0 }))];_x000D_
console.log(JSON.stringify({_x000D_
p1, p2, p3_x000D_
}, null, ' '));
_x000D_
This allows you to initialize a set of var
, let
, or const
variables to the same value on a single line all with the same expected scope.
References:
MDN: Array Global Object
MDN: Array.fill
For the instance of
render :json => @projects, :include => :tasks
You are stating that you want to render @projects
as JSON, and include the association tasks
on the Project model in the exported data.
For the instance of
render :json => @projects, :callback => 'updateRecordDisplay'
You are stating that you want to render @projects
as JSON, and wrap that data in a javascript call that will render somewhat like:
updateRecordDisplay({'projects' => []})
This allows the data to be sent to the parent window and bypass cross-site forgery issues.
Most browsers will let you put very large amounts of data in a URL and thus lots of things end up creating very large URLs so if you are talking about anything more than the domain part of a URL you will need to use a TEXT column since the VARCHAR/CHAR are limited.
Notepad++ will forget your macros unless you map them to hotkeys via Settings - Shortcut mapper - Macros before exiting Notepad++ (as per https://superuser.com/questions/332481/how-can-i-add-a-macro-in-notepad. Tested with Notepad v6.8.3 on Windows7.)
This mostly happens when you take a SECRET key and pass it to elastic client.
e.g: Secret Key: ABCW1233**+OxMMMMMMM8x**
While configuring in the client, You should only pass: ABCW1233**(The part before the + sign).
Windows uses .cer extension for an X.509 certificate. These can be in "binary" (ASN.1 DER), or it can be encoded with Base-64 and have a header and footer applied (PEM); Windows will recognize either. To verify the integrity of a certificate, you have to check its signature using the issuer's public key... which is, in turn, another certificate.
Windows uses .pfx for a PKCS #12 file. This file can contain a variety of cryptographic information, including certificates, certificate chains, root authority certificates, and private keys. Its contents can be cryptographically protected (with passwords) to keep private keys private and preserve the integrity of root certificates.
Windows uses .pvk for a private key file. I'm not sure what standard (if any) Windows follows for these. Hopefully they are PKCS #8 encoded keys. Emmanuel Bourg reports that these are a proprietary format. Some documentation is available.
You should never disclose your private key. These are contained in .pfx and .pvk files.
Generally, you only exchange your certificate (.cer) and the certificates of any intermediate issuers (i.e., the certificates of all of your CAs, except the root CA) with other parties.
(1) How do I ... build those URI's? Do I need to write a PHP code at that URI?
There is no standard for how an API URI scheme should be set up, but it's common to have slash-separated values. For this you can use...
$apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
...to get an array of slash-separated values in the URI after the file name.
Example: Assuming you have an API file api.php
in your application somewhere and you do a request for api.php/members/3
, then $apiArgArray
will be an array containing ['members', '3']
. You can then use those values to query your database or do other processing.
(2) How do I build the JSON objects to return as a response?
You can take any PHP object and turn it into JSON with json_encode. You'll also want to set the appropriate header.
header('Content-Type: application/json');
$myObject = (object) array( 'property' => 'value' ); // example
echo json_encode($myObject); // outputs JSON text
All this is good for an API that returns JSON, but the next question you should ask is:
(3) How do I make my API RESTful?
For that we'll use $_SERVER['REQUEST_METHOD']
to get the method being used, and then do different things based on that. So the final result is something like...
header('Content-Type: application/json');
$apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
$returnObject = (object) array();
/* Based on the method, use the arguments to figure out
whether you're working with an individual or a collection,
then do your processing, and ultimately set $returnObject */
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
// List entire collection or retrieve individual member
break;
case 'PUT':
// Replace entire collection or member
break;
case 'POST':
// Create new member
break;
case 'DELETE':
// Delete collection or member
break;
}
echo json_encode($returnObject);
Sources: https://stackoverflow.com/a/897311/1766230 and http://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_web_services
Microsoft API Code Pack. ShellObjectWatcher class.
I would recommend storing these as numbers in columns of type varchar - one column per "field" (like contry code etc.).
The format should be applied when you interact with a user... that makes it easier to account for format changes for example and will help esp. when your application goes international...
Here's a solution I've used that I was a little surprised hasn't been added yet.
There are two parts to it. First part is setting the default in the actual migration, and the second part is adding a validation in the model ensuring that the presence is true.
add_column :teams, :new_team_signature, :string, default: 'Welcome to the Team'
So you'll see here that the default is already set. Now in the validation you want to ensure that there is always a value for the string, so just do
validates :new_team_signature, presence: true
What this will do is set the default value for you. (for me I have "Welcome to the Team"), and then it will go one step further an ensure that there always is a value present for that object.
Hope that helps!
At first, open your Bash Profile in your home directory. The easiest way to open & edit your bash_profile using your default editor.
For example, I open it using the VS Code using this command: code .bash_profile.
Then just paste the following codes to your Bash.
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "
The function
parse_git_branch()
will fetch the branch name & then through PS1 you can show it in your terminal.
Here,
\u = Username
@ = Static Text
\h = Computer Name
\w = Current Directory
$ = Static Text
You can change or remove these variables for more customization.
If you use Git for the first time in terminal or instantly after configuration, maybe sometimes you can not see the branch name.
If you get this problem, don't worry. In that case, just make a sample repository and commit it after some changes. When the commit command will execute once, the terminal will find git branch from then.
I always add this style to my Bootstrap LESS / SASS:
.row-no-padding {
[class*="col-"] {
padding-left: 0 !important;
padding-right: 0 !important;
}
}
Then in the HTML you can write:
<div class="row row-no-padding">
How about this?
if (window.location.protocol !== 'https:') {
window.location = 'https://' + window.location.hostname + window.location.pathname + window.location.hash;
}
Ideally you'd do it on the server side, though.
foo = {}
foo[#foo+1]="bar"
foo[#foo+1]="baz"
This works because the #
operator computes the length of the list. The empty list has length 0, etc.
If you're using Lua 5.3+, then you can do almost exactly what you wanted:
foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"
Expressions are not statements in Lua and they need to be used somehow.
Your onclick
fires before the href so it will change before the page is opened, you need to make the function handle the window opening like so:
function changeLink() {
var link = document.getElementById("mylink");
window.open(
link.href,
'_blank'
);
link.innerHTML = "facebook";
link.setAttribute('href', "http://facebook.com");
return false;
}
An example, available for POSIX compliant systems :
/*
* This program displays the names of all files in the current directory.
*/
#include <dirent.h>
#include <stdio.h>
int main(void) {
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}
Beware that such an operation is platform dependant in C.
Source : http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608
A simple modification to henrik's answer to touch most required possibilities.
function isValidJson($string) {
json_decode($string);
if(json_last_error() == JSON_ERROR_NONE) {
if( $string[0] == "{" || $string[0] == "[" ) {
$first = $string [0];
if( substr($string, -1) == "}" || substr($string, -1) == "]" ) {
$last = substr($string, -1);
if($first == "{" && $last == "}"){
return true;
}
if($first == "[" && $last == "]"){
return true;
}
return false;
}
return false;
}
return false;
}
return false;
}
You can easily make SSH connections using SSHLibrary. Read this post :
https://workpython.blogspot.com/2020/04/creating-ssh-connections-with-python.html
delete your certificate in your dev then Reinstall and it will working!
Jscript is a .NET language similar to C#, with the same capabilities and access to all the .NET functions.
JavaScript is run on the ASP Classic server. Use Classic ASP to run the same JavaScript that you have on the Client (excluding HTML5 capabilities). I only have one set of code this way for most of my code.
I run .ASPX JScript when I require Image and Binary File functions, (among many others) that are not in Classic ASP. This code is unique for the server, but extremely powerful.
echo "<p><a href=\"javascript:history.go(-1)\" title=\"Return to previous page\">«Go back</a></p>";
Will go back one page.
echo "<p><a href=\"javascript:history.go(-2)\" title=\"Return to previous page\">«Go back</a></p>";
Will go back two pages.
As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:
xlrd has explicitly removed support for anything other than xls files.
In your case, the solution is to:
openpyxl
: https://openpyxl.readthedocs.io/en/stable/df1 = pd.read_excel(
os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
engine='openpyxl',
)
In my scenario, I've got an MVC app and WebAPI in one solution, and I'm using local IIS (not express).
I also set up the sites in IIS as real domains, and edited my host file so that I can type in the real domain and everything works. I also noticed 2 things:
The MVC code debugging was working perfectly.
Attaching to process worked perfectly too. Just when I was debugging it didn't hit the breakpoint in my API.
This was the solution for me:
Right click webapi project > properties > Web > Project URL
By default it points to localhost, but since I set up the site in IIS, I forgot to change the URL to the website domain (i.e. instead of locahost, it should say http://{domain-name}/).
I've faced with the same problem, have struggled a couple of day with it and should say that the most easiest way to overcome I found this is to use fragment.hide() / fragment.show() when tab is selected/unselected().
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft)
{
if (mFragment != null)
ft.hide(mFragment);
}
When screen rotation occurs all parent and child fragments get correctly destroyed.
This approach has also one additional advantage - using hide()/show() does not cause fragment views to loose their state, so there is no need to restore the previous scroll position for ScrollViews for example.
The problem is that I don't know whether it is correct to not detach fragments when they are not visible. I think the official example of TabListener is designed with a thought in mind that fragments are reusable and you should not pollute with them memory, however, I think if you have just a few tabs and you know that users will be switching between them frequently it will be appropriate to keep them attached to the current activity.
I would like to hear comments from more experienced developers.
I couldn't quite get there in my use case from the examples above, but Ahmad got me the closest (thank you). For those reading this in the future, here is the code that worked for me.
def get_class(fully_qualified_path, module_name, class_name, *instantiation):
"""
Returns an instantiated class for the given string descriptors
:param fully_qualified_path: The path to the module eg("Utilities.Printer")
:param module_name: The module name eg("Printer")
:param class_name: The class name eg("ScreenPrinter")
:param instantiation: Any fields required to instantiate the class
:return: An instance of the class
"""
p = __import__(fully_qualified_path)
m = getattr(p, module_name)
c = getattr(m, class_name)
instance = c(*instantiation)
return instance
Other simple way is to do this:
string path = @"C:\Folder1\Folder2\Folder3\Folder4";
string newPath = Path.GetFullPath(Path.Combine(path, @"..\..\"));
Note This goes two levels up. The result would be:
newPath = @"C:\Folder1\Folder2\";
1. Basic Concept -
When you declare as follows : -
1. char *ch - (called character pointer)
- ch contains the address of a single character.
- (*ch) will dereference to the value of the character..
2. char **ch -
'ch' contains the address of an Array of character pointers. (as in 1)
'*ch' contains the address of a single character. (Note that it's different from 1, due to difference in declaration).
(**ch) will dereference to the exact value of the character..
Adding more pointers expand the dimension of a datatype, from character to string, to array of strings, and so on... You can relate it to a 1d, 2d, 3d matrix..
So, the usage of pointer depends upon how you declare it.
Here is a simple code..
int main()
{
char **p;
p = (char **)malloc(100);
p[0] = (char *)"Apple"; // or write *p, points to location of 'A'
p[1] = (char *)"Banana"; // or write *(p+1), points to location of 'B'
cout << *p << endl; //Prints the first pointer location until it finds '\0'
cout << **p << endl; //Prints the exact character which is being pointed
*p++; //Increments for the next string
cout << *p;
}
2. Another Application of Double Pointers -
(this would also cover pass by reference)
Suppose you want to update a character from a function. If you try the following : -
void func(char ch)
{
ch = 'B';
}
int main()
{
char ptr;
ptr = 'A';
printf("%c", ptr);
func(ptr);
printf("%c\n", ptr);
}
The output will be AA. This doesn't work, as you have "Passed By Value" to the function.
The correct way to do that would be -
void func( char *ptr) //Passed by Reference
{
*ptr = 'B';
}
int main()
{
char *ptr;
ptr = (char *)malloc(sizeof(char) * 1);
*ptr = 'A';
printf("%c\n", *ptr);
func(ptr);
printf("%c\n", *ptr);
}
Now extend this requirement for updating a string instead of character.
For this, you need to receive the parameter in the function as a double pointer.
void func(char **str)
{
strcpy(str, "Second");
}
int main()
{
char **str;
// printf("%d\n", sizeof(char));
*str = (char **)malloc(sizeof(char) * 10); //Can hold 10 character pointers
int i = 0;
for(i=0;i<10;i++)
{
str = (char *)malloc(sizeof(char) * 1); //Each pointer can point to a memory of 1 character.
}
strcpy(str, "First");
printf("%s\n", str);
func(str);
printf("%s\n", str);
}
In this example, method expects a double pointer as a parameter to update the value of a string.
According to your query
Select * from [User] U where U.DateCreated = '2014-02-07'
SQL Server is comparing exact date and time i.e (comparing 2014-02-07 12:30:47.220
with 2014-02-07 00:00:00.000
for equality). that's why result of comparison is false
Therefore, While comparing dates you need to consider time also. You can use
Select * from [User] U where U.DateCreated BETWEEN '2014-02-07' AND '2014-02-08'
.
You must add the these attributes which is compulsary to marquee
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
I usually don't like to guess, but I'm going to on this one...
If you remember Microsoft's .NET marketing hype back in the day (2001?), it was hard to tell what .NET even was. Was it a server? a programming platform? a language? something new entirely? Given the ads, it was ambiguously anything you wanted it to be - it just solved any problem you might have.
So, my guess is there was a hidden grand vision that ASP.NET code could run anywhere - server side OR client side, in a copy of Internet Explorer tied to the .NET runtime. runat="server" is just a vestigial remnant, left behind because it's client-side equivalent never made it to production.
Remember those weird ads?
Related: Article from The Register with some .NET history.
Simple answer with sample answer ;-)
on iOS Simulator,
Press Command + control + c or from menu : Edit>Copy Screen
open "Preview" app, Press Command + n or from menu : File> New from clipboard , then you can save Command + s
UnCheck Alpha
You can change Image dimension to your requirement.
Here is the Final Image,For example
The above behavior is happening because of Branch prediction.
To understand branch prediction one must first understand Instruction Pipeline:
Any instruction is broken into a sequence of steps so that different steps can be executed concurrently in parallel. This technique is known as instruction pipeline and this is used to increase throughput in modern processors. To understand this better please see this example on Wikipedia.
Generally, modern processors have quite long pipelines, but for ease let's consider these 4 steps only.
4-stage pipeline in general for 2 instructions.
Moving back to the above question let's consider the following instructions:
A) if (data[c] >= 128)
/\
/ \
/ \
true / \ false
/ \
/ \
/ \
/ \
B) sum += data[c]; C) for loop or print().
Without branch prediction, the following would occur:
To execute instruction B or instruction C the processor will have to wait till the instruction A doesn't reach till EX stage in the pipeline, as the decision to go to instruction B or instruction C depends on the result of instruction A. So the pipeline will look like this.
when if condition returns true:
When if condition returns false:
As a result of waiting for the result of instruction A, the total CPU cycles spent in the above case (without branch prediction; for both true and false) is 7.
So what is branch prediction?
Branch predictor will try to guess which way a branch (an if-then-else structure) will go before this is known for sure. It will not wait for the instruction A to reach the EX stage of the pipeline, but it will guess the decision and go to that instruction (B or C in case of our example).
In case of a correct guess, the pipeline looks something like this:
If it is later detected that the guess was wrong then the partially executed instructions are discarded and the pipeline starts over with the correct branch, incurring a delay. The time that is wasted in case of a branch misprediction is equal to the number of stages in the pipeline from the fetch stage to the execute stage. Modern microprocessors tend to have quite long pipelines so that the misprediction delay is between 10 and 20 clock cycles. The longer the pipeline the greater the need for a good branch predictor.
In the OP's code, the first time when the conditional, the branch predictor does not have any information to base up prediction, so the first time it will randomly choose the next instruction. Later in the for loop, it can base the prediction on the history. For an array sorted in ascending order, there are three possibilities:
Let us assume that the predictor will always assume the true branch on the first run.
So in the first case, it will always take the true branch since historically all its predictions are correct. In the 2nd case, initially it will predict wrong, but after a few iterations, it will predict correctly. In the 3rd case, it will initially predict correctly till the elements are less than 128. After which it will fail for some time and the correct itself when it sees branch prediction failure in history.
In all these cases the failure will be too less in number and as a result, only a few times it will need to discard the partially executed instructions and start over with the correct branch, resulting in fewer CPU cycles.
But in case of a random unsorted array, the prediction will need to discard the partially executed instructions and start over with the correct branch most of the time and result in more CPU cycles compared to the sorted array.
try this
var date = new Date();
$.ajax(
{
type: "POST",
url: "/Group/Refresh",
contentType: "application/json; charset=utf-8",
data: "{ 'MyDate': " + date.getTimezoneOffset() + " }",
success: function (result) {
//do something
},
error: function (req, status, error) {
//error
}
});
In C#
DateTime.Now.ToUniversalTime().AddMinutes(double.Parse(MyDate)).ToString();
You can try using set operations: MINUS
and INTERSECT
See here for more details:
O'Reilly - Mastering Oracle SQL - Chapter 7 - Set Operations
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
urllib
and Django-like regexThe Django URL validation regex was actually pretty good but I needed to tweak it a little bit for my use case. Feel free to adapt it to yours!
import re
import urllib
# Check https://regex101.com/r/A326u1/5 for reference
DOMAIN_FORMAT = re.compile(
r"(?:^(\w{1,255}):(.{1,255})@|^)" # http basic authentication [optional]
r"(?:(?:(?=\S{0,253}(?:$|:))" # check full domain length to be less than or equal to 253 (starting after http basic auth, stopping before port)
r"((?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+" # check for at least one subdomain (maximum length per subdomain: 63 characters), dashes in between allowed
r"(?:[a-z0-9]{1,63})))" # check for top level domain, no dashes allowed
r"|localhost)" # accept also "localhost" only
r"(:\d{1,5})?", # port [optional]
re.IGNORECASE
)
SCHEME_FORMAT = re.compile(
r"^(http|hxxp|ftp|fxp)s?$", # scheme: http(s) or ftp(s)
re.IGNORECASE
)
def validate_url(url: str):
url = url.strip()
if not url:
raise Exception("No URL specified")
if len(url) > 2048:
raise Exception("URL exceeds its maximum length of 2048 characters (given length={})".format(len(url)))
result = urllib.parse.urlparse(url)
scheme = result.scheme
domain = result.netloc
if not scheme:
raise Exception("No URL scheme specified")
if not re.fullmatch(SCHEME_FORMAT, scheme):
raise Exception("URL scheme must either be http(s) or ftp(s) (given scheme={})".format(scheme))
if not domain:
raise Exception("No URL domain specified")
if not re.fullmatch(DOMAIN_FORMAT, domain):
raise Exception("URL domain malformed (domain={})".format(domain))
return url
scheme
and netloc
part of a given URL. (To do this properly, I split the URL with urllib.parse.urlparse()
in the two according parts which are then matched with the corresponding regex terms.)The netloc
part stops before the first occurrence of a slash /
, so port
numbers are still part of the netloc
, e.g.:
https://www.google.com:80/search?q=python
^^^^^ ^^^^^^^^^^^^^^^^^
| |
| +-- netloc (aka "domain" in my code)
+-- scheme
IPv4 addresses are also validated
If you want the URL validator to also work with IPv6 addresses, do the following:
is_valid_ipv6(ip)
from Markus Jarderot's answer, which has a really good IPv6 validator regexand not is_valid_ipv6(domain)
to the last if
Here are some examples of the regex for the netloc
(aka domain
) part in action:
I believe you could addClass to the element. But either way you'd have to use Jquery or reg JS
div {
opacity:0;
transition:opacity 1s linear;*
}
div.SomeClass {
opacity:1;
}
It may be a bit pedantic / redundant with its numeric casting, but here's a safe function to calculate percentage of a given number:
function getPerc(num, percent) {
return Number(num) - ((Number(percent) / 100) * Number(num));
}
// Usage: getPerc(10000, 25);
set -x
or set -o xtrace
expands variables and prints a little + sign before the line.
set -v
or set -o verbose
does not expand the variables before printing.
Use set +x
and set +v
to turn off the above settings.
On the first line of the script, one can put #!/bin/sh -x
(or -v
) to have the same effect as set -x
(or -v
) later in the script.
The above also works with /bin/sh
.
See the bash-hackers' wiki on set
attributes, and on debugging.
$ cat shl
#!/bin/bash
DIR=/tmp/so
ls $DIR
$ bash -x shl
+ DIR=/tmp/so
+ ls /tmp/so
$
I am providing my solution with the assumption on your business logic. Basicall in my design i will allow the table to store only one record for a user-game combination. So I will add a composite key to the table.
PRIMARY KEY (`user_id`,`game_id`)
Historically, the first extensions used for C++ were .c
and .h
, exactly like for C. This caused practical problems, especially the .c
which didn't allow build systems to easily differentiate C++ and C files.
Unix, on which C++ has been developed, has case sensitive file systems. So some used .C
for C++ files. Other used .c++
, .cc
and .cxx
. .C
and .c++
have the problem that they aren't available on other file systems and their use quickly dropped. DOS and Windows C++ compilers tended to use .cpp
, and some of them make the choice difficult, if not impossible, to configure. Portability consideration made that choice the most common, even outside MS-Windows.
Headers have used the corresponding .H
, .h++
, .hh
, .hxx
and .hpp
. But unlike the main files, .h
remains to this day a popular choice for C++ even with the disadvantage that it doesn't allow to know if the header can be included in C context or not. Standard headers now have no extension at all.
Additionally, some are using .ii
, .ixx
, .ipp
, .inl
for headers providing inline definitions and .txx
, .tpp
and .tpl
for template definitions. Those are either included in the headers providing the definition, or manually in the contexts where they are needed.
Compilers and tools usually don't care about what extensions are used, but using an extension that they associate with C++ prevents the need to track out how to configure them so they correctly recognize the language used.
2017 edit: the experimental module support of Visual Studio recognize .ixx
as a default extension for module interfaces, clang++ is recognizing .c++m
, .cppm
and .cxxm
for the same purpose.
All u need is just use one of the attribute of CSS , which is---->
cursor:pointer
just use this property in css , no matter its inline or internal or external
for example(for inline css)
<form>
<input type="submit" style= "cursor:pointer" value="Button" name="Button">
</form>
Java (at least 5 and 6, java 7 Paths solved most) has a problem with UNC and URI. Eclipse team wrapped it up here : http://wiki.eclipse.org/Eclipse/UNC_Paths
From java.io.File javadocs, the UNC prefix is "////", and java.net.URI handles file:////host/path (four slashes).
More details on why this happens and possible problems it causes in other URI and URL methods can be found in the list of bugs at the end of the link given above.
Using these informations, Eclipse team developed org.eclipse.core.runtime.URIUtil class, which source code can probably help out when dealing with UNC paths.
This is how I would go about it.
$posts = $this->post->orderBy('id', 'DESC')->get();
The parentheses are misplaced:
SELECT setval('payments_id_seq', 21, true); # next value will be 22
Otherwise you're calling setval
with a single argument, while it requires two or three.
See doco for setText() in TextView http://developer.android.com/reference/android/widget/TextView.html
To style your strings, attach android.text.style.* objects to a SpannableString, or see the Available Resource Types documentation for an example of setting formatted text in the XML resource file.
Remy Sharp has a good description of the process in his article "Doing it right: skipping the iPhone url bar":
Making the iPhone hide the url bar is fairly simple, you need run the following JavaScript:
window.scrollTo(0, 1);
However there's the question of when? You have to do this once the height is correct so that the iPhone can scroll to the first pixel of the document, otherwise it will try, then the height will load forcing the url bar back in to view.
You could wait until the images have loaded and the window.onload event fires, but this doesn't always work, if everything is cached, the event fires too early and the scrollTo never has a chance to jump. Here's an example using window.onload: http://jsbin.com/edifu4/4/
I personally use a timer for 1 second - which is enough time on a mobile device while you wait to render, but long enough that it doesn't fire too early:
setTimeout(function () { window.scrollTo(0, 1); }, 1000);
However, you only want this to setup if it's an iPhone (or just mobile) browser, so a sneaky sniff (I don't generally encourage this, but I'm comfortable with this to prevent "normal" desktop browsers from jumping one pixel):
/mobile/i.test(navigator.userAgent) && setTimeout(function () { window.scrollTo(0, 1); }, 1000);
The very last part of this, and this is the part that seems to be missing from some examples I've seen around the web is this: if the user specifically linked to a url fragment, i.e. the url has a hash on it, you don't want to jump. So if I navigate to http://full-frontal.org/tickets#dayconf - I want the browser to scroll naturally to the element whose id is dayconf, and not jump to the top using scrollTo(0, 1):
/mobile/i.test(navigator.userAgent) && !location.hash && setTimeout(function () { window.scrollTo(0, 1); }, 1000);?
Try this out on an iPhone (or simulator) http://jsbin.com/edifu4/10 and you'll see it will only scroll when you've landed on the page without a url fragment.
File
> Import
> General
> Existing Projects into workspace
.
Select the root folder that has your project(s). It lists all the projects available in the selected folder. Select the ones you would like to import and click Finish
. This should work just fine.
For Windows users:
If you go to Task Manager, choose the eclipse application, and click on the little arrow next to it, you will usually just see one sub-process appear below "eclipse.exe". However, in my case, if you have multiple instances of "Java Platform SE Binary", then end all of them. For some reason, I had three of these running in the background, even though I wasn't currently running any projects. Nevertheless, this will boost performance back to the way it likely was when you first installed eclipse on your computer.
If you can no longer run a project after the change, then try relaunching eclipse.
Generate your own API key here. Check out the documentation here.
You may need to set up a billing account when you try to enable the Google Cloud Translation API
in your account.
Below is a quick start example which translates two English
strings to Spanish
:
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.translate.Translate;
import com.google.api.services.translate.model.TranslationsListResponse;
import com.google.api.services.translate.model.TranslationsResource;
public class QuickstartSample
{
public static void main(String[] arguments) throws IOException, GeneralSecurityException
{
Translate t = new Translate.Builder(
GoogleNetHttpTransport.newTrustedTransport()
, GsonFactory.getDefaultInstance(), null)
// Set your application name
.setApplicationName("Stackoverflow-Example")
.build();
Translate.Translations.List list = t.new Translations().list(
Arrays.asList(
// Pass in list of strings to be translated
"Hello World",
"How to use Google Translate from Java"),
// Target language
"ES");
// TODO: Set your API-Key from https://console.developers.google.com/
list.setKey("your-api-key");
TranslationsListResponse response = list.execute();
for (TranslationsResource translationsResource : response.getTranslations())
{
System.out.println(translationsResource.getTranslatedText());
}
}
}
Required maven dependencies for the code snippet:
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-translate</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-gson</artifactId>
<version>LATEST</version>
</dependency>
Consider using onUserLeaveHint. This will only be called when your app goes into the background. onPause will have corner cases to handle, since it can be called for other reasons; for example if the user opens another activity in your app such as your settings page, your main activity's onPause method will be called even though they are still in your app; tracking what is going in will lead to bugs when you can instead simply use the onUserLeaveHint callback which does what you are asking.
When on UserLeaveHint is called, you can set a boolean inBackground flag to true. When onResume is called, only assume you came back into the foreground if the inBackground flag is set. This is because onResume will also be called on your main activity if the user was just in your settings menu and never left the app.
Remember that if the user hits the home button while in your settings screen, onUserLeaveHint will be called in your settings activity, and when they return onResume will be called in your settings activity. If you only have this detection code in your main activity you will miss this use case. To have this code in all your activities without duplicating code, have an abstract activity class which extends Activity, and put your common code in it. Then each activity you have can extend this abstract activity.
For example:
public abstract AbstractActivity extends Activity {
private static boolean inBackground = false;
@Override
public void onResume() {
if (inBackground) {
// You just came from the background
inBackground = false;
}
else {
// You just returned from another activity within your own app
}
}
@Override
public void onUserLeaveHint() {
inBackground = true;
}
}
public abstract MainActivity extends AbstractActivity {
...
}
public abstract SettingsActivity extends AbstractActivity {
...
}
the simplest way to copy a List is to pass it to the constructor of the new list:
List<String> b = new ArrayList<>(a);
b
will be a shallow copy of a
Looking at the source of Collections.copy(List,List)
(I'd never seen it before) it seems to be for coping the elements index by index. using List.set(int,E)
thus element 0 will over write element 0 in the target list etc etc. Not particularly clear from the javadocs I'd have to admit.
List<String> a = new ArrayList<>(a);
a.add("foo");
b.add("bar");
List<String> b = new ArrayList<>(a); // shallow copy 'a'
// the following will all hold
assert a.get(0) == b.get(0);
assert a.get(1) == b.get(1);
assert a.equals(b);
assert a != b; // 'a' is not the same object as 'b'
Right Click on Project--> Add--> New Project-->click on Class Library.
Now your class library is created as class1.cs
Right Click on References(of your program/console app)
-->Add Reference-->classLibrary1(whatever you named) Now mention "using ClassLibrary1" in your program/console app
Now u can easily call the method/property in your console app
Be aware that HttpOnly doesn't stop cross-site scripting; instead, it neutralizes one possible attack, and currently does that only on IE (FireFox exposes HttpOnly cookies in XmlHttpRequest, and Safari doesn't honor it at all). By all means, turn HttpOnly on, but don't drop even an hour of output filtering and fuzz testing in trade for it.
It's time I post an answer about RVO, me too...
If you return an object by value, the compiler often optimizes this so it doesn't get constructed twice, since it's superfluous to construct it in the function as a temporary and then copy it. This is called return value optimization: the created object will be moved instead of being copied.
Please use .size() function instead of .length and also specify li tag in selector.
Change your code like.
if ( $('#menu ul li').size() > 1 ) {
/**
* Singleton class
*
*/
final class UserFactory
{
/**
* Call this method to get singleton
*
* @return UserFactory
*/
public static function Instance()
{
static $inst = null;
if ($inst === null) {
$inst = new UserFactory();
}
return $inst;
}
/**
* Private ctor so nobody else can instantiate it
*
*/
private function __construct()
{
}
}
To use:
$fact = UserFactory::Instance();
$fact2 = UserFactory::Instance();
$fact == $fact2;
But:
$fact = new UserFactory()
Throws an error.
See http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static to understand static variable scopes and why setting static $inst = null;
works.
Code check:
This is offtopic here but the people over at CodeReview are more than happy to help you.
I strongly suggest you to do so, there are several things that need attention in your code. Likewise I suggest that you do start reading tutorials since there is really no good reason not to do so.
Lists:
As you said yourself: you need a list of items. The way it is now you only store a reference to one item. Lucky there is exactly that to hold a group of related objects: a List
.
Lists are very straightforward to use but take a look at the related documentation anyway.
A very simple example to keep multiple bikes in a list:
List<Motorbike> bikes = new List<Motorbike>();
bikes.add(new Bike { make = "Honda", color = "brown" });
bikes.add(new Bike { make = "Vroom", color = "red" });
And to iterate over the list you can use the foreach
statement:
foreach(var bike in bikes) {
Console.WriteLine(bike.make);
}
git reset --soft origin/my_remote_tracking_branch
This way you will not loose your local changes
You need to use HAVING
, not WHERE
.
The difference is: the WHERE
clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT
function.
HAVING
is like WHERE
, only it happens after the COUNT
value has been computed, so it'll work as you expect. Rewrite your subquery as:
( -- where that pid is in the set:
SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)
Adding another option - based on the excepted answer.
For Typescript:
import { Injectable } from '@nestjs/common';
import { parse } from 'node-html-parser';
import * as fs from 'fs';
import * as path from 'path'
@Injectable()
export class HtmlParserService {
getDocument(id: string): string {
const htmlRAW = fs.readFileSync(
path.join(__dirname, "../assets/files/some_file.html"),
"utf8"
);
const parsedHtml = parse(htmlRAW);
const className = '.'+id;
//Debug
//console.log(parsedHtml.querySelectorAll(className));
return parsedHtml.querySelectorAll(className).toString();
}
}
(*) Example above is using with nestjs and node-html-parser.
The problem is that 2011-01-31 really is 2011-01-31 00:00:00. That is the beginning of the day. Everything during the day is not included.
First, run
sudo apt-get install nodejs-dev node-gyp libssl1.0-dev
then run
sudo apt install npm
var element = document.getElementById(element_id);
element.className += " " + newClassName;
Voilà. This will work on pretty much every browser ever. The leading space is important, because the className
property treats the css classes like a single string, which ought to match the class
attribute on HTML elements (where multiple classes must be separated by spaces).
Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.
In prototype, for instance:
// Prototype automatically checks that the element doesn't already have the class
$(element_id).addClassName(newClassName);
See how much nicer that is?!
You can do it like this:
uint8_t (*matrix_ptr)[10][20] = &l_matrix;
Use the correct call: strptime
is a classmethod of the datetime.datetime
class, it's not a function in the datetime
module.
self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")
As mentioned by Jon Clements in the comments, some people do from datetime import datetime
, which would bind the datetime
name to the datetime
class, and make your initial code work.
To identify which case you're facing (in the future), look at your import statements
import datetime
: that's the module (that's what you have right now).from datetime import datetime
: that's the class.This is my code:
try {_x000D_
String folderPath = "../" + filePath.trim() + "/";_x000D_
logger.info("Path: " + folderPath);_x000D_
File folder = new File(folderPath);_x000D_
File[] listOfFiles = folder.listFiles();_x000D_
int length = listOfFiles.length;_x000D_
logger.info("So luong files: " + length);_x000D_
ArrayList<CdrFileBO> lstFile = new ArrayList< CdrFileBO>();_x000D_
_x000D_
if (listOfFiles != null && length > 0) {_x000D_
int count = 0;_x000D_
for (int i = 0; i < length; i++) {_x000D_
if (listOfFiles[i].isFile()) {_x000D_
lstFile.add(new CdrFileBO(listOfFiles[i]));_x000D_
}_x000D_
}_x000D_
Collections.sort(lstFile);_x000D_
for (CdrFileBO bo : lstFile) {_x000D_
//String newName = START_NAME + "_" + getSeq(SEQ_START) + "_" + DateSTR + ".s";_x000D_
String newName = START_NAME + DateSTR + getSeq(SEQ_START) + ".DAT";_x000D_
SEQ_START = SEQ_START + 1;_x000D_
bo.getFile().renameTo(new File(folderPath + newName));_x000D_
logger.info("newName: " + newName);_x000D_
logger.info("Next file: " + getSeq(SEQ_START));_x000D_
}_x000D_
_x000D_
}_x000D_
} catch (Exception ex) {_x000D_
logger.error(ex);_x000D_
ex.printStackTrace();_x000D_
}
_x000D_
<input style="border:none" >
Worked well for me. Wished to have it fixed in html itself ... :)
If you attempt to commit, and if there are conflicts, then git will give you the list of the currently unresolved conflicts... but not as a plain list. This is usually what you want when working interactively because the list gets shorter as you fix the conflicts.
I got a better way to hide static cells and even sections dynamically without any hacks.
Setting the row height to 0 can hide a row, but that doesn't work if you want to hide an entire section which will hold some spaces even you hide all the rows.
My approach is to build a section array of static cells. Then the table view contents will be driven by the section array.
Here is some sample code:
var tableSections = [[UITableViewCell]]()
private func configTableSections() {
// seciton A
tableSections.append([self.cell1InSectionA, self.cell2InSectionA])
// section B
if shouldShowSectionB {
tableSections.append([self.cell1InSectionB, self.cell2InSectionB])
}
// section C
if shouldShowCell1InSectionC {
tableSections.append([self.cell1InSectionC, self.cell2InSectionC, self.cell3InSectionC])
} else {
tableSections.append([self.cell2InSectionC, self.cell3InSectionC])
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return tableSections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableSections[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableSections[indexPath.section][indexPath.row]
}
This way, you can put all of your configuration code together without having to write the nasty code to calculate number of rows and sections. And of course, no 0
heights anymore.
This code is also very easy maintain. For example, if you want to add/remove more cells or sections.
Similarly, you can create a section header title array and section footer title array to config your section titles dynamically.
"each" uses callback function. Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
You could find the difference between dates in columns in a data frame by using the function difftime
as follows:
df$diff_in_days<- difftime(df$datevar1 ,df$datevar2 , units = c("days"))
I like the Infragistics controls. The WebDropDown has what you need. The only drawback is they can be a bit spendy.
The problem with all of these answers for me was they weren't responsive. I had to have a fixed height for a parent div which i didn't want. I also didn't want to spend a ton of time dinking around with media queries. If you are using angular, you can use bootstraps tabset and it will do all of the hard work for you. You'll be able to scroll the inner content and it will be responsive. When you setup the tab, do it like this: $scope.tab = { title: '', url: '', theclass: '', ative: true };
... the point is, you don't want a title or image icon. then hide the outline of the tab in cs like this:
.nav-tabs {
border-bottom:none;
}
and also this .nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus {border:none;}
and finally to remove the invisible tab that you can still click on if you don't implement this: .nav > li > a {padding:0px;margin:0px;}
FIRST: make sure you have a color as a bitmap, like this:
Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
paintcolor = bmp.GetPixel(e.X, e.Y);
(e is from the event handler wich picked my color!)
What I did when I had this problem a whilke ago, I first got the rgba (red, green, blue and alpha) values. Next I created 3 floats: float hue, float saturation, float brightness. Then you simply do:
hue = yourcolor.Gethue;
saturation = yourcolor.GetSaturation;
brightness = yourcolor.GetBrightness;
The whole lot looks like this:
Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
paintcolor = bmp.GetPixel(e.X, e.Y);
float hue;
float saturation;
float brightness;
hue = paintcolor.GetHue();
saturation = paintcolor.GetSaturation();
brightness = paintcolor.GetBrightness();
If you now want to display them in a label, just do:
yourlabelname.Text = hue.ToString;
yourlabelname.Text = saturation.ToString;
yourlabelname.Text = brightness.ToString;
Here you go, you now have RGB Values into HSV values :)
Hope this helps
One really simple option is to install a Windows bash shell such as MinGW and use that:
There is a little bit of a learning curve as you will need to use Unix command line functionality, but you will love the power of it and you can set the console character set to UTF-8.
Of course you also get all the usual *nix goodies like grep, find, less, etc.
sys.argv
is the list of command line arguments passed to a Python script, where sys.argv[0]
is the script name itself.
It is erroring out because you are not passing any commandline argument, and thus sys.argv
has length 1 and so sys.argv[1]
is out of bounds.
To "fix", just make sure to pass a commandline argument when you run the script, e.g.
python ConcatenateFiles.py /the/path/to/the/directory
However, you likely wanted to use some default directory so it will still work when you don't pass in a directory:
cur_dir = sys.argv[1] if len(sys.argv) > 1 else '.'
with open(cur_dir + '/Concatenated.csv', 'w+') as outfile:
try:
with open(cur_dir + '/MatrixHeader.csv') as headerfile:
for line in headerfile:
outfile.write(line + '\n')
except:
print 'No Header File'
Try this:
UPDATE test
SET
field = 1
WHERE id = 123 and condition
If you are using Jrockit VM then here is an other way of getting VM CPU usage. Runtime bean can also give you CPU load per processor. I have used this only on Red Hat Linux to observer Tomcat performance. You have to enable JMX remote in catalina.sh for this to work.
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://my.tomcat.host:8080/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
MBeanServerConnection conn = jmxc.getMBeanServerConnection();
ObjectName name = new ObjectName("oracle.jrockit.management:type=Runtime");
Double jvmCpuLoad =(Double)conn.getAttribute(name, "VMGeneratedCPULoad");
If you want it to stop looking after a while (timeout) then the following jQuery will work. It will time out after 10sec. I needed to use this code rather than pure JS because I needed to select an input via name and was having trouble implementing some of the other solutions.
// Wait for element to exist.
function imageLoaded(el, cb,time) {
if ($(el).length) {
// Element is now loaded.
cb($(el));
var imageInput = $('input[name=product\\[image_location\\]]');
console.log(imageInput);
} else if(time < 10000) {
// Repeat every 500ms.
setTimeout(function() {
time = time+500;
imageLoaded(el, cb, time)
}, 500);
}
};
var time = 500;
imageLoaded('input[name=product\\[image_location\\]]', function(el) {
//do stuff here
},time);
You can use built-in function open: I use it in all of my programs in which I need to store some history (Including Calculator, etc.) for example:
#gk-test.py or anything else would do
try: # use the try loop only if you haven't created the history file outside program
username = open("history.txt").readline().strip("\n")
user_age = open("history.txt").readlines()[1].strip("\n")
except FileNotFoundError:
username = input("Enter Username: ")
user_age = input("Enter User's Age: ")
open("history.txt", "w").write(f"{username}\n{user_age}")
#Rest of the code is secret! try it your own!
I would thank to all of them who liked my comments! Thank you for reading this!
All of the above might be true, however for me "online-updating" of figures only works with some backends, specifically wx
. You just might try to change to this, e.g. by starting ipython/pylab by ipython --pylab=wx
! Good luck!
I encountered this error message in a situation that is not (clearly) addressed by the help info linked in patrick's answer.
When I used transaction.atomic()
to wrap a call to FooModel.objects.get_or_create()
and called that code simultaneously from two different threads, only one thread would succeed, while the other would get the "database is locked" error. Changing the timeout database option had no effect on the behavior.
I think this is due to the fact that sqlite cannot handle multiple simultaneous writers, so the application must serialize writes on their own.
I solved the problem by using a threading.RLock
object instead of transaction.atomic()
when my Django app is running with a sqlite backend. That's not entirely equivalent, so you may need to do something else in your application.
Here's my code that runs FooModel.objects.get_or_create
simultaneously from two different threads, in case it is helpful:
from concurrent.futures import ThreadPoolExecutor
import configurations
configurations.setup()
from django.db import transaction
from submissions.models import ExerciseCollectionSubmission
def makeSubmission(user_id):
try:
with transaction.atomic():
e, _ = ExerciseCollectionSubmission.objects.get_or_create(
student_id=user_id, exercise_collection_id=172)
except Exception as e:
return f'failed: {e}'
e.delete()
return 'success'
futures = []
with ThreadPoolExecutor(max_workers=2) as executor:
futures.append(executor.submit(makeSubmission, 296))
futures.append(executor.submit(makeSubmission, 297))
for future in futures:
print(future.result())