In my case the problem was:
define ('DB_PASSWORD', "MyPassw0rd!'");
(the odd single ' before the double ")
For what it's worth I was having the same issue when passing app
into onRequest
. I realized the issue was a trailing slash on the request url for the firebase function. Express was looking for '/'
but I didn't have the trailing slash on the function [project-id].cloudfunctions.net/[function-name]
. The CORS error was a false negative. When I added the trailing slash, I got the response I was expecting.
Here it's another approach :
function a(first,second)
{
return (second)(first);
}
a('Hello',function(e){alert(e+ ' world!');}); //=> Hello world
The Json conversion should work out-of-the box. In order this to happen you need add some simple configurations:
First add a contentNegotiationManager into your spring config file. It is responsible for negotiating the response type:
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
<property name="favorParameter" value="true" />
<property name="ignoreAcceptHeader" value="true" />
<property name="useJaf" value="false" />
<property name="defaultContentType" value="application/json" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
</bean>
<mvc:annotation-driven
content-negotiation-manager="contentNegotiationManager" />
<context:annotation-config />
Then add Jackson2 jars (jackson-databind and jackson-core) in the service's class path. Jackson is responsible for the data serialization to JSON. Spring will detect these and initialize the MappingJackson2HttpMessageConverter automatically for you. Having only this configured I have my automatic conversion to JSON working. The described config has an additional benefit of giving you the possibility to serialize to XML if you set accept:application/xml header.
Solution Working in the Year 2020 and 2021:
I tried the other solutions and nothing worked. This is because of input logic in React.js has been changed. For detail, you can see this link: https://hustle.bizongo.in/simulate-react-on-change-on-controlled-components-baa336920e04.
In short, when we change the value of input by changing state and then dispatch a change event then React will register both the setState and the event and consider it a duplicate event and swallow it.
The solution is to call native value setter on input (See setNativeValue function in following code)
Example Code
import React, { Component } from 'react'
export class CustomInput extends Component {
inputElement = null;
// THIS FUNCTION CALLS NATIVE VALUE SETTER
setNativeValue(element, value) {
const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
const prototype = Object.getPrototypeOf(element);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(element, value);
} else {
valueSetter.call(element, value);
}
}
constructor(props) {
super(props);
this.state = {
inputValue: this.props.value,
};
}
addToInput = (valueToAdd) => {
this.setNativeValue(this.inputElement, +this.state.inputValue + +valueToAdd);
this.inputElement.dispatchEvent(new Event('input', { bubbles: true }));
};
handleChange = e => {
console.log(e);
this.setState({ inputValue: e.target.value });
this.props.onChange(e);
};
render() {
return (
<div>
<button type="button" onClick={() => this.addToInput(-1)}>-</button>
<input
readOnly
ref={input => { this.inputElement = input }}
name={this.props.name}
value={this.state.inputValue}
onChange={this.handleChange}></input>
<button type="button" onClick={() => this.addToInput(+1)}>+</button>
</div>
)
}
}
export default CustomInput
Result
You can use C#'s null coalescing operator
return accountNumber ?? string.Empty;
I built a laravel package for making statistics : https://github.com/Ifnot/statistics
It is based on eloquent, carbon and indicators so it is really easy to use. It may be usefull for extracting date grouped indicators.
$statistics = Statistics::of(MyModel::query());
$statistics->date('validated_at');
$statistics->interval(Interval::$DAILY, Carbon::createFromFormat('Y-m-d', '2016-01-01'), Carbon::now())
$statistics->indicator('total', function($row) {
return $row->counter;
});
$data = $statistics->make();
echo $data['2016-01-01']->total;
```
You can login to mysql and type
mysql> SHOW INNODB STATUS\G
You will have all the output and you should have a better idea of what the error is.
pow
is built into the language(not part of the math library). The problem is that you haven't imported math.
Try this:
import math
math.sqrt(4)
JavaScript
<script language="javascript">
var flag=0;
function username()
{
user=loginform.username.value;
if(user=="")
{
document.getElementById("error0").innerHTML="Enter UserID";
flag=1;
}
}
function password()
{
pass=loginform.password.value;
if(pass=="")
{
document.getElementById("error1").innerHTML="Enter password";
flag=1;
}
}
function check(form)
{
flag=0;
username();
password();
if(flag==1)
return false;
else
return true;
}
</script>
HTML
<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">
<div id="error0"></div>
<input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
controls">
<div id="error1"></div>
<input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">
<button type="submit" class="btn">Sign in</button>
</div>
</div>
</form>
Another base R
option could be gl()
:
gl(5, 3)
Where the output is a factor:
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5
If integers are needed, you can convert it:
as.numeric(gl(5, 3))
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
By experiment I was able to observe this:
When SQL Profiler 2005 or SQL Profiler 2000 is used with database residing in SQLServer 2000 - problem mentioned problem persists, but when SQL Profiler 2005 is used with SQLServer 2005 database, it works perfect!
In Summary, the issue seems to be prevalent in SQLServer 2000 & rectified in SQLServer 2005.
The solution for the issue when dealing with SQLServer 2000 is (as explained by wearejimbo)
Identify the DatabaseID of the database you want to filter by querying the sysdatabases table as below
SELECT *
FROM master..sysdatabases
WHERE name like '%your_db_name%' -- Remove this line to see all databases
ORDER BY dbid
Use the DatabaseID Filter (instead of DatabaseName) in the New Trace window of SQL Profiler 2000
In my case, two leading '\\' working fine for me.
For example : if your word contains the '#' character (e.g. aa#100, you can escape it with two leading '\\'
key= aa\\#100
_x000D_
All other answers, and mainly about list comprehension, are great. But just to explain your error:
strip_list = []
for lengths in range(1,20):
strip_list.append(0) #longest word in the text file is 20 characters long
for a in lines:
strip_list.append(lines[a].strip())
a
is a member of your list, not an index. What you could write is this:
[...]
for a in lines:
strip_list.append(a.strip())
Another important comment: you can create an empty list this way:
strip_list = [0] * 20
But this is not so useful, as .append
appends stuff to your list. In your case, it's not useful to create a list with defaut values, as you'll build it item per item when appending stripped strings.
So your code should be like:
strip_list = []
for a in lines:
strip_list.append(a.strip())
But, for sure, the best one is this one, as this is exactly the same thing:
stripped = [line.strip() for line in lines]
In case you have something more complicated than just a .strip
, put this in a function, and do the same. That's the most readable way to work with lists.
There are many ways you can import Text file to the current sheet. Here are three (including the method that you are using above)
Cells.Copy
Using a QueryTable
Here is a simple macro that I recorded. Please amend it to suit your needs.
Sub Sample()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
)
.Name = "Sample"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Open the text file in memory
Sub Sample()
Dim MyData As String, strData() As String
Open "C:\Sample.txt" For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
End Sub
Once you have the data in the array you can export it to the current sheet.
Using the method that you are already using
Sub Sample()
Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet
Set wbI = ThisWorkbook
Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import
Set wbO = Workbooks.Open("C:\Sample.txt")
wbO.Sheets(1).Cells.Copy wsI.Cells
wbO.Close SaveChanges:=False
End Sub
FOLLOWUP
You can use the Application.GetOpenFilename
to choose the relevant file. For example...
Sub Sample()
Dim Ret
Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")
If Ret <> False Then
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=Range("$A$1"))
'~~> Rest of the code
End With
End If
End Sub
This also works:
CAST( coulmn_value AS UNSIGNED ) // will return 0 if not numeric string.
for example
SELECT CAST('a123' AS UNSIGNED) // returns 0
SELECT CAST('123' AS UNSIGNED) // returns 123 i.e. > 0
Even if the elements are of different types it can cause you some serious problems...
Suppose you have 3 buttons with the same id:
<button id="myid" data-mydata="this is button 1">button 1</button>
<button id="myid" data-mydata="this is button 2">button 2</button>
<button id="myid" data-mydata="this is button 3">button 3</button>
Now you setup some jQuery
code to do something when myid
buttons are clicked:
$(document).ready(function ()
{
$("#myid").click(function ()
{
var buttonData = $(this).data("mydata");
// Call interesting function...
interestingFunction();
$('form').trigger('submit');
});
});
What would you expect? That every button clicked would execute the click event handler setup with jQuery. Unfortunately it won't happen. ONLY the 1st button calls the click handler. The other 2 when clicked do nothing. It is as if they weren't buttons at all!
So always assign different IDs
to HTML
elements. This will get you covered against strange things. :)
<button id="button1" class="mybtn" data-mydata="this is button 1">button 1</button>
<button id="button2" class="mybtn" data-mydata="this is button 2">button 2</button>
<button id="button3" class="mybtn" data-mydata="this is button 3">button 3</button>
Now if you want the click event handler to run when any of the buttons get clicked it will work perfectly if you change the selector in the jQuery code to use the CSS
class applied to them like this:
$(document).ready(function ()
{
$(".mybtn").click(function ()
{
var buttonData = $(this).data("mydata");
// Call interesting function...
interstingFunction();
$('form').trigger('submit');
});
});
In force layouts simply setting the 'height' and 'width' attributes will not work to re-center/move the plot into the svg container. However, there's a very simple answer that works for Force Layouts found here. In summary:
Use same (any) eventing you like.
window.on('resize', resize);
Then assuming you have svg & force variables:
var svg = /* D3 Code */;
var force = /* D3 Code */;
function resize(e){
// get width/height with container selector (body also works)
// or use other method of calculating desired values
var width = $('#myselector').width();
var height = $('#myselector').height();
// set attrs and 'resume' force
svg.attr('width', width);
svg.attr('height', height);
force.size([width, height]).resume();
}
In this way, you don't re-render the graph entirely, we set the attributes and d3 re-calculates things as necessary. This at least works when you use a point of gravity. I'm not sure if that's a prerequisite for this solution. Can anyone confirm or deny ?
Cheers, g
You are exceeding the SQL limit of 4000 bytes which applies to LISTAGG
as well.
SQL> SELECT listagg(text, ',') WITHIN GROUP (
2 ORDER BY NULL)
3 FROM
4 (SELECT to_char(to_date(level,'j'), 'jsp') text FROM dual CONNECT BY LEVEL < 250
5 )
6 /
SELECT listagg(text, ',') WITHIN GROUP (
*
ERROR at line 1:
ORA-01489: result of string concatenation is too long
As a workaround, you could use XMLAGG.
For example,
SQL> SET LONG 2000000
SQL> SET pagesize 50000
SQL> SELECT rtrim(xmlagg(XMLELEMENT(e,text,',').EXTRACT('//text()')
2 ).GetClobVal(),',') very_long_text
3 FROM
4 (SELECT to_char(to_date(level,'j'), 'jsp') text FROM dual CONNECT BY LEVEL < 250
5 )
6 /
VERY_LONG_TEXT
--------------------------------------------------------------------------------
one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen
,fifteen,sixteen,seventeen,eighteen,nineteen,twenty,twenty-one,twenty-two,twenty
-three,twenty-four,twenty-five,twenty-six,twenty-seven,twenty-eight,twenty-nine,
thirty,thirty-one,thirty-two,thirty-three,thirty-four,thirty-five,thirty-six,thi
rty-seven,thirty-eight,thirty-nine,forty,forty-one,forty-two,forty-three,forty-f
our,forty-five,forty-six,forty-seven,forty-eight,forty-nine,fifty,fifty-one,fift
y-two,fifty-three,fifty-four,fifty-five,fifty-six,fifty-seven,fifty-eight,fifty-
nine,sixty,sixty-one,sixty-two,sixty-three,sixty-four,sixty-five,sixty-six,sixty
-seven,sixty-eight,sixty-nine,seventy,seventy-one,seventy-two,seventy-three,seve
nty-four,seventy-five,seventy-six,seventy-seven,seventy-eight,seventy-nine,eight
y,eighty-one,eighty-two,eighty-three,eighty-four,eighty-five,eighty-six,eighty-s
even,eighty-eight,eighty-nine,ninety,ninety-one,ninety-two,ninety-three,ninety-f
our,ninety-five,ninety-six,ninety-seven,ninety-eight,ninety-nine,one hundred,one
hundred one,one hundred two,one hundred three,one hundred four,one hundred five
,one hundred six,one hundred seven,one hundred eight,one hundred nine,one hundre
d ten,one hundred eleven,one hundred twelve,one hundred thirteen,one hundred fou
rteen,one hundred fifteen,one hundred sixteen,one hundred seventeen,one hundred
eighteen,one hundred nineteen,one hundred twenty,one hundred twenty-one,one hund
red twenty-two,one hundred twenty-three,one hundred twenty-four,one hundred twen
ty-five,one hundred twenty-six,one hundred twenty-seven,one hundred twenty-eight
,one hundred twenty-nine,one hundred thirty,one hundred thirty-one,one hundred t
hirty-two,one hundred thirty-three,one hundred thirty-four,one hundred thirty-fi
ve,one hundred thirty-six,one hundred thirty-seven,one hundred thirty-eight,one
hundred thirty-nine,one hundred forty,one hundred forty-one,one hundred forty-tw
o,one hundred forty-three,one hundred forty-four,one hundred forty-five,one hund
red forty-six,one hundred forty-seven,one hundred forty-eight,one hundred forty-
nine,one hundred fifty,one hundred fifty-one,one hundred fifty-two,one hundred f
ifty-three,one hundred fifty-four,one hundred fifty-five,one hundred fifty-six,o
ne hundred fifty-seven,one hundred fifty-eight,one hundred fifty-nine,one hundre
d sixty,one hundred sixty-one,one hundred sixty-two,one hundred sixty-three,one
hundred sixty-four,one hundred sixty-five,one hundred sixty-six,one hundred sixt
y-seven,one hundred sixty-eight,one hundred sixty-nine,one hundred seventy,one h
undred seventy-one,one hundred seventy-two,one hundred seventy-three,one hundred
seventy-four,one hundred seventy-five,one hundred seventy-six,one hundred seven
ty-seven,one hundred seventy-eight,one hundred seventy-nine,one hundred eighty,o
ne hundred eighty-one,one hundred eighty-two,one hundred eighty-three,one hundre
d eighty-four,one hundred eighty-five,one hundred eighty-six,one hundred eighty-
seven,one hundred eighty-eight,one hundred eighty-nine,one hundred ninety,one hu
ndred ninety-one,one hundred ninety-two,one hundred ninety-three,one hundred nin
ety-four,one hundred ninety-five,one hundred ninety-six,one hundred ninety-seven
,one hundred ninety-eight,one hundred ninety-nine,two hundred,two hundred one,tw
o hundred two,two hundred three,two hundred four,two hundred five,two hundred si
x,two hundred seven,two hundred eight,two hundred nine,two hundred ten,two hundr
ed eleven,two hundred twelve,two hundred thirteen,two hundred fourteen,two hundr
ed fifteen,two hundred sixteen,two hundred seventeen,two hundred eighteen,two hu
ndred nineteen,two hundred twenty,two hundred twenty-one,two hundred twenty-two,
two hundred twenty-three,two hundred twenty-four,two hundred twenty-five,two hun
dred twenty-six,two hundred twenty-seven,two hundred twenty-eight,two hundred tw
enty-nine,two hundred thirty,two hundred thirty-one,two hundred thirty-two,two h
undred thirty-three,two hundred thirty-four,two hundred thirty-five,two hundred
thirty-six,two hundred thirty-seven,two hundred thirty-eight,two hundred thirty-
nine,two hundred forty,two hundred forty-one,two hundred forty-two,two hundred f
orty-three,two hundred forty-four,two hundred forty-five,two hundred forty-six,t
wo hundred forty-seven,two hundred forty-eight,two hundred forty-nine
If you want to concatenate multiple columns which itself have 4000 bytes, then you can concatenate the XMLAGG output of each column to avoid the SQL limit of 4000 bytes.
For example,
WITH DATA AS
( SELECT 1 id, rpad('a1',4000,'*') col1, rpad('b1',4000,'*') col2 FROM dual
UNION
SELECT 2 id, rpad('a2',4000,'*') col1, rpad('b2',4000,'*') col2 FROM dual
)
SELECT ID,
rtrim(xmlagg(XMLELEMENT(e,col1,',').EXTRACT('//text()') ).GetClobVal(), ',')
||
rtrim(xmlagg(XMLELEMENT(e,col2,',').EXTRACT('//text()') ).GetClobVal(), ',')
AS very_long_text
FROM DATA
GROUP BY ID
ORDER BY ID;
There is no difference ...
So principially you could use both (one at a time !-)
But for the sake of readability and for the cleanliness of the html-code I always prefer the window.onload !o]
Adding ... android:usesCleartextTraffic="true" ... to your manifest file may appear to fix the problem but it opens a threat to data integrity.
For security reasons I used manifest placeholders with android:usesCleartextTraffic inside the manifest file (like in Option 3 of the accepted answer i.e @Hrishikesh Kadam's response) to only allow cleartext on debug environment.
Inside my build.gradle(:app) file, I added a manifest placeholder like this:
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
manifestPlaceholders.cleartextTrafficPermitted ="true"
}
}
Note the placeholder name cleartextTrafficPermitted at this line above
manifestPlaceholders.cleartextTrafficPermitted ="true"
Then in my Android Manifest, I used the same placeholder ...
AndroidManifest.xml -
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="${cleartextTrafficPermitted}"
...>
...
</application>
</manifest>
With that, cleartext traffic is only permitted under the debug environment.
i work on a multi platform project, so i can't use _s function and i don't want pollute my code with visual studio specific code.
my solution is disable the warning 4996 on the visual studio project. go to Project -> Properties -> Configuration properties -> C/C++ -> Advanced -> Disable specific warning add the value 4996.
if you use also the mfc and/or atl library (not my case) define before include mfc _AFX_SECURE_NO_DEPRECATE and before include atl _ATL_SECURE_NO_DEPRECATE.
i use this solution across visual studio 2003 and 2005.
p.s. if you use only visual studio the secure template overloads could be a good solution.
The main image manager in PIL
is PIL
's Image
module.
from PIL import Image
import math
foo = Image.open("path\\to\\image.jpg")
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
foo = foo.resize((x2,y2),Image.ANTIALIAS)
foo.save("path\\to\\save\\image_scaled.jpg",quality=95)
You can add optimize=True
to the arguments of you want to decrease the size even more, but optimize only works for JPEG's and PNG's.
For other image extensions, you could decrease the quality of the new saved image.
You could change the size of the new image by just deleting a bit of code and defining the image size and you can only figure out how to do this if you look at the code carefully.
I defined this size:
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
just to show you what is (almost) normally done with horizontal images. For vertical images you might do:
x, y = foo.size
x2, y2 = math.floor(x-20), math.floor(y-50)
. Remember, you can still delete that bit of code and define a new size.
Regarding your query of
So when should interface with default methods be used and when should an abstract class be used? Are the abstract classes still useful in that scenario?
java documentation provides perfect answer.
Abstract Classes Compared to Interfaces:
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation.
However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.
With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.
Use cases for each of them have been explained in below SE post:
What is the difference between an interface and abstract class?
Are the abstract classes still useful in that scenario?
Yes. They are still useful. They can contain non-static, non-final methods and attributes (protected, private in addition to public), which is not possible even with Java-8 interfaces.
My preffered way to compare nullable fields is: NULLIF(nullablefield, :ParameterValue) IS NULL AND NULLIF(:ParameterValue, nullablefield) IS NULL . This is cumbersome but is of universal use while Coalesce is impossible in some cases.
The second and inverse use of NULLIF is because "NULLIF(nullablefield, :ParameterValue) IS NULL" will always return "true" if the first parameter is null.
If you want to input more data into the form, you simply access the submitted data through $_POST.
If you have
<input type="text" name="firstname" />
you access it with
$firstname = $_POST["firstname"];
You could then update your query line to read
mysql_query("INSERT INTO dbProfiles (photo,firstname)
VALUES('{$filename}','{$firstname}')");
Note: Always filter and sanitize your data.
If you want to have back button with back arrow you can use an image and code below
backArrow.png [email protected] [email protected]
override func viewDidLoad() {
super.viewDidLoad()
let customBackButton = UIBarButtonItem(image: UIImage(named: "backArrow") , style: .plain, target: self, action: #selector(backAction(sender:)))
customBackButton.imageInsets = UIEdgeInsets(top: 2, left: -8, bottom: 0, right: 0)
navigationItem.leftBarButtonItem = customBackButton
}
func backAction(sender: UIBarButtonItem) {
// custom actions here
navigationController?.popViewController(animated: true)
}
var obj={_x000D_
name:"SanD",_x000D_
age:"27"_x000D_
}_x000D_
Object.keys(obj).forEach((key)=>console.log(key,obj[key]));
_x000D_
To loop through JavaScript Object we can use forEach and to optimize code we can use arrow function
No you can't do if in CSS, but you can choose which style sheet you will use
Here is an example :
<!--[if IE 6]>
Special instructions for IE 6 here
<![endif]-->
will use only for IE 6 here is the website where it is from http://www.quirksmode.org/css/condcom.html , only IE has conditional comments. Other browser do not, although there are some properties you can use for Firefox starting with -moz or for safari starting with -webkit. You can use javascript to detect which browser you're using and use javascript if for whatever actions you want to perform but that is a bad idea, since it can be disabled.
Instead of using textbox you can use button also. Works best for me, where I don't want users to write date manually.
think works
Criteria criteria = getSession().createCriteria(clazz);
Criterion rest1= Restrictions.and(Restrictions.eq(A, "X"),
Restrictions.in("B", Arrays.asList("X",Y)));
Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"),
Restrictions.eq(B, "Z"));
criteria.add(Restrictions.or(rest1, rest2));
Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?
I had this issue, and solved. This was due to the WHERE clause contains String value instead of integer value.
If you already have a struct.
import (
"bytes"
"encoding/json"
"io"
"net/http"
"os"
)
// .....
type Student struct {
Name string `json:"name"`
Address string `json:"address"`
}
// .....
body := &Student{
Name: "abc",
Address: "xyz",
}
payloadBuf := new(bytes.Buffer)
json.NewEncoder(payloadBuf).Encode(body)
req, _ := http.NewRequest("POST", url, payloadBuf)
client := &http.Client{}
res, e := client.Do(req)
if e != nil {
return e
}
defer res.Body.Close()
fmt.Println("response Status:", res.Status)
// Print the body to the stdout
io.Copy(os.Stdout, res.Body)
Full gist.
For me it was a silly thing: my mac uploaded the file into iCloud, and that is why Xcode did not find it.
If you turn off the automatic upload, it wont happen again.
If you want to perform this all operation with C programming in the Linux kernel then I suggest to use standard APIs of the Linux kernel.
See https://www.kernel.org/doc/htmldocs/kernel-api/ch02s03.html
set_bit Atomically set a bit in memory
clear_bit Clears a bit in memory
change_bit Toggle a bit in memory
test_and_set_bit Set a bit and return its old value
test_and_clear_bit Clear a bit and return its old value
test_and_change_bit Change a bit and return its old value
test_bit Determine whether a bit is set
Note: Here the whole operation happens in a single step. So these all are guaranteed to be atomic even on SMP computers and are useful to keep coherence across processors.
If you want a really light weight (no dependencies, simple API, 15 kb jar file) and very fast solution, take a look at annotation-detector
found at https://github.com/rmuller/infomas-asl
Disclaimer: I am the author.
There is one simple way by which we can check if file exists or not in S3 bucket. We donot need to use exception for this
sesssion = boto3.Session(aws_access_key_id, aws_secret_access_key)
s3 = session.client('s3')
object_name = 'filename'
bucket = 'bucketname'
obj_status = s3.list_objects(Bucket = bucket, Prefix = object_name)
if obj_status.get('Contents'):
print("File exists")
else:
print("File does not exists")
I remember the way you described it using Visual Basic 6.0. In Visual Studio, the only way I have found so far is by specifying a breakpoint condition.
I did a bit of looking around on the Mac side. You may want to use the installer here as it looks like it does all the setup for you to automatically launch on Mac OS. The only downside is it looks like it's using a pretty old mongo version.
This link here also explains the setup to get mongo automatically launching as a background service on the Mac.
A php file is run whenever you access it via an HTTP request be it GET,POST, PUT.
You can use JQuery/Ajax to send a request on a button click, or even just change the URL of the browser to navigate to the php address.
Depending on the data sent in the POST/GET you can have a switch statement running a different function.
You can utilize the code here: How to call PHP function from string stored in a Variable along with a switch statement to automatically call the appropriate function depending on data sent.
So on PHP side you can have something like this:
<?php
//see http://php.net/manual/en/function.call-user-func-array.php how to use extensively
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction']))
call_user_func($_GET['runFunction']);
else
echo "Function not found or wrong input";
function test()
{
echo("test");
}
function hello()
{
echo("hello");
}
?>
and you can make the simplest get request using the address bar as testing:
http://127.0.0.1/test.php?runFunction=hellodddddd
results in:
Function not found or wrong input
http://127.0.0.1/test.php?runFunction=hello
results in:
hello
GET Request via JQuery
See: http://api.jquery.com/jQuery.get/
$.get("test.cgi", { name: "John"})
.done(function(data) {
alert("Data Loaded: " + data);
});
POST Request via JQuery
See: http://api.jquery.com/jQuery.post/
$.post("test.php", { name: "John"} );
GET Request via Javascript location
See: http://www.javascripter.net/faq/buttonli.htm
<input type=button
value="insert button text here"
onClick="self.location='Your_URL_here.php?name=hello'">
See PHP Turotial for reading post and get: http://www.tizag.com/phpT/postget.php
http://php.net/manual/en/function.call-user-func.php http://php.net/manual/en/function.function-exists.php
I know the question is tagged python, but it mentions dynamic languages so thought I should mention that in ruby the if statement actually has a return type so you can do something like
def foo
rv = if (A > B)
A+1
else
A-1
end
return rv
end
Or because it also has implicit return simply
def foo
if (A>B)
A+1
else
A-1
end
end
which gets around the style issue of not having multiple returns quite nicely.
You can use Django's built-in validators—
from django.db.models import IntegerField, Model
from django.core.validators import MaxValueValidator, MinValueValidator
class CoolModelBro(Model):
limited_integer_field = IntegerField(
default=1,
validators=[
MaxValueValidator(100),
MinValueValidator(1)
]
)
Edit: When working directly with the model, make sure to call the model full_clean method before saving the model in order to trigger the validators. This is not required when using ModelForm
since the forms will do that automatically.
Way 1: only works for dataURL, not for other types of url.
function dataURLtoFile(dataurl, filename) {_x000D_
_x000D_
var arr = dataurl.split(','),_x000D_
mime = arr[0].match(/:(.*?);/)[1],_x000D_
bstr = atob(arr[1]), _x000D_
n = bstr.length, _x000D_
u8arr = new Uint8Array(n);_x000D_
_x000D_
while(n--){_x000D_
u8arr[n] = bstr.charCodeAt(n);_x000D_
}_x000D_
_x000D_
return new File([u8arr], filename, {type:mime});_x000D_
}_x000D_
_x000D_
//Usage example:_x000D_
var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt');_x000D_
console.log(file);
_x000D_
Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)
//return a promise that resolves with a File instance_x000D_
function urltoFile(url, filename, mimeType){_x000D_
return (fetch(url)_x000D_
.then(function(res){return res.arrayBuffer();})_x000D_
.then(function(buf){return new File([buf], filename,{type:mimeType});})_x000D_
);_x000D_
}_x000D_
_x000D_
//Usage example:_x000D_
urltoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt','text/plain')_x000D_
.then(function(file){ console.log(file);});
_x000D_
When multiple threads need to check and change the boolean. For example:
if (!initialized) {
initialize();
initialized = true;
}
This is not thread-safe. You can fix it by using AtomicBoolean
:
if (atomicInitialized.compareAndSet(false, true)) {
initialize();
}
Also you can use faster_than_requests package. That's very fast and simple:
import faster_than_requests as r
content = r.get2str("http://test.com/")
Look at this comparison:
import pytest
class Test:
@pytest.fixture()
def setUp(self):
print("setup")
yield "resource"
print("teardown")
def test_that_depends_on_resource(self, setUp):
print("testing {}".format(setUp))
In order to run:
pytest nam_of_the_module.py -v
hmm, well here's a workaround anyway:
function JSON_stringify(s, emit_unicode)
{
var json = JSON.stringify(s);
return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
function(c) {
return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
}
);
}
test case:
js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"
Properties can return anything they want to, but it's going to need to return the correct type.
private decimal _amount;
public string FormattedAmount
{
get { return string.Format("{0:C}", _amount); }
}
Question was asked... what if it was a nullable decimal.
private decimal? _amount;
public string FormattedAmount
{
get
{
return _amount == null ? "null" : string.Format("{0:C}", _amount.Value);
}
}
Command line arguments are accessible via String[] args
parameter of main
method.
For first argument you can check args[0]
entire code would look like
public static void main(String[] args) {
if ("a".equals(args[0])) {
// do something
}
}
Better use Uri.IsWellFormedUriString(string uriString, UriKind uriKind)
. http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx
Example :-
if(Uri.IsWellFormedUriString(slct.Text,UriKind.Absolute))
{
Uri uri = new Uri(slct.Text);
if (DeleteFileOnServer(uri))
{
nn.BalloonTipText = slct.Text + " has been deleted.";
nn.ShowBalloonTip(30);
}
}
This question is old and although you managed to make it work but I feel it would be helpful if I make clear some of points you have raised here.
First about directory name having spaces. I have been playing with apache2 configuration files and I have discovered that, if the directory name has space then enclose it in double quotes and all problems disappear. For example...
NameVirtualHost local.webapp.org
<VirtualHost local.webapp.org:80>
ServerAdmin [email protected]
DocumentRoot "E:/Project/my php webapp"
ServerName local.webapp.org
</VirtualHost>
Note the way DocumentRoot line is written.
Second is about Access forbidden from xampp. I found that default xampp configuration (..path to xampp/apache/httpd.conf) has a section that looks like the following.
<Directory>
AllowOverride none
Require all denied
</Directory>
Change it and make it look like below. Save the file restart apache from xampp and that solves the problem.
<Directory>
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride none
Require all granted
</Directory>
Ultimately was able to figure it out , i just hope it will help someone like me.
Following is how the web pack config file should look like
check the dist dir and output file specified. I was missing the way to specify the path of dist directory
const webpack = require('webpack');
const path = require('path');
var config = {
entry: './main.js',
output: {
path: path.join(__dirname, '/dist'),
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
resolveLoader: {
modules: [path.join(__dirname, 'node_modules')]
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
}
module.exports = config;
Then the package json file
{
"name": "reactapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack --progress",
"production": "webpack -p --progress"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2",
"webpack": "^2.2.1"
},
"devDependencies": {
"babel-core": "^6.0.20",
"babel-loader": "^6.0.1",
"babel-preset-es2015": "^6.0.15",
"babel-preset-react": "^6.0.15",
"babel-preset-stage-0": "^6.0.15",
"express": "^4.13.3",
"webpack": "^1.9.6",
"webpack-devserver": "0.0.6"
}
}
Notice the script section and production section, production section is what gives you the final deployable index.js file ( name can be anything )
Rest fot the things will depend upon your code and components
Execute following sequence of commands
npm install
this should get you all the dependency (node modules)
then
npm run production
this should get you the final index.js
file which will contain all the code bundled
Once done place index.html
and index.js
files under www/html or the web app root directory and that's all.
@Entity(name = "someThing")
=> this name will be used to identify the domain ..this name will only be identified by hql
queries ..ie ..name of the domain object
@Table(name = "someThing")
=> this name will be used to which table referred by domain object..ie ..name of the table
This solution is for windows:
Here is another way to loop through XML elements using JDOM.
List<Element> nodeNodes = inputNode.getChildren();
if (nodeNodes != null) {
for (Element nodeNode : nodeNodes) {
List<Element> elements = nodeNode.getChildren(elementName);
if (elements != null) {
elements.size();
nodeNodes.removeAll(elements);
}
}
Here is a extension method, this allows coding like the SQL IN command.
public static bool In<T>(this T o, params T[] values)
{
if (values == null) return false;
return values.Contains(o);
}
public static bool In<T>(this T o, IEnumerable<T> values)
{
if (values == null) return false;
return values.Contains(o);
}
This allows stuff like that:
List<int> ints = new List<int>( new[] {1,5,7});
int i = 5;
bool isIn = i.In(ints);
Or:
int i = 5;
bool isIn = i.In(1,2,3,4,5);
On IE7, IE8, and IE9 just go to Settings->Internet Options->Security->Custom Level and change security settings under "Miscellaneous" set "Access data sources across domains" to Enable.
@ECHO OFF
:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/
:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"
:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m
:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m
PAUSE
Why don't you use cURL
?
$yourkey="your api key";
$url="https://prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=$yourkey";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$auth = curl_exec($curl);
if($auth)
{
$json = json_decode($auth);
print_r($json);
}
}
If you happened to know the general location of cell towers, you could check to see if the current cell tower matches the location given (within an error margin of something large, like 10 or more miles).
For example, if your app unlocks features only if the user is in a specific location (your store, for example), you could check gps as well as cell towers. Currently, no gps spoofing app also spoofs the cell towers, so you could see if someone across the country is simply trying to spoof their way into your special features (I'm thinking of the Disney Mobile Magic app, for one example).
This is how the Llama app manages location by default, since checking cell tower ids are much less battery intensive than gps. It isn't useful for very specific locations, but if home and work are several miles away, it can distinguish between the two general locations very easily.
Of course, this would require the user to have a cell signal at all. And you would have to know all the cell towers ids in the area --on all network providers-- or you would run the risk of a false negative.
add $row = mysql_fetch_object($result);
after your mysql_query();
your html <img src="<?php echo $row->dvdimage; ?>" width="175" height="200" />
For Linq to work over Dictionary
you need at least .Net v3.5 and using System.Linq;
.
Some alternatives:
string myDesiredOutput = string.Join(";", myDict.Select(x => string.Join("=", x.Key, x.Value)));
or
string myDesiredOutput = string.Join(";", myDict.Select(x => $"{x.Key}={x.Value}"));
If you can't use Linq for some reason, use Stringbuilder
:
StringBuilder sb = new StringBuilder();
var isFirst = true;
foreach(var x in myDict)
{
if (isFirst)
{
sb.Append($"{x.Key}={x.Value}");
isFirst = false;
}
else
sb.Append($";{x.Key}={x.Value}");
}
string myDesiredOutput = sb.ToString();
myDesiredOutput:
A=1;B=2;C=3;D=4
For SQL Server 2005 and above use Coalesce for nulls
and I am using Cast or Convert if there are numeric values
-
declare @CodeNameString nvarchar(max)
select @CodeNameString = COALESCE(@CodeNameString + ',', '') + Cast(CodeName as varchar) from AccountCodes ORDER BY Sort
select @CodeNameString
Double click and install the production certificate in your key chain. This might resolve the issue.
Just add ?autoplay=1 after url in embed code, example :
<iframe width="420" height="315" src="http://www.youtube.com/embed/
oHg5SJYRHA0" frameborder="0"></iframe>
Change it to:
<iframe width="420" height="315" src="http://www.youtube.com/embed/
oHg5SJYRHA0?autoplay=1" frameborder="0"></iframe>
I had a similar problem, you may find that going to the top right corner of your page in Eclipse and click "Java EE" instead of "Java" will solve your problem. I had EE installed correctly like you, and this solved the issue for me. Hope I helped :)
select cast(score/10 as varchar) + '-' + cast(score/10+9 as varchar),
count(*)
from scores
group by score/10
Or spin Linux instance for SFTP Gateway in your AWS infrastructure that saves uploaded files to your Amazon S3 bucket.
Supported by Thorntech
What about using something like PouchDB? http://pouchdb.com/
To switch to C99 mode in CodeBlocks, follow the next steps:
Click Project/Build options, then in tab Compiler Settings choose subtab Other options, and place -std=c99
in the text area, and click Ok.
This will turn C99 mode on for your Compiler.
I hope this will help someone!
Sounds like you're just trying to do a classic two-column lookup. http://www.dailydoseofexcel.com/archives/2009/04/21/vlookup-on-two-columns/
Tons of solutions for this, most simple is probably the following (which doesn't require an array formula):
=SUMPRODUCT((Lookup!A:A=Param!A1)*(Lookup!B:B=Param!B1)*(Lookup!C:C))
To translate your specific example, you would use:
=SUMPRODUCT((A1:A3=A2)*(B1:B3="B")*(C1:C3))
select myfield, CAST(myfield as varbinary(max)) ...
Just one more suggestion... This was caused for me by some old dll's from an MVC 3 project after upgrading to MVC 5 in the site bin folder on the deployment server. Even though these dll's were no longer used by the code base they appeared to be causing the problem. Cleaned it all out and re-deployed and it was fine.
The class static variables can be declared in the header but must be defined in a .cpp file. This is because there can be only one instance of a static variable and the compiler can't decide in which generated object file to put it so you have to make the decision, instead.
To keep the definition of a static value with the declaration in C++11 a nested static structure can be used. In this case the static member is a structure and has to be defined in a .cpp file, but the values are in the header.
class A
{
private:
static struct _Shapes {
const std::string RECTANGLE {"rectangle"};
const std::string CIRCLE {"circle"};
} shape;
};
Instead of initializing individual members the whole static structure is initialized in .cpp:
A::_Shapes A::shape;
The values are accessed with
A::shape.RECTANGLE;
or -- since the members are private and are meant to be used only from A -- with
shape.RECTANGLE;
Note that this solution still suffers from the problem of the order of initialization of the static variables. When a static value is used to initialize another static variable, the first may not be initialized, yet.
// file.h
class File {
public:
static struct _Extensions {
const std::string h{ ".h" };
const std::string hpp{ ".hpp" };
const std::string c{ ".c" };
const std::string cpp{ ".cpp" };
} extension;
};
// file.cpp
File::_Extensions File::extension;
// module.cpp
static std::set<std::string> headers{ File::extension.h, File::extension.hpp };
In this case the static variable headers will contain either { "" } or { ".h", ".hpp" }, depending on the order of initialization created by the linker.
As mentioned by @abyss.7 you could also use constexpr
if the value of the variable can be computed at compile time. But if you declare your strings with static constexpr const char*
and your program uses std::string
otherwise there will be an overhead because a new std::string
object will be created every time you use such a constant:
class A {
public:
static constexpr const char* STRING = "some value";
};
void foo(const std::string& bar);
int main() {
foo(A::STRING); // a new std::string is constructed and destroyed.
}
?vector
X <- vector(mode="character", length=10)
This will give you empty strings which get printed as two adjacent double quotes, but be aware that there are no double-quote characters in the values themselves. That's just a side-effect of how print.default
displays the values. They can be indexed by location. The number of characters will not be restricted, so if you were expecting to get 10 character element you will be disappointed.
> X[5] <- "character element in 5th position"
> X
[1] "" ""
[3] "" ""
[5] "character element in 5th position" ""
[7] "" ""
[9] "" ""
> nchar(X)
[1] 0 0 0 0 33 0 0 0 0 0
> length(X)
[1] 10
As an aside to those that stumble along across this, one nice way to run test level on using the HostingEnvironment call, is if accessing say a UNC share: \example\ that is mapped to ~/example/ you could execute this to get around IIS-Express issues:
#if DEBUG
var fs = new FileStream(@"\\example\file",FileMode.Open, FileAccess.Read);
#else
var fs = new FileStream(HostingEnvironment.MapPath("~/example/file"), FileMode.Open, FileAccess.Read);
#endif
I find that helpful in case you have rights to locally test on a file, but need the env mapping once in production.
You need to set a height on the DIV. Otherwise it will keep expanding indefinitely.
Finaly I got it!!!
import csv
def select_index(index):
csv_file = open('oscar_age_female.csv', 'r')
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
l = line['Index']
if l == index:
print(line[' "Name"'])
select_index('11')
"Bette Davis"
Here is another solution using css transform (for performance purposes on mobiles, see answer of @mate64 ) without having to use animations and keyframes.
I created two versions to slide-in from either side.
$('#toggle').click(function() {_x000D_
$('.slide-in').toggleClass('show');_x000D_
});
_x000D_
.slide-in {_x000D_
z-index: 10; /* to position it in front of the other content */_x000D_
position: absolute;_x000D_
overflow: hidden; /* to prevent scrollbar appearing */_x000D_
}_x000D_
_x000D_
.slide-in.from-left {_x000D_
left: 0;_x000D_
}_x000D_
_x000D_
.slide-in.from-right {_x000D_
right: 0;_x000D_
}_x000D_
_x000D_
.slide-in-content {_x000D_
padding: 5px 20px;_x000D_
background: #eee;_x000D_
transition: transform .5s ease; /* our nice transition */_x000D_
}_x000D_
_x000D_
.slide-in.from-left .slide-in-content {_x000D_
transform: translateX(-100%);_x000D_
-webkit-transform: translateX(-100%);_x000D_
}_x000D_
_x000D_
.slide-in.from-right .slide-in-content {_x000D_
transform: translateX(100%);_x000D_
-webkit-transform: translateX(100%);_x000D_
}_x000D_
_x000D_
.slide-in.show .slide-in-content {_x000D_
transform: translateX(0);_x000D_
-webkit-transform: translateX(0);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="slide-in from-left">_x000D_
<div class="slide-in-content">_x000D_
<ul>_x000D_
<li>Lorem</li>_x000D_
<li>Ipsum</li>_x000D_
<li>Dolor</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="slide-in from-right">_x000D_
<div class="slide-in-content">_x000D_
<ul>_x000D_
<li>One</li>_x000D_
<li>Two</li>_x000D_
<li>Three</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
I'm not sure that I understand what you mean by "rights of ownership".
If User B owns a stored procedure, User B can grant User A permission to run the stored procedure
GRANT EXECUTE ON b.procedure_name TO a
User A would then call the procedure using the fully qualified name, i.e.
BEGIN
b.procedure_name( <<list of parameters>> );
END;
Alternately, User A can create a synonym in order to avoid having to use the fully qualified procedure name.
CREATE SYNONYM procedure_name FOR b.procedure_name;
BEGIN
procedure_name( <<list of parameters>> );
END;
It turns out that one can get the raw XML by using Provider<Source>, in this way:
import java.io.ByteArrayOutputStream;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.ws.Provider;
import javax.xml.ws.Service;
import javax.xml.ws.ServiceMode;
import javax.xml.ws.WebServiceProvider;
@ServiceMode(value=Service.Mode.PAYLOAD)
@WebServiceProvider()
public class SoapProvider implements Provider<Source>
{
public Source invoke(Source msg)
{
StreamResult sr = new StreamResult();
ByteArrayOutputStream out = new ByteArrayOutputStream();
sr.setOutputStream(out);
try {
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.transform(msg, sr);
// Use out to your heart's desire.
}
catch (TransformerException e) {
e.printStackTrace();
}
return msg;
}
}
I've ended up not needing this solution, so I haven't actually tried this code myself - it might need some tweaking to get right. But I know this is the right path to go down to get the raw XML from a web service.
(I'm not sure how to make this work if you absolutely must have a SOAPMessage object, but then again, if you're going to be handling the raw XML anyways, why would you use a higher-level object?)
thanks to below posts, and I am able to add on the webpage link address to be printed and present time on the PDF generated, no matter how many pages it has.
Add text to Existing PDF using Python
https://github.com/disflux/django-mtr/blob/master/pdfgen/doc_overlay.py
To share the script as below:
import time
from pyPdf import PdfFileWriter, PdfFileReader
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from xhtml2pdf import pisa
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
url = 'http://www.yahoo.com'
tem_pdf = "c:\\tem_pdf.pdf"
final_file = "c:\\younameit.pdf"
app = QApplication(sys.argv)
web = QWebView()
#Read the URL given
web.load(QUrl(url))
printer = QPrinter()
#setting format
printer.setPageSize(QPrinter.A4)
printer.setOrientation(QPrinter.Landscape)
printer.setOutputFormat(QPrinter.PdfFormat)
#export file as c:\tem_pdf.pdf
printer.setOutputFileName(tem_pdf)
def convertIt():
web.print_(printer)
QApplication.exit()
QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)
app.exec_()
sys.exit
# Below is to add on the weblink as text and present date&time on PDF generated
outputPDF = PdfFileWriter()
packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.setFont("Helvetica", 9)
# Writting the new line
oknow = time.strftime("%a, %d %b %Y %H:%M")
can.drawString(5, 2, url)
can.drawString(605, 2, oknow)
can.save()
#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(file(tem_pdf, "rb"))
pages = existing_pdf.getNumPages()
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
for x in range(0,pages):
page = existing_pdf.getPage(x)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = file(final_file, "wb")
output.write(outputStream)
outputStream.close()
print final_file, 'is ready.'
I've opted for a quick Polyfill based on the above answers:
//# Polyfill
window.addEventListener = window.addEventListener || function (e, f) { window.attachEvent('on' + e, f); };
//# Standard usage
window.addEventListener("message", function(){ /*...*/ }, false);
Of course, like the answers above this doesn't ensure that window.attachEvent
exists, which may or may not be an issue.
A simple method to show/hide elements in React using Hooks
const [showText, setShowText] = useState(false);
Now, let's add some logic to our render method:
{showText && <div>This text will show!</div>}
And
onClick={() => setShowText(!showText)}
Good job.
UseParNewGC usually knowns as "parallel young generation collector" is same in all ways as the parallel garbage collector (-XX:+UseParallelGC), except that its more sophiscated and effiecient. Also it can be used with a "concurrent low pause collector".
See Java GC FAQ, question 22 for more information.
Note that there are some known bugs with UseParNewGC
$(document).ready(function() {
var count = $("h1").text().length;
alert(count);
});
Also, you can put your own element id or class instead of "h1" and length event count your characters of text area string ?
Just to add description for another one case. I've got to install similar Vagrant Ubuntu 18.04 based configurations to multiple Ubuntu machines. Downloaded bionic64 box to one using vagrant up
with Vagrantfile
where this box was specified, then copied folder .vagrant.d/boxes/ubuntu-VAGRANTSLASH-bionic64
to others.
I should this On Windows, environment variable expansion is %BUILD_NUMBER%
Tables are not meant for this, why don't you use <div>
's and CSS?
do not forget to insert (or unCommanet) this line at the beginning of your pod file:
platform :iOS, '9.0'
that saves my day
In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.
When I see this on my machine, it's worse than just a "some process has the file open". The actual ownership of the file gets jacked up to the point where I (running as administrator) can only access it after rebooting.
Nearest I can tell, IIS is part of the problem. If I switch between two major branches that require a lot of files to modify, git will delete a file or directory (usually DLLs) while IIS is trying to do something or another with it. At this point, the IIS process automatically overwrites the file on disk with a version that's locked and appears to be owned by nobody.
Stopping IIS at this point doesn't do it. Best I've found out to do is to reboot, and remember to stop IIS before changing across major branches in the future.
I know that doesn't really answer the question, but might be helpful to others.
Here's another looping example. This one also contains an 'if-statement' as an example of checking to see if the entry is a 'file' (or a 'directory' for example):
for f in $(cat 1.txt); do if [ -f $f ]; then rm $f; fi; done
mime_content_type() is deprecated, so you won't be able to count on it working in the future. There is a "fileinfo" PECL extension, but I haven't heard good things about it.
If you are running on a *nix server, you can do the following, which has worked fine for me:
$file = escapeshellarg( $filename );
$mime = shell_exec("file -bi " . $file);
$filename should probably include the absolute path.
i = 20
"%x" % i #=> "14"
For IE9+
@media screen and (min-width:0\0) and (min-resolution: +72dpi) {
// IE9+ CSS
.selector{
color: red;
}
}
IE Edge 12+
@supports (-ms-ime-align: auto) {
.selector {
color: red;
}
}
This one works on Edge and all IEs
:-ms-lang(x), .selector { color: red; }
var obj = {"a": "test1", "b": "test2"};
var getValuesOfObject = Object.values(obj)
for(index = 0; index < getValuesOfObject.length; index++){
return Boolean(getValuesOfObject[index] === "test1")
}
The Object.values() method returned an array (assigned to getValuesOfObject) containing the given object's (obj) own enumerable property values. The array was iterated using the for
loop to retrieve each value (values in the getValuesfromObject) and returns a Boolean() function to find out if the expression ("text1" is a value in the looping array) is true.
By using System.Windows.Forms.Timer
class you can achieve what you need.
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();
void timer_Tick(object sender, EventArgs e)
{
//Call method
}
By using stop() method you can stop timer.
t.Stop();
You could use the 'tailer' library: https://pypi.python.org/pypi/tailer/
It has an option to get the last few lines:
# Get the last 3 lines of the file
tailer.tail(open('test.txt'), 3)
# ['Line 9', 'Line 10', 'Line 11']
And it can also follow a file:
# Follow the file as it grows
for line in tailer.follow(open('test.txt')):
print line
If one wants tail-like behaviour, that one seems to be a good option.
When define some member variable outside any member method, the variable can be either static or non-static depending on how the variable is expressed.
For example:
#!/usr/bin/python
class A:
var=1
def printvar(self):
print "self.var is %d" % self.var
print "A.var is %d" % A.var
a = A()
a.var = 2
a.printvar()
A.var = 3
a.printvar()
The results are
self.var is 2
A.var is 1
self.var is 2
A.var is 3
Actually, you dont really have to code to make the form get to centerscreen.
Just modify the properties of the jframe
Follow below steps to modify:
FormSize
policy to - generate resize codeYou're done. Why take the pain of coding. :)
The phpqrcode library is really fast to configure and the API documentation is easy to understand.
In addition to abaumg's answer I have attached 2 examples in PHP
from http://phpqrcode.sourceforge.net/examples/index.php
1. QR code encoder
first include the library from your local path
include('../qrlib.php');
then to output the image directly as PNG stream do for example:
QRcode::png('your texte here...');
to save the result locally as a PNG image:
$tempDir = EXAMPLE_TMP_SERVERPATH;
$codeContents = 'your message here...';
$fileName = 'qrcode_name.png';
$pngAbsoluteFilePath = $tempDir.$fileName;
$urlRelativeFilePath = EXAMPLE_TMP_URLRELPATH.$fileName;
QRcode::png($codeContents, $pngAbsoluteFilePath);
2. QR code decoder
See also the zxing decoder:
http://zxing.org/w/decode.jspx
Pretty useful to check the output.
3. List of Data format
A list of data format you can use in your QR code according to the data type :
http://
)You can export the private key with the command-line tool from GPG. It works on the Windows-shell. Use the following command:
gpg --export-secret-keys
A normal export with --export
will not include any private keys, therefore you have to use --export-secret-keys
.
Edit:
To sum up the information given in my comments, this is the command that allows you to export a specific key with the ID 1234ABCD to the file secret.asc:
gpg --export-secret-keys --armor 1234ABCD > secret.asc
You can find the ID that you need using the following command. The ID is the second part of the second column:
gpg --list-keys
To Export just 1 specific secret key instead of all of them:
gpg --export-secret-keys keyIDNumber > exportedKeyFilename.asc
keyIDNumber is the number of the key id for the desired key you are trying to export.
You need to delete your old db folder and recreate new one. It will resolve your issue.
function printInt(n) { return n.toPrecision(100).replace(/\..*/,""); }
with some issues:
The []
s in a regex denote a character class. If no ranges are specified, it implicitly ors every character within it together. Thus, [abcde]
is the same as (a|b|c|d|e)
, except that it doesn't capture anything; it will match any one of a
, b
, c
, d
, or e
. All a range indicates is a set of characters; [ac-eg]
says "match any one of: a
; any character between c
and e
; or g
". Thus, your match says "match any one of: 0
; any character between 1
and 1
(i.e., just 1
); or 2
.
Your goal is evidently to specify a number range: any number between 01
and 12
written with two digits. In this specific case, you can match it with 0[1-9]|1[0-2]
: either a 0
followed by any digit between 1
and 9
, or a 1
followed by any digit between 0
and 2
. In general, you can transform any number range into a valid regex in a similar manner. There may be a better option than regular expressions, however, or an existing function or module which can construct the regex for you. It depends on your language.
You are probably printing from a signed char array. Either print from an unsigned char array or mask the value with 0xff: e.g. ar[i] & 0xFF. The c0 values are being sign extended because the high (sign) bit is set.
For anybody reading this in 2019, after React 16.8 was released, take a look at the React Hooks. It really simplifies handling states in components. The docs are very well written with an example of exactly what you need.
Just a test which is working fine.
#parent{
width: 100%;
height: 100%;
overflow: hidden;
}
#child{
width: 100%;
height: 100%;
overflow-y: scroll;
padding-right: 17px; /* Increase/decrease this value for cross-browser compatibility */
box-sizing: content-box; /* So the width will be 100% + 17px */
}
Since the scrollbar width differs in different browsers, it is better to handle it with JavaScript. If you do Element.offsetWidth - Element.clientWidth
, the exact scrollbar width will show up.
Using Position: absolute
,
#parent{
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
}
#child{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: -17px; /* Increase/Decrease this value for cross-browser compatibility */
overflow-y: scroll;
}
Based on this answer, I created a simple scroll plugin.
Since MySQL (8.0.16) and MariaDB (10.2.1) both implemented the CHECK constraint, I would now use
bool_val TINYINT CHECK(bool_val IN(0,1))
You will only be able to store 0
, 1
or NULL
, as well as values which can be converted to 0
or 1
without errors like '1'
, 0x00
, b'1'
or TRUE
/FALSE
.
If you don't want to permit NULLs, add the NOT NULL
option
bool_val TINYINT NOT NULL CHECK(bool_val IN(0,1))
Note that there is virtually no difference if you use TINYINT
, TINYINT(1)
or TINYINT(123)
.
If you want your schema to be upwards compatible, you can also use BOOL
or BOOLEAN
bool_val BOOL CHECK(bool_val IN(TRUE,FALSE))
You can reach main page with parent command (parent is the window) after the step you can make everything...
function funcx() {
var result = confirm('bla bla bla.!');
if(result)
//parent.location.assign("http://localhost:58250/Ekocc/" + document.getElementById('hdnLink').value + "");
parent.location.assign("http://blabla.com/" + document.getElementById('hdnLink').value + "");
}
An easy way to print the sorted contents of the dictionary, in Python 3:
>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> for key, value in sorted(dict_example.items()):
... print("{} : {}".format(key, value))
...
a : 3
b : 2
c : 1
The expression dict_example.items()
returns tuples, which can then be sorted by sorted()
:
>>> dict_example.items()
dict_items([('c', 1), ('b', 2), ('a', 3)])
>>> sorted(dict_example.items())
[('a', 3), ('b', 2), ('c', 1)]
Below is an example to pretty print the sorted contents of a Python dictionary's values.
for key, value in sorted(dict_example.items(), key=lambda d_values: d_values[1]):
print("{} : {}".format(key, value))
This worked great I just add the -a option to ping to resolve the hostname. Thanks https://stackoverflow.com/users/4447323/wombat
@echo off setlocal enabledelayedexpansion set OUTPUT_FILE=result.csv
>nul copy nul %OUTPUT_FILE%
echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
set SERVER_ADDRESS_I=UNRESOLVED
set SERVER_ADDRESS_L=UNRESOLVED
for /f "tokens=1,2,3" %%x in ('ping -n 1 -a %%i ^&^& echo SERVER_IS_UP') do (
if %%x==Pinging set SERVER_ADDRESS_L=%%y
if %%x==Pinging set SERVER_ADDRESS_I=%%z
if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
)
If anyone using bootstrap 4 and looking for equal height columns just use row-eq-height
to parent div
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="row row-eq-height">_x000D_
<div class="col-xs-4" style="border: 1px solid grey;">.row.row-eq-height > .col-xs-4</div>_x000D_
<div class="col-xs-4" style="border: 1px solid grey;">.row.row-eq-height > .col-xs-4<br>this is<br>a much<br>taller<br>column<br>than the others</div>_x000D_
<div class="col-xs-4" style="border: 1px solid grey;">.row.row-eq-height > .col-xs-4</div>_x000D_
</div>
_x000D_
Ref: http://getbootstrap.com.vn/examples/equal-height-columns/
If a
is your array:
In [11]: a[:,:2]
Out[11]:
array([[-0.57098887, -0.4274751 ],
[-0.22279713, -0.51723555],
[ 0.67492385, -0.69294472],
[ 0.41086611, 0.26374238]])
This one $("#yourDiv").load(" #yourDiv > *");
is the best if you are planning to just reload a <div>
Make sure to use an id
and not a class
. Also, remember to paste <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
in the <head>
section of the html file, if you haven't already. In opposite case it won't work.
Here is an implementation of a single key to multi value map in C# which uses a set based key type:
https://github.com/ColmBhandal/CsharpExtras/blob/master/CsharpExtras/Dictionary/MultiValueMapImpl.cs
The dictionary behaves like a regular dictionary from the key type onto a set of the value type, but also provides functionality to directly add a single value of the value type, and in the background handles the creation of an underlying set and/or addition to that set.
This is correct.
A[] a = new A[4];
...creates 4 A
references, similar to doing this:
A a1;
A a2;
A a3;
A a4;
Now you couldn't do a1.someMethod()
without allocating a1
like this:
a1 = new A();
Similarly, with the array you need to do this:
a[0] = new A();
...before using it.
def exit(self):
self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)
This worked for me to destroy my Tkinter frame on clicking the exit button.
Here's another way to be compatible with an IHttpActionResult return type. In this case I am asking it to use the XML Serializer(optional) instead of Data Contract serializer, I'm using return ResponseMessage(
so that I get a return compatible with IHttpActionResult:
return ResponseMessage(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<SomeType>(objectToSerialize,
new System.Net.Http.Formatting.XmlMediaTypeFormatter {
UseXmlSerializer = true
})
});
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
You could use a div
with a background image instead and this CSS3 property:
background-size: contain
You can check out an example on:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#contain
To quote Mozilla:
The contain value specifies that regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container.
However, keep in mind that your image will be upscaled if the div
is larger than your original image.
UIAlertViews
use a delegate to communicate with you, the client.
You add a second button, and you create an object to receive the delegate messages from the view:
class LogInErrorDelegate : UIAlertViewDelegate {
init {}
// not sure of the prototype of this, you should look it up
func alertView(view :UIAlertView, clickedButtonAtIndex :Integer) -> Void {
switch clickedButtonAtIndex {
case 0:
userClickedOK() // er something
case 1:
userClickedRetry()
/* Don't use "retry" as a function name, it's a reserved word */
default:
userClickedRetry()
}
}
/* implement rest of the delegate */
}
logInErrorAlert.addButtonWithTitle("Retry")
var myErrorDelegate = LogInErrorDelegate()
logInErrorAlert.delegate = myErrorDelegate
I was looking for a solution to transpose any kind of matrix (nxn or mxn) with any kind of data (numbers or data) and got the following solution:
Row2Trans=number1
Col2Trans=number2
for ((i=1; $i <= Line2Trans; i++));do
for ((j=1; $j <=Col2Trans ; j++));do
awk -v var1="$i" -v var2="$j" 'BEGIN { FS = "," } ; NR==var1 {print $((var2)) }' $ARCHIVO >> Column_$i
done
done
paste -d',' `ls -mv Column_* | sed 's/,//g'` >> $ARCHIVO
Could be a few problems here depending on what version of grunt is being used. Newer versions of grunt actually specify that you have a file named Gruntfile.js
(instead of the old grunt.js
).
You should have the grunt-cli
tool be installed globally (this is done via npm install -g grunt-cli
). This allows you to actually run grunt
commands from the command line.
Secondly make sure you've installed grunt locally for your project. If you see your package.json
doesn't have something like "grunt": "0.4.5"
in it then you should do npm install grunt --save
in your project directory.
I like using (open source and gui friendly) Quantum GIS to convert the shapefile to kml.
Google Maps API supports only a subset of the KML standard. One limitation is file size.
To reduce your file size, you can Quantum GIS's "simplify geometries" function. This "smooths" polygons.
Then you can select your layer and do a "save as kml" on it.
If you need to process a bunch of files, the process can be batched with Quantum GIS's ogr2ogr command from osgeo4w shell.
Finally, I recommend zipping your kml (with your favorite compression program) for reduced file size and saving it as kmz.
Here's a script that will use the Google API to acquire the users postal code and populate an input field.
function postalCodeLookup(input) {
var head= document.getElementsByTagName('head')[0],
script= document.createElement('script');
script.src= '//maps.googleapis.com/maps/api/js?sensor=false';
head.appendChild(script);
script.onload = function() {
if (navigator.geolocation) {
var a = input,
fallback = setTimeout(function () {
fail('10 seconds expired');
}, 10000);
navigator.geolocation.getCurrentPosition(function (pos) {
clearTimeout(fallback);
var point = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
new google.maps.Geocoder().geocode({'latLng': point}, function (res, status) {
if (status == google.maps.GeocoderStatus.OK && typeof res[0] !== 'undefined') {
var zip = res[0].formatted_address.match(/,\s\w{2}\s(\d{5})/);
if (zip) {
a.value = zip[1];
} else fail('Unable to look-up postal code');
} else {
fail('Unable to look-up geolocation');
}
});
}, function (err) {
fail(err.message);
});
} else {
alert('Unable to find your location.');
}
function fail(err) {
console.log('err', err);
a.value('Try Again.');
}
};
}
You can adjust accordingly to acquire different information. For more info, check out the Google Maps API documentation.
I have found a pretty big difference in timing when testing in my browser.
I used the following script:
WARNING: running this will freeze your browser a bit, might even crash it.
var n = 10000000, i;_x000D_
i = n;_x000D_
console.time('selector');_x000D_
while (i --> 0){_x000D_
$("body");_x000D_
}_x000D_
_x000D_
console.timeEnd('selector');_x000D_
_x000D_
i = n;_x000D_
console.time('element');_x000D_
while (i --> 0){_x000D_
$(document.body);_x000D_
}_x000D_
_x000D_
console.timeEnd('element');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
I did 10 million interactions, and those were the results (Chrome 65):
selector: 19591.97509765625ms
element: 4947.8759765625ms
Passing the element directly is around 4 times faster than passing the selector.
Well, you're on the right path, Benno!
There are some tips regarding VBA programming that might help you out.
Use always explicit references to the sheet you want to interact with. Otherwise, Excel may 'assume' your code applies to the active sheet and eventually you'll see it screws your spreadsheet up.
As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.
Explicitly declare your variables... they'll show the list of methods each object offers in VBA. It might save your time digging on the internet.
Now, let's have a draft code...
Remember this code must be within the Excel Sheet object, as explained by lionz. It only applies to Sheet 2, is up to you to adapt it to both Sheet 2 and Sheet 3 in the way you prefer.
Hope it helps!
Private Sub Worksheet_Change(ByVal Target As Range)
Dim oSheet As Excel.Worksheet
'We only want to do something if the changed cell is B6, right?
If Target.Address = "$B$6" Then
'Checks if it's a number...
If IsNumeric(Target.Value) Then
'Let's avoid values out of your bonds, correct?
If Target.Value > 0 And Target.Value < 51 Then
'Let's assign the worksheet we'll show / hide rows to one variable and then
' use only the reference to the variable itself instead of the sheet name.
' It's safer.
'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent
' the sheet index within the workbook
Set oSheet = ActiveWorkbook.Sheets("Sheet 2")
'We'll unhide before hide, to ensure we hide the correct ones
oSheet.Range("A7:A56").EntireRow.Hidden = False
oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True
End If
End If
End If
End Sub
I know that this is late answer, maybe helpful for researchers
if (!WindowName.IsVisible)
{
WindowName.Show();
WindowName.Activate();
}
Just to add to mopoke's answer, it's also a matter of semantics. or
is considered to be a good practice because it reads much better than ||
.
Best to import x1 and x2 explicitly:
from file1 import x1, x2
This allows you to avoid unnecessary namespace conflicts with variables and functions from file1
while working in file2
.
But if you really want, you can import all the variables:
from file1 import *
Things to check when enabling the bundle optimization;
BundleTable.EnableOptimizations = true;
and
webconfig debug = "false"
bundles.IgnoreList.Clear();
this will ignore the minified assets of your bundles like *.min.css
or *.min.js
which can cause an undefine error of your script. To fix is replace the .min
asset to original. if you do this you may not need the bundles.IgnoreList.Clear();
e.g.
bundles.Add(new ScriptBundle("~/bundles/datatablesjs")
.Include("~/Scripts/datatables.min.js") <---- change this to non minified ver.
Make sure the names of the bundles of your css and js are unique.
bundles.Add(new StyleBundle("~/bundles/datatablescss").Include( ...) );
bundles.Add(new ScriptBundle("~/bundles/datatablesjs").Include( ...) );
Make sure you use the Render name of your @Script.Render and Style.Render are the same on your bundle config. e.g.
@Styles.Render("~/bundles/datatablescss")
@Scripts.Render("~/bundles/datatablesjs")
Thought I'd add this bit for people who come looking for "How to pass a connection string to a DbContext": You can construct a connection string for your underlying datastore and pass the entire connection string to the constructor of your type derived from DbContext.
(Re-using Code from @Lol Coder) Model & Context
public class Dinner
{
public int DinnerId { get; set; }
public string Title { get; set; }
}
public class NerdDinners : DbContext
{
public NerdDinners(string connString)
: base(connString)
{
}
public DbSet<Dinner> Dinners { get; set; }
}
Then, say you construct a Sql Connection string using the SqlConnectioStringBuilder like so:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(GetConnectionString());
Where the GetConnectionString method constructs the appropriate connection string and the SqlConnectionStringBuilder ensures the connection string is syntactically correct; you may then instantiate your db conetxt like so:
var myContext = new NerdDinners(builder.ToString());
I had this issue too, also running on an emulator.. The same message was showing up on Logcat, but it wasn't affecting the functionality of the app. But it was annoying, and I don't like seeing errors on the log that I don't understand.
Anyway, I got rid of the message by increasing the RAM on the emulator.
Now with xCode 8 you can do:
? + ? + /
to auto-generate a doc comment.
Source: https://twitter.com/felix_schwarz/status/774166330161233920
Use option bty = "n"
in legend
to remove the box around the legend. For example:
legend(1, 5,
"This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",
bty = "n")
When using merged columns, I got it centered by using PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS instead of PHPExcel_Style_Alignment::HORIZONTAL_CENTER
just need putting the datatype of the column in the datasource
dataSource: {
data: empModel.Value,
pageSize: 10,
schema: {
model: {
fields: {
DOJ: { type: "date" }
}
}
}
}
and then your statement column:
columns: [
{
field: "Name",
width: 90,
title: "Name"
},
{
field: "DOJ",
width: 90,
title: "DOJ",
type: "date",
format:"{0:MM-dd-yyyy}"
}
]
If you want a previous version of file, I would recommend using git checkout.
git checkout <commit-hash>
Doing this will send you back in time, it does not affect the current state of your project, you can come to mainline git checkout mainline
but when you add a file in the argument, that file is brought back to you from a previous time to your current project time, i.e. your current project is changed and needs to be committed.
git checkout <commit-hash> -- file_name
git add .
git commit -m 'file brought from previous time'
git push
The advantage of this is that it does not delete history, and neither does revert a particular code changes (git revert)
Check more here https://www.atlassian.com/git/tutorials/undoing-changes#git-checkout
Breaking down your code example (Explanations are under the line of code.)
import cv2
imports openCV for usage
camera = cv2.VideoCapture(0)
creates an object called camera, of type openCV video capture, using the first camera in the list of cameras connected to the computer.
for i in range(10):
tells the program to loop the following indented code 10 times
return_value, image = camera.read()
read values from the camera object, using it's read method. it resonds with 2 values save the 2 data values into two temporary variables called "return_value" and "image"
cv2.imwrite('opencv'+str(i)+'.png', image)
use the openCV method imwrite (that writes an image to a disk) and write an image using the data in the temporary data variable
fewer indents means that the loop has now ended...
del(camera)
deletes the camrea object, we no longer needs it.
you can what you request in many ways, one could be to replace the for loop with a while loop, (running forever, instead of 10 times), and then wait for a keypress (like answered by danidee while I was typing)
or create a much more evil service that hides in the background and captures an image everytime someone presses the keyboard...
Try this
String str="10,692,467,440,017.120".replaceAll(",","");
BigDecimal bd=new BigDecimal(str);
To copy conditional formatting from google spreadsheet (doc1) to another (doc2) you need to do the following:
There's 3 ways to clear file input with javascript:
set value property to empty or null.
Works for IE11+ and other modern browsers.
Create an new file input element and replace the old one.
The disadvantage is you will lose event listeners and expando properties.
Reset the owner form via form.reset() method.
To avoid affecting other input elements in the same owner form, we can create an new empty form and append the file input element to this new form and reset it. This way works for all browsers.
I wrote a javascript function. demo: http://jsbin.com/muhipoye/1/
function clearInputFile(f){
if(f.value){
try{
f.value = ''; //for IE11, latest Chrome/Firefox/Opera...
}catch(err){ }
if(f.value){ //for IE5 ~ IE10
var form = document.createElement('form'),
parentNode = f.parentNode, ref = f.nextSibling;
form.appendChild(f);
form.reset();
parentNode.insertBefore(f,ref);
}
}
}
actual error thrown Message=Unrecognized element 'providers' in web.config so from the web.config file remove the providers section
Settings
(or Preferences
if you are on Mac) | Editor
| General
| Appearance
and check Show line numbers
.
I feel like none of the answers really solve the issue. I think you need to tell the embedded server of Spring Boot what should be the maximum time to process a request. How exactly we do that is dependent on the type of the embedded server used.
In case of Undertow, one can do this:
@Component
class WebServerCustomizer : WebServerFactoryCustomizer<UndertowServletWebServerFactory> {
override fun customize(factory: UndertowServletWebServerFactory) {
factory.addBuilderCustomizers(UndertowBuilderCustomizer {
it.setSocketOption(Options.READ_TIMEOUT, 5000)
it.setSocketOption(Options.WRITE_TIMEOUT, 25000)
})
}
}
Spring Boot official doc: https://docs.spring.io/spring-boot/docs/2.2.0.RELEASE/reference/html/howto.html#howto-configure-webserver
As Pekka stated above
foreach ($array as $key => $value)
Also you might want to try a recursive function
displayRecursiveResults($site);
function displayRecursiveResults($arrayObject) {
foreach($arrayObject as $key=>$data) {
if(is_array($data)) {
displayRecursiveResults($data);
} elseif(is_object($data)) {
displayRecursiveResults($data);
} else {
echo "Key: ".$key." Data: ".$data."<br />";
}
}
}
;WITH u AS (
SELECT Unit FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) v(Unit)
),
d AS (
SELECT
(Thousands+Hundreds+Tens+Units) V
FROM
(SELECT Thousands = Unit * 1000 FROM u) Thousands
,(SELECT Hundreds = Unit * 100 FROM u) Hundreds
,(SELECT Tens = Unit * 10 FROM u) Tens
,(SELECT Units = Unit FROM u) Units
WHERE
(Thousands+Hundreds+Tens+Units) <= 10000
)
SELECT * FROM d ORDER BY v
#include <boost/algorithm/string/trim.hpp>
[...]
std::string msg = " some text with spaces ";
boost::algorithm::trim(msg);
ansible-playbook release.yml -e "version=1.23.45 other_variable=foo"
It doesn't. There's a vague equivalent:
mycol VARCHAR(10) NOT NULL CHECK (mycol IN('Useful', 'Useless', 'Unknown'))
It is possible to use the host_name() function
select HOST_NAME()
Using some of the knowledge from this and a couple of other posts, I found the method that worked the best for me was to:
adb shell 'stty raw; screencap -p'
I have posted a very simple Python script on GitHub that essentially mirrors the screen of a device connected over ADB:
Here's a list of keycodes that includes a way to look them up interactively.
By MSDN
The .NET Framework includes the following three predefined IFormatProvider implementations to provide culture-specific information that is used in formatting or parsing numeric and date and time values:
NumberFormatInfo
class, which provides information that is used to format numbers, such as the currency, thousands separator, and decimal separator symbols for a particular culture. For information about the predefined format strings recognized by a NumberFormatInfo
object and used in numeric formatting operations, see Standard Numeric Format Strings and Custom Numeric Format Strings.DateTimeFormatInfo
class, which provides information that is used to format dates and times, such as the date and time separator symbols for a particular culture or the order and format of a date's year, month, and day components. For information about the predefined format strings recognized by a DateTimeFormatInfo
object and used in numeric formatting operations, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.CultureInfo
class, which represents a particular culture. Its GetFormat
method returns a culture-specific NumberFormatInfo
or DateTimeFormatInfo
object, depending on whether the CultureInfo
object is used in a formatting or parsing operation that involves numbers or dates and times.The .NET Framework also supports custom formatting. This typically involves the creation of a formatting class that implements both IFormatProvider and ICustomFormatter. An instance of this class is then passed as a parameter to a method that performs a custom formatting operation, such as String.Format(IFormatProvider, String, Object[])
.
IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'Database Name'
and TABLE_SCHEMA = 'Schema Name'
and TABLE_NAME = 'Table Name'
and COLUMN_NAME = 'Column Name'
and DATA_TYPE = 'Column Type') -- Where statement lines can be deleted.
BEGIN
--COLUMN EXISTS IN TABLE
END
ELSE BEGIN
--COLUMN DOES NOT EXISTS IN TABLE
END
Windows: Mostly C and C++, some C#
Is there a specific reason that you need to change the tag? If you just want to make the text bigger, changing the p tag's CSS class would be a better way to go about that.
Something like this:
$('#change').click(function(){
$('p').addClass('emphasis');
});
Newer versions of ARC(Advaced Rest client) also provides file upload option:
find the main differences between JWT & OAuth
OAuth 2.0 defines a protocol & JWT defines a token format.
OAuth can use either JWT as a token format or access token which is a bearer token.
OpenID connect mostly use JWT as a token format.
I use:
Intent sendIntent = new Intent(Intent.ACTION_MAIN);
sendIntent.putExtra("sms_body", "text");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
$d = new DateTime('10-16-2003');
$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16
Edit: you can also pass a DateTimeZone to DateTime() constructor to ensure the creation of the date for the desired time zone, not the server default one.
A slight generalization to Peter's answer -- you can specify a range over the original array's shape if you want to go beyond three dimensional arrays.
e.g. to flatten all but the last two dimensions:
arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)
EDIT: A slight generalization to my earlier answer -- you can, of course, also specify a range at the beginning of the of the reshape too:
arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)
Do this:
<div id="sampleDiv">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div>
#sampleDiv{
overflow-wrap: break-word;
}
Just a simplification of the Tim's answer. The groovy way to do it is using a map, as already suggested, but then let's put the mandatory parameters also in the map. This will look like this:
def someMethod(def args) {
println "MANDATORY1=${args.mandatory1}"
println "MANDATORY2=${args.mandatory2}"
println "OPTIONAL1=${args?.optional1}"
println "OPTIONAL2=${args?.optional2}"
}
someMethod mandatory1:1, mandatory2:2, optional1:3
with the output:
MANDATORY1=1
MANDATORY2=2
OPTIONAL1=3
OPTIONAL2=null
This looks nicer and the advantage of this is that you can change the order of the parameters as you like.
If want to remove the word from only the start of the string, then you could do:
string[string.startswith(prefix) and len(prefix):]
Where string is your string variable and prefix is the prefix you want to remove from your string variable.
For example:
>>> papa = "papa is a good man. papa is the best."
>>> prefix = 'papa'
>>> papa[papa.startswith(prefix) and len(prefix):]
' is a good man. papa is the best.'
According to the documentation, $lookup can join only one external collection.
What you could do is to combine userInfo
and userRole
in one collection, as provided example is based on relational DB schema. Mongo is noSQL database - and this require different approach for document management.
Please find below 2-step query, which combines userInfo with userRole - creating new temporary collection used in last query to display combined data. In last query there is an option to use $out and create new collection with merged data for later use.
create collections
db.sivaUser.insert(
{
"_id" : ObjectId("5684f3c454b1fd6926c324fd"),
"email" : "[email protected]",
"userId" : "AD",
"userName" : "admin"
})
//"userinfo"
db.sivaUserInfo.insert(
{
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"phone" : "0000000000"
})
//"userrole"
db.sivaUserRole.insert(
{
"_id" : ObjectId("56d82612b63f1c31cf906003"),
"userId" : "AD",
"role" : "admin"
})
"join" them all :-)
db.sivaUserInfo.aggregate([
{$lookup:
{
from: "sivaUserRole",
localField: "userId",
foreignField: "userId",
as: "userRole"
}
},
{
$unwind:"$userRole"
},
{
$project:{
"_id":1,
"userId" : 1,
"phone" : 1,
"role" :"$userRole.role"
}
},
{
$out:"sivaUserTmp"
}
])
db.sivaUserTmp.aggregate([
{$lookup:
{
from: "sivaUser",
localField: "userId",
foreignField: "userId",
as: "user"
}
},
{
$unwind:"$user"
},
{
$project:{
"_id":1,
"userId" : 1,
"phone" : 1,
"role" :1,
"email" : "$user.email",
"userName" : "$user.userName"
}
}
])
Here's some more benchmarks for Docker based memcached server
versus host native memcached server
using Twemperf benchmark tool https://github.com/twitter/twemperf with 5000 connections and 20k connection rate
Connect time overhead for docker based memcached seems to agree with above whitepaper at roughly twice native speed.
Twemperf Docker Memcached
Connection rate: 9817.9 conn/s
Connection time [ms]: avg 341.1 min 73.7 max 396.2 stddev 52.11
Connect time [ms]: avg 55.0 min 1.1 max 103.1 stddev 28.14
Request rate: 83942.7 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 83942.7 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 28.6 min 1.2 max 65.0 stddev 0.01
Response time [ms]: p25 24.0 p50 27.0 p75 29.0
Response time [ms]: p95 58.0 p99 62.0 p999 65.0
Twemperf Centmin Mod Memcached
Connection rate: 11419.3 conn/s
Connection time [ms]: avg 200.5 min 0.6 max 263.2 stddev 73.85
Connect time [ms]: avg 26.2 min 0.0 max 53.5 stddev 14.59
Request rate: 114192.6 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 114192.6 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 17.4 min 0.0 max 28.8 stddev 0.01
Response time [ms]: p25 12.0 p50 20.0 p75 23.0
Response time [ms]: p95 28.0 p99 28.0 p999 29.0
Here's bencmarks using memtier benchmark tool
memtier_benchmark docker Memcached
4 Threads
50 Connections per thread
10000 Requests per thread
Type Ops/sec Hits/sec Misses/sec Latency KB/sec
------------------------------------------------------------------------
Sets 16821.99 --- --- 1.12600 2271.79
Gets 168035.07 159636.00 8399.07 1.12000 23884.00
Totals 184857.06 159636.00 8399.07 1.12100 26155.79
memtier_benchmark Centmin Mod Memcached
4 Threads
50 Connections per thread
10000 Requests per thread
Type Ops/sec Hits/sec Misses/sec Latency KB/sec
------------------------------------------------------------------------
Sets 28468.13 --- --- 0.62300 3844.59
Gets 284368.51 266547.14 17821.36 0.62200 39964.31
Totals 312836.64 266547.14 17821.36 0.62200 43808.90
You can use this
moment().format("DD/MM/YYYY");
However, this returns a date string in the specified format for today, not a moment date object. Doing the following will make it a moment date object in the format you want.
var someDateString = moment().format("DD/MM/YYYY");
var someDate = moment(someDateString, "DD/MM/YYYY");
td style is not necessary but will make it easier to see this example in browser
<table>
<tr>
<td style="border: 1px solid black; width: 200px;">
<div style="width: 50%; float: left; text-align: left;">left</div>
<div style="width: 50%; float: left; text-align: right;">right</div>
</td>
</tr>
</table>
I also like to define my own functions that take and return arguments in degrees rather than radians. I am sure there some capitalization purest who don't like my names, but I just use a capital first letter for my custom functions. The definitions and testing code are below.
#Definitions for trig functions using degrees.
def Cos(a):
return cos(radians(a))
def Sin(a):
return sin(radians(a))
def Tan(a):
return tan(radians(a))
def ArcTan(a):
return degrees(arctan(a))
def ArcSin(a):
return degrees(arcsin(a))
def ArcCos(a):
return degrees(arccos(a))
#Testing Code
print(Cos(90))
print(Sin(90))
print(Tan(45))
print(ArcTan(1))
print(ArcSin(1))
print(ArcCos(0))
Note that I have imported math (or numpy) into the namespace with
from math import *
Also note, that my functions are in the namespace in which they were defined. For instance,
math.Cos(45)
does not exist.
Firstly, it probably depends which version of Solaris you're running, but also what hardware you have.
On SPARC at least, you have psrinfo
to show you processor information, which run on its own will show you the number of CPU
s the machine sees. psrinfo -p
shows you the number of physical processors installed. From that you can deduce the number of threads/cores per physical processors.
prtdiag
will display a fair bit of info about the hardware in your machine. It looks like on a V240 you do get memory channel info from prtdiag
, but you don't on a T2000. I guess that's an architecture issue between UltraSPARC IIIi and UltraSPARC T1.
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
Your /home/gnu/bin/c++
seem to require additional flag to link things properly and CMake doesn't know about that.
To use /usr/bin/c++
as your compiler run cmake
with -DCMAKE_CXX_COMPILER=/usr/bin/c++
.
Also, CMAKE_PREFIX_PATH
variable sets destination dir where your project' files should be installed. It has nothing to do with CMake installation prefix and CMake itself already know this.
If you are talking about cache that is been used for caching of templates without reloading whole page, then you can empty it by something like:
.controller('mainCtrl', function($scope, $templateCache) {
$scope.clearCache = function() {
$templateCache.removeAll();
}
});
And in markup:
<button ng-click='clearCache()'>Clear cache</button>
And press this button to clear cache.
The get
method of a dict (like for example characters
) works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError
it returns the default value (if you call .get
with just one argument, the key, the default value is None
).
So an equivalent Python function (where calling myget(d, k, v)
is just like d.get(k, v)
might be:
def myget(d, k, v=None):
try: return d[k]
except KeyError: return v
The sample code in your question is clearly trying to count the number of occurrences of each character: if it already has a count for a given character, get
returns it (so it's just incremented by one), else get
returns 0 (so the incrementing correctly gives 1
at a character's first occurrence in the string).
Inside sublime editor,Find the Tab named View
,
View --> Layout --> "select your need"
This is example code that works for sure. It took me a day to make this to read a set of objects from a REST service:
RootObject is the type of the object I'm reading from the REST service.
string url = @"http://restcountries.eu/rest/v1";
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(IEnumerable<RootObject>));
WebClient syncClient = new WebClient();
string content = syncClient.DownloadString(url);
using (MemoryStream memo = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
IEnumerable<RootObject> countries = (IEnumerable<RootObject>)serializer.ReadObject(memo);
}
Console.Read();
Use os.path.join to combine the path to the Documents
directory with the completeName
(filename?) supplied by the user.
import os
with open(os.path.join('/path/to/Documents',completeName), "w") as file1:
toFile = raw_input("Write what you want into the field")
file1.write(toFile)
If you want the Documents
directory to be relative to the user's home directory, you could use something like:
os.path.join(os.path.expanduser('~'),'Documents',completeName)
Others have proposed using os.path.abspath
. Note that os.path.abspath
does not resolve '~'
to the user's home directory:
In [10]: cd /tmp
/tmp
In [11]: os.path.abspath("~")
Out[11]: '/tmp/~'
This was the code that worked for me when the column Id is unknown and the AutoGenerateColumns == true;
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Drawing" %>
<html>
<head runat="server">
<script runat="server">
protected void Page_Load(object sender, EventArgs eventArgs)
{
DataTable data = new DataTable();
data.Columns.Add("Id", typeof(int));
data.Columns.Add("Notes", typeof(string));
data.Columns.Add("RequestedDate", typeof(DateTime));
for (int idx = 0; idx < 5; idx++)
{
DataRow row = data.NewRow();
row["Id"] = idx;
row["Notes"] = string.Format("Note {0}", idx);
row["RequestedDate"] = DateTime.Now.Subtract(new TimeSpan(idx, 0, 0, 0, 0));
data.Rows.Add(row);
}
listData.DataSource = data;
listData.DataBind();
}
private void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (TableCell tableCell in e.Row.Cells)
{
DataControlFieldCell cell = (DataControlFieldCell)tableCell;
if (cell.ContainingField.HeaderText == "Id")
{
cell.Visible = false;
continue;
}
if (cell.ContainingField.HeaderText == "Notes")
{
cell.Width = 400;
cell.BackColor = Color.Blue;
continue;
}
if (cell.ContainingField.HeaderText == "RequestedDate")
{
cell.Width = 130;
continue;
}
}
}
</script>
</head>
<body>
<form runat="server">
<asp:GridView runat="server" ID="listData" AutoGenerateColumns="True" HorizontalAlign="Left"
PageSize="20" OnRowDataBound="GridView_RowDataBound" EmptyDataText="No Data Available."
Width="95%">
</asp:GridView>
</form>
</body>
</html>
just use pow(a,b)
,which is exactly 3**4
in python
Azure Data Studio - free and from Microsoft - offers automatic formatting (ctrl + shift + p while editing -> format document). More information about Azure Data Studio here.
While this is not SSMS, it's great for writing queries, free and an official product from Microsoft. It's even cross-platform. Short story: Just switch to Azure Data Studio to write your queries!
Update: Actually Azure Data Studio is in some way the recommended tool for writing queries (source)
Use Azure Data Studio if you: [..] Are mostly editing or executing queries.
If you'd like to initialize the array to values other than 0, with gcc
you can do:
int array[1024] = { [ 0 ... 1023 ] = -1 };
This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99
to compile your code.
Check if the columns contain Nan
using .isnull()
and check for empty strings using .eq('')
, then join the two together using the bitwise OR operator |
.
Sum along axis 0
to find columns with missing data, then sum along axis 1
to the index locations for rows with missing data.
missing_cols, missing_rows = (
(df2.isnull().sum(x) | df2.eq('').sum(x))
.loc[lambda x: x.gt(0)].index
for x in (0, 1)
)
>>> df2.loc[missing_rows, missing_cols]
A2 A3
2 1.10035
5 -0.508501
6 NaN NaN
7 NaN NaN
You can also use a simple library called repyt, here is an example:
repyt ./app.py
All file modes in Python
r
for readingr+
opens for reading and writing (cannot truncate a file)w
for writing w+
for writing and reading (can truncate a file) rb
for reading a binary file. The file pointer is placed at the beginning of the file.rb+
reading or writing a binary filewb+
writing a binary filea+
opens for appendingab+
Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.x
open for exclusive creation, failing if the file already exists (Python 3)My problem was that there was task already for Customer Experience Improvement Program in Task Scheduler "\Microsoft\Windows\AppFabric\Customer Experience Improvement Program\Consolidator". I removed that task and after that installation succeeded.
If you are running iOS 12 you will need to do an extra step. I've been struggling to make this code work and finally found this on Apple's site: "Important To use this function in iOS 12 and later, enable the Access WiFi Information capability for your app in Xcode. When you enable this capability, Xcode automatically adds the Access WiFi Information entitlement to your entitlements file and App ID." https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo
$("input[attr]").length
might be a better option.
The answers above are great. If you are in need of parsing all numbers out of a string that are nonconsecutive then the following may be of some help:
string input = "1-205-330-2342";
string result = Regex.Replace(input, @"[^\d]", "");
Console.WriteLine(result); // >> 12053302342
mysql -u app -p
mysql> set @@global.show_compatibility_56=ON;
as per http://bugs.mysql.com/bug.php?id=78159 worked for me.
So to make your expression work, changing &&
for -a
will do the trick.
It is correct like this:
if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
then ....
or like
if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
then ....
or even
if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
then ....
You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.
So it sounds like the bad commit was incorporated in a merge commit at some point. Has your merge commit been pulled yet? If yes, then you'll want to use git revert
; you'll have to grit your teeth and work through the conflicts. If no, then you could conceivably either rebase or revert, but you can do so before the merge commit, then redo the merge.
There's not much help we can give you for the first case, really. After trying the revert, and finding that the automatic one failed, you have to examine the conflicts and fix them appropriately. This is exactly the same process as fixing merge conflicts; you can use git status
to see where the conflicts are, edit the unmerged files, find the conflicted hunks, figure out how to resolve them, add the conflicted files, and finally commit. If you use git commit
by itself (no -m <message>
), the message that pops up in your editor should be the template message created by git revert
; you can add a note about how you fixed the conflicts, then save and quit to commit.
For the second case, fixing the problem before your merge, there are two subcases, depending on whether you've done more work since the merge. If you haven't, you can simply git reset --hard HEAD^
to knock off the merge, do the revert, then redo the merge. But I'm guessing you have. So, you'll end up doing something like this:
git rebase -i <something before the bad commit> <temporary branch>
to remove the bad commit)git rebase --onto <temporary branch> <old merge commit> <real branch>
You can tell Gradle to re-download some dependencies in the build script by flagging the dependency as 'changing'. Gradle will then check for updates every 24 hours, but this can be configured using the resolutionStrategy DSL. I find it useful to use this for for SNAPSHOT or NIGHTLY builds.
configurations.all {
// Check for updates every build
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}
Expanded:
dependencies {
implementation group: "group", name: "projectA", version: "1.1-SNAPSHOT", changing: true
}
Condensed:
implementation('group:projectA:1.1-SNAPSHOT') { changing = true }
I found this solution at this forum thread.
i guess this one will be handy as well as precise
>>>factors=[ x for x in range (1,n+1) if n%x==0]
print len(factors)
For writing any Text to a file.
public static void WriteToFile(string DirectoryPath,string FileName,string Text)
{
//Check Whether directory exist or not if not then create it
if(!Directory.Exists(DirectoryPath))
{
Directory.CreateDirectory(DirectoryPath);
}
string FilePath = DirectoryPath + "\\" + FileName;
//Check Whether file exist or not if not then create it new else append on same file
if (!File.Exists(FilePath))
{
File.WriteAllText(FilePath, Text);
}
else
{
Text = $"{Environment.NewLine}{Text}";
File.AppendAllText(FilePath, Text);
}
}
For reading a Text from file
public static string ReadFromFile(string DirectoryPath,string FileName)
{
if (Directory.Exists(DirectoryPath))
{
string FilePath = DirectoryPath + "\\" + FileName;
if (File.Exists(FilePath))
{
return File.ReadAllText(FilePath);
}
}
return "";
}
For Reference here this is the official microsoft document link.