I had a PFX file and needed to create KEY file for NGINX, so I did this:
openssl pkcs12 -in file.pfx -out file.key -nocerts -nodes
Then I had to edit the KEY file and remove all content up to -----BEGIN PRIVATE KEY-----
. After that NGINX accepted the KEY file.
This is possible with a bit of format conversion.
To extract the private key in a format openssh can use:
openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa
To convert the private key to a public key:
openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8
To extract the public key in a format openssh can use:
openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8
They JKS file is just a container for certificates and key pairs. In a client-side authentication scenario, the various parts of the keys will be located here:
The separation of truststore and keystore is not mandatory but recommended. They can be the same physical file.
To set the filesystem locations of the two stores, use the following system properties:
-Djavax.net.ssl.keyStore=clientsidestore.jks
and on the server:
-Djavax.net.ssl.trustStore=serversidestore.jks
To export the client's certificate (public key) to a file, so you can copy it to the server, use
keytool -export -alias MYKEY -file publicclientkey.cer -store clientsidestore.jks
To import the client's public key into the server's keystore, use (as the the poster mentioned, this has already been done by the server admins)
keytool -import -file publicclientkey.cer -store serversidestore.jks
You can easily switch back to bash by using command "bye"
It's critical to emphasize the comma (,
) in a when
clause. It acts as an ||
of an if
statement, that is, it does an OR comparison and not an AND comparison between the delimited expressions of the when
clause. See the following case statement:
x = 3
case x
when 3, x < 2 then 'apple'
when 3, x > 2 then 'orange'
end
=> "apple"
x
is not less than 2, yet the return value is "apple"
. Why? Because x
was 3 and since ',`` acts as an
||, it did not bother to evaluate the expression
x < 2'.
You might think that to perform an AND, you can do something like this below, but it doesn't work:
case x
when (3 && x < 2) then 'apple'
when (3 && x > 2) then 'orange'
end
=> nil
It doesn't work because (3 && x > 2)
evaluates to true, and Ruby takes the True value and compares it to x
with ===
, which is not true, since x
is 3.
To do an &&
comparison, you will have to treat case
like an if
/else
block:
case
when x == 3 && x < 2 then 'apple'
when x == 3 && x > 2 then 'orange'
end
In the Ruby Programming Language book, Matz says this latter form is the simple (and infrequently used) form, which is nothing more than an alternative syntax for if
/elsif
/else
. However, whether it is infrequently used or not, I do not see any other way to attach multiple &&
expressions for a given when
clause.
If is from a text file and and presuming name file are surrounded by white spaces this is a way:
$a = get-content c:\myfile.txt
$b = $a | select-string -pattern "\s.+\..{3,4}\s" | select -ExpandProperty matches | select -ExpandProperty value
$b | % {"File name:{0} - Extension:{1}" -f $_.substring(0, $_.lastindexof('.')) , $_.substring($_.lastindexof('.'), ($_.length - $_.lastindexof('.'))) }
If is a file you can use something like this based on your needs:
$a = dir .\my.file.xlsx # or $a = get-item c:\my.file.xlsx
$a
Directory: Microsoft.PowerShell.Core\FileSystem::C:\ps
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 25/01/10 11.51 624 my.file.xlsx
$a.BaseName
my.file
$a.Extension
.xlsx
I got so fed up with checking for null and empty strings specifically, that I now usually just write and call a small function to do it for me.
/**
* Test if the given value equals null or the empty string.
*
* @param {string} value
**/
const isEmpty = (value) => value === null || value === '';
// Test:
isEmpty(''); // true
isEmpty(null); // true
isEmpty(1); // false
isEmpty(0); // false
isEmpty(undefined); // false
We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...
Map<String, Person> map =
roster
.stream()
.collect(
Collectors.toMap(p -> p.getLast(),
p -> p,
(person1, person2) -> person1+";"+person2)
);
"SELECT "+_ID+" , "+_DESCRIPTION +","+_CREATED_DATE +","+_DATE_TIME+" FROM "+TBL_NOTIFICATION+" ORDER BY "+"strftime(%s,"+_DATE_TIME+") DESC";
If you really want to do this with jQuery (why?) you should get the DOM window.location object to use its functions:
$(window.location)[0].replace("https://www.google.it");
Note that [0] says to jQuery to use directly the DOM object and not the $(window.location) jQuery object incapsulating the DOM object.
theme(plot.title = element_text(size = 12, face = "bold"),
legend.title=element_text(size=10),
legend.text=element_text(size=9))
I know it's "a bit late" but just in case if anybody needs to do this in LINQ Method syntax (which is why I found this post initially), this would be how to do that:
var results = context.Periods
.GroupJoin(
context.Facts,
period => period.id,
fk => fk.periodid,
(period, fact) => fact.Where(f => f.otherid == 17)
.Select(fact.Value)
.DefaultIfEmpty()
)
.Where(period.companyid==100)
.SelectMany(fact=>fact).ToList();
You can not use DATEDIFF
but you can use this (if columns are not date type):
SELECT
to_date('2008-08-05','YYYY-MM-DD')-to_date('2008-06-05','YYYY-MM-DD')
AS DiffDate from dual
I cannot believe how did I fix the issue! weird solution!
I kept the app running then I removed all template tags and again I returned them back and it worked! but I don't understand what happened.
This issue occurs because of the Gradle version changes, since your application uses old version of gradle, you need to update to new version.
This changes needs to be done in build.gradle file, have look at this link http://www.feelzdroid.com/2015/11/android-plugin-too-old-update-recent-version.html. to know how to update the gradle and detailed steps are provided. there.
Thans
For me it was fixed by downloading the image data set I was using again (in fact I forwarded the copy I had locally using vs-code's SFTP). Here is the jupyter notebook I used (in vscode) with it's output:
from pathlib import Path
import PIL
import PIL.Image as PILI
#from PIL import Image
print(PIL.__version__)
img_path = Path('PATH_UR_DATASET/miniImagenet/train/n03998194/n0399819400000585.jpg')
print(img_path.exists())
img = PILI.open(img_path).convert('RGB')
print(img)
output:
7.0.0
True
<PIL.Image.Image image mode=RGB size=158x160 at 0x7F4AD0A1E050>
note that open
always opens in r
mode and even has a check to throw an error if that mode is changed.
If you click on the title CSS (SCSS)
in CodePen (don't change the pre-processor with the gear) it will switch to the compiled CSS view.
you can get loccalhost page by writing localhost/xampp
or by writing http://127.0.0.1
you will get the local host page. After starting the apache serve that can be from wamp, xamp or lamp.
You're over-complicating it - it just needs to be:
void generateArray(int *a, int si)
{
for (int j = 0; j < si; j++)
a[j] = rand() % 9;
}
int main()
{
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}
When you pass an array as a parameter to a function it decays to a pointer to the first element of the array. So there is normally never a need to pass a pointer to an array.
You do not need to create data frame from vector of strings, if you want to replace some characters in it. Regular expressions is good choice for it as it has been already mentioned by @Andrie and @Dirk Eddelbuettel.
Pay attention, if you want to replace special characters, like dots, you should employ full regular expression syntax, as shown in example below:
ctr_names <- c("Czech.Republic","New.Zealand","Great.Britain")
gsub("[.]", " ", ctr_names)
this will produce
[1] "Czech Republic" "New Zealand" "Great Britain"
This builds on the above answer from Gordon--not all of it is my original work. What I did was add a more generic method to my static utility class.
public static int MatchingRowIndex(DataGridView dgv, string columnName, string searchValue)
{
int rowIndex = -1;
bool tempAllowUserToAddRows = dgv.AllowUserToAddRows;
dgv.AllowUserToAddRows = false; // Turn off or .Value below will throw null exception
if (dgv.Rows.Count > 0 && dgv.Columns.Count > 0 && dgv.Columns[columnName] != null)
{
DataGridViewRow row = dgv.Rows
.Cast<DataGridViewRow>()
.FirstOrDefault(r => r.Cells[columnName].Value.ToString().Equals(searchValue));
rowIndex = row.Index;
}
dgv.AllowUserToAddRows = tempAllowUserToAddRows;
return rowIndex;
}
Then in whatever form I want to use it, I call the method passing the DataGridView, column name and search value. For simplicity I am converting everything to strings for the search, though it would be easy enough to add overloads for specifying the data types.
private void UndeleteSectionInGrid(string sectionLetter)
{
int sectionRowIndex = UtilityMethods.MatchingRowIndex(dgvSections, "SectionLetter", sectionLetter);
dgvSections.Rows[sectionRowIndex].Cells["DeleteSection"].Value = false;
}
PaddingTextField.swift
import UIKit
class PaddingTextField: UITextField {
@IBInspectable var paddingLeft: CGFloat = 0
@IBInspectable var paddingRight: CGFloat = 0
override func textRectForBounds(bounds: CGRect) -> CGRect {
return CGRectMake(bounds.origin.x + paddingLeft, bounds.origin.y,
bounds.size.width - paddingLeft - paddingRight, bounds.size.height);
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
return textRectForBounds(bounds)
}}
Remember Ternary operator and Elvis operator hold separate meanings in Kotlin unlike in many popular languages. Doing expression? value1: value2
would give you bad words by the Kotlin compiler, unlike any other language as there is no ternary operator in Kotlin as mentioned in the official docs. The reason is that the if, when and try-catch statements themselves return values.
So, doing expression? value1: value2
can be replaced by
val max = if (a > b) print("Choose a") else print("Choose b")
The Elvis operator that Kotlin has, works only in the case of nullable variables ex.:
If I do something like
value3 = value1 ?: value2
then if value1 is null then value2 would be returned otherwise value1 would be returned.
A more clear understanding can be achieved from these answers.
Permanent:
UPDATE
MyTable
SET
MyColumn = UPPER(MyColumn)
Temporary:
SELECT
UPPER(MyColumn) AS MyColumn
FROM
MyTable
try using form collection
<input id="responsable" value="True" name="checkResp" type="checkbox" />
[HttpPost]
public ActionResult Index(FormCollection collection)
{
if(!string.IsNullOrEmpty(collection["checkResp"])
{
string checkResp=collection["checkResp"];
bool checkRespB=Convert.ToBoolean(checkResp);
}
}
Just wanted to add a couple of pence to the excellent answers above: If you are working on pre Extjs 4.1, and don't have application wide events but need them, I've been using a very simple technique that might help: Create a simple object extending Observable, and define any app wide events you might need in it. You can then fire those events from anywhere in your app, including actual html dom element and listen to them from any component by relaying the required elements from that component.
Ext.define('Lib.MessageBus', {
extend: 'Ext.util.Observable',
constructor: function() {
this.addEvents(
/*
* describe the event
*/
"eventname"
);
this.callParent(arguments);
}
});
Then you can, from any other component:
this.relayEvents(MesageBus, ['event1', 'event2'])
And fire them from any component or dom element:
MessageBus.fireEvent('event1', somearg);
<input type="button onclick="MessageBus.fireEvent('event2', 'somearg')">
That is exactly what you do with an advanced filter. If it's a one shot, you don't even need a macro, it is available in the Data menu.
Sheets("Sheet1").Range("A1:D17").AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Sheets("Sheet1").Range("G1:G2"), CopyToRange:=Range("A1:D1") _
, Unique:=False
Make sure the header files are publicly available as part of the framework's public headers.
Goto Framework -> Target -> Build Phases and drag to move the relevant header files from Project to Public. Hope that helps!
With dplyr
package, Use
nrow(filter(mydata, sCode == "CA")),
All the solutions provided here gave me same error as multi-sam but that one worked.
The easiest cross browser solution for supporting parameters in setTimeout:
setTimeout(function() {
postinsql(topicId);
}, 4000)
If you don't mind not supporting IE 9 and lower:
setTimeout(postinsql, 4000, topicId);
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
You should generally use urllib2, since this makes things a bit easier at times by accepting Request objects and will also raise a URLException on protocol errors. With Google App Engine though, you can't use either. You have to use the URL Fetch API that Google provides in its sandboxed Python environment.
To get a timestamp
from Date()
, you'll need to divide getTime()
by 1000
, i.e. :
Date currentDate = new Date();
currentDate.getTime() / 1000;
// 1397132691
or simply:
long unixTime = System.currentTimeMillis() / 1000L;
const destroy = container => {
document.getElementById(container).innerHTML = '';
};
Faster previous
const destroyFast = container => {
const el = document.getElementById(container);
while (el.firstChild) el.removeChild(el.firstChild);
};
UPD 2020: "Open Graph Object Debugger" has been discontinued. Use Sharing Debugger to refresh Facebook cache.
There is some confusion about tons of Facebook Tools and Documentation. So many people probably use the Sharing Debugger tool to check their OpenGraph markup: https://developers.facebook.com/tools/debug/sharing/
But it only retrieves the information about your site from the Facebook cache. This means that after you change the ogp-markup on your site, the Sharing Debugger will still be using the old cached data. Moreover, if there is no cached data on the Facebook server then the Sharing Debugger will show you the error: This URL hasn't been shared on Facebook before.
So, the solution is to use another tool – Open Graph Object Debugger: https://developers.facebook.com/tools/debug/og/object/
It allows you to Fetch new scrape information and refresh the Facebook cache:
Honestly, I don't know how to find this tool exploring the Tools & Support section of developers.facebook.com – I cannot find any links and mentions. I only have this tool in my bookmarks. That's Facebook :)
I also noted that some developers use the name
attribute instead of property
. Many parsers probably will process such tags properly, but according to The Open Graph protocol, we should use property
, not name
:
<meta property="og:url" content="http://www.mywebaddress.com"/>
The last recommendation is to specify full URLs. For example, Facebook complains when you use relative URL in og:image
. So use the full one:
<meta property="og:image" content="http://www.mywebaddress.com/myimage.jpg"/>
For those searching for a solution not based on jQuery, this is a plain JavaScript version of the solution provided by Thomas M:
window.addEventListener("storage", message_receive);
function message_broadcast(message) {
localStorage.setItem('message',JSON.stringify(message));
}
function message_receive(ev) {
if (ev.key == 'message') {
var message=JSON.parse(ev.newValue);
}
}
You have to just check whether your WAMP server is online or not.
To put your WAMP server online, follow these steps.
And you are DONE...
I'd try to declare i
outside of the loop!
Good luck on solving 3n+1 :-)
Here's an example:
#include <stdio.h>
int main() {
int i;
/* for loop execution */
for (i = 10; i < 20; i++) {
printf("i: %d\n", i);
}
return 0;
}
Read more on for loops in C here.
I'd recommend to keep your controller free from translation logic and translate your strings directly inside your view like this:
<h1>{{ 'TITLE.HELLO_WORLD' | translate }}</h1>
Angular Translate provides the $translate
service which you can use in your Controllers.
An example usage of the $translate
service can be:
.controller('TranslateMe', ['$scope', '$translate', function ($scope, $translate) {
$translate('PAGE.TITLE')
.then(function (translatedValue) {
$scope.pageTitle = translatedValue;
});
});
The translate service also has a method for directly translating strings without the need to handle a promise, using $translate.instant()
:
.controller('TranslateMe', ['$scope', '$translate', function ($scope, $translate) {
$scope.pageTitle = $translate.instant('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});
The downside with using $translate.instant()
could be that the language file isn't loaded yet if you are loading it async.
This is my preferred way since I don't have to handle promises this way. The output of the filter can be directly set to a scope variable.
.controller('TranslateMe', ['$scope', '$filter', function ($scope, $filter) {
var $translate = $filter('translate');
$scope.pageTitle = $translate('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});
Since @PascalPrecht is the creator of this awesome library, I'd recommend going with his advise (see his answer below) and use the provided directive which seems to handle translations very intelligent.
The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.
I was able to solve the same problem with different solution.
The solution that worked for me was to Right click project "pom.xml" in eclipse and select "Maven Install".
I might be missing something, but afaik, you get undefined
only
Update: Ok, I missed a lot, trying to complete:
You get undefined
...
... when you try to access properties of an object that don't exist:
var a = {}
a.foo // undefined
... when you have declared a variable but not initialized it:
var a;
// a is undefined
... when you access a parameter for which no value was passed:
function foo (a, b) {
// something
}
foo(42); // b inside foo is undefined
... when a function does not return a value:
function foo() {};
var a = foo(); // a is undefined
It might be that some built-in functions return null
on some error, but if so, then it is documented. null
is a concrete value in JavaScript, undefined
is not.
Normally you don't need to distinguish between those. Depending on the possible values of a variable, it is sufficient to use if(variable)
to test whether a value is set or not (both, null
and undefined
evaluate to false
).
Also different browsers seem to be returning these differently.
Please give a concrete example.
select
ROW_NUMBER() Over (Order by CustomerID) As [S.N.],
CustomerID ,
CustomerName,
Address,
City,
State,
ZipCode
from Customers;
Select *
FROM test_table
WHERE user_id = value
AND date_added = (select max(date_added)
from test_table
where user_id = value)
From an int:
YourEnum foo = (YourEnum)yourInt;
From a string:
YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
// The foo.ToString().Contains(",") check is necessary for enumerations marked with an [Flags] attribute
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
throw new InvalidOperationException($"{yourString} is not an underlying value of the YourEnum enumeration.")
}
Update:
From number you can also
YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt);
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
this deletes test.blue
android:spinnerMode="dialog"
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
Update: This will create a second context same as in applicationContext.xml
or you can add this code snippet to your web.xml
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
instead of
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
A full answer: (Tested with r71)
To set a background color use:
renderer.setClearColor( 0xffffff ); // white background - replace ffffff with any hex color
If you want a transparent background you will have to enable alpha in your renderer first:
renderer = new THREE.WebGLRenderer( { alpha: true } ); // init like this
renderer.setClearColor( 0xffffff, 0 ); // second param is opacity, 0 => transparent
View the docs for more info.
Use .prop()
instead and if we go with your code then compare like this:
Look at the example jsbin:
$("#news_list tr").click(function () {
var ele = $(this).find(':checkbox');
if ($(':checked').length) {
ele.prop('checked', false);
$(this).removeClass('admin_checked');
} else {
ele.prop('checked', true);
$(this).addClass('admin_checked');
}
});
Changes:
input
to :checkbox
.the length
of the checked checkboxes
.If you want to find out only whether or not the files are identical, you can use the Windows fc
command in binary mode:
fc.exe /b file1 file2
For details, see the reference for fc
The other answers normalize an image based on the entire image. But if your image has a predominant color (such as black), it will mask out the features that you're trying to enhance since it will not be as pronounced. To get around this limitation, we can normalize the image based on a subsection region of interest (ROI). Essentially we will normalize based on the section of the image that we want to enhance instead of equally treating each pixel with the same weight. Take for instance this earth image:
Input image ->
Normalization based on entire image
If we want to enhance the clouds by normalizing based on the entire image, the result will not be very sharp and will be over saturated due to the black background. The features to enhance are lost. So to obtain a better result we can crop a ROI, normalize based on the ROI, and then apply the normalization back onto the original image. Say we crop the ROI highlighted in green:
This gives us this ROI
The idea is to calculate the mean and standard deviation of the ROI and then clip the frame based on the lower and upper range. In addition, we could use an offset to dynamically adjust the clip intensity. From here we normalize the original image to this new range. Here's the result:
Before ->
After
Code
import cv2
import numpy as np
# Load image as grayscale and crop ROI
image = cv2.imread('1.png', 0)
x, y, w, h = 364, 633, 791, 273
ROI = image[y:y+h, x:x+w]
# Calculate mean and STD
mean, STD = cv2.meanStdDev(ROI)
# Clip frame to lower and upper STD
offset = 0.2
clipped = np.clip(image, mean - offset*STD, mean + offset*STD).astype(np.uint8)
# Normalize to range
result = cv2.normalize(clipped, clipped, 0, 255, norm_type=cv2.NORM_MINMAX)
cv2.imshow('image', image)
cv2.imshow('ROI', ROI)
cv2.imshow('result', result)
cv2.waitKey()
The difference between normalizing based on the entire image vs a specific section of the ROI can be visualized by applying a heatmap to the result. Notice the difference on how the clouds are defined.
Input image ->
heatmap
Normalized on entire image ->
heatmap
Normalized on ROI ->
heatmap
Heatmap code
import matplotlib.pyplot as plt
import numpy as np
import cv2
image = cv2.imread('result.png', 0)
colormap = plt.get_cmap('inferno')
heatmap = (colormap(image) * 2**16).astype(np.uint16)[:,:,:3]
heatmap = cv2.cvtColor(heatmap, cv2.COLOR_RGB2BGR)
cv2.imshow('image', image)
cv2.imshow('heatmap', heatmap)
cv2.waitKey()
Note: The ROI bounding box coordinates were obtained using how to get ROI Bounding Box Coordinates without Guess & Check and heatmap code was from how to convert a grayscale image to heatmap image with Python OpenCV
A cronjob could monitor this log and based on events created by your trigger it could invoke a php script. That is if you absolutely have no control over you insertion.. If you have transaction logs in you MySQL, you can create a trigger for purpose of a log instance creation.
As an additional note, there is no need for the for loop because of R's vectorization.
This:
P <- 243.51
t <- 31 / 365
n <- 365
for (r in seq(0.15, 0.22, by = 0.01))
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P
}
is equivalent to:
P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P
Because r
is a vector, the expression above containing it is performed for all values of the vector.
Use implicitly wait for wait of every element on page till given time.
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
this wait for every element on page for 30 sec.
Another wait is Explicitly wait or conditional wait in this wait until given condition.
WebDriverWait wait = new WebDriverWait(driver, 40);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
In id give static element id which is diffidently display on the page, as soon as page is load.
This library adds a desiredAccuracy and maxWait option to geolocation calls, which means it will keep trying to get a position until the accuracy is within a specified range.
I think use drop duplicate
sometimes will not so useful depending dataframe.
I found this:
[in] df['col_1'].unique()
[out] array(['A', 'B', 'C'], dtype=object)
And work for me!
https://riptutorial.com/pandas/example/26077/select-distinct-rows-across-dataframe
The question may be getting old, but I've struggled with the same issue just now.
After deleting passwords with resetroot.bat
, as instructed by Nedshed, you can choose another password by going to http://localhost/security/index.php
In combination with what Guffa described, you could use the technique described in
Explanation of <script type = "text/template"> ... </script> to store the HTML document in a special script
element (see the link for an explanation on how this works). That's a lot easier than storing the HTML document in a string.
use mysql source
command to avoid redirection failures, especially on windows.
mysql [-u <username>] [-p<password>] <databasename> -e "source /path/to/dump.sql"
where e for "Execute command"
On Windows, please remember to use double quote for sql command.
However, either backslash \ or slash / will work on Windows.
With inspiration from MacFreak, I put together something that works for me.
This js method prevents hover from sticking on an ipad, and prevents the click registering as two clicks in some cases. In CSS, if you have any :hover psudo classes in your css, change them to .hover For example .some-class:hover to .some-class.hover
Test this code on an ipad to see how css and js hover method behave differently (in hover effect only). The CSS button doesn't have a fancy click alert. http://jsfiddle.net/bensontrent/ctgr6stm/
function clicker(id, doStuff) {_x000D_
id.on('touchstart', function(e) {_x000D_
id.addClass('hover');_x000D_
}).on('touchmove', function(e) {_x000D_
id.removeClass('hover');_x000D_
}).mouseenter(function(e) {_x000D_
id.addClass('hover');_x000D_
}).mouseleave(function(e) {_x000D_
id.removeClass('hover');_x000D_
}).click(function(e) {_x000D_
id.removeClass('hover');_x000D_
//It's clicked. Do Something_x000D_
doStuff(id);_x000D_
});_x000D_
}_x000D_
_x000D_
function doStuff(id) {_x000D_
//Do Stuff_x000D_
$('#clicked-alert').fadeIn(function() {_x000D_
$(this).fadeOut();_x000D_
});_x000D_
}_x000D_
clicker($('#unique-id'), doStuff);
_x000D_
button {_x000D_
display: block;_x000D_
margin: 20px;_x000D_
padding: 10px;_x000D_
-webkit-appearance: none;_x000D_
touch-action: manipulation;_x000D_
}_x000D_
.hover {_x000D_
background: yellow;_x000D_
}_x000D_
.btn:active {_x000D_
background: red;_x000D_
}_x000D_
.cssonly:hover {_x000D_
background: yellow;_x000D_
}_x000D_
.cssonly:active {_x000D_
background: red;_x000D_
}_x000D_
#clicked-alert {_x000D_
display: none;_x000D_
}
_x000D_
<button id="unique-id" class="btn">JS Hover for Mobile devices<span id="clicked-alert"> Clicked</span>_x000D_
_x000D_
</button>_x000D_
<button class="cssonly">CSS Only Button</button>_x000D_
<br>This js method prevents hover from sticking on an ipad, and prevents the click registering as two clicks. In CSS, if you have any :hover in your css, change them to .hover For example .some-class:hover to .some-class.hover
_x000D_
These two settings worked for me to upload 1GB mp4 videos.
<system.web>
<httpRuntime maxRequestLength="2097152" requestLengthDiskThreshold="2097152" executionTimeout="240"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
</requestFiltering>
</security>
</system.webServer>
The solution I use is the following:
<input list="answers" id="answer">
<datalist id="answers">
<option data-value="42" value="The answer">
</datalist>
Then access the value to be sent to the server using JavaScript like this:
var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;
Hope it helps.
Simplest way to get everything working in RStudio under Windows 10
:
Open up Internet Explorer, select Internet Options
:
Open editor for Environment variables:
Add a variable HTTP_PROXY in form:
HTTP_PROXY=http://username:password@localhost:port/
Example:
HTTP_PROXY=http://John:JohnPassword@localhost:8080/
RStudio should work:
You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:
solution 1: call alpha's alphaMethod1()
from beta's alphaMethod1()
class Beta extends Alpha
{
public void alphaMethod1()
{
super.alphaMethod1();
}
}
or from any other method of Beta like:
class Beta extends Alpha
{
public void foo()
{
super.alphaMethod1();
}
}
class Test extends Beta
{
public static void main(String[] args)
{
Beta beta = new Beta();
beta.foo();
}
}
solution 2: create alpha's object and call alpha's alphaMethod1()
class Test extends Beta
{
public static void main(String[] args)
{
Alpha alpha = new Alpha();
alpha.alphaMethod1();
}
}
You should autowire interface AbstractManager
instead of class MailManager
. If you have different implemetations of AbstractManager
you can write @Component("mailService")
and then @Autowired @Qualifier("mailService")
combination to autowire specific class.
This is due to the fact that Spring creates and uses proxy objects based on the interfaces.
One issue that you must know is that when you import a namespace via web.config
in Views
folder, that namespace
is imported JUST for views in that folder. Means if you want to import a namespace
in an area views, you must also import that namespace
, in that area's web.config
file, located in area's Views
folder;
The difference is that ActionEvent
is fired when the action is performed on the JCheckBox
that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox
is selected or deselected.
For instance, if JCheckBox c1
(say) is added to a ButtonGroup
. Changing the state of other JCheckBoxes
in the ButtonGroup
will not fire an ActionEvent
on other JCheckBox
, instead an ItemEvent
is fired.
Final words: An ItemEvent
is fired even when the user deselects a check box by selecting another JCheckBox
(when in a ButtonGroup
), however ActionEvent
is not generated like that instead ActionEvent
only listens whether an action is performed on the JCheckBox
(to which the ActionListener
is registered only) or not. It does not know about ButtonGroup
and all other selection/deselection stuff.
Simple Example to understand how to access elements in the dictionary:-
d = {'dog' : 'bark', 'cat' : 'meow' }
print(d.get('cat'))
print(d.get('lion'))
print(d.get('lion', 'Not in the dictionary'))
print(d.get('lion', 'NA'))
print(d.get('dog', 'NA'))
Explore more about Python Dictionaries and learn interactively here...
static int B,H;
static boolean flag = true;
static{
Scanner scan = new Scanner(System.in);
B = scan.nextInt();
scan.nextLine();
H = scan.nextInt();
if(B < 0 || H < 0){
flag = false;
System.out.println("java.lang.Exception: Breadth and height must be positive");
}
}
In the spirit of providing functionality, go to your .profile
or .bashrc
file located at /home/usr/
and at the bottom add the line:
alias enw='emacs -nw'
Now each time you open a terminal session you just type, for example, enw
and you have the Emacs no-window option with three letters :).
Its very simple and single line query.
SELECT * FROM Table_Name ORDER BY RAND() LIMIT 0,10;
Device Explorer path for Emulator in Mac
/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/...
Logs File path for Emulator in Mac
/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/"EmulatorName"/storage/emulated/0/Android/data/com.app.domain/files/LogFiles/
Shared Preferences File path for Emulator in Mac
/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/"EmulatorName"/data/data/com.app.domain/shared_prefs/
It annoys me to no end that none of these answers is fully automatic, despite the fact that it should be automatable (at least mostly). I created a set of aliases to try to remedy this:
# Useful commands
#################
# Undo the last rebase
undo-rebase = "! f() { : git reset ; PREV_COMMIT=`git x-rev-before-rebase` && git reset --merge \"$PREV_COMMIT\" \"$@\";}; f"
# See what changed since the last rebase
rdiff = "!f() { : git diff ; git diff `git x-rev-before-rebase` "$@";}; f"
# Helpers
########
# Get the revision before the last rebase started
x-rev-before-rebase = !git reflog --skip=1 -1 \"`git x-start-of-rebase`\" --format=\"%gD\"
# Get the revision that started the rebase
x-start-of-rebase = reflog --grep-reflog '^rebase (start)' -1 --format="%gD"
You should be able to tweak this to allow going back an arbitrary number of rebases pretty easily (juggling the args is the trickiest part), which can be useful if you do a number of rebases in quick succession and mess something up along the way.
It will get confused if any commit messages begin with "rebase (start)" (please don't do this). You could make the regex more resilient to improve the situation by matching something like this for your regex:
--grep-reflog "^rebase (start): checkout "
WARNING: not tested (regex may need adjustments)
The reason I haven't done this is because I'm not 100% that a rebase always begins with a checkout. Can anyone confirm this?
[If you're curious about the null (:
) commands at the beginning of the function, that's a way of setting up bash completions for the aliases]
There is a better way which don't need you to alter the table:
mysql> DROP INDEX email ON fuinfo;
where email is the name of unique key (index).
You can also bring it back like that:
mysql> CREATE UNIQUE INDEX email ON fuinfo(email);
where email after IDEX is the name of the index and it's not optional. You can use KEY instead of INDEX.
Also it's possible to create (remove) multicolumn unique indecies like that:
mysql> CREATE UNIQUE INDEX email_fid ON fuinfo(email, fid);
mysql> DROP INDEX email_fid ON fuinfo;
If you didn't specify the name of multicolumn index you can remove it like that:
mysql> DROP INDEX email ON fuinfo;
where email is the column name.
#include<stdio.h>
int main()
{
int a,b,i,c,j;
printf("\n Enter the two no. in between you want to check:");
scanf("%d%d",&a,&c);
printf("%d-%d\n",a,c);
for(j=a;j<=c;j++)
{
b=0;
for(i=1;i<=c;i++)
{
if(j%i==0)
{
b++;
}
}
if(b==2)
{
printf("\nPrime number:%d\n",j);
}
else
{
printf("\n\tNot prime:%d\n",j);
}
}
}
https://jsfiddle.net/krf0v6pw/
HTML
<table>
<tr>
<td class="overflow-wrap-hack">
<div class="content">
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
</div>
</td>
</tr>
</table>
CSS
.content{
word-wrap:break-word; /*old browsers*/
overflow-wrap:break-word;
}
table{
width:100%; /*must be set (to any value)*/
}
.overflow-wrap-hack{
max-width:1px;
}
Benefits:
overflow-wrap:break-word
instead of word-break:break-all
. Which is better because it tries to break on spaces first, and cuts the word off only if the word is bigger than it's container.table-layout:fixed
needed. Use your regular auto-sizing.width
or fixed max-width
in pixels. Define %
of the parent if needed.Tested in FF57, Chrome62, IE11, Safari11
Inside Controller Action you can access HttpContext.Response. There you can set the response status as in the following listing.
[HttpPost]
public ActionResult PostViaAjax()
{
var body = Request.BinaryRead(Request.TotalBytes);
var result = Content(JsonError(new Dictionary<string, string>()
{
{"err", "Some error!"}
}), "application/json; charset=utf-8");
HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
return result;
}
In my case, with Windows Server 2008, I had to change the PATH
variable.
The former version of PHP (VC9) was inside it.
I have changed it with the newer version of PHP (VC11).
After a restart of Apache, it was okay.
you need to assign the mysql_query to a variable (eg $result), then display this variable as you would a normal result from the database.
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(5);
var timer = new System.Threading.Timer((e) =>
{
MyMethod();
}, null, startTimeSpan, periodTimeSpan);
The 'is' test will test for identity using the builtin 'id()' function which essentially returns the memory address of the object and therefore isn't overloadable.
However in the case of testing the equality of a class you probably want to be a little bit more strict about your tests and only compare the data attributes in your class:
import types
class ComparesNicely(object):
def __eq__(self, other):
for key, value in self.__dict__.iteritems():
if (isinstance(value, types.FunctionType) or
key.startswith("__")):
continue
if key not in other.__dict__:
return False
if other.__dict__[key] != value:
return False
return True
This code will only compare non function data members of your class as well as skipping anything private which is generally what you want. In the case of Plain Old Python Objects I have a base class which implements __init__, __str__, __repr__ and __eq__ so my POPO objects don't carry the burden of all that extra (and in most cases identical) logic.
You might also consider adding "
.
For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus"
is very good idea.
No, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least. If you wanted to get/store information server-side, though, you can certainly make an Ajax call to a PHP/ASP/Python/etc. script that can then get/store the data in the server. If you meant store data on the client machine, this is impossible with JavaScript alone. I suspect Flash/Java may be able to, but I am not sure.
If you are only trying to store a small amount of information for an unreliable period of time regarding a specific user, I think you want Web Storage API or cookies. I am not sure from your question what you are trying to accomplish, though.
You cannot save anything inside the app's bundle, but you can use +[NSData dataWithContentsOfURL:]
to store the image in your app's documents directory, e.g.:
NSData *imageData = [NSData dataWithContentsOfURL:myImageURL];
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];
[imageData writeToFile:imagePath atomically:YES];
Not exactly permanent, but it stays there at least until the user deletes the app.
You Can use Linq by Name Grouping
var allEntries = from r in dt.AsEnumerable()
select r["Amount"];
using name space using System.Linq;
You can find the sample total,subtotal,grand total in datatable using c# at Myblog
Note: Not in boolean
WebDriver driver=new FirefoxDriver();
driver.get("http://www.gmail.com");
if(driver.getPageSource().contains("Ur message"))
{
System.out.println("Pass");
}
else
{
System.out.println("Fail");
}
I am one of the engineers on the Fresco project. So obviously I'm biased.
But you don't have to take my word for it. We've released a sample app that allows you to compare the performance of five libraries - Fresco, Picasso, UIL, Glide, and Volley Image Loader - side by side. You can get it at our GitHub repo.
I should also point out that Fresco is available on Maven Central, as com.facebook.fresco:fresco
.
Fresco offers features that Picasso, UIL, and Glide do not yet have:
There are many others (see our documentation), but these are the most important.
if you are on linux, edit the /etc/php/php.ini
(or you will have to create a new extension import file at /etc/php5/cli/conf.d) file so that you add the imap shared object file and then, restart the apache server. Uncomment
;extension=imap.so
so that it becomes like this:
extension=imap.so
Then, restart the apache by
# /etc/rc.d/httpd restart
As you say, you don't need to use a regex for this. You can use rstrip
.
my_file_path = my_file_path.rstrip('/')
If there is more than one /
at the end, this will remove all of them, e.g. '/file.jpg//'
-> '/file.jpg'
. From your question, I assume that would be ok.
You can also unpack the axes in the subplots call
And set whether you want to share the x and y axes between the subplots
Like this:
import matplotlib.pyplot as plt
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
ax1.plot(range(10), 'r')
ax2.plot(range(10), 'b')
ax3.plot(range(10), 'g')
ax4.plot(range(10), 'k')
plt.show()
"/" is integer division in python 2 so it is going to round to a whole number. If you would like a decimal returned, just change the type of one of the inputs to float:
float(20)/15 #1.33333333
You can parse the output of ifconfig
The recommended approach is:
window.greeting = "Hello World!"
You can then access it within any function:
function foo() {
alert(greeting); // Hello World!
alert(window["greeting"]); // Hello World!
alert(window.greeting); // Hello World! (recommended)
}
This approach is preferred for two reasons.
The intent is explicit. The use of the var
keyword can easily lead to declaring global vars
that were intended to be local or vice versa. This sort of variable scoping is a point of confusion for a lot of Javascript developers. So as a general rule, I make sure all variable declarations are preceded with the keyword var
or the prefix window
.
You standardize this syntax for reading the variables this way as well which means that a locally scoped var
doesn't clobber the global var
or vice versa. For example what happens here is ambiguous:
greeting = "Aloha";
function foo() {
greeting = "Hello"; // overrides global!
}
function bar(greeting) {
alert(greeting);
}
foo();
bar("Howdy"); // does it alert "Hello" or "Howdy" ?
However, this is much cleaner and less error prone (you don't really need to remember all the variable scoping rules):
function foo() {
window.greeting = "Hello";
}
function bar(greeting) {
alert(greeting);
}
foo();
bar("Howdy"); // alerts "Howdy"
Just want to add one more case when controller can init twice (this is actual for angular.js 1.3.1):
<div ng-if="loading">Loading...</div>
<div ng-if="!loading">
<div ng-view></div>
</div>
In this case $route.current will be already set when ng-view will init. That cause double initialization.
To fix it just change ng-if to ng-show/ng-hide and all will work well.
I wrote extension method
public static string ToMatrixString<T>(this T[,] matrix, string delimiter = "\t")
{
var s = new StringBuilder();
for (var i = 0; i < matrix.GetLength(0); i++)
{
for (var j = 0; j < matrix.GetLength(1); j++)
{
s.Append(matrix[i, j]).Append(delimiter);
}
s.AppendLine();
}
return s.ToString();
}
To use just call the method
results.ToMatrixString();
Note that if the user may be in multiple zones used in the query, you may probably want to add .distinct()
. Otherwise you get one user multiple times:
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3]).distinct()
Using Model:
Model::where('column','value')->get(['column1','column2','column3',...]);
Using Query Builder:
DB::table('table_name')->where('column','value')->get(['column1','column2','column3',...]);
Exceding the maximum value of a long doesnt throw an exception, instead it cicles back. If you do this:
Long.MAX_VALUE + 1
you will notice that the result is the equivalent to Long.MIN_VALUE.
From here: java number exceeds long.max_value - how to detect?
This will capture requests for files like version
,
release
, and README.md
, etc. which should be
treated either as endpoints, if defined (as in the
case of /release), or as "not found."
Use the Count(*) analytic function OVER PARTITION BY NULL This will count the total # of rows
This works:
$("#myselect").find('option').removeAttr("selected");
or
$("#myselect").find('option:selected').removeAttr("selected");
The correct syntax for updating the password using SQL Developer is:
alter user
user_name
identified by
new_password
replace
old_password
;
You can check more options for this command here: ALTER USER-Oracle DOCS
A race condition is an undesirable situation that occurs when two or more process can access and change the shared data at the same time.It occurred because there were conflicting accesses to a resource . Critical section problem may cause race condition. To solve critical condition among the process we have take out only one process at a time which execute the critical section.
If you are using CSS to style (Not recommended.) you can use display:block;
, however, this will only give you line breaks before and after the styled element.
If you already know beforehand how many columns your new DataTable would have, you can do something like this:
DataTable matrix = ... // get matrix values from db
DataTable newDataTable = new DataTable();
newDataTable.Columns.Add("c_to", typeof(string));
newDataTable.Columns.Add("p_to", typeof(string));
var query = from r in matrix.AsEnumerable()
where r.Field<string>("c_to") == "foo" &&
r.Field<string>("p_to") == "bar"
let objectArray = new object[]
{
r.Field<string>("c_to"), r.Field<string>("p_to")
}
select objectArray;
foreach (var array in query)
{
newDataTable.Rows.Add(array);
}
Most of the solutions given here to create the prepared query are more complex that they need to be. Using PHP's built in functions you can easily creare the SQL statement without significant overhead.
Given $records
, an array of records where each record is itself an indexed array (in the form of field => value
), the following function will insert the records into the given table $table
, on a PDO connection $connection
, using only a single prepared statement. Note that this is a PHP 5.6+ solution because of the use of argument unpacking in the call to array_push
:
private function import(PDO $connection, $table, array $records)
{
$fields = array_keys($records[0]);
$placeHolders = substr(str_repeat(',?', count($fields)), 1);
$values = [];
foreach ($records as $record) {
array_push($values, ...array_values($record));
}
$query = 'INSERT INTO ' . $table . ' (';
$query .= implode(',', $fields);
$query .= ') VALUES (';
$query .= implode('),(', array_fill(0, count($records), $placeHolders));
$query .= ')';
$statement = $connection->prepare($query);
$statement->execute($values);
}
To delete all the files inside the directory as well as its sub-directories, without removing the folders themselves, simply do this:
import os
mypath = "my_folder" #Enter your path here
for root, dirs, files in os.walk(mypath):
for file in files:
os.remove(os.path.join(root, file))
You should be able to access the document in the IFRAME using the following code:
document.getElementById('myframe').contentWindow.document
However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). THis is because of the browser's Same Origin Policy.
If you care about performance and micro-optimizations check this one-liner:
function no_dupes(array $input_array) {
return count($input_array) === count(array_flip($input_array));
}
Description:
Function compares number of array elements in $input_array
with array_flip'ed elements. Values become keys and guess what - keys must be unique in associative arrays so not unique values are lost and final number of elements is lower than original.
As said in manual array keys can be only type of int
or string
so this is what you can have in original array values to compare, otherwise PHP will start casting with unexpected results.
Test case:
<?php
$elements = array_merge(range(1,10000000),[1]);
$time = microtime(true);
accepted_solution($elements);
echo 'Accepted solution: ', (microtime(true) - $time), 's', PHP_EOL;
$time = microtime(true);
most_voted_solution($elements);
echo 'Most voted solution: ', (microtime(true) - $time), 's', PHP_EOL;
$time = microtime(true);
this_answer_solution($elements);
echo 'This answer solution: ', (microtime(true) - $time), 's', PHP_EOL;
function accepted_solution($array){
$dupe_array = array();
foreach($array as $val){
// sorry, but I had to add below line to remove millions of notices
if(!isset($dupe_array[$val])){$dupe_array[$val]=0;}
if(++$dupe_array[$val] > 1){
return true;
}
}
return false;
}
function most_voted_solution($array) {
return count($array) !== count(array_unique($array));
}
function this_answer_solution(array $input_array) {
return count($input_array) === count(array_flip($input_array));
}
Notice that accepted solution might be faster in certain condition when not unique values are near the beginning of huge array.
This doesn't seem to have <a> </a>
tags so selenium might not be able to detect it as a link.
You may try and use
driver.findElement(By.xpath("//*[@class='ng-binding']")).click();
if this is the only element in that page with this class .
@echo OFF
[your command] >> [Your log file name].txt
I used the command above in my batch file and it works. In the log file, it shows the results of my command.
It is Nanny. I feel .Net got this one right - it raises a warning for unreachable code, but not an error. It is good to be warned about it, but I see no reason to prevent compilation (especially during debugging sessions where it is nice to throw a return in to bypass some code).
You can use glut libraries like this:
for a sphere:
glutWireSphere(radius,20,20);
for a Cylinder:
GLUquadric *quadratic = gluNewQuadric();
gluQuadricDrawStyle(quadratic,GLU_LINE);
gluCylinder(quadratic,1,1,1,12,1);
for a Cube:
glutWireCube(1.5);
The distinction between reference types and value types are basically a performance tradeoff in the design of the language. Reference types have some overhead on construction and destruction and garbage collection, because they are created on the heap. Value types on the other hand have overhead on method calls (if the data size is larger than a pointer), because the whole object is copied rather than just a pointer. Because strings can be (and typically are) much larger than the size of a pointer, they are designed as reference types. Also, as Servy pointed out, the size of a value type must be known at compile time, which is not always the case for strings.
The question of mutability is a separate issue. Both reference types and value types can be either mutable or immutable. Value types are typically immutable though, since the semantics for mutable value types can be confusing.
Reference types are generally mutable, but can be designed as immutable if it makes sense. Strings are defined as immutable because it makes certain optimizations possible. For example, if the same string literal occurs multiple times in the same program (which is quite common), the compiler can reuse the same object.
So why is "==" overloaded to compare strings by text? Because it is the most useful semantics. If two strings are equal by text, they may or may not be the same object reference due to the optimizations. So comparing references are pretty useless, while comparing text are almost always what you want.
Speaking more generally, Strings has what is termed value semantics. This is a more general concept than value types, which is a C# specific implementation detail. Value types have value semantics, but reference types may also have value semantics. When a type have value semantics, you can't really tell if the underlying implementation is a reference type or value type, so you can consider that an implementation detail.
Since g++ 4.7 it does understand the new C++11 override
keyword:
class child : public parent {
public:
// force handle_event to override a existing function in parent
// error out if the function with the correct signature does not exist
void handle_event(int something) override;
};
Using contains didn't work well for my string with special characters. Find worked though.
df[df['A'].str.find("hello") != -1]
As you noted yourself, fmin
and fmax
were introduced in C99. Standard C++ library doesn't have fmin
and fmax
functions. Until C99 standard library gets incorporated into C++ (if ever), the application areas of these functions are cleanly separated. There's no situation where you might have to "prefer" one over the other.
You just use templated std::min
/std::max
in C++, and use whatever is available in C.
As of October 2020:
Tensorflow only supports the 64-bit version of Python
Tensorflow only supports Python 3.5 to 3.8
So, if you're using an out-of-range version of Python (older or newer) or a 32-bit version, then you'll need to use a different version.
In @Patrick McMahon's response, the second comment here ( $first_condition is false and $second_condition is true ) is not entirely accurate:
<?php if($first_condition): ?>
/*$first_condition is true*/
<div class="first-condition-true">First Condition is true</div>
<?php elseif($second_condition): ?>
/*$first_condition is false and $second_condition is true*/
<div class="second-condition-true">Second Condition is true</div>
<?php else: ?>
/*$first_condition and $second_condition are false*/
<div class="first-and-second-condition-false">Conditions are false</div>
<?php endif; ?>
Elseif fires whether $first_condition is true or false, as do additional elseif statements, if there are multiple.
I am no PHP expert, so I don't know whether that's the correct way to say IF this OR that ELSE that or if there is another/better way to code it in PHP, but this would be an important distinction to those looking for OR conditions versus ELSE conditions.
Source is w3schools.com and my own experience.
Let's say your variable is always integer. In that case this is easier:
<?PHP
$number = 4;
echo '<script>';
echo 'var number = ' . $number . ';';
echo 'alert(number);';
echo '</script>';
?>
Output:
<script>var number = 4;alert(number);</script>
Let's say your variable is not an integer, but if you try above method you will get something like this:
<script>var number = abcd;alert(number);</script>
But in JavaScript this is a syntax error.
So in PHP we have a function call json_encode
that encode string to a JSON object.
<?PHP
$number = 'abcd';
echo '<script>';
echo 'var number = ' . json_encode($number) . ';';
echo 'alert(number);';
echo '</script>';
?>
Since abcd
in JSON is "abcd"
, it looks like this:
<script>var number = "abcd";alert(number);</script>
You can use same method for arrays:
<?PHP
$details = [
'name' => 'supun',
'age' => 456,
'weight' => '55'
];
echo '<script>';
echo 'var details = ' . json_encode($details) . ';';
echo 'alert(details);';
echo 'console.log(details);';
echo '</script>';
?>
And your JavaScript code looks like this:
<script>var details = {"name":"supun","age":456,"weight":"55"};alert(details);console.log(details);</script>
Console output
I commonly like to use a slight variant on the standard for loop. I often use this to run a command on a series of remote hosts. I take advantage of bash's brace expansion to create for loops that allow me to create non-numerical for-loops.
Example:
I want to run the uptime command on frontend hosts 1-5 and backend hosts 1-3:
% for host in {frontend{1..5},backend{1..3}}.mycompany.com
do ssh $host "echo -n $host; uptime"
done
I typically run this as a single-line command with semicolons on the ends of the lines instead of the more readable version above. The key usage consideration are that braces allow you to specify multiple values to be inserted into a string (e.g. pre{foo,bar}post results in prefoopost, prebarpost) and allow counting/sequences by using the double periods (you can use a..z etc.). However, the double period syntax is a new feature of bash 3.0; earlier versions will not support this.
Its more than just setting the connection to null. That may be what the documentation says, but that is not the truth for mysql. The connection will stay around for a bit longer (Ive heard 60s, but never tested it)
If you want to here the full explanation see this comment on the connections https://www.php.net/manual/en/pdo.connections.php#114822
To force the close the connection you have to do something like
$this->connection = new PDO();
$this->connection->query('KILL CONNECTION_ID()');
$this->connection = null;
alert("some text\nmore text in a new line");
_x000D_
Output:
some text
more text in a new line
There is a finishAffinity()
method in Activity
that will finish the current activity and all parent activities, but it works only in Android 4.1 or higher.
For API 16+, use
finishAffinity();
For lower (Android 4.1 lower), use
ActivityCompat.finishAffinity(YourActivity.this);
This code will help you, and it's fairly self-explanatory:
#include <stdio.h> /* Standard Library of Input and Output */
#include <complex.h> /* Standard Library of Complex Numbers */
int main() {
double complex z1 = 1.0 + 3.0 * I;
double complex z2 = 1.0 - 4.0 * I;
printf("Working with complex numbers:\n\v");
printf("Starting values: Z1 = %.2f + %.2fi\tZ2 = %.2f %+.2fi\n", creal(z1), cimag(z1), creal(z2), cimag(z2));
double complex sum = z1 + z2;
printf("The sum: Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum));
double complex difference = z1 - z2;
printf("The difference: Z1 - Z2 = %.2f %+.2fi\n", creal(difference), cimag(difference));
double complex product = z1 * z2;
printf("The product: Z1 x Z2 = %.2f %+.2fi\n", creal(product), cimag(product));
double complex quotient = z1 / z2;
printf("The quotient: Z1 / Z2 = %.2f %+.2fi\n", creal(quotient), cimag(quotient));
double complex conjugate = conj(z1);
printf("The conjugate of Z1 = %.2f %+.2fi\n", creal(conjugate), cimag(conjugate));
return 0;
}
with:
creal(z1)
: get the real part (for float crealf(z1)
, for long double creall(z1)
)
cimag(z1)
: get the imaginary part (for float cimagf(z1)
, for long double cimagl(z1)
)
Another important point to remember when working with complex numbers is that functions like cos()
, exp()
and sqrt()
must be replaced with their complex forms, e.g. ccos()
, cexp()
, csqrt()
.
In Windows it worked for me only after trying the following: 1. Open cmd inside the folder where "requests" is unpacked. (CTRL+SHIFT+right mouse click, choose the appropriate popup menu item) 2. (Here is the path to your pip3.exe)\pip3.exe install requests Done
Two alternatives
1) Ordering the original array with sortInPlace
self.assignments.sortInPlace({ $0.order < $1.order })
self.printAssignments(assignments)
2) Using an alternative array to store the ordered array
var assignmentsO = [Assignment] ()
assignmentsO = self.assignments.sort({ $0.order < $1.order })
self.printAssignments(assignmentsO)
There are multiple function to do this work that wrote in bottom based on priority.
Set one or more CSS properties for the set of matched elements.
$("div").css("display", "block")
// Or add multiple CSS properties
$("div").css({
display: "block",
color: "red",
...
})
Display the matched elements and is roughly equivalent to calling .css("display", "block")
You can display element using .show()
instead
$("div").show()
Set one or more attributes for the set of matched elements.
If target element hasn't style
attribute, you can use this method to add inline style to element.
$("div").attr("style", "display:block")
// Or add multiple CSS properties
$("div").attr("style", "display:block; color:red")
You can add specific CSS property to element using pure javascript, if you don't want to use jQuery.
var div = document.querySelector("div");
// One property
div.style.display = "block";
// Multiple properties
div.style.cssText = "display:block; color:red";
// Multiple properties
div.setAttribute("style", "display:block; color:red");
Depending on devices you might not find sqlite3 command in adb shell. In that case you might want to follow this :
adb shell
$ run-as package.name
$ cd ./databases/
$ ls -l #Find the current permissions - r=4, w=2, x=1
$ chmod 666 ./dbname.db
$ exit
$ exit
adb pull /data/data/package.name/databases/dbname.db ~/Desktop/
adb push ~/Desktop/dbname.db /data/data/package.name/databases/dbname.db
adb shell
$ run-as package.name
$ chmod 660 ./databases/dbname.db #Restore original permissions
$ exit
$ exit
for reference go to https://stackoverflow.com/a/17177091/3758972.
There might be cases when you get "remote object not found" after following above procedure. Then change permission of your database folder to 755 in adb shell.
$ chmod 755 databases/
But please mind that it'll work only on android version < 21.
You have to append the module’s path to PYTHONPATH
:
export PYTHONPATH="${PYTHONPATH}:/path/to/your/module/"
As I was recently in need of this, I will share a solution that uses 3 tables, but does not require JavaScript.
Table 1 (parent) contains two rows. The first row contains table 2 (child 1) for the column headers. The second row contains table 3 (child 2) for the scrolling content.
It must be noted the childTbl
must be 25px
shorter than the parentTbl
for the scroller to appear properly.
This is the source, where I got the idea from. I made it HTML5-friendly without the deprecated tags and the inline CSS.
.parentTbl table {_x000D_
border-spacing: 0;_x000D_
border-collapse: collapse;_x000D_
border: 0;_x000D_
width: 690px;_x000D_
}_x000D_
.childTbl table {_x000D_
border-spacing: 0;_x000D_
border-collapse: collapse;_x000D_
border: 1px solid #d7d7d7;_x000D_
width: 665px;_x000D_
}_x000D_
.childTbl th,_x000D_
.childTbl td {_x000D_
border: 1px solid #d7d7d7;_x000D_
}_x000D_
.scrollData {_x000D_
width: 690;_x000D_
height: 150px;_x000D_
overflow-x: hidden;_x000D_
}
_x000D_
<div class="parentTbl">_x000D_
<table>_x000D_
<tr>_x000D_
<td>_x000D_
<div class="childTbl">_x000D_
<table class="childTbl">_x000D_
<tr>_x000D_
<th>Header 1</th>_x000D_
<th>Header 2</th>_x000D_
<th>Header 3</th>_x000D_
<th>Header 4</th>_x000D_
<th>Header 5</th>_x000D_
<th>Header 6</th>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class="scrollData childTbl">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>
_x000D_
This is reliable on different browsers, the downside would be having to hard code the table widths.
I found an extra
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.28.0" newVersion="2.2.28.0" />
</dependentAssembly>
in my web.config. removed that to get it to work. some other package I installed, and then removed caused the issue.
In command mode, use the U key to undo and Ctrl + r to redo. Have a look at http://www.vim.org/htmldoc/undo.html.
The solutions here didn't work for me as I'm styling react components.
What worked though for the sidebar was
.sidebar{
position: sticky;
top: 0;
}
Hope this helps someone.
Sample DF:
In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))
In [80]: df
Out[80]:
a b c
0 6 11 11
1 14 7 8
2 13 5 11
3 13 7 11
4 13 5 9
5 5 11 9
6 9 8 6
7 5 11 10
8 8 10 14
9 7 14 13
present only those rows where b > 10
In [81]: df[df.b > 10]
Out[81]:
a b c
0 6 11 11
5 5 11 9
7 5 11 10
9 7 14 13
Minimums (for all columns) for the rows satisfying b > 10
condition
In [82]: df[df.b > 10].min()
Out[82]:
a 5
b 11
c 9
dtype: int32
Minimum (for the b
column) for the rows satisfying b > 10
condition
In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11
UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.
Please note that this fix may only apply to IntelliJ users!! (More information at the bottom of this post that should apply to everyone.)
Fixed this problem! I use IntelliJ and it turns out I just had misconfigured the way I was including the google-play-services_lib
module as a dependency.
As I fixed this entirely through GUI and not at all by editing any files, here's a couple of screenshots:
So my Project Structure started off looking like this...
Then I removed the google-play-services
library from my dependencies list by selecting it and then clicking the minus button at the bottom. Notice the error at the bottom of the dialog, as my project absolutely does require this library. But don't worry, we'll re-add it soon!
Next I added google-play-services_lib
as a module dependency instead of a library dependency. Then I hit the up arrow button at the bottom a couple times to move this dependency to the top of the list. But notice the error at the bottom (we're still not done yet!)
I then clicked the lightbulb at the bottom of the dialog in the error message area to bring up this little small popup that gives two choices (Add to dependencies... or Remove Library). Click the Add to dependencies... option!
A new small dialog window should have popped up. It gave me two choices, one for my main project (it's name is blurred out), and then another for the google-play-services_lib
project. Yours may have a bunch more depending on your project (like you may see actionbarsherlock
, stuff like that). Select google-play-services_lib
and click okay!
And finally, you're done! I hope this helps someone else out there!
I believe the reason that this issue was happening to begin with is because I thought that I had properly included the entire google-play-services_lib
project into my overall project... but I actually had not, and had instead only properly included its jar file (google-play-services_lib/libs/google-play-services.jar
). That jar file only includes code, not Android resources values, and so as such the @integer/google_play_services_version
value was never really in my project. But the code was able to be used in my project, and so that made it seem like everything was fine.
And as a side note, fixing this issue also seems to have fixed the GooglePlayServicesUtil.getErrorDialog(...).show()
crash that I used to have. But that could also have been fixed by the update, not really 100% sure there.
You can use this:
yylval.sval=strdup("VHDL + Volcal trance...");
Where yylval is char*. strdup from does the job.
it may be that the application/x-www-form-urlencoded midia type convert space to +, and the reciever will decode the data by converting the + to space.check the url for more info.http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
If you go to C:\Windows\system32\Windowspowershell\v1.0
(and C:\Windows\syswow64\Windowspowershell\v1.0
on x64 machines) in Windows Explorer and double-click powershell.exe
you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe
can be set independently from the default properties.
To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.
Running start powershell
from cmd.exe should start a new console with your default settings.
On windows, you can print with this command in your CLI
C:\Users\dir\env | more
You can view all environment variables set on your system with the env command. The list is long, so pipe the output through more to make it easier to read.
Worked on the same issue , finally done this is top for the question so just putting what i did.
Observation - 1 -The file was not actually XLS i renamed to txt and noticed HTML text in file.
2 - Renamed the file to html and tried reading pd.read_html, Failed.
3- Added as it was not there in txt file, removed style to ensure that table is displaying in browser from local, and WORKED.
Below is the code may help someone..
import pandas as pd
import os
import shutil
import html5lib
import requests
from bs4 import BeautifulSoup
import re
import time
shutil.copy('your.xls','file.html')
shutil.copy('file.html','file.txt')
time.sleep(2)
txt = open('file.txt','r').read()
# Modify the text to ensure the data display in html page, delete style
txt = str(txt).replace('<style> .text { mso-number-format:\@; } </script>','')
# Add head and body if it is not there in HTML text
txt_with_head = '<html><head></head><body>'+txt+'</body></html>'
# Save the file as HTML
html_file = open('output.html','w')
html_file.write(txt_with_head)
# Use beautiful soup to read
url = r"C:\Users\hitesh kumar\PycharmProjects\OEM ML\output.html"
page = open(url)
soup = BeautifulSoup(page.read(), features="lxml")
my_table = soup.find("table",attrs={'border': '1'})
frame = pd.read_html(str(my_table))[0]
print(frame.head())
frame.to_excel('testoutput.xlsx',sheet_name='sheet1', index=False)
You can't target each word in CSS. However, with a bit of jQuery you probably could.
With jQuery you can wrap each word in a <span>
and then CSS set span to display:block
which would put it on its own line.
In theory of course :P
<sup>
and <sub>
tags work and are your only good solution for arbitrary text. Other solutions include:
Unicode
If the superscript (or subscript) you need is of a mathematical nature, Unicode may well have you covered.
I've compiled a list of all the Unicode super and subscript characters I could identify in this gist. Some of the more common/useful ones are:
°
SUPERSCRIPT ZERO (U+2070)¹
SUPERSCRIPT ONE (U+00B9)²
SUPERSCRIPT TWO (U+00B2)³
SUPERSCRIPT THREE (U+00B3)n
SUPERSCRIPT LATIN SMALL LETTER N (U+207F)People also often reach for <sup>
and <sub>
tags in an attempt to render specific symbols like these:
™
TRADE MARK SIGN (U+2122)®
REGISTERED SIGN (U+00AE)?
SERVICE MARK (U+2120)Assuming your editor supports Unicode, you can copy and paste the characters above directly into your document.
Alternatively, you could use the hex values above in an HTML character escape. Eg, ²
instead of ²
. This works with GitHub (and should work anywhere else your Markdown is rendered to HTML) but is less readable when presented as raw text/Markdown.
Images
If your requirements are especially unusual, you can always just inline an image. The GitHub supported syntax is:
![Alt text goes here, if you'd like](path/to/image.png)
You can use a full path (eg. starting with https://
or http://
) but it's often easier to use a relative path, which will load the image from the repo, relative to the Markdown document.
If you happen to know LaTeX (or want to learn it) you could do just about any text manipulation imaginable and render it to an image. Sites like Quicklatex make this quite easy.
Here's a cross-browser less mixin for using CSS's calc
with any property:
.calc(@prop; @val) {
@{prop}: calc(~'@{val}');
@{prop}: -moz-calc(~'@{val}');
@{prop}: -webkit-calc(~'@{val}');
@{prop}: -o-calc(~'@{val}');
}
Example usage:
.calc(width; "100% - 200px");
And the CSS that's output:
width: calc(100% - 200px);
width: -moz-calc(100% - 200px);
width: -webkit-calc(100% - 200px);
width: -o-calc(100% - 200px);
A codepen of this example: http://codepen.io/patrickberkeley/pen/zobdp
Microsoft guidelines as checked by FxCop discourage use of List<T> in public APIs - prefer IList<T>.
Incidentally, I now almost always declare one-dimensional arrays as IList<T>, which means I can consistently use the IList<T>.Count property rather than Array.Length. For example:
public interface IMyApi
{
IList<int> GetReadOnlyValues();
}
public class MyApiImplementation : IMyApi
{
public IList<int> GetReadOnlyValues()
{
List<int> myList = new List<int>();
... populate list
return myList.AsReadOnly();
}
}
public class MyMockApiImplementationForUnitTests : IMyApi
{
public IList<int> GetReadOnlyValues()
{
IList<int> testValues = new int[] { 1, 2, 3 };
return testValues;
}
}
If, like me, you had dynamically created buttons on your page, the
$("#your-bs-button's-id").on("click", function(event) {
or
$(".your-bs-button's-class").on("click", function(event) {
methods won't work because they only work on current elements (not future elements). Instead you need to reference a parent item that existed at the initial loading of the web page.
$(document).on("click", "#your-bs-button's-id", function(event) {
or more generally
$("#pre-existing-element-id").on("click", ".your-bs-button's-class", function(event) {
There are many other references to this issue on stack overflow here and here.
using include 'page1.php'
in second page is one option but it can generate warnings and errors of undefined variables.
Three methods by which you can use variables of one php file in another php file:
use session to pass variable from one page to another
method:
first you have to start the session in both the files using php command
sesssion_start();
then in first file consider you have one variable
$x='var1';now assign value of $x to a session variable using this:
$_SESSION['var']=$x;
now getting value in any another php file:
$y=$_SESSION['var'];//$y is any declared variable
using get method and getting variables on clicking a link
method
<a href="page2.php?variable1=value1&variable2=value2">clickme</a>
getting values in page2.php file by $_GET function:$x=$_GET['variable1'];//value1 be stored in $x
$y=$_GET['variable2'];//vale2 be stored in $y
if you want to pass variable value using button then u can use it by following method:
$x='value1'
<input type="submit" name='btn1' value='.$x.'/>
in second php$var=$_POST['btn1'];
Use git stash push
, like this:
git stash push [--] [<pathspec>...]
For example:
git stash push -- my/file.sh
This is available since Git 2.13, released in spring 2017.
Grab the params from location.search with one line:
const params = new Map(this.props.location.search.slice(1).split('&').map(param => param.split('=')))
Then, simply:
if(params.get("year")){
//year exists. do something...
} else {
//year doesn't exist. do something else...
}
When indicating HTTP Basic Authentication we return something like:
WWW-Authenticate: Basic realm="myRealm"
Whereas Basic
is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.
You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.
From recollection, Windows Challenge Response uses a different scheme and different arguments.
The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.
My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.
For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.
Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.
The other alternative is burn the AJAX request but that's a poor user experience.
You can use menu left sidebar collapse accordion, animated with right arrow
I wanted to share with you my solution to export a database with Microsoft SQL Server Management Studio.
To Export your database
DECLARE @BackupFile NVARCHAR(255);
SET @BackupFile = 'c:\database-backup_2020.07.22.bak';
PRINT @BackupFile;
BACKUP DATABASE [%databaseName%] TO DISK = @BackupFile;
Don't forget to replace %databaseName%
with the name of the database you want to export.
Note that this method gives a lighter file than from the menu.
To import this file from SQL Server Management Studio. Don't forget to delete your database beforehand.
Enjoy! :) :)
On IE7, IE8, and IE9 just go to Settings->Internet Options->Security->Custom Level and change security settings under "Miscellaneous" set "Access data sources across domains" to Enable.
Another easy way:
//In your ListViewActivity:
public void refreshListView() {
listAdapter = new ListAdapter(this);
setListAdapter(listAdapter);
}
in my case i always put these stuffs in a p tag like
<p>
name : < input type=text />
</p>
and so on and then applying the css like
p {
text-align:left;
}
p input {
float:right;
}
You need to specify the width of the p tag.because the input tags will float all the way right.
This css will also affect the submit button. You need to override the rule for this tag.
Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:
- Install Visual Studio 2008
- Install the service Package 1 (SP1)
- Install SQL Server 2008 r2
I'm quite sure this can be very simple
2.0.0p247 :032 > list = Array.new(5)
=> [nil, nil, nil, nil, nil]
2.0.0p247 :033 > list.map!{ |x| x = [0] }
=> [[0], [0], [0], [0], [0]]
2.0.0p247 :034 > list[0][0]
=> 0
Encapsulation: binding data and the methods that act on it. this allows the hiding of data from all other methods in other classes.
example: MyList
class that can add an item, remove an item, and remove all items
the methods add
, remove
, and removeAll
act on the list(a private array) that can not be accessed directly from the outside.
Abstraction: is hiding the non relevant behavior and data. How the items are actually stored, added, or deleted is hidden (abstracted). My data may be held in simple array, ArrayList, LinkedList, and so on. Also, how the methods are implemented is hidden from the outside.
Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
Predicate is a special kind of Func often used for comparisons.
Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.
Here is a small example for Action and Func without using Linq:
class Program
{
static void Main(string[] args)
{
Action<int> myAction = new Action<int>(DoSomething);
myAction(123); // Prints out "123"
// can be also called as myAction.Invoke(123);
Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
Console.WriteLine(myFunc(5)); // Prints out "2.5"
}
static void DoSomething(int i)
{
Console.WriteLine(i);
}
static double CalculateSomething(int i)
{
return (double)i/2;
}
}
I have found a difference between literal newlines in <xsl:text>
and literal newlines using 

.
While literal newlines worked fine in my environment (using both Saxon and the default Java XSLT processor) my code failed when it was executed by another group running in a .NET environment.
Changing to entities (

) got my file generation code running consistently on both Java and .NET.
Also, literal newlines are vulnerable to being reformatted by IDEs and can inadvertently get lost when the file is maintained by someone 'not in the know'.
Here is a cleaner way to do it if you are using Bootstrap 3.2.0.
Link HTML
<a href="#my_modal" data-toggle="modal" data-book-id="my_id_value">Open Modal</a>
Modal JavaScript
//triggered when modal is about to be shown
$('#my_modal').on('show.bs.modal', function(e) {
//get data-id attribute of the clicked element
var bookId = $(e.relatedTarget).data('book-id');
//populate the textbox
$(e.currentTarget).find('input[name="bookId"]').val(bookId);
});
The below code will return username group membership using the samaccountname. You can modify it to get input from a file or change the query to get accounts with non expiring passwords etc
$location = "c:\temp\Peace2.txt"
$users = (get-aduser -filter *).samaccountname
$le = $users.length
for($i = 0; $i -lt $le; $i++){
$output = (get-aduser $users[$i] | Get-ADPrincipalGroupMembership).name
$users[$i] + " " + $output
$z = $users[$i] + " " + $output
add-content $location $z
}
Sample Output:
Administrator Domain Users Administrators Schema Admins Enterprise Admins Domain Admins Group Policy Creator Owners Guest Domain Guests Guests krbtgt Domain Users Denied RODC Password Replication Group Redacted Domain Users CompanyUsers Production Redacted Domain Users CompanyUsers Production Redacted Domain Users CompanyUsers Production
//Sets the row color depending on the value in the "Status" column.
function setRowColors() {
var range = SpreadsheetApp.getActiveSheet().getDataRange();
var statusColumnOffset = getStatusColumnOffset();
for (var i = range.getRow(); i < range.getLastRow(); i++) {
rowRange = range.offset(i, 0, 1);
status = rowRange.offset(0, statusColumnOffset).getValue();
if (status == 'Completed') {
rowRange.setBackgroundColor("#99CC99");
} else if (status == 'In Progress') {
rowRange.setBackgroundColor("#FFDD88");
} else if (status == 'Not Started') {
rowRange.setBackgroundColor("#CC6666");
}
}
}
//Returns the offset value of the column titled "Status"
//(eg, if the 7th column is labeled "Status", this function returns 6)
function getStatusColumnOffset() {
lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn();
var range = SpreadsheetApp.getActiveSheet().getRange(1,1,1,lastColumn);
for (var i = 0; i < range.getLastColumn(); i++) {
if (range.offset(0, i, 1, 1).getValue() == "Status") {
return i;
}
}
}
After finding answers around, I think this page might be helpful. https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation Not sure about the history of declaration merging, but it explains why the following could work.
declare global {
interface Window { MyNamespace: any; }
}
window.MyNamespace = window.MyNamespace || {};
Most of the time you would create a list in groovy rather than an array. You could do it like this:
names = ["lucas", "Fred", "Mary"]
Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:
names = "lucas Fred Mary".split()
Try this function ...
public static string GetTempFilePathWithExtension(string extension) {
var path = Path.GetTempPath();
var fileName = Guid.NewGuid().ToString() + extension;
return Path.Combine(path, fileName);
}
It will return a full path with the extension of your choice.
Note, it's not guaranteed to produce a unique file name since someone else could have technically already created that file. However the chances of someone guessing the next guid produced by your app and creating it is very very low. It's pretty safe to assume this will be unique.
To disable resize for all textarea
s:
textarea {
resize: none;
}
To disable resize for a specific textarea
, add an attribute, name
, or an id
and set it to something. In this case, it is named noresize
<textarea name='noresize' id='noresize'> </textarea>
/* Using the attribute name */
textarea[name=noresize] {
resize: none;
}
/* Or using the id */
#noresize {
resize: none;
}
It is mostly syntactic sugar, but a couple differences are noteworthy:
ON is the more general of the two. One can join tables ON a column, a set of columns and even a condition. For example:
SELECT * FROM world.City JOIN world.Country ON (City.CountryCode = Country.Code) WHERE ...
USING is useful when both tables share a column of the exact same name on which they join. In this case, one may say:
SELECT ... FROM film JOIN film_actor USING (film_id) WHERE ...
An additional nice treat is that one does not need to fully qualify the joining columns:
SELECT film.title, film_id -- film_id is not prefixed
FROM film
JOIN film_actor USING (film_id)
WHERE ...
To illustrate, to do the above with ON, we would have to write:
SELECT film.title, film.film_id -- film.film_id is required here
FROM film
JOIN film_actor ON (film.film_id = film_actor.film_id)
WHERE ...
Notice the film.film_id
qualification in the SELECT
clause. It would be invalid to just say film_id
since that would make for an ambiguity:
ERROR 1052 (23000): Column 'film_id' in field list is ambiguous
As for select *
, the joining column appears in the result set twice with ON
while it appears only once with USING
:
mysql> create table t(i int);insert t select 1;create table t2 select*from t;
Query OK, 0 rows affected (0.11 sec)
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
Query OK, 1 row affected (0.19 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> select*from t join t2 on t.i=t2.i;
+------+------+
| i | i |
+------+------+
| 1 | 1 |
+------+------+
1 row in set (0.00 sec)
mysql> select*from t join t2 using(i);
+------+
| i |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
mysql>
You cannot directly create a table stored as a sequence file and insert text into it. You must do this:
Example:
CREATE TABLE test_txt(field1 int, field2 string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';
LOAD DATA INPATH '/path/to/file.tsv' INTO TABLE test_txt;
CREATE TABLE test STORED AS SEQUENCEFILE
AS SELECT * FROM test_txt;
DROP TABLE test_txt;
For perl,
To run perl script use this procedure
Requirement: You need to setup classpath variable.
Go to plugins->NppExec->Execute
In command section, type this
cmd /c cd "$(CURRENT_DIRECTORY)"&&"$(FULL_CURRENT_PATH)"
Save it and give name to it.(I give Perl).
Press OK. If editor wants to restart, do it first.
Now press F6 and you will find your Perl script output on below side.
Note: Not required seperate config for seperate files.
For java,
Requirement: You need to setup JAVA_HOME
and classpath
variable.
Go to plugins->NppExec->Execute
In command section, type this
cmd /c cd "$(CURRENT_DIRECTORY)"&&"%JAVA_HOME%\bin\javac""$(FULL_CURRENT_PATH)"
your *.class
will generate on location of current folder; despite of programming error.
For Python,
Use this Plugin Python Plugin
Go to plugins->NppExec-> Run file in Python intercative
By using this you can run scripts within Notepad++.
For PHP,
No need for different configuration just download this plugin.
PHP Plugin and done.
For C language,
Requirement: You need to setup classpath variable.
I am using MinGW compiler.
Go to plugins->NppExec->Execute
paste this into there
NPP_SAVE
CD $(CURRENT_DIRECTORY)
C:\MinGW32\bin\gcc.exe -g "$(FILE_NAME)"
a
(Remember to give above four lines separate lines.)
Now, give name, save and ok.
Restart Npp.
Go to plugins->NppExec->Advanced options.
Menu Item->Item Name (I have C compiler)
Associated Script-> from combo box select the above name of script.
Click on Add/modify and Ok.
Now assign shortcut key as given in first answer.
Press F6 and select script or just press shortcut(I assigned Ctrl+2).
For C++,
Only change g++ instead of gcc
and *.cpp
instead on *.c
That's it!!
I would like to give an example which I tried by understanding above documentation and works correctly. If you wish to apply 25% padding on left and right sides medium screen size then please use px-md-1. It works as desired and can similarly follow for other screen sizes. :)
You could also use
data2 <- data[data$sum_points == 2500, ]
This will make a dataframe with the values where sum_points = 2500
It gives :
airfoils sum_points field_points init_t contour_t field_t
...
491 5 2500 5625 0.000086 0.004272 6.321774
498 5 2500 5625 0.000087 0.004507 6.325083
504 5 2500 5625 0.000088 0.004370 6.336034
603 5 250 10000 0.000072 0.000525 1.111278
577 5 250 10000 0.000104 0.000559 1.111431
587 5 250 10000 0.000072 0.000528 1.111524
606 5 250 10000 0.000079 0.000538 1.111685
....
> data2 <- data[data$sum_points == 2500, ]
> data2
airfoils sum_points field_points init_t contour_t field_t
108 5 2500 625 0.000082 0.004329 0.733109
106 5 2500 625 0.000102 0.004564 0.733243
117 5 2500 625 0.000087 0.004321 0.733274
112 5 2500 625 0.000081 0.004428 0.733587
This is how it should be done in typescript:
(new Date()).valueOf() - (new Date("2013-02-20T12:01:04.753Z")).valueOf()
Better readability:
var eventStartTime = new Date(event.startTime);
var eventEndTime = new Date(event.endTime);
var duration = eventEndTime.valueOf() - eventStartTime.valueOf();
There are two things to remember here. One is to add the -PassThru
argument and two is to add the -Wait
argument. You need to add the wait argument because of this defect: http://connect.microsoft.com/PowerShell/feedback/details/520554/start-process-does-not-return-exitcode-property
-PassThru [<SwitchParameter>]
Returns a process object for each process that the cmdlet started. By d
efault, this cmdlet does not generate any output.
Once you do this a process object is passed back and you can look at the ExitCode property of that object. Here is an example:
$process = start-process ping.exe -windowstyle Hidden -ArgumentList "-n 1 -w 127.0.0.1" -PassThru -Wait
$process.ExitCode
# This will print 1
If you run it without -PassThru
or -Wait
, it will print out nothing.
The same answer is here: How do I run a Windows installer and get a succeed/fail value in PowerShell?
==
is a bash-specific alias for =
and it performs a string (lexical) comparison instead of a numeric comparison. eq
being a numeric comparison of course.
Finally, I usually prefer to use the form if [ "$a" == "$b" ]
I was solving a similar task today in javascript.
I've settled on this getPerceivedLightness(rgb)
function for a HEX RGB color.
It deals with Helmholtz-Kohlrausch effect via Fairchild and Perrotta formula for luminance correction.
/**
* Converts RGB color to CIE 1931 XYZ color space.
* https://www.image-engineering.de/library/technotes/958-how-to-convert-between-srgb-and-ciexyz
* @param {string} hex
* @return {number[]}
*/
export function rgbToXyz(hex) {
const [r, g, b] = hexToRgb(hex).map(_ => _ / 255).map(sRGBtoLinearRGB)
const X = 0.4124 * r + 0.3576 * g + 0.1805 * b
const Y = 0.2126 * r + 0.7152 * g + 0.0722 * b
const Z = 0.0193 * r + 0.1192 * g + 0.9505 * b
// For some reason, X, Y and Z are multiplied by 100.
return [X, Y, Z].map(_ => _ * 100)
}
/**
* Undoes gamma-correction from an RGB-encoded color.
* https://en.wikipedia.org/wiki/SRGB#Specification_of_the_transformation
* https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
* @param {number}
* @return {number}
*/
function sRGBtoLinearRGB(color) {
// Send this function a decimal sRGB gamma encoded color value
// between 0.0 and 1.0, and it returns a linearized value.
if (color <= 0.04045) {
return color / 12.92
} else {
return Math.pow((color + 0.055) / 1.055, 2.4)
}
}
/**
* Converts hex color to RGB.
* https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
* @param {string} hex
* @return {number[]} [rgb]
*/
function hexToRgb(hex) {
const match = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
if (match) {
match.shift()
return match.map(_ => parseInt(_, 16))
}
}
/**
* Converts CIE 1931 XYZ colors to CIE L*a*b*.
* The conversion formula comes from <http://www.easyrgb.com/en/math.php>.
* https://github.com/cangoektas/xyz-to-lab/blob/master/src/index.js
* @param {number[]} color The CIE 1931 XYZ color to convert which refers to
* the D65/2° standard illuminant.
* @returns {number[]} The color in the CIE L*a*b* color space.
*/
// X, Y, Z of a "D65" light source.
// "D65" is a standard 6500K Daylight light source.
// https://en.wikipedia.org/wiki/Illuminant_D65
const D65 = [95.047, 100, 108.883]
export function xyzToLab([x, y, z]) {
[x, y, z] = [x, y, z].map((v, i) => {
v = v / D65[i]
return v > 0.008856 ? Math.pow(v, 1 / 3) : v * 7.787 + 16 / 116
})
const l = 116 * y - 16
const a = 500 * (x - y)
const b = 200 * (y - z)
return [l, a, b]
}
/**
* Converts Lab color space to Luminance-Chroma-Hue color space.
* http://www.brucelindbloom.com/index.html?Eqn_Lab_to_LCH.html
* @param {number[]}
* @return {number[]}
*/
export function labToLch([l, a, b]) {
const c = Math.sqrt(a * a + b * b)
const h = abToHue(a, b)
return [l, c, h]
}
/**
* Converts a and b of Lab color space to Hue of LCH color space.
* https://stackoverflow.com/questions/53733379/conversion-of-cielab-to-cielchab-not-yielding-correct-result
* @param {number} a
* @param {number} b
* @return {number}
*/
function abToHue(a, b) {
if (a >= 0 && b === 0) {
return 0
}
if (a < 0 && b === 0) {
return 180
}
if (a === 0 && b > 0) {
return 90
}
if (a === 0 && b < 0) {
return 270
}
let xBias
if (a > 0 && b > 0) {
xBias = 0
} else if (a < 0) {
xBias = 180
} else if (a > 0 && b < 0) {
xBias = 360
}
return radiansToDegrees(Math.atan(b / a)) + xBias
}
function radiansToDegrees(radians) {
return radians * (180 / Math.PI)
}
function degreesToRadians(degrees) {
return degrees * Math.PI / 180
}
/**
* Saturated colors appear brighter to human eye.
* That's called Helmholtz-Kohlrausch effect.
* Fairchild and Pirrotta came up with a formula to
* calculate a correction for that effect.
* "Color Quality of Semiconductor and Conventional Light Sources":
* https://books.google.ru/books?id=ptDJDQAAQBAJ&pg=PA45&lpg=PA45&dq=fairchild+pirrotta+correction&source=bl&ots=7gXR2MGJs7&sig=ACfU3U3uIHo0ZUdZB_Cz9F9NldKzBix0oQ&hl=ru&sa=X&ved=2ahUKEwi47LGivOvmAhUHEpoKHU_ICkIQ6AEwAXoECAkQAQ#v=onepage&q=fairchild%20pirrotta%20correction&f=false
* @return {number}
*/
function getLightnessUsingFairchildPirrottaCorrection([l, c, h]) {
const l_ = 2.5 - 0.025 * l
const g = 0.116 * Math.abs(Math.sin(degreesToRadians((h - 90) / 2))) + 0.085
return l + l_ * g * c
}
export function getPerceivedLightness(hex) {
return getLightnessUsingFairchildPirrottaCorrection(labToLch(xyzToLab(rgbToXyz(hex))))
}
As mentioned in other answers, JavaScript regexes have no support for Unicode character classes. However, there is a library that does provide this: Steven Levithan's excellent XRegExp and its Unicode plug-in.
Sorry if this is old but I just found a solution.
Try setting the font-size
to 0. Thus the white-spaces in between the images will be 0 in width, and the images won't be affected.
Don't know if this works in all browsers, but I tried it with Chromium and some <li>
elements with display: inline-block;
.
I had a similar problem:
docker: Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"sh\": executable file not found in $PATH": unknown.
In my case, I know the image works in other places, then was a corrupted local image.
I solved the issue removing the image (docker rmi <imagename>
) and pulling it again(docker pull <imagename>
).
I did a docker system prune
too, but I think it's not mandatory.
You are passing hello()
as a string, also hello()
means execute hello
immediately.
try
onClick={hello}
if you want your datetime.now()
precise till the minute , you can use
datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M'), '%Y-%m-%d %H:%M')
similarly for hour it will be
datetime.strptime(datetime.now().strftime('%Y-%m-%d %H'), '%Y-%m-%d %H')
It is kind of a hack, if someone has a better solution, I am all ears
This applies for "Intellij Idea- 2020.1.2" on window
Navigate to "IntelliJ IDEA->File->Settings->Editor->Code Style->java".
Here's one way:
Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = theDialog.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
Modified from here:MSDN OpenFileDialog.OpenFile
EDIT Here's another way more suited to your needs:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
string filename = theDialog.FileName;
string[] filelines = File.ReadAllLines(filename);
List<Employee> employeeList = new List<Employee>();
int linesPerEmployee = 4;
int currEmployeeLine = 0;
//parse line by line into instance of employee class
Employee employee = new Employee();
for (int a = 0; a < filelines.Length; a++)
{
//check if to move to next employee
if (a != 0 && a % linesPerEmployee == 0)
{
employeeList.Add(employee);
employee = new Employee();
currEmployeeLine = 1;
}
else
{
currEmployeeLine++;
}
switch (currEmployeeLine)
{
case 1:
employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
break;
case 2:
employee.Name = filelines[a].Trim();
break;
case 3:
employee.Address = filelines[a].Trim();
break;
case 4:
string[] splitLines = filelines[a].Split(' ');
employee.Wage = Convert.ToDouble(splitLines[0].Trim());
employee.Hours = Convert.ToDouble(splitLines[1].Trim());
break;
}
}
//Test to see if it works
foreach (Employee emp in employeeList)
{
MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
emp.Name + Environment.NewLine +
emp.Address + Environment.NewLine +
emp.Wage + Environment.NewLine +
emp.Hours + Environment.NewLine);
}
}
}
You can try viewport units (CSS3):
canvas {
height: 100vh;
width: 100vw;
display: block;
}
Here's a great method I recently found on a different stack overflow post regarding multi-dimensional arrays, but the answer works beautifully for single dimensional arrays as well:
# Create an 8 x 5 matrix of 0's:
w, h = 8, 5;
MyMatrix = [ [0 for x in range( w )] for y in range( h ) ]
# Create an array of objects:
MyList = [ {} for x in range( n ) ]
I love this because you can specify the contents and size dynamically, in one line!
One more for the road:
# Dynamic content initialization:
MyFunkyArray = [ x * a + b for x in range ( n ) ]
Update your environment variables
Ensure the reference to java/bin is up to date in 'Path'; This may be automatic if you have JAVA_HOME or equivalent set. If JAVA_HOME is set, simply update it to refer to the older JRE installation.
Oracle doesn't provide such IIF Function. Instead, try using one of the following alternatives:
SELECT DECODE(EMP_ID, 1, 'True', 'False') from Employee
SELECT CASE WHEN EMP_ID = 1 THEN 'True' ELSE 'False' END from Employee
in your servlet
request.setAttribute("submitDone","done");
return mapping.findForward("success");
In your jsp
<c:if test="${not empty submitDone}">
<script>alert("Form submitted");
</script></c:if>
It's possible that you're creating your controls on the wrong thread. Consider the following documentation from MSDN:
This means that InvokeRequired can return false if Invoke is not required (the call occurs on the same thread), or if the control was created on a different thread but the control's handle has not yet been created.
In the case where the control's handle has not yet been created, you should not simply call properties, methods, or events on the control. This might cause the control's handle to be created on the background thread, isolating the control on a thread without a message pump and making the application unstable.
You can protect against this case by also checking the value of IsHandleCreated when InvokeRequired returns false on a background thread. If the control handle has not yet been created, you must wait until it has been created before calling Invoke or BeginInvoke. Typically, this happens only if a background thread is created in the constructor of the primary form for the application (as in Application.Run(new MainForm()), before the form has been shown or Application.Run has been called.
Let's see what this means for you. (This would be easier to reason about if we saw your implementation of SafeInvoke also)
Assuming your implementation is identical to the referenced one with the exception of the check against IsHandleCreated, let's follow the logic:
public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous)
{
if (uiElement == null)
{
throw new ArgumentNullException("uiElement");
}
if (uiElement.InvokeRequired)
{
if (forceSynchronous)
{
uiElement.Invoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
}
else
{
uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
}
}
else
{
if (uiElement.IsDisposed)
{
throw new ObjectDisposedException("Control is already disposed.");
}
updater();
}
}
Consider the case where we're calling SafeInvoke
from the non-gui thread for a control whose handle has not been created.
uiElement
is not null, so we check uiElement.InvokeRequired
. Per the MSDN docs (bolded) InvokeRequired
will return false
because, even though it was created on a different thread, the handle hasn't been created! This sends us to the else
condition where we check IsDisposed
or immediately proceed to call the submitted action... from the background thread!
At this point, all bets are off re: that control because its handle has been created on a thread that doesn't have a message pump for it, as mentioned in the second paragraph. Perhaps this is the case you're encountering?
The simplest way is use return View.
return View("ViewName");
Remember, the physical name of the "ViewName" should be something like ViewName.cshtml in your project, if your are using MVC C# / .NET.
You can also look in the init script area (e.g. centos vi /etc/init.d/jenkins ) for details on how the service is actually started and stopped.
You can use LiteWare.Configuration library for that. It is very similar to .NET Framework original ConfigurationManager
and works for .NET Core/Standard. Code-wise, you'll end up with something like:
string cacheDirectory = ConfigurationManager.AppSettings.GetValue<string>("CacheDirectory");
ulong cacheFileSize = ConfigurationManager.AppSettings.GetValue<ulong>("CacheFileSize");
Disclaimer: I am the author of LiteWare.Configuration.
I've had this problem. See The Python "Connection Reset By Peer" Problem.
You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.
You can (sometimes) correct this with a time.sleep(0.01)
placed strategically.
"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just before you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.
Embedding the YouTube player in Android is very simple & it hardly takes you 10 minutes,
1) Enable YouTube API from Google API console
2) Download YouTube player Jar file
3) Start using it in Your app
Here are the detailed steps http://www.feelzdroid.com/2017/01/embed-youtube-video-player-android-app-example.html.
Just refer it & if you face any problem, let me know, ill help you
You could do an SQLDump
of the database (and its data) then search that file.
public static boolean isDirectory(String path) {
return path !=null && new File(path).isDirectory();
}
To answer the question directly.
You could try using Path.IsPathRooted() in combination with Path.GetInvalidFileNameChars() to make sure the path is half-way okay.
You can specify the interpretation order of the axes using the order
parameter:
np.reshape(arr, (2, -1), order='F')
You can set the "value" property
dateTimePicker1.Value = DateTime.Today;
Here are couple of alternatives versions with Jackson (since there are more than one ways you might want data as):
ObjectMapper mapper = new ObjectMapper(); // just need one
// Got a Java class that data maps to nicely? If so:
FacebookGraph graph = mapper.readValue(url, FaceBookGraph.class);
// Or: if no class (and don't need one), just map to Map.class:
Map<String,Object> map = mapper.readValue(url, Map.class);
And specifically the usual (IMO) case where you want to deal with Java objects, can be made one liner:
FacebookGraph graph = new ObjectMapper().readValue(url, FaceBookGraph.class);
Other libs like Gson also support one-line methods; why many examples show much longer sections is odd. And even worse is that many examples use obsolete org.json library; it may have been the first thing around, but there are half a dozen better alternatives so there is very little reason to use it.
It sounds like you're not instantiating your class. That's the primary reason I get the "an object reference is required" error.
MyClass myClass = new MyClass();
once you've added that line you can then call your method
myClass.myMethod();
Also, are all of your classes in the same namespace? When I was first learning c# this was a common tripping point for me.
Whilst this can be done with react, be aware that using onClicks with divs (instead of Buttons or Anchors, and others which already have behaviours for click events) is bad practice and should be avoided whenever it can be.
I was able to import the module within the function (only) that would require the objects from this module:
def my_func():
import Foo
foo_instance = Foo()
Set npm registry globally
use the below command to modify the .npmrc config file for the logged in user
npm config set registry <registry url>
Example: npm config set registry https://registry.npmjs.org/
Set npm registry Scope
Scopes allow grouping of related packages together. Scoped packages will be installed in a sub-folder under node_modules folder.
Example: node_modules/@my-org/packagaename
To set the scope registry use: npm config set @my-org:registry http://example.reg-org.com
To install packages using scope use: npm install @my-org/mypackage
whenever you install any packages from scope @my-org npm will search in the registry setting linked to scope @my-org for the registry url.
Set npm registry locally for a project
To modify the npm registry only for the current project. create a file inside the root folder of the project as .npmrc
Add the below contents in the file
registry = 'https://registry.npmjs.org/'