You can add reference of Microsoft.Office.Core
from COM components tab in the add reference window by adding reference of Microsoft Office 12.0 Object Library
. The screen shot will shows what component you need.
After much research and testing, I have developed a solution for an app I'm currently converting from Android/iOS to Flutter.
With Android and iOS I used a 'Scaling Factor' applied to base font sizes, rendering text sizes that were relative to the screen size.
This article was very helpful: https://medium.com/flutter-community/flutter-effectively-scale-ui-according-to-different-screen-sizes-2cb7c115ea0a
I created a StatelessWidget to get the font sizes of the Material Design typographical styles. Getting device dimensions using MediaQuery, calculating a scaling factor, then resetting the Material Design text sizes. The Widget can be used to define a custom Material Design Theme.
Emulators used:
set_app_theme.dart (SetAppTheme Widget)
import 'package:flutter/material.dart';
import 'dart:math';
class SetAppTheme extends StatelessWidget {
final Widget child;
SetAppTheme({this.child});
@override
Widget build(BuildContext context) {
final _divisor = 400.0;
final MediaQueryData _mediaQueryData = MediaQuery.of(context);
final _screenWidth = _mediaQueryData.size.width;
final _factorHorizontal = _screenWidth / _divisor;
final _screenHeight = _mediaQueryData.size.height;
final _factorVertical = _screenHeight / _divisor;
final _textScalingFactor = min(_factorVertical, _factorHorizontal);
final _safeAreaHorizontal = _mediaQueryData.padding.left + _mediaQueryData.padding.right;
final _safeFactorHorizontal = (_screenWidth - _safeAreaHorizontal) / _divisor;
final _safeAreaVertical = _mediaQueryData.padding.top + _mediaQueryData.padding.bottom;
final _safeFactorVertical = (_screenHeight - _safeAreaVertical) / _divisor;
final _safeAreaTextScalingFactor = min(_safeFactorHorizontal, _safeFactorHorizontal);
print('Screen Scaling Values:' + '_screenWidth: $_screenWidth');
print('Screen Scaling Values:' + '_factorHorizontal: $_factorHorizontal ');
print('Screen Scaling Values:' + '_screenHeight: $_screenHeight');
print('Screen Scaling Values:' + '_factorVertical: $_factorVertical ');
print('_textScalingFactor: $_textScalingFactor ');
print('Screen Scaling Values:' + '_safeAreaHorizontal: $_safeAreaHorizontal ');
print('Screen Scaling Values:' + '_safeFactorHorizontal: $_safeFactorHorizontal ');
print('Screen Scaling Values:' + '_safeAreaVertical: $_safeAreaVertical ');
print('Screen Scaling Values:' + '_safeFactorVertical: $_safeFactorVertical ');
print('_safeAreaTextScalingFactor: $_safeAreaTextScalingFactor ');
print('Default Material Design Text Themes');
print('display4: ${Theme.of(context).textTheme.display4}');
print('display3: ${Theme.of(context).textTheme.display3}');
print('display2: ${Theme.of(context).textTheme.display2}');
print('display1: ${Theme.of(context).textTheme.display1}');
print('headline: ${Theme.of(context).textTheme.headline}');
print('title: ${Theme.of(context).textTheme.title}');
print('subtitle: ${Theme.of(context).textTheme.subtitle}');
print('body2: ${Theme.of(context).textTheme.body2}');
print('body1: ${Theme.of(context).textTheme.body1}');
print('caption: ${Theme.of(context).textTheme.caption}');
print('button: ${Theme.of(context).textTheme.button}');
TextScalingFactors _textScalingFactors = TextScalingFactors(
display4ScaledSize: (Theme.of(context).textTheme.display4.fontSize * _safeAreaTextScalingFactor),
display3ScaledSize: (Theme.of(context).textTheme.display3.fontSize * _safeAreaTextScalingFactor),
display2ScaledSize: (Theme.of(context).textTheme.display2.fontSize * _safeAreaTextScalingFactor),
display1ScaledSize: (Theme.of(context).textTheme.display1.fontSize * _safeAreaTextScalingFactor),
headlineScaledSize: (Theme.of(context).textTheme.headline.fontSize * _safeAreaTextScalingFactor),
titleScaledSize: (Theme.of(context).textTheme.title.fontSize * _safeAreaTextScalingFactor),
subtitleScaledSize: (Theme.of(context).textTheme.subtitle.fontSize * _safeAreaTextScalingFactor),
body2ScaledSize: (Theme.of(context).textTheme.body2.fontSize * _safeAreaTextScalingFactor),
body1ScaledSize: (Theme.of(context).textTheme.body1.fontSize * _safeAreaTextScalingFactor),
captionScaledSize: (Theme.of(context).textTheme.caption.fontSize * _safeAreaTextScalingFactor),
buttonScaledSize: (Theme.of(context).textTheme.button.fontSize * _safeAreaTextScalingFactor));
return Theme(
child: child,
data: _buildAppTheme(_textScalingFactors),
);
}
}
final ThemeData customTheme = ThemeData(
primarySwatch: appColorSwatch,
// fontFamily: x,
);
final MaterialColor appColorSwatch = MaterialColor(0xFF3787AD, appSwatchColors);
Map<int, Color> appSwatchColors =
{
50 : Color(0xFFE3F5F8),
100 : Color(0xFFB8E4ED),
200 : Color(0xFF8DD3E3),
300 : Color(0xFF6BC1D8),
400 : Color(0xFF56B4D2),
500 : Color(0xFF48A8CD),
600 : Color(0xFF419ABF),
700 : Color(0xFF3787AD),
800 : Color(0xFF337799),
900 : Color(0xFF285877),
};
_buildAppTheme (TextScalingFactors textScalingFactors) {
return customTheme.copyWith(
accentColor: appColorSwatch[300],
buttonTheme: customTheme.buttonTheme.copyWith(buttonColor: Colors.grey[500],),
cardColor: Colors.white,
errorColor: Colors.red,
inputDecorationTheme: InputDecorationTheme(border: OutlineInputBorder(),),
primaryColor: appColorSwatch[700],
primaryIconTheme: customTheme.iconTheme.copyWith(color: appColorSwatch),
scaffoldBackgroundColor: Colors.grey[100],
textSelectionColor: appColorSwatch[300],
textTheme: _buildAppTextTheme(customTheme.textTheme, textScalingFactors),
appBarTheme: customTheme.appBarTheme.copyWith(
textTheme: _buildAppTextTheme(customTheme.textTheme, textScalingFactors)),
// accentColorBrightness: ,
// accentIconTheme: ,
// accentTextTheme: ,
// appBarTheme: ,
// applyElevationOverlayColor: ,
// backgroundColor: ,
// bannerTheme: ,
// bottomAppBarColor: ,
// bottomAppBarTheme: ,
// bottomSheetTheme: ,
// brightness: ,
// buttonBarTheme: ,
// buttonColor: ,
// canvasColor: ,
// cardTheme: ,
// chipTheme: ,
// colorScheme: ,
// cupertinoOverrideTheme: ,
// cursorColor: ,
// dialogBackgroundColor: ,
// dialogTheme: ,
// disabledColor: ,
// dividerColor: ,
// dividerTheme: ,
// floatingActionButtonTheme: ,
// focusColor: ,
// highlightColor: ,
// hintColor: ,
// hoverColor: ,
// iconTheme: ,
// indicatorColor: ,
// materialTapTargetSize: ,
// pageTransitionsTheme: ,
// platform: ,
// popupMenuTheme: ,
// primaryColorBrightness: ,
// primaryColorDark: ,
// primaryColorLight: ,
// primaryTextTheme: ,
// secondaryHeaderColor: ,
// selectedRowColor: ,
// sliderTheme: ,
// snackBarTheme: ,
// splashColor: ,
// splashFactory: ,
// tabBarTheme: ,
// textSelectionHandleColor: ,
// toggleableActiveColor: ,
// toggleButtonsTheme: ,
// tooltipTheme: ,
// typography: ,
// unselectedWidgetColor: ,
);
}
class TextScalingFactors {
final double display4ScaledSize;
final double display3ScaledSize;
final double display2ScaledSize;
final double display1ScaledSize;
final double headlineScaledSize;
final double titleScaledSize;
final double subtitleScaledSize;
final double body2ScaledSize;
final double body1ScaledSize;
final double captionScaledSize;
final double buttonScaledSize;
TextScalingFactors({
@required this.display4ScaledSize,
@required this.display3ScaledSize,
@required this.display2ScaledSize,
@required this.display1ScaledSize,
@required this.headlineScaledSize,
@required this.titleScaledSize,
@required this.subtitleScaledSize,
@required this.body2ScaledSize,
@required this.body1ScaledSize,
@required this.captionScaledSize,
@required this.buttonScaledSize
});
}
TextTheme _buildAppTextTheme(
TextTheme _customTextTheme,
TextScalingFactors _scaledText) {
return _customTextTheme.copyWith(
display4: _customTextTheme.display4.copyWith(fontSize: _scaledText.display4ScaledSize),
display3: _customTextTheme.display3.copyWith(fontSize: _scaledText.display3ScaledSize),
display2: _customTextTheme.display2.copyWith(fontSize: _scaledText.display2ScaledSize),
display1: _customTextTheme.display1.copyWith(fontSize: _scaledText.display1ScaledSize),
headline: _customTextTheme.headline.copyWith(fontSize: _scaledText.headlineScaledSize),
title: _customTextTheme.title.copyWith(fontSize: _scaledText.titleScaledSize),
subtitle: _customTextTheme.subtitle.copyWith(fontSize: _scaledText.subtitleScaledSize),
body2: _customTextTheme.body2.copyWith(fontSize: _scaledText.body2ScaledSize),
body1: _customTextTheme.body1.copyWith(fontSize: _scaledText.body1ScaledSize),
caption: _customTextTheme.caption.copyWith(fontSize: _scaledText.captionScaledSize),
button: _customTextTheme.button.copyWith(fontSize: _scaledText.buttonScaledSize),
).apply(bodyColor: Colors.black);
}
main.dart (Demo App)
import 'package:flutter/material.dart';
import 'package:scaling/set_app_theme.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SetAppTheme(child: HomePage()),
);
}
}
class HomePage extends StatelessWidget {
final demoText = '0123456789';
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Text Scaling with SetAppTheme',
style: TextStyle(color: Colors.white),),
),
body: SingleChildScrollView(
child: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.display4.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.display3.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.display2.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.display1.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.headline.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.title.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.subtitle.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.body2.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.body1.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.caption.fontSize,
),
),
Text(
demoText,
style: TextStyle(
fontSize: Theme.of(context).textTheme.button.fontSize,
),
),
],
),
),
),
),
),
);
}
}
they're listed in /proc/net/tcp.
it's the second column, after the ":", in hex:
> cat /proc/net/tcp
sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
0: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 10863 1 ffff88020c785400 99 0 0 10 -1
1: 0100007F:0277 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 7983 1 ffff88020eb7b3c0 99 0 0 10 -1
2: 0500010A:948F 0900010A:2328 01 00000000:00000000 02:00000576 00000000 1000 0 10562454 2 ffff88010040f7c0 22 3 30 5 3
3: 0500010A:E077 5F2F7D4A:0050 01 00000000:00000000 02:00000176 00000000 1000 0 10701021 2 ffff880100474080 41 3 22 10 -1
4: 0500010A:8773 16EC97D1:0050 01 00000000:00000000 02:00000BDC 00000000 1000 0 10700849 2 ffff880104335440 57 3 18 10 -1
5: 0500010A:8772 16EC97D1:0050 01 00000000:00000000 02:00000BF5 00000000 1000 0 10698952 2 ffff88010040e440 46 3 0 10 -1
6: 0500010A:DD2C 0900010A:0016 01 00000000:00000000 02:0006E764 00000000 1000 0 9562907 2 ffff880104334740 22 3 30 5 4
7: 0500010A:AAA4 6A717D4A:0050 08 00000000:00000001 02:00000929 00000000 1000 0 10696677 2 ffff880106cc77c0 45 3 0 10 -1
so i guess one of those :50
in the third column must be stackoverflow :o)
look in man 5 proc
for more details. and picking that apart with sed etc is left as an exercise for the gentle reader...
The following produces more general k-fold cross-validation splits. Your 50-50 partitioning would be achieved by making k=2
below, all you would have to to is to pick one of the two partitions produced. Note: I haven't tested the code, but I'm pretty sure it should work.
import random, math
def k_fold(myfile, myseed=11109, k=3):
# Load data
data = open(myfile).readlines()
# Shuffle input
random.seed=myseed
random.shuffle(data)
# Compute partition size given input k
len_part=int(math.ceil(len(data)/float(k)))
# Create one partition per fold
train={}
test={}
for ii in range(k):
test[ii] = data[ii*len_part:ii*len_part+len_part]
train[ii] = [jj for jj in data if jj not in test[ii]]
return train, test
1:
[{value:5}, {value:10}].reduce((previousValue, currentValue) => { return {value: previousValue.value + currentValue.value}})
>> Object {value: 15}
2:
[{value:5}, {value:10}].map(item => item.value).reduce((previousValue, currentValue) => {return previousValue + currentValue })
>> 15
3:
[{value:5}, {value:10}].reduce(function (previousValue, currentValue) {
return {value: previousValue.value + currentValue.value};
})
>> Object {value: 15}
I would like to share what I understood from this keyword. This keyword has 6 usages in java as follows:-
1. It can be used to refer to the current class variable. Let us understand with a code.*
Let's understand the problem if we don't use this keyword by the example given below:
class Employee{
int id_no;
String name;
float salary;
Student(int id_no,String name,float salary){
id_no = id_no;
name=name;
salary = salary;
}
void display(){System.out.println(id_no +" "+name+" "+ salary);}
}
class TestThis1{
public static void main(String args[]){
Employee s1=new Employee(111,"ankit",5000f);
Employee s2=new Employee(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:-
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.
class Employee{
int id_no;
String name;
float salary;
Student(int id_no,String name,float salary){
this.id_no = id_no;
this.name=name;
this.salary = salary;
}
void display(){System.out.println(id_no +" "+name+" "+ salary);}
}
class TestThis1{
public static void main(String args[]){
Employee s1=new Employee(111,"ankit",5000f);
Employee s2=new Employee(112,"sumit",6000f);
s1.display();
s2.display();
}}
output:
111 ankit 5000
112 sumit 6000
2. To invoke the current class method.
class A{
void m(){System.out.println("hello Mandy");}
void n(){
System.out.println("hello Natasha");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output:
hello Natasha
hello Mandy
3. to invoke the current class constructor. It is used to constructor chaining.
class A{
A(){System.out.println("hello ABCD");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Output:
hello ABCD
10
4. to pass as an argument in the method.
class S2{
void m(S2 obj){
System.out.println("The method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
Output:
The method is invoked
5. to pass as an argument in the constructor call
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:-
10
6. to return current class instance
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:-
Hello
Also, this keyword cannot be used without .(dot) as it's syntax is invalid.
The first set of errors, for the missing vtable, are caused because you do not implement takeaway::textualGame()
; instead you implement a non-member function, textualGame()
. I think that adding the missing takeaway::
will fix that.
The cause of the last error is that you're calling a virtual function, initialData()
, from the constructor of gameCore
. At this stage, virtual functions are dispatched according to the type currently being constructed (gameCore
), not the most derived class (takeaway
). This particular function is pure virtual, and so calling it here gives undefined behaviour.
Two possible solutions:
gameCore
out of the constructor and into a separate initialisation function, which must be called after the object is fully constructed; orgameCore
into two classes: an abstract interface to be implemented by takeaway
, and a concrete class containing the state. Construct takeaway
first, and then pass it (via a reference to the interface class) to the constructor of the concrete class.I would recommend the second, as it is a move towards smaller classes and looser coupling, and it will be harder to use the classes incorrectly. The first is more error-prone, as there is no way be sure that the initialisation function is called correctly.
One final point: the destructor of a base class should usually either be virtual (to allow polymorphic deletion) or protected (to prevent invalid polymorphic deletion).
You don't need to change the compliance level here, or rather, you should but that's not the issue.
The code compliance ensures your code is compatible with a given Java version.
For instance, if you have a code compliance targeting Java 6, you can't use Java 7's or 8's new syntax features (e.g. the diamond, the lambdas, etc. etc.).
The actual issue here is that you are trying to compile something in a Java version that seems different from the project dependencies in the classpath.
Instead, you should check the JDK/JRE you're using to build.
In Eclipse, open the project properties and check the selected JRE in the Java build path.
If you're using custom Ant (etc.) scripts, you also want to take a look there, in case the above is not sufficient per se.
Consider:
Double.isFinite (value) && Double.compare (value, StrictMath.rint (value)) == 0
This sticks to core Java and avoids an equality comparison between floating point values (==
) which is consdered bad. The isFinite()
is necessary as rint()
will pass-through infinity values.
Why do you use new Array();
for hash? You need to use new Object()
instead.
And i think you will get what you want.
If you already have logging enabled and you still get this error on Windows 7 64 bit, try this in IIS 7.5:
Create a new application pool
Go to the Advanced Settings of this application pool
Set the Enable 32-Bit Application to True
Point your web application to use this new pool
I am a little late to party but you may want to consider using GetAwaiter.GetResult() to run your async code in sync context but as paralled as below;
Parallel.ForEach(ids, i =>
{
ICustomerRepo repo = new CustomerRepo();
// Run this in thread which Parallel library occupied.
var cust = repo.GetCustomer(i).GetAwaiter().GetResult();
customers.Add(cust);
});
I found vanila solution
var hasScrollbar = function() {_x000D_
// The Modern solution_x000D_
if (typeof window.innerWidth === 'number')_x000D_
return window.innerWidth > document.documentElement.clientWidth_x000D_
_x000D_
// rootElem for quirksmode_x000D_
var rootElem = document.documentElement || document.body_x000D_
_x000D_
// Check overflow style property on body for fauxscrollbars_x000D_
var overflowStyle_x000D_
_x000D_
if (typeof rootElem.currentStyle !== 'undefined')_x000D_
overflowStyle = rootElem.currentStyle.overflow_x000D_
_x000D_
overflowStyle = overflowStyle || window.getComputedStyle(rootElem, '').overflow_x000D_
_x000D_
// Also need to check the Y axis overflow_x000D_
var overflowYStyle_x000D_
_x000D_
if (typeof rootElem.currentStyle !== 'undefined')_x000D_
overflowYStyle = rootElem.currentStyle.overflowY_x000D_
_x000D_
overflowYStyle = overflowYStyle || window.getComputedStyle(rootElem, '').overflowY_x000D_
_x000D_
var contentOverflows = rootElem.scrollHeight > rootElem.clientHeight_x000D_
var overflowShown = /^(visible|auto)$/.test(overflowStyle) || /^(visible|auto)$/.test(overflowYStyle)_x000D_
var alwaysShowScroll = overflowStyle === 'scroll' || overflowYStyle === 'scroll'_x000D_
_x000D_
return (contentOverflows && overflowShown) || (alwaysShowScroll)_x000D_
}
_x000D_
I wrestled with this problem and implemented the URL concatenation solution contributed by @Kushan in the accepted answer above. It worked in my local MySql instance. But when I deployed my Play/Scala app to Heroku it no longer would work. Heroku also concatenates several args to the DB URL that they provide users, and this solution, because of Heroku's use concatenation of "?" before their own set of args, will not work. However I found a different solution which seems to work equally well.
SET sql_mode = 'NO_ZERO_DATE';
I put this in my table descriptions and it solved the problem of '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp
The 2018 ES6+ ANSWER IS:
const arr = [1, 2, 3];
arr.forEach((val, key, arr) => {
if (Object.is(arr.length - 1, key)) {
// execute last item logic
console.log(`Last callback call at index ${key} with value ${val}` );
}
});
<script type="text/javascript">
function idleTimer() {
var t;
//window.onload = resetTimer;
window.onmousemove = resetTimer; // catches mouse movements
window.onmousedown = resetTimer; // catches mouse movements
window.onclick = resetTimer; // catches mouse clicks
window.onscroll = resetTimer; // catches scrolling
window.onkeypress = resetTimer; //catches keyboard actions
function logout() {
window.location.href = 'logout.php'; //Adapt to actual logout script
}
function reload() {
window.location = self.location.href; //Reloads the current page
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, 1800000); // time is in milliseconds (1000 is 1 second)
t= setTimeout(reload, 300000); // time is in milliseconds (1000 is 1 second)
}
}
idleTimer();
</script>
Instead of strtotime
you should use DateTime
with PHP. You can also regard the timezone this way:
$dt = DateTime::createFromFormat('Y-m-d H:i:s', $mysqltime, new DateTimeZone('Europe/Berlin'));
$unix_timestamp = $dt->getTimestamp();
$mysqltime
is of type MySQL Datetime, e. g. 2018-02-26 07:53:00
.
.val()
always works with textarea
elements.
.text()
works sometimes and fails other times! It's not reliable (tested in Chrome 33)
What's best is that .val()
works seamlessly with other form elements too (like input
) whereas .text()
fails.
Do you want to iterate over characters or words?
For words, you'll have to split the words first, such as
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index
This prints the index of the word.
For the absolute character position you'd need something like
chars = 0
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
chars += len(word) + 1
If your SQL database allows Null values for that field try using int? value
like that :
if (this.txtboxname.Text == "" || this.txtboxname.text == null)
value = null;
else
value = Convert.ToInt32(this.txtboxname.Text);
Take care that Convert.ToInt32 of a null value returns 0 !
Convert.ToInt32(null) returns 0
If anybody is interested in using regex with CLR here is a solution. The function below (C# .net 4.5) returns a 1 if the pattern is matched and a 0 if the pattern is not matched. I use it to tag lines in sub queries. The SQLfunction attribute tells sql server that this method is the actual UDF that SQL server will use. Save the file as a dll in a place where you can access it from management studio.
// default using statements above
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text.RegularExpressions;
namespace CLR_Functions
{
public class myFunctions
{
[SqlFunction]
public static SqlInt16 RegexContain(SqlString text, SqlString pattern)
{
SqlInt16 returnVal = 0;
try
{
string myText = text.ToString();
string myPattern = pattern.ToString();
MatchCollection mc = Regex.Matches(myText, myPattern);
if (mc.Count > 0)
{
returnVal = 1;
}
}
catch
{
returnVal = 0;
}
return returnVal;
}
}
}
In management studio import the dll file via programability -- assemblies -- new assembly
Then run this query:
CREATE FUNCTION RegexContain(@text NVARCHAR(50), @pattern NVARCHAR(50))
RETURNS smallint
AS
EXTERNAL NAME CLR_Functions.[CLR_Functions.myFunctions].RegexContain
Then you should have complete access to the function via the database you stored the assembly in.
Then use in queries like so:
SELECT *
FROM
(
SELECT
DailyLog.Date,
DailyLog.Researcher,
DailyLog.team,
DailyLog.field,
DailyLog.EntityID,
DailyLog.[From],
DailyLog.[To],
dbo.RegexContain(Researcher, '[\p{L}\s]+') as 'is null values'
FROM [DailyOps].[dbo].[DailyLog]
) AS a
WHERE a.[is null values] = 0
Okay so you are trying to get a bitmap from a file? Title says URL. Anyways, when you are getting files from external storage in Android you should never use a direct path. Instead call getExternalStorageDirectory() like so:
File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/" + PATH_TO_IMAGE);
Bitmap bitmap = BitmapFactory.decodeFile(bitmapFile);
getExternalStorageDirectory() gives you the path to the SD card. Also you need to declare the WRITE_EXTERNAL_STORAGE permission in the Manifest.
You need to use GROUP BY
instead of DISTINCT
if you want to use aggregation functions.
SELECT title, MIN(date)
FROM table
GROUP BY title
From Dianne Hackborn:
Things That Cannot Change:
The most obvious and visible of these is the “manifest package name,” the unique name you give to your application in its AndroidManifest.xml. The name uses a Java-language-style naming convention, with Internet domain ownership helping to avoid name collisions. For example, since Google owns the domain “google.com”, the manifest package names of all of our applications should start with “com.google.” It’s important for developers to follow this convention in order to avoid conflicts with other developers.
Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application.
More on things you cannot change here
Regarding your question on the URL from Google Play, the package defined there is linked to the app's fully qualified package you have in your AndroidManifest.xml file. More on Google Play's link formats here.
You want to use regexp_substr()
for this. This should work for your example:
select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t
Here, by the way, is the SQL Fiddle.
Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace()
for the first part:
select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t
And here is this corresponding SQL Fiddle.
Enjoy this :) Without cast each value individually.
SELECT ...,
IsCoursedBased = CAST(
CASE WHEN fc.CourseId is not null THEN 1 ELSE 0 END
AS BIT
)
FROM fc
You can do it easily by using JUnit or TestNG framework. Do the assertion as below:
String actualTitle = driver.getTitle();
String expectedTitle = "Title of Page";
assertEquals(expectedTitle,actualTitle);
OR,
assertTrue(driver.getTitle().contains("Title of Page"));
Just tested:
Run the following command:
sudo shred -u /etc/ssh/*_key /etc/ssh/*_key.pub
Then:
A new Append<TSource>
method has been added to IEnumerable<TSource>
since .NET Framework 4.7.1 and .NET Core 1.0.
Here is how to use it:
var numbers = new [] { "one", "two", "three" };
numbers = numbers.Append("four").ToArray();
Console.WriteLine(string.Join(", ", numbers)); // one, two, three, four
Note that if you want to add the element at the beginning of the array, you can use the new Prepend<TSource>
method instead.
Lets talk about different scope in 'C'
SCOPE: It is basically how long can I see something and how far.
Local variable : Scope is only inside a function. It resides in the STACK area of RAM. Which means that every time a function gets called all the variables that are the part of that function, including function arguments are freshly created and are destroyed once the control goes out of the function. (Because the stack is flushed every time function returns)
Static variable: Scope of this is for a file. It is accessible every where in the file
in which it is declared. It resides in the DATA segment of RAM. Since
this can only be accessed inside a file and hence INTERNAL linkage. Any
other files cannot see this variable. In fact STATIC keyword is the
only way in which we can introduce some level of data or function
hiding in 'C'
Global variable: Scope of this is for an entire application. It is accessible form every where of the application. Global variables also resides in DATA segment Since it can be accessed every where in the application and hence EXTERNAL Linkage
By default all functions are global. In case, if you need to hide some functions in a file from outside, you can prefix the static keyword to the function. :-)
This problem happened for me only in special cases, when I called website from some internet providers,
I've configured only ip v4 in VirtualHost configuration of apache, but some of router use ip v6, and when I added ip v6 to apache config the problem solved.
Try the following code:
public static byte[] decode(String hex){
String[] list=hex.split("(?<=\\G.{2})");
ByteBuffer buffer= ByteBuffer.allocate(list.length);
System.out.println(list.length);
for(String str: list)
buffer.put(Byte.parseByte(str,16));
return buffer.array();
}
To convert to String just create a new String with the byte[] returned by the decode method.
Instead of doing file_put_contents(***WebSiteURL***...)
you need to use the server path to /cache/lang/file.php
(e.g. /home/content/site/folders/filename.php
).
You cannot open a file over HTTP
and expect it to be written. Instead you need to open it using the local path.
You could use a character class ([./-]
) so that the seperators can be any of the defined characters
var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/
Or better still, match the character class for the first seperator, then capture that as a group ([./-])
and use a reference to the captured group \1
to match the second seperator, which will ensure that both seperators are the same:
var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/
"22-03-1981".match(dateReg) // matches
"22.03-1981".match(dateReg) // does not match
"22.03.1981".match(dateReg) // matches
Code:
using System;
using System.Diagnostics;
namespace playSound
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(args[0]);
Process amixerMediaProcess = new Process();
amixerMediaProcess.StartInfo.CreateNoWindow = false;
amixerMediaProcess.StartInfo.UseShellExecute = false;
amixerMediaProcess.StartInfo.ErrorDialog = false;
amixerMediaProcess.StartInfo.RedirectStandardOutput = false;
amixerMediaProcess.StartInfo.RedirectStandardInput = false;
amixerMediaProcess.StartInfo.RedirectStandardError = false;
amixerMediaProcess.EnableRaisingEvents = true;
amixerMediaProcess.StartInfo.Arguments = string.Format("{0}","-ssh username@"+args[0]+" -pw password -m commands.txt");
amixerMediaProcess.StartInfo.FileName = "plink.exe";
amixerMediaProcess.Start();
Console.Write("Presskey to continue . . . ");
Console.ReadKey(true);
}
}
}
Sample commands.txt:
ps
My solution was to remove @objc from Custom class definition.
Note that I prefer the code to be short.
List<ListItem> selected = CBLGold.Items.Cast<ListItem>()
.Where(li => li.Selected)
.ToList();
or with a simple foreach
:
List<ListItem> selected = new List<ListItem>();
foreach (ListItem item in CBLGold.Items)
if (item.Selected) selected.Add(item);
If you just want the ListItem.Value
:
List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.ToList();
An easy way to do this with some jQuery and straight JavaScript, just view your console in Chrome or Firefox to see the output...
var queries = {};
$.each(document.location.search.substr(1).split('&'),function(c,q){
var i = q.split('=');
queries[i[0].toString()] = i[1].toString();
});
console.log(queries);
The following uses EventTrigger
to show the Popup
. This means we don't need a ToggleButton
for state binding.
In this example the Click
event of a Button
is used. You can adapt it to use another element/event combination.
<Button x:Name="OpenPopup">Popup
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames
Storyboard.TargetName="ContextPopup"
Storyboard.TargetProperty="IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Button.Triggers>
</Button>
<Popup x:Name="ContextPopup"
PlacementTarget="{Binding ElementName=OpenPopup}"
StaysOpen="False">
<Label>Popupcontent...</Label>
</Popup>
Please note that the Popup
is referencing the Button
by name and vice versa. So x:Name="..."
is required on both, the Popup
and the Button
.
It can actually be further simplified by replacing the Storyboard
stuff with a custom SetProperty
EventTrigger Action described in this SO Answer
CASE might help you out:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
WHEN status_flag = STATUS_INACTIVE THEN 'T'
ELSE null END)
AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
WHEN source_flag = SOURCE_USER THEN 'users'
ELSE null END)
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.
Here is another solution using flexbox but without using flex-end for bottom alignment. The idea is to set margin-bottom
on h1 to auto to push the remaining content to the bottom:
#header {_x000D_
height: 350px;_x000D_
display:flex;_x000D_
flex-direction:column;_x000D_
border:1px solid;_x000D_
}_x000D_
_x000D_
#header h1 {_x000D_
margin-bottom:auto;_x000D_
}
_x000D_
<div id="header">_x000D_
<h1>Header title</h1>_x000D_
Header content (one or multiple lines) Header content (one or multiple lines)Header content (one or multiple lines) Header content (one or multiple lines)_x000D_
</div>
_x000D_
We can also do the same with margin-top:auto
on the text but in this case we need to wrap it inside a div
or span
:
#header {_x000D_
height: 350px;_x000D_
display:flex;_x000D_
flex-direction:column;_x000D_
border:1px solid;_x000D_
}_x000D_
_x000D_
#header span {_x000D_
margin-top:auto;_x000D_
}
_x000D_
<div id="header">_x000D_
<h1>Header title</h1>_x000D_
<span>Header content (one or multiple lines)</span>_x000D_
</div>
_x000D_
svn log --verbose -r 42
You can use this on any element where onclick works:
onclick="window.open('some.htm','_blank');"
def SecondLargest(x):
largest = max(x[0],x[1])
largest2 = min(x[0],x[1])
for item in x:
if item > largest:
largest2 = largest
largest = item
elif largest2 < item and item < largest:
largest2 = item
return largest2
SecondLargest([20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7])
Very useful I had a slightly different scenario where I the request xml was itself the body of the POST and not a param. For that the following code can be used - Posting as an answer just in case anyone else having similar issue will benefit.
final HttpHeaders headers = new HttpHeaders();
headers.add("header1", "9998");
headers.add("username", "xxxxx");
headers.add("password", "xxxxx");
headers.add("header2", "yyyyyy");
headers.add("header3", "zzzzz");
headers.setContentType(MediaType.APPLICATION_XML);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
final HttpEntity<MyXmlbeansRequestDocument> httpEntity = new HttpEntity<MyXmlbeansRequestDocument>(
MyXmlbeansRequestDocument.Factory.parse(request), headers);
final ResponseEntity<MyXmlbeansResponseDocument> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity,MyXmlbeansResponseDocument.class);
log.info(responseEntity.getBody());
Java and Kotlin runs on Java Virtual Machine (JVM).
Converting a Kotlin file to Java file involves two steps i.e. compiling the Kotlin code to the JVM bytecode and then decompile the bytecode to the Java code.
Steps to convert your Kotlin source file to Java source file:
use this type it works for me . windows 7 with python 2.7 and django 1.5
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'C:\\tool\\mysite\\data.db',
hope its works...
Here's a more concise approach...
df['a_bsum'] = df.groupby('A')['B'].transform(sum)
df.sort(['a_bsum','C'], ascending=[True, False]).drop('a_bsum', axis=1)
The first line adds a column to the data frame with the groupwise sum. The second line performs the sort and then removes the extra column.
Result:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
NOTE: sort
is deprecated, use sort_values
instead
DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
if(result == DialogResult.Yes)
{
//...
}
else if (result == DialogResult.No)
{
//...
}
else
{
//...
}
Probably is the use of the "on" event that Bootstrap use a lot and was inserted at jQuery 1.7 http://api.jquery.com/on/
Nope, no difference. It's just syntactic sugar. Arrays.asList(..)
creates an additional list.
If all you want to do is conditionally show or hide a <div>, then you could declare it as an <asp:panel > (renders to html as a div tag) and set it's .Visible property.
Found a solution:
mysql> UPDATE table SET last_update=now(), last_monitor=last_update WHERE id=1;
I found this in MySQL Docs and after a few tests it works:
the following statement sets col2 to the current (updated) col1 value, not the original col1 value. The result is that col1 and col2 have the same value. This behavior differs from standard SQL.
UPDATE t1 SET col1 = col1 + 1, col2 = col1;
You must must be in your Laravel Project Folder
When creating a new project with laravel new project-name
, a folder will be created with your project name as name. You must get in that folder before using any php artisan
command like php artisan serve
because the artisan file is in that folder
Well, first you need to select the elements with a function like getElementById
.
var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];
getElementById
only returns one node, but getElementsByClassName
returns a node list. Since there is only one element with that class name (as far as I can tell), you can just get the first one (that's what the [0]
is for—it's just like an array).
Then, you can change the html with .textContent
.
targetDiv.textContent = "Goodbye world!";
var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];_x000D_
targetDiv.textContent = "Goodbye world!";
_x000D_
<div id="foo">_x000D_
<div class="bar">_x000D_
Hello world!_x000D_
</div>_x000D_
</div>
_x000D_
I imagine this like that:
<html>
<head>
<script>
var frame_loaded = 0;
function setFrameLoaded()
{
frame_loaded = 1;
alert("Iframe is loaded");
}
$('#click').click(function(){
if(frame_loaded == 1)
console.log('iframe loaded')
} else {
console.log('iframe not loaded')
}
})
</script>
</head>
<button id='click'>click me</button>
<iframe id='MainPopupIframe' onload='setFrameLoaded();' src='http://...' />...</iframe>
I've found that you can move div elements to the next line simply by setting the property
Display: block;
On each div.
I've read about a bug in Xcode 6 which prevents landscape only apps from displaying a launch image.
Try to set images and orientation within Images.xcassets:
If you want to print wall cell execution time here is a trick, use
%%time
<--code goes here-->
but here make sure that, the %%time is a magic function, so put it at first line in your code.
if you put it after some line of your code it's going to give you usage error and not gonna work.
I just went through this issue and none of the suggestions solved my problem. While I was unable to start MySQL on boot and found the same message in the logs ("Another MySQL daemon already running with the same unix socket"), I was able to start the service once I arrived at the console.
In my configuration file, I found the following line: bind-address=xx.x.x.x
. I randomly decided to comment it out, and the error on boot disappeared. Because the bind address provides security, in a way, I decided to explore it further. I was using the machine's IP address, rather than the IPv4 loopback address - 127.0.0.1
.
In short, by using 127.0.0.1
as the bind-address
, I was able to fix this error. I hope this helps those who have this problem, but are unable to resolve it using the answers detailed above.
Try this code
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
//You can get
}
return super.onOptionsItemSelected(item);
}
Add below code to your onCreate() metod
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
METHOD1->
Since origin already exist remove it.
git remote rm origin
git remote add origin https://github.com/USERNAME/REPOSITORY.git
METHOD2->
One can also change existing remote repository URL by ->git remote set-url
If you're updating to use HTTPS
git remote set-url origin https://github.com/USERNAME/REPOSITORY.git
If you're updating to use SSH
git remote set-url origin [email protected]:USERNAME/REPOSITORY.git
If trying to update a remote that doesn't exist you will receive a error. So be careful of that.
METHOD3->
Use the git remote rename command to rename an existing remote. An existing remote name, for example, origin.
git remote rename origin startpoint
# Change remote name from 'origin' to 'startpoint'
To verify remote's new name->
git remote -v
If new to Git try this tutorial->
This simple thing worked for me!
If it says it can't do 2 things at same time, separate them.
git branch branch_name origin/branch_name
git checkout branch_name
Try this:
response.write(JSON.stringify(request.body));
That will take the object which bodyParser
has created for you and turn it back into a string and write it to the response. If you want the exact request body (with the same whitespace, etc), you will need data
and end
listeners attached to the request before and build up the string chunk by chunk as you can see in the json parsing source code from connect.
try this one out resizeable button
<button type="submit me" style="height: 25px; width: 100px">submit me</button>
So, say you have your View with PartialView, which have to be updated by button click:
<div class="target">
@{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
There are some ways to do it. For example you may use jQuery:
<script type="text/javascript">
$(function(){
$('.button').on("click", function(){
$.post('@Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.target').load('/Home/UpdatePoints');
})
});
});
</script>
PostActionToUpdatePoints
is your Action
with [HttpPost]
attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
Specific Table Migration
php artisan migrate --path=/database/migrations/fileName.php
You are specifying .fixedbutton
in your CSS (a class) and specifying the id
on the element itself.
Change your CSS to the following, which will select the id
fixedbutton
#fixedbutton {
position: fixed;
bottom: 0px;
right: 0px;
}
You can use this QString constructor for conversion from QByteArray to QString:
QString(const QByteArray &ba)
QByteArray data;
QString DataAsString = QString(data);
we can simply copy the code from tostring of object class to get the reference of string
class Test
{
public static void main(String args[])
{
String a="nikhil"; // it stores in String constant pool
String s=new String("nikhil"); //with new stores in heap
System.out.println(Integer.toHexString(System.identityHashCode(a)));
System.out.println(Integer.toHexString(System.identityHashCode(s)));
}
}
I recommend using Spring's @ControllerAdvice
to handle errors. Read this guide for a good introduction, starting at the section named "Spring Boot Error Handling". For an in-depth discussion, there's an article in the Spring.io blog that was updated on April, 2018.
A brief summary on how this works:
ResponseEntity<Success>
. It will not be responsible for returning error or exception responses.@ControllerAdvice
@ExceptionHandler
ResponseEntity<Error>
With this approach, you only need to implement your controller exception handling in one place for all endpoints in your API. It also makes it easy for your API to have a uniform exception response structure across all endpoints. This simplifies exception handling for your clients.
Right now there is no view:clear command. For laravel 4 this can probably help you: https://gist.github.com/cjonstrup/8228165
Disabling caching can be done by skipping blade. View caching is done because blade compiling each time is a waste of time.
Use:
<!-- For Google -->
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<meta name="copyright" content="" />
<meta name="application-name" content="" />
<!-- For Facebook -->
<meta property="og:title" content="" />
<meta property="og:type" content="article" />
<meta property="og:image" content="" />
<meta property="og:url" content="" />
<meta property="og:description" content="" />
<!-- For Twitter -->
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="" />
<meta name="twitter:description" content="" />
<meta name="twitter:image" content="" />
Fill the content =" ... " according to the content of your page.
For more information, visit 18 Meta Tags Every Webpage Should Have in 2013.
Why not just use the WordPress get_query_var()
function? WordPress Code Reference
// Test if the query exists at the URL
if ( get_query_var('ppc') ) {
// If so echo the value
echo get_query_var('ppc');
}
Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php
by adding an action during initialization:
add_action('init','add_get_val');
function add_get_val() {
global $wp;
$wp->add_query_var('ppc');
}
Or by adding a hook to the query_vars filter:
function add_query_vars_filter( $vars ){
$vars[] = "ppc";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
I have the same problem. I avoid it with remove.packages("Package making this confusion")
and it works. In my case, I don't need the second package, so that is not a very good idea.
you can add method in LoginController add line use App\User;
on Top, after this add method, it is work for me wkwkwkwkw , but you must add {{ csrf_field() }}
on view admin and user
protected function authenticated(Request $request, $user){
$user=User::where('email',$request->input('email'))->pluck('jabatan');
$c=" ".$user." ";
$a=strcmp($c,' ["admin"] ');
if ($a==0) {
return redirect('admin');
}else{
return redirect('user');
}}
In Visual Studio 2012, open the Options dialog (Tools -> Options). Under Environment -> General, the first setting is "Color theme." You can use this to switch between Light and Dark.
The shell theme is distinct from the editor theme--you can use any editor fonts and colors settings with either shell theme.
There is also a Color Theme Editor extension that can be used to create new themes.
From what I see you just try to see if they are equal, if this is true
, just go with something like this:
boolean areEqual = Arrays.equals(arr1, arr2);
This is the standard way of doing it.
Please note that the arrays must be also sorted to be considered equal, from the JavaDoc:
Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order.
Sorry for missing that.
Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.
int64_t delayInSeconds = 0.6;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
do something to the button(s)
});
I found that when inserting, the null column values had to be specifically declared as NULL, otherwise I would get a constraint violation error (as opposed to an empty string).
I'm not sure you have gotten past this yet, but I had to work on something very similar today and I got your fiddle working like you are asking, basically what I did was make another table row under it, and then used the accordion control. I tried using just collapse but could not get it working and saw an example somewhere on SO that used accordion.
Here's your updated fiddle: http://jsfiddle.net/whytheday/2Dj7Y/11/
Since I need to post code here is what each collapsible "section" should look like ->
<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
<td>1</td>
<td>05 May 2013</td>
<td>Credit Account</td>
<td class="text-success">$150.00</td>
<td class="text-error"></td>
<td class="text-success">$150.00</td>
</tr>
<tr>
<td colspan="6" class="hiddenRow">
<div class="accordion-body collapse" id="demo1">Demo1</div>
</td>
</tr>
I had modified my answer tons of times and realized i don't have to say anything, python had explained itself already.
a = 'string'
a.replace('t', '_')
print(a)
>>> 'string'
a = a.replace('t', '_')
print(a)
>>> 's_ring'
b = 100
b + 1
print(b)
>>> 100
b = b + 1
print(b)
>>> 101
def test_id(arg):
c = id(arg)
arg = 123
d = id(arg)
return
a = 'test ids'
b = id(a)
test_id(a)
e = id(a)
# b = c = e != d
# this function do change original value
del change_like_mutable(arg):
arg.append(1)
arg.insert(0, 9)
arg.remove(2)
return
test_1 = [1, 2, 3]
change_like_mutable(test_1)
# this function doesn't
def wont_change_like_str(arg):
arg = [1, 2, 3]
return
test_2 = [1, 1, 1]
wont_change_like_str(test_2)
print("Doesn't change like a imutable", test_2)
This devil is not the reference / value / mutable or not / instance, name space or variable / list or str, IT IS THE SYNTAX, EQUAL SIGN.
To send mail through SQL Server we need to set up DB mail profile we can either use T-SQl or SQL Database mail option in sql server to create profile. After below code is used to send mail through query or stored procedure.
Use below link to create DB mail profile
http://www.freshcodehub.com/Article/42/configure-database-mail-in-sql-server-database
http://www.freshcodehub.com/Article/43/create-a-database-mail-configuration-using-t-sql-script
--Sending Test Mail_x000D_
EXEC msdb.dbo.sp_send_dbmail_x000D_
@profile_name = 'TestProfile', _x000D_
@recipients = 'To Email Here', _x000D_
@copy_recipients ='CC Email Here', --For CC Email if exists_x000D_
@blind_copy_recipients= 'BCC Email Here', --For BCC Email if exists_x000D_
@subject = 'Mail Subject Here', _x000D_
@body = 'Mail Body Here',_x000D_
@body_format='HTML',_x000D_
@importance ='HIGH',_x000D_
@file_attachments='C:\Test.pdf'; --For Attachments if exists
_x000D_
I have had the same problem (on several different servers). Applying SP3 and Report Viewer SP1 has helped on some of the servers, allowing the client machines to connect and download the control with no problem. However, I have had one server that, even after applying the updates, when accessing the report viewer using a client machine, it was still giving me the error. On looking into the exact URL GET request that is being sent, I discovered that it is possible to force the client machine to connect directly to the Report Server to download the control.
The user would need to enter the following url:
This should then pop up the required download/install prompt.
A very common issue not described yet that front-end coders often run into is the scope that is visible to an inline event handler in the HTML - for example, with
<button onclick="foo()"></button>
The scope of the variables that an on*
attribute can reference must be either:
querySelector
as a standalone variable will point to document.querySelector
; rare)Otherwise, you'll get a ReferenceError when the handler is invoked. So, for example, if the inline handler references a function which is defined inside window.onload
or $(function() {
, the reference will fail, because the inline handler may only reference variables in the global scope, and the function is not global:
window.addEventListener('DOMContentLoaded', () => {_x000D_
function foo() {_x000D_
console.log('foo running');_x000D_
}_x000D_
});
_x000D_
<button onclick="foo()">click</button>
_x000D_
Properties of the document
and properties of the element the handler is attached to may also be referenced as standalone variables inside inline handlers because inline handlers are invoked inside of two with
blocks, one for the document
, one for the element. The scope chain of variables inside these handlers is extremely unintuitive, and a working event handler will probably require a function to be global (and unnecessary global pollution should probably be avoided).
Since the scope chain inside inline handlers is so weird, and since inline handlers require global pollution to work, and since inline handlers sometimes require ugly string escaping when passing arguments, it's probably easier to avoid them. Instead, attach event handlers using Javascript (like with addEventListener
), rather than with HTML markup.
function foo() {_x000D_
console.log('foo running');_x000D_
}_x000D_
document.querySelector('.my-button').addEventListener('click', foo);
_x000D_
<button class="my-button">click</button>
_x000D_
On a different note, unlike normal <script>
tags, which run on the top level, code inside ES6 modules runs in its own private scope. A variable defined at the top of a normal <script>
tag is global, so you can reference it in other <script>
tags, like this:
<script>_x000D_
const foo = 'foo';_x000D_
</script>_x000D_
<script>_x000D_
console.log(foo);_x000D_
</script>
_x000D_
But the top level of an ES6 module is not global. A variable declared at the top of an ES6 module will only be visible inside that module, unless the variable is explicitly export
ed, or unless it's assigned to a property of the global object.
<script type="module">_x000D_
const foo = 'foo';_x000D_
</script>_x000D_
<script>_x000D_
// Can't access foo here, because the other script is a module_x000D_
console.log(typeof foo);_x000D_
</script>
_x000D_
The top level of an ES6 module is similar to that of the inside of an IIFE on the top level in a normal <script>
. The module can reference any variables which are global, and nothing can reference anything inside the module unless the module is explicitly designed for it.
There is conditional assignment in Python 2.5 and later - the syntax is not very obvious hence it's easy to miss. Here's how you do it:
x = true_value if condition else false_value
For further reference, check out the Python 2.5 docs.
Another approach is to use pickle. See this answer to a duplicate of this question.
SET A uses short-circuiting boolean operators.
What 'short-circuiting' means in the context of boolean operators is that for a set of booleans b1, b2, ..., bn, the short circuit versions will cease evaluation as soon as the first of these booleans is true (||) or false (&&).
For example:
// 2 == 2 will never get evaluated because it is already clear from evaluating
// 1 != 1 that the result will be false.
(1 != 1) && (2 == 2)
// 2 != 2 will never get evaluated because it is already clear from evaluating
// 1 == 1 that the result will be true.
(1 == 1) || (2 != 2)
If you will use the new list later, you can simply set the elem to None, and then judge it in the later loop, like this
for i in li:
i = None
for elem in li:
if elem is None:
continue
In this way, you dont't need copy the list and it's easier to understand.
If you're OK with not using <p>
s (only <div>
s and <span>
s), this solution might even allow you to align your inline-block
s center or right, if you want to (or just keep them left, the way you originally asked for). While the solution might still work with <p>
s, I don't think the resulting HTML code would be quite correct, but it's up to you anyways.
The trick is to wrap each one of your <span>
s with a corresponding <div>
. This way we're taking advantage of the line break caused by the <div>
's display: block
(default), while still keeping the visual green box tight to the limits of the text (with your display: inline-block
declaration).
.text span {_x000D_
background:rgba(165, 220, 79, 0.8);_x000D_
display:inline-block;_x000D_
padding:7px 10px;_x000D_
color:white;_x000D_
}_x000D_
.large { font-size:80px }
_x000D_
<div class="text">_x000D_
<div><span class="medium">We</span></div>_x000D_
<div><span class="large">build</span></div>_x000D_
<div><span class="medium">the</span></div>_x000D_
<div><span class="large">Internet</span></div>_x000D_
</div>
_x000D_
Simply skip the error using .values
at the end.
affinity_matrix.loc['sums'] = affinity_matrix.sum(axis=0).values
The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).
you can use your verbal #{your verbal}
By far the easiest way is by using TaskFactory.FromAsync from the TPL. It's literally a couple of lines of code when used in conjunction with the new async/await keywords:
var request = WebRequest.Create("http://www.stackoverflow.com");
var response = (HttpWebResponse) await Task.Factory
.FromAsync<WebResponse>(request.BeginGetResponse,
request.EndGetResponse,
null);
Debug.Assert(response.StatusCode == HttpStatusCode.OK);
If you can't use the C#5 compiler then the above can be accomplished using the Task.ContinueWith method:
Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,
request.EndGetResponse,
null)
.ContinueWith(task =>
{
var response = (HttpWebResponse) task.Result;
Debug.Assert(response.StatusCode == HttpStatusCode.OK);
});
According to this article:
JavaScript is a scripting language developed by Netscape Communications designed for developing client and server Internet applications. Netscape Navigator is designed to interpret JavaScript embedded into Web pages. JavaScript is independent of Sun Microsystem's Java language.
Microsoft JScript is an open implementation of Netscape's JavaScript. JScript is a high-performance scripting language designed to create active online content for the World Wide Web. JScript allows developers to link and automate a wide variety of objects in Web pages, including ActiveX controls and Java programs. Microsoft Internet Explorer is designed to interpret JScript embedded into Web pages.
There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).
Start the SQL service again and use the new created login (recovery in my example) Go via the security panel to the properties and change the password of the SA account.
Now write down the new SA password.
Don't know why, but only thing that worked for me was using asset_path instead of image_path, even though my images are under the assets/images/ directory:
Example:
app/assets/images/mypic.png
In Ruby:
asset_path('mypic.png')
In .scss:
url(asset-path('mypic.png'))
UPDATE:
Figured it out- turns out these asset helpers come from the sass-rails gem (which I had installed in my project).
The UUID currently has a proposal for addition to the standard library and can be supported here https://github.com/tc39/proposal-uuid
The proposal encompasses having UUID as the following:
// We're not yet certain as to how the API will be accessed (whether it's in the global, or a
// future built-in module), and this will be part of the investigative process as we continue
// working on the proposal.
uuid(); // "52e6953d-edbe-4953-be2e-65ed3836b2f0"
This implemtation follows the same layout as the V4 random uuid generation found here: https://www.npmjs.com/package/uuid
const uuidv4 = require('uuid/v4');
uuidv4(); // ? '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
I think it's noteworthy to understand how much bandwidth could be saved by this having an official implementation in the standard library. The authors of the proposal have also noted:
The 12 kb uuid module is downloaded from npm > 62,000,000 times a month (June 2019); making it available in the standard library eventually saves TBs of bandwidth globally. If we continue to address user needs, such as uuid, with the standard library, bandwidth savings add up.
On windows, nearly all AMPP (Apache,MySQL,PHP,PHPmyAdmin) packages don't include a mail server (but nearly all naked linuxes do have!). So, when using PHP under windows, you need to setup a mail server!
Imo the best and most simple tool ist this: http://smtp4dev.codeplex.com/
SMTP4Dev is a simple one-file mail server tool that does collect the mails it send (so it does not really sends mail, it just keeps them for development). Perfect tool.
To further complete @Ryan 's answer using json, one very convenient function to convert unicode is the one posted here: https://stackoverflow.com/a/13105359/7599285
ex with double or single quotes:
>print byteify(json.loads(u'[ "A","B","C" , " D"]')
>print byteify(json.loads(u"[ 'A','B','C' , ' D']".replace('\'','"')))
['A', 'B', 'C', ' D']
['A', 'B', 'C', ' D']
To detect when mouse or key are pressed, you can also write:
$(document).on('keyup mouseup', '#your-id', function() {
console.log('changed');
});
Example: button.titleLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
Future googlers, on MySQL, try this:
select date_sub(ref_date, interval day(ref_date)-1 day) as day1;
install this https://www.microsoft.com/en-us/download/details.aspx?id=13255
install the 32 bit version no matter whether you are 64 bit and enable the 32 bit apps in the application pool
Spring Boot seems had changed the way of reading the VM options as it evolves. Here's some way to try when you launch an application in Intellij and want to active some profile:
Open "Edit configuration" in "Run", and in "VM options", add: -Dspring.profiles.active=local
It actually works with one project of mine with Spring Boot v2.0.3.RELEASE
and Spring v5.0.7.RELEASE
, but not with another project with Spring Boot v2.1.1.RELEASE
and Spring v5.1.3.RELEASE
.
Also, when running with Maven or JAR, people mentioned this:
mvn spring-boot:run -Drun.profiles=dev
or
java -jar -Dspring.profiles.active=dev XXX.jar
(See here: how to use Spring Boot profiles)
It is mentioned somewhere, that Spring changes the way of launching the process of applications if you specify some JVM options; it forks another process and will not pass the arg it received so this does not work. The only way to pass args to it, is:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="..."
Again, this is for Maven. https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-debug.html
What works for me for the second project, was setting the environment variable, as mentioned in some answer above: "Edit configuration" - "Environment variable", and:
SPRING_PROFILES_ACTIVE=local
How about:
For Each oSheet In ActiveWorkbook.Sheets
If oSheet.ListObjects.Count > 0 Then
oCmbBox.AddItem oSheet.Name
End If
Next oSheet
var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");_x000D_
//U2FsdGVkX18ZUVvShFSES21qHsQEqZXMxQ9zgHy+bu0=_x000D_
_x000D_
var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");_x000D_
//4d657373616765_x000D_
_x000D_
_x000D_
document.getElementById("demo1").innerHTML = encrypted;_x000D_
document.getElementById("demo2").innerHTML = decrypted;_x000D_
document.getElementById("demo3").innerHTML = decrypted.toString(CryptoJS.enc.Utf8);
_x000D_
Full working sample actually is:_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js" integrity="sha256-/H4YS+7aYb9kJ5OKhFYPUjSJdrtV6AeyJOtTkw6X72o=" crossorigin="anonymous"></script>_x000D_
_x000D_
<br><br>_x000D_
<label>encrypted</label>_x000D_
<div id="demo1"></div>_x000D_
<br>_x000D_
_x000D_
<label>decrypted</label>_x000D_
<div id="demo2"></div>_x000D_
_x000D_
<br>_x000D_
<label>Actual Message</label>_x000D_
<div id="demo3"></div>
_x000D_
OK, just change your code to something like this:
<script>
function submit() {
return confirm('Do you really want to submit the form?');
}
</script>
<form onsubmit="return submit(this);">
<input type="image" src="xxx" border="0" name="submit" onclick="show_alert();"
alt="PayPal - The safer, easier way to pay online!" value="Submit">
</form>
Also this is the code in run, just I make it easier to see how it works, just run the code below to see the result:
function submitForm() {_x000D_
return confirm('Do you really want to submit the form?');_x000D_
}
_x000D_
<form onsubmit="return submitForm(this);">_x000D_
<input type="text" border="0" name="submit" />_x000D_
<button value="submit">submit</button>_x000D_
</form>
_x000D_
As I investigated and I found that UTF-8 is not working well on MAC and Windows so I tried with Windows-1252 , it supports well on both of them but you must select type of encoding on ubuntu.
Here is my code$valueToWrite = mb_convert_encoding($value, 'Windows-1252');
$response->headers->set('Content-Type', $mime . '; charset=Windows-1252');
$response->headers->set('Pragma', 'public');
$response->headers->set('Content-Endcoding','Windows-1252');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
echo "\xEF\xBB\xBF"; // UTF-8 BOM
For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.
Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.
Extensions can be loaded in unpacked mode by following the following steps:
chrome://extensions
(via omnibox or menu -> Tools -> Extensions).If you have a crx
file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.
These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.
Like this:
var myAssembly = System.Reflection.Assembly.GetEntryAssembly();
var myAssemblyLocation = System.IO.Path.GetDirectoryName(a.Location);
var myHtmlPath = Path.Combine(myAssemblyLocation, "my.html");
Note this was done on Excel for Mac 2011 but should be same for Windows
Macro:
Sub numberformats()
Dim rng As Range
Set rng = Range("A24:A35")
For Each c In rng
Debug.Print c.NumberFormat
Next c
End Sub
Result:
General General
Number 0
Currency $#,##0.00;[Red]$#,##0.00
Accounting _($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)
Date m/d/yy
Time [$-F400]h:mm:ss am/pm
Percentage 0.00%
Fraction # ?/?
Scientific 0.00E+00
Text @
Special ;;
Custom #,##0_);[Red](#,##0)
(I just picked a random entry for custom)
Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.
A better way to do this is to pop up a dialog box and get the name you wish to use.
One line code:
System.out.println(new Gson().fromJson(jsonLine,JsonObject.class).getAsJsonObject().get("data").getAsJsonObject().get("translations").getAsJsonArray().get(0).getAsJsonObject().get("translatedText").getAsString());
To those who are stuck wondering why a window flashes and goes away without doing anything, the problem may related to the RELATIVE path in your Python script. e.g. you used ".\". Even the Python script and Excel Workbook is in the same directory, the Current Directory may still be different. If you don't want to modify your code to change it to an absolute path. Just change your current Excel directory before you run the python script by:
ChDir ActiveWorkbook.Path
I'm just giving a example here. If the flash do appear, one of the first issues to check is the Current Working Directory.
I mostly build large scale, high availability type systems, so my answer is biased towards looking at it from a production support standpoint; that said, we assign roughly as follows:
error: the system is in distress, customers are probably being affected (or will soon be) and the fix probably requires human intervention. The "2AM rule" applies here- if you're on call, do you want to be woken up at 2AM if this condition happens? If yes, then log it as "error".
warn: an unexpected technical or business event happened, customers may be affected, but probably no immediate human intervention is required. On call people won't be called immediately, but support personnel will want to review these issues asap to understand what the impact is. Basically any issue that needs to be tracked but may not require immediate intervention.
info: things we want to see at high volume in case we need to forensically analyze an issue. System lifecycle events (system start, stop) go here. "Session" lifecycle events (login, logout, etc.) go here. Significant boundary events should be considered as well (e.g. database calls, remote API calls). Typical business exceptions can go here (e.g. login failed due to bad credentials). Any other event you think you'll need to see in production at high volume goes here.
debug: just about everything that doesn't make the "info" cut... any message that is helpful in tracking the flow through the system and isolating issues, especially during the development and QA phases. We use "debug" level logs for entry/exit of most non-trivial methods and marking interesting events and decision points inside methods.
trace: we don't use this often, but this would be for extremely detailed and potentially high volume logs that you don't typically want enabled even during normal development. Examples include dumping a full object hierarchy, logging some state during every iteration of a large loop, etc.
As or more important than choosing the right log levels is ensuring that the logs are meaningful and have the needed context. For example, you'll almost always want to include the thread ID in the logs so you can follow a single thread if needed. You may also want to employ a mechanism to associate business info (e.g. user ID) to the thread so it gets logged as well. In your log message, you'll want to include enough info to ensure the message can be actionable. A log like " FileNotFound exception caught" is not very helpful. A better message is "FileNotFound exception caught while attempting to open config file: /usr/local/app/somefile.txt. userId=12344."
There are also a number of good logging guides out there... for example, here's an edited snippet from JCL (Jakarta Commons Logging):
- error - Other runtime errors or unexpected conditions. Expect these to be immediately visible on a status console.
- warn - Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console.
- info - Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum.
- debug - detailed information on the flow through the system. Expect these to be written to logs only.
- trace - more detailed information. Expect these to be written to logs only.
This answer is not exactly to this question. But I will add this since this question still searchable for how to add/deduct period from date.
$date = new DateTime('now');
$date->modify('+3 month'); // or you can use '-90 day' for deduct
$date = $date->format('Y-m-d h:i:s');
echo $date;
Well i can give you an example why to use something like that. Think of a game where you want to store your level and enemies in an XML file. When you parse this file, you might have an element like this.
<Enemy X="10" Y="100" Type="MyGame.OrcGuard"/>
what you can do now is, create dynamically the objects found in your level file.
foreach(XmlNode node in doc)
var enemy = Activator.CreateInstance(null, node.Attributes["Type"]);
This is very useful, for building dynamic enviroments. Of course its also possible to use this for Plugin or addin scenarios and alot more.
Or... You could place the image in an anchor tag. Cause I had the same problem and it fixed it without issue. A lot of people use local paths before they publish their site and photos. Just make sure you go back and fix that in the final editing phase.
Introducer for the return type of a local lambda expression:
std::vector<MyType> seq;
// fill with instances...
std::sort(seq.begin(), seq.end(),
[] (const MyType& a, const MyType& b) -> bool {
return a.Content < b.Content;
});
introducing a trailing return type of a function in combination of the re-invented auto
:
struct MyType {
// declares a member function returning std::string
auto foo(int) -> std::string;
};
You can check the socket.connected
property:
var socket = io.connect();
console.log('check 1', socket.connected);
socket.on('connect', function() {
console.log('check 2', socket.connected);
});
It's updated dynamically, if the connection is lost it'll be set to false
until the client picks up the connection again. So easy to check for with setInterval
or something like that.
Another solution would be to catch disconnect
events and track the status yourself.
First checkout to the branch which you want to rename:
git branch -m old_branch new_branch
git push -u origin new_branch
To remove an old branch from remote
:
git push origin :old_branch
Use regular expression to achieve this task. Please refer the below code.
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your content: ");
String data = reader.readLine();
boolean b1 = Pattern.matches("^\\d+$", data);
boolean b2 = Pattern.matches("[0-9a-zA-Z([+-]?\\d*\\.+\\d*)]*", data);
boolean b3 = Pattern.matches("^([+-]?\\d*\\.+\\d*)$", data);
if(b1) {
System.out.println("It is integer.");
} else if(b2) {
System.out.println("It is String. ");
} else if(b3) {
System.out.println("It is Float. ");
}
} catch (IOException ex) {
Logger.getLogger(TypeOF.class.getName()).log(Level.SEVERE, null, ex);
}
}
No there is no special attribute you can use. JavaScriptSerializer
serializes enums
to their numeric values and not their string representation. You would need to use custom serialization to serialize the enum
as its name instead of numeric value.
If you can use JSON.Net instead of JavaScriptSerializer
than see answer on this question provided by OmerBakhari: JSON.net covers this use case (via the attribute [JsonConverter(typeof(StringEnumConverter))]
) and many others not handled by the built in .net serializers. Here is a link comparing features and functionalities of the serializers.
It's a pain to have to delete all your development .apk files, because the new certificate doesn't match so you can't upgrade them in all your AVDs. You have to get another development MAP-API key as well. There's another solution.
You can create your own debug certificate in debug.keystore
with whatever expiration you want. Do this in the .android
folder under your HOME
directory:
keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -validity 14000
keytool.exe
can be found in the JDK bin folder (e.g. C:\Program Files\Java\jdk1.6.0_31\bin\
on Windows).
ADT sets the first and last name on the certificate as "Android Debug", the organizational unit as "Android" and the two-letter country code as "US". You can leave the organization, city, and state values as "Unknown". This example uses a validity of 14000 days. You can use whatever value you like.
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
Using set_time_limit(0)
is useless when using php-fpm or similar process manager.
Bottomline is not to use set_time_limit
when using php-fpm
, to increase your execution timeout, check this tutorial.
Adding the following to build.gradle solves the problem :
android {
...
compileOptions.encoding = 'ISO-8859-1'
}
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
Use this one
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
@Test
public void testInsertObject() throws Exception {
String url = BASE_URL + "/object";
ObjectBean anObject = new ObjectBean();
anObject.setObjectId("33");
anObject.setUserId("4268321");
//... more
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String requestJson=ow.writeValueAsString(anObject );
mockMvc.perform(post(url).contentType(APPLICATION_JSON_UTF8)
.content(requestJson))
.andExpect(status().isOk());
}
As described in the comments, this works because the object is converted to json and passed as the request body. Additionally, the contentType is defined as Json (APPLICATION_JSON_UTF8).
An abbreviated version of your code worked for me,
class Remote: NSObject {
var data = NSMutableData()
func connect(query:NSString) {
var url = NSURL.URLWithString("http://www.google.com")
var request = NSURLRequest(URL: url)
var conn = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
println("didReceiveResponse")
}
func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
self.data.appendData(conData)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
println(self.data)
}
deinit {
println("deiniting")
}
}
This is the code I used in the calling class,
class ViewController: UIViewController {
var remote = Remote()
@IBAction func downloadTest(sender : UIButton) {
remote.connect("/apis")
}
}
You didn't specify in your question where you had this code,
var remote = Remote()
remote.connect("/apis")
If var is a local variable, then the Remote class will be deallocated right after the connect(query:NSString) method finishes, but before the data returns. As you can see by my code, I usually implement reinit (or dealloc up to now) just to make sure when my instances go away. You should add that to your Remote class to see if that's your problem.
Just send xml bytes directly:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests
xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text
{
"origin": "x.x.x.x",
"files": {},
"form": {},
"url": "http://httpbin.org/post",
"args": {},
"headers": {
"Content-Length": "48",
"Accept-Encoding": "identity, deflate, compress, gzip",
"Connection": "keep-alive",
"Accept": "*/*",
"User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
"Host": "httpbin.org",
"Content-Type": "application/xml"
},
"json": null,
"data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}
try this code in here...this is done using javascript onKeyUp() function...
<script>
function toCount(entrance,exit,text,characters) {
var entranceObj=document.getElementById(entrance);
var exitObj=document.getElementById(exit);
var length=characters - entranceObj.value.length;
if(length <= 0) {
length=0;
text='<span class="disable"> '+text+' <\/span>';
entranceObj.value=entranceObj.value.substr(0,characters);
}
exitObj.innerHTML = text.replace("{CHAR}",length);
}
</script>
How about this
UPDATE table SET columnB = columnA;
This will update every row.
When people talk about HTML5 applications they're most likely talking about writing just a simple web page or embedding a web page into their app (which will essentially provide the user interface). For the later there are different frameworks available, e.g. PhoneGap. These are used to provide more than the default browser features (e.g. multi touch) as well as allowing the app to run seamingly "standalone" and without the browser's navigation bars etc.
A new version for the scenario where the callback will be called by some other function, not your own code, and you want to add additional parameters.
For example, let's pretend that you have a lot of nested calls with success and error callbacks. I will use angular promises for this example but any javascript code with callbacks would be the same for the purpose.
someObject.doSomething(param1, function(result1) {
console.log("Got result from doSomething: " + result1);
result.doSomethingElse(param2, function(result2) {
console.log("Got result from doSomethingElse: " + result2);
}, function(error2) {
console.log("Got error from doSomethingElse: " + error2);
});
}, function(error1) {
console.log("Got error from doSomething: " + error1);
});
Now you may want to unclutter your code by defining a function to log errors, keeping the origin of the error for debugging purposes. This is how you would proceed to refactor your code:
someObject.doSomething(param1, function (result1) {
console.log("Got result from doSomething: " + result1);
result.doSomethingElse(param2, function (result2) {
console.log("Got result from doSomethingElse: " + result2);
}, handleError.bind(null, "doSomethingElse"));
}, handleError.bind(null, "doSomething"));
/*
* Log errors, capturing the error of a callback and prepending an id
*/
var handleError = function (id, error) {
var id = id || "";
console.log("Got error from " + id + ": " + error);
};
The calling function will still add the error parameter after your callback function parameters.
You can use lftp interactively in a shell script so the password not saved in .bash_history or similar by doing the following:
vi test_script.sh
Add the following to your file:
#!/bin/sh
HOST=<yourhostname>
USER=<someusername>
PASSWD=<yourpasswd>
cd <base directory for your put file>
lftp<<END_SCRIPT
open sftp://$HOST
user $USER $PASSWD
put local-file.name
bye
END_SCRIPT
And write/quit the vi editor after you edit the host, user, pass, and directory for your put file typing :wq
.Then make your script executable chmod +x test_script.sh
and execute it ./test_script.sh
.
// Size of numbers
def n=100;
// A list of numbers that is missing k numbers.
def list;
// A map
def map = [:];
// Populate the map so that it contains all numbers.
for(int index=0; index<n; index++)
{
map[index+1] = index+1;
}
// Get size of list that is missing k numbers.
def size = list.size();
// Remove all numbers, that exists in list, from the map.
for(int index=0; index<size; index++)
{
map.remove(list.get(index));
}
// Content of map is missing numbers
println("Missing numbers: " + map);
In your link function, do this:
// link function
function (scope, element, attrs) {
var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}
Also, in your link function, don't name your scope
variable using a $
. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.
I use >> /dev/null 2>&1
for a silent cronjob. A cronjob will do the job, but not send a report to my email.
As far as I know, don't remove /dev/null
. It's useful, especially when you run cPanel, it can be used for throw-away cronjob reports.
You can get Browser type here:
<script>
var browser_type = Object.keys($.browser)[0];
alert(browser_type);
</script>
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
You can pass the parent´s stdio to the child process if that´s what you want:
require('child_process').execSync(
'rsync -avAXz --info=progress2 "/src" "/dest"',
{stdio: 'inherit'}
);
select directory_path from dba_directories where upper(directory_name) = 'CSVDIR'
Neither <iostream>
nor <iostream.h>
are standard C header files. Your code is meant to be C++, where <iostream>
is a valid header. Use g++
(and a .cpp
file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream>
and using namespace std;
, and replace cout << endl;
with putchar('\n');
... I advise compiling using C99 (eg. gcc -std=c99
)
I had the same error when trying to launch spyder. "RuntimeError: module compiled against API version 0xb but this version of numpy is 0xa". This error appeared once I modified the numpy version of my machine by mistake (I thought I was in a venv). If your are using spyder installed with conda, my advice is to only use conda to manage package.
This works for me:
conda install anaconda
(I had conda but no anaconda on my machine) then:
conda update numpy
To use the Like Button and have the Open Graph inspect your website, you need an application.
So you need to associate the Like Button with a fb:app_id
If you want other users to see the administration page for your website on Facebook you add fb:admins
. So if you are the developer of the application and the website owner there is no need to add fb:admins
Based upon dwanderson's helpful comment, I was able to do this in a Bash one-liner:
conda create --name envpython2 --file <(conda list -n env1 -e )
My badly named env was "env1" and the new one I wish to clone from it is "envpython2".
HTML
<div id="fixedbtn"><button type="button" value="Delete"></button></div>
CSS
#fixedbtn{
position: fixed;
margin: 0px 10px 0px 10px;
width: 10%;
}
First, Latin-1 is the same as ISO-8859-1, so, the default was already OK for you. Right?
You successfully set the encoding to ISO-8859-1 with your command line parameter. You also set it programmatically to "Latin-1", but, that's not a recognized value of a file encoding for Java. See http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html
When you do that, looks like Charset resets to UTF-8, from looking at the source. That at least explains most of the behavior.
I don't know why OutputStreamWriter shows ISO8859_1. It delegates to closed-source sun.misc.* classes. I'm guessing it isn't quite dealing with encoding via the same mechanism, which is weird.
But of course you should always be specifying what encoding you mean in this code. I'd never rely on the platform default.
Use different format or pattern to get the information from the date
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
For more info: https://momentjs.com/docs/#/parsing/string-format/
Instead of detecting a browser, you should rather detect a feature (whether it's supported or not). This is what Modernizr does.
Of course there are cases where you still need to check the browser because you need to work around an issue and not to detect a feature. Specific WebKit
check which does not use jQuery $.browser
:
var isWebKit = !!window.webkitURL;
As some of the comments suggested the above approach doesn't work for older Safari versions. Updating with another approach suggested in comments and by another answer:
var isWebKit = 'WebkitAppearance' in document.documentElement.style;
Closeable
extends AutoCloseable
, and is specifically dedicated to IO streams: it throws IOException instead of Exception, and is idempotent, whereas AutoCloseable doesn't provide this guarantee.
This is all explained in the javadoc of both interfaces.
Implementing AutoCloseable (or Closeable) allows a class to be used as a resource of the try-with-resources construct introduced in Java 7, which allows closing such resources automatically at the end of a block, without having to add a finally block which closes the resource explicitely.
Your class doesn't represent a closeable resource, and there's absolutely no point in implementing this interface: an IOTest can't be closed. It shouldn't even be possible to instantiate it, since it doesn't have any instance method. Remember that implementing an interface means that there is a is-a relationship between the class and the interface. You have no such relationship here.
To insert a VARCHAR2
into a BLOB
column you can rely on the function utl_raw.cast_to_raw
as next:
insert into mytable(id, myblob) values (1, utl_raw.cast_to_raw('some magic here'));
It will cast your input VARCHAR2
into RAW
datatype without modifying its content, then it will insert the result into your BLOB
column.
More details about the function utl_raw.cast_to_raw
Use conditional formatting.
You can enter a condition using any cell you like and a format to apply if the formula is true.
You can use {}
arround your variable, to separate it from what's after:
echo "{$test}y"
As reference, you can take a look to the Variable parsing - Complex (curly) syntax section of the PHP manual.
import time
seconds_since_epoch = time.mktime(your_datetime.timetuple()) * 1000
As an alternative to the other (very good) answers, you could cast to uintptr_t
or intptr_t
(from stdint.h
/inttypes.h
) and use the corresponding integer conversion specifiers. This would allow more flexibility in how the pointer is formatted, but strictly speaking an implementation is not required to provide these typedefs.
I caution against using the command
setx PATH "%PATH%;C:\Something\bin"
to modify the PATH variable because of a "feature" of its implementation. On many (most?) installations these days the variable will be lengthy - setx
will truncate the stored string to 1024 bytes, potentially corrupting the PATH (see the discussion here).
(I signed up specifically to flag this issue, and so lack the site reputation to directly comment on the answer posted on May 2 '12. My thanks to beresfordt for adding such a comment)
There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...
For tomcat you can increase the permGem space by using
-XX:MaxPermSize=128m
For this you need to create (if not already exists) a file named setenv.sh in tomcat/bin folder and include following line in it
export JAVA_OPTS="-XX:MaxPermSize=128m"
Reference : http://wiki.razuna.com/display/ecp/Adjusting+Memory+Settings+for+Tomcat
I think in Postgres you can play with formats for example if you want dd/mm/yyyy
TO_CHAR(submit_time, 'DD/MM/YYYY') as submit_date
Simply you cannot do it with FF3.
The other option could be using applet or other controls to select and upload files.
One of the easiest solution is
$objectData = (object) $arrayData
Another thing to check is if any applications still have a hold on the file.
Had some issues with MoveFile. Part of my permissions problem was that my script opens the file (in this case in Excel), makes a modification, closes it, then moves it to a "processed" folder.
In debugging a couple things, the script crashed a few times. Digging into the permission denied error I found that I had 4 instances of Excel running in the background because the script was never able to properly terminate the application due to said crashes. Apparently one of them still had a hold on the file and, thusly, "permission denied."
You could reference the variable in an assertion and then build with -fsanitize=address
:
void foo (int32_t& i) {
// Assertion will trigger address sanitizer if not initialized:
assert(static_cast<int64_t>(i) != INT64_MAX);
}
This will cause the program to reliably crash with a stack trace (as opposed to undefined behavior).
You can view the java doc examples or the example of usage of Predicate here
Basically it is used to filter rows in the resultset based on any specific criteria that you may have and return true for those rows that are meeting your criteria:
// the age column to be between 7 and 10
AgeFilter filter = new AgeFilter(7, 10, 3);
// set the filter.
resultset.beforeFirst();
resultset.setFilter(filter);
You can also pull the latest commit and just undo until the commit you desire:
git pull origin master
git reset --hard HEAD~1
Replace master
with your desired branch.
Use git log to see to which commit you would like to revert:
git log
Personally, this has worked for me better.
Basically, what this does is pulls the latest commit, and you manually revert commits one by one. Use git log in order to see commit history.
Good points: Works as advertised. You don't have to use commit hash or pull unneeded branches.
Bad points: You need to revert commits on by one.
WARNING: Commit/stash all your local changes, because with --hard
you are going to lose them. Use at your own risk!
You could use the dplyr
package:
library(dplyr)
filter(expr, cell_type == "hesc")
filter(expr, cell_type == "hesc" | cell_type == "bj fibroblast")
Just write this simple line of code :-
button.performClick();
where button is the reference variable of Button class and defined as follows:-
private Button buttonToday ;
buttonToday = (Button) findViewById(R.id.buttonToday);
That's it.
Using bash regex capabilities:
re="^([^-]+)-(.*)$"
[[ "ABCDE-123456" =~ $re ]] && var1="${BASH_REMATCH[1]}" && var2="${BASH_REMATCH[2]}"
echo $var1
echo $var2
OUTPUT
ABCDE
123456
Writing the actual condition can be the tricky part, so I tend to
Advantages of using the Immediate window:
This example breaks when the code is referring to a table with the name "Setting":
table.GetTableName().Contains("Setting")
It's a hexadecimal number.
0x6400 translates to 4*16^2 + 6*16^3 = 25600
just make it function,
<script type="text/javascript">
function AlertIt() {
var answer = confirm ("Please click on OK to continue.")
if (answer)
window.location="http://www.continue.com";
}
</script>
<a href="javascript:AlertIt();">click me</a>
This is because you select not a theme of your project. Try to do next:
i would just do:
char x = 0; //Which will give you an empty value of character
I've been facing this problem for long but what this solves my problem Go inside the tsconfig.json and add the following under compilerOptions
{
"compilerOptions": {
...
"allowJs": true
...
}
}
Building off my answer to "python: How to add property to a class dynamically?":
class data(object):
def __init__(self,*args,**argd):
self.__dict__.update(dict(*args,**argd))
def makedata(d):
d2 = {}
for n in d:
d2[n] = trydata(d[n])
return data(d2)
def trydata(o):
if isinstance(o,dict):
return makedata(o)
elif isinstance(o,list):
return [trydata(i) for i in o]
else:
return o
You call makedata
on the dictionary you want converted, or maybe trydata
depending on what you expect as input, and it spits out a data object.
Notes:
trydata
if you need more functionality.x.a = {}
or similar.In Node.js, __dirname
is always the directory in which the currently executing script resides (see this). So if you typed __dirname
into /d1/d2/myscript.js
, the value would be /d1/d2
.
By contrast, .
gives you the directory from which you ran the node
command in your terminal window (i.e. your working directory) when you use libraries like path
and fs
. Technically, it starts out as your working directory but can be changed using process.chdir()
.
The exception is when you use .
with require()
. The path inside require
is always relative to the file containing the call to require
.
Let's say your directory structure is
/dir1
/dir2
pathtest.js
and pathtest.js
contains
var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));
and you do
cd /dir1/dir2
node pathtest.js
you get
. = /dir1/dir2
__dirname = /dir1/dir2
Your working directory is /dir1/dir2
so that's what .
resolves to. Since pathtest.js
is located in /dir1/dir2
that's what __dirname
resolves to as well.
However, if you run the script from /dir1
cd /dir1
node dir2/pathtest.js
you get
. = /dir1
__dirname = /dir1/dir2
In that case, your working directory was /dir1
so that's what .
resolved to, but __dirname
still resolves to /dir1/dir2
.
.
inside require
...If inside dir2/pathtest.js
you have a require
call into include a file inside dir1
you would always do
require('../thefile')
because the path inside require
is always relative to the file in which you are calling it. It has nothing to do with your working directory.
For the simple reason:
Andy-B-MacBook:~ l.admin$ brew install sshpass
Error: No available formula with the name "sshpass"
We won't add sshpass because it makes it too easy for novice SSH users to
ruin SSH's security.
Thus, the answer to do the curl / configure / install worked great for me on Mac.
i was trying to use airbnb deeplink dispatch and got this error. i had to also exlude the findbugs group from the annotationProcessor.
//airBnb
compile ('com.airbnb:deeplinkdispatch:3.1.1'){
exclude group:'com.google.code.findbugs'
}
annotationProcessor ('com.airbnb:deeplinkdispatch-processor:3.1.1'){
exclude group:'com.google.code.findbugs'
}
To avoid undesired effects while pasting, there is an option that needs to be set:
set paste
A useful command to have in your .vimrc is set pastetoggle=<F10>
or some other button, to easily toggle between paste and nopaste.
I think this is non-restful. I do not think the restful service should handle the requirement of forcing the user to confirm a delete. I would handle this in the UI.
Does specifying force_delete=true make sense if this were a program's API? If someone was writing a script to delete this resource, would you want to force them to specify force_delete=true to actually delete the resource?
(function(A, B){ b=A; a=B; })(parseInt(a), parseInt(b));
This is simple method to get request data from HttpServletRequest
using Java 8 Stream API:
String requestData = request.getReader().lines().collect(Collectors.joining());
I had this same question a while back and came across one of Scott Hanselman's posts:
Implementing HTTP File Upload with ASP.NET MVC including Tests and Mocks
Hope this helps.
In my case, I configured an external Maven installation, and I made sure to be using a JDK instead of a JRE (in the eclipse configuration, and in the Server Environment). You can run a Maven Build of the project from eclipse to check everything is working ok.
After that, I updated the maven projects, cleaned and built the projects, cleaned the server, and redeployed the artifacts.
With library fpp
, you can easily create time series with date format:
time_ser=ts(data,frequency=4,start=c(1954,2))
here we start at the 2nd quarter of 1954 with quarter fequency.
NOTE: not for Windows
Using ren-1.0 the correct form is:
"ren *.*" "#2.jpg"
From man ren
The replacement pattern is another filename with embedded wildcard indexes, each of which consists of the character # followed by a digit from 1 to 9. In the new name of a matching file, the wildcard indexes are replaced by the actual characters that matched the referenced wildcards in the original filename.
and
Note that the shell normally expands the wildcards * and ?, which in the case of ren is undesirable. Thus, in most cases it is necessary to enclose the search pattern in quotes.
This code worked for me
public static void main(String[] args) {
try {
java.net.URL myUr = new java.net.URL("http://path");
System.out.println("Instantiated new URL: " + connection_url);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
Instantiated new URL: http://path
You can't modify a collection while iterating it. That way lies madness - most notably, if you were allowed to delete and deleted the current item, the iterator would have to move on (+1) and the next call to next
would take you beyond that (+2), so you'd end up skipping one element (the one right behind the one you deleted). You have two options:
.keys()
et al for this (in Python 3, pass the resulting iterator to list
). Could be highly wasteful space-wise though.mydict
as usual, saving the keys to delete in a seperate collection to_delete
. When you're done iterating mydict
, delete all items in to_delete
from mydict
. Saves some (depending on how many keys are deleted and how many stay) space over the first approach, but also requires a few more lines.A more generalised example - if looking for parts of a word OR specific words in a string:
df = pd.DataFrame([('cat andhat', 1000.0), ('hat', 2000000.0), ('the small dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])
Specific parts of sentence or word:
searchfor = '.*cat.*hat.*|.*the.*dog.*'
Creat column showing the affected rows (can always filter out as necessary)
df["TrueFalse"]=df['col1'].str.contains(searchfor, regex=True)
col1 col2 TrueFalse
0 cat andhat 1000.0 True
1 hat 2000000.0 False
2 the small dog 1000.0 True
3 fog 330000.0 False
4 pet 3 30000.0 False
Just toggle each time it is called
this.boolValue = !this.boolValue;
The most effective solution that I found is to define the parent element with display:flex
and align-items:center
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.myclass{
display:flex;
align-items:center;
background-color:grey;
color:#fff;
height:50px;
}
</style>
</head>
<body>
<div class="myclass">
<input type="checkbox">
<label>do you love Ananas?
</label>
</div>
</body>
</html>
OUTPUT:
Once you've created the frame the part of the code with your conditional isn't going to get entered. To put it another way, at the time you execute the test if (btn1Clicked == true)
, the button has not only not been clicked yet, it hasn't even been displayed to the user.
Lose the booleans and move the line with the btnConvertDocuments.setEnabled(false)
into your actionListener. Make the buttons instance variables, do not make them static variables. (Alternatively you could keep the buttons as local variables and assign each of them their own anonymous inner class listener.)
1) I have experienced same issue, my Xcode version was 7.0.1, and I updated my iPhone to version 9.2, then upon using Xcode, my iPhone was shown in the section of unavailable device. Just like in image below:
2) But then I somehow managed to select my iPhone by clicking at
Product -> Destination -> Unavailable Device
3) But that didn't solved my problem, and it started showing:
Could not find Developer Disk Image
Solution) Then finally I downloaded latest version of Xcode version 7.2 from here and everything has worked fine for me.
Update: Whenever version of iPhone device is higher than version of Xcode, you may experience same issue, so you should update your Xcode version to remove this error.