I had the same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. @Domnic answer didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.
An extended answer for remote IP db connections:
Step 1: Link servers
EXEC sp_addlinkedserver @server='SRV_NAME',
@srvproduct=N'',
@provider=N'SQLNCLI',
@datasrc=N'aaa.bbb.ccc.ddd';
EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'
...where SRV_NAME
is an invented name. We will use it to refer to the remote server from our queries. aaa.bbb.ccc.ddd
is the ip address of the remote server hosting your SQLserver DB.
Step 2: Run your queries For instance:
SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table
...and that's it!
Syntax details: sp_addlinkedserver and sp_addlinkedsrvlogin
Check the path where you have generated the public key. You can also copy the id_rsa
by using this command:
clip < ~/.ssh/id_rsa.pub
This is for those who want to prevent users to enter decimal numbers
<input id="myInput" onkeyup="doSomething()" type="number" />
<script>
function doSomething() {
var intNum = $('#myInput').val();
if (!Number.isInteger(intNum)) {
intNum = Math.round(intNum);
}
console.log(intNum);
}
</script>
Customize the filter, and determine what kind of abnormality, there should be a better method than this
public class ExceptionFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String msg = "";
try {
filterChain.doFilter(request, response);
} catch (Exception e) {
if (e instanceof JwtException) {
msg = e.getMessage();
}
response.setCharacterEncoding("UTF-8");
response.setContentType(MediaType.APPLICATION_JSON.getType());
response.getWriter().write(JSON.toJSONString(Resp.error(msg)));
return;
}
}
}
The thing is that you are using the option -t
when running your container.
Could you check if enabling the tty
option (see reference) in your docker-compose.yml file the container keeps running?
version: '2'
services:
ubuntu:
build: .
container_name: ubuntu
volumes:
- ~/sph/laravel52:/www/laravel
ports:
- "80:80"
tty: true
$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');
var_dump(strtotime($today) > strtotime($expiry)); //false or true
I have used the below package for a meteor/MongoDB project, and it works well, the main advantage is that it stores history/revisions within an array in the same document, hence no need for an additional publications or middleware to access change-history. It can support a limited number of previous versions (ex. last ten versions), it also supports change-concatenation (so all changes happened within a specific period will be covered by one revision).
nicklozon/meteor-collection-revisions
Another sound option is to use Meteor Vermongo (here)
Try like this:
from flask import Response
@app.route('/ajax_ddl')
def ajax_ddl():
xml = 'foo'
return Response(xml, mimetype='text/xml')
The actual Content-Type is based on the mimetype parameter and the charset (defaults to UTF-8).
Response (and request) objects are documented here: http://werkzeug.pocoo.org/docs/wrappers/
This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().
http://louisremi.github.io/jquery.transform.js/
For example
$('#div').css({ transform: 'scale(.5)' });
OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.
http://www.browsersupport.net/CSS/zoom
Or just look at this question, which this one is likely just a dupe of:
Visual C++ Redistributable for Visual Studio 2015 (x32 bit version) - RC.
This should correct that. You can google for what the DLL is, but that's not important.
PS: It's officially from Microsoft too:)
Where I found it: Downloads (Visual Studio)
I was facing this problem when trying to add a .NETStandard dependency to a .NET4.6.1 library, and compiling it in Linux with Mono 4.6.2 (the version that comes with Ubuntu 16.04).
I finally solved it today; the solution requires to do both of these things:
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
to <TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>
in the .csproj file.aiohttp can be used with HTTP proxy already:
import asyncio
import aiohttp
@asyncio.coroutine
def do_request():
proxy_url = 'http://localhost:8118' # your proxy address
response = yield from aiohttp.request(
'GET', 'http://google.com',
proxy=proxy_url,
)
return response
loop = asyncio.get_event_loop()
loop.run_until_complete(do_request())
While this does not address the OP's question, I had trouble with my bootstrap rows / columns while trying to use them in conjunction with Kendo ListView (even with the bootstrap-kendo css).
Adding the following css fixed the problem for me:
#myListView.k-widget, #catalog-items.k-widget * {
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
The easiest way to draw a relationship between items is by understanding them in plain languages. Example
A user can have many cars but then a car can have just one owner. After establishing this, the foreign key should be used on the item with the many relationship. In this case the car. Meaning you'll include user as a foreign key in cars
And a one on one relationship is quite simple. Say a man and a heart. A man has only one heart and a heart can belong to just one man
use the below command to set the port number in node process while running node JS programme:
set PORT =3000 && node file_name.js
The set port can be accessed in the code as
process.env.PORT
IN KOTLIN :
Suppose that you have a String
like this :
private val phoneNumber="9121111111"
At first you should get the first one :
val firstChar=phoneNumber.slice(0..0)
At second you can check the first char
that return
a Boolean
:
firstChar.isInt() // or isFloat()
When you say str
, you should be careful what you mean:
do you mean the variable str
?
or do you mean the object referenced by str
?
In your StringBuffer
example you are not altering the value of str
, and in your String
example you are not altering the state of the String
object.
The most poignant way to experience the difference would be something like this:
static void change(String in) {
in = in + " changed";
}
static void change(StringBuffer in) {
in.append(" changed");
}
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("value");
String str = "value";
change(sb);
change(str);
System.out.println("StringBuffer: "+sb);
System.out.println("String: "+str);
}
What regex engine are you using? Most of them will support the following expression:
\{\d+:\d+\}
The \d
is actually shorthand for [0-9]
, but the important part is the addition of +
which means "one or more".
Use of the jQuery $().load() as an IMG event handler isn't guaranteed. If the image loads from the cache, some browsers may not fire off the event. In the case of (older?) versions of Safari, if you changed the SRC property of an IMG element to the same value, the onload event will NOT fire.
It appears that this is recognized in the latest jQuery (1.4.x) - http://api.jquery.com/load-event - to quote:
It is possible that the load event will not be triggered if the image is loaded from the browser cache. To account for this possibility, we can use a special load event that fires immediately if the image is ready. event.special.load is currently available as a plugin.
There is a plug-in now to recognize this case and IE's "complete" property for IMG element load states: http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js
package main
import "fmt"
import "strconv"
func FloatToString(input_num float64) string {
// to convert a float number to a string
return strconv.FormatFloat(input_num, 'f', 6, 64)
}
func main() {
fmt.Println(FloatToString(21312421.213123))
}
If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg
strconv.FormatFloat(input_num, 'f', -1, 64)
Personally I find fmt
easier to use. (Playground link)
fmt.Printf("x = %.6f\n", 21312421.213123)
Or if you just want to convert the string
fmt.Sprintf("%.6f", 21312421.213123)
You can use ip-api.io to get visitor's location. It supports IPv6.
As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.
JavaScript Code:
function getIPDetails() {
var ipAddress = document.getElementById("txtIP").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(JSON.parse(xhttp.responseText));
}
};
xhttp.open("GET", "http://ip-api.io/json/" + ipAddress, true);
xhttp.send();
}
<input type="text" id="txtIP" placeholder="Enter the ip address" />
<button onclick="getIPDetails()">Get IP Details</button>
jQuery Code:
$(document).ready(function () {
$('#btnGetIpDetail').click(function () {
if ($('#txtIP').val() == '') {
alert('IP address is reqired');
return false;
}
$.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
function (result) {
alert('Country Name: ' + result.country_name)
console.log(result);
});
});
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div>
<input type="text" id="txtIP" />
<button id="btnGetIpDetail">Get Location of IP</button>
</div>
String string = "This is Yasir Shabbir ";
for(char ch : string.toCharArray()){
}
or If you want individually then you can as
char ch = string.charAt(1);
$("#vp_code").textinput("enable");
$("#vp_code").textinput("disable");
you can try it
Too late for the OP of course, but still... Rearranging the expression as:
int bmi = (10000 * weight) / (height * height)
Eliminates all the floating point, and converts a division by a constant to a multiplication, which should execute faster. Integer precision is probably adequate for this application, but if it is not then:
double bmi = (10000.0 * weight) / (height * height)
would still be an improvement.
Two choices come to my mind:
s.toUpperCase().hashCode();
as the key of the Map
.TreeMap<String>
with a custom Comparator
that ignore the case.Otherwise, if you prefer your solution, instead of defining a new kind of String, I would rather implement a new Map with the required case insensibility functionality.
In another way, you can also make the two column primary key unique
and the auto-increment key primary
. Just like this: https://stackoverflow.com/a/6157337
len(nams)
should be equal to n
in your code. All indexes 0 <= i < n
"exist".
Python 3.6 f-strings allows us to add leading zeros easily:
number = 5
print(f' now we have leading zeros in {number:02d}')
Have a look at this good post about this feature.
There is the easiest method, using File::Slurp
module:
use File::Slurp;
my @lines = read_file("filename", chomp => 1); # will chomp() each line
If you need some validation for each line you can use grep
in front of read_file
.
For example, filter lines which contain only integers:
my @lines = grep { /^\d+$/ } read_file("filename", chomp => 1);
SELECT sc.name +'.'+ ta.name TableName
,SUM(pa.rows) RowCnt
FROM sys.tables ta
INNER JOIN sys.partitions pa
ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY sc.name,ta.name
ORDER BY SUM(pa.rows) DESC
See this:
For the record to go back and forth in basic python3:
a = 10
bin(a)
# '0b1010'
int(bin(a), 2)
# 10
eval(bin(a))
# 10
Use Apache Commons IO api. Its simple
Use API as
FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");
Maven Dependency
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
Old question I know. You don't need to convert it. See this function:
function getType( oObj )
{
if( typeof oObj === "object" )
{
return ( oObj === null )?'Null':
// Check if it is an alien object, for example created as {world:'hello'}
( typeof oObj.constructor !== "function" )?'Object':
// else return object name (string)
oObj.constructor.name;
}
// Test simple types (not constructed types)
return ( typeof oObj === "boolean")?'Boolean':
( typeof oObj === "number")?'Number':
( typeof oObj === "string")?'String':
( typeof oObj === "function")?'Function':false;
};
Examples:
function MyObject() {}; // Just for example
console.log( getType( new String( "hello ") )); // String
console.log( getType( new Function() ); // Function
console.log( getType( {} )); // Object
console.log( getType( [] )); // Array
console.log( getType( new MyObject() )); // MyObject
var bTest = false,
uAny, // Is undefined
fTest function() {};
// Non constructed standard types
console.log( getType( bTest )); // Boolean
console.log( getType( 1.00 )); // Number
console.log( getType( 2000 )); // Number
console.log( getType( 'hello' )); // String
console.log( getType( "hello" )); // String
console.log( getType( fTest )); // Function
console.log( getType( uAny )); // false, cannot produce
// a string
Low cost and simple.
Your focus is working before return false; ,After that is not working. You try this solution. Control after return false;
Put code in function:
function validateNumber(){
var mnumber = document.getElementById('mobileno').value;
if(mnumber.length >=10) {
alert("Mobile Number Should be in 10 digits only");
document.getElementById('mobileno').value = "";
return false;
}else{
return true;
}
}
Caller function:
function submitButton(){
if(!validateNumber()){
document.getElementById('mobileno').focus();
return false;
}
}
HTML:
Input:<input type="text" id="mobileno">
<button onclick="submitButton();" >Submit</button>
You cannot use var
in a field, only on local variables.
But even this won't work:
Site master = Master as Site;
Because you cannot use this
in a field and Master as Site
is the same as this.Master as Site
. So just initialize the field from Page_Init
when the page is fully initialized and you can use this
:
Site master = null;
protected void Page_Init(object sender, EventArgs e)
{
master = this.Master as Site;
}
Pass a duration to show()
and hide()
:
When a duration is provided,
.show()
becomes an animation method.
E.g. element.delay(1000).show(0)
To fix this, i put this class on the webpage
<style>
td.vcenter {
vertical-align: middle !important;
text-align: center !important;
}
</style>
and this in my TemplateField
<asp:TemplateField ItemStyle-CssClass="vcenter">
as the CSS class points directly to the td (tabledata) element and has the !important statment at the end each setting. It will over rule bootsraps CSS class settings.
Hope it helps
Add the below mentioned attribute on the property in your model class.
Attribute = [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
Reference = System.ComponentModel.DataAnnotations.Schema
Initially I forgot to add this attribute. So in my database the constraint was created like
ALTER TABLE [dbo].[TableName] ADD DEFAULT (getdate()) FOR [ColumnName]
and I added this attribute and updated my db then it got changed into
ALTER TABLE [dbo].[TableName] ADD CONSTRAINT [DF_dbo.TableName_ColumnName] DEFAULT (getdate()) FOR [ColumnName]
Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" />
</p>
</form>
</body>
Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page
If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.
Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.
The button is a web control Button Add a Click event to the button call it Button1Click:
void Button1Click(Object sender,EventArgs e) { }
Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.
So if for example you want to access the text in TextBox1
you just need to call that object in the C# code:
String firstBox = TextBox1.Text;
In the same way you can populate the objects when event occur.
Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.
If, like me, you find you want essentially the same sorting code in more than one place, or just want to keep the code complexity down, you can abstract away the sorting itself to a separate function, to which you pass the function that does the actual work you want (which would be different at each call site, of course).
Given a map with key type K
and value type V
, represented as <K>
and <V>
below, the common sort function might look something like this Go-code template (which Go version 1 does not support as-is):
/* Go apparently doesn't support/allow 'interface{}' as the value (or
/* key) of a map such that any arbitrary type can be substituted at
/* run time, so several of these nearly-identical functions might be
/* needed for different key/value type combinations. */
func sortedMap<K><T>(m map[<K>]<V>, f func(k <K>, v <V>)) {
var keys []<K>
for k, _ := range m {
keys = append(keys, k)
}
sort.Strings(keys) # or sort.Ints(keys), sort.Sort(...), etc., per <K>
for _, k := range keys {
v := m[k]
f(k, v)
}
}
Then call it with the input map and a function (taking (k <K>, v <V>)
as its input arguments) that is called over the map elements in sorted-key order.
So, a version of the code in the answer posted by Mingu might look like:
package main
import (
"fmt"
"sort"
)
func sortedMapIntString(m map[int]string, f func(k int, v string)) {
var keys []int
for k, _ := range m {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
f(k, m[k])
}
}
func main() {
// Create a map for processing
m := make(map[int]string)
m[1] = "a"
m[2] = "c"
m[0] = "b"
sortedMapIntString(m,
func(k int, v string) { fmt.Println("Key:", k, "Value:", v) })
}
The sortedMapIntString()
function can be re-used for any map[int]string
(assuming the same sort order is desired), keeping each use to just two lines of code.
Downsides include:
Other languages have various solutions:
<K>
and <V>
(to denote types for the key and value) looks a bit familiar, that code template is not terribly unlike C++ templates.range
a first-class type such that it could be substituted with a custom ordered-range
(in place of range
in the original code), I think some other languages provide iterators that are powerful enough to accomplish the same thing.Another application are intrusive lists. The element type can tell the list what its next/prev pointers are. So the list does not use hard-coded names but can still use existing pointers:
// say this is some existing structure. And we want to use
// a list. We can tell it that the next pointer
// is apple::next.
struct apple {
int data;
apple * next;
};
// simple example of a minimal intrusive list. Could specify the
// member pointer as template argument too, if we wanted:
// template<typename E, E *E::*next_ptr>
template<typename E>
struct List {
List(E *E::*next_ptr):head(0), next_ptr(next_ptr) { }
void add(E &e) {
// access its next pointer by the member pointer
e.*next_ptr = head;
head = &e;
}
E * head;
E *E::*next_ptr;
};
int main() {
List<apple> lst(&apple::next);
apple a;
lst.add(a);
}
Simply remove "DEFINER=your user name
@localhost
" and run the SQL from phpmyadminwill works fine.
add following property in your hibernate.cfg.xml file
<property name="hibernate.hbm2ddl.auto">update</property>
BTW, in your Entity class, you must define your @Id filed like this:
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "id")
private long id;
if you use the following definition, it maybe not work:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
EDIT 2
After three months we can say: no more official Google Apps in Genymotion and CyanogenMod-like method is only way to get Google Apps. However, you can still use the previous project of the Genymotion team: AndroVM (download mirror).
EDIT
Google apps will be removed from Genymotion in November. You can find more information on the Genymotion Google Plus page.
Choose virtual device with Google Apps:
Done:
Correct solution is to copy or install to /usr/local/bin
not /usr/bin
.This is due to System Integrity Protection (SIP). SIP makes /usr/bin
read-only but leaves /usr/local
as read-write.
SIP should not be disabled as stated in the answer above because it adds another layer of protection against malware gaining root access. Here is a complete explanation of what SIP does and why it is useful.
As suggested in this answer one should not disable SIP (rootless mode) "It is not recommended to disable rootless mode! The best practice is to install custom stuff to "/usr/local" only."
I simple add a dupe check as follows:
private void OnChanged(object source, FileSystemEventArgs e)
{
string sTabName = Path.GetFileNameWithoutExtension(e.Name);
string sLastLine = ReadLastLine(e.FullPath);
if(sLastLine != _dupeCheck)
{
TabPage tp = tcLogs.TabPages[sTabName];
TextBox tbLog = (TextBox)tp.Controls[0] as TextBox;
tbLog.Invoke(new Action(() => tbLog.AppendText(sLastLine + Environment.NewLine)));
tbLog.Invoke(new Action(() => tbLog.SelectionStart = tbLog.Text.Length));
tbLog.Invoke(new Action(() => tbLog.ScrollToCaret()));
_dupeCheck = sLastLine;
}
}
public static String ReadLastLine(string path)
{
return ReadLastLine(path, Encoding.Default, "\n");
}
public static String ReadLastLine(string path, Encoding encoding, string newline)
{
int charsize = encoding.GetByteCount("\n");
byte[] buffer = encoding.GetBytes(newline);
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
long endpos = stream.Length / charsize;
for (long pos = charsize; pos < endpos; pos += charsize)
{
stream.Seek(-pos, SeekOrigin.End);
stream.Read(buffer, 0, buffer.Length);
if (encoding.GetString(buffer) == newline)
{
buffer = new byte[stream.Length - stream.Position];
stream.Read(buffer, 0, buffer.Length);
return encoding.GetString(buffer);
}
}
}
return null;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
private const int WM_VSCROLL = 0x115;
private const int SB_BOTTOM = 7;
/// <summary>
/// Scrolls the vertical scroll bar of a multi-line text box to the bottom.
/// </summary>
/// <param name="tb">The text box to scroll</param>
public static void ScrollToBottom(TextBox tb)
{
SendMessage(tb.Handle, WM_VSCROLL, (IntPtr)SB_BOTTOM, IntPtr.Zero);
}
def update():
import time
while True:
print 'Hello World!'
time.sleep(5)
That'll run as a function. The while True:
makes it run forever. You can always take it out of the function if you need.
Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/
But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing
-rw-r--r--@
thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:
-rw-r--rw-@
This did it. The message disappeared.
Try This code:
public class GenericCompare<T> : IEqualityComparer<T> where T : class
{
private Func<T, object> _expr { get; set; }
public GenericCompare(Func<T, object> expr)
{
this._expr = expr;
}
public bool Equals(T x, T y)
{
var first = _expr.Invoke(x);
var sec = _expr.Invoke(y);
if (first != null && first.Equals(sec))
return true;
else
return false;
}
public int GetHashCode(T obj)
{
return obj.GetHashCode();
}
}
Example of its use would be
collection = collection
.Except(ExistedDataEles, new GenericCompare<DataEle>(x=>x.Id))
.ToList();
Any() returns true if any of the elements in a collection meet your predicate's criteria.
Where() returns an enumerable of all elements in a collection that meet your predicate's criteria.
Exists() does the same thing as any except it's just an older implementation that was there on the IList back before Linq.
I would never recommend SendGrid. I took up their free account offer and never managed to send a single email - all got blocked - I spent days trying to resolve it. When I enquired why they got blocked, they told me that free accounts share an ip address and if any account abuses that ip by sending spam - then everyone on the shared ip address gets blocked - totally useless. Also if you use them - do not store your email key in a git public repository as anyone can read the key from there (using a crawler) and use your chargeable account to send bulk emails.
A free email service which I've been using reliably with an Azure website is to use my Gmail (Google mail) account. That account has an option for using it with applications - once you enable that, then email can be sent from your azure website. Pasting in sample send code as the port to use (587) is not obvious.
public static void SendMail(MailMessage Message)
{
SmtpClient client = new SmtpClient();
client.Host = EnvironmentSecret.Instance.SmtpHost; // smtp.googlemail.com
client.Port = 587;
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Credentials = new NetworkCredential(
EnvironmentSecret.Instance.NetworkCredentialUserName,
EnvironmentSecret.Instance.NetworkCredentialPassword);
client.Send(Message);
}
document.addEventListener('touchstart', function (e) {
e.preventDefault();
});
Do not use the ontouchmove
property to register the event handler as you are running at risk of overwriting an existing event handler(s). Use addEventListener instead (see the note about IE on the MDN page).
Beware that preventing default for the touchstart
event on the window
or document
will disable scrolling of the descending areas.
To prevent the scrolling of the document but leave all the other events intact prevent default for the first touchmove
event following touchstart
:
var firstMove;
window.addEventListener('touchstart', function (e) {
firstMove = true;
});
window.addEventListener('touchmove', function (e) {
if (firstMove) {
e.preventDefault();
firstMove = false;
}
});
The reason this works is that mobile Safari is using the first move to determine if body of the document is being scrolled. I have realised this while devising a more sophisticated solution.
In case this would ever stop working, the more sophisticated solution is to inspect the touchTarget
element and its parents and make a map of directions that can be scrolled to. Then use the first touchmove
event to detect the scroll direction and see if it is going to scroll the document or the target element (or either of the target element parents):
var touchTarget,
touchScreenX,
touchScreenY,
conditionParentUntilTrue,
disableScroll,
scrollMap;
conditionParentUntilTrue = function (element, condition) {
var outcome;
if (element === document.body) {
return false;
}
outcome = condition(element);
if (outcome) {
return true;
} else {
return conditionParentUntilTrue(element.parentNode, condition);
}
};
window.addEventListener('touchstart', function (e) {
touchTarget = e.targetTouches[0].target;
// a boolean map indicating if the element (or either of element parents, excluding the document.body) can be scrolled to the X direction.
scrollMap = {}
scrollMap.left = conditionParentUntilTrue(touchTarget, function (element) {
return element.scrollLeft > 0;
});
scrollMap.top = conditionParentUntilTrue(touchTarget, function (element) {
return element.scrollTop > 0;
});
scrollMap.right = conditionParentUntilTrue(touchTarget, function (element) {
return element.scrollWidth > element.clientWidth &&
element.scrollWidth - element.clientWidth > element.scrollLeft;
});
scrollMap.bottom =conditionParentUntilTrue(touchTarget, function (element) {
return element.scrollHeight > element.clientHeight &&
element.scrollHeight - element.clientHeight > element.scrollTop;
});
touchScreenX = e.targetTouches[0].screenX;
touchScreenY = e.targetTouches[0].screenY;
disableScroll = false;
});
window.addEventListener('touchmove', function (e) {
var moveScreenX,
moveScreenY;
if (disableScroll) {
e.preventDefault();
return;
}
moveScreenX = e.targetTouches[0].screenX;
moveScreenY = e.targetTouches[0].screenY;
if (
moveScreenX > touchScreenX && scrollMap.left ||
moveScreenY < touchScreenY && scrollMap.bottom ||
moveScreenX < touchScreenX && scrollMap.right ||
moveScreenY > touchScreenY && scrollMap.top
) {
// You are scrolling either the element or its parent.
// This will not affect document.body scroll.
} else {
// This will affect document.body scroll.
e.preventDefault();
disableScroll = true;
}
});
The reason this works is that mobile Safari is using the first touch move to determine if the document body is being scrolled or the element (or either of the target element parents) and sticks to this decision.
A side note: Java has |= but not an ||=
An example of when you must use || is when the first expression is a test to see if the second expression would blow up. e.g. Using a single | in hte following case could result in an NPE.
public static boolean isNotSet(String text) {
return text == null || text.length() == 0;
}
Just in case you want to do it in the view controller and not in the app delegate: Just fetch the reference to the AppDelegate in your view controller and reset it's window object with the right view controller as it's rootviewController.
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let yourVC = mainStoryboard.instantiateViewControllerWithIdentifier("YOUR_VC_IDENTIFIER") as! YourViewController
appDelegate.window?.rootViewController = yourVC
appDelegate.window?.makeKeyAndVisible()
I adapted the SetTags() search function above (which should be replaced by the equivalent set tags+=./tags;/
) to work for cscope. Seems to work!
"cscope file-searching alternative
function SetCscope()
let curdir = getcwd()
while !filereadable("cscope.out") && getcwd() != "/"
cd ..
endwhile
if filereadable("cscope.out")
execute "cs add " . getcwd() . "/cscope.out"
endif
execute "cd " . curdir
endfunction
call SetCscope()
You might want to check out RFC 6570. This URI Template spec shows many examples of how urls can contain parameters.
For Kotlin Users
val params = mImageView?.layoutParams as FrameLayout.LayoutParams
params.width = FrameLayout.LayoutParams.MATCH_PARENT
params.height = FrameLayout.LayoutParams.MATCH_PARENT
mImageView?.layoutParams = params
Here I used FrameLayout.LayoutParams
since my views( ImageView
) parent is FrameLayout
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
The former code will add the image at the end of the gallery. If you want to modify the date so it appears at the beginning or any other metadata, see the code below (Cortesy of S-K, samkirton):
https://gist.github.com/samkirton/0242ba81d7ca00b475b9
/**
* Android internals have been modified to store images in the media folder with
* the correct date meta data
* @author samuelkirton
*/
public class CapturePhotoUtils {
/**
* A copy of the Android internals insertImage method, this method populates the
* meta data with DATE_ADDED and DATE_TAKEN. This fixes a common problem where media
* that is inserted manually gets saved at the end of the gallery (because date is not populated).
* @see android.provider.MediaStore.Images.Media#insertImage(ContentResolver, Bitmap, String, String)
*/
public static final String insertImage(ContentResolver cr,
Bitmap source,
String title,
String description) {
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DISPLAY_NAME, title);
values.put(Images.Media.DESCRIPTION, description);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
storeThumbnail(cr, miniThumb, id, 50F, 50F,Images.Thumbnails.MICRO_KIND);
} else {
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
}
/**
* A copy of the Android internals StoreThumbnail method, it used with the insertImage to
* populate the android.provider.MediaStore.Images.Media#insertImage with all the correct
* meta data. The StoreThumbnail method is private so it must be duplicated here.
* @see android.provider.MediaStore.Images.Media (StoreThumbnail private method)
*/
private static final Bitmap storeThumbnail(
ContentResolver cr,
Bitmap source,
long id,
float width,
float height,
int kind) {
// create the matrix to scale it
Matrix matrix = new Matrix();
float scaleX = width / source.getWidth();
float scaleY = height / source.getHeight();
matrix.setScale(scaleX, scaleY);
Bitmap thumb = Bitmap.createBitmap(source, 0, 0,
source.getWidth(),
source.getHeight(), matrix,
true
);
ContentValues values = new ContentValues(4);
values.put(Images.Thumbnails.KIND,kind);
values.put(Images.Thumbnails.IMAGE_ID,(int)id);
values.put(Images.Thumbnails.HEIGHT,thumb.getHeight());
values.put(Images.Thumbnails.WIDTH,thumb.getWidth());
Uri url = cr.insert(Images.Thumbnails.EXTERNAL_CONTENT_URI, values);
try {
OutputStream thumbOut = cr.openOutputStream(url);
thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut);
thumbOut.close();
return thumb;
} catch (FileNotFoundException ex) {
return null;
} catch (IOException ex) {
return null;
}
}
}
You could use the keydown
, keyup
and keypress
events as well.
You will need to configure you IIS (assuming this is the web server your are/will using) allowing access from WLAN/LAN to specific users (or anonymous). Allow IIS trought your firewall if you have one.
Your application won't need to be changed, that's just networking problems ans configuration you will have to face to allow acces only trought LAN and WLAN.
I had the exact same error (on windows 7) and the cause was different. I solved it in a different way so I thought I'd add the cause and solution here for others.
Even though the error seemed to point to heroku really the error was saying "Heroku can't get to the git repository"
. I swore I had the same keys on all the servers because I created it and uploaded it to one after the other at the same time.
After spending almost a day on this I realized that because git was only showing me the fingerprint and not the actual key. I couldn't verify that it's key matched the one on my HD or heroku. I looked in the known hosts file and guess what... it shows the keys for each server and I was able to clearly see that the git and heroku public keys did not match.
1) I deleted all the files in my key folder, the key from github using their website, and the key from heroku using git bash and the command heroku keys:clear
2) Followed github's instructions here to generate a new key pair and upload the public key to git
3) using git bash-
heroku keys:add
to upload the same key to heroku.
Now git push heroku master
works.
what a nightmare, hope this helped somebody.
Bryan
Consider breaking this problem up into two pieces:
filter
out the items that match
the given regular expression0
matches in itconst sampleStringData = ["frog", "pig", "tiger"];
const matches = sampleStringData.filter((animal) => /any.regex.here/.test(animal));
if (matches.length === 0) {
console.log("No matches");
}
I adapted the answer by ChrisB. Like in his example a temporary combobox is made visible when a cell is clicked. Additionally:
Option Explicit_x000D_
_x000D_
Private Const DATA_RANGE = "A1:A16"_x000D_
Private Const DROPDOWN_RANGE = "F2:F10"_x000D_
Private Const HELP_COLUMN = "$G"_x000D_
_x000D_
_x000D_
Private Sub Worksheet_SelectionChange(ByVal target As Range)_x000D_
Dim xWs As Worksheet_x000D_
Set xWs = Application.ActiveSheet_x000D_
_x000D_
On Error Resume Next_x000D_
_x000D_
With Me.TempCombo_x000D_
.LinkedCell = vbNullString_x000D_
.Visible = False_x000D_
End With_x000D_
_x000D_
If target.Cells.count > 1 Then_x000D_
Exit Sub_x000D_
End If_x000D_
_x000D_
Dim isect As Range_x000D_
Set isect = Application.Intersect(target, Range(DROPDOWN_RANGE))_x000D_
If isect Is Nothing Then_x000D_
Exit Sub_x000D_
End If_x000D_
_x000D_
With Me.TempCombo_x000D_
.Visible = True_x000D_
.Left = target.Left - 1_x000D_
.Top = target.Top - 1_x000D_
.Width = target.Width + 5_x000D_
.Height = target.Height + 5_x000D_
.LinkedCell = target.Address_x000D_
_x000D_
End With_x000D_
_x000D_
Me.TempCombo.Activate_x000D_
Me.TempCombo.DropDown_x000D_
End Sub_x000D_
_x000D_
Private Sub TempCombo_Change()_x000D_
If Me.TempCombo.Visible = False Then_x000D_
Exit Sub_x000D_
End If_x000D_
_x000D_
Dim currentValue As String_x000D_
currentValue = Range(Me.TempCombo.LinkedCell).Value_x000D_
_x000D_
If Trim(currentValue & vbNullString) = vbNullString Then_x000D_
Me.TempCombo.ListFillRange = "=" & DATA_RANGE_x000D_
Else_x000D_
If Me.TempCombo.ListIndex = -1 Then_x000D_
Dim listCount As Integer_x000D_
listCount = write_matching_items(currentValue)_x000D_
Me.TempCombo.ListFillRange = "=" & HELP_COLUMN & "1:" & HELP_COLUMN & listCount_x000D_
Me.TempCombo.DropDown_x000D_
End If_x000D_
_x000D_
End If_x000D_
End Sub_x000D_
_x000D_
_x000D_
Private Function write_matching_items(currentValue As String) As Integer_x000D_
Dim xWs As Worksheet_x000D_
Set xWs = Application.ActiveSheet_x000D_
_x000D_
Dim cell As Range_x000D_
Dim c As Range_x000D_
Dim firstAddress As Variant_x000D_
Dim count As Integer_x000D_
count = 0_x000D_
xWs.Range(HELP_COLUMN & ":" & HELP_COLUMN).Delete_x000D_
With xWs.Range(DATA_RANGE)_x000D_
Set c = .Find(currentValue, LookIn:=xlValues)_x000D_
If Not c Is Nothing Then_x000D_
firstAddress = c.Address_x000D_
Do_x000D_
Set cell = xWs.Range(HELP_COLUMN & "$" & (count + 1))_x000D_
cell.Value = c.Value_x000D_
count = count + 1_x000D_
_x000D_
Set c = .FindNext(c)_x000D_
If c Is Nothing Then_x000D_
GoTo DoneFinding_x000D_
End If_x000D_
Loop While c.Address <> firstAddress_x000D_
End If_x000D_
DoneFinding:_x000D_
End With_x000D_
_x000D_
write_matching_items = count_x000D_
_x000D_
End Function_x000D_
_x000D_
Private Sub TempCombo_KeyDown( __x000D_
ByVal KeyCode As MSForms.ReturnInteger, __x000D_
ByVal Shift As Integer)_x000D_
_x000D_
Select Case KeyCode_x000D_
Case 9 ' Tab key_x000D_
Application.ActiveCell.Offset(0, 1).Activate_x000D_
Case 13 ' Pause key_x000D_
Application.ActiveCell.Offset(1, 0).Activate_x000D_
End Select_x000D_
End Sub
_x000D_
Notes:
2 - fmMatchEntryNone
. Don't forget to set ComboBox name to TempCombo
ComboBox.addItem
, but it turned out to be hard to repaint list box as user typesIn order to resolve java.lang.OutOfMemoryError: Java heap space in Maven, try to configure below configuration in pom
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<verbose>true</verbose>
<fork>true</fork>
<argLine>-XX:MaxPermSize=500M</argLine>
</configuration>
</plugin>
export https_proxy=http://127.0.0.1:1087 http_proxy=http://127.0.0.1:1087 all_proxy=socks5://127.0.0.1:1080
works for me
and I think it can solve all the problems like
Failed to connect to raw.githubusercontent.com port 443: Connection refused
A particular feature of a HashMap is that unlike, say, balanced trees, its behavior is probabilistic. In these cases its usually most helpful to talk about complexity in terms of the probability of a worst-case event occurring would be. For a hash map, that of course is the case of a collision with respect to how full the map happens to be. A collision is pretty easy to estimate.
pcollision = n / capacity
So a hash map with even a modest number of elements is pretty likely to experience at least one collision. Big O notation allows us to do something more compelling. Observe that for any arbitrary, fixed constant k.
O(n) = O(k * n)
We can use this feature to improve the performance of the hash map. We could instead think about the probability of at most 2 collisions.
pcollision x 2 = (n / capacity)2
This is much lower. Since the cost of handling one extra collision is irrelevant to Big O performance, we've found a way to improve performance without actually changing the algorithm! We can generalzie this to
pcollision x k = (n / capacity)k
And now we can disregard some arbitrary number of collisions and end up with vanishingly tiny likelihood of more collisions than we are accounting for. You could get the probability to an arbitrarily tiny level by choosing the correct k, all without altering the actual implementation of the algorithm.
We talk about this by saying that the hash-map has O(1) access with high probability
As others have mentioned, you'll probably want to use the BigDecimal
class, if you want to have an exact representation of 11.4.
Now, a little explanation into why this is happening:
The float
and double
primitive types in Java are floating point numbers, where the number is stored as a binary representation of a fraction and a exponent.
More specifically, a double-precision floating point value such as the double
type is a 64-bit value, where:
These parts are combined to produce a double
representation of a value.
(Source: Wikipedia: Double precision)
For a detailed description of how floating point values are handled in Java, see the Section 4.2.3: Floating-Point Types, Formats, and Values of the Java Language Specification.
The byte
, char
, int
, long
types are fixed-point numbers, which are exact representions of numbers. Unlike fixed point numbers, floating point numbers will some times (safe to assume "most of the time") not be able to return an exact representation of a number. This is the reason why you end up with 11.399999999999
as the result of 5.6 + 5.8
.
When requiring a value that is exact, such as 1.5 or 150.1005, you'll want to use one of the fixed-point types, which will be able to represent the number exactly.
As has been mentioned several times already, Java has a BigDecimal
class which will handle very large numbers and very small numbers.
From the Java API Reference for the BigDecimal
class:
Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by the BigDecimal is therefore (unscaledValue × 10^-scale).
There has been many questions on Stack Overflow relating to the matter of floating point numbers and its precision. Here is a list of related questions that may be of interest:
If you really want to get down to the nitty gritty details of floating point numbers, take a look at What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Instead, you simply JOIN to both tables, and in your SELECT clause, return data from the one that matches:
I suggest you to go through this link Conditional Joins in SQL Server and T-SQL Case Statement in a JOIN ON Clause
e.g.
SELECT *
FROM sys.indexes i
JOIN sys.partitions p
ON i.index_id = p.index_id
JOIN sys.allocation_units a
ON a.container_id =
CASE
WHEN a.type IN (1, 3)
THEN p.hobt_id
WHEN a.type IN (2)
THEN p.partition_id
END
Edit: As per comments.
You can not specify the join condition as you are doing.. Check the query above that have no error. I have take out the common column up and the right column value will be evaluated on condition.
Assuming, that you have root access on the box you can do:
sudo -u postgres psql
If that fails with a database "postgres" does not exists this block.
sudo -u postgres psql template1
Then sudo nano /etc/postgresql/11/main/pg_hba.conf file
local all postgres ident
For newer versions of PostgreSQL ident actually might be peer.
Inside the psql shell you can give the DB user postgres a password:
ALTER USER postgres PASSWORD 'newPassword';
Besides {{ 1 * num_str + 1}} You can also try like this(minus first):
{{ num_str - 0 + 1}}
But the it's very fragile, if num_str contains letters, then it will fail. So better should try writing a filter as @hassassin said, or preprocess the data right after initiating it.
This should work:
$("label[for='comedyclubs']")
See also: Selectors/attributeEquals - jQuery JavaScript Library
am startservice <INTENT>
or actually from the OS shell
adb shell am startservice <INTENT>
To Download Specific Branch - Go To Downloads from Left panel, Select Branches on Downloads page. It will list all Branches available. Download your desired branch in zip, gz, or bz2 format.
Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)
I just removed the head portion in index.html file and it worked fine.This is the head tag in html file
Create a new class that wraps your Blog object and provides the equality/hashcode method you need. For maximum efficiency I would add two static methods on the wrapper, one to convert Blogs list -> Blog Wrapper list and the other to convert Blog Wrapper list -> Blog list. Then you would:
Code for Blog Wrapper would be something like this:
import java.util.ArrayList;
import java.util.List;
public class BlogWrapper {
public static List<Blog> unwrappedList(List<BlogWrapper> blogWrapperList) {
if (blogWrapperList == null)
return new ArrayList<Blog>(0);
List<Blog> blogList = new ArrayList<Blog>(blogWrapperList.size());
for (BlogWrapper bW : blogWrapperList) {
blogList.add(bW.getBlog());
}
return blogList;
}
public static List<BlogWrapper> wrappedList(List<Blog> blogList) {
if (blogList == null)
return new ArrayList<BlogWrapper>(0);
List<BlogWrapper> blogWrapperList = new ArrayList<BlogWrapper>(blogList
.size());
for (Blog b : blogList) {
blogWrapperList.add(new BlogWrapper(b));
}
return blogWrapperList;
}
private Blog blog = null;
public BlogWrapper() {
super();
}
public BlogWrapper(Blog aBlog) {
super();
setBlog(aBlog);
}
public boolean equals(Object other) {
// Your equality logic here
return super.equals(other);
}
public Blog getBlog() {
return blog;
}
public int hashCode() {
// Your hashcode logic here
return super.hashCode();
}
public void setBlog(Blog blog) {
this.blog = blog;
}
}
And you could use this like so:
List<BlogWrapper> myBlogWrappers = BlogWrapper.wrappedList(your blog list here);
Set<BlogWrapper> noDupWrapSet = new HashSet<BlogWrapper>(myBlogWrappers);
List<BlogWrapper> noDupWrapList = new ArrayList<BlogWrapper>(noDupSet);
List<Blog> noDupList = BlogWrapper.unwrappedList(noDupWrapList);
Quite obviously you can make the above code more efficient, particularly by making the wrap and unwrap methods on Blog Wrapper take collections instead of Lists.
An alternative route to wrapping the Blog class would be to use a byte code manipulation library like BCEL to actually change the equals and hashcode method for Blog. But of course, that could have unintended consequences to the rest of your code if they require the original equals/hashcode behaviour.
I use a Dynamic Management View (DMV) to capture locks as well as the object_id or partition_id of the item that is locked.
(MUST switch to the Database you want to observe to get object_id)
SELECT
TL.resource_type,
TL.resource_database_id,
TL.resource_associated_entity_id,
TL.request_mode,
TL.request_session_id,
WT.blocking_session_id,
O.name AS [object name],
O.type_desc AS [object descr],
P.partition_id AS [partition id],
P.rows AS [partition/page rows],
AU.type_desc AS [index descr],
AU.container_id AS [index/page container_id]
FROM sys.dm_tran_locks AS TL
INNER JOIN sys.dm_os_waiting_tasks AS WT
ON TL.lock_owner_address = WT.resource_address
LEFT OUTER JOIN sys.objects AS O
ON O.object_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.partitions AS P
ON P.hobt_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.allocation_units AS AU
ON AU.allocation_unit_id = TL.resource_associated_entity_id;
As everyone else have already said, primary keys are automatically indexed.
Creating more indexes on the primary key column only makes sense when you need to optimize a query that uses the primary key and some other specific columns. By creating another index on the primary key column and including some other columns with it, you may reach the desired optimization for a query.
For example you have a table with many columns but you are only querying ID, Name and Address columns. Taking ID as the primary key, we can create the following index that is built on ID but includes Name and Address columns.
CREATE NONCLUSTERED INDEX MyIndex
ON MyTable(ID)
INCLUDE (Name, Address)
So, when you use this query:
SELECT ID, Name, Address FROM MyTable WHERE ID > 1000
SQL Server will give you the result only using the index you've created and it'll not read anything from the actual table.
here's another solution for Python3:
import csv
with open(filename, "r") as csvfile:
datareader = csv.reader(csvfile)
count = 0
for row in datareader:
if row[3] in ("column header", criterion):
doSomething(row)
count += 1
elif count > 2:
break
here datareader
is a generator function.
I don't know your system environment, but it seems, that you have typed:
git commit
And your default editor has been launched. In the worst case scenario (for you) it could have been vim :)
If you don't know how to quit vim, use :q.
If you have further problems, you could use
git commit -m 'Type your commit message here'
you can use always:
'C:/mydir'
this works both in linux and windows. Other posibility is
'C:\\mydir'
if you have problems with some names you can also try raw string literals:
r'C:\mydir'
however best practice is to use the os.path
module functions that always select the correct configuration for your OS:
os.path.join(mydir, myfile)
From python 3.4 you can also use the pathlib module. This is equivelent to the above:
pathlib.Path(mydir, myfile)
or
pathlib.Path(mydir) / myfile
See this TechNet article: Runas command documentation
From a command prompt:
C:\> runas /user:<localmachinename>\administrator cmd
Or, if you're connected to a domain:
C:\> runas /user:<DomainName>\<AdministratorAccountName> cmd
Perhaps you could try using the DateTime.FromOADate
method to convert between Excel and .net.
One can also use the io
module as in:
import io
my_string = "hi there"
with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
f.write(my_string)
you should add servler-api.jar file in WEB-INF/lib folder
I had a simular issue and resolved it using android:adjustViewBounds="true"
on the ImageView.
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/banner_alt"
android:src="@drawable/banner_portrait" />
One of the reason may be improper date/time of your PC.
In Ubuntu PC to check the date and time using:
date
Example, One of the ways to update date and time is:
date -s "23 MAR 2017 17:06:00"
You can use:
((count = FIRSTV - SECONDV))
to avoid invoking a separate process, as per the following transcript:
pax:~$ FIRSTV=7
pax:~$ SECONDV=2
pax:~$ ((count = FIRSTV - SECONDV))
pax:~$ echo $count
5
You didn't specify what the error you're seeing is.
Is the problem that gcc
is giving you an error, or that you can't run gcc
at all?
If it's the latter, the most likely explanation is that you didn't check "UNIX Development Support" when you installed the development tools, so the command-line executables aren't installed in your path. Re-install the development tools, and make sure to click "customize" and check that box.
There is no python3.exe file, that is why it fails.
Try:
py
instead.
py is just a launcher for python.exe. If you have more than one python versions installed on your machine (2.x, 3.x) you can specify what version of python to launch by
py -2 or py -3
-- create test table "Accounts"
create table Accounts (
c_ID int primary key
,first_name varchar(100)
,last_name varchar(100)
,city varchar(100)
);
insert into Accounts values (101, 'Sebastian', 'Volk', 'Frankfurt' );
insert into Accounts values (102, 'Beate', 'Mueller', 'Hamburg' );
insert into Accounts values (103, 'John', 'Walker', 'Washington' );
insert into Accounts values (104, 'Britney', 'Sears', 'Holywood' );
insert into Accounts values (105, 'Sarah', 'Schmidt', 'Mainz' );
insert into Accounts values (106, 'George', 'Lewis', 'New Jersey' );
insert into Accounts values (107, 'Jian-xin', 'Wang', 'Peking' );
insert into Accounts values (108, 'Katrina', 'Khan', 'Bolywood' );
-- declare table variable
declare @tb_FirstName table(name varchar(100));
insert into @tb_FirstName values ('John'), ('Sarah'), ('George');
SELECT *
FROM Accounts
WHERE first_name in (select name from @tb_FirstName);
SELECT *
FROM Accounts
WHERE first_name not in (select name from @tb_FirstName);
go
drop table Accounts;
go
If I understood correct,You need to set time zone first like:
date_default_timezone_set('UTC');
And than you can use date function:
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
Good news everybody! Craigslist has actually released a bulk posting api now!
If you need a transparent cut out edge, you can use a rotated pseudo element as a background for the div
and position it to cut out the desired corner:
body {_x000D_
background: url(http://i.imgur.com/k8BtMvj.jpg);_x000D_
background-size: cover;_x000D_
}_x000D_
div {_x000D_
position: relative;_x000D_
width: 50%;_x000D_
margin: 0 auto;_x000D_
overflow: hidden;_x000D_
padding: 20px;_x000D_
text-align: center;_x000D_
}_x000D_
div:after {_x000D_
content: '';_x000D_
position: absolute;_x000D_
width: 1100%; height: 1100%;_x000D_
top: 20px; right: -500%;_x000D_
background: rgba(255,255,255,.8);_x000D_
transform-origin: 54% 0;_x000D_
transform: rotate(45deg);_x000D_
z-index: -1;_x000D_
}
_x000D_
<div>_x000D_
... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>_x000D_
</div>
_x000D_
Note that this solution uses transforms and you need to add the required vendor prefixes. For more info see canIuse.
To cut the bottom right edge, you can change the top, transform and transform-origin properties of the pseudo element to:
body {_x000D_
background: url(http://i.imgur.com/k8BtMvj.jpg);_x000D_
background-size: cover;_x000D_
}_x000D_
div {_x000D_
position: relative;_x000D_
width: 50%;_x000D_
margin: 0 auto;_x000D_
overflow: hidden;_x000D_
padding: 20px;_x000D_
text-align: center;_x000D_
}_x000D_
div:after {_x000D_
content: '';_x000D_
position: absolute;_x000D_
width: 1100%; height: 1100%;_x000D_
bottom: 20px; right: -500%;_x000D_
background: rgba(255,255,255,.8);_x000D_
transform-origin: 54% 100%;_x000D_
transform: rotate(-45deg);_x000D_
z-index: -1;_x000D_
}
_x000D_
<div>_x000D_
... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>... content ...<br/>_x000D_
</div>
_x000D_
Checkboxes can be really weird in JS. You're best off checking for the presence of the checked
attribute. (I've had older jQuery versions return true even if checked
is set to 'false'.) Once you've determined that something is checked then you can get the value from the value
attribute.
Why not using just one controller action?
public string Get(int? id, string firstName, string lastName, string address)
{
if (id.HasValue)
GetById(id);
else if (string.IsNullOrEmpty(address))
GetByName(firstName, lastName);
else
GetByNameAddress(firstName, lastName, address);
}
Another option is to use attribute routing, but then you'd need to have a different URL format:
//api/person/byId?id=1
[HttpGet("byId")]
public string Get(int id)
{
}
//api/person/byName?firstName=a&lastName=b
[HttpGet("byName")]
public string Get(string firstName, string lastName, string address)
{
}
Just generate ID and check whether it is already present or not in your list of generated IDs.
Check your manifest.xml. Make sure you have the category LAUNCHER there.
<activity android:name=".myActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
In the few words - function returns something. You can use function in SQL query. Procedure is part of code to do something with data but you can not invoke procedure from query, you have to run it in PL/SQL block.
It may be worth noting that auto-indent does not work if there are syntax errors in the document. Get rid of the red squigglies, and THEN try CTRL+K, CTRL+D, whatever...
NOTE: Using set_fact
as described below sets a fact/variable onto the remote servers that the task is running against. This fact/variable will then persist across subsequent tasks for the entire duration of your playbook.
Also, these facts are immutable (for the duration of the playbook), and cannot be changed once set.
Use set_fact
before your task to set facts which seem interchangeable with variables:
- name: Set Apache URL
set_fact:
apache_url: 'http://example.com/apache'
- name: Download Apache
shell: wget {{ apache_url }}
See http://docs.ansible.com/set_fact_module.html for the official word.
I would use a value that gets set when more button get pushed closed the first dialog and then have the original form test the value and then display the the there dialog.
For the Ex
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool DrawText = false;
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
if (f2.ShowMoreActions)
{
Form3 f3 = new Form3();
f3.ShowDialog();
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public bool ShowMoreActions = false;
private void button1_Click(object sender, EventArgs e)
{
ShowMoreActions = true;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
Most of the base R answers address the situation where only one data.frame has additional columns or that the resulting data.frame would have the intersection of the columns. Since the OP writes I am hoping to retain the columns that do not match after the bind, an answer using base R methods to address this issue is probably worth posting.
Below, I present two base R methods: One that alters the original data.frames, and one that doesn't. Additionally, I offer a method that generalizes the non-destructive method to more than two data.frames.
First, let's get some sample data.
# sample data, variable c is in df1, variable d is in df2
df1 = data.frame(a=1:5, b=6:10, d=month.name[1:5])
df2 = data.frame(a=6:10, b=16:20, c = letters[8:12])
Two data.frames, alter originals
In order to retain all columns from both data.frames in an rbind
(and allow the function to work without resulting in an error), you add NA columns to each data.frame with the appropriate missing names filled in using setdiff
.
# fill in non-overlapping columns with NAs
df1[setdiff(names(df2), names(df1))] <- NA
df2[setdiff(names(df1), names(df2))] <- NA
Now, rbind
-em
rbind(df1, df2)
a b d c
1 1 6 January <NA>
2 2 7 February <NA>
3 3 8 March <NA>
4 4 9 April <NA>
5 5 10 May <NA>
6 6 16 <NA> h
7 7 17 <NA> i
8 8 18 <NA> j
9 9 19 <NA> k
10 10 20 <NA> l
Note that the first two lines alter the original data.frames, df1 and df2, adding the full set of columns to both.
Two data.frames, do not alter originals
To leave the original data.frames intact, first loop through the names that differ, return a named vector of NAs that are concatenated into a list with the data.frame using c
. Then, data.frame
converts the result into an appropriate data.frame for the rbind
.
rbind(
data.frame(c(df1, sapply(setdiff(names(df2), names(df1)), function(x) NA))),
data.frame(c(df2, sapply(setdiff(names(df1), names(df2)), function(x) NA)))
)
Many data.frames, do not alter originals
In the instance that you have more than two data.frames, you could do the following.
# put data.frames into list (dfs named df1, df2, df3, etc)
mydflist <- mget(ls(pattern="df\\d+"))
# get all variable names
allNms <- unique(unlist(lapply(mydflist, names)))
# put em all together
do.call(rbind,
lapply(mydflist,
function(x) data.frame(c(x, sapply(setdiff(allNms, names(x)),
function(y) NA)))))
Maybe a bit nicer to not see the row names of original data.frames? Then do this.
do.call(rbind,
c(lapply(mydflist,
function(x) data.frame(c(x, sapply(setdiff(allNms, names(x)),
function(y) NA)))),
make.row.names=FALSE))
To add all file at a time, use git add -A
To check git whole status, use git log
Press Ctrl + F10 to rotate the emulator screen.
Nope IF is the way to go, what is the problem you have with using it?
BTW your example won't ever get to the third block of code as it and the second block are exactly alike.
for Earth plugin APIs, create the balloon outside your loop and pass your counter to the function to get unique contents for each placemark!
function createBalloon(placemark, i, event) {
var p = placemark;
var j = i;
google.earth.addEventListener(p, 'click', function (event) {
// prevent the default balloon from popping up
event.preventDefault();
var balloon = ge.createHtmlStringBalloon('');
balloon.setFeature(event.getTarget());
balloon.setContentString('iframePath#' + j);
ge.setBalloon(balloon);
});
}
Only the Assets and ProjectSettings folders need to be under git version control.
You can make a gitignore like this.
[Ll]ibrary/
[Tt]emp/
[Oo]bj/
# Autogenerated VS/MD solution and project files
*.csproj
*.unityproj
*.sln
*.suo
*.userprefs
# Mac
.DS_Store
*.swp
*.swo
Thumbs.db
Thumbs.db.meta
.vs/
According to http://msdn.microsoft.com/en-us/library/cc288472(VS.85).aspx#html, IE8 will have "strong" HTML 5 support. I haven't seen anything discussing exactly what "strong support" entails, but I can say that yes, some HTML5 stuff is going to make it into IE8.
The other answers are correct: You don't have a default value. However, you have another problem in your logic:
You read the same file twice. After reading it once, the cursor is at the end of the file. To solve this, you can do two things: Either open/close the file upon each function call:
def temp_sky(lreq, breq):
with open("/home/path/to/file",'r') as tfile:
# do your stuff
This hase the disadvantage of having to open the file each time. The better way would be:
tfile.seek(0)
You do this after your for line in tfile:
loop. It resets the cursor to the beginning to the next call will start from there again.
First off, using the mail() function that comes with PHP is not an optimal solution. It is easily marked as spammed, and you need to set up header to ensure that you are sending HTML emails correctly. As for whether the code snippet will work, it would, but I doubt you will get HTML code inside it correctly without specifying extra headers
I'll suggest you take a look at SwiftMailer, which has HTML support, support for different mime types and SMTP authentication (which is less likely to mark your mail as spam).
C++.
It is the gold standard for AAA game programming. If you need to do something interesting, you will need to do C++ or delve into unmanaged C#(not always nice).
C++ is also arguably faster(usual caveats apply).
As a learning experience, C# is not worth it. C++ is unquestionably better, especially in the quasi-embedded world of consoles. To get the object-oriented experience, go towards Java.
Works for me:
select DATE( FROM_UNIXTIME( columnname ) ) from tablename;
You can create very easy a dropdown from this array (It was a time-consuming task to put this together and test it). We already use this list in some of our apps.
It is very important to store timezone identifiers in your database and not just the timezone offset like "GMT+2", because of Daylight Saving Times.
I updated/corrected the timezones list (also checkout: https://github.com/paptamas/timezones):
<?php
$timezones = array (
'(GMT-11:00) Midway Island' => 'Pacific/Midway',
'(GMT-11:00) Samoa' => 'Pacific/Samoa',
'(GMT-10:00) Hawaii' => 'Pacific/Honolulu',
'(GMT-09:00) Alaska' => 'US/Alaska',
'(GMT-08:00) Pacific Time (US & Canada)' => 'America/Los_Angeles',
'(GMT-08:00) Tijuana' => 'America/Tijuana',
'(GMT-07:00) Arizona' => 'US/Arizona',
'(GMT-07:00) Chihuahua' => 'America/Chihuahua',
'(GMT-07:00) La Paz' => 'America/Chihuahua',
'(GMT-07:00) Mazatlan' => 'America/Mazatlan',
'(GMT-07:00) Mountain Time (US & Canada)' => 'US/Mountain',
'(GMT-06:00) Central America' => 'America/Managua',
'(GMT-06:00) Central Time (US & Canada)' => 'US/Central',
'(GMT-06:00) Guadalajara' => 'America/Mexico_City',
'(GMT-06:00) Mexico City' => 'America/Mexico_City',
'(GMT-06:00) Monterrey' => 'America/Monterrey',
'(GMT-06:00) Saskatchewan' => 'Canada/Saskatchewan',
'(GMT-05:00) Bogota' => 'America/Bogota',
'(GMT-05:00) Eastern Time (US & Canada)' => 'US/Eastern',
'(GMT-05:00) Indiana (East)' => 'US/East-Indiana',
'(GMT-05:00) Lima' => 'America/Lima',
'(GMT-05:00) Quito' => 'America/Bogota',
'(GMT-04:00) Atlantic Time (Canada)' => 'Canada/Atlantic',
'(GMT-04:30) Caracas' => 'America/Caracas',
'(GMT-04:00) La Paz' => 'America/La_Paz',
'(GMT-04:00) Santiago' => 'America/Santiago',
'(GMT-03:30) Newfoundland' => 'Canada/Newfoundland',
'(GMT-03:00) Brasilia' => 'America/Sao_Paulo',
'(GMT-03:00) Buenos Aires' => 'America/Argentina/Buenos_Aires',
'(GMT-03:00) Georgetown' => 'America/Argentina/Buenos_Aires',
'(GMT-03:00) Greenland' => 'America/Godthab',
'(GMT-02:00) Mid-Atlantic' => 'America/Noronha',
'(GMT-01:00) Azores' => 'Atlantic/Azores',
'(GMT-01:00) Cape Verde Is.' => 'Atlantic/Cape_Verde',
'(GMT+00:00) Casablanca' => 'Africa/Casablanca',
'(GMT+00:00) Edinburgh' => 'Europe/London',
'(GMT+00:00) Greenwich Mean Time : Dublin' => 'Etc/Greenwich',
'(GMT+00:00) Lisbon' => 'Europe/Lisbon',
'(GMT+00:00) London' => 'Europe/London',
'(GMT+00:00) Monrovia' => 'Africa/Monrovia',
'(GMT+00:00) UTC' => 'UTC',
'(GMT+01:00) Amsterdam' => 'Europe/Amsterdam',
'(GMT+01:00) Belgrade' => 'Europe/Belgrade',
'(GMT+01:00) Berlin' => 'Europe/Berlin',
'(GMT+01:00) Bern' => 'Europe/Berlin',
'(GMT+01:00) Bratislava' => 'Europe/Bratislava',
'(GMT+01:00) Brussels' => 'Europe/Brussels',
'(GMT+01:00) Budapest' => 'Europe/Budapest',
'(GMT+01:00) Copenhagen' => 'Europe/Copenhagen',
'(GMT+01:00) Ljubljana' => 'Europe/Ljubljana',
'(GMT+01:00) Madrid' => 'Europe/Madrid',
'(GMT+01:00) Paris' => 'Europe/Paris',
'(GMT+01:00) Prague' => 'Europe/Prague',
'(GMT+01:00) Rome' => 'Europe/Rome',
'(GMT+01:00) Sarajevo' => 'Europe/Sarajevo',
'(GMT+01:00) Skopje' => 'Europe/Skopje',
'(GMT+01:00) Stockholm' => 'Europe/Stockholm',
'(GMT+01:00) Vienna' => 'Europe/Vienna',
'(GMT+01:00) Warsaw' => 'Europe/Warsaw',
'(GMT+01:00) West Central Africa' => 'Africa/Lagos',
'(GMT+01:00) Zagreb' => 'Europe/Zagreb',
'(GMT+02:00) Athens' => 'Europe/Athens',
'(GMT+02:00) Bucharest' => 'Europe/Bucharest',
'(GMT+02:00) Cairo' => 'Africa/Cairo',
'(GMT+02:00) Harare' => 'Africa/Harare',
'(GMT+02:00) Helsinki' => 'Europe/Helsinki',
'(GMT+02:00) Istanbul' => 'Europe/Istanbul',
'(GMT+02:00) Jerusalem' => 'Asia/Jerusalem',
'(GMT+02:00) Kyiv' => 'Europe/Helsinki',
'(GMT+02:00) Pretoria' => 'Africa/Johannesburg',
'(GMT+02:00) Riga' => 'Europe/Riga',
'(GMT+02:00) Sofia' => 'Europe/Sofia',
'(GMT+02:00) Tallinn' => 'Europe/Tallinn',
'(GMT+02:00) Vilnius' => 'Europe/Vilnius',
'(GMT+03:00) Baghdad' => 'Asia/Baghdad',
'(GMT+03:00) Kuwait' => 'Asia/Kuwait',
'(GMT+03:00) Minsk' => 'Europe/Minsk',
'(GMT+03:00) Nairobi' => 'Africa/Nairobi',
'(GMT+03:00) Riyadh' => 'Asia/Riyadh',
'(GMT+03:00) Volgograd' => 'Europe/Volgograd',
'(GMT+03:30) Tehran' => 'Asia/Tehran',
'(GMT+04:00) Abu Dhabi' => 'Asia/Muscat',
'(GMT+04:00) Baku' => 'Asia/Baku',
'(GMT+04:00) Moscow' => 'Europe/Moscow',
'(GMT+04:00) Muscat' => 'Asia/Muscat',
'(GMT+04:00) St. Petersburg' => 'Europe/Moscow',
'(GMT+04:00) Tbilisi' => 'Asia/Tbilisi',
'(GMT+04:00) Yerevan' => 'Asia/Yerevan',
'(GMT+04:30) Kabul' => 'Asia/Kabul',
'(GMT+05:00) Islamabad' => 'Asia/Karachi',
'(GMT+05:00) Karachi' => 'Asia/Karachi',
'(GMT+05:00) Tashkent' => 'Asia/Tashkent',
'(GMT+05:30) Chennai' => 'Asia/Calcutta',
'(GMT+05:30) Kolkata' => 'Asia/Kolkata',
'(GMT+05:30) Mumbai' => 'Asia/Calcutta',
'(GMT+05:30) New Delhi' => 'Asia/Calcutta',
'(GMT+05:30) Sri Jayawardenepura' => 'Asia/Calcutta',
'(GMT+05:45) Kathmandu' => 'Asia/Katmandu',
'(GMT+06:00) Almaty' => 'Asia/Almaty',
'(GMT+06:00) Astana' => 'Asia/Dhaka',
'(GMT+06:00) Dhaka' => 'Asia/Dhaka',
'(GMT+06:00) Ekaterinburg' => 'Asia/Yekaterinburg',
'(GMT+06:30) Rangoon' => 'Asia/Rangoon',
'(GMT+07:00) Bangkok' => 'Asia/Bangkok',
'(GMT+07:00) Hanoi' => 'Asia/Bangkok',
'(GMT+07:00) Jakarta' => 'Asia/Jakarta',
'(GMT+07:00) Novosibirsk' => 'Asia/Novosibirsk',
'(GMT+08:00) Beijing' => 'Asia/Hong_Kong',
'(GMT+08:00) Chongqing' => 'Asia/Chongqing',
'(GMT+08:00) Hong Kong' => 'Asia/Hong_Kong',
'(GMT+08:00) Krasnoyarsk' => 'Asia/Krasnoyarsk',
'(GMT+08:00) Kuala Lumpur' => 'Asia/Kuala_Lumpur',
'(GMT+08:00) Perth' => 'Australia/Perth',
'(GMT+08:00) Singapore' => 'Asia/Singapore',
'(GMT+08:00) Taipei' => 'Asia/Taipei',
'(GMT+08:00) Ulaan Bataar' => 'Asia/Ulan_Bator',
'(GMT+08:00) Urumqi' => 'Asia/Urumqi',
'(GMT+09:00) Irkutsk' => 'Asia/Irkutsk',
'(GMT+09:00) Osaka' => 'Asia/Tokyo',
'(GMT+09:00) Sapporo' => 'Asia/Tokyo',
'(GMT+09:00) Seoul' => 'Asia/Seoul',
'(GMT+09:00) Tokyo' => 'Asia/Tokyo',
'(GMT+09:30) Adelaide' => 'Australia/Adelaide',
'(GMT+09:30) Darwin' => 'Australia/Darwin',
'(GMT+10:00) Brisbane' => 'Australia/Brisbane',
'(GMT+10:00) Canberra' => 'Australia/Canberra',
'(GMT+10:00) Guam' => 'Pacific/Guam',
'(GMT+10:00) Hobart' => 'Australia/Hobart',
'(GMT+10:00) Melbourne' => 'Australia/Melbourne',
'(GMT+10:00) Port Moresby' => 'Pacific/Port_Moresby',
'(GMT+10:00) Sydney' => 'Australia/Sydney',
'(GMT+10:00) Yakutsk' => 'Asia/Yakutsk',
'(GMT+11:00) Vladivostok' => 'Asia/Vladivostok',
'(GMT+12:00) Auckland' => 'Pacific/Auckland',
'(GMT+12:00) Fiji' => 'Pacific/Fiji',
'(GMT+12:00) International Date Line West' => 'Pacific/Kwajalein',
'(GMT+12:00) Kamchatka' => 'Asia/Kamchatka',
'(GMT+12:00) Magadan' => 'Asia/Magadan',
'(GMT+12:00) Marshall Is.' => 'Pacific/Fiji',
'(GMT+12:00) New Caledonia' => 'Asia/Magadan',
'(GMT+12:00) Solomon Is.' => 'Asia/Magadan',
'(GMT+12:00) Wellington' => 'Pacific/Auckland',
'(GMT+13:00) Nuku\'alofa' => 'Pacific/Tongatapu'
);
?>
You need to use delimiters with regexes in PHP. You can use the often used /
, but PHP lets you use any matching characters, so @
and #
are popular.
If you are interpolating variables inside your regex, be sure to pass the delimiter you chose as the second argument to preg_quote()
.
That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:
JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println data.link }
If you know it's a single-element Map then you can directly access the link
:
def data = userJson.values().iterator().next()
String link = data.link
And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:
String id = '212315952136472'
...
String link = userJson[id].link
finally I found... it will work nice when table displays only 3 rows... if rows are more change should be accordingly...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
cell.textLabel.text =[NSString stringWithFormat:@"Hello roe no. %d",[indexPath row]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell * theCell = (UITableViewCell *)[tableView
cellForRowAtIndexPath:indexPath];
CGPoint tableViewCenter = [tableView contentOffset];
tableViewCenter.y += myTable.frame.size.height/2;
[tableView setContentOffset:CGPointMake(0,theCell.center.y-65) animated:YES];
[tableView reloadData];
}
getopt()
/getopts()
is a good option. Copied from here:
The simple use of "getopt" is shown in this mini-script:
#!/bin/bash
echo "Before getopt"
for i
do
echo $i
done
args=`getopt abc:d $*`
set -- $args
echo "After getopt"
for i
do
echo "-->$i"
done
What we have said is that any of -a, -b, -c or -d will be allowed, but that -c is followed by an argument (the "c:" says that).
If we call this "g" and try it out:
bash-2.05a$ ./g -abc foo
Before getopt
-abc
foo
After getopt
-->-a
-->-b
-->-c
-->foo
-->--
We start with two arguments, and "getopt" breaks apart the options and puts each in its own argument. It also added "--".
You can simply delete this folder
/Library/Developer/CommandLineTools
Please note: This is the root /Library, not user's ~/Library).
mvn install "-Dsomeproperty=propety value"
In pom.xml:
<properties>
<someproperty> ${someproperty} </someproperty>
</properties>
Referred from this question
This should make your TextView bold, underlined and italic at the same time.
strings.xml
<resources>
<string name="register"><u><b><i>Copyright</i></b></u></string>
</resources>
To set this String to your TextView, do this in your main.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/register" />
or In JAVA,
TextView textView = new TextView(this);
textView.setText(R.string.register);
Sometimes the above approach will not be helpful when you might have to use Dynamic Text. So in that case SpannableString comes into action.
String tempString="Copyright";
TextView text=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.ITALIC), 0, spanString.length(), 0);
text.setText(spanString);
OUTPUT
After some thinking i came up with this solution:
LENGTHB(TO_CHAR(SUBSTR(<CLOB-Column>,1,4000)))
SUBSTR
returns only the first 4000 characters (max string size)
TO_CHAR
converts from CLOB
to VARCHAR2
LENGTHB
returns the length in Bytes used by the string.
You have to match the settings for PHP-FPM and Nginx to communicate over sockets or TCP.
So go to /etc/php5/fpm/pool.d/www.conf
and look for this line:
listen = /var/run/php5-fpm.sock
Then go to /etc/nginx/nginx.conf
Look for this:
upstream php {
server unix:/var/run/php5-fpm.socket;
}
Match those values and you should be all set.
It has been three years since this question was asked, but I am just now coming across it. Since this answer is so far down the stack, please allow me to repeat it:
Q: I am interested if there are any limits to what types of values can be set using const in JavaScript—in particular functions. Is this valid? Granted it does work, but is it considered bad practice for any reason?
I was motivated to do some research after observing one prolific JavaScript coder who always uses const
statement for functions
, even when there is no apparent reason/benefit.
In answer to "is it considered bad practice for any reason?" let me say, IMO, yes it is, or at least, there are advantages to using function
statement.
It seems to me that this is largely a matter of preference and style. There are some good arguments presented above, but none so clear as is done in this article:
Constant confusion: why I still use JavaScript function statements by medium.freecodecamp.org/Bill Sourour, JavaScript guru, consultant, and teacher.
I urge everyone to read that article, even if you have already made a decision.
Here's are the main points:
Function statements have two clear advantages over [const] function expressions:
Advantage #1: Clarity of intent
When scanning through thousands of lines of code a day, it’s useful to be able to figure out the programmer’s intent as quickly and easily as possible.
Advantage #2: Order of declaration == order of execution
Ideally, I want to declare my code more or less in the order that I expect it will get executed.
This is the showstopper for me: any value declared using the const keyword is inaccessible until execution reaches it.
What I’ve just described above forces us to write code that looks upside down. We have to start with the lowest level function and work our way up.
My brain doesn’t work that way. I want the context before the details.
Most code is written by humans. So it makes sense that most people’s order of understanding roughly follows most code’s order of execution.
If you're using webservices, you'll also need the 'allow-http-request-headers-from' element. Here's our default, development, 'allow everything' policy.
<?xml version="1.0" ?>
<cross-domain-policy>
<site-control permitted-cross-domain-policies="master-only"/>
<allow-access-from domain="*"/>
<allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>
I got this Error after re-creating a Repository on my Server (Codebeamer) - the User in Question lacked some permissions, after granting them, everything worked fine.
This solution works if you are using asp.net validators:
<script language="javascript" type="text/javascript">
function disableButton(sender,group)
{
Page_ClientValidate(group);
if (Page_IsValid)
{
sender.disabled = "disabled";
__doPostBack(sender.name, '');
}
}</script>
and change the button:
<asp:Button runat="server" ID="btnSendMessage" Text="Send" OnClick="btnSendMessage_OnClick" OnClientClick="disableButton(this,'theValidationGroup')" CausesValidation="true" ValidationGroup="theValidationGroup" />
This happens when your result is not a result (but a "false" instead). You should change this line
$sql = 'SELECT * FROM $usertable WHERE PartNumber = $partid';
to this:
$sql = "SELECT * FROM $usertable WHERE PartNumber = $partid";
because the " can interprete $variables while ' cannot.
Works fine with integers (numbers), for strings you need to put the $variable in single quotes, like
$sql = "SELECT * FROM $usertable WHERE PartNumber = '$partid' ";
If you want / have to work with single quotes, then php CAN NOT interprete the variables, you will have to do it like this:
$sql = 'SELECT * FROM '.$usertable.' WHERE string_column = "'.$string.'" AND integer_column = '.$number.';
gcc main.cpp -o main.out
./main.out
along the lines of bayer's answer:
''.join(i for i in s if i.isdigit())
Use concat() function instead of +
like this:
select concat(firstname, lastname) as "Name" from test.student
The default font on windows 10 is Consolas
To access services in two different namespaces you can use url like this:
HTTP://<your-service-name>.<namespace-with-that-service>.svc.cluster.local
To list out all your namespaces you can use:
kubectl get namespace
And for service in that namespace you can simply use:
kubectl get services -n <namespace-name>
this will help you.
Here are the steps that worked for me:
C:\Program Files\Notepad++\plugins
Settings -> Import -> Import plugin
(import the plugin).So for people who want semantics similar to:
$ chmod 755 somefile
Use:
$ python -c "import os; os.chmod('somefile', 0o755)"
If your Python is older than 2.6:
$ python -c "import os; os.chmod('somefile', 0755)"
If the other solutions don't work, you can always see the output in the Android Monitor.
Make sure to set your filter to Show only selected application or create a custom filter.
Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.
First, your IntentFilter must contain an event.
static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
Second, when you send a broadcast, use this same action:
Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);
Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.
Fourth, is your service declared in the AndroidManifest.xml?
You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.
One way around this is to use JSONP. This allows cross-site requests.
In JSON, you are returned:
{a: 5, b: 6}
In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.
callback({a: 5, b: 6})
You need to edit your REST service to accept a parameter called callback
, and then to use the value of that parameter as the function name. You should also change the content-type
to application/javascript
.
For example: http://localhost:8080/restws/json/product/get?callback=process
should output:
process({a: 5, b: 6})
In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=?
to the URL.
$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
function(data) {
alert(data);
});
If you use $.ajax
, it will auto append the ?callback=?
if you tell it to use jsonp
.
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/restws/json/product/get",
success: function(data){
alert(data);
}
});
In order to connect remotely you have to have MySQL bind port 3306 to your machine's IP address in my.cnf. Then you have to have created the user in both localhost and '%' wildcard and grant permissions on all DB's as such . See below:
my.cnf (my.ini on windows)
#Replace xxx with your IP Address
bind-address = xxx.xxx.xxx.xxx
then
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';
Then
GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';
flush privileges;
Depending on your OS you may have to open port 3306 to allow remote connections.
There is another way, take this as example
Dim sr As String
sr = "6:10"
Rows(sr).Select
All you need to do is to convert your variables iStartRow
, iEndRow
to a string.
You can do it in two different ways.
Option 1: The -eq
operator
>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False
Option 2: The .Equals()
method of the string
object. Because strings in PowerShell are .Net System.String
objects, any method of that object can be called directly.
>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method
List of System.String
methods follows.
Here is another variation that works well for me, adjust the rect.top + 40, rect.left + 0 to suit your needs:
$(".datepicker").datepicker({_x000D_
changeMonth: true,_x000D_
changeYear: true,_x000D_
dateFormat: 'mm/dd/yy',_x000D_
beforeShow: function (input, inst) {_x000D_
var rect = input.getBoundingClientRect();_x000D_
setTimeout(function () {_x000D_
inst.dpDiv.css({ top: rect.top + 40, left: rect.left + 0 });_x000D_
}, 0);_x000D_
}_x000D_
});
_x000D_
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">_x000D_
<script src="//code.jquery.com/jquery-1.10.2.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>_x000D_
<form>_x000D_
<input class="datepicker" name="date1" type="text">_x000D_
<input class="datepicker" name="date2" type="text">_x000D_
</form>
_x000D_
Here's a compact Objective-C version as a Category on NSData. It takes some thinking about...
@implementation NSData (DataUtils)
static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- (NSString *)newStringInBase64FromData
{
NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];
unsigned char * working = (unsigned char *)[self bytes];
int srcLen = [self length];
// tackle the source in 3's as conveniently 4 Base64 nibbles fit into 3 bytes
for (int i=0; i<srcLen; i += 3)
{
// for each output nibble
for (int nib=0; nib<4; nib++)
{
// nibble:nib from char:byt
int byt = (nib == 0)?0:nib-1;
int ix = (nib+1)*2;
if (i+byt >= srcLen) break;
// extract the top bits of the nibble, if valid
unsigned char curr = ((working[i+byt] << (8-ix)) & 0x3F);
// extract the bottom bits of the nibble, if valid
if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) & 0x3F);
[dest appendFormat:@"%c", base64[curr]];
}
}
return dest;
}
@end
Padding can be added if required by making the scope of 'byt' wider and appending 'dest' with (2-byt) "=" characters before returning.
A Category can then be added to NSString, thus:
@implementation NSString (StringUtils)
- (NSString *)newStringInBase64FromString
{
NSData *theData = [NSData dataWithBytes:[self UTF8String] length:[self length]];
return [theData newStringInBase64FromData];
}
@end
add your script tag on the bottom of the body tag. so that script loads after html content then you won't get such error and add=
My Java version was the 1.6 and I found that was using 1.7 with CDI however after that I changed the Java version to 1.7 and import the package javax.faces.bean.ManagedBean and everything worked.
Thanks @PM77-1
Try to just use isNotNull function.
df.filter(df.dt_mvmt.isNotNull()).count()
Create PROCEDURE USP_S_NameAvilability
(@Value VARCHAR(50)=null,
@TableName VARCHAR(50)=null,
@ColumnName VARCHAR(50)=null)
AS
BEGIN
DECLARE @cmd AS NVARCHAR(max)
SET @Value = ''''+@Value+ ''''
SET @cmd = N'SELECT * FROM ' + @TableName + ' WHERE ' + @ColumnName + ' = ' + @Value
EXEC(@cmd)
END
As i have tried one the answer, it is getting executed successfully but while running its not giving correct output, the above works well
I had the similar issue and I resolved with below steps:
** Add proxy details in git**
git config --global http.sslVerify false
git config --global https.sslVerify false
git config --global http.proxy http://user:pass@yourproxy:port
git config --global https.proxy http://user:pass@yourproxy:port
You'll probably have to either give it a constant class and call getElementsByClassName
, or maybe just use getElementsByTagName
, and loop through your results, checking the name.
I'd suggest looking at your underlying problem and figure out a way where you can know the ID in advance.
Maybe if you posted a little more about why you're getting this, we could find a better alternative.
@Bass Jobsen and @ElwoodP attempted to answer this question in reverse--giving the outer margins the same DOUBLE size as the gutters. The OP (and me, as well) was searching for a way to have a SINGLE size gutter in all places. Here are the correct CSS adjustments to do so:
.row {
margin-left: -7px;
margin-right: -7px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
padding-left: 7px;
padding-right: 7px;
}
.container {
padding-left: 14px;
padding-right: 14px;
}
This leaves a 14px
gutter and outside margin in all places.
var value1=$("id1").val();
var value2=$("id2").val();
data:"{'data1':'"+value1+"','data2':'"+value2+"'}"
You can use this way to pass data
For SQL Server 2016+ and Azure SQL Database, the STRING_SPLIT function was added that would be a perfect solution for this problem. Here is the documentation: https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql
Here is an example:
/*List of ids in a comma delimited string
Note: the ') WAITFOR DELAY ''00:00:02''' is a way to verify that your script
doesn't allow for SQL injection*/
DECLARE @listOfIds VARCHAR(MAX) = '1,3,a,10.1,) WAITFOR DELAY ''00:00:02''';
--Make sure the temp table was dropped before trying to create it
IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP TABLE #MyTable;
--Create example reference table
CREATE TABLE #MyTable
([Id] INT NOT NULL);
--Populate the reference table
DECLARE @i INT = 1;
WHILE(@i <= 10)
BEGIN
INSERT INTO #MyTable
SELECT @i;
SET @i = @i + 1;
END
/*Find all the values
Note: I silently ignore the values that are not integers*/
SELECT t.[Id]
FROM #MyTable as t
INNER JOIN
(SELECT value as [Id]
FROM STRING_SPLIT(@listOfIds, ',')
WHERE ISNUMERIC(value) = 1 /*Make sure it is numeric*/
AND ROUND(value,0) = value /*Make sure it is an integer*/) as ids
ON t.[Id] = ids.[Id];
--Clean-up
DROP TABLE #MyTable;
The result of the query is 1,3
~Cheers
you can also check this link
SELECT * FROM master_question
WHERE 1 ORDER BY question_id
ASC LIMIT 20
There is also another possible source of this error. In some J2EE / web containers (in my experience under Jboss 7.x and Tomcat 7.x) You have to add each class You want to use as a hibernate Entity into the file persistence.xml as
<class>com.yourCompanyName.WhateverEntityClass</class>
In case of jboss this concerns every entity class (local - i.e. within the project You are developing or in a library). In case of Tomcat 7.x this concerns only entity classes within libraries.
Try this code using VIewWillDisappear
method to detect the press of The back button of NavigationItem:
-(void) viewWillDisappear:(BOOL)animated
{
if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound)
{
// Navigation button was pressed. Do some stuff
[self.navigationController popViewControllerAnimated:NO];
}
[super viewWillDisappear:animated];
}
OR There is another way to get Action of the Navigation BAck button.
Create Custom button for UINavigationItem of back button .
For Ex:
In ViewDidLoad :
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStyleBordered target:self action:@selector(home:)];
self.navigationItem.leftBarButtonItem=newBackButton;
}
-(void)home:(UIBarButtonItem *)sender
{
[self.navigationController popToRootViewControllerAnimated:YES];
}
Swift :
override func willMoveToParentViewController(parent: UIViewController?)
{
if parent == nil
{
// Back btn Event handler
}
}
input file element:
<input type="file" id="fileinput" />
get file :
var myFile = $('#fileinput').prop('files');
An adaption to @Mrchief's / @amit's answer, but for people using VB
Dim JSONOut As String = JsonConvert.SerializeObject(
myContainerObject,
New JsonSerializerSettings With {
.NullValueHandling = NullValueHandling.Ignore
}
)
See: "Object Initializers: Named and Anonymous Types (Visual Basic)"
As of MVC 5 this can be easily achieved by adding this in your global.asax
.
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
Can't you set the Loglevel in httpd.conf to debug? (I'm using FreeBSD)
ee usr/local/etc/apache22/httpd.conf
change loglevel :
'LogLevel: Control the number of messages logged to the error_log. Possible values include: debug, info, notice, warn, error, crit, alert, emerg.'
Try changing to debug and re-checking the error log after that.
I don't think you have data for every single day for the past seven days. Days for which no data exist, will obviously not show up.
Try this and validate that you have data for EACH day for the past 7 days
SELECT DISTINCT CreatedDate
FROM News
WHERE CreatedDate >= DATEADD(day,-7, GETDATE())
ORDER BY CreatedDate
EDIT - Copied from your comment
i have dec 19th -1 row data,18th -2 rows,17th -3 rows,16th -3 rows,15th -3 rows,12th -2 rows, 11th -4 rows,9th -1 row,8th -1 row
You don't have data for all days. That is your problem and not the query. If you execute the query today - 22nd - you will only get data for 19th, 18th,17th,16th and 15th. You have no data for 20th, 21st and 22nd.
EDIT - To get data for the last 7 days, where data is available you can try
select id,
NewsHeadline as news_headline,
NewsText as news_text,
state,
CreatedDate as created_on
from News
WHERE CreatedDate IN (SELECT DISTINCT TOP 7 CreatedDate from News
order by createddate DESC)
The git solution for such scenarios is setting SKIP-WORKTREE BIT. Run only the following command:
git update-index --skip-worktree .classpath .gitignore
It is used when you want git to ignore changes of files that are already managed by git and exist on the index. This is a common use case for config files.
Running git rm --cached
doesn't work for the scenario mentioned in the question. If I simplify the question, it says:
How to have
.classpath
and.project
on the repo while each one can change it locally and git ignores this change?
As I commented under the accepted answer, the drawback of git rm --cached
is that it causes a change in the index, so you need to commit the change and then push it to the remote repository. As a result, .classpath
and .project
won't be available on the repo while the PO wants them to be there so anyone that clones the repo for the first time, they can use it.
Based on git documentaion:
Skip-worktree bit can be defined in one (long) sentence: When reading an entry, if it is marked as skip-worktree, then Git pretends its working directory version is up to date and read the index version instead. Although this bit looks similar to assume-unchanged bit, its goal is different from assume-unchanged bit’s. Skip-worktree also takes precedence over assume-unchanged bit when both are set.
More details is available here.
@Synxmax's answer is correct when using a Service
and the MediaPlayer
class, however you also need to declare the Service
in the Manifest for this to work, like so:
<service
android:enabled="true"
android:name="com.package.name.BackgroundSoundService" />
[k for k,v in l if v =='delicia']
here l is the list of tuples-[(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
And instead of converting it to a dict, we are using llist comprehension.
*Key* in Key,Value in list, where value = **delicia**
To see both of the structure and location (directory) of an any (internal or external)table, we can use table's create statment-
show create table table_name;
Use jQuery.attr()
in your click handler:
$("#myform").attr('action', 'page1.php');
"Segmentation fault" means that you tried to access memory that you do not have access to.
The first problem is with your arguments of main
. The main
function should be int main(int argc, char *argv[])
, and you should check that argc
is at least 2 before accessing argv[1]
.
Also, since you're passing in a float
to printf
(which, by the way, gets converted to a double
when passing to printf
), you should use the %f
format specifier. The %s
format specifier is for strings ('\0'
-terminated character arrays).
clone() was designed with several mistakes (see this question), so it's best to avoid it.
From Effective Java 2nd Edition, Item 11: Override clone judiciously
Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays. If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.
This book also describes the many advantages copy constructors have over Cloneable/clone.
All standard collections have copy constructors. Use them.
List<Double> original = // some list
List<Double> copy = new ArrayList<Double>(original);
$(window).on("touchstart", function(ev) {
var e = ev.originalEvent;
console.log(e.touches);
});
I know it been asked a long time ago, but I thought a concrete example might help.
k = sh.Range("A2", sh.Range("A1").End(xlDown)).Rows.Count
or
k = sh.Range("A2", sh.Range("A1").End(xlDown)).Cells.Count
or
k = sh.Range("A2", sh.Range("A1").End(xlDown)).Count
It's a one-liner with mutate_at
:
dat %>% mutate_at("l1", factor) %>% mutate_at("l2", as.numeric)
As most answers seem to be pretty old here, referencing menu items I can't seem to find in the current versions of popular browsers, here's how to do it in the current version in Firefox Developer Edition:
CTRL + SHIFT + I
)How about the H2 console application?
Have you tried the uncurl
package (https://github.com/spulec/uncurl)? You can install it via pip, pip install uncurl
. Your curl request returns:
>>> uncurl "curl --header \"Authorization:access_token myToken\" https://website.com/id"
requests.get("https://website.com/id",
headers={
"Authorization": "access_token myToken"
},
cookies={},
)
As long as you're doing a fast-forward merge, then you can simply use
git fetch <remote> <sourceBranch>:<destinationBranch>
Examples:
# Merge local branch foo into local branch master,
# without having to checkout master first.
# Here `.` means to use the local repository as the "remote":
git fetch . foo:master
# Merge remote branch origin/foo into local branch foo,
# without having to checkout foo first:
git fetch origin foo:foo
While Amber's answer will also work in fast-forward cases, using git fetch
in this way instead is a little safer than just force-moving the branch reference, since git fetch
will automatically prevent accidental non-fast-forwards as long as you don't use +
in the refspec.
You cannot merge a branch B into branch A without checking out A first if it would result in a non-fast-forward merge. This is because a working copy is needed to resolve any potential conflicts.
However, in the case of fast-forward merges, this is possible, because such merges can never result in conflicts, by definition. To do this without checking out a branch first, you can use git fetch
with a refspec.
Here's an example of updating master
(disallowing non-fast-forward changes) if you have another branch feature
checked out:
git fetch upstream master:master
This use-case is so common, that you'll probably want to make an alias for it in your git configuration file, like this one:
[alias]
sync = !sh -c 'git checkout --quiet HEAD; git fetch upstream master:master; git checkout --quiet -'
What this alias does is the following:
git checkout HEAD
: this puts your working copy into a detached-head state. This is useful if you want to update master
while you happen to have it checked-out. I think it was necessary to do with because otherwise the branch reference for master
won't move, but I don't remember if that's really right off-the-top of my head.
git fetch upstream master:master
: this fast-forwards your local master
to the same place as upstream/master
.
git checkout -
checks out your previously checked-out branch (that's what the -
does in this case).
git fetch
for (non-)fast-forward mergesIf you want the fetch
command to fail if the update is non-fast-forward, then you simply use a refspec of the form
git fetch <remote> <remoteBranch>:<localBranch>
If you want to allow non-fast-forward updates, then you add a +
to the front of the refspec:
git fetch <remote> +<remoteBranch>:<localBranch>
Note that you can pass your local repo as the "remote" parameter using .
:
git fetch . <sourceBranch>:<destinationBranch>
From the git fetch
documentation that explains this syntax (emphasis mine):
<refspec>
The format of a
<refspec>
parameter is an optional plus+
, followed by the source ref<src>
, followed by a colon:
, followed by the destination ref<dst>
.The remote ref that matches
<src>
is fetched, and if<dst>
is not empty string, the local ref that matches it is fast-forwarded using<src>
. If the optional plus+
is used, the local ref is updated even if it does not result in a fast-forward update.
I ran into a similar issue where eclipse was not using my current %JAVA_HOME%
that was on the path
and was instead using an older version. The documentation points out that if no -vm
is specified in the ini file, eclipse will search for a shared library jvm.dll
This appears in the registry under the key HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment
that gets installed when using the windows java installer (key might be a bit different based on 64-bit vs 32-bit, but search for jvm.dll
). Because it was finding this shared library on my path
before the %JAVA_HOME%/bin
, it was using the old version.
Like others have stated, the easiest way to deal with this is to specify the specific vm you want to use in the eclipse.ini
file. I'm writing this because I couldn't figure out how it was still using the old version when it wasn't specified anywhere on the path
or eclipse.ini
file.
See link to doc below: http://help.eclipse.org/kepler/topic/org.eclipse.platform.doc.isv/reference/misc/launcher.html?cp=2_1_3_1
Finding a VM and using the JNI Invocation API
The Eclipse launcher is capable of loading the Java VM in the eclipse process using the Java Native Interface Invocation API. The launcher is still capable of starting the Java VM in a separate process the same as previous version of Eclipse did. Which method is used depends on how the VM was found.
No -vm specified
When no -vm is specified, the launcher looks for a virtual machine first in a jre directory in the root of eclipse and then on the search path. If java is found in either location, then the launcher looks for a jvm shared library (jvm.dll on Windows, libjvm.so on *nix platforms) relative to that java executable.
- If a jvm shared library is found the launcher loads it and uses the JNI invocation API to start the vm.
- If no jvm shared library is found, the launcher executes the java launcher to start the vm in a new process.
-vm specified on the command line or in eclipse.ini
Eclipse can be started with "-vm " to indicate a virtual machine to use. There are several possibilities for the value of :
- directory: is a directory. We look in that directory for:
- (1) a java launcher or
- (2) the jvm shared library.
If we find the jvm shared library, we use JNI invocation. If we find a launcher, we attempt to find a jvm library in known locations relative to the launcher. If we find one, we use JNI invocation. If no jvm library is found, we exec java in a new process.
java.exe/javaw.exe: is a path to a java launcher. We exec that java launcher to start the vm in a new process.
jvm dll or so: is a path to a jvm shared library. We attempt to load that library and use the JNI Invocation API to start the vm in the current process.
You may also want to consider the possibility of using SWT (another Java GUI library). Pros and cons of each are listed at:
You have 2 options here to do that either to discard all your outgoing commits OR to undo specific commit ..
1- Discard all your outgoing commits:
To discard all your outgoing commits For example if you have local branch named master from remote branch, You can:
1- Rename your local branch from master to anything so you can remove it. 2- Remove the renamed branch. 3- create new branch from the master
So now you have a new branch without your commits ..
2- Undo specific commit: To undo specific commit you have to revert the unneeded by:
1- Double click on the unneeded commit. Double click on the unneeded commit 2- Click on revert Click on revert
But FYI the reverted commit will appear in the history of your commits with the revert commit ..
How does spring know which polymorphic type to use.
As long as there is only a single implementation of the interface and that implementation is annotated with @Component
with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).
Do I need @Qualifier or @Resource?
Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier
annotation to inject the right implementation, along with @Autowired
annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name
attribute of this annotation.
Why do we autowire the interface and not the implemented class?
Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.
interface IA
{
public void someFunction();
}
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Your bean configuration should look like this:
<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />
Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with @Component
as follows:
interface IA
{
public void someFunction();
}
@Component(value="b")
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
@Component(value="c")
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
@Component
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Then worker
in MyRunner
will be injected with an instance of type B
.
If you are working with MVC C#, this is the way to deal with printers and serial ports for dropdowns.
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;
using System.Drawing.Printing;
public class Miclass
{
private void AllViews()
{
List<PortClass> ports = new List<PortClass>();
List<Printersclass> Printersfor = new List<Printersclass>();
string[] portnames = SerialPort.GetPortNames();
/*PORTS*/
for (int i = 0; i < portnames.Count(); i++)
{
ports.Add(new PortClass() { Name = portnames[i].Trim(), Desc = portnames[i].Trim() });
}
/*PRINTER*/
for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
{
Printersfor.Add(new Printersclass() { Name = PrinterSettings.InstalledPrinters[i].Trim(), Desc = PrinterSettings.InstalledPrinters[i].Trim() });
}
}
}
public class PortClass
{
public string Name { get; set; }
public string Desc { get; set; }
public override string ToString()
{
return string.Format("{0} ({1})", Name, Desc);
}
}
public class Printersclass
{
public string Name { get; set; }
public string Desc { get; set; }
public override string ToString()
{
return string.Format("{0} ({1})", Name, Desc);
}
}
The key lies in when you create the project in eclipse.
First step, you create the Java project in eclipse. Right click on the project and choose Team > Share>Git.
In the Configure Git Repository dialog, ensure that you select the option to create the Repository in the parent folder of the project.. Then you can push to github.
N.B: Eclipse will give you a warning about putting git repositories in your workspace. So when you create your project, set your project directory outside the default workspace.
It sounds to me as if you actually mean "linux guests" and not "linux hosts".
But in any case, I suspect you did not install the VMWare Tools: doubleclick on that icon on the Desktop that can be seen on your screenshot. It will install some drivers that communicate with VMWare that, among other things, allow to adjust the screen resolution dynamically.
When the installation process is finished, you'll most likely have to reboot the VM.
Cerating extention method like one suggested does not really solve issues with race conditions, but rather hide them.
public static void SafeInvoke(this EventHandler handler, object sender)
{
if (handler != null) handler(sender, EventArgs.Empty);
}
As stated this code is the elegant equivalent to solution with temporary variable, but...
The problem with both that it's possible that subsciber of the event could be called AFTER it has unsubscribed from the event. This is possible because unsubscription can happen after delegate instance is copied to the temp variable (or passed as parameter in the method above), but before delegate is invoked.
In general the behaviour of the client code is unpredictable in such case: component state could not allow to handle event notification already. It's possible to write client code in the way to handle it, but it would put unnecesssary responsibility to the client.
The only known way to ensure thread safity is to use lock statement for the sender of the event. This ensures that all subscriptions\unsubscriptions\invocation are serialized.
To be more accurate lock should be applied to the same sync object used in add\remove event accessor methods which is be default 'this'.
Yes, if bar is not None
is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar:
will execute if bar
is any kind of zero or empty container, or False
.
Many people do use not bar
where they really do mean bar is not None
.
You can do that in this way:
ORDER BY `products`.`product_category_id` DESC ,`naam` ASC
Have a look at ORDER BY
Optimization
Ok, For installing Android on Windows phone, I think you can..(But your window phone has required configuration to run Android) (For other I don't know If I will then surely post here)
Just go through these links,
Run Android on Your Windows Mobile Phone
full tutorial on how to put android on windows mobile touch pro 2
How to install Android on most Windows Mobile phones
Update:
For Windows 7 to Android device, this also possible, (You need to do some hack for this)
Just go through these links,
Install Windows Phone 7 Mango on HTC HD2 [How-To Guide]
HTC HD2: How To Install WP7 (Windows Phone 7) & MAGLDR 1.13 To NAND
Install windows phone 7 on android and iphones | Tips and Tricks
How to install Windows Phone 7 on HTC HD2? (Video)
To Install Android on your iOS Devices (This also possible...)
After making no changes to a production server we began receiving this error. After trying several different things and thinking that perhaps there were DNS issues, restarting IIS fixed the issue (restarting only the site did not fix the issue). It likely won't work for everyone but if we tried that first it would have saved a lot of time.
I found this is working perfectly
str = "count a character occurance"
str = str.replace(' ', '')
print (str)
print (len(str))
The question doesn't ask for jquery. So lets do it without jquery:
document.addEventListener("DOMContentLoaded", function(event) {
//Do work
});
Note this method will not work on IE8.
You are calling this script before DOM is ready. If you write this code into jquery's $(function() method it will work.
Off hand, setting the http.agent
system property to ""
might do the trick (I don't have the code in front of me).
You might get away with:
System.setProperty("http.agent", "");
but that might require a race between you and initialisation of the URL protocol handler, if it caches the value at startup (actually, I don't think it does).
The property can also be set through JNLP files (available to applets from 6u10) and on the command line:
-Dhttp.agent=
Or for wrapper commands:
-J-Dhttp.agent=
You're giving parameters to your program instead to Java. Use
java -Dtest="true" -jar myApplication.jar
instead.
Consider using
"true".equalsIgnoreCase(System.getProperty("test"))
to avoid the NPE. But do not use "Yoda conditions" always without thinking, sometimes throwing the NPE is the right behavior and sometimes something like
System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")
is right (providing default true). A shorter possibility is
!"false".equalsIgnoreCase(System.getProperty("test"))
but not using double negation doesn't make it less hard to misunderstand.
Use the requests library, pretty print the results so you can better locate the keys/values you want to extract, and then use nested for loops to parse the data. In the example I extract step by step driving directions.
import json, requests, pprint
url = 'http://maps.googleapis.com/maps/api/directions/json?'
params = dict(
origin='Chicago,IL',
destination='Los+Angeles,CA',
waypoints='Joplin,MO|Oklahoma+City,OK',
sensor='false'
)
data = requests.get(url=url, params=params)
binary = data.content
output = json.loads(binary)
# test to see if the request was valid
#print output['status']
# output all of the results
#pprint.pprint(output)
# step-by-step directions
for route in output['routes']:
for leg in route['legs']:
for step in leg['steps']:
print step['html_instructions']
Below is the way we are going within our developing application.
import java.text.SimpleDateFormat
String newDateAdded = "2018-11-11T09:30:31"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
Date dateAdded = dateFormat.parse(newDateAdded)
println(dateAdded)
The output looks like
Sun Nov 11 09:30:31 GMT 2018
In your example, we could adjust a bit to meet your need. If I were you, I will do:
String datePattern = "d/M/yyyy H:m:s"
String theDate = "28/09/2010 16:02:43"
SimpleDateFormat df = new SimpleDateFormat(datePattern)
println df.parse(theDate)
I hope this would help you much.
Who do you trust?
I've always considered this area too critical to trust a third party to manage the runtime security of your application. Once that component is cracked for one application, it's cracked for all applications. It happened to Discreet in five minutes once they went with a third-party license solution for 3ds Max years ago... Good times!
Seriously, consider rolling your own for having complete control over your algorithm. If you do, consider using components in your key along the lines of:
Then checksum the hell out of them and add whatever (reversable) encryption you want to it to make it harder to crack.
To make a trial license key, simply have set values for the above values that translate as "trial mode".
And since this is now probably the most important code in your application/company, on top of/instead of obfuscation consider putting the decrypt routines in a native DLL file and simply P/Invoke to it.
Several companies I've worked for have adopted generalised approaches for this with great success. Or maybe the products weren't worth cracking ;)
I used dir /s /b /o:n /a:d
, and it worked perfectly, just make sure you let the file finish writing, or you'll have an incomplete list.
The modal dialog can be positioned on top by overriding its z-index property:
.modal.fade {
z-index: 10000000 !important;
}
Ran into this same issue. Background info: before building, I had added a new Project X to the solution. Project Y depended on Project X and Project A, B, C depended on Project Y.
Build errors were that Project A, B, C, Y, and X dlls could not be found.
Root cause was that newly created Project X targeted .NET 4.5 while the rest of the solution projects targeted .NET 4.5.1. Project X didn't build causing the rest of the Projects to not build either.
Make sure any newly added Projects target the same .NET version as the rest of the solution.
In Controller i have specified the below code with ActionResult which is a base class that can have 11 subtypes in MVC like: ViewResult, PartialViewResult, EmptyResult, RedirectResult, RedirectToRouteResult, JsonResult, JavaScriptResult, ContentResult, FileContentResult, FileStreamResult, FilePathResult.
public ActionResult Index()
{
if (HttpContext.Session["LoggedInUser"] == null)
{
return RedirectToAction("Login", "Home");
}
else
{
return View(); // returns ViewResult
}
}
//More Examples
[HttpPost]
public ActionResult Index(string Name)
{
ViewBag.Message = "Hello";
return Redirect("Account/Login"); //returns RedirectResult
}
[HttpPost]
public ActionResult Index(string Name)
{
return RedirectToRoute("RouteName"); // returns RedirectToRouteResult
}
Likewise we can return all these 11 subtypes by using ActionResult() without specifying every subtype method explicitly. ActionResult is the best thing if you are returning different types of views.
Depends on the database server. MySQL
doesn't care, its basically the same thing.
Oracle
, DB2
, and other enterprise level database solutions make a distinction. Usually a schema is a collection of tables and a Database is a collection of schemas.