{ "error_message" : "This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console: Learn more: https://code.google.com/apis/console", "results" : [], "status" : "REQUEST_DENIED" }
Enabling Directions API made me this error fixed
https://console.developers.google.com/apis/library/directions-backend.googleapis.com
You don't "remove the character 'u' from a list", you encode Unicode strings. In fact the strings you have are perfectly fine for most uses; you will just need to encode them appropriately before outputting them.
if your port is 7001, since it's the default it might not be mentioned in the config.xml. config.xml only reports stuff which differs from the default, for sake of simplicity.
apart from the config.xml, you should look into a number of other places under your domain-home:
bin/stopWebLogic.sh
bin/stopManagedWebLogic.sh
bin/startManagedWebLogic.sh
config/fmwconfig/servers/osbts1as/applications/em/META-INF/emoms.properties
config/config.xml
init-info/startscript.xml
init-info/tokenValue.properties
servers/osbts1as/data/nodemanager/osbts1as.url
servers/osbts1as/data/ldap/conf/replicas.prop
servers/osbts1ms1/data/nodemanager/osbts1ms1.url
servers/osbts1ms1/data/nodemanager/startup.properties
servers/osbts1ms2/data/nodemanager/osbts1ms2.url
servers/osbts1ms2/data/nodemanager/startup.properties
startManagedWebLogic_readme.txt
sysman/state/targets.xml
And don't forget to update any internal URIs of your deployed code.
See also http://www.javamonamour.org/2013/04/weblogic-change-admin-port-number.html
Especially changing the listen address/port of the admin can be troublesome. If you change only the managed server, it's a lot easier.
The best option is just rebuilding the domain.
You have to use execute immediate (dynamic sql).
DECLARE
v_owner varchar2(40);
v_table_name varchar2(40);
cursor get_tables is
select distinct table_name,user
from user_tables
where lower(user) = 'schema_name';
begin
open get_tables;
loop
fetch get_tables into v_table_name,v_owner;
EXIT WHEN get_tables%NOTFOUND;
execute immediate 'INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED)
SELECT ''' || v_table_name || ''' , ''' || v_owner ||''',COUNT(*),TO_DATE(SYSDATE,''DD-MON-YY'') FROM ' || v_table_name;
end loop;
CLOSE get_tables;
END;
One more method worth to mention here:
SQLCMD -S SEVERNAME -E -Q "SELECT COLUMN FROM TABLE" -s "," -o "c:\test.csv"
NOTE: I don't see any network admin let you run powershell scripts
For everyone that says checking types and doing something based on the type is not a great idea for generics I sort of agree but I think there could be some circumstances where this perfectly makes sense.
For example if you have a class that say is implemented like so (Note: I am not showing everything that this code does for simplicity and have simply cut and pasted into here so it may not build or work as intended like the entire code does but it gets the point across. Also, Unit is an enum):
public class FoodCount<TValue> : BaseFoodCount
{
public TValue Value { get; set; }
public override string ToString()
{
if (Value is decimal)
{
// Code not cleaned up yet
// Some code and values defined in base class
mstrValue = Value.ToString();
decimal mdecValue;
decimal.TryParse(mstrValue, out mdecValue);
mstrValue = decimal.Round(mdecValue).ToString();
mstrValue = mstrValue + mstrUnitOfMeasurement;
return mstrValue;
}
else
{
// Simply return a string
string str = Value.ToString() + mstrUnitOfMeasurement;
return str;
}
}
}
...
public class SaturatedFat : FoodCountWithDailyValue<decimal>
{
public SaturatedFat()
{
mUnit = Unit.g;
}
}
public class Fiber : FoodCount<int>
{
public Fiber()
{
mUnit = Unit.g;
}
}
public void DoSomething()
{
nutritionFields.SaturatedFat oSatFat = new nutritionFields.SaturatedFat();
string mstrValueToDisplayPreFormatted= oSatFat.ToString();
}
So in summary, I think there are valid reasons why you might want to check to see what type the generic is, in order to do something special.
You need to change the Solution Platform from "Any CPU" to "x86" or "x64" based on the bitness of office installation.
The steps are given below:
Compile and run your application.
I've used this "portable plotter". It's very small, multiplatform, easy to use and you can plug it into different graphical libraries. pplot
(Only for the plots part)
If you use or plan to use Qt, another multiplatform solution is Qwt and Qchart
Old question with plenty of answers, but here's more solutions:
A Bash function can't return a string directly like you want it to. You can do three things:
This is also true for some other shells.
Here's how to do each of those options:
lockdir="somedir"
testlock(){
retval=""
if mkdir "$lockdir"
then # Directory did not exist, but it was created successfully
echo >&2 "successfully acquired lock: $lockdir"
retval="true"
else
echo >&2 "cannot acquire lock, giving up on $lockdir"
retval="false"
fi
echo "$retval"
}
retval=$( testlock )
if [ "$retval" == "true" ]
then
echo "directory not created"
else
echo "directory already created"
fi
lockdir="somedir"
testlock(){
if mkdir "$lockdir"
then # Directory did not exist, but was created successfully
echo >&2 "successfully acquired lock: $lockdir"
retval=0
else
echo >&2 "cannot acquire lock, giving up on $lockdir"
retval=1
fi
return "$retval"
}
testlock
retval=$?
if [ "$retval" == 0 ]
then
echo "directory not created"
else
echo "directory already created"
fi
lockdir="somedir"
retval=-1
testlock(){
if mkdir "$lockdir"
then # Directory did not exist, but it was created successfully
echo >&2 "successfully acquired lock: $lockdir"
retval=0
else
echo >&2 "cannot acquire lock, giving up on $lockdir"
retval=1
fi
}
testlock
if [ "$retval" == 0 ]
then
echo "directory not created"
else
echo "directory already created"
fi
On the one hand you could use sp_executesql:
exec sp_executesql N'select @rowcount=count(*) from anytable',
N'@rowcount int output', @rowcount output;
On the other hand you could use a temporary table:
declare @result table ([rowcount] int);
insert into @result ([rowcount])
exec (N'select count(*) from anytable');
declare @rowcount int = (select top (1) [rowcount] from @result);
Try this:
function validate() {
var remember = document.getElementById("remember");
if (remember.checked) {
alert("checked");
} else {
alert("You didn't check it! Let me check it for you.");
}
}
Your script doesn't know what the variable remember
is. You need to get the element first using getElementById().
GitHub pages host only static HTML pages. No server side technology is supported, so Node.js applications won't run on GitHub pages. There are lots of hosting providers, as listed on the Node.js wiki.
App fog seems to be the most economical as it provides free hosting for projects with 2GB of RAM (which is pretty good if you ask me).
As stated here, AppFog removed their free plan for new users.
If you want to host static pages on GitHub, then read this guide. If you plan on using Jekyll, then this guide will be very helpful.
After a some research i found the way to bypass ssl error Trust anchor for certification path not found. This might be not a good way to do but you can use it for a testing purpose.
private HttpsURLConnection httpsUrlConnection( URL urlDownload) throws Exception {
HttpsURLConnection connection=null;
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@SuppressLint("TrustAllX509TrustManager")
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@SuppressLint("TrustAllX509TrustManager")
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL"); // Add in try catch block if you get error.
sc.init(null, trustAllCerts, new java.security.SecureRandom()); // Add in try catch block if you get error.
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier usnoHostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
connection = (HttpsURLConnection) urlDownload.openConnection();
connection.setHostnameVerifier(usnoHostnameVerifier);
connection.setSSLSocketFactory(sslSocketFactory);
return connection;
}
This is the natural javascript option
var myArray = ['1','2',3,4]_x000D_
_x000D_
myArray.forEach(function(value){_x000D_
console.log(value);_x000D_
});
_x000D_
However it won't work if you're using await inside the forEach loop because forEach is not asynchronous. you'll be forced to use the second answer or some other equivalent:
let myArray = ["a","b","c","d"];_x000D_
for (let item of myArray) {_x000D_
console.log(item);_x000D_
}
_x000D_
Or you could create an asyncForEach explained here:
https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
I also meet that problems,and just delete bottom code:
DELETE THESE LINES:
android {
compileSdkVersion 22
buildToolsVersion '22.0.1'
}
it worked?
I did it that way and I like it better, but it can be optimized, right?
// Obtengo los botones y la caja de contenido
var home = document.getElementById("home");
var about = document.getElementById("about");
var service = document.getElementById("service");
var contact = document.getElementById("contact");
var content = document.querySelector("section");
function botonPress(e){
console.log(e.getAttribute("id"));
var screen = e.getAttribute("id");
switch(screen){
case "home":
// cambiar fondo
content.style.backgroundColor = 'black';
break;
case "about":
// cambiar fondo
content.style.backgroundColor = 'blue';
break;
case "service":
// cambiar fondo
content.style.backgroundColor = 'green';
break;
case "contact":
// cambiar fondo
content.style.backgroundColor = 'red';
break;
}
}
It is likely you will have to pull the text file into memory and then do the replacements. You will then have to overwrite the file using the method you clearly know about. So you would first:
// Read lines from source file.
string[] arr = File.ReadAllLines(file);
YOu can then loop through and replace the text in the array.
var writer = new StreamWriter(GetFileName(baseFolder, prefix, num));
for (int i = 0; i < arr.Length; i++)
{
string line = arr[i];
line.Replace("match", "new value");
writer.WriteLine(line);
}
this method gives you some control on the manipulations you can do. Or, you can merely do the replace in one line
File.WriteAllText("test.txt", text.Replace("match", "new value"));
I hope this helps.
Update:
As of Xcode 7.1, you don't need to manually enter the NSAppTransportSecurity
Dictionary in the info.plist
.
It will now autocomplete for you, realize it's a dictionary, and then autocomplete the Allows Arbitrary
Loads as well.
info.plist screenshot
Somthing like this should workL
SELECT BookingId, StartTime
FROM Booking
WHERE StartTime between dateadd(hour, -1, getdate()) and getdate()
Messagebox is for windows only. You have to use Javascript
Alert('dd');
I think this happen because the name of your class is the same name of another class in the JDK . Help eclipse to determine which one you are trying to run by selecting the package your class is in . Go to run configuration select the project and the main class.
When you press the search button to select the main class, you will find options that have the same name but different package, select your class.
Make sure you don't include extension of the resource, nor path to it. It's only the resource file name.
PictureBoxName.Image = My.Resources.ResourceManager.GetObject("object_name")
Andreas Grech was pretty close... it's actually this
(note the reference to this
instead of the item in the loop):
var $dropdown = $("#dropdown");
$.each(result, function() {
$dropdown.append($("<option />").val(this.ImageFolderID).text(this.Name));
});
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name,*
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%YOUR_COLUMN%'
ORDER BY schema_name, table_name;
It looks like you can also use a netmask, e.g.
GRANT ... TO 'user'@'192.168.0.0/255.255.255.0' IDENTIFIED BY ...
:not
selector:
input:not([type]), input[type='text'], input[type='password'] {
/* style here */
}
Support: in Internet Explorer 9 and higher
In addition to the perfect answer provided by @Guilherme Meireles as shown below, you could tweak your implementation by adding smooth scroll as shown below
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'my-app',
template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
window.scrollTo(0, 0)
});
}
}
then add the snippet below
html {
scroll-behavior: smooth;
}
to your styles.css
Assuming that all your inputs are lists and that the double quotes in the input actually don't matter, this can be done with a simple regexp replace. It is a bit perl-y but works like a charm. Note also that the output is now a list of unicode strings, you didn't specify that you needed that, but it seems to make sense given unicode input.
import re
x = u'[ "A","B","C" , " D"]'
junkers = re.compile('[[" \]]')
result = junkers.sub('', x).split(',')
print result
---> [u'A', u'B', u'C', u'D']
The junkers variable contains a compiled regexp (for speed) of all characters we don't want, using ] as a character required some backslash trickery. The re.sub replaces all these characters with nothing, and we split the resulting string at the commas.
Note that this also removes spaces from inside entries u'["oh no"]' ---> [u'ohno']. If this is not what you wanted, the regexp needs to be souped up a bit.
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
I think this is a very good chart describing the differences in short. A quick glance at it shows most of the differences.
One thing I would like to add is that, AngularJS can be made to follow the MVVM design pattern while jQuery does not follow any of the standard Object Oriented patterns.
You can use as below,
Select X.a, X.b, Y.c from (
Select X.a as a, sum (b) as sum_b from name_table X
group by X.a)X
left join from name_table Y on Y.a = X.a
Example;
CREATE TABLE #products (
product_name VARCHAR(MAX),
code varchar(3),
list_price [numeric](8, 2) NOT NULL
);
INSERT INTO #products VALUES ('paku', 'ACE', 2000)
INSERT INTO #products VALUES ('paku', 'ACE', 2000)
INSERT INTO #products VALUES ('Dinding', 'ADE', 2000)
INSERT INTO #products VALUES ('Kaca', 'AKB', 2000)
INSERT INTO #products VALUES ('paku', 'ACE', 2000)
--SELECT * FROM #products
SELECT distinct x.code, x.SUM_PRICE, product_name FROM (SELECT code, SUM(list_price) as SUM_PRICE From #products
group by code)x
left join #products y on y.code=x.code
DROP TABLE #products
On Ubuntu 12.04 (Precise Pangolin), I got this working with the following command:
sudo apt-get install ruby1.9.1
sudo apt-get install ruby1.9.3
It's simple. Just do this:
#include <iostream>
#include <vector>
#include <string.h>
int main(int argc, char *argv[])
{
std::vector<std::string> argList;
for(int i=0;i<argc;i++)
argList.push_back(argv[i]);
//now you can access argList[n]
}
@Benjamin Lindley You are right. This is not a good solution. Please read the one answered by juanchopanza.
I ran into this in IntelliJ and fixed it by adding the following to my pom:
<!-- logging dependencies -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<exclusions>
<exclusion>
<!-- Defined below -->
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:
In [1]: float_formatter = "{:.2f}".format
The f
here means fixed-point format (not 'scientific'), and the .2
means two decimal places (you can read more about string formatting here).
Let's test it out with a float value:
In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'
To make numpy print all float arrays this way, you can pass the formatter=
argument to np.set_printoptions
:
In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})
Now numpy will print all float arrays this way:
In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]
Note that this only affects numpy arrays, not scalars:
In [5]: np.pi
Out[5]: 3.141592653589793
It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.
You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.
For example:
In [6]: a = np.array([1E-9])
In [7]: a
Out[7]: array([0.00])
In [8]: a == 0
Out[8]: array([False], dtype=bool)
numpy prints a
as if it were equal to 0
, but it is not - it still equals 1E-9
.
If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round
, as others have already pointed out.
To use session variables, it's necessary to start the session by using the session_start
function, this will allow you to store your data in the global variable $_SESSION
in a productive way.
so your code will finally look like this :
<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>
<?php
// starting the session
session_start();
if (isset($_POST['Submit'])) {
$_SESSION['picturenum'] = $_POST['picturenum'];
}
?>
<strong><?php echo $_SESSION['picturenum'];?></strong>
to make it easy to use and to avoid forgetting it again, you can create a session_file.php
which you will want to be included in all your codes and will start the session for you:
session_start.php
<?php
session_start();
?>
and then include it wherever you like :
<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>
<?php
// including the session file
require_once("session_start.php");
if (isset($_POST['Submit'])) {
$_SESSION['picturenum'] = $_POST['picturenum'];
}
?>
that way it is more portable and easy to maintain in the future.
other remarks
if you are using Apache version 2 or newer, be careful. instead of
<?
to open php's tags, use
<?php
, otherwise your code will not be interpreted
variables names in php are case-sensitive, instead of write $_session, write $_SESSION in capital letters
good work!
<script>
var scrollHeight = document.body.scrollHeight;
var clientHeight = document.documentElement.clientHeight;
var hasVerticalScrollbar = scrollHeight > clientHeight;
alert(scrollHeight + " and " + clientHeight); //for checking / debugging.
alert("hasVerticalScrollbar is " + hasVerticalScrollbar + "."); //for checking / debugging.
</script>
This one will tell you if you have a scrollbar or not. I've included some information that may help with debugging, which will display as a JavaScript alert.
Put this in a script tag, after the closing body tag.
This function returns an array regardless of the size of the range.
Ranges will return an array unless the range is only 1 cell and then it returns a single value instead. This function will turn the single value into an array (1 based, the same as the array's returned by ranges)
This answer improves on previous answers as it will return an array from a range no matter what the size. It is also more efficient that other answers as it will return the array generated by the range if possible. Works with single dimension and multi-dimensional arrays
The function works by trying to find the upper bounds of the array. If that fails then it must be a single value so we'll create an array and assign the value to it.
Public Function RangeToArray(inputRange As Range) As Variant()
Dim size As Integer
Dim inputValue As Variant, outputArray() As Variant
' inputValue will either be an variant array for ranges with more than 1 cell
' or a single variant value for range will only 1 cell
inputValue = inputRange
On Error Resume Next
size = UBound(inputValue)
If Err.Number = 0 Then
RangeToArray = inputValue
Else
On Error GoTo 0
ReDim outputArray(1 To 1, 1 to 1)
outputArray(1,1) = inputValue
RangeToArray = outputArray
End If
On Error GoTo 0
End Function
When you want to count the frequency of categorical data in a column in pandas dataFrame use: df['Column_Name'].value_counts()
-Source.
You can do this with CSS Variable
.box-shadow {
--box-shadow-color: #000; /* Declaring the variable */
width: 30px;
height: 30px;
box-shadow: 1px 1px 25px var(--box-shadow-color); /* Calling the variable */
}
.box-shadow:hover {
--box-shadow-color: #ff0000; /* Changing the value of the variable */
}
In my case the maven "Run configuration" was using the wrong JRE (1.7). Be sure to check Run -> Run Configurations -> (Tab) JRE to be some jdk1.8.x.
Most answers here do not realize the problem, the user wants to have a COPY of the elements from first list to the second list, destination list elements are new objects and not reference to the elements of original list. (means changing an element of second list should not change values for corresponding element of source list.) For the mutable objects we cannot use ArrayList(Collection) constructor because it will simple refer to the original list element and will not copy. You need to have a list cloner for each object when copying.
Yes if you are using latest java which is version 8. Java8 make it possible to define anonymous functions which was impossible in previous versions.
Lets take example from java docs to get know how we can declare anonymous functions, classes
The following example, HelloWorldAnonymousClasses, uses anonymous classes in the initialization statements of the local variables frenchGreeting and spanishGreeting, but uses a local class for the initialization of the variable englishGreeting:
public class HelloWorldAnonymousClasses {
interface HelloWorld {
public void greet();
public void greetSomeone(String someone);
}
public void sayHello() {
class EnglishGreeting implements HelloWorld {
String name = "world";
public void greet() {
greetSomeone("world");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hello " + name);
}
}
HelloWorld englishGreeting = new EnglishGreeting();
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
HelloWorld spanishGreeting = new HelloWorld() {
String name = "mundo";
public void greet() {
greetSomeone("mundo");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hola, " + name);
}
};
englishGreeting.greet();
frenchGreeting.greetSomeone("Fred");
spanishGreeting.greet();
}
public static void main(String... args) {
HelloWorldAnonymousClasses myApp =
new HelloWorldAnonymousClasses();
myApp.sayHello();
}
}
Syntax of Anonymous Classes
Consider the instantiation of the frenchGreeting object:
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
The anonymous class expression consists of the following:
new
operatorThe name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.
Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
If anyone faces the following error message when they use adb devices
no permissions (verify udev rules); see [http://developer.android.com/tools/device.html]
Execute the following
sudo -s
adb kill-server
adb start-server
That fixed the issue for me on a custom build android device
Just thinking off the top of my head, you could do this:
public string[] Randomize(string[] input)
{
List<string> inputList = input.ToList();
string[] output = new string[input.Length];
Random randomizer = new Random();
int i = 0;
while (inputList.Count > 0)
{
int index = r.Next(inputList.Count);
output[i++] = inputList[index];
inputList.RemoveAt(index);
}
return (output);
}
<roleManager
enabled="true"
cacheRolesInCookie="false"
cookieName=".ASPXROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All"
defaultProvider="AspNetSqlRoleProvider"
createPersistentCookie="false"
maxCachedResults="25">
<providers>
<clear />
<add
connectionStringName="MembershipConnection"
applicationName="Mvc3"
name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add
applicationName="Mvc3"
name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>
sudo su - postgres
psql template1
creating role on pgsql with privilege as "superuser"
CREATE ROLE username superuser;
eg. CREATE ROLE demo superuser;
Then create user
CREATE USER username;
eg. CREATE USER demo;
Assign privilege to user
GRANT ROOT TO username;
And then enable login that user, so you can run e.g.: psql template1
, from normal $
terminal:
ALTER ROLE username WITH LOGIN;
I haven 't seen it here so i post it because for me is the best way in winforms:
List<object> objList = new List<object>();
listBox.DataSource = objList ;
listBox.Refresh();
listBox.Update();
This worked for my case
// Create/Set toolbar as actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Check if the version of Android is Lollipop or higher
if (Build.VERSION.SDK_INT >= 21) {
// Set the status bar to dark-semi-transparentish
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// Set paddingTop of toolbar to height of status bar.
// Fixes statusbar covers toolbar issue
toolbar.setPadding(0, getStatusBarHeight(), 0, 0);
}
// A method to find height of the status bar
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
For more information about working with statusBars: youtube.com/watch?v=_mGDMVRO3iE
Just use the split
function. It returns a list, so you can keep the first element:
>>> s1.split(':')
['Username', ' How are you today?']
>>> s1.split(':')[0]
'Username'
In php 7 you can do:
$_POST['value'] ?? null;
If value is equal to '' as said in other answers it will also send you null.
You should try this. It starts the program with no window. It actually flashes up for a second but goes away fairly quickly.
start "name" /B myprogram.exe param1
Just ask it for the objectForKey:@"b"
. If it returns nil
, no object is set at that key.
if ([xyz objectForKey:@"b"]) {
NSLog(@"There's an object set for key @\"b\"!");
} else {
NSLog(@"No object set for key @\"b\"");
}
Edit: As to your edited second question, it's simply NSUInteger mCount = [xyz count];
. Both of these answers are documented well and easily found in the NSDictionary class reference ([1] [2]).
Try that:
var defaultEmailNews = "Email address";
$('input[name=email]').focus(function() {
if($(this).val() == defaultEmailNews) $(this).val("");
});
$('input[name=email]').focusout(function() {
if($(this).val() == "") $(this).val(defaultEmailNews);
});
For python 3, try something like this:
import urllib.request
urllib.request.urlretrieve('http://crcv.ucf.edu/THUMOS14/UCF101/UCF101/v_YoYo_g19_c02.avi', "video_name.avi")
It will download the video to the current working directory
You may use negative superthick semi-transparent border...
.red {_x000D_
outline: 100px solid rgba(255, 0, 0, 0.5) !important;_x000D_
outline-offset: -100px;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
}
_x000D_
<div class="red">Anything can be red.</div>_x000D_
<h1>Or even image...</h1>_x000D_
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" class="red"/>
_x000D_
This solution requires you to know exact sizes of covered object.
This is the Swift version of David's Objective-C answer. You use the global queue to run things in the background and the main queue to update the UI.
DispatchQueue.global(qos: .background).async {
// Background Thread
DispatchQueue.main.async {
// Run UI Updates
}
}
Not sure if the cleanest for long commands but certainly the easiest:
ssh user@host "cmd1; cmd2; cmd3"
Jon Tan has done this with his site - http://jontangerine.com/ Everything including images has been declared in ems. Everything. This is how the desired effect is achieved. Text zoom and screen zoom yield almost the exact same result.
If a special character other than $, _, and # is used in the name of a column or table, the name must be enclosed in double quotations. Link
your understanding is right. For detailed info on {} see bash ref - parameter expansion
'for' and 'while' have different syntax and offer different styles of programmer control for an iteration. Most non-asm languages offer a similar syntax.
With while, you would probably write i=0; while [ $i -lt 10 ]; do echo $i; i=$(( i + 1 )); done
in essence manage everything about the iteration yourself
I had same issue and I solved it by "pod setup" after installing cocoapods.
Just create a data.frame
with 0 length variables
eg
nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)
## 'data.frame': 0 obs. of 3 variables:
## $ x: num
## $ y: int
## $ z: Factor w/ 0 levels:
or to create a data.frame with 5 columns named a,b,c,d,e
nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))
jqyery this is another version with jquery a little less shorter.
assuming that the <a>
element is inside de <li>
element
$(li).click(function(){
$(this).children().click();
});
You need to commit or destroy any unsaved changes before you switch branch.
Git won't let you switch branch if it means unsaved changes would be removed.
Peter Lawrey's answer is great because it is simple and not depending on anything special, and it's the way you should do it. If you need something that removes subdirectories and their contents as well, use recursion:
void purgeDirectory(File dir) {
for (File file: dir.listFiles()) {
if (file.isDirectory())
purgeDirectory(file);
file.delete();
}
}
To spare subdirectories and their contents (part of your question), modify as follows:
void purgeDirectoryButKeepSubDirectories(File dir) {
for (File file: dir.listFiles()) {
if (!file.isDirectory())
file.delete();
}
}
Or, since you wanted a one-line solution:
for (File file: dir.listFiles())
if (!file.isDirectory())
file.delete();
Using an external library for such a trivial task is not a good idea unless you need this library for something else anyway, in which case it is preferrable to use existing code. You appear to be using the Apache library anyway so use its FileUtils.cleanDirectory()
method.
try using:
RAISERROR('your message here!!!',0,1) WITH NOWAIT
you could also try switching to "Results to Text" it is just a few icons to the right of "Execute" on the default tool bar.
With both of the above in place, and you still you do not see the messages, make sure you are running the same server/database/owner version of the procedure that you are editing. Make sure you are hitting the RAISERROR command, make it the first command inside the procedure.
If all else fails, you could create a table:
create table temp_log (RowID int identity(1,1) primary key not null
, MessageValue varchar(255))
then:
INSERT INTO temp_log VALUES ('Your message here')
then after running the procedure (provided no rollbacks) just select
the table.
Do it this way instead:
function mycommand {
ssh [email protected] "cd testdir;./test.sh \"$1\""
}
You still have to pass the whole command as a single string, yet in that single string you need to have $1
expanded before it is sent to ssh so you need to use ""
for it.
Another proper way to do this actually is to use printf %q
to properly quote the argument. This would make the argument safe to parse even if it has spaces, single quotes, double quotes, or any other character that may have a special meaning to the shell:
function mycommand {
printf -v __ %q "$1"
ssh [email protected] "cd testdir;./test.sh $__"
}
function
, ()
is not necessary.This worked for me (I'm using VS Code):
for:
This is just\na simple sentence
Use:
This .+ sentence
((?=\d{4})\d{4}|(?=[a-zA-Z]{3})[a-zA-Z]{3}|\d{2})((?=\/)\/|\-)((?=[0-9]{2})[0-9]{2}|(?=[0-9]{1,2})[0-9]{1,2}|[a-zA-Z]{3})((?=\/)\/|\-)((?=[0-9]{4})[0-9]{4}|(?=[0-9]{2})[0-9]{2}|[a-zA-Z]{3})
Regex Compile on it
2012/22/Jan
2012/22/12
2012/22/12
2012/22/12
2012/22/12
2012/22/12
2012/22/12
2012-Dec-22
2012-12-22
23/12/2012
23/12/2012
Dec-22-2012
12-2-2012
23-12-2012
23-12-2012
I demonstrate how to receive a string, for example "-484876800000" and tryparse the string to make sure it can be assigned to a long. I calculate the Date from universaltime and return a string. When you convert a string to a number, you must decide the numeric type and precision and test if the string data can be parse, otherwise, it will throw and error.
function universalToDate
{
param (
$paramValue
)
$retVal=""
if ($paramValue)
{
$epoch=[datetime]'1/1/1970'
[long]$returnedLong = 0
[bool]$result = [long]::TryParse($paramValue,[ref]$returnedLong)
if ($result -eq 1)
{
$val=$returnedLong/1000.0
$retVal=$epoch.AddSeconds($val).ToString("yyyy-MM-dd")
}
}
else
{
$retVal=$null
}
return($retVal)
}
Usage:
CountDownTimer timer = new CountDownTimer();
//set to 30 mins
timer.SetTime(30,0);
timer.Start();
//update label text
timer.TimeChanged += () => Label1.Text = timer.TimeLeftMsStr;
// show messageBox on timer = 00:00.000
timer.CountDownFinished += () => MessageBox.Show("Timer finished the work!");
//timer step. By default is 1 second
timer.StepMs = 77; // for nice milliseconds time switch
and don't forget to Dispose();
when timer is useless for you;
Source code:
using System;
using System.Diagnostics;
using System.Windows.Forms;
public class CountDownTimer : IDisposable
{
public Stopwatch _stpWatch = new Stopwatch();
public Action TimeChanged;
public Action CountDownFinished;
public bool IsRunnign => timer.Enabled;
public int StepMs
{
get => timer.Interval;
set => timer.Interval = value;
}
private Timer timer = new Timer();
private TimeSpan _max = TimeSpan.FromMilliseconds(30000);
public TimeSpan TimeLeft => (_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) > 0 ? TimeSpan.FromMilliseconds(_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) : TimeSpan.FromMilliseconds(0);
private bool _mustStop => (_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) < 0;
public string TimeLeftStr => TimeLeft.ToString(@"\mm\:ss");
public string TimeLeftMsStr => TimeLeft.ToString(@"mm\:ss\.fff");
private void TimerTick(object sender, EventArgs e)
{
TimeChanged?.Invoke();
if (_mustStop)
{
CountDownFinished?.Invoke();
_stpWatch.Stop();
timer.Enabled = false;
}
}
public CountDownTimer(int min, int sec)
{
SetTime(min, sec);
Init();
}
public CountDownTimer(TimeSpan ts)
{
SetTime(ts);
Init();
}
public CountDownTimer()
{
Init();
}
private void Init()
{
StepMs = 1000;
timer.Tick += new EventHandler(TimerTick);
}
public void SetTime(TimeSpan ts)
{
_max = ts;
TimeChanged?.Invoke();
}
public void SetTime(int min, int sec = 0) => SetTime(TimeSpan.FromSeconds(min * 60 + sec));
public void Start() {
timer.Start();
_stpWatch.Start();
}
public void Pause()
{
timer.Stop();
_stpWatch.Stop();
}
public void Stop()
{
Reset();
Pause();
}
public void Reset()
{
_stpWatch.Reset();
}
public void Restart()
{
_stpWatch.Reset();
timer.Start();
}
public void Dispose() => timer.Dispose();
}
(updated 6.6.2020, because of problems with time calculation)
If you don't care about a minimum width for the div and really just don't want the div to expand across the whole container, you can float it left -- floated divs by default expand to support their contents, like so:
<form>
<div style="float: left; background-color: blue">
<input type="button" name="blah" value="lots and lots of characters"/>
<input type="button" name="blah2" value="some characters"/>
</div>
</form>
LEFT ('BTA200', 3) will work for the examples you have given, as in :
SELECT LEFT(MyField, 3)
FROM MyTable
To extract the numeric part, you can use this code
SELECT RIGHT(MyField, LEN(MyField) - 3)
FROM MyTable
WHERE MyField LIKE 'BTA%'
--Only have this test if your data does not always start with BTA.
preg_match_all(/<pre>([^>]*?)<\/pre>/,$content,$matches)
this regex will select everyting between tag. no matter is it in new line(work with multiline.
The permgen space is the area of heap that holds all the reflective data of the virtual machine itself, such as class and method objects.
Code like this
<html>
<head>
<script type="text/javascript" src="path/to/script.js"></script>
<!--other script and also external css included over here-->
</head>
<body>
<form>
<select name="users" onChange="showUser(this.value)">
<option value="1">Tom</option>
<option value="2">Bob</option>
<option value="3">Joe</option>
</select>
</form>
</body>
</html>
I hope it will help you.... thanks
you can simply do this..
<img src={"http://img.example.com/test/" + this.props.url +"/1.jpg"}/>
HTML5 and the VLC web plugin were a no go for me but I was able to get this work using the following setup:
DivX Web Player (NPAPI browsers only)
And here is the HTML:
<embed id="divxplayer" type="video/divx" width="1024" height="768"
src ="path_to_file" autoPlay=\"true\"
pluginspage=\"http://go.divx.com/plugin/download/\"></embed>
The DivX player seems to allow for a much wider array of video and audio options than the native HTML5, so far I am very impressed by it.
This worked for me
var dateToFormat = "2018-05-16 12:57:13"; //TIMESTAMP
moment(dateToFormat).format("DD/MM/YYYY"); // you get "16/05/2018"
For me, ctrl + m
is used to save the webpage as png, so it does not work properly. But I find another way.
On the toolbar, there is a bottom named open the command paletee, you can click it and type in the line, and you can see the toggle cell line number here.
An old thread, but may help future readers...
I would avoid using .lower() on filenames if for no other reason than to make your code more platform independent. (linux is case sensistive, .lower() on a filename will surely corrupt your logic eventually ...or worse, an important file!)
Why not use re? (Although to be even more robust, you should check the magic file header of each file... How to check type of files without extensions in python? )
import re
def checkext(fname):
if re.search('\.mp3$',fname,flags=re.IGNORECASE):
return('mp3')
if re.search('\.flac$',fname,flags=re.IGNORECASE):
return('flac')
return('skip')
flist = ['myfile.mp3', 'myfile.MP3','myfile.mP3','myfile.mp4','myfile.flack','myfile.FLAC',
'myfile.Mov','myfile.fLaC']
for f in flist:
print "{} ==> {}".format(f,checkext(f))
Output:
myfile.mp3 ==> mp3
myfile.MP3 ==> mp3
myfile.mP3 ==> mp3
myfile.mp4 ==> skip
myfile.flack ==> skip
myfile.FLAC ==> flac
myfile.Mov ==> skip
myfile.fLaC ==> flac
You could also organise them into modules. So it would be something like.
./
controllers
index.js
indexController.js
app.js
and then in the indexController.js of the controllers export your controllers.
//indexController.js
module.exports = function(){
//do some set up
var self = {
indexAction : function (req,res){
//do your thing
}
return self;
};
then in index.js of controllers dir
exports.indexController = require("./indexController");
and finally in app.js
var controllers = require("./controllers");
app.get("/",controllers.indexController().indexAction);
I think this approach allows for clearer seperation and also you can configure your controllers by passing perhaps a db connection in.
The xargs utility reads space, tab, newline and end-of-file delimited strings from the standard input and executes utility with the strings as arguments.
You want to avoid using space as a delimiter. This can be done by changing the delimiter for xargs. According to the manual:
-0 Change xargs to expect NUL (``\0'') characters as separators, instead of spaces and newlines. This is expected to be used in concert with the -print0 function in find(1).
Such as:
find . -name "*.mp3" -print0 | xargs -0 mplayer
To answer the question about playing the seventh mp3; it is simpler to run
mplayer "$(ls *.mp3 | sed -n 7p)"
You're saying you have this:
char array[20]; char string[100];
array[0]='1';
array[1]='7';
array[2]='8';
array[3]='.';
array[4]='9';
And you'd like to have this:
string[0]= "178.9"; // where it was stored 178.9 ....in position [0]
You can't have that. A char holds 1 character. That's it. A "string" in C is an array of characters followed by a sentinel character (NULL terminator).
Now if you want to copy the first x characters out of array
to string
you can do that with memcpy()
:
memcpy(string, array, x);
string[x] = '\0';
Use let instead of var in code :
for(let i=1;i<=5;i++){setTimeout(()=>{console.log(i)},1000);}
No, CSV doesn't specify any way of tagging comments - they will just be loaded by programs like Excel as additional cells containing text.
The closest you can manage (with CSV being imported into a specific application such as Excel) is to define a special way of tagging comments that Excel will ignore. For Excel, you can "hide" the comment (to a limited degree) by embedding it into a formula. For example, try importing the following csv file into Excel:
=N("This is a comment and will appear as a simple zero value in excel")
John, Doe, 24
You still end up with a cell in the spreadsheet that displays the number 0, but the comment is hidden.
Alternatively, you can hide the text by simply padding it out with spaces so that it isn't displayed in the visible part of cell:
This is a sort-of hidden comment!,
John, Doe, 24
Note that you need to follow the comment text with a comma so that Excel fills the following cell and thus hides any part of the text that doesn't fit in the cell.
Nasty hacks, which will only work with Excel, but they may suffice to make your output look a little bit tidier after importing.
That can be done by using some/every methods of Array and RegEx.
To check whether ALL of words from list(array) are present in the string:
const multiSearchAnd = (text, searchWords) => (
searchWords.every((el) => {
return text.match(new RegExp(el,"i"))
})
)
multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["cle", "hire"]) //returns false
multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
To check whether ANY of words from list(array) are present in the string:
const multiSearchOr = (text, searchWords) => (
searchWords.some((el) => {
return text.match(new RegExp(el,"i"))
})
)
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "zzzz"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "1111"]) //returns false
A number of things can cause session state to mysteriously disappear.
-
If you are using IIS 7 or 7.5, here are a few things to look for:
If you are using IIS 6, the same settings apply (for the most part but with different ways of getting to them), however getting them to log the recycles is more of a pain. Here is a link to a way to get IIS 6 to log AppPool recycle events:
-
If you are updating files on your web app, you should expect all session to be lost. That's just the nature of the beast. However, you might not expect it to happen multiple times. If you update 15 or more files (aspx, dll, etc), there is a likelyhood that you will have multiple restarts over a period of time as these pages are recompiled by users accessing the site. See these two links:
http://support.microsoft.com/kb/319947
Setting the numCompilesBeforeAppRestart to a higher number (or manually bouncing your AppPool) will eliminate this issue.
-
You can always handle Application_SessionStart and Application_SessionEnd to be notified when a session is created or ended. The HttpSessionState class also has an IsNewSession property you can check on any page request to determine if a new session is created for the active user.
-
Finally, if it's possible in your circumstance, I have used the SQL Server session mode with good success. It's not recommended if you are storing a large amount of data in it (every request loads and saves the full amount of data from SQL Server) and it can be a pain if you are putting custom objects in it (as they have to be serializable), but it has helped me in a shared hosting scenario where I couldn't configure my AppPool to not recycle couple hours. In my case, I stored limited information and it had no adverse performance effect. Add to this the fact that an existing user will reuse their SessionID by default and my users never noticed the fact that their in-memory Session was dropped by an AppPool recycle because all their state was stored in SQL Server.
A solution, can be:
with open("file", "r") as fd:
lines = fd.read().splitlines()
You get the list of lines without "\r\n" or "\n".
Or, use the classic way:
with open("file", "r") as fd:
for line in fd:
line = line.strip()
You read the file, line by line and drop the spaces and newlines.
If you only want to drop the newlines:
with open("file", "r") as fd:
for line in fd:
line = line.replace("\r", "").replace("\n", "")
Et voilà.
Note: The behavior of Python 3 is a little different. To mimic this behavior, use io.open
.
See the documentation of io.open.
So, you can use:
with io.open("file", "r", newline=None) as fd:
for line in fd:
line = line.replace("\n", "")
When the newline parameter is None
: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.
newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:
On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
You can use the Material Components Library and the MaterialButton
component.
Use the app:icon
and app:iconGravity="start"
attributes.
Something like:
<com.google.android.material.button.MaterialButton
style="@style/Widget.MaterialComponents.Button.Icon"
app:icon="@drawable/..."
app:iconGravity="start"
../>
You can use the opt(int)
method and use a classical for
loop.
Some other options:
<object type="application/pdf" data="filename.pdf" width="100%" height="100%">
</object>
<object type="application/pdf" data="#request.localhost#_includes/filename.pdf"
width="100%" height="100%">
<param name="src" value="#request.localhost#_includes/filename.pdf">
</object>
You can use input text with "list" attribute, which refers to the datalist of values.
<input type="text" name="city" list="cityname">_x000D_
<datalist id="cityname">_x000D_
<option value="Boston">_x000D_
<option value="Cambridge">_x000D_
</datalist>
_x000D_
This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist
There is more help available by reading the FindBoost.cmake
file itself. It is located in your 'Modules' directory.
A good start is to set(Boost_DEBUG 1)
- this will spit out a good deal of information about where boost is looking, what it's looking for, and may help explain why it can't find it.
It can also help you to figure out if it is picking up on your BOOST_ROOT
properly.
FindBoost.cmake
also sometimes has problems if the exact version of boost is not listed in the Available Versions variables. You can find more about this by reading FindBoost.cmake
.
Lastly, FindBoost.cmake
has had some bugs in the past. One thing you might try is to take a newer version of FindBoost.cmake
out of the latest version of CMake, and stick it into your project folder alongside CMakeLists.txt
- then even if you have an old version of boost, it will use the new version of FindBoost.cmake
that is in your project's folder.
Good luck.
open jquery-ui-*.js
find $.widget( "ui.accordion", {
find _eventHandler: function( event ) {
inside
change
var options = this.options, active = this.active, clicked = $( event.currentTarget ), clickedIsActive = clicked[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : clicked.next(), toHide = active.next(), eventData = {
oldHeader: active,
oldPanel: toHide,
newHeader: collapsing ? $() : clicked,
newPanel: toShow };
to
var options = this.options,
clicked = $( event.currentTarget),
clickedIsActive = clicked.next().attr('aria-expanded') == 'true',
collapsing = clickedIsActive && options.collapsible;
if (clickedIsActive == true) {
var toShow = $();
var toHide = clicked.next();
} else {
var toShow = clicked.next();
var toHide = $();
}
eventData = {
oldHeader: $(),
oldPanel: toHide,
newHeader: clicked,
newPanel: toShow
};
before active.removeClass( "ui-accordion-header-active ui-state-active" );
add if (typeof(active) !== 'undefined') {
and closing }
enjoy
With Python3x, you need to convert your string to raw bytes. You would have to encode the string as bytes. Over the network you need to send bytes and not characters. You are right that this would work for Python 2x since in Python 2x, socket.sendto on a socket takes a "plain" string and not bytes. Try this:
print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))
None of the other answers worked for me but closing all open tabs in Visual Studio appears to have solved the problem.
Actually, this is the proper way to get what you want, unless you can use MS SQL 2014 (which finally enables custom format strings for date times).
To get yyyymm
instead of yyyym
, you can use this little trick:
select
right('0000' + cast(datepart(year, getdate()) as varchar(4)), 4)
+ right('00' + cast(datepart(month, getdate()) as varchar(2)), 2)
It's faster and more reliable than gettings parts of convert(..., 112)
.
Regex with replaceAll.
public class Main
{
public static void main(final String[] argv)
{
String str;
str = "hello\r\njava\r\nbook";
str = str.replaceAll("(\\r|\\n)", "");
System.out.println(str);
}
}
If you only want to remove \r\n when they are pairs (the above code removes either \r or \n) do this instead:
str = str.replaceAll("\\r\\n", "");
Is this something you are going to be doing a lot? If so, you may want to consider a different data structure. Grep is going to search the entire array every time and for a large array could be quite costly. If speed is an issue then you may want to consider using a Hash instead.
In your example, the key would be the number and the value would be the count of elements of that number.
I'm using following markup and had encoutered the same problem:
<ul class="nav">
<li><a href="abc.html">abc</a></li>
<li><a href="def.html">def</a></li>
</ul>
Here I have used the following logic:
$(".nav > li").click(function(e){
if(e.target != this) return; // only continue if the target itself has been clicked
// this section only processes if the .nav > li itself is clicked.
alert("you clicked .nav > li, but not it's children");
});
In terms of the exact question, I can see that working as follows:
$(".example").click(function(e){
if(e.target != this) return; // only continue if the target itself has been clicked
$(".example").fadeOut("fast");
});
or of course the other way around:
$(".example").click(function(e){
if(e.target == this){ // only if the target itself has been clicked
$(".example").fadeOut("fast");
}
});
Hope that helps.
SELECT CAST(FLOOR(CAST(GETDATE() AS float)) as datetime)
or
SELECT CONVERT(datetime,FLOOR(CONVERT(float,GETDATE())))
find /folder -type f -mtime -90 | grep -E "(.txt|.php|.inc|.root|.gif)" | xargs ls -l > WWWlastActivity.log
Had the same issue recently. Check your .env
file and use equal sign not colon. Here's an example:
key=value
instead of:
key:value
The email in the profile can be obtained using extended permission but I Guess it's not possible to get the email used to login fb. In my app i wanted to display mulitple fb accounts of a user in a list, i wanted to show the login emails of fb accounts as a unique identifier of the respective accounts but i couldn't get it off from fb, all i got was the primary email in the user profile but in my case my login email and my primary email are different.
You can iterate over the index values if your dataframe has already been created.
df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
print name
print df.loc[name]
To set the value of the checkbox, you need to bind the v-model to a value. The checkbox will be checked if the value is truthy. In this case, you are iterating over modules
and each module
has a checked
property.
The following code will bind the checkbox with that property:
<input type="checkbox" v-model="module.checked" v-bind:id="module.id">
Notice that I removed v-bind:value="module.id"
. You shouldn't use v-model
and v-bind:value
on the same element. From the vue docs:
<input v-model="something">
is just syntactic sugar for:
<input v-bind:value="something" v-on:input="something = $event.target.value">
So, by using v-model
and v-bind:value
, you actually end up having v-bind:value
twice, which could lead to undefined behavior.
Depends in how you are hiding your div, diplay=none
is different of visibility=hidden
and the opacity=0
Visibility then use ...style.visibility='visible'
Display then use ...style.display='block'
(or others depends how
you setup ur css, inline, inline-block, flex...)
Opacity then use ...style.opacity='1';
If $a
is the array that's passed, $a[76][0]['id']
should give '76' and $a[76][1]['id']
should give '81', but I can't test as I don't have PHP installed on this machine.
you also can simply use
<script type="text/javascript">
var data = [];
@foreach (var r in Model.rows)
{
@:data.push([ @r.UnixTime * 1000, @r.Value ]);
}
</script>
note @:
This is a helpful website listing the mapping for the latest releases of Chrome -
Extending bp's answer, I wanted to show you what he meant by immutable types.
First, this is okay:
>>> class TestB():
... def __init__(self, attr=1):
... self.attr = attr
...
>>> a = TestB()
>>> b = TestB()
>>> a.attr = 2
>>> a.attr
2
>>> b.attr
1
However, this only works for immutable (unchangable) types. If the default value was mutable (meaning it can be replaced), this would happen instead:
>>> class Test():
... def __init__(self, attr=[]):
... self.attr = attr
...
>>> a = Test()
>>> b = Test()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[1]
>>>
Note that both a
and b
have a shared attribute. This is often unwanted.
This is the Pythonic way of defining default values for instance variables, when the type is mutable:
>>> class TestC():
... def __init__(self, attr=None):
... if attr is None:
... attr = []
... self.attr = attr
...
>>> a = TestC()
>>> b = TestC()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[]
The reason my first snippet of code works is because, with immutable types, Python creates a new instance of it whenever you want one. If you needed to add 1 to 1, Python makes a new 2 for you, because the old 1 cannot be changed. The reason is mostly for hashing, I believe.
Another simple way is to use a tuple:
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10];
// Access elements
console.log("First: " + x["0"] + " Second: " + x["1"]);
Output:
First: hello Second: 10
In Other ways to get difference between date;
import dateutil.parser
import datetime
timeDifference = current_date - dateutil.parser.parse(last_sent_date)
time_difference_in_minutes = (int(timeDifference.days) * 24 * 60) + int((timeDifference.seconds) / 60)
Thanks
Normal money conversions will preserve individual pennies:
SELECT convert(varchar(30), moneyfield, 1)
The last parameter decides what the output format looks like:
0 (default) No commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; for example, 4235.98.
1 Commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; for example, 3,510.92.
2 No commas every three digits to the left of the decimal point, and four digits to the right of the decimal point; for example, 4235.9819.
If you want to truncate the pennies, and count in pounds, you can use rounding to the nearest pound, floor to the lowest whole pound, or ceiling to round up the pounds:
SELECT convert(int, round(moneyfield, 0))
SELECT convert(int, floor(moneyfield))
SELECT convert(int, ceiling(moneyfield))
The main question was to remove the CR/LF. Using the replace and char functions works for me:
Select replace(replace(Name,char(10),''),char(13),'')
For Postgres or Oracle SQL, use the CHR function instead:
replace(replace(Name,CHR(10),''),CHR(13),'')
Here's how I did it:
Responsive jQuery UI Dialog ( and a fix for maxWidth bug )
Fixing the maxWidth & width: auto bug.
For testing how to insert the double quotes in MySQL using the terminal, you can use the following way:
TableName(Name,DString) - > Schema
insert into TableName values("Name","My QQDoubleQuotedStringQQ")
After inserting the value you can update the value in the database with double quotes or single quotes:
update table TableName replace(Dstring, "QQ", "\"")
If that's your whole string, then just try parsing it:
if (DateTime::createFromFormat('Y-m-d H:i:s', $myString) !== FALSE) {
// it's a date
}
I had some trouble with this - my EntityKey consists of three properties (PK with 3 columns) and I didn't want to check each of the columns because that would be ugly. I thought about a solution that works all time with all entities.
Another reason for this is I don't like to catch UpdateExceptions every time.
A little bit of Reflection is needed to get the values of the key properties.
The code is implemented as an extension to simplify the usage as:
context.EntityExists<MyEntityType>(item);
Have a look:
public static bool EntityExists<T>(this ObjectContext context, T entity)
where T : EntityObject
{
object value;
var entityKeyValues = new List<KeyValuePair<string, object>>();
var objectSet = context.CreateObjectSet<T>().EntitySet;
foreach (var member in objectSet.ElementType.KeyMembers)
{
var info = entity.GetType().GetProperty(member.Name);
var tempValue = info.GetValue(entity, null);
var pair = new KeyValuePair<string, object>(member.Name, tempValue);
entityKeyValues.Add(pair);
}
var key = new EntityKey(objectSet.EntityContainer.Name + "." + objectSet.Name, entityKeyValues);
if (context.TryGetObjectByKey(key, out value))
{
return value != null;
}
return false;
}
Another approach to solving this securely is to use the following module.
node_extra_ca_certs_mozilla_bundle
This module can work without any code modification by generating a PEM file that includes all root and intermediate certificates trusted by Mozilla. You can use the following environment variable (Works with Nodejs v7.3+),
To generate the PEM file to use with the above environment variable. You can install the module using:
npm install --save node_extra_ca_certs_mozilla_bundle
and then launch your node script with an environment variable.
NODE_EXTRA_CA_CERTS=node_modules/node_extra_ca_certs_mozilla_bundle/ca_bundle/ca_intermediate_root_bundle.pem node your_script.js
Other ways to use the generated PEM file are available at:
https://github.com/arvind-agarwal/node_extra_ca_certs_mozilla_bundle
NOTE: I am the author of the above module.
In case this page comes up in someones web search, as of Java 1.7 you can now use java.nio.charset.StandardCharsets to get access to constant definitions of standard charsets.
If you really want to use plain HTML (for whatever reason) and not the built-in HtmlHelper extensions, you can do it this way.
Instead of
<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
try using
<input id="Remember" name="Remember" type="checkbox" value="true" @(Model.Remember ? "checked" : "") />
Checkbox inputs in HTML work so that when they're checked, they send the value, and when they're not checked, they don't send anything at all (which will cause ASP.NET MVC to fallback to the default value of the field, false
). Also, the value of the checkbox in HTML can be anything not just true/false, so if you really wanted, you can even use a checkbox for a string field in your model.
If you use the built-in Html.RenderCheckbox
, it actually outputs two inputs: checkbox and a hidden field so that a false value is sent when the checkbox is unchecked (not just nothing). That may cause some unexpected situations, like this:
The singular form dtype
is used to check the data type for a single column. And the plural form dtypes
is for data frame which returns data types for all columns. Essentially:
For a single column:
dataframe.column.dtype
For all columns:
dataframe.dtypes
Example:
import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})
df.A.dtype
# dtype('int64')
df.B.dtype
# dtype('bool')
df.C.dtype
# dtype('O')
df.dtypes
#A int64
#B bool
#C object
#dtype: object
To solve this edit /etc/ssh/ssh_config and comment the following line 1
https://www.evilbox.ro/linux/solve-ssh_exchange_identification-connection-closed-by-remote-host/ for reference
here is what i did:
window.addEventListener('orientationchange', doOnOrientationChange);
function doOnOrientationChange()
{
if (screen.height > screen.width) {
console.log('portrait');
} else {
console.log('landscape');
}
}
If you are developing for Android, Color's method for this is rgb(int, int, int)
So you would do something like
myPaint.setColor(Color.rgb(int, int, int));
For retrieving the individual color values you can use the methods for doing so:
Color.red(int color)
Color.blue(int color)
Color.green(int color)
Refer to this document for more info
At the end of each switch case, just add the break
-statement to resolve this problem
switch (manu)
{
case manufacturers.Nokia:
_phanefact = new NokiaFactory();
break;
case manufacturers.Samsung:
_phanefact = new SamsungFactory();
break;
}
$.ajax({
type: "POST",
url: "url to hit on servelet",
data: JSON.stringify(json),
dataType: "json",
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
$('#info').html("Info has been added to the list successfully.<br>"+
"The Details are as follws : <br> Name : ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});
This error can also happen if you pass a key word argument for which one of the keys is similar (has same string name) to a positional argument.
>>> class Foo():
... def bar(self, bar, **kwargs):
... print(bar)
...
>>> kwgs = {"bar":"Barred", "jokes":"Another key word argument"}
>>> myfoo = Foo()
>>> myfoo.bar("fire", **kwgs)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() got multiple values for argument 'bar'
>>>
"fire" has been accepted into the 'bar' argument. And yet there is another 'bar' argument present in kwargs.
You would have to remove the keyword argument from the kwargs before passing it to the method.
I think you've misunderstood some python syntax, the following does two assignments:
In [11]: a = b = 1
In [12]: a
Out[12]: 1
In [13]: b
Out[13]: 1
So in your code it was as if you were doing:
sum = df['budget'] + df['actual'] # a Series
# and
df['variance'] = df['budget'] + df['actual'] # assigned to a column
The latter creates a new column for df:
In [21]: df
Out[21]:
cluster date budget actual
0 a 2014-01-01 00:00:00 11000 10000
1 a 2014-02-01 00:00:00 1200 1000
2 a 2014-03-01 00:00:00 200 100
3 b 2014-04-01 00:00:00 200 300
4 b 2014-05-01 00:00:00 400 450
5 c 2014-06-01 00:00:00 700 1000
6 c 2014-07-01 00:00:00 1200 1000
7 c 2014-08-01 00:00:00 200 100
8 c 2014-09-01 00:00:00 200 300
In [22]: df['variance'] = df['budget'] + df['actual']
In [23]: df
Out[23]:
cluster date budget actual variance
0 a 2014-01-01 00:00:00 11000 10000 21000
1 a 2014-02-01 00:00:00 1200 1000 2200
2 a 2014-03-01 00:00:00 200 100 300
3 b 2014-04-01 00:00:00 200 300 500
4 b 2014-05-01 00:00:00 400 450 850
5 c 2014-06-01 00:00:00 700 1000 1700
6 c 2014-07-01 00:00:00 1200 1000 2200
7 c 2014-08-01 00:00:00 200 100 300
8 c 2014-09-01 00:00:00 200 300 500
As an aside, you shouldn't use sum
as a variable name as the overrides the built-in sum function.
LIFO is the way browser parses CSS properties..If you are using Sass declare a variable called as
"$header-background: red;"
use it instead of directly assigning values like red or blue. When you want to override just reassign the value to
"$header-background:blue"
then
background-color:$header-background;
it should smoothly override. Using "!important" is not always the right choice..Its just a hotfix
The way you're doing it you're querying for the process twice. Also Lynn raises a good point about being nice first. I'd probably try something like the following:
# get Firefox process
$firefox = Get-Process firefox -ErrorAction SilentlyContinue
if ($firefox) {
# try gracefully first
$firefox.CloseMainWindow()
# kill after five seconds
Sleep 5
if (!$firefox.HasExited) {
$firefox | Stop-Process -Force
}
}
Remove-Variable firefox
Disable CONSTRAINT
ALTER TABLE [TableName] NOCHECK CONSTRAINT ALL;
Disable Index
ALTER INDEX ALL ON [TableName] DISABLE;
Rebuild Index
ALTER INDEX ALL ON [TableName] REBUILD;
Enable CONSTRAINT
ALTER TABLE [TableName] CHECK CONSTRAINT ALL;
Delete again
... in Powershell you can do something like this:
Get-Date (get-Date ((Get-Date) ) -format MM.yyyy)
... for the last month do this:
Get-Date (get-Date ((Get-Date).AddMonths(-1) ) -format MM.yyyy)
... or for custom Date do this:
Get-Date (get-Date ((Get-Date 12.01.2013) ) -format MM.yyyy)
Im sure there
s something like this possible ...
Gruß
You may use as following to get Height and Weight of an Numpy array:
int height = arr.shape[0]
int weight = arr.shape[1]
If your array has multiple dimensions, you can increase the index to access them.
This thread is quite old, but currently you can do this: much cleaner imho
SELECT *
FROM Sales.SalesOrderDetail
ORDER BY SalesOrderDetailID
OFFSET 20 ROWS
FETCH NEXT 10 ROWS ONLY;
GO
You can use Object.values():
The
Object.values()
method returns an array of a given object's own enumerable property values, in the same order as that provided by afor...in
loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
and then use the indexOf() method:
The
indexOf()
method returns the first index at which a given element can be found in the array, or -1 if it is not present.
For example:
Object.values(obj).indexOf("test`") >= 0
A more verbose example is below:
var obj = {_x000D_
"a": "test1",_x000D_
"b": "test2"_x000D_
}_x000D_
_x000D_
_x000D_
console.log(Object.values(obj).indexOf("test1")); // 0_x000D_
console.log(Object.values(obj).indexOf("test2")); // 1_x000D_
_x000D_
console.log(Object.values(obj).indexOf("test1") >= 0); // true_x000D_
console.log(Object.values(obj).indexOf("test2") >= 0); // true _x000D_
_x000D_
console.log(Object.values(obj).indexOf("test10")); // -1_x000D_
console.log(Object.values(obj).indexOf("test10") >= 0); // false
_x000D_
Download from Instant Client for Microsoft Windows (x64) and extract the files below to "c:\oracle":
instantclient-basic-windows.x64-12.1.0.2.0.zip
instantclient-sqlplus-windows.x64-12.1.0.2.0.zip
instantclient-sdk-windows.x64-12.1.0.2.0.zip This will create the following folder "C:\Oracle\instantclient_12_1".
Finally, add the "C:\Oracle\instantclient_12_1" folder to the PATH enviroment variable, placing it on the leftmost place.
Then Restart your server.
In IIS Manager, I added a binding to the site specifying the IP address. Previously, all my bindings were host names.
If you are using C99 just include stdint.h
. BTW, the 64bit types are there iff the processor supports them.
It is working you have to check attr after assigning value
$('#amount').attr( 'datamin','1000');
alert($('#amount').attr( 'datamin'));?
You should use a StringBuilder:
StringBuilder contentBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader("mypage.html"));
String str;
while ((str = in.readLine()) != null) {
contentBuilder.append(str);
}
in.close();
} catch (IOException e) {
}
String content = contentBuilder.toString();
I'd recommend using this plugin: https://github.com/chartjs/chartjs-plugin-datalabels
Labels can be added to your charts simply by importing the plugin to the js file e.g.:
import 'chartjs-plugin-datalabels'
And can be fine tuned using these docs: https://chartjs-plugin-datalabels.netlify.com/options.html
Alternatively, if you want to export a copy without modifying the working copy, you can use rsync:
rsync -a --exclude .svn path/to/working/copy path/to/export
As mentioned array.find()
is not supported in IE.
However you can read about a Polyfill here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find#Polyfill
This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can polyfill Array.prototype.find with the following snippet:
Code:
// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
value: function(predicate) {
// 1. Let O be ? ToObject(this value).
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If IsCallable(predicate) is false, throw a TypeError exception.
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
// 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
var thisArg = arguments[1];
// 5. Let k be 0.
var k = 0;
// 6. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kValue be ? Get(O, Pk).
// c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
// d. If testResult is true, return kValue.
var kValue = o[k];
if (predicate.call(thisArg, kValue, k, o)) {
return kValue;
}
// e. Increase k by 1.
k++;
}
// 7. Return undefined.
return undefined;
}
});
}
How about:
foreach(var s in listBox1.Items.ToArray())
{
MessageBox.Show(s);
//do stuff with (s);
listBox1.Items.Remove(s);
}
The ToArray makes a copy of the list, so you don't need to worry about it changing the list while you are processing it.
As of ES5 (when this answer was given):
If you want an empty array of undefined
elements, you could simply do
var whatever = new Array(5);
this would give you
[undefined, undefined, undefined, undefined, undefined]
and then if you wanted it to be filled with empty strings, you could do
whatever.fill('');
which would give you
["", "", "", "", ""]
And if you want to do it in one line:
var whatever = Array(5).fill('');
Many distinctions have already been mentioned. Here is one more:
Running npm install
at the top of your source directory will run various scripts: prepublish
, preinstall
, install
, postinstall
. Depending on what these scripts do, a npm install
may do considerably more work than just installing dependencies.
I've just had a use case where prepublish
would call make
and the Makefile
was designed to fetch dependencies if the package.json
got updated. Calling npm install
from within the Makefile
would have lead to an infinite recursion, while calling npm update
worked just fine, installing all dependencies so that the build could proceed even if make
was called directly.
You should be careful if the strings in a
or str
gets longer. The straightforward solutions take O(S*(A^2)), where S
is the length of str
and A is the sum of the lenghts of all strings in a
. For a faster solution, look at Aho-Corasick algorithm for string matching, which runs in linear time O(S+A).
You would use the read.csv
function; for example:
dat = read.csv("spam.csv", header = TRUE)
You can also reference this tutorial for more details.
Note: make sure the .csv
file to read is in your working directory (using getwd()
) or specify the right path to file. If you want, you can set the current directory using setwd
.
Try using
DateTime.ParseExact(
txtPaymentSummaryBeginDate.Text.Trim(),
"MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture
);
It throws an exception if the input string is not in proper format, so in the catch
section you can return false;
mysql -u root -P 4406 -h localhost --protocol=tcp -p
Remember to change the user, port and host so that it matches your configurations. The -p flag is required if your database user is configured with a password
This saves the absolute path of the current working directory to the variable cwd
:
cwd=$(pwd)
In your case you can just do:
export PATH=$PATH:$(pwd)+somethingelse
This way it worked for me:
var noticias = from n in db.Noticias.Take(6)
where n.Atv == 1
orderby n.DatHorLan descending
select n;
I answer this topic just in case someone read it and is interested on the result. It is possible to view a video element (video html5 tag) within a WebView, but I must say I had to deal with it for few days. These are the steps I had to follow so far:
-Find a properly encoded video
-When initializing the WebView, set the JavaScript, Plug-ins the WebViewClient and the WebChromeClient.
url = new String("http://broken-links.com/tests/video/"); mWebView = (WebView) findViewById(R.id.webview); mWebView.setWebChromeClient(chromeClient); mWebView.setWebViewClient(wvClient); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setPluginState(PluginState.ON); mWebView.loadUrl(url);
-Handle the onShowCustomView in the WebChromeClient object.
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
if (view instanceof FrameLayout){
FrameLayout frame = (FrameLayout) view;
if (frame.getFocusedChild() instanceof VideoView){
VideoView video = (VideoView) frame.getFocusedChild();
frame.removeView(video);
a.setContentView(video);
video.setOnCompletionListener(this);
video.setOnErrorListener(this);
video.start();
}
}
}
-Handle the onCompletion and the onError events for the video, in order to get back to the web view.
public void onCompletion(MediaPlayer mp) {
Log.d(TAG, "Video completo");
a.setContentView(R.layout.main);
WebView wb = (WebView) a.findViewById(R.id.webview);
a.initWebView();
}
But now I should say there are still an important issue. I can play it only once. The second time I click on the video dispatcher (either the poster or some play button), it does nothing.
I would also like the video to play inside the WebView frame, instead of opening the Media Player window, but this is for me a secondary issue.
I hope it helps somebody, and I would also thank any comment or suggestion.
Saludos, terrícolas.
I had a similar issue when trying to migrate a Drupal website from one local host to another. From Mac running XAMMP to Windows running WAMP.
This was the error message I kept getting when trying to access the pages of the website.
PDOException: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it.
in drupal_get_installed_schema_version() (line 155 of C:\wamp\www\chia\includes\install.inc).
In settings.php, I've changed everything correctly, database name, user and password.
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => 'mydatabasename',
'username' => 'mydbusername',
'password' => 'mydbpass',
'host' => 'localhost',
'port' => '8889',
'driver' => 'mysql',
'prefix' => '',
),
),
);
After a couple of hours of mindless google searching I've changed the port to a empty value:
'port' => '',
And after that the site loaded properly.
I tried the above options but none of them is working for me. Here is the solution
if(window.event)
{
if(window.event.clientX < 40 && window.event.clientY < 0)
{
alert("Browser back button is clicked...");
}
else
{
alert("Browser refresh button is clicked...");
}
}
Refer this link http://www.codeproject.com/Articles/696526/Solution-to-Browser-Back-Button-Click-Event-Handli for more details
The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.
Top answer with most upvotes isn't wrong but still the opposite of what I would post. I say it will totally work to start an exe file and you can do this in the context of any user. Logically you just can't have any user interface or ask for user input...
Here is my advice:
Example to start e.g. plink.exe. You could even listen to the output:
var psi = new ProcessStartInfo()
{
FileName = "./Client/plink.exe", //path to your *.exe
Arguments = "-telnet -P 23 127.0.0.1 -l myUsername -raw", //arguments
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true //no window, you can't show it anyway
};
var p = Process.Start(psi);
I took LocalSystem account which is default and more than Local Service. It worked fine without having to enter login information of a specific user. I didn't even tick the checkbox "Allow service to interact with desktop" which you could if you need higher permissions.
Lastly I just want to say how funny it is that the top answer says quite the opposite of my answer and still both of us are right it's just how you interpret the question :-D. If you now say but you can't with the windows service project type - You CAN but I had this before and installation was sketchy and it was maybe kind of an unintentional hack until I found NSSM.
If the run method ends, the thread will end.
If you use a loop, a proper way is like following:
// In your imlemented Runnable class:
private volatile boolean running = true;
public void run()
{
while (running)
{
...
}
}
public void stopRunning()
{
running = false;
}
Of course returning is the best way.
You can also initialize data members at the point you declare them:
class another_example{
public:
another_example();
~another_example();
private:
int m_iInteger=10;
double m_dDouble=10.765;
};
I use this form pretty much exclusively, although I have read some people consider it 'bad form', perhaps because it was only recently introduced - I think in C++11. To me it is more logical.
Another useful facet to the new rules is how to initialize data-members that are themselves classes. For instance suppose that CDynamicString
is a class that encapsulates string handling. It has a constructor that allows you specify its initial value CDynamicString(wchat_t* pstrInitialString)
. You might very well use this class as a data member inside another class - say a class that encapsulates a windows registry value which in this case stores a postal address. To 'hard code' the registry key name to which this writes you use braces:
class Registry_Entry{
public:
Registry_Entry();
~Registry_Entry();
Commit();//Writes data to registry.
Retrieve();//Reads data from registry;
private:
CDynamicString m_cKeyName{L"Postal Address"};
CDynamicString m_cAddress;
};
Note the second string class which holds the actual postal address does not have an initializer so its default constructor will be called on creation - perhaps automatically setting it to a blank string.
Why not use a regular expression ?
public static boolean toBoolean( String target )
{
if( target == null ) return false;
return target.matches( "(?i:^(1|true|yes|oui|vrai|y)$)" );
}
Use str.join
:
>>> tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
>>> ''.join(tup)
'abcdgxre'
>>>
>>> help(str.join)
Help on method_descriptor:
join(...)
S.join(iterable) -> str
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
>>>
Try the following steps:
1) Open project.json
file and Remove all Microsoft.EntityFrameworkCore.Tools references from dependencies and tools sections.
2) Close Package Manager Console (PMC) and restart Visual Studio
3) Add under dependencies section:
"Microsoft.EntityFrameworkCore.Tools": {
"version": "1.0.0-preview2-final",
"type": "build"
}
4) Add under tools section
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
5) Restart again Visual Studio 2015
6) Open the PMC and type
Add-Migration $Your_First_Migration_Name$
This happen because the PMC recognize the tools when Visual Studio is starting.
catch (WhateverException e) {
throw e;
}
will simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.
For me, if I want to interact with the hidden div without seeing it disappear each time I leave the triggering element (a in that case) I must add:
div:hover {
display: block;
}
var year1 = moment().format('YYYY');_x000D_
var year2 = moment().year();_x000D_
_x000D_
console.log('using format("YYYY") : ',year1);_x000D_
console.log('using year(): ',year2);_x000D_
_x000D_
// using javascript _x000D_
_x000D_
var year3 = new Date().getFullYear();_x000D_
console.log('using javascript :',year3);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
There is an easy way, just remove the symbolic link from "/usr/bin". It will work.
This is how it worked for me.
Object
var my_object ={"Super Hero":["Iron Man", "Super Man"]};
Set
Encode the stringified object with encodeURIComponent() and set as attribute:
var data_str = encodeURIComponent(JSON.stringify(my_object));
$("div#mydiv").attr("data-hero",data-str);
Get
To get the value as an object, parse the decoded, with decodeURIComponent(), attribute value:
var data_str = $("div#mydiv").attr("data-hero");
var my_object = JSON.parse(decodeURIComponent(data_str));
It should be noted that releasing an alpha app for the first time may take up to a few hours before an opt-in link is available and invitations are sent out to the email addresses in your testers list.
From Google support:
After publishing an alpha/beta app for the first time, it may take a few hours for your test link to be available to testers. If you publish additional changes, they may take several hours to be available for testers. [source]
You may want to wait until you have an initial opt-in link before publishing more changes to the app because doing so is likely to increase your wait time for receiving your tester link; or, may lead to your testers testing with the incorrect version.
Hope that clears things up for anyone confused about why they don't have an opt-in link as depicted in screenshots in this SO thread!
If you are in Android Studio Open Terminal
adb kill-server
press enter and again
adb start-server
press enter
Otherwise
Open Command prompt and got android
sdk>platform-tools> adb kill-server
press enter
and again
adb start-server
press enter
@Ignatius most excellent answer, updated to work with v2.0.7 of MarkerClustererPlus.
Add a prototype click method in the MarkerClusterer class, like so - we will override this later in the map initialize() function:
// BEGIN MODIFICATION (around line 715)
MarkerClusterer.prototype.onClick = function() {
return true;
};
// END MODIFICATION
In the ClusterIcon class, add the following code AFTER the click/clusterclick trigger:
// EXISTING CODE (around line 143)
google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name
// BEGIN MODIFICATION
var zoom = mc.getMap().getZoom();
// Trying to pull this dynamically made the more zoomed in clusters not render
// when then kind of made this useless. -NNC @ BNB
// var maxZoom = mc.getMaxZoom();
var maxZoom = 15;
// if we have reached the maxZoom and there is more than 1 marker in this cluster
// use our onClick method to popup a list of options
if (zoom >= maxZoom && cClusterIcon.cluster_.markers_.length > 1) {
return mc.onClick(cClusterIcon);
}
// END MODIFICATION
Then, in your initialize() function where you initialize the map and declare your MarkerClusterer object:
markerCluster = new MarkerClusterer(map, markers);
// onClick OVERRIDE
markerCluster.onClick = function(clickedClusterIcon) {
return multiChoice(clickedClusterIcon.cluster_);
}
Where multiChoice() is YOUR (yet to be written) function to popup an InfoWindow with a list of options to select from. Note that the markerClusterer object is passed to your function, because you will need this to determine how many markers there are in that cluster. For example:
function multiChoice(clickedCluster) {
if (clickedCluster.getMarkers().length > 1)
{
// var markers = clickedCluster.getMarkers();
// do something creative!
return false;
}
return true;
};
You can do the HTML parsing but it is not at all recommended instead ask the website owners to provide web services then you can parse that information.
I got the same problem and this is how i solved. :
return car.GetType().GetProperty(propertyName).GetValue(car, null);
A tad more generic copy/paste function for your project.
sumjq = function(selector) {
var sum = 0;
$(selector).each(function() {
sum += Number($(this).text());
});
return sum;
}
console.log(sumjq('.price'));
>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'
You have at least three options. I have presented them in order of usage preference.
Method 1 - You can use the SC tool (Sc.exe) included in the Resource Kit. (included with Windows 7/8)
Open a Command Prompt and enter
sc delete <service-name>
Tool help snippet follows:
DESCRIPTION:
SC is a command line program used for communicating with the
NT Service Controller and services.
delete----------Deletes a service (from the registry).
Method 2 - use delserv
Download and use delserv command line utility. This is a legacy tool developed for Windows 2000. In current Window XP boxes this was superseded by sc described in method 1.
Method 3 - manually delete registry entries (Note that this backfires in Windows 7/8)
Windows services are registered under the following registry key.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
Search for the sub-key with the service name under referred key and delete it. (and you might need to restart to remove completely the service from the Services list)
do {
stuff()
} while (condition())
->
while True:
stuff()
if not condition():
break
You can do a function:
def do_while(stuff, condition):
while condition(stuff()):
pass
But 1) It's ugly. 2) Condition should be a function with one parameter, supposed to be filled by stuff (it's the only reason not to use the classic while loop.)
If you're not using a remote repository (like artifactory), use plain old:
mvn clean install
Pretty old topic but AFAIK, if you run your own repository (eg: with artifactory) to share jar among your team(s), you might want to use
mvn clean deploy
instead.
This way, your continuous integration server can be sure that all dependencies are correctly pushed into your remote repository. If you missed one, mvn will not be able to find it into your CI local m2 repository.
To set a title for a button in Xcode using swift - 04: first create a method called setTitle with parameter title and UIController state like below ;
func setTitle(_ title : String?, for state : UIControl.State) {
}
and recall this method in your button action method like ;
yourButtonName.setTitle("String", for: .state)
See:
Code:
var strDate = "03.09.1979";
var dateParts = strDate.split(".");
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
The issue in my case is because I have children route with same path with the parent :
const routes: Routes = [
{
path: '',
component: HomeComponent,
children: [
{ path: '', redirectTo: 'home', pathMatch: 'prefix' },
{ path: 'home', loadChildren: './home.module#HomeModule' },
]
}
];
So I had to remove the line of the children route
const routes: Routes = [
{
path: '',
component: HomeComponent,
children: [
{ path: 'home', loadChildren: './home.module#HomeModule' },
]
}
];
Try This Code.
.card {_x000D_
_x000D_
width: 200px;_x000D_
_x000D_
height: 195px;_x000D_
_x000D_
position: relative;_x000D_
_x000D_
display: inline-block;_x000D_
_x000D_
}_x000D_
_x000D_
.card .img-top {_x000D_
_x000D_
display: none;_x000D_
_x000D_
position: absolute;_x000D_
_x000D_
top: 0;_x000D_
_x000D_
left: 0;_x000D_
_x000D_
z-index: 99;_x000D_
width:200px;_x000D_
}_x000D_
_x000D_
.card:hover .img-top {_x000D_
_x000D_
display: inline;_x000D_
_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
<title>Image Change on Hover with CSS</title>_x000D_
_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<div class="card">_x000D_
_x000D_
<img src="http://www.dhresource.com/200x200s/f2-albu-g5-M00-EC-97-rBVaJFkAobCAHD9XAADvz9DDocA266.jpg/diy-wall-stickers-home-decor-nature-colorful.jpg" alt="Card Back" style="width:200px">_x000D_
_x000D_
<img src="https://s-media-cache-ak0.pinimg.com/236x/31/17/98/3117987a0be0a7d8976869aabf54d2d7.jpg" class="img-top" alt="Card Front">_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Depending on your table type, locking will perform differently, but so will a SELECT count. For MyISAM tables a simple SELECT count(*) FROM table should not lock the table since it accesses meta data to pull the record count. Innodb will take longer since it has to grab the table in a snapshot to count the records, but it shouldn't cause locking.
You should at least have concurrent_insert set to 1 (default). Then, if there are no "gaps" in the data file for the table to fill, inserts will be appended to the file and SELECT and INSERTs can happen simultaneously with MyISAM tables. Note that deleting a record puts a "gap" in the data file which will attempt to be filled with future inserts and updates.
If you rarely delete records, then you can set concurrent_insert equal to 2, and inserts will always be added to the end of the data file. Then selects and inserts can happen simultaneously, but your data file will never get smaller, no matter how many records you delete (except all records).
The bottom line, if you have a lot of updates, inserts and selects on a table, you should make it InnoDB. You can freely mix table types in a system though.
Try one of the following, depending on your image format:
UIImageJPEGRepresentation
Returns the data for the specified image in JPEG format.
NSData * UIImageJPEGRepresentation (
UIImage *image,
CGFloat compressionQuality
);
UIImagePNGRepresentation
Returns the data for the specified image in PNG format
NSData * UIImagePNGRepresentation (
UIImage *image
);
EDIT:
if you want to access the raw bytes that make up the UIImage, you could use this approach:
CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
const uint8_t* bytes = [data bytes];
This will give you the low-level representation of the image RGB pixels.
(Omit the CFBridgingRelease
bit if you are not using ARC).
Series.apply(func, convert_dtype=True, args=(), **kwds)
args : tuple
x = my_series.apply(my_function, args = (arg1,))
(new FileInfo(filePath)).Directory.Create()
Before writing to the file.
System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);
pickling is recursive, not sequential. Thus, to pickle a list, pickle
will start to pickle the containing list, then pickle the first element… diving into the first element and pickling dependencies and sub-elements until the first element is serialized. Then moves on to the next element of the list, and so on, until it finally finishes the list and finishes serializing the enclosing list. In short, it's hard to treat a recursive pickle as sequential, except for some special cases. It's better to use a smarter pattern on your dump
, if you want to load
in a special way.
The most common pickle, it to pickle everything with a single dump
to a file -- but then you have to load
everything at once with a single load
. However, if you open a file handle and do multiple dump
calls (e.g. one for each element of the list, or a tuple of selected elements), then your load
will mirror that… you open the file handle and do multiple load
calls until you have all the list elements and can reconstruct the list. It's still not easy to selectively load
only certain list elements, however. To do that, you'd probably have to store your list elements as a dict
(with the index of the element or chunk as the key) using a package like klepto
, which can break up a pickled dict
into several files transparently, and enables easy loading of specific elements.
On mac, press Command + R
or got to Database
-> Reverse Engineer
and keep selecting your requirements and continue
You want border-spacing
:
<table style="border-spacing: 10px;">
Or in a CSS block somewhere:
table {
border-spacing: 10px;
}
See quirksmode on border-spacing
. Be aware that border-spacing
does not work on IE7 and below.
For Me I just wanted to see the error in my VBA application so in the function I created the below code..
Function Database_FileRpt
'-------------------------
On Error GoTo CleanFail
'-------------------------
'
' Create_DailyReport_Action and code
CleanFail:
'*************************************
MsgBox "********************" _
& vbCrLf & "Err.Number: " & Err.Number _
& vbCrLf & "Err.Description: " & Err.Description _
& vbCrLf & "Err.Source: " & Err.Source _
& vbCrLf & "********************" _
& vbCrLf & "...Exiting VBA Function: Database_FileRpt" _
& vbCrLf & "...Excel VBA Program Reset." _
, , "VBA Error Exception Raised!"
*************************************
' Note that the next line will reset the error object to 0, the variables
above are used to remember the values
' so that the same error can be re-raised
Err.Clear
' *************************************
Resume CleanExit
CleanExit:
'cleanup code , if any, goes here. runs regardless of error state.
Exit Function ' SUB or Function
End Function ' end of Database_FileRpt
' ------------------
I usually do it using Seaborn which is built on top of matplotlib
import seaborn as sns
iris = sns.load_dataset('iris')
sns.scatterplot(x='sepal_length', y='sepal_width',
hue='species', data=iris);
It says you don't have a local grunt
so try:
npm install grunt
(without the -g
it's a local grunt
)
Though not directly related, make sure you have Gruntfile.js
in your current folder.
The Global Assembly Cache (GAC) is a folder in Windows directory to store the .NET assemblies that are specifically designated to be shared by all applications executed on a system. Assemblies can be shared among multiple applications on the machine by registering them in global Assembly cache(GAC). GAC is a machine wide a local cache of assemblies maintained by the .NET Framework.
Since there is no native way to do this ,Here is less intrusive solution i found (dont add any 'old' prototype methods):
var ListenerTracker=new function(){
var is_active=false;
// listener tracking datas
var _elements_ =[];
var _listeners_ =[];
this.init=function(){
if(!is_active){//avoid duplicate call
intercep_events_listeners();
}
is_active=true;
};
// register individual element an returns its corresponding listeners
var register_element=function(element){
if(_elements_.indexOf(element)==-1){
// NB : split by useCapture to make listener easier to find when removing
var elt_listeners=[{/*useCapture=false*/},{/*useCapture=true*/}];
_elements_.push(element);
_listeners_.push(elt_listeners);
}
return _listeners_[_elements_.indexOf(element)];
};
var intercep_events_listeners = function(){
// backup overrided methods
var _super_={
"addEventListener" : HTMLElement.prototype.addEventListener,
"removeEventListener" : HTMLElement.prototype.removeEventListener
};
Element.prototype["addEventListener"]=function(type, listener, useCapture){
var listeners=register_element(this);
// add event before to avoid registering if an error is thrown
_super_["addEventListener"].apply(this,arguments);
// adapt to 'elt_listeners' index
useCapture=useCapture?1:0;
if(!listeners[useCapture][type])listeners[useCapture][type]=[];
listeners[useCapture][type].push(listener);
};
Element.prototype["removeEventListener"]=function(type, listener, useCapture){
var listeners=register_element(this);
// add event before to avoid registering if an error is thrown
_super_["removeEventListener"].apply(this,arguments);
// adapt to 'elt_listeners' index
useCapture=useCapture?1:0;
if(!listeners[useCapture][type])return;
var lid = listeners[useCapture][type].indexOf(listener);
if(lid>-1)listeners[useCapture][type].splice(lid,1);
};
Element.prototype["getEventListeners"]=function(type){
var listeners=register_element(this);
// convert to listener datas list
var result=[];
for(var useCapture=0,list;list=listeners[useCapture];useCapture++){
if(typeof(type)=="string"){// filtered by type
if(list[type]){
for(var id in list[type]){
result.push({"type":type,"listener":list[type][id],"useCapture":!!useCapture});
}
}
}else{// all
for(var _type in list){
for(var id in list[_type]){
result.push({"type":_type,"listener":list[_type][id],"useCapture":!!useCapture});
}
}
}
}
return result;
};
};
}();
ListenerTracker.init();