If you need it to work on both Mac and Windows, you can use QueryTables:
With ActiveSheet.QueryTables.Add(Connection:="URL;http://carbon.brighterplanet.com/flights.txt", Destination:=Range("A2"))
.PostText = "origin_airport=MSN&destination_airport=ORD"
.RefreshStyle = xlOverwriteCells
.SaveData = True
.Refresh
End With
Notes:
For more details, you can see my full summary about "using web services from Excel."
The quick and dirty way, you can view the available environment variables from the below link.
http://localhost:8080/env-vars.html/
Just replace localhost
with your Jenkins hostname, if its different
Since it is only a warning you can suppress it. Go to your XML's Graphical Layout and do this:
Click on the right top corner red button
Select "Disable Issue Type" (for example)
Here's one site that will format your code and spit out html, and it even includes inline styles for syntax coloring. Might not work for all of your needs, but is a good start. I believe he has made the source available if you want to extend it:
In addition to the accepted answer, if you are using Android Studio you can
Android Device Monitor
,Devices
tab on the left,File Explorer
tab on the right,Pull a file from the device
button to save it to your local file systemI think the fast and easy way is
Object.entries(event).forEach(k => {
console.log("properties ... ", k[0], k[1]); });
just check the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
Consider UTF-8. In UTF-8 Unicode code points are built from one or more bytes. A class encapsulating a UTF-8 byte array can implement the CharSequence interface but is most decidedly not a String. Certainly you can't pass a UTF-8 byte array where a String is expected but you certainly can pass a UTF-8 wrapper class that implements CharSequence when the contract is relaxed to allow a CharSequence. On my project, I am developing a class called CBTF8Field (Compressed Binary Transfer Format - Eight Bit) to provide data compression for xml and am looking to use the CharSequence interface to implement conversions from CBTF8 byte arrays to/from character arrays (UTF-16) and byte arrays (UTF-8).
The reason I came here was to get a complete understanding of the subsequence contract.
from s in context.shift
where !context.employeeshift.Any(es=>(es.shiftid==s.shiftid)&&(es.empid==57))
select s;
Hope this helps
Change:
data: JSON.stringify({ model: source })
To:
data: {model: JSON.stringify(source)}
And in your controller you do this:
public void PartSourceAPI(string model)
{
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
var result = js.Deserialize<PartSourceModel>(model);
}
If the url you use in jquery is /api/PartSourceAPI
then the controller name must be api
and the action(method) should be PartSourceAPI
You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-
(untested code)
Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")
' now you can manipulate the data in the workbook anyway you want, e.g. '
Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value
Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False
' etc '
Call wbk.Close(False)
Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.
You check if it's null
in C# like this:
if(MyObject != null) {
//do something
}
If you want to check against default (tough to understand the question on the info given) check:
if(MyObject != default(MyObject)) {
//do something
}
For windows: Follow these steps-
cd-to-home
from target
(b) Type folder path you want to start with git in "Start in".This worked for me:)
Set the Dropdown arrow image to spinner like this :
<Spinner
android:id="@+id/Exam_Course"
android:layout_width="320dp"
android:background="@drawable/spinner_bg"
android:layout_height="wrap_content"/>
Here android:background="@drawable/spinner_bg" the spinner_bg is the Dropdown arrow image.
You could write a User Defined Function that returns the min date value like this:
select cast(-53690 as datetime)
Then use that function in your scripts, and if you ever need to change it, there is only one place to do that.
Alternately, you could use this query if you prefer it for better readability:
select cast('1753-1-1' as datetime)
Example Function
create function dbo.DateTimeMinValue()
returns datetime as
begin
return (select cast(-53690 as datetime))
end
Usage
select dbo.DateTimeMinValue() as DateTimeMinValue
DateTimeMinValue
-----------------------
1753-01-01 00:00:00.000
Invalid login/password could be also related to issues in your DNS server - that's what happened to me and cost me good 5 hours of my life. See if you can specify ip address instead on domain name.
This is flask.jsonify()
def jsonify(*args, **kwargs):
if __debug__:
_assert_have_json()
return current_app.response_class(json.dumps(dict(*args, **kwargs),
indent=None if request.is_xhr else 2), mimetype='application/json')
The json
module used is either simplejson
or json
in that order. current_app
is a reference to the Flask()
object i.e. your application. response_class()
is a reference to the Response()
class.
the perfect solution is to Using UICollectionViewDelegateFlowLayout but you can easily so calculate the cell width and divided on the wanted number of columns you want
the tricky is to make the width with no fraction
(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat screenWidth = self.view.frame.size.width;
CGFloat marginWidth = (screenWidth - collectionView.frame.size.width);
CGFloat cellWith = (collectionView.frame.size.width - marginWidth )/3;
cellWith= floorf(cellWith);
CGSize retval = CGSizeMake(cellWith,cellWith);
return retval;}
convert_to_array = function (sentence) {
return sentence.trim().split(" ");
};
let ages = convert_to_array ("I'm a programmer in javascript writing script");
function confirmEnding(string) {
let target = "ipt";
return (string.substr(-target.length) === target) ? true : false;
}
function mySearchResult() {
return ages.filter(confirmEnding);
}
mySearchResult();
you could check like this and return an array of the matched words using filter
Your Print method likely needs to wait for the continuation to finish (ContinueWith returns a task which you can wait on). Otherwise the second ReadAsStringAsync finishes, the method returns (before result is assigned in the continuation). Same problem exists in your send method. Both need to wait on the continuation to consistently get the results you want. Similar to below
private static string Send(int id)
{
Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
string result = string.Empty;
Task continuation = responseTask.ContinueWith(x => result = Print(x));
continuation.Wait();
return result;
}
private static string Print(Task<HttpResponseMessage> httpTask)
{
Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
string result = string.Empty;
Task continuation = task.ContinueWith(t =>
{
Console.WriteLine("Result: " + t.Result);
result = t.Result;
});
continuation.Wait();
return result;
}
import java.util.*;
import java.lang.*;
import java.io.*;
class hari
{
public static void main (String[] args) throws Exception
{ Scanner s=new Scanner(System.in);
int i=0;
int b=0;
HashSet<Integer> h=new HashSet<Integer>();
try{
for(i=0;i<1000;i++)
{ b=s.nextInt();
h.add(b);
}
}
catch(Exception e){
System.out.println(h+","+h.size());
}
}}
first select database : USE db_name
then creat table:CREATE TABLE tb_name ( id int, name varchar(255), salary int, city varchar(255) );
this for mysql 5.5 version syntax
I wrote a custom classloader, from which it is possible to unload individual classes without GCing the classloader. Jar Class Loader
Recursively add subfolders,
for i in `find . -name "*.java" -type f`; do
echo "$i"
done
When creating a generator from a mutable object (like a list) be aware that the generator will get evaluated on the state of the list at time of using the generator, not at time of the creation of the generator:
>>> mylist = ["a", "b", "c"]
>>> gen = (elem + "1" for elem in mylist)
>>> mylist.clear()
>>> for x in gen: print (x)
# nothing
If there is any chance of your list getting modified (or a mutable object inside that list) but you need the state at creation of the generator you need to use a list comprehension instead.
If you just need to set the value of a dropdown then the best way is
$("#ID").val("2");
If You have to trigger any script after updating the dropdown value like If you set any onChange event on the dropdown and you want to run this after update the dropdown than You need to use like this
$("#ID").val("2").change();
Neither of them worked for me for some reason.
I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.
And finally this worked for me.
cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
connect.commit()
Your observation is correct. This behavior is happening due to the reuse of cells. But you dont have to do any thing with the prepareForReuse. Instead do your check in cellForItem and set the properties accordingly. Some thing like..
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cvCell" forIndexPath:indexPath];
if (cell.selected) {
cell.backgroundColor = [UIColor blueColor]; // highlight selection
}
else
{
cell.backgroundColor = [UIColor redColor]; // Default color
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
datasetCell.backgroundColor = [UIColor blueColor]; // highlight selection
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
datasetCell.backgroundColor = [UIColor redColor]; // Default color
}
Figure sizes are specified in inches and can be included as a global option of the document output format. For example:
---
title: "My Document"
output:
html_document:
fig_width: 6
fig_height: 4
---
And the plot's size in the graphic device can be increased at the chunk level:
```{r, fig.width=14, fig.height=12} #Expand the plot width to 14 inches
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You can also use the out.width
and out.height
arguments to directly define the size of the plot in the output file:
```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You could make an array the same size as the ArrayList
and then make an iterated for loop to index the items and insert them into the array.
To include column names to your csv file you can do the following:
sqlite> .headers on
sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout
To verify the changes that you have made you can run this command:
sqlite> .show
Output:
echo: off
explain: off
headers: on
mode: csv
nullvalue: ""
output: stdout
separator: "|"
stats: off
width: 22 18
Try psrinfo to find the processor type and the number of physical processors installed on the system.
Logical Processing Order of the SELECT statement
The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.
- FROM
- ON
- JOIN
- WHERE
- GROUP BY
- WITH CUBE or WITH ROLLUP
- HAVING
- SELECT
- DISTINCT
- ORDER BY
- TOP
Source: http://msdn.microsoft.com/en-us/library/ms189499%28v=sql.110%29.aspx
Your list comprehension goes through all the dict's items finding all the matches, then just returns the first key. This generator expression will only iterate as far as necessary to return the first value:
key = next(key for key, value in dd.items() if value == 'value')
where dd
is the dict. Will raise StopIteration
if no match is found, so you might want to catch that and return a more appropriate exception like ValueError
or KeyError
.
Try this and let me know if it does not work on your end:
<input type="checkbox" name='agree' ref={input => this.inputElement = input}/>
<div onClick={() => this.inputElement.click()}>Click</div>
Clicking on the div
should simulate a click on the input
element
For MS compilers:
#define inc_enum(i) ((decltype(i)) ((int)i + 1))
enum enumtype { one, two, three, count};
for(enumtype i = one; i < count; i = inc_enum(i))
{
dostuff(i);
}
Note: this is a lot less code than the simple templatized custom iterator answer.
You can get this to work with GCC by using typeof
instead of decltype
, but I don't have that compiler handy at the moment to make sure it compiles.
I need to know way for converting uri to string and string to uri.
Use toString()
to convert a Uri
to a String
. Use Uri.parse()
to convert a String
to a Uri
.
this code doesn't work
That is not a valid string representation of a Uri
. A Uri
has a scheme, and "/external/images/media/470939"
does not have a scheme.
https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
window.location.assign("../");
// one level upwindow.location.assign("/path");
// relative to domainif re.search(r'pattern', string):
Simple if-test:
if re.search(r'ing\b', "seeking a great perhaps"): # any words end with ing?
print("yes")
Pattern check, extract a substring, case insensitive:
match_object = re.search(r'^OUGHT (.*) BE$', "ought to be", flags=re.IGNORECASE)
if match_object:
assert "to" == match_object.group(1) # what's between ought and be?
Notes:
Use re.search()
not re.match. Match restricts to the start of strings, a confusing convention if you ask me. If you do want a string-starting match, use caret or \A
instead, re.search(r'^...', ...)
Use raw string syntax r'pattern'
for the first parameter. Otherwise you would need to double up backslashes, as in re.search('ing\\b', ...)
In this example, \b
is a special sequence meaning word-boundary in regex. Not to be confused with backspace.
re.search()
returns None
if it doesn't find anything, which is always falsy.
re.search()
returns a Match object if it finds anything, which is always truthy.
a group is what matched inside parentheses
group numbering starts at 1
LIMIT allow you to skip any number of rows. It has two parameters, and first of them - how many rows to skip
If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the Python interpreter that lives inside virtualenv's /bin/ directory:
import subprocess
# Path to a Python interpreter that runs any Python script
# under the virtualenv /path/to/virtualenv/
python_bin = "/path/to/virtualenv/bin/python"
# Path to the script that must run under the virtualenv
script_file = "must/run/under/virtualenv/script.py"
subprocess.Popen([python_bin, script_file])
However, if you want to activate the virtualenv under the current Python interpreter instead of a subprocess, you can use the activate_this.py
script:
# Doing execfile() on this file will alter the current interpreter's
# environment so you can import libraries in the virtualenv
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"
execfile(activate_this_file, dict(__file__=activate_this_file))
Maybe check for any thing that you have changed under the php.ini file. For example I changed the ";intl.default_locale =" to ";intl.default_locale = en_utf8" in order to enable the "Internationalization extension (Intl)" without adding the "extension=php_intl.dll" then this same error occurred. So I suggest to check for similar mistakes.
Thanks you all! Now it's work. DATAJPA-231
It will be nice if was possible to create count…By… methods just like find…By ones. Example:
public interface UserRepository extends JpaRepository<User, Long> {
public Long /*or BigInteger */ countByActiveTrue();
}
/* for chrome */
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;}
/* for mozilla */
input[type=number] {-moz-appearance: textfield;}
import the ViewChild
decorator from @angular/core
, like so:
HTML Code:
<form #f="ngForm">
...
...
</form>
TS Code:
import { ViewChild } from '@angular/core';
class TemplateFormComponent {
@ViewChild('f') myForm: any;
.
.
.
}
now you can use 'myForm' object to access any element within it in the class.
I had this problem too (encountered through Macports compilers). Previous versions of Xcode would let you install command line tools through xcode/Preferences, but xcode5 doesn't give a command line tools option in the GUI, that so I assumed it was automatically included now. Try running this command:
xcode-select --install
(as per this answer)
sudo apt-get install libc6-dev
(as per this comment)
apk add libc-dev
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
Easy way out is to use a condition like this ( use desired date > GETDATE()-1)
your sql statement "date specific" > GETDATE()-1
Execution is not related to laravel go to the php.ini file In php.ini file set max_execution_time=360 (time may be variable depends on need) if you want to increase execution of a specific page then write ini_set('max_execution_time',360) at top of page
otherwise in htaccess php_value max_execution_time 360
Your file .idea/workspace.xml
is not under git version control. You have either not added it yet (check git status/Untracked files) or ignored it (using .gitignore or .git/info/exclude files)
You can verify it using following git command, that lists all ignored files:
git ls-files --others -i --exclude-standard
Regards.
I wrote a useful scalar function to simulate the TRY_CAST function of SQL SERVER 2012 in SQL Server 2008.
You can see it in the next link below and we help each other to improve it. TRY_CAST Function for SQL Server 2008 https://gist.github.com/jotapardo/800881eba8c5072eb8d99ce6eb74c8bb
The two main differences are that you must pass 3 parameters and you must additionally perform an explicit CONVERT or CAST to the field. However, it is still very useful because it allows you to return a default value if CAST is not performed correctly.
dbo.TRY_CAST(Expression, Data_Type, ReturnValueIfErrorCast)
Example:
SELECT CASE WHEN dbo.TRY_CAST('6666666166666212', 'INT', DEFAULT) IS NULL
THEN 'Cast failed'
ELSE 'Cast succeeded'
END AS Result;
For now only supports the data types INT, DATE, NUMERIC, BIT and FLOAT
I hope you find it useful.
CODE:
DECLARE @strSQL NVARCHAR(1000)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[TRY_CAST]'))
BEGIN
SET @strSQL = 'CREATE FUNCTION [dbo].[TRY_CAST] () RETURNS INT AS BEGIN RETURN 0 END'
EXEC sys.sp_executesql @strSQL
END
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
------------------------------------------------------------------------------------------------------------------------
Description:
Syntax
---------------
dbo.TRY_CAST(Expression, Data_Type, ReturnValueIfErrorCast)
+---------------------------+-----------------------+
| Expression | VARCHAR(8000) |
+---------------------------+-----------------------+
| Data_Type | VARCHAR(8000) |
+---------------------------+-----------------------+
| ReturnValueIfErrorCast | SQL_VARIANT = NULL |
+---------------------------+-----------------------+
Arguments
---------------
expression
The value to be cast. Any valid expression.
Data_Type
The data type into which to cast expression.
ReturnValueIfErrorCast
Value returned if cast fails or is not supported. Required. Set the DEFAULT value by default.
Return Type
----------------
Returns value cast to SQL_VARIANT type if the cast succeeds; otherwise, returns null if the parameter @pReturnValueIfErrorCast is set to DEFAULT,
or that the user indicates.
Remarks
----------------
dbo.TRY_CAST function simulates the TRY_CAST function reserved of SQL SERVER 2012 for using in SQL SERVER 2008.
dbo.TRY_CAST function takes the value passed to it and tries to convert it to the specified Data_Type.
If the cast succeeds, dbo.TRY_CAST returns the value as SQL_VARIANT type; if the cast doesn´t succees, null is returned if the parameter @pReturnValueIfErrorCast is set to DEFAULT.
If the Data_Type is unsupported will return @pReturnValueIfErrorCast.
dbo.TRY_CAST function requires user make an explicit CAST or CONVERT in ANY statements.
This version of dbo.TRY_CAST only supports CAST for INT, DATE, NUMERIC and BIT types.
Examples
====================================================================================================
--A. Test TRY_CAST function returns null
SELECT
CASE WHEN dbo.TRY_CAST('6666666166666212', 'INT', DEFAULT) IS NULL
THEN 'Cast failed'
ELSE 'Cast succeeded'
END AS Result;
GO
--B. Error Cast With User Value
SELECT
dbo.TRY_CAST('2147483648', 'INT', DEFAULT) AS [Error Cast With DEFAULT],
dbo.TRY_CAST('2147483648', 'INT', -1) AS [Error Cast With User Value],
dbo.TRY_CAST('2147483648', 'INT', NULL) AS [Error Cast With User NULL Value];
GO
--C. Additional CAST or CONVERT required in any assignment statement
DECLARE @IntegerVariable AS INT
SET @IntegerVariable = CAST(dbo.TRY_CAST(123, 'INT', DEFAULT) AS INT)
SELECT @IntegerVariable
GO
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp (
Id INT IDENTITY
, FieldNumeric NUMERIC(3, 1)
)
INSERT INTO dbo.#temp (FieldNumeric)
SELECT CAST(dbo.TRY_CAST(12.3, 'NUMERIC(3,1)', 0) AS NUMERIC(3, 1));--Need explicit CAST on INSERT statements
SELECT *
FROM #temp
DROP TABLE #temp
GO
--D. Supports CAST for INT, DATE, NUMERIC and BIT types.
SELECT dbo.TRY_CAST(2147483648, 'INT', 0) AS [Cast failed]
, dbo.TRY_CAST(2147483647, 'INT', 0) AS [Cast succeeded]
, SQL_VARIANT_PROPERTY(dbo.TRY_CAST(212, 'INT', 0), 'BaseType') AS [BaseType];
SELECT dbo.TRY_CAST('AAAA0101', 'DATE', DEFAULT) AS [Cast failed]
, dbo.TRY_CAST('20160101', 'DATE', DEFAULT) AS [Cast succeeded]
, SQL_VARIANT_PROPERTY(dbo.TRY_CAST('2016-01-01', 'DATE', DEFAULT), 'BaseType') AS [BaseType];
SELECT dbo.TRY_CAST(1.23, 'NUMERIC(3,1)', DEFAULT) AS [Cast failed]
, dbo.TRY_CAST(12.3, 'NUMERIC(3,1)', DEFAULT) AS [Cast succeeded]
, SQL_VARIANT_PROPERTY(dbo.TRY_CAST(12.3, 'NUMERIC(3,1)', DEFAULT), 'BaseType') AS [BaseType];
SELECT dbo.TRY_CAST('A', 'BIT', DEFAULT) AS [Cast failed]
, dbo.TRY_CAST(1, 'BIT', DEFAULT) AS [Cast succeeded]
, SQL_VARIANT_PROPERTY(dbo.TRY_CAST('123', 'BIT', DEFAULT), 'BaseType') AS [BaseType];
GO
--E. B. TRY_CAST return NULL on unsupported data_types
SELECT dbo.TRY_CAST(4, 'xml', DEFAULT) AS [unsupported];
GO
====================================================================================================
------------------------------------------------------------------------------------------------------------------------
Responsible: Javier Pardo
Date: diciembre 29/2016
WB tests: Javier Pardo
------------------------------------------------------------------------------------------------------------------------
Update by: Javier Eduardo Pardo Moreno
Date: febrero 16/2017
Id update: JEPM20170216
Description: Fix ISNUMERIC function makes it unreliable. SELECT dbo.TRY_CAST('+', 'INT', 0) will yield Msg 8114,
Level 16, State 5, Line 16 Error converting data type varchar to float.
ISNUMERIC() function treats few more characters as numeric, like: – (minus), + (plus), $ (dollar), \ (back slash), (.)dot and (,)comma
Collaborator aperiooculus (http://stackoverflow.com/users/3083382/aperiooculus )
Fix dbo.TRY_CAST('2013/09/20', 'datetime', DEFAULT) for supporting DATETIME format
WB tests: Javier Pardo
------------------------------------------------------------------------------------------------------------------------
*/
ALTER FUNCTION dbo.TRY_CAST
(
@pExpression AS VARCHAR(8000),
@pData_Type AS VARCHAR(8000),
@pReturnValueIfErrorCast AS SQL_VARIANT = NULL
)
RETURNS SQL_VARIANT
AS
BEGIN
--------------------------------------------------------------------------------
-- INT
--------------------------------------------------------------------------------
IF @pData_Type = 'INT'
BEGIN
IF ISNUMERIC(@pExpression) = 1 AND @pExpression NOT IN ('-','+','$','.',',','\') --JEPM20170216
BEGIN
DECLARE @pExpressionINT AS FLOAT = CAST(@pExpression AS FLOAT)
IF @pExpressionINT BETWEEN - 2147483648.0 AND 2147483647.0
BEGIN
RETURN CAST(@pExpressionINT as INT)
END
ELSE
BEGIN
RETURN @pReturnValueIfErrorCast
END --FIN IF @pExpressionINT BETWEEN - 2147483648.0 AND 2147483647.0
END
ELSE
BEGIN
RETURN @pReturnValueIfErrorCast
END -- FIN IF ISNUMERIC(@pExpression) = 1
END -- FIN IF @pData_Type = 'INT'
--------------------------------------------------------------------------------
-- DATE
--------------------------------------------------------------------------------
IF @pData_Type IN ('DATE','DATETIME')
BEGIN
IF ISDATE(@pExpression) = 1
BEGIN
DECLARE @pExpressionDATE AS DATETIME = cast(@pExpression AS DATETIME)
IF @pData_Type = 'DATE'
BEGIN
RETURN cast(@pExpressionDATE as DATE)
END
IF @pData_Type = 'DATETIME'
BEGIN
RETURN cast(@pExpressionDATE as DATETIME)
END
END
ELSE
BEGIN
DECLARE @pExpressionDATEReplaced AS VARCHAR(50) = REPLACE(REPLACE(REPLACE(@pExpression,'\',''),'/',''),'-','')
IF ISDATE(@pExpressionDATEReplaced) = 1
BEGIN
IF @pData_Type = 'DATE'
BEGIN
RETURN cast(@pExpressionDATEReplaced as DATE)
END
IF @pData_Type = 'DATETIME'
BEGIN
RETURN cast(@pExpressionDATEReplaced as DATETIME)
END
END
ELSE
BEGIN
RETURN @pReturnValueIfErrorCast
END
END --FIN IF ISDATE(@pExpression) = 1
END --FIN IF @pData_Type = 'DATE'
--------------------------------------------------------------------------------
-- NUMERIC
--------------------------------------------------------------------------------
IF @pData_Type LIKE 'NUMERIC%'
BEGIN
IF ISNUMERIC(@pExpression) = 1
BEGIN
DECLARE @TotalDigitsOfType AS INT = SUBSTRING(@pData_Type,CHARINDEX('(',@pData_Type)+1, CHARINDEX(',',@pData_Type) - CHARINDEX('(',@pData_Type) - 1)
, @TotalDecimalsOfType AS INT = SUBSTRING(@pData_Type,CHARINDEX(',',@pData_Type)+1, CHARINDEX(')',@pData_Type) - CHARINDEX(',',@pData_Type) - 1)
, @TotalDigitsOfValue AS INT
, @TotalDecimalsOfValue AS INT
, @TotalWholeDigitsOfType AS INT
, @TotalWholeDigitsOfValue AS INT
SET @pExpression = REPLACE(@pExpression, ',','.')
SET @TotalDigitsOfValue = LEN(REPLACE(@pExpression, '.',''))
SET @TotalDecimalsOfValue = CASE Charindex('.', @pExpression)
WHEN 0
THEN 0
ELSE Len(Cast(Cast(Reverse(CONVERT(VARCHAR(50), @pExpression, 128)) AS FLOAT) AS BIGINT))
END
SET @TotalWholeDigitsOfType = @TotalDigitsOfType - @TotalDecimalsOfType
SET @TotalWholeDigitsOfValue = @TotalDigitsOfValue - @TotalDecimalsOfValue
-- The total digits can not be greater than the p part of NUMERIC (p, s)
-- The total of decimals can not be greater than the part s of NUMERIC (p, s)
-- The total digits of the whole part can not be greater than the subtraction between p and s
IF (@TotalDigitsOfValue <= @TotalDigitsOfType) AND (@TotalDecimalsOfValue <= @TotalDecimalsOfType) AND (@TotalWholeDigitsOfValue <= @TotalWholeDigitsOfType)
BEGIN
DECLARE @pExpressionNUMERIC AS FLOAT
SET @pExpressionNUMERIC = CAST (ROUND(@pExpression, @TotalDecimalsOfValue) AS FLOAT)
RETURN @pExpressionNUMERIC --Returns type FLOAT
END
else
BEGIN
RETURN @pReturnValueIfErrorCast
END-- FIN IF (@TotalDigitisOfValue <= @TotalDigits) AND (@TotalDecimalsOfValue <= @TotalDecimals)
END
ELSE
BEGIN
RETURN @pReturnValueIfErrorCast
END --FIN IF ISNUMERIC(@pExpression) = 1
END --IF @pData_Type LIKE 'NUMERIC%'
--------------------------------------------------------------------------------
-- BIT
--------------------------------------------------------------------------------
IF @pData_Type LIKE 'BIT'
BEGIN
IF ISNUMERIC(@pExpression) = 1
BEGIN
RETURN CAST(@pExpression AS BIT)
END
ELSE
BEGIN
RETURN @pReturnValueIfErrorCast
END --FIN IF ISNUMERIC(@pExpression) = 1
END --IF @pData_Type LIKE 'BIT'
--------------------------------------------------------------------------------
-- FLOAT
--------------------------------------------------------------------------------
IF @pData_Type LIKE 'FLOAT'
BEGIN
IF ISNUMERIC(REPLACE(REPLACE(@pExpression, CHAR(13), ''), CHAR(10), '')) = 1
BEGIN
RETURN CAST(@pExpression AS FLOAT)
END
ELSE
BEGIN
IF REPLACE(@pExpression, CHAR(13), '') = '' --Only white spaces are replaced, not new lines
BEGIN
RETURN 0
END
ELSE
BEGIN
RETURN @pReturnValueIfErrorCast
END --IF REPLACE(@pExpression, CHAR(13), '') = ''
END --FIN IF ISNUMERIC(@pExpression) = 1
END --IF @pData_Type LIKE 'FLOAT'
--------------------------------------------------------------------------------
-- Any other unsupported data type will return NULL or the value assigned by the user to @pReturnValueIfErrorCast
--------------------------------------------------------------------------------
RETURN @pReturnValueIfErrorCast
END
This topic is well covered already but I wanted to add something more specific : I wanted to be sure that a certain value would be mapped to that color (not to any color).
It is not complicated but as it took me some time, it might help others not lossing as much time as I did :)
import matplotlib
from matplotlib.colors import ListedColormap
# Let's design a dummy land use field
A = np.reshape([7,2,13,7,2,2], (2,3))
vals = np.unique(A)
# Let's also design our color mapping: 1s should be plotted in blue, 2s in red, etc...
col_dict={1:"blue",
2:"red",
13:"orange",
7:"green"}
# We create a colormar from our list of colors
cm = ListedColormap([col_dict[x] for x in col_dict.keys()])
# Let's also define the description of each category : 1 (blue) is Sea; 2 (red) is burnt, etc... Order should be respected here ! Or using another dict maybe could help.
labels = np.array(["Sea","City","Sand","Forest"])
len_lab = len(labels)
# prepare normalizer
## Prepare bins for the normalizer
norm_bins = np.sort([*col_dict.keys()]) + 0.5
norm_bins = np.insert(norm_bins, 0, np.min(norm_bins) - 1.0)
print(norm_bins)
## Make normalizer and formatter
norm = matplotlib.colors.BoundaryNorm(norm_bins, len_lab, clip=True)
fmt = matplotlib.ticker.FuncFormatter(lambda x, pos: labels[norm(x)])
# Plot our figure
fig,ax = plt.subplots()
im = ax.imshow(A, cmap=cm, norm=norm)
diff = norm_bins[1:] - norm_bins[:-1]
tickz = norm_bins[:-1] + diff / 2
cb = fig.colorbar(im, format=fmt, ticks=tickz)
fig.savefig("example_landuse.png")
plt.show()
In PowerShell v5+, there is an Expand-Archive command (as well as Compress-Archive) built in:
Expand-Archive c:\a.zip -DestinationPath c:\a
The idea is to send a callback to the child which will be called to give the data back
A complete and minimal example using functions:
App will create a Child which will compute a random number and send it back directly to the parent, which will console.log
the result
const Child = ({ handleRandom }) => {
handleRandom(Math.random())
return <span>child</span>
}
const App = () => <Child handleRandom={(num) => console.log(num)}/>
If you are having this problem with a homebrew installation of maven 3 on the OSX 10.9.4 then check out this blog post.
Simple: you can't.
This is an old question, but answering for gathering knowledge. We have an original form with a button to show the new form.
The code for the button click is below
private void button1_Click(object sender, EventArgs e)
{
New_Form new_Form = new New_Form();
new_Form.Show();
}
Now when click is made, New Form is shown. Since, you want to hide after 2 seconds we are adding a onload event to the new form designer
this.Load += new System.EventHandler(this.OnPageLoad);
This OnPageLoad function runs when that form is loaded
In NewForm.cs ,
public partial class New_Form : Form
{
private Timer formClosingTimer;
private void OnPageLoad(object sender, EventArgs e)
{
formClosingTimer = new Timer(); // Creating a new timer
formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period
formClosingTimer.Interval = 2000; // Time Interval in miliseconds
formClosingTimer.Start(); // Starting a timer
}
private void CloseForm(object sender, EventArgs e)
{
formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals
this.Close(); // Closing the current form
}
}
In this new form , a timer is used to invoke a method which closes that form.
Here is the new form which automatically closes after 2 seconds, we will be able operate on both the forms where no interference between those two forms.
For your knowledge,
form.close()
will free the memory and we can never interact with that form again
form.hide()
will just hide the form, where the code part can still run
For more details about timer refer this link, https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2
ArrayList get(int index)
method is used for fetching an element from the list. We need to specify the index while calling get method and it returns the value present at the specified index.
public Element get(int index)
Example : In below example we are getting few elements of an arraylist by using get method.
package beginnersbook.com;
import java.util.ArrayList;
public class GetMethodExample {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("pen");
al.add("pencil");
al.add("ink");
al.add("notebook");
al.add("book");
al.add("books");
al.add("paper");
al.add("white board");
System.out.println("First element of the ArrayList: "+al.get(0));
System.out.println("Third element of the ArrayList: "+al.get(2));
System.out.println("Sixth element of the ArrayList: "+al.get(5));
System.out.println("Fourth element of the ArrayList: "+al.get(3));
}
}
Output:
First element of the ArrayList: pen
Third element of the ArrayList: ink
Sixth element of the ArrayList: books
Fourth element of the ArrayList: notebook
If you are using GNU make, $(CURDIR) is actually a built-in variable. It is the location where the Makefile resides the current working directory, which is probably where the Makefile is, but not always.
OUTPUT_PATH = /project1/bin/$(notdir $(CURDIR))
See Appendix A Quick Reference in http://www.gnu.org/software/make/manual/make.html
As of today you can throttle your connection natively in Google Chrome Canary 46.0.2489.0
. Simply open up Dev Tools and head over to the Network tab:
In windows 10, period is first parameter
docker build . -t docker-whale
As far as I can tell, at this point it is not possible to set click_action in the console.
While not a strict answer to how to get the click_action set in the console, you can use curl as an alternative:
curl --header "Authorization: key=<YOUR_KEY_GOES_HERE>" --header Content-Type:"application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"/topics/news\",\"notification\": {\"title\": \"Click Action Message\",\"text\": \"Sample message\",\"click_action\":\"OPEN_ACTIVITY_1\"}}"
This is an easy way to test click_action mapping. It requires an intent filter like the one specified in the FCM docs:
<intent-filter>_x000D_
<action android:name="OPEN_ACTIVITY_1" />_x000D_
<category android:name="android.intent.category.DEFAULT" />_x000D_
</intent-filter>
_x000D_
This also makes use of topics to set the audience. In order for this to work you will need to subscribe to a topic called "news".
FirebaseMessaging.getInstance().subscribeToTopic("news");
Even though it takes several hours to see a newly-created topic in the console, you may still send messages to it through the FCM apis.
Also, keep in mind, this will only work if the app is in the background. If it is in the foreground you will need to implement an extension of FirebaseMessagingService. In the onMessageReceived method, you will need to manually navigate to your click_action target:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//This will give you the topic string from curl request (/topics/news)
Log.d(TAG, "From: " + remoteMessage.getFrom());
//This will give you the Text property in the curl request(Sample Message):
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//This is where you get your click_action
Log.d(TAG, "Notification Click Action: " + remoteMessage.getNotification().getClickAction());
//put code here to navigate based on click_action
}
As I said, at this time I cannot find a way to access notification payload properties through the console, but I thought this work around might be helpful.
You can load HTML page partial, in your case is everything inside div#mytable.
setTimeout(function(){
$( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds
more information read this http://api.jquery.com/load/
<button id="refresh-btn">Refresh Table</button>
<script>
$(document).ready(function() {
function RefreshTable() {
$( "#mytable" ).load( "your-current-page.html #mytable" );
}
$("#refresh-btn").on("click", RefreshTable);
// OR CAN THIS WAY
//
// $("#refresh-btn").on("click", function() {
// $( "#mytable" ).load( "your-current-page.html #mytable" );
// });
});
</script>
If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:
Didn't pass linting
const x = new Obj(a as b);
The linter was complaining that a
was missing properties that existed on b
. In other words, a
had some properties and methods of b
, but not all. To work around this, I followed VS Code's suggestion:
Passed linting and testing
const x = new Obj(a as unknown as b);
Note that if your code attempts to call one of the properties that exists on type b
that is not implemented on type a
, you should realize a runtime fault.
Since the checked value is Boolean
it's preferred to use it directly for less coding and at all it did same ==true
After many attemps I managed to fix this problem. Variable ${PODS_ROOT} was not set and I do below trick. Go to Build Phases -> Check Pods Manifest.lock and replace
diff "${PODS_ROOT}/../Podfile.lock" "${PODS_ROOT}/Manifest.lock" > /dev/null
to
diff "${SRCROOT}/Podfile.lock" "${SRCROOT}/Pods/Manifest.lock" > /dev/null
It helps me.
I would use a negative lookahead for any character:
^(?![\s\S])
This can only match if the input is totally empty, because the character class will match any character, including any of the various newline characters.
There's really no easy way to mix fluid and fixed widths with Bootstrap 3. It's meant to be like this, as the grid system is designed to be a fluid, responsive thing. You could try hacking something up, but it would go against what the Responsive Grid system is trying to do, the intent of which is to make that layout flow across different device types.
If you need to stick with this layout, I'd consider laying out your page with custom CSS and not using the grid.
I had the same issue, but I have resolved it the next:
1) Install jdk1.8...
2) In AndroidStudio File->Project Structure->SDK Location, select your directory where the JDK is located, by default Studio uses embedded JDK but for some reason it produces error=216.
3) Click Ok.
For VB6:
You need to declare your C functions as __stdcall, otherwise you get "invalid calling convention" type errors. About other your questions:
can I take arguments by pointer/reference from the VB front-end?
Yes, use ByRef/ByVal modifiers.
Can the DLL call a theoretical function in the front-end?
Yes, use AddressOf statement. You need to pass function pointer to dll before.
Or have a function take a "function pointer" (I don't even know if that's possible) from VB and call it?)
Yes, use AddressOf statement.
update (more questions appeared :)):
to load it into VB, do I just do the usual method (what I would do to load winsock.ocx or some other runtime, but find my DLL instead) or do I put an API call into a module?
You need to decaler API function in VB6 code, like next:
Private Declare Function SHGetSpecialFolderLocation Lib "shell32" _
(ByVal hwndOwner As Long, _
ByVal nFolder As Long, _
ByRef pidl As Long) As Long
The names of the first dataframe do not match the names of the second one. Just as the error message says.
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] FALSE
If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:
> names(xd.small[[1]]) <- names(xd.small[[2]])
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE
Then things should proceed happily.
In simple words other major difference is that IEnumerable execute select query on server side, load data in-memory on client side and then filter data while IQueryable execute select query on server side with all filters.
Try this:
string callbackurl = Request.Url.Host != "localhost"
? Request.Url.Host : Request.Url.Authority;
This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.
In your class you should have:
public void paint(Graphics g){
g.drawLine(x1, y1, x2, y2);
}
Then in code if there is needed you will change x1, y1, x2, y2 and call repaint();
.
As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:
TSKILL processName
or
TSKILL PID
Have on mind that processName
should not have the .exe
suffix and is limited to 18 characters.
Another option is WMIC
:
wmic Path win32_process Where "Caption Like 'MyProcess.exe'" Call Terminate
wmic offer even more flexibility than taskkill .With wmic Path win32_process get
you can see the available fileds you can filter.
If you are using React.js, you could do this:
render() {
// ...
<img
onLoad={() => this.onImgLoad({ item })}
onError={() => this.onImgLoad({ item })}
src={item.src} key={item.key}
ref={item.key} />
// ... }
Where:
When and where to use \\\"
instead. OK if you are like me you will feel just as silly as I did when I realized what I was doing after I found this thread.
If you're making a .json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes:\"
is the one you're looking for.
However if you're like me and you're trying to get the w3schools.com "Tryit Editor" to have a double quotes in the output of the JSON.parse(text), then the one you're looking for is the triple backslash double quotes \\\"
. This is because you're building your text string within an HTML <script>
block, and the first double backslash inserts a single backslash into the string variable then the following backslash double quote inserts the double quote into the string so that the resulting script string contains the \"
from the standard answer and the JSON parser will parse this as just the double quotes.
<script>
var text="{";
text += '"quip":"\\\"If nobody is listening, then you\'re likely talking to the wrong audience.\\\""';
text += "}";
var obj=JSON.parse(text);
</script>
+1: since it's a JavaScript text string, a double backslash double quote \\"
would work too; because the double quote does not need escaped within a single quoted string eg '\"'
and '"'
result in the same JS string.
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
HashMap<String, int[]> map = new HashMap<String, int[]>();
pick one, for example
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
map.put("Something", new ArrayList<Integer>());
for (int i=0;i<numarulDeCopii; i++) {
map.get("Something").add(coeficientUzura[i]);
}
or just
HashMap<String, int[]> map = new HashMap<String, int[]>();
map.put("Something", coeficientUzura);
The thing that worked for me (and that I took from another stackoverflow response), is to set the flag:
Response.TrySkipIisCustomErrors = true;
I ran into a similar issue a while back.
Your problem could be in two different areas. It's either how you're creating the file to write to, or your method of writing could be flawed in that it is phone dependent.
If you're writing the file to a specific location on the SD card, try using Environment variables. They should always point to a valid location. Here's an example to write to the downloads folder:
java.io.File xmlFile = new java.io.File(Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
+ "/Filename.xml");
If you're writing the file to the application's internal storage. Try this example:
java.io.File xmlFile = new java.io.File((getActivity()
.getApplicationContext().getFileStreamPath("FileName.xml")
.getPath()));
Personally I rely on external libraries to handle the streaming to file. This one hasn't failed me yet.
org.apache.commons.io.FileUtils.copyInputStreamToFile(is, file);
I've lost data one too many times on a failed write command, so I rely on well-known and tested libraries for my IO heavy lifting.
If the files are large, you may also want to look into running the IO in the background, or use callbacks.
If you're already using environment variables, it could be a permissions issue. Check out Justin Fiedler's answer below.
you should remove last comma and as nrodic said your command is not correct.
you should change it like this :
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact " + ") VALUES (" + " textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, comboBox1.Text,comboBox2.Text,textBox7.Text" + ")", cn);
If you want only letters - so from a to z, lower case or upper case, excluding everything else (numbers, blank spaces, symbols), you can modify your function like this:
function validate() {
if (document.myForm.name.value == "") {
alert("Enter a name");
document.myForm.name.focus();
return false;
}
if (!/^[a-zA-Z]*$/g.test(document.myForm.name.value)) {
alert("Invalid characters");
document.myForm.name.focus();
return false;
}
}
Try This.....
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Label12.Text = TimeOfDay.ToString("h:mm:ss tt")
End Sub
XCode 6.4, for iOS 8.4, ARC enabled
Obviously lots of ways of doing it. The one that has worked for me is the following...
@property(nonatomic, readonly, getter=isKeyWindow) BOOL keyWindow
This can be used in any view controller in the following way,
[self.view.window isKeyWindow]
If you call this property in -(void)viewDidLoad
you get 0, then if you call this after -(void)viewDidAppear:(BOOL)animated
you get 1.
Hope this helps someone. Thanks! Cheers.
I use this simple script to get a log from the pods of a deployment:
#!/usr/bin/env bash
DEPLOYMENT=$1
for p in $(kubectl get pods | grep ^${DEPLOYMENT}- | cut -f 1 -d ' '); do
echo ---------------------------
echo $p
echo ---------------------------
kubectl logs $p
done
Usage: log_deployment.sh "deployment-name".
Script will then show log of all pods that start with that "deployment-name".
when you are using 32bits node on 64bits windows(like node-webkit or atom-shell developers), process.platform will echo win32
use
function isOSWin64() {
return process.arch === 'x64' || process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432');
}
(check here for details)
If your VM already came with VMware Tools pre-installed, but this still isn't working for you--or if you install and still no luck--make sure you run Workstation or Player as Administrator. That fixed the issue for me.
It's been a little while since I coded with selenium, but your code looks ok to me. One thing to note is that if the element is not found, but the timeout is passed, I think the code will continue to execute. So you can do something like this:
boolean exists = driver.findElements(By.xpath("//*[@id='someID']")).size() != 0
What does the above boolean return? And are you sure selenium actually navigates to the expected page? (That may sound like a silly question but are you actually watching the pages change... selenium can be run remotely you know...)
function arrayUnique($myArray)
{
$newArray = Array();
if (is_array($myArray))
{
foreach($myArray as $key=>$val)
{
if (is_array($val))
{
$val2 = arrayUnique($val);
}
else
{
$val2 = $val;
$newArray=array_unique($myArray);
$newArray=deleteEmpty($newArray);
break;
}
if (!empty($val2))
{
$newArray[$key] = $val2;
}
}
}
return ($newArray);
}
function deleteEmpty($myArray)
{
$retArray= Array();
foreach($myArray as $key=>$val)
{
if (($key<>"") && ($val<>""))
{
$retArray[$key] = $val;
}
}
return $retArray;
}
Simple Find Write Code in On Location Method
public void onLocationChanged(Location location) {
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(18));
PolylineOptions pOptions = new PolylineOptions()
.width(5)
.color(Color.GREEN)
.geodesic(true);
for (int z = 0; z < routePoints.size(); z++) {
LatLng point = routePoints.get(z);
pOptions.add(point);
}
line = mMap.addPolyline(pOptions);
routePoints.add(latLng);
}
String match = "hello";
String text = "0123456789hello0123456789hello";
int j = 0;
String indxOfmatch = "";
for (int i = -1; i < text.length()+1; i++) {
j = text.indexOf("hello", i);
if (i>=j && j > -1) {
indxOfmatch += text.indexOf("hello", i)+" ";
}
}
System.out.println(indxOfmatch);
The following is how I do it using Visual Studio 2017 for an RDL targetted for SSRS 2017:
Right-click on the field in the textbox on the design surface and choose Placeholder Properties. Choose the Number panel and click on Date in the Category listbox, then select the formatting you are looking for in the Type listbox.
Had this problem couldn't find the answer so i went looking on other threads, I found that i was making my app with 1.8 but for some reason my jre was out dated even though i remember updating it. I downloaded the lastes jre 8 and the jar file runs perfectly. Hope this helps.
Do everything suggested by ziesemer.
You may also want to remove from the registry:
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\<any Ora* drivers> keys
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers<any Ora* driver> values
So they no longer appear in the "ODBC Drivers that are installed on your system" in ODBC Data Source Administrator
PostgreSQL does not support IF NOT EXISTS
for CREATE DATABASE
statement. It is supported only in CREATE SCHEMA
. Moreover CREATE DATABASE
cannot be issued in transaction therefore it cannot be in DO
block with exception catching.
When CREATE SCHEMA IF NOT EXISTS
is issued and schema already exists then notice (not error) with duplicate object information is raised.
To solve these problems you need to use dblink
extension which opens a new connection to database server and execute query without entering into transaction. You can reuse connection parameters with supplying empty string.
Below is PL/pgSQL
code which fully simulates CREATE DATABASE IF NOT EXISTS
with same behavior like in CREATE SCHEMA IF NOT EXISTS
. It calls CREATE DATABASE
via dblink
, catch duplicate_database
exception (which is issued when database already exists) and converts it into notice with propagating errcode
. String message has appended , skipping
in the same way how it does CREATE SCHEMA IF NOT EXISTS
.
CREATE EXTENSION IF NOT EXISTS dblink;
DO $$
BEGIN
PERFORM dblink_exec('', 'CREATE DATABASE testdb');
EXCEPTION WHEN duplicate_database THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
END
$$;
This solution is without any race condition like in other answers, where database can be created by external process (or other instance of same script) between checking if database exists and its own creation.
Moreover when CREATE DATABASE
fails with other error than database already exists then this error is propagated as error and not silently discarded. There is only catch for duplicate_database
error. So it really behaves as IF NOT EXISTS
should.
You can put this code into own function, call it directly or from transaction. Just rollback (restore dropped database) would not work.
Testing output (called two times via DO and then directly):
$ sudo -u postgres psql
psql (9.6.12)
Type "help" for help.
postgres=# \set ON_ERROR_STOP on
postgres=# \set VERBOSITY verbose
postgres=#
postgres=# CREATE EXTENSION IF NOT EXISTS dblink;
CREATE EXTENSION
postgres=# DO $$
postgres$# BEGIN
postgres$# PERFORM dblink_exec('', 'CREATE DATABASE testdb');
postgres$# EXCEPTION WHEN duplicate_database THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
postgres$# END
postgres$# $$;
DO
postgres=#
postgres=# CREATE EXTENSION IF NOT EXISTS dblink;
NOTICE: 42710: extension "dblink" already exists, skipping
LOCATION: CreateExtension, extension.c:1539
CREATE EXTENSION
postgres=# DO $$
postgres$# BEGIN
postgres$# PERFORM dblink_exec('', 'CREATE DATABASE testdb');
postgres$# EXCEPTION WHEN duplicate_database THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
postgres$# END
postgres$# $$;
NOTICE: 42P04: database "testdb" already exists, skipping
LOCATION: exec_stmt_raise, pl_exec.c:3165
DO
postgres=#
postgres=# CREATE DATABASE testdb;
ERROR: 42P04: database "testdb" already exists
LOCATION: createdb, dbcommands.c:467
And if you want to create the list with some elements to start with:
var emailList = new List<EmailData>
{
new EmailData { FirstName = "John", LastName = "Doe", Location = "Moscow" },
new EmailData {.......}
};
For *nix users who are using SSH:
Make sure the username for your account on your local machine does not differ from the username for the account on the server. Apparently, eGit does not seem to be able to handle this. For example, if your username on your local machine is 'john', and the account you are using on the server is named 'git', egit simply fails to connect (for me anyways). The only work around I have found is to make sure you have identical usernames in both the local machine and the server.
Tortoise Settings > Icon Overlays -> Overlay Handlers -> Start registry editor
1. Rename icon name :By adding a space(s) at the beginning of the file's name and then press F5 until it goes to top . example: " Tortoise1Normal" (in default 2 spaces included)? " Tortoise1Normal" (3 spaces)
2. Restart explorer in Task manager
Here is another fix:
My build system (Gradle) added a required native library (dll) to the Eclipse build path (Right Click on Project -> Properties -> Java Build Path -> Libraries). Telling the build system not to add the native dll library to the Eclipse classpath solved the problem.
You can't; at least not the same way you can test whether a pointer is NULL
.
A std::string
object is always initialized and always contains a string; its contents by default are an empty string (""
).
You can test for emptiness (using s.size() == 0
or s.empty()
).
There is also zzos. (Full disclosure: I wrote it). It only decompiles the actual resources, not the dex part (baksmali, which I did not write, does an excellent job of handling that part).
Zzos is much less known than apktool, but there are some APKs that are better handled by it (and vice versa - more on that later). Mostly, APKs containing custom resource types (not modifiers) were not handled by apktool the last time I checked, and are handled by zzos. There are also some cases with escaping that zzos handles better.
On the negative side of things, zzos (current version) requires a few support tools to install. It is written in perl (as opposed to APKTool, which is written in Java), and uses aapt for the actual decompilation. It also does not decompile attrib resources yet (which APKTool does).
The meaning of the name is "aapt", Android's resource compiler, shifted down one letter.
First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).
Second, the -vm argument in eclipse.ini
should point to the java executable. See
http://wiki.eclipse.org/Eclipse.ini for examples.
If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?
Try this options:
UserModel.find({}, function (err, users) {
//i got into errors using so i changed to res.send()
return res.send( JSON.parse(JSON.stringify(users)) );
//Or
//return JSON.parse(JSON.stringify(users));
}
A little helper function I always use in my projects for simple, speedy debugging via the console. Inspiration taken from Laravel.
/**
* @param variable mixed The var to log to the console
* @param varName string Optional, will appear as a label before the var
*/
function dd(variable, varName) {
var varNameOutput;
varName = varName || '';
varNameOutput = varName ? varName + ':' : '';
console.warn(varNameOutput, variable, ' (' + (typeof variable) + ')');
}
Usage
var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj');
A small note on custom attributes: HTML5 allows all kind of custom attributes, as long as they are prefixed with the particle data-
, i.e. data-my-attribute="true"
.
Just do this:
git checkout master
Or, if you have changes that you want to keep, do this:
git checkout -b temp
git checkout -B master temp
This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.
The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(42, 68)
);
As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.
Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:
The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null
. In other words, leaving the anchor null ensures the tip points where it is supposed to point.
However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.
By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.
var pinShadow = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
null,
null,
/* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
new google.maps.Point(40, 110),
new google.maps.Size(120, 110));
to give this:
You can use $emit
and $on
. Using @RoyJ code:
html:
<div id="app">
<my-component></my-component>
<button @click="click">Click</button>
</div>
javascript:
var Child = {
template: '<div>{{value}}</div>',
data: function () {
return {
value: 0
};
},
methods: {
setValue: function(value) {
this.value = value;
}
},
created: function() {
this.$parent.$on('update', this.setValue);
}
}
new Vue({
el: '#app',
components: {
'my-component': Child
},
methods: {
click: function() {
this.$emit('update', 7);
}
}
})
Running example: https://jsfiddle.net/rjurado/m2spy60r/1/
Nice one with a combination of array_slice
and implode
:
$arr = array(1, 2, 3);
echo implode(array_slice($arr, 0, 1));
// Outputs 1
/*---------------------------------*/
$arr = array(
'key_1' => 'One',
'key_2' => 'Two',
'key_3' => 'Three',
);
echo implode(array_slice($arr, 0, 1));
// Outputs One
Quote from this post (it's written by the author of doxygen himself) :
run doxygen -g and change the following options of the generated Doxyfile:
EXTRACT_ALL = YES
HAVE_DOT = YES
UML_LOOK = YES
run doxygen again
For me the Web API was Rails and client side Angular used with Restangular and FileSaver.js
Web API
module Api
module V1
class DownloadsController < BaseController
def show
@download = Download.find(params[:id])
send_data @download.blob_data
end
end
end
end
HTML
<a ng-click="download('foo')">download presentation</a>
Angular controller
$scope.download = function(type) {
return Download.get(type);
};
Angular Service
'use strict';
app.service('Download', function Download(Restangular) {
this.get = function(id) {
return Restangular.one('api/v1/downloads', id).withHttpConfig({responseType: 'arraybuffer'}).get().then(function(data){
console.log(data)
var blob = new Blob([data], {
type: "application/pdf"
});
//saveAs provided by FileSaver.js
saveAs(blob, id + '.pdf');
})
}
});
tray this:
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
inside onCreate()
;
Since I cannot comment, adding this note in addition to @jethro answer.
I found out that you also need to do the FOREIGN KEY line as the last part of create the table statement, otherwise you will get a syntax error when installing your app. What I mean is, you cannot do something like this:
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " (" + TASK_ID
+ " integer primary key autoincrement, " + TASK_TITLE
+ " text not null, " + TASK_NOTES + " text not null, "
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+" ("+CAT_ID+"), "
+ TASK_DATE_TIME + " text not null);";
Where I put the TASK_DATE_TIME after the foreign key line.
When you use a command substitution (i.e., the $(...)
construct), you are creating a subshell. Subshells inherit variables from their parent shells, but this only works one way: A subshell cannot modify the environment of its parent shell.
Your variable e
is set within a subshell, but not the parent shell. There are two ways to pass values from a subshell to its parent. First, you can output something to stdout, then capture it with a command substitution:
myfunc() {
echo "Hello"
}
var="$(myfunc)"
echo "$var"
The above outputs:
Hello
For a numerical value in the range of 0 through 255, you can use return
to pass the number as the exit status:
mysecondfunc() {
echo "Hello"
return 4
}
var="$(mysecondfunc)"
num_var=$?
echo "$var - num is $num_var"
This outputs:
Hello - num is 4
The "jQuery method" of determining the document size - query everything, take the highest value, and hope for the best - works in most cases, but not in all of them .
If you really need bullet-proof results for the document size, I'd suggest you use my jQuery.documentSize plugin. Unlike the other methods, it actually tests and evaluates browser behaviour when it is loaded and, based on the result, queries the right property from there on out.
The impact of this one-time test on performance is minimal, and the plugin returns the right results in even the weirdest scenarios - not because I say so, but because a massive, auto-generated test suite actually verifies that it does.
Because the plugin is written in vanilla Javascript, you can use it without jQuery, too.
def find_substring():
s = 'bobobnnnnbobmmmbosssbob'
cnt = 0
for i in range(len(s)):
if s[i:i+3] == 'bob':
cnt += 1
print 'bob found: ' + str(cnt)
return cnt
def main():
print(find_substring())
main()
What you're looking for is n choose k. Basically:
For every pair of 100 items, you'd have 4,950 combinations - provided order doesn't matter (AB and BA are considered a single combination) and you don't want to repeat (AA is not a valid pair).
In python
3.6.3 with pandas
0.22.0 you can also use concat
as long as you set as index the columns you want to use for the joining
pd.concat(
(iDF.set_index('name') for iDF in [df1, df2, df3]),
axis=1, join='inner'
).reset_index()
where df1
, df2
, and df3
are defined as in John Galt's answer
import pandas as pd
df1 = pd.DataFrame(np.array([
['a', 5, 9],
['b', 4, 61],
['c', 24, 9]]),
columns=['name', 'attr11', 'attr12']
)
df2 = pd.DataFrame(np.array([
['a', 5, 19],
['b', 14, 16],
['c', 4, 9]]),
columns=['name', 'attr21', 'attr22']
)
df3 = pd.DataFrame(np.array([
['a', 15, 49],
['b', 4, 36],
['c', 14, 9]]),
columns=['name', 'attr31', 'attr32']
)
the modern answer for this should be using Kotlin's no-arg compiler plugin
which creates a non argument construct code for classic apies more about here
simply you have to add the plugin class path in build.gradle project level
dependencies {
....
classpath "org.jetbrains.kotlin:kotlin-noarg:1.4.10"
....
}
then configure your annotation to generate the no-arg
constructor
apply plugin: "kotlin-noarg"
noArg {
annotation("your.path.to.annotaion.NoArg")
invokeInitializers = true
}
then define your annotation file NoArg.kt
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class NoArg
finally in any data class you can simply use your own annotation
@NoArg
data class SomeClass( val datafield:Type , ... )
I used to create my own no-arg
constructor as the accepted answer , which i got by search but then this plugin released or something and I found it way cleaner .
200 (cache) means Firefox is simply using the locally cached version. This is the fastest because no request to the Web server is made.
304 means Firefox is sending a "If-Modified-Since" conditional request to the Web server. If the file has not been updated since the date sent by the browser, the Web server returns a 304 response which essentially tells Firefox to use its cached version. It is not as fast as 200 (cache) because the request is still sent to the Web server, but the server doesn't have to send the contents of the file.
To your last question, I don't know why the two JavaScript files in the same directory are returning different results.
Remove the function and check the output of:
var_dump(function_exists('parseDate'));
In which case, change the name of the function.
If you get false, you're including the file with that function twice, replace :
include
by
include_once
And replace :
require
by
require_once
EDIT : I'm just a little too late, post before beat me to it !
To add ANDROID_HOME value permanently,
gedit ~/.bashrc
and add the following lines
export ANDROID_HOME=/root/Android/Sdk
PATH=$PATH:$ANDROID_HOME/tools
Save the file and you need not update ANDROID_HOME value everytime.
Linked List are more of an overhead to maintain than array, it also requires additional memory storage all these points are agreed. But there are a few things which array cant do. In many cases suppose you want an array of length 10^9 you can't get it because getting one continous memory location has to be there. Linked list could be a saviour here.
Suppose you want to store multiple things with data then they can be easily extended in the linked list.
STL containers usually have linked list implementation behind the scene.
Tested in Xcode 9.4, Swift 4 Another way to solve this issue is , You can add
override func layoutSubviews() {
self.frame = (self.superview?.bounds)!
}
in subview class.
add this at the top of file,
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
The easiest way is to use a for loop template tag.
Given the view:
def MyView(request):
...
query_results = YourModel.objects.all()
...
#return a response to your template and add query_results to the context
You can add a snippet like this your template...
<table>
<tr>
<th>Field 1</th>
...
<th>Field N</th>
</tr>
{% for item in query_results %}
<tr>
<td>{{ item.field1 }}</td>
...
<td>{{ item.fieldN }}</td>
</tr>
{% endfor %}
</table>
This is all covered in Part 3 of the Django tutorial. And here's Part 1 if you need to start there.
To resolve this issue, I had to do the following:
Once the DLLs are installed, you can add references to them using the method that Agent007 indicated in his answer.
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
I just discovered Telerik has some great components, including Grid, and they are open source too. http://demos.telerik.com/aspnet-mvc/
Every Driver service in selenium calls the similar code(following is the firefox specific code) while creating the driver object
@Override
protected File findDefaultExecutable() {
return findExecutable(
"geckodriver", GECKO_DRIVER_EXE_PROPERTY,
"https://github.com/mozilla/geckodriver",
"https://github.com/mozilla/geckodriver/releases");
}
now for the driver that you want to use, you have to set the system property with the value of path to the driver executable.
for firefox GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver" and this can be set before creating the driver object as below
System.setProperty("webdriver.gecko.driver", "./libs/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
What you need is named array. I wanted to write the following code:
int[] n = new int[4];
for(int i=1;i<4;i++)
{
n[i] = 5;
}
My philosophy is this:
Create an activity only if it's absolutely absolutely required. With the back stack made available for committing bunch of fragment transactions, I try to create as few activities in my app as possible. Also, communicating between various fragments is much easier than sending data back and forth between activities.
Activity transitions are expensive, right? At least I believe so - since the old activity has to be destroyed/paused/stopped, pushed onto the stack, and then the new activity has to be created/started/resumed.
It's just my philosophy since fragments were introduced.
/dt is the commad which lists you all the tables present in a database. using
/d command and /d+ we can get the details of a table. The sysntax will be like
* /d table_name (or) \d+ table_name
The one the eclipse run in is the default java installed in the system (unless set specifically in the eclipse.ini file, use the -vm option). You can of course add more Java runtimes and use them for your projects
The string you've written is the right one, but it is specific to your environment. If you want to know the exact update then run the following code:
public class JavaVersion {
public static void main(String[] args) {
System.out.println(System.getProperty("java.runtime.version"));
}
}
Use a FULL OUTER JOIN:
select
a.col_a,
a.col_b,
b.col_c
from
(select col_a,col_bfrom tab1) a
join
(select col_a,col_cfrom tab2) b
on a.col_a= b.col_a
The topic is quite old but still relevant in enterprise business contexts. I tried to avoid to touch the xsds in order to easily update them in the future. Here are my solutions..
xjc:simple
is sufficient<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jxb:bindings version="2.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
jxb:extensionBindingPrefixes="xjc">
<jxb:globalBindings>
<xjc:simple/> <!-- adds @XmlRootElement annotations -->
</jxb:globalBindings>
</jxb:bindings>
It will mostly create XmlRootElements for importing xsd definitions.
jaxb2-maven-plugin
executionsI have encountered that it makes a huge difference if you try to generate classes from multiple xsd definitions instead of a execution definition per xsd.
So if you have a definition with multiple <source>
's, than just try to split them:
<execution>
<id>xjc-schema-1</id>
<goals>
<goal>xjc</goal>
</goals>
<configuration>
<xjbSources>
<xjbSource>src/main/resources/xsd/binding.xjb</xjbSource>
</xjbSources>
<sources>
<source>src/main/resources/xsd/definition1/</source>
</sources>
<clearOutputDir>false</clearOutputDir>
</configuration>
</execution>
<execution>
<id>xjc-schema-2</id>
<goals>
<goal>xjc</goal>
</goals>
<configuration>
<xjbSources>
<xjbSource>src/main/resources/xsd/binding.xjb</xjbSource>
</xjbSources>
<sources>
<source>src/main/resources/xsd/definition2/</source>
</sources>
<clearOutputDir>false</clearOutputDir>
</configuration>
</execution>
The generator will not catch the fact that one class might be sufficient and therefore create custom classes per execution. And thats exactly what I need ;).
The xcodebuild
tool can build and export archive products with the -exportArchive flag (as of Xcode 5). The export step was previously only possible via the Xcode Organizer UI.
First archive your app:
xcodebuild -scheme <scheme name> archive
Given $ARCHIVE_PATH
(the path to the .xcarchive file), export the app from the archive with one of the following:
iOS .ipa file:
xcodebuild -exportArchive -exportFormat ipa -archivePath "$ARCHIVE_PATH" -exportPath "myApp.ipa" -exportProvisioningProfile "My App Provisioning profile"
Mac .app file:
xcodebuild -exportArchive -exportFormat app -archivePath "$ARCHIVE_PATH" -exportPath "myApp.app" -exportSigningIdentity "Developer ID Application: My Software Company"
In both commands the -exportProvisioningProfile and -exportSigningIdentity arguments are optional. man xcodebuild
for details on the semantics. In these examples, the provisioning profile for the iOS build specified an AdHoc distribution provisioning profile, and the signing identity for the Mac app specified a Developer ID for export as a 3rd party application (i.e. not distributed via the Mac App Store).
jQuery UI has it's own elements, but jQuery alone hasn't.
Working example:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
</head>
<body>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
</body>
</html>
Java doesn't normally accept "/" to use in defining a file directory, so try this:
File file = new File ("C:\\Users\\user\\workspace\\FileTester\\myFile.txt");
If the file doesn't exist do:
try {
file.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
If you are on Linux, then start the 'mysqld' with strace
, for eg strace ./mysqld
.
Among all the other system calls, you will find something like:
stat64("/etc/my.cnf", 0xbfa3d7fc) = -1 ENOENT (No such file or directory)
stat64("/etc/mysql/my.cnf", {st_mode=S_IFREG|0644, st_size=4227, ...}) = 0
open("/etc/mysql/my.cnf", O_RDONLY|O_LARGEFILE) = 3
So, as you can see..it lists the .cnf files, that it attempts to use and finally uses.
Everything seems to be perfect in your code except the fact that handleClick() isn't working because this function lacks a parameter in its function call invocation(but the function definition within has an argument which makes a function mismatch to occur).
The following is a sample working code for calculating all semester's total marks and corresponding grade. It demonstrates the use of a JavaScript function(call) within a html file and also solves the problem you are facing.
<!DOCTYPE html>
<html>
<head>
<title> Semester Results </title>
</head>
<body>
<h1> Semester Marks </h1> <br>
<script type = "text/javascript">
function checkMarks(total)
{
document.write("<h1> Final Result !!! </h1><br>");
document.write("Total Marks = " + total + "<br><br>");
var avg = total / 6.0;
document.write("CGPA = " + (avg / 10.0).toFixed(2) + "<br><br>");
if(avg >= 90)
document.write("Grade = A");
else if(avg >= 80)
document.write("Grade = B");
else if(avg >= 70)
document.write("Grade = C");
else if(avg >= 60)
document.write("Grade = D");
else if(avg >= 50)
document.write("Grade = Pass");
else
document.write("Grade = Fail");
}
</script>
<form name = "myform" action = "javascript:checkMarks(Number(s1.value) + Number(s2.value) + Number(s3.value) + Number(s4.value) + Number(s5.value) + Number(s6.value))"/>
Semester 1: <input type = "text" id = "s1"/> <br><br>
Semester 2: <input type = "text" id = "s2"/> <br><br>
Semester 3: <input type = "text" id = "s3"/> <br><br>
Semester 4: <input type = "text" id = "s4"/> <br><br>
Semester 5: <input type = "text" id = "s5"/> <br><br>
Semester 6: <input type = "text" id = "s6"/> <br><br><br>
<input type = "submit" value = "Submit"/>
</form>
</body>
</html>
You can programatically change it by setting the system property:
public class App {
public static void main(String[] args) {
System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE");
final org.slf4j.Logger log = LoggerFactory.getLogger(App.class);
log.trace("trace");
log.debug("debug");
log.info("info");
log.warn("warning");
log.error("error");
}
}
The log levels are ERROR > WARN > INFO > DEBUG > TRACE.
Please note that once the logger is created the log level can't be changed. If you need to dynamically change the logging level you might want to use log4j with SLF4J.
In your case you can just use strpos()
, or stripos()
for case insensitive search:
if (stripos($text, "world") !== false) {
echo "True";
}
If your git version does not have the --orphan option, this method should be used:
git symbolic-ref HEAD refs/heads/<newbranch>
rm .git/index
git clean -fdx
After doing some work:
git add -A
git commit -m <message>
git push origin <newbranch>
Try this instead ...
i=0
x="abc"
while i<len(x) :
print(x[i],end=" ")
print(i)
i+=1
Looks like you've got some answers to this, however I think there is something worth mentioning here that will greatly simplify your code. jQuery introduced the $.when
in v1.5. It looks like:
$.when($.ajax(...), $.ajax(...)).then(function (resp1, resp2) {
//this callback will be fired once all ajax calls have finished.
});
Didn't see it mentioned here, hope it helps.
Let me try a complex computation using datetime and considering nulls or empty spaces. I am reducing 30 years on a datetime column and using apply
method as well as lambda
and converting datetime format. Line if x != '' else x
will take care of all empty spaces or nulls accordingly.
df['Date'] = df['Date'].fillna('')
df['Date'] = df['Date'].apply(lambda x : ((datetime.datetime.strptime(str(x), '%m/%d/%Y') - datetime.timedelta(days=30*365)).strftime('%Y%m%d')) if x != '' else x)
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
Adding commons-logging.jar or commons-logging-1.1.jar will solve this...
Another way to do this is to use the numpy matrix
class (rather than a numpy array) and the I
attribute. For example:
>>> m = np.matrix([[2,3],[4,5]])
>>> m.I
matrix([[-2.5, 1.5],
[ 2. , -1. ]])
I believe you can do this using a Unicode encoding, but I doubt this is what you really want.
The ==
is the unicode value 2A76 so I belive you can do this:
char c = '\u2A76';
I can't test this at the moment but I'd be interested to know if that works for you.
You will need to dig around for the others. Here is a unicode table if you want to look:
If your iframe is from another domain, (cross domain), you will simply need to use this:
var currentUrl = document.referrer;
and - here you've got the main url!
I use the following command to reload Nginx (version 1.5.9) only if a configuration test was successful:
/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload
If you need to do this often, you may want to use an alias. I use the following:
alias n='/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload'
The trick here is done by the "&&" which only executes the second command if the first was successful. You can see here a more detailed explanation of the use of the "&&" operator.
You can use "restart" instead of "reload" if you really want to restart the server.
I had the same issue. It seems the easiest solution is to just remove the remote, readd it, and fetch.
The date function would be defined something like this:
function date($format, $timestamp = null)
{
if ($timestamp === null) {
$timestamp = time();
}
// Format the timestamp according to $format
}
Usually, you would put the default value like this:
function foo($required, $optional = 42)
{
// This function can be passed one or more arguments
}
However, only literals are valid default arguments, which is why I used null
as default argument in the first example, not $timestamp = time()
, and combined it with a null check. Literals include arrays (array()
or []
), booleans, numbers, strings, and null
.
You can change the number format of the column to this custom format:
0;-0;;@
which will hide all 0 values.
To do this, select the column, right-click > Format Cells > Custom.
No, it is not okay to put a link
element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):
“This element defines a link. Unlike
A
, it may only appear in theHEAD
section of a document, although it may appear any number of times.”
What's the difference? => A lot.
I think, the this
version is used to enable encapsulation, i.e. data hiding.
It helps to manipulate private variables.
Let us look at the following example:
var AdultPerson = function() {
var age;
this.setAge = function(val) {
// some housekeeping
age = val >= 18 && val;
};
this.getAge = function() {
return age;
};
this.isValid = function() {
return !!age;
};
};
Now, the prototype
structure can be applied as following:
Different adults have different ages, but all of the adults get the same rights.
So, we add it using prototype, rather than this.
AdultPerson.prototype.getRights = function() {
// Should be valid
return this.isValid() && ['Booze', 'Drive'];
};
Lets look at the implementation now.
var p1 = new AdultPerson;
p1.setAge(12); // ( age = false )
console.log(p1.getRights()); // false ( Kid alert! )
p1.setAge(19); // ( age = 19 )
console.log(p1.getRights()); // ['Booze', 'Drive'] ( Welcome AdultPerson )
var p2 = new AdultPerson;
p2.setAge(45);
console.log(p2.getRights()); // The same getRights() method, *** not a new copy of it ***
Hope this helps.
I am using OS X Mavericks (version 10.9)
and when I run the above I got the following message: If builds of PostgreSQL 9 are failing and you have version 8.x installed.
So I run the following command:
ARCHFLAGS="-arch x86_64" gem install pg
and this worked for me, I hope this helps someone :)
1: C is a type of computer programming language. While embedded C is a set of language extensions for the C Programming language.
2: C has a free-format program source code, in a desktop computer. while embedded C has different format based on embedded processor (micro- controllers/microprocessors).
3: C have normal optimization, in programming. while embedded C high level optimization in programming.
4: C programming must have required operating system. while embedded C may or may not be required operating system.
5: C can use resources from OS, memory, etc, i.e all resources from desktop computer can be used by C. while embedded C can use limited resources, like RAM, ROM, and I/Os on an embedded processor.
Try sudo npm uninstall cordova -g
to uninstall it globally and then just npm install cordova
without the -g flag after cd
ing to the local app directory
Windows task manager > Processes > find tomcat > right click > open file location > if you run Tomcat7w.exe it is visible at description.
Tomcat should running to be visible at Processes if not at Windows Vista/7 go to task manager > tab (services) find tomcat start it and then processes.
Set your header and footer position to "absolute" and that should do the trick. Hope it helps and good luck with your project!
X.each_with_index do |item, index|
puts "current_index: #{index}"
end
The correct approach in Angularjs is to use ng-value
for non-string values of models.
Modify your code like this:
<label data-ng-repeat="choice in question.choices">
<input type="radio" name="response" data-ng-model="choice.isUserAnswer" data-ng-value="true" />
{{choice.text}}
</label>
The simplest way:
Directory.Delete(path,true);
Directory.CreateDirectory(path);
Be aware that this may wipe out some permissions on the folder.
EDIT: Yes, you can; but you have to cheat: The currently running class name is present on the call stack, and the traceback
module allows you to access the stack.
>>> import traceback
>>> def get_input(class_name):
... return class_name.encode('rot13')
...
>>> class foo(object):
... _name = traceback.extract_stack()[-1][2]
... input = get_input(_name)
...
>>>
>>> foo.input
'sbb'
However, I wouldn't do this; My original answer is still my own preference as a solution. Original answer:
probably the very simplest solution is to use a decorator, which is similar to Ned's answer involving metaclasses, but less powerful (decorators are capable of black magic, but metaclasses are capable of ancient, occult black magic)
>>> def get_input(class_name):
... return class_name.encode('rot13')
...
>>> def inputize(cls):
... cls.input = get_input(cls.__name__)
... return cls
...
>>> @inputize
... class foo(object):
... pass
...
>>> foo.input
'sbb'
>>>
With small custom synchronization context, sync function can wait for completion of async function, without creating deadlock. Here is small example for WinForms app.
Imports System.Threading
Imports System.Runtime.CompilerServices
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SyncMethod()
End Sub
' waiting inside Sync method for finishing async method
Public Sub SyncMethod()
Dim sc As New SC
sc.WaitForTask(AsyncMethod())
sc.Release()
End Sub
Public Async Function AsyncMethod() As Task(Of Boolean)
Await Task.Delay(1000)
Return True
End Function
End Class
Public Class SC
Inherits SynchronizationContext
Dim OldContext As SynchronizationContext
Dim ContextThread As Thread
Sub New()
OldContext = SynchronizationContext.Current
ContextThread = Thread.CurrentThread
SynchronizationContext.SetSynchronizationContext(Me)
End Sub
Dim DataAcquired As New Object
Dim WorkWaitingCount As Long = 0
Dim ExtProc As SendOrPostCallback
Dim ExtProcArg As Object
<MethodImpl(MethodImplOptions.Synchronized)>
Public Overrides Sub Post(d As SendOrPostCallback, state As Object)
Interlocked.Increment(WorkWaitingCount)
Monitor.Enter(DataAcquired)
ExtProc = d
ExtProcArg = state
AwakeThread()
Monitor.Wait(DataAcquired)
Monitor.Exit(DataAcquired)
End Sub
Dim ThreadSleep As Long = 0
Private Sub AwakeThread()
If Interlocked.Read(ThreadSleep) > 0 Then ContextThread.Resume()
End Sub
Public Sub WaitForTask(Tsk As Task)
Dim aw = Tsk.GetAwaiter
If aw.IsCompleted Then Exit Sub
While Interlocked.Read(WorkWaitingCount) > 0 Or aw.IsCompleted = False
If Interlocked.Read(WorkWaitingCount) = 0 Then
Interlocked.Increment(ThreadSleep)
ContextThread.Suspend()
Interlocked.Decrement(ThreadSleep)
Else
Interlocked.Decrement(WorkWaitingCount)
Monitor.Enter(DataAcquired)
Dim Proc = ExtProc
Dim ProcArg = ExtProcArg
Monitor.Pulse(DataAcquired)
Monitor.Exit(DataAcquired)
Proc(ProcArg)
End If
End While
End Sub
Public Sub Release()
SynchronizationContext.SetSynchronizationContext(OldContext)
End Sub
End Class
You need to either put the code below the HTML or load if using the document load event:
<input type="text" id="goal-input" name="goal" />
<script type="text/javascript">
$(function(){
$("#goal-input").focus();
});
</script>
Update:
Switching divs doesn't trigger the document load event since everything already have been loaded. You need to focus it when you switch div:
if (goal) {
step1.fadeOut('fast', function() {
step1.hide();
step2.fadeIn('fast', function() {
$("#name").focus();
});
});
}
std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K
and V
.
Also bear in mind that std::sort
requires a strict weak ordeing comparison, and <=
does not satisfy that. You would need, for example, a less-than comparison <
for K
and V
. With that in place, all you need is
std::vector<pair<K,V>> items;
std::sort(items.begin(), items.end());
If you really need to provide your own comparison function, then you need something along the lines of
template <typename K, typename V>
bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
{
return lhs.first < rhs.first;
}
From ggplot 2.2.0
labels can easily be stacked by using position = position_stack(vjust = 0.5)
in geom_text
.
ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5))
Also note that "position_stack()
and position_fill()
now stack values in the reverse order of the grouping, which makes the default stack order match the legend."
Answer valid for older versions of ggplot
:
Here is one approach, which calculates the midpoints of the bars.
library(ggplot2)
library(plyr)
# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year),
transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)
# library(dplyr) ## If using dplyr...
# Data <- group_by(Data,Year) %>%
# mutate(pos = cumsum(Frequency) - (0.5 * Frequency))
# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
geom_bar(aes(fill = Category), stat="identity") +
geom_text(aes(label = Frequency, y = pos), size = 3)
You did not need
Options Indexes FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order Allow,Deny
Allow from all
Require all granted
the only thing what you need is...
Require all granted
...inside the directory section.
See Apache 2.4 upgrading side:
If you are dealing with a large df (40m x 700 in my case) it works much faster and memory savvy through iteration on columns with something like.
for col in df.columns:
df[col][df[col] < 0] = 0
I had an issue with duplicate entries in one table itself. Below is the approaches were working for me. It has also been advocated by @sibaz.
Finally I solved it using the below queries:
The select query is saved in a temp table
IF OBJECT_ID(N'tempdb..#New_format_donor_temp', N'U') IS NOT NULL
DROP TABLE #New_format_donor_temp;
select *
into #New_format_donor_temp
from DONOR_EMPLOYMENTS
where DONOR_ID IN (
1, 2
)
-- Test New_format_donor_temp
-- SELECT *
-- FROM #New_format_donor_temp;
The temp table is joined in the update query.
UPDATE de
SET STATUS_CD=de_new.STATUS_CD, STATUS_REASON_CD=de_new.STATUS_REASON_CD, TYPE_CD=de_new.TYPE_CD
FROM DONOR_EMPLOYMENTS AS de
INNER JOIN #New_format_donor_temp AS de_new ON de_new.EMP_NO = de.EMP_NO
WHERE
de.DONOR_ID IN (
3, 4
)
I not very experienced with SQL please advise any better approach you know.
Above queries are for MySql server.
You can order by address_id in an subquery, then order by what you want in an outer query.
SELECT * FROM
(SELECT DISTINCT ON (address_id) purchases.address_id, purchases.*
FROM "purchases"
WHERE "purchases"."product_id" = 1 ORDER BY address_id DESC )
ORDER BY purchased_at DESC
Another variation of answer suggested by JAR.JAR.beans
(Math.random()*1e32).toString(36)
By changing multiplicator 1e32
you can change length of random string.
Open your php.ini file (If you are using Linux - sudo vim /etc/php5/apache2/php.ini)
Add this lines into that file
error_reporting = E_ALL & ~E_WARNING
(If you need to disabled any other errors -> error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE & ~E_WARNING)
display_errors = On
And finally you need to restart your APACHE server.
Yes. Only comments and the end tag for the html element are allowed after the end tag for the body.
Browsers may perform error recovery, but you should never depend on that.
tl;dr: baz() { this.foo(); this.bar() }
In ES2015 this construct:
var obj = {
foo() { console.log('foo') }
}
is equal to this ES5 code:
var obj = {
foo : function foo() { console.log('foo') }
}
exports.default = {}
is like creating an object, your default export translates to ES5 code like this:
exports['default'] = {
foo: function foo() {
console.log('foo');
},
bar: function bar() {
console.log('bar');
},
baz: function baz() {
foo();bar();
}
};
now it's kind of obvious (I hope) that baz
tries to call foo
and bar
defined somewhere in the outer scope, which are undefined. But this.foo
and this.bar
will resolve to the keys defined in exports['default']
object. So the default export referencing its own methods shold look like this:
export default {
foo() { console.log('foo') },
bar() { console.log('bar') },
baz() { this.foo(); this.bar() }
}
Does that work in IE6?
No, IE6 does not support attribute selectors at all, cf. CSS Compatibility and Internet Explorer.
You might find How to workaround: IE6 does not support CSS “attribute” selectors worth the read.
EDIT
If you are to ignore IE6, you could do (CSS2.1):
input[type=submit][disabled=disabled],
button[disabled=disabled] {
...
}
CSS3 (IE9+):
input[type=submit]:disabled,
button:disabled {
...
}
You can substitute [disabled=disabled]
(attribute value) with [disabled]
(attribute presence).
Swift 4+
button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
You can write a jQuery function like this to determine if an element is in the viewport.
Include this somewhere after jQuery is included:
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
Sample usage:
$(window).on('resize scroll', function() {
if ($('#Something').isInViewport()) {
// do something
} else {
// do something else
}
});
Note that this only checks the top and bottom positions of elements, it doesn't check if an element is outside of the viewport horizontally.
For me, the following also worked in Jenkins 2 (2.73.3)
Replace
def pa = new ParametersAction([new StringParameterValue("FOO", foo)])
build.addAction(pa)
with
def pa = new ParametersAction([new StringParameterValue("FOO", foo)], ["FOO"])
build.addAction(pa)
ParametersAction seems to have a second constructor which allows to pass in "additionalSafeParameters" https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/model/ParametersAction.java
If you want to use your custom pipe in your components, you can add
@Injectable({
providedIn: 'root'
})
annotation to your custom pipe. Then, you can use it as a service
The ViewBag
is an System.Dynamic.ExpandoObject
as suggested. The properties in the ViewBag
are essentially KeyValue
pairs, where you access the value by the key. In this sense these are equivalent:
ViewBag.Foo = "Bar";
ViewBag["Foo"] = "Bar";
ADD following -
It's works for me.
Dockerfile comments start with '#', just like Python. Here is a good example (kstaken/dockerfile-examples):
# Install a more-up-to date version of MongoDB than what is included in the default Ubuntu repositories.
FROM ubuntu
MAINTAINER Kimbro Staken
RUN apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
RUN echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | tee -a /etc/apt/sources.list.d/10gen.list
RUN apt-get update
RUN apt-get -y install apt-utils
RUN apt-get -y install mongodb-10gen
#RUN echo "" >> /etc/mongodb.conf
CMD ["/usr/bin/mongod", "--config", "/etc/mongodb.conf"]
I recommend you to check docs section dedicated for Loop to get better understanding. Some snippet taken from there:
We have two calls that are similar as far as users are concerned, but their names are confusing.
process.nextTick() fires immediately on the same phase
setImmediate() fires on the following iteration or 'tick' of the
event loop
In essence, the names should be swapped. process.nextTick() fires more immediately than setImmediate(), but this is an artifact of the past which is unlikely to change.
Oracle Workshop for WebLogic (formally BEA Workshop) has excellent support for JavaScript and for visually editing HTMLs. It support many servers, not only WebLogic, including Tomcat, JBoss, Resin, Jetty, and WebSphere.
It recently became free, check out my post about it. Given that it was an expensive product not long ago, I guess it's worth checking out.
// Save search term state to React Hooks with spread operator and wrapper function
// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query))
// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query))
// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query])
// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query])
https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc
In workbench 6.0 Connect to any of the database. You will see two tabs.
1.Management
2. Schemas
By default Schemas
tab is selected.
Select Management
tab
then select Data Export
.
You will get list of all databases.
select the desired database and and the file name and ther options you wish and start export.
You are done with backup.
try: typeof(predQuery[preId])=='undefined'
or more generally: typeof(yourArray[yourIndex])=='undefined'
You're comparing "undefined" to undefined, which returns false =)
Your code looks syntactically correct, but I think your property doesn't exist to create the URL.
I just tested it, and it works fine for me.
Try using category.idCategory
instead of category.id
, for example…
<tr th:each="category : ${categories}">
<td th:text="${category.idCategory}"></td>
<td th:text="${category.name}"></td>
<td>
<a th:href="@{'/category/edit/' + ${category.idCategory}}">view</a>
</td>
</tr>
I think the JavaScriptSerializer does not create a dynamic object.
So you should define the class first:
class MyObj {
public int arg1 {get;set;}
public int arg2 {get;set;}
}
And deserialize that instead of object
:
serializer.Deserialize<MyObj>(str);
Not testet, please try.
Try
import sys
print(sys.version)
This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.
You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.
A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.
Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1
Here's an example of a union from my own codebase (from memory and paraphrased so it may not be exact). It was used to store language elements in an interpreter I built. For example, the following code:
set a to b times 7.
consists of the following language elements:
Language elements were defines as '#define
' values thus:
#define ELEM_SYM_SET 0
#define ELEM_SYM_TO 1
#define ELEM_SYM_TIMES 2
#define ELEM_SYM_FULLSTOP 3
#define ELEM_VARIABLE 100
#define ELEM_CONSTANT 101
and the following structure was used to store each element:
typedef struct {
int typ;
union {
char *str;
int val;
}
} tElem;
then the size of each element was the size of the maximum union (4 bytes for the typ and 4 bytes for the union, though those are typical values, the actual sizes depend on the implementation).
In order to create a "set" element, you would use:
tElem e;
e.typ = ELEM_SYM_SET;
In order to create a "variable[b]" element, you would use:
tElem e;
e.typ = ELEM_VARIABLE;
e.str = strdup ("b"); // make sure you free this later
In order to create a "constant[7]" element, you would use:
tElem e;
e.typ = ELEM_CONSTANT;
e.val = 7;
and you could easily expand it to include floats (float flt
) or rationals (struct ratnl {int num; int denom;}
) and other types.
The basic premise is that the str
and val
are not contiguous in memory, they actually overlap, so it's a way of getting a different view on the same block of memory, illustrated here, where the structure is based at memory location 0x1010
and integers and pointers are both 4 bytes:
+-----------+
0x1010 | |
0x1011 | typ |
0x1012 | |
0x1013 | |
+-----+-----+
0x1014 | | |
0x1015 | str | val |
0x1016 | | |
0x1017 | | |
+-----+-----+
If it were just in a structure, it would look like this:
+-------+
0x1010 | |
0x1011 | typ |
0x1012 | |
0x1013 | |
+-------+
0x1014 | |
0x1015 | str |
0x1016 | |
0x1017 | |
+-------+
0x1018 | |
0x1019 | val |
0x101A | |
0x101B | |
+-------+