Previously, you would do this through NPAPI plugins.
However, Google is now phasing out NPAPI for Chrome, so the preferred way to do this is using the native messaging API. The external application would have to register a native messaging host in order to exchange messages with your application.
If the text is retrieved from a mysql database you may try adding this after BD connection.
mysqli_set_charset($con, "utf8");
There are two primary contenders for python apps on Android
This integrates with the Android build system, it provides a Python API for all android features. To quote the site "The complete Android API and user interface toolkit are directly at your disposal."
This provides a multi target transpiler, supports many targets such as Android and iOS. It uses a generic widget toolkit (toga) that maps to the host interface calls.
Both are active projects and their github accounts shows a fair amount of recent activity.
Beeware Toga like all widget libraries is good for getting the basics out to multiple platforms. If you have basic designs, and a desire to expand to other platforms this should work out well for you.
On the other hand, Chaquopy is a much more precise in its mapping of the python API to Android. It also allows you to mix in Java, useful if you want to use existing code from other resources. If you have strict design targets, and predominantly want to target Android this is a much better resource.
The problem is in the line,
int([x[age1]])
What you want is
x = int(age1)
You also need to convert the int to a string for the output...
print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."
The complete script looks like,
name1 = raw_input("What's your name? ")
age1 = raw_input ("how old are you? ")
x = 0
x = int(age1)
twentyone = 21 - x
print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."
Although this question isn't quite new and an answer was already chosen, I would like to share another nice approach.
Using the paramiko library - a pure python implementation of SSH2 - your python script can connect to a remote host via SSH, copy itself (!) to that host and then execute that copy on the remote host. Stdin, stdout and stderr of the remote process will be available on your local running script. So this solution is pretty much independent of an IDE.
On my local machine, I run the script with a cmd-line parameter 'deploy', which triggers the remote execution. Without such a parameter, the actual code intended for the remote host is run.
import sys
import os
def main():
print os.name
if __name__ == '__main__':
try:
if sys.argv[1] == 'deploy':
import paramiko
# Connect to remote host
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('remote_hostname_or_IP', username='john', password='secret')
# Setup sftp connection and transmit this script
sftp = client.open_sftp()
sftp.put(__file__, '/tmp/myscript.py')
sftp.close()
# Run the transmitted script remotely without args and show its output.
# SSHClient.exec_command() returns the tuple (stdin,stdout,stderr)
stdout = client.exec_command('python /tmp/myscript.py')[1]
for line in stdout:
# Process each line in the remote output
print line
client.close()
sys.exit(0)
except IndexError:
pass
# No cmd-line args provided, run script normally
main()
Exception handling is left out to simplify this example. In projects with multiple script files you will probably have to put all those files (and other dependencies) on the remote host.
If you're using MS Sql Server...
SELECT COUNT(0) AS 'Null_ColumnA_Records',
(
SELECT COUNT(0)
FROM your_table
WHERE ColumnA IS NOT NULL
) AS 'NOT_Null_ColumnA_Records'
FROM your_table
WHERE ColumnA IS NULL;
I don't recomend you doing this... but here you have it (in the same table as result)
You actually don't need to use the attach at all. I had the same problem and it was resolved by removing the attach statement.
Change to another USB port works for me. I tried reset ADB, but problem still there.
In Java 8:
List<WorldLocation> locations = new ArrayList<>();
.getMap(locations.stream().toArray(WorldLocation[]::new));
Try This
;With Tab AS (SELECT DISTINCT Email FROM Products)
SELECT Email,ROW_NUMBER() OVER(ORDER BY Email ASC) AS Id FROM Tab
ORDER BY Email ASC
Problem could occur if you have changed the namespace of your project.
Change the Namespace from Project Properties and also replace all old Namespace with new ones. Renaming to correct namespace might fix the issue.
TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)
The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.
"name":"value"
.Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.
What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name")
, and then create another JProperty of your desire and then add it after this using AddAfterSelf
method. You are done then.
For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm
This is the code I modified.
public class Program
{
public static void Main()
{
try
{
string jsonText = @"
{
""food"": {
""fruit"": {
""apple"": {
""colour"": ""red"",
""size"": ""small""
},
""orange"": {
""colour"": ""orange"",
""size"": ""large""
}
}
}
}";
var foodJsonObj = JObject.Parse(jsonText);
var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");
var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));
Console.WriteLine(foodJsonObj.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
}
}
}
You can verify the key length limit:
int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
System.out.println("MaxAllowedKeyLength=[" + maxKeyLen + "].");
FWIW, I don't see that anyone solved this in quite the same way as I needed to. No complaints at compile time, but I was getting a null view at runtime, and calling things in the proper order. That is, findViewById() after setContentView(). The problem turned out that my view is defined in content_main.xml, but in my activity_main.xml, I lacked this one statement:
<include layout="@layout/content_main" />
When I added that to activity_main.xml, no more NullPointer.
Make sure Virtualization is enabled in your bios.
You can submit the regex to preg_match
which will return false if the regex is not valid. Don't forget to use the @
to suppress error messages:
@preg_match($regexToTest, '');
//
. You get a horizontal straight line because it did not converge.
Better convergence is attained if the first parameter of the fitting (p0) is put as max(y), 5 in the example, instead of 1.
Found a possible workaround that I don't believe was mentioned.
Here is a good description of the problem: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Basically as long as you use forms/url-encoded/plain text content types you are fine.
$.ajax({
type: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'text/plain'
},
dataType: "json",
url: "http://localhost/endpoint",
data: JSON.stringify({'DataToPost': 123}),
success: function (data) {
alert(JSON.stringify(data));
}
});
I use it with ASP.NET WebAPI2. So on the other end:
public static void RegisterWebApi(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}
This way Json formatter gets used when parsing plain text content type.
And don't forget in Web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol>
Hope this helps.
Stub is a function definition that has correct function name, the correct number of parameters and produces dummy result of the correct type.
It helps to write the test and serves as a kind of scaffolding to make it possible to run the examples even before the function design is complete
Blowfish isn't better than MD5 or SHA512, as they serve different purposes. MD5 and SHA512 are hashing algorithms, Blowfish is an encryption algorithm. Two entirely different cryptographic functions.
I think, UNSIGNED
would be the best option to store something like time_duration
(Eg: resolved_call_time = resolved_time(DateTime)-creation_time(DateTime)
) value in minutes or hours or seconds format which will definitely be a non-negative number
Why not just use a FlowDocumentScrollViewer ?
This is all a bit roundabout..
I've used the glyphs like this
</div>
<div class="span2">
<span class="glyphicons thumbs_up"><i class="green"></i></span>
</div>
<div class="span2">
<span class="glyphicons thumbs_down"><i class="red"></i></span>
</div>
and to affect the color, i included a bit of css at the head like this
<style>
i.green:before {
color: green;
}
i.red:before {
color: red;
}
</style>
Voila, green and red thumbs.
Check that way that worked better for me What is .self
if ((self.window.rootViewController?.isKind(of: WebViewController.self))!)
{
//code
}
Setting autoScroll to true did not the trick for me, so I did choose another solution. I built a service that hooks in every time the route changes and that uses the built-in $anchorScroll service to scroll to top. Works for me :-).
Service:
(function() {
"use strict";
angular
.module("mymodule")
.factory("pageSwitch", pageSwitch);
pageSwitch.$inject = ["$rootScope", "$anchorScroll"];
function pageSwitch($rootScope, $anchorScroll) {
var registerListener = _.once(function() {
$rootScope.$on("$locationChangeSuccess", scrollToTop);
});
return {
registerListener: registerListener
};
function scrollToTop() {
$anchorScroll();
}
}
}());
Registration:
angular.module("mymodule").run(["pageSwitch", function (pageSwitch) {
pageSwitch.registerListener();
}]);
I tried all of the above, nothing worked for me. Then I changed tomcat port numbers both HTTP/1.1 and Tomcat admin port and it got solved.
I see other solutions above worked for the people but it is worth to try this one if any of the above doesn't work.
Thanks everyone!
MySQL 4.1 and above has a default character set that it calls utf8
but which is actually only a subset of UTF-8 (allows only three-byte characters and smaller).
Use utf8mb4
as your charset if you want "full" UTF-8.
Either you set LDAP_DOMAIN variable or you misconfigured it. Jump inside of ldap machine/container and run:
slapcat > backup.ldif
If it fails, check punctuation, quotes etc while you assigned variable "LDAP_DOMAIN" Otherwise you will find answer inside on backup.ldif file.
Since it is absolutely positioned you can use top: 50% to vertically align it in the center.
But then you run into the issue of the page being bigger than you want it to be. For that you can use the overflow: hidden for the parent div. This is what I used to create the same effect:
The CSS:
div.parent {
width: 100%;
height: 300px;
position: relative;
overflow: hidden;
}
div.parent div.absolute {
position: absolute;
top: 50%;
height: 300px;
}
The HTML:
<div class="parent">
<div class="absolute">This is vertically center aligned</div>
</div>
Yes, this is confusing...
According to this blog post, it looks like this is an omission from WPF.
To make it work you need to use a style:
<Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
<Border.Style>
<Style>
<Setter Property="Border.Background" Value="Blue"/>
<Style.Triggers>
<Trigger Property="Border.IsMouseOver" Value="True">
<Setter Property="Border.Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
</Border>
I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.
SQL Server(2012) provides another way to generate script for the SQL Server databases with its objects and data. This script can be used to copy the tables’ schema and data from the source database to the destination one in our case.
SQL Scripting method is useful to generate one single script for the tables’ schema and data, including the indexes and keys. But again this method doesn’t generate the tables’ creation script in the correct order if there are relations between the tables.
If anyone is looking for the angular version of this answer then I would suggest creating a directive would be a great idea.
NOTE: ngx-bootstrap is used.
import { Directive, Host, Self, Optional, Input, Renderer2, OnInit, ElementRef } from '@angular/core';
import { CarouselComponent } from 'ngx-bootstrap/carousel';
@Directive({
selector: '[appCarouselSwipe]'
})
export class AppCarouselSwipeDirective implements OnInit {
@Input() swipeThreshold = 50;
private start: number;
private stillMoving: boolean;
private moveListener: Function;
constructor(
@Host() @Self() @Optional() private carousel: CarouselComponent,
private renderer: Renderer2,
private element: ElementRef
) {
}
ngOnInit(): void {
if ('ontouchstart' in document.documentElement) {
this.renderer.listen(this.element.nativeElement, 'touchstart', this.onTouchStart.bind(this));
this.renderer.listen(this.element.nativeElement, 'touchend', this.onTouchEnd.bind(this));
}
}
private onTouchStart(e: TouchEvent): void {
if (e.touches.length === 1) {
this.start = e.touches[0].pageX;
this.stillMoving = true;
this.moveListener = this.renderer.listen(this.element.nativeElement, 'touchmove', this.onTouchMove.bind(this));
}
}
private onTouchMove(e: TouchEvent): void {
if (this.stillMoving) {
const x = e.touches[0].pageX;
const difference = this.start - x;
if (Math.abs(difference) >= this.swipeThreshold) {
this.cancelTouch();
if (difference > 0) {
if (this.carousel.activeSlide < this.carousel.slides.length - 1) {
this.carousel.activeSlide = this.carousel.activeSlide + 1;
}
} else {
if (this.carousel.activeSlide > 0) {
this.carousel.activeSlide = this.carousel.activeSlide - 1;
}
}
}
}
}
private onTouchEnd(e: TouchEvent): void {
this.cancelTouch();
}
private cancelTouch() {
if (this.moveListener) {
this.moveListener();
this.moveListener = undefined;
}
this.start = null;
this.stillMoving = false;
}
}
in html:
<carousel appCarouselSwipe>
...
</carousel>
If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a WeakMap
:
// Note that object must be an object or array,
// NOT a primitive value like string, number, etc.
var objIdMap=new WeakMap, objectCount = 0;
function objectId(object){
if (!objIdMap.has(object)) objIdMap.set(object,++objectCount);
return objIdMap.get(object);
}
var o1={}, o2={}, o3={a:1}, o4={a:1};
console.log( objectId(o1) ) // 1
console.log( objectId(o2) ) // 2
console.log( objectId(o1) ) // 1
console.log( objectId(o3) ) // 3
console.log( objectId(o4) ) // 4
console.log( objectId(o3) ) // 3
Using a WeakMap
instead of Map
ensures that the objects can still be garbage-collected.
You cannot delete everything with either rmdir
or del
alone:
rmdir /s /q
does not accept wildcard params. So rmdir /s /q *
will error.del /s /f /q
will delete all files, but empty subdirectories will remain.My preferred solution (as I have used in many other batch files) is:
rmdir /s /q . 2>NUL
All the solutions suggest you to use the predefined float value through code.
But in case you are wondering how to reference the predefined float value in XML (for example layouts), then following is an example of what I did and it's working perfectly:
Define resource values as type="integer"
but format="float"
, for example:
<item name="windowWeightSum" type="integer" format="float">6.0</item>
<item name="windowNavPaneSum" type="integer" format="float">1.5</item>
<item name="windowContentPaneSum" type="integer" format="float">4.5</item>
And later use them in your layout using @integer/name_of_resource
, for example:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="@integer/windowWeightSum" // float 6.0
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="@integer/windowNavPaneSum" // float 1.5
android:orientation="vertical">
<!-- other views -->
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="@integer/windowContentPaneSum" // float 4.5
android:orientation="vertical">
<!-- other views -->
</LinearLayout>
</LinearLayout>
Here is the complete code for simple example of delegate
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Striped Rows</h2>
<p>The .table-striped class adds zebra-stripes to a table:</p>
<table class="table table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>[email protected]</td>
<td>click</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>[email protected]</td>
<td>click</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>[email protected]</td>
<td>click</td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function(){
$("div").delegate("table tbody tr td:nth-child(4)", "click", function(){
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td:nth-child(2)");
$.each($tds, function() {
console.log($(this).text());
var x = $(this).text();
alert(x);
});
});
});
</script>
</div>
</body>
</html>
Supported Operating Systems:
- Windows 8.1 (x86 and x64)
- Windows 8 (x86 and x64)
- Windows 7 SP1 (x86 and x64)
- Windows Server 2012 R2 (x64)
- Windows Server 2012 (x64)
- Windows Server 2008 R2 SP1 (x64)
Hardware requirements:
- 1.6 GHz or faster processor
- 1 GB of RAM (1.5 GB if running on a virtual machine)
- 20 GB of available hard disk space
- 5400 RPM hard disk drive
- DirectX 9-capable video card that runs at 1024 x 768 or higher display resolution
Additional Requirements for the laptop:
- Internet Explorer 10
- KB2883200 (available through Windows Update) is required
And don't forget to reboot after updating your windows
you can convert to isoformat
my_date = '2020/08/08'
my_date = my_date.replace('/','-') # just to adapte to your question
date_timestamp = datetime.datetime.fromisoformat(my_date).timestamp()
I experienced the same problem in Chrome and I tried unsuccessfully to use BigJump's solution.
I fixed my problem by forcing a hard refresh, as shown in this blog (originally from this SuperUser answer).
Ensure your address bar is using the http scheme and then go through these steps, possibly a couple of times:
It is not on PyPI and you should not be installing it via pip
. If you have matplotlib
installed, you should be able to import mpl_toolkits
directly:
$ pip install --upgrade matplotlib
...
$ python
>>> import mpl_toolkits
>>>
using numpy and list comprehension you can do the
import numpy as np
[num for num in np.arange(1,101) if (num%4 == 1 or num%4 == 2)]
Looks like the secret key isn't on the other machine, so even with the right passphrase (read from a file) it wouldn't work.
These options should work, to
A few useful looking options from man gpg
:
--export
Either export all keys from all keyrings (default keyrings and those registered via option--keyring
), or if at least one name is given, those of the given name. The new keyring is written to STDOUT or to the file given with option--output
. Use together with--armor
to mail those keys.
--export-secret-keys
Same as--export
, but exports the secret keys instead.
--import
--fast-import
Import/merge keys. This adds the given keys to the keyring. The fast version is currently just a synonym.
And maybe
--keyring file
Add file to the current list of keyrings. If file begins with a tilde and a slash, these are replaced by the $HOME directory. If the file- name does not contain a slash, it is assumed to be in the GnuPG home directory ("~/.gnupg" if --homedir or $GNUPGHOME is not used).Note that this adds a keyring to the current list. If the intent is to use the specified keyring alone, use
--keyring
along with--no-default-keyring
.
--secret-keyring file
Same as--keyring
but for the secret keyrings.
String currentString = "Fruit: they taste good";
String[] separated = currentString.split(":");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
You may want to remove the space to the second String:
separated[1] = separated[1].trim();
If you want to split the string with a special character like dot(.) you should use escape character \ before the dot
Example:
String currentString = "Fruit: they taste good.very nice actually";
String[] separated = currentString.split("\\.");
separated[0]; // this will contain "Fruit: they taste good"
separated[1]; // this will contain "very nice actually"
There are other ways to do it. For instance, you can use the StringTokenizer
class (from java.util
):
StringTokenizer tokens = new StringTokenizer(currentString, ":");
String first = tokens.nextToken();// this will contain "Fruit"
String second = tokens.nextToken();// this will contain " they taste good"
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method
Three ways you can do this - from the form designer, select the form, and where you normally see the list of properties, just above it there should be a little lightning symbol - this shows you all the events of the form. Find the form load event in the list, and you should be able to pick ProgramViwer_Load
from the dropdown.
A second way to do it is programmatically - somewhere (constructor maybe) you'd need to add it, something like: ProgramViwer.Load += new EventHandler(ProgramViwer_Load);
A third way using the designer (probably the quickest) - when you create a new form, double click on the middle of it on it in design mode. It'll create a Form load event for you, hook it in, and take you to the event handler code. Then you can just add your two lines and you're good to go!
For those who have mentioned a reconciliation as a potential future for Hudson and Jenkins, with the fact that Jenkins will be joining SPI, it is unlikely at this point they will reconcile.
.headerDivider {
border-left:1px solid #38546d;
border-right:1px solid #16222c;
height:80px;
position:absolute;
right:249px;
top:10px;
}
<div class="headerDivider"></div>
Please, Check this out, I hope it's help
<div class="row">
<iframe class="col-lg-12 col-md-12 col-sm-12" src="http://www.w3schools.com">
</iframe>
</div>
Yes.
KVO requires dynamic dispatch, so you simply need to add the dynamic
modifier to a method, property, subscript, or initializer:
dynamic var foo = 0
The dynamic
modifier ensures that references to the declaration will be dynamically dispatched and accessed through objc_msgSend
.
In addition to the Haack post, Hanselman also has a similar post. BIN Delploying ASP.NET MVC 3 with Razor to a Windows Server without MVC installed
For me, the "Copy Local = true" solution was insufficient because my Website's project references did not include all the dlls that were missing. As Scott mentions in his post, I also needed to get additional dlls from the following folder on my development box: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies. The error message informed me which dll was missing (System.Web.Infrastructure, System.Web.Razor, etc.) I continued to add each missing dll, one by one, until it worked.
Go to c:/wamp/apps/phpadmin3.5.2 Make a new subfolder called ‘upload’ Edit config.inc.php to find and update this line: $cfg[‘UploadDir’] = ‘upload’ Now when you import a database, you will give a drop-down list in web server upload directory with all the files in this directory. Chose the file you want and you are done.
I'm not sure when filtering was added but it's a way to exclude the object blobs if you only want to fetch the history/ref-logs:
git clone --filter=blob:none --no-checkout --single-branch --branch master git://some.repo.git .
git log
When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php
. That is how PHP works with includes.
So, in your example, since you've set a variable called $name
in your front.inc
file, and then included both front.inc
and end.inc
in your index.php
, you will be able to echo
the variable $name
anywhere after the include
of front.inc
within your index.php
. Again, PHP processes your index.php
as if the code from the two files you are including are part of the file.
When you place an echo
within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.
In other words, to do the behavior you're expecting, you will need to define it as a global.
Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link
function of the directive.
There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls
Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.
EDIT: Rather than using $(element)
, you can make use of angular.element(element)
when using AngularJS with jQuery
Take a closer look at the second parameter of json_decode($json, $assoc, $depth)
at https://secure.php.net/json_decode
By default the android sdk installer path is ~/Library/Android/sdk/
Unfortunately there is no hung state for a process. Now hung can be deadlock. This is block state. The threads in the process are blocked. The other things could be live lock where the process is running but doing the same thing again and again. This process is in running state. So as you can see there is no definite hung state. As suggested you can use the top command to see if the process is using 100% CPU or lot of memory.
if your question is "how to bind events on ajax loaded content" you can do like this :
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
// lazy load to DOMNodeInserted event
$(document).bind('DOMNodeInserted', function(e) {
$("img.lazy").lazyload({
effect : "fadeIn",
event: "scrollstop",
skip_invisible : true
}).removeClass('lazy');
});
so you don't need to place your configuration to every you ajax code
Just to clarify, there is a big difference between these two actions, as suggested by Jean-François Corbett.
One action is to copy / load the actual data FROM the Range("A2:A9")
INTO a Variant Array called vArray
(Changed to avoid confusion between Variant Array and Sheet both called Src):
vArray = Sheets("Src").Range("A2:A9").Value
while the other simply sets up a Range variable (SrcRange) with the ADDRESS of the range Sheets("Src").Range("A2:A9")
:
Set SrcRange = Sheets("Src").Range("A2:A9")
In this case, the data is not copied, and remains where it is, but can now be accessed in much the same way as an Array. That is often perfectly adequate, but if you need to repeatedly access, test or calculate with that data, loading it into an Array first will be MUCH faster.
For example, say you want to check a "database" (large sheet) against a list of known Suburbs and Postcodes. Both sets of data are in separate sheets, but if you want it to run fast, load the suburbs and postcodes into an Array (lives in memory), then run through each line of the main database, testing against the array data. This will be much faster than if you access both from their original sheets.
public class JsonParsing {
public static Properties properties = null;
public static JSONObject jsonObject = null;
static {
properties = new Properties();
}
public static void main(String[] args) {
try {
JSONParser jsonParser = new JSONParser();
File file = new File("src/main/java/read.json");
Object object = jsonParser.parse(new FileReader(file));
jsonObject = (JSONObject) object;
parseJson(jsonObject);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void getArray(Object object2) throws ParseException {
JSONArray jsonArr = (JSONArray) object2;
for (int k = 0; k < jsonArr.size(); k++) {
if (jsonArr.get(k) instanceof JSONObject) {
parseJson((JSONObject) jsonArr.get(k));
} else {
System.out.println(jsonArr.get(k));
}
}
}
public static void parseJson(JSONObject jsonObject) throws ParseException {
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
if (jsonObject.get(obj) instanceof JSONArray) {
System.out.println(obj.toString());
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
parseJson((JSONObject) jsonObject.get(obj));
} else {
System.out.println(obj.toString() + "\t"
+ jsonObject.get(obj));
}
}
}
}}
I had renamed a xib and had this problem, the solution for me was to edit the main window.xib manually and change the offending text
search for the offending xib name in the relevant xib ( view as source code)
changed
<viewController nibName="OldNibName" id="116" customClass="SomeViewController">
with
<viewController nibName="NewNibName" id="116" customClass="SomeViewController">
and it worked
Simplest way? It works. :)
Dim queryString As String = "Stor_Proc_Name " & data1 & "," & data2
Try
Using connection As New SqlConnection(ConnStrg)
connection.Open()
Dim command As New SqlCommand(queryString, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim DTResults As New DataTable
DTResults.Load(reader)
MsgBox(DTResults.Rows(0)(0).ToString)
End Using
Catch ex As Exception
MessageBox.Show("Error while executing .. " & ex.Message, "")
Finally
End Try
In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.
So to convert string limit="100"
to a number, you need to do
limit = int(limit) # will return new object (integer) and assign to "limit"
If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:
def int_in_place(mutable):
mutable[0] = int(mutable[0])
mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer
But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).
Seems like only real solutions today revolve around scaling out or sharding. All modern databases (NoSQLs as well as NewSQLs) support horizontal scaling right out of the box, at the database layer, without the need for the application to have sharding code or something.
Unfortunately enough, for the trusted good-old MySQL, sharding is not provided "out of the box". ScaleBase (disclaimer: I work there) is a maker of a complete scale-out solution an "automatic sharding machine" if you like. ScaleBae analyzes your data and SQL stream, splits the data across DB nodes, and aggregates in runtime – so you won’t have to! And it's free download.
Don't get me wrong, NoSQLs are great, they're new, new is more choice and choice is always good!! But choosing NoSQL comes with a price, make sure you can pay it...
You can see here some more data about MySQL, NoSQL...: http://www.scalebase.com/extreme-scalability-with-mongodb-and-mysql-part-1-auto-sharding
Hope that helped.
Assuming you have those values stored in some strings, try this:
function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
pad("3", 3); // => "003"
pad("123", 3); // => "123"
pad("1234", 3); // => "1234"
var test = "MR 2";
var parts = test.split(" ");
parts[1] = pad(parts[1], 3);
parts.join(" "); // => "MR 002"
It's not firing because the value hasn't "changed". It's the same value. Unfortunately, you can't achieve the desired behaviour using the change
event.
You can handle the blur
event and do whatever processing you need when the user leaves the select box. That way you can run the code you need even if the user selects the same value.
$ mail -s "test message from centos" [email protected]
hello from centos linux command line
Ctrl+D to finish
It's kind of pointless to talk about "database performance", "query performance" is a better term here. And the answer is: it depends on the query, data that it operates on, indexes, hardware, etc. You can get an idea of how many rows are going to be scanned and what indexes are going to be used with EXPLAIN syntax.
2GB does not really count as a "large" database - it's more of a medium size.
You can also use
clone()
Method to copy all elements from one hashmap to another hashmap
Program for copy all elements from one hashmap to another
import java.util.HashMap;
public class CloneHashMap {
public static void main(String a[]) {
HashMap hashMap = new HashMap();
HashMap hashMap1 = new HashMap();
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");
System.out.println("Original HashMap : " + hashMap);
hashMap1 = (HashMap) hashMap.clone();
System.out.println("Copied HashMap : " + hashMap1);
}
}
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#content").attr("src","http://vnexpress.net");
})
</script>
</head>
<body>
<iframe id="content"></div>
</body>
</html>
I solved it by using vanilla JavaScript:
<input type="hidden" name="checkboxName" value="0"><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value">
Be careful not to have any spaces or linebreaks between this two input elements!
You can use this.previousSibling.previousSibling
to get "upper" elements.
With PHP you can check the named hidden field for 0 (not set) or 1 (set).
The above solution works perfectly. I prefer to choose Web API option while selecting the project template as shown in the picture below
Note: The solution works with Visual Studio 2013 or higher. The original question was asked in 2012 and it is 2016, therefore adding a solution Visual Studio 2013 or higher.
By checking the source code of glob.glob
you see that it internally calls os.listdir
, described here:
http://docs.python.org/library/os.html?highlight=os.listdir#os.listdir
Key sentence: os.listdir(path) Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.
Arbitrary order. :)
It's ES6 Spread_operator
and Destructuring_assignment
.
<div {...this.props}>
Content Here
</div>
It's equal to Class Component
const person = {
name: "xgqfrms",
age: 23,
country: "China"
};
class TestDemo extends React.Component {
render() {
const {name, age, country} = {...this.props};
// const {name, age, country} = this.props;
return (
<div>
<h3> Person Information: </h3>
<ul>
<li>name={name}</li>
<li>age={age}</li>
<li>country={country}</li>
</ul>
</div>
);
}
}
ReactDOM.render(
<TestDemo {...person}/>
, mountNode
);
or Function component
const props = {
name: "xgqfrms",
age: 23,
country: "China"
};
const Test = (props) => {
return(
<div
name={props.name}
age={props.age}
country={props.country}>
Content Here
<ul>
<li>name={props.name}</li>
<li>age={props.age}</li>
<li>country={props.country}</li>
</ul>
</div>
);
};
ReactDOM.render(
<div>
<Test {...props}/>
<hr/>
<Test
name={props.name}
age={props.age}
country={props.country}
/>
</div>
, mountNode
);
You can access the namespace's dictionary with vars():
>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}
You can modify the dictionary directly if you wish:
>>> d['baz'] = 'store me'
>>> args.baz
'store me'
Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.
You can use map() function:
a = list(map(lambda x: x - 13, a))
Try this
I recently leaned about $wpdb->prepare
HERE and added into our Free Class Booking plugin, plugin approved on wordpress.org and will live soon:
global $wpdb;
$tablename = $wpdb->prefix . "submitted_form";
$name = "Kumkum"; //string value use: %s
$email = "[email protected]"; //string value use: %s
$phone = "3456734567"; //numeric value use: %d
$country = "India"; //string value use: %s
$course = "Database"; //string value use: %s
$message = "hello i want to read db"; //string value use: %s
$now = new DateTime(); //string value use: %s
$datesent = $now->format('Y-m-d H:i:s'); //string value use: %s
$sql = $wpdb->prepare("INSERT INTO `$tablename` (`name`, `email`, `phone`, `country`, `course`, `message`, `datesent`) values (%s, %s, %d, %s, %s, %s, %s)", $name, $email, $phone, $country, $course, $message, $datesent);
$wpdb->query($sql);
Thanks -Frank
ECMASCRIPT 5:
Object.keys(myObj).map(function(x) { return myObj[x]; })
ECMASCRIPT 2015 or ES6:
Object.keys(myObj).map(x => myObj[x])
There is a combination service. You can combine the above listed solutions like mandrill with a service EmailJS, which can make the system more secure. They have not yet started the service though.
Any performance difference would be so small that it wouldn't justify using the approach that's less clear.
First, one case that wasn't mentioned where references are generally superior is const
references. For non-simple types, passing a const reference
avoids creating a temporary and doesn't cause the confusion you're concerned about (because the value isn't modified). Here, forcing a person to pass a pointer causes the very confusion you're worried about, as seeing the address taken and passed to a function might make you think the value changed.
In any event, I basically agree with you. I don't like functions taking references to modify their value when it's not very obvious that this is what the function is doing. I too prefer to use pointers in that case.
When you need to return a value in a complex type, I tend to prefer references. For example:
bool GetFooArray(array &foo); // my preference
bool GetFooArray(array *foo); // alternative
Here, the function name makes it clear that you're getting information back in an array. So there's no confusion.
The main advantages of references are that they always contain a valid value, are cleaner than pointers, and support polymorphism without needing any extra syntax. If none of these advantages apply, there is no reason to prefer a reference over a pointer.
I use PHP's file modified time function, for example:
echo <img src='Images/image.png?" . filemtime('Images/image.png') . "' />";
If you change the image then the new image is used rather than the cached one, due to having a different modified timestamp.
SELECT CAST(CAST('000000000' AS INTEGER) AS VARCHAR)
This has a limit on the length of the string that can be converted to an INT
According to the documentation:
Field.choices
An iterable (e.g., a list or tuple) consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for this field. If this is given, the default form widget will be a select box with these choices instead of the standard text field.
The first element in each tuple is the actual value to be stored, and the second element is the human-readable name.
So, your code is correct, except that you should either define variables JANUARY
, FEBRUARY
etc. or use calendar
module to define MONTH_CHOICES
:
import calendar
...
class MyModel(models.Model):
...
MONTH_CHOICES = [(str(i), calendar.month_name[i]) for i in range(1,13)]
month = models.CharField(max_length=9, choices=MONTH_CHOICES, default='1')
You edit an element's value
by editing it's .value
property.
document.getElementById('DATE').value = 'New Value';
Use the cut
command with -f 2-
(POSIX) or --complement
(not POSIX):
$ echo a b c | cut -f 2- -d ' '
b c
$ echo a b c | cut -f 1 -d ' '
a
$ echo a b c | cut -f 1,2 -d ' '
a b
$ echo a b c | cut -f 1 -d ' ' --complement
b c
Apart from the settings explained in the answer by @DarkNeuron:
"files.encoding": "any encoding"
you can also specify settings for a specific language like so:
"[language id]": {
"files.encoding": "any encoding"
}
For example, I use this when I need to edit PowerShell files previously created with ISE (which are created in ANSI format):
"[powershell]": {
"files.encoding": "windows1252"
}
You can get a list of identifiers of well-known languages here.
It should be in %USERNAME%
. Obviously this can be easily spoofed, so don't rely on it for security.
Useful tip: type set
in a command prompt will list all environment variables.
You can call sortable
on a <tbody>
instead of on the individual rows.
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>?
<script>
$('tbody').sortable();
</script>
$(function() {_x000D_
$( "tbody" ).sortable();_x000D_
});
_x000D_
_x000D_
table {_x000D_
border-spacing: collapse;_x000D_
border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
width: 50px;_x000D_
height: 25px;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
_x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>4</td>_x000D_
</tr>_x000D_
<tr> _x000D_
<td>5</td>_x000D_
<td>6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>7</td>_x000D_
<td>8</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>9</td> _x000D_
<td>10</td>_x000D_
</tr> _x000D_
</tbody> _x000D_
</table>
_x000D_
Use boost::filesystem. It will be incorporated into the next standard anyway so you may as well get used to it.
Above answers all assume that the object in question is an object with behaviour. An advanced strategy in OOP is to separate data objects (that do zip, only have fields) and behaviour objects.
With data objects, it is perfectly fine to omit getters and instead have public fields. They usually don't have setters, since they most commonly are immutable - their fields are set via the constructors, and never again. Have a look at Bob Martin's Clean Code or Pryce and Freeman's Growing OO Software... for details.
forceUpdate();
method will work but it is advisable to use setState();
For some reason other answers are unnecessarily complex, it's easy to do it in one line in pure JavaScript:
Array.prototype.find.call(selectElement.options, o => o.value === optionValue).disabled = true;
or
selectElement.querySelector('option[value="'+optionValue.replace(/["\\]/g, '\\$&')+'"]').disabled = true;
The performance depends on the number of the options (the more the options, the slower the first one) and whether you can omit the escaping (the replace
call) from the second one. Also the first one uses Array.find
and arrow functions that are not available in IE11.
Changing Bundle Identifier worked for me.
If it still doesn't work, try again with these steps before:
cd /Users/my_username/Library/MobileDevice/Provisioning Profiles && rm *
(in my case)Use the TimeSpan object to capture your initial time element and use the methods such as AddHours
or AddMinutes
. To substract 3 hours, you will do AddHours(-3)
. To substract 45 mins, you will do AddMinutes(-45)
I had the same issue. It was damaged the archive file...
Just an another ussage example for Notepad++ (regular expression search mode)
Find: (g|c|u|d)(et|reate|pdate|elete)_(.)([^\s (]+)
Replace: \U\1\E$2\U\3\E$4
Example:
get_user -> GetUser
create_user -> CreateUser
update_user -> UpdateUser
delete_user -> DeleteUser
The DataGrid has an XAML property IsReadOnly
that you can set to true
:
<my:DataGrid
IsReadOnly="True"
/>
Distinguish between static analysis and runtime analysis. Use static analysis for internal stuff, and runtime analysis for the public boundaries of your code.
For things that should not be null:
Runtime check: Use "if (x == null) ..." (zero dependency) or @javax.validation.NotNull (with bean validation) or @lombok.NonNull (plain and simple) or guavas Preconditions.checkNotNull(...)
Static check: Use an @NonNull annotation
This should give the best result: warnings in the IDE, errors by Findbugs and checkerframework, meaningful runtime exceptions.
Do not expect static checks to be mature, their naming is not standardized and different libraries and IDEs treat them differently, ignore them. The JSR305 javax.annotations.* classes look like standard, but they are not, and they cause split packages with Java9+.
Some notes explanations:
Before Java9, this is my recommendation:
// file: package-info.java
@javax.annotation.ParametersAreNonnullByDefault
package example;
// file: PublicApi
package example;
public interface PublicApi {
Person createPerson(
// NonNull by default due to package-info.java above
String firstname,
String lastname);
}
// file: PublicApiImpl
public class PublicApiImpl implements PublicApi {
public Person createPerson(
// In Impl, handle cases where library users still pass null
@Nullable String firstname, // Users might send null
@Nullable String lastname // Users might send null
) {
if (firstname == null) throw new IllagalArgumentException(...);
if (lastname == null) throw new IllagalArgumentException(...);
return doCreatePerson(fistname, lastname, nickname);
}
@NonNull // Spotbugs checks that method cannot return null
private Person doCreatePerson(
String firstname, // Spotbugs checks null cannot be passed, because package has ParametersAreNonnullByDefault
String lastname,
@Nullable String nickname // tell Spotbugs null is ok
) {
return new Person(firstname, lastname, nickname);
}
@CheckForNull // Do not use @Nullable here, Spotbugs will ignore it, though IDEs respect it
private Person getNickname(
String firstname,
String lastname) {
return NICKNAMES.get(firstname + ':' + lastname);
}
}
Note that there is no way to make Spotbugs raise a warning when a nullable method parameter is dereferenced (at the time of writing, version 3.1 of Spotbugs). Maybe checkerframework can do that.
Sadly these annotations do not distinguish between the cases of a public method of a library with arbitrary callsites, and non-public methods where each callsite can be known. So the double meaning of: "Indicate that null is undesired, but prepare for null being passed nevertheless" is not possible in a single declaration, hence the above example has different annotations for the interface and the implementation.
For cases where the split interface approach is not practical, the following approach is a compromise:
public Person createPerson(
@NonNull String firstname,
@NonNull String lastname
) {
// even though parameters annotated as NonNull, library clients might call with null.
if (firstname == null) throw new IllagalArgumentException(...);
if (lastname == null) throw new IllagalArgumentException(...);
return doCreatePerson(fistname, lastname, nickname);
}
This helps clients to not pass null (writing correct code), while returning useful errors if they do.
Changes for Swift 3.0:
NSPipe
has been renamedPipe
NSTask
has been renamedProcess
This is based on inkit's Objective-C answer above. He wrote it as a category on NSString
—
For Swift, it becomes an extension of String
.
extension String {
func runAsCommand() -> String {
let pipe = Pipe()
let task = Process()
task.launchPath = "/bin/sh"
task.arguments = ["-c", String(format:"%@", self)]
task.standardOutput = pipe
let file = pipe.fileHandleForReading
task.launch()
if let result = NSString(data: file.readDataToEndOfFile(), encoding: String.Encoding.utf8.rawValue) {
return result as String
}
else {
return "--- Error running command - Unable to initialize string from file data ---"
}
}
}
let input = "echo hello"
let output = input.runAsCommand()
print(output) // prints "hello"
or just:
print("echo hello".runAsCommand()) // prints "hello"
@IBAction func toggleFinderShowAllFiles(_ sender: AnyObject) {
var newSetting = ""
let readDefaultsCommand = "defaults read com.apple.finder AppleShowAllFiles"
let oldSetting = readDefaultsCommand.runAsCommand()
// Note: the Command results are terminated with a newline character
if (oldSetting == "0\n") { newSetting = "1" }
else { newSetting = "0" }
let writeDefaultsCommand = "defaults write com.apple.finder AppleShowAllFiles \(newSetting) ; killall Finder"
_ = writeDefaultsCommand.runAsCommand()
}
Note the Process
result as read from the Pipe
is an NSString
object. It might be an error string and it can also be an empty string, but it should always be an NSString
.
So, as long as it's not nil, the result can cast as a Swift String
and returned.
If for some reason no NSString
at all can be initialized from the file data, the function returns an error message. The function could have been written to return an optional String?
, but that would be awkward to use and wouldn't serve a useful purpose because it's so unlikely for this to occur.
I see that there is already some great advice and methods suggest for how to get the post back control. However I found another web page (Mahesh blog) with a method to retrieve post back control ID.
I will post it here with a little modification, including making it an extension class. Hopefully it is more useful in that way.
/// <summary>
/// Gets the ID of the post back control.
///
/// See: http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
/// </summary>
/// <param name = "page">The page.</param>
/// <returns></returns>
public static string GetPostBackControlId(this Page page)
{
if (!page.IsPostBack)
return string.Empty;
Control control = null;
// first we will check the "__EVENTTARGET" because if post back made by the controls
// which used "_doPostBack" function also available in Request.Form collection.
string controlName = page.Request.Params["__EVENTTARGET"];
if (!String.IsNullOrEmpty(controlName))
{
control = page.FindControl(controlName);
}
else
{
// if __EVENTTARGET is null, the control is a button type and we need to
// iterate over the form collection to find it
// ReSharper disable TooWideLocalVariableScope
string controlId;
Control foundControl;
// ReSharper restore TooWideLocalVariableScope
foreach (string ctl in page.Request.Form)
{
// handle ImageButton they having an additional "quasi-property"
// in their Id which identifies mouse x and y coordinates
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
controlId = ctl.Substring(0, ctl.Length - 2);
foundControl = page.FindControl(controlId);
}
else
{
foundControl = page.FindControl(ctl);
}
if (!(foundControl is IButtonControl)) continue;
control = foundControl;
break;
}
}
return control == null ? String.Empty : control.ID;
}
Update (2016-07-22): Type check for Button
and ImageButton
changed to look for IButtonControl
to allow postbacks from third party controls to be recognized.
You can simply do it like this with an object literal:
function makeGamePlayer(name,totalScore,gamesPlayed) {
return {
name: name,
totalscore: totalScore,
gamesPlayed: gamesPlayed
};
}
I looked into this before buying a Mac Mini. The answer is, essentially, no. You pretty much have to buy a Leopard Mac to do iPhone SDK development for apps that run on non-jailbroken iPhones.
Not that it's 100% impossible, but it's 99.99% unreasonable. Like changing light bulbs with your feet.
Not only do you have to be in Xcode, but you have to get certificates into the Keychain manager to be able to have Xcode and the iPhone communicate. And you have to set all kinds of setting in Xcode just right.
In MSVC to suppress a particular warning it is enough to specify the it's number to compiler as /wd#. My CMakeLists.txt contains such the block:
If (MSVC)
Set (CMAKE_EXE_LINKER_FLAGS "$ {CMAKE_EXE_LINKER_FLAGS} / NODEFAULTLIB: LIBCMT")
Add_definitions (/W4 /wd4512 /wd4702 /wd4100 /wd4510 /wd4355 /wd4127)
Add_definitions (/D_CRT_SECURE_NO_WARNINGS)
Elseif (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_COMPILER_IS_GNUC)
Add_definitions (-Wall -W -pedantic)
Else ()
Message ("Unknown compiler")
Endif ()
Now I can not say what exactly /wd4512 /wd4702 /wd4100 /wd4510 /wd4355 /wd4127 mean, because I do not pay any attention to MSVC for three years, but they suppress superpedantic warnings that does not influence the result.
ASP.NET 4 was not registered in IIS. Had to run the following command in the command line/run
32bit (x86) Windows
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
64bit (x64) Windows
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
Note from David Murdoch's comment:
That the .net version has changed since this Answer was posted. Check which version of the framework is in the %windir%\Microsoft.NET\Framework64 directory and change the command accordingly before running (it is currently v4.0.30319)
Can add disable like below and can get data on submit. something like this .. DEMO
Html
<input type="hidden" name="email" value="email" />
<input type="text" id="dis" class="disable" value="email" name="email" >
JS
$("#dis").attr('disabled','disabled');
CSS
.disable { opacity : .35; background-color:lightgray; border:1px solid gray;}
You can use Google Page Speed API to achieve your task easily. In my current project, I have used Google Page Speed API`s query written in Python to capture screenshots of any Web URL provided and save it to a location. Have a look.
import urllib2
import json
import base64
import sys
import requests
import os
import errno
# The website's URL as an Input
site = sys.argv[1]
imagePath = sys.argv[2]
# The Google API. Remove "&strategy=mobile" for a desktop screenshot
api = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?screenshot=true&strategy=mobile&url=" + urllib2.quote(site)
# Get the results from Google
try:
site_data = json.load(urllib2.urlopen(api))
except urllib2.URLError:
print "Unable to retreive data"
sys.exit()
try:
screenshot_encoded = site_data['screenshot']['data']
except ValueError:
print "Invalid JSON encountered."
sys.exit()
# Google has a weird way of encoding the Base64 data
screenshot_encoded = screenshot_encoded.replace("_", "/")
screenshot_encoded = screenshot_encoded.replace("-", "+")
# Decode the Base64 data
screenshot_decoded = base64.b64decode(screenshot_encoded)
if not os.path.exists(os.path.dirname(impagepath)):
try:
os.makedirs(os.path.dirname(impagepath))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
# Save the file
with open(imagePath, 'w') as file_:
file_.write(screenshot_decoded)
Unfortunately, following are the drawbacks. If these do not matter, you can proceed with Google Page Speed API. It works well.
There are various Java JSON serializers and deserializers linked from the JSON home page.
As of this writing, there are these 22:
...but of course the list can change.
OpenMP is supported on many platforms (including Visual Studio 2005) and it offers a
int omp_get_num_procs();
function that returns the number of processors/cores available at the time of call.
Use DBNull.Value.Equals on the object without converting it to a string.
Here's an example:
if (! DBNull.Value.Equals(row[fieldName]))
{
//not null
}
else
{
//null
}
breast$class <- as.numeric(as.character(breast$class))
If you have many columns to convert to numeric
indx <- sapply(breast, is.factor)
breast[indx] <- lapply(breast[indx], function(x) as.numeric(as.character(x)))
Another option is to use stringsAsFactors=FALSE
while reading the file using read.table
or read.csv
Just in case, other options to create/change columns
breast[,'class'] <- as.numeric(as.character(breast[,'class']))
or
breast <- transform(breast, class=as.numeric(as.character(breast)))
For those of you with Spanish keyboard on mac this are the shortcuts:
? + ? + [ for un-indent
? + ? + ] for indent
by VB function:
Dim m_RowNr(3) as Variant
'
Function RowNr(ByVal strQName As String, ByVal vUniqValue) As Long
' m_RowNr(3)
' 0 - Nr
' 1 - Query Name
' 2 - last date_time
' 3 - UniqValue
If Not m_RowNr(1) = strQName Then
m_RowNr(0) = 1
m_RowNr(1) = strQName
ElseIf DateDiff("s", m_RowNr(2), Now) > 9 Then
m_RowNr(0) = 1
ElseIf Not m_RowNr(3) = vUniqValue Then
m_RowNr(0) = m_RowNr(0) + 1
End If
m_RowNr(2) = Now
m_RowNr(3) = vUniqValue
RowNr = m_RowNr(0)
End Function
Usage(without sorting option):
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
From table A
Order By A.id
if sorting required or multiple tables join then create intermediate table:
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
INTO table_with_Nr
From table A
Order By A.id
Doing it all in two fell swoops:
char *otherString = strncpy((char*)malloc(6), someString);
otherString[5] = 0;
@Bruno Lavit has a great answer, but if you want you can just access the log and download it as txt file to your workspace from the job's URL:
${BUILD_URL}/consoleText
Then it's only a matter of downloading this page to your ${Workspace}
Invoke ANT
" and use the GET targetGood luck!
Edit:
The actual log file on the file system is not on the slave, but kept in the Master machine. You can find it under: $JENKINS_HOME/jobs/$JOB_NAME/builds/lastSuccessfulBuild/log
If you're looking for another build just replace lastSuccessfulBuild
with the build you're looking for.
For Mac OSX I had to do
tar -zcv --exclude='folder' -f theOutputTarFile.tar folderToTar
Note the -f
after the --exclude=
Have a look at this excellent article at CSS-Tricks:
Taken from the article:
The final unit of measurement that it is possible to declare font sizes in is point values (pt). Point values are only for print CSS! A point is a unit of measurement used for real-life ink-on-paper typography. 72pts = one inch. One inch = one real-life inch like-on-a-ruler. Not an inch on a screen, which is totally arbitrary based on resolution.
Just like how pixels are dead-accurate on monitors for font-sizing, point sizes are dead-accurate on paper. For the best cross-browser and cross-platform results while printing pages, set up a print stylesheet and size all fonts with point sizes.
For good measure, the reason we don't use point sizes for screen display (other than it being absurd), is that the cross-browser results are drastically different:
If you need fine-grained control, sizing fonts in pixel values (px) is an excellent choice (it's my favorite). On a computer screen, it doesn't get any more accurate than a single pixel. With sizing fonts in pixels, you are literally telling browsers to render the letters exactly that number of pixels in height:
Windows, Mac, aliased, anti-aliased, cross-browsers, doesn't matter, a font set at 14px will be 14px tall. But that isn't to say there won't still be some variation. In a quick test below, the results were slightly more consistent than with keywords but not identical:
Due to the nature of pixel values, they do not cascade. If a parent element has an 18px pixel size and the child is 16px, the child will be 16px. However, font-sizing settings can be using in combination. For example, if the parent was set to 16px and the child was set to larger, the child would indeed come out larger than the parent. A quick test showed me this:
"Larger" bumped the 16px of the parent into 20px, a 25% increase.
Pixels have gotten a bad wrap in the past for accessibility and usability concerns. In IE 6 and below, font-sizes set in pixels cannot be resized by the user. That means that us hip young healthy designers can set type in 12px and read it on the screen just fine, but when folks a little longer in the tooth go to bump up the size so they can read it, they are unable to. This is really IE 6's fault, not ours, but we gots what we gots and we have to deal with it.
Setting font-size in pixels is the most accurate (and I find the most satisfying) method, but do take into consideration the number of visitors still using IE 6 on your site and their accessibility needs. We are right on the bleeding edge of not needing to care about this anymore.
nohup some_command > /dev/null 2>&1&
That's all you need to do!
urls.py:
#...
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),
views.py:
from django.shortcuts import redirect
from .models import Element
def element_info(request):
# ...
element = Element.object.get(pk=1)
return redirect('element_update', pk=element.id)
def element_update(request, pk)
# ...
The mktemp(1)
man page explains it fairly well:
Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win. A safer, though still inferior, approach is to make a temporary directory using the same naming scheme. While this does allow one to guarantee that a temporary file will not be subverted, it still allows a simple denial of service attack. For these reasons it is suggested that mktemp be used instead.
In a script, I invoke mktemp something like
mydir=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")
which creates a temporary directory I can work in, and in which I can safely name the actual files something readable and useful.
mktemp
is not standard, but it does exist on many platforms. The "X"s will generally get converted into some randomness, and more will probably be more random; however, some systems (busybox ash, for one) limit this randomness more significantly than others
By the way, safe creation of temporary files is important for more than just shell scripting. That's why python has tempfile, perl has File::Temp, ruby has Tempfile, etc…
If you are only interested in the direct parent, and not other ancestors, you can just use parent()
, and give it the selector, as in target.parent('div#hello')
.
Example: http://jsfiddle.net/6BX9n/
function fun(evt) {
var target = $(evt.target);
if (target.parent('div#hello').length) {
alert('Your clicked element is having div#hello as parent');
}
}
Or if you want to check to see if there are any ancestors that match, then use .parents()
.
Example: http://jsfiddle.net/6BX9n/1/
function fun(evt) {
var target = $(evt.target);
if (target.parents('div#hello').length) {
alert('Your clicked element is having div#hello as parent');
}
}
Look closely at URI's for ordinary web resources. Those are your template. Think of directory trees; use simple Linux-like file and directory names.
HelloWorld
isn't a really good class of resources. It doesn't appear to be a "thing". It might be, but it isn't very noun-like. A greeting
is a thing.
user-id
might be a noun that you're fetching. It's doubtful, however, that the result of your request is only a user_id. It's much more likely that the result of the request is a User. Therefore, user
is the noun you're fetching
www.example.com/greeting/user/x/
Makes sense to me. Focus on making your REST request a kind of noun phrase -- a path through a hierarchy (or taxonomy, or directory). Use the simplest nouns possible, avoiding noun phrases if possible.
Generally, compound noun phrases usually mean another step in your hierarchy. So you don't have /hello-world/user/
and /hello-universe/user/
. You have /hello/world/user/
and hello/universe/user/
. Or possibly /world/hello/user/
and /universe/hello/user/
.
The point is to provide a navigation path among resources.
If you are making the boolean column as not null then the default 'default' value is false; you don't have to explicitly specify it.
A user agent style sheet is a ”default style sheet” provided by the browser (e.g., Chrome, Firefox, Edge, etc.) in order to present the page in a way that satisfies ”general presentation expectations.” For example, a default style sheet would provide base styles for things like font size, borders, and spacing between elements. It is common to employ a reset style sheet to deal with inconsistencies amongst browsers.
From the specification...
A user agent's default style sheet should present the elements of the document language in ways that satisfy general presentation expectations for the document language. ~ The Cascade.
For more information about user agents in general, see user agent.
Here is how to do it if you are using a SimpleCursorAdapter
(where columnName
is the name of the db column that you used to populate your spinner
):
private int getIndex(Spinner spinner, String columnName, String searchString) {
//Log.d(LOG_TAG, "getIndex(" + searchString + ")");
if (searchString == null || spinner.getCount() == 0) {
return -1; // Not found
}
else {
Cursor cursor = (Cursor)spinner.getItemAtPosition(0);
int initialCursorPos = cursor.getPosition(); // Remember for later
int index = -1; // Not found
for (int i = 0; i < spinner.getCount(); i++) {
cursor.moveToPosition(i);
String itemText = cursor.getString(cursor.getColumnIndex(columnName));
if (itemText.equals(searchString)) {
index = i; // Found!
break;
}
}
cursor.moveToPosition(initialCursorPos); // Leave cursor as we found it.
return index;
}
}
Also (a refinement of Akhil's answer) this is the corresponding way to do it if you are filling your Spinner from an array:
private int getIndex(Spinner spinner, String searchString) {
if (searchString == null || spinner.getCount() == 0) {
return -1; // Not found
}
else {
for (int i = 0; i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).toString().equals(searchString)) {
return i; // Found!
}
}
return -1; // Not found
}
};
r+
is the canonical mode for reading and writing at the same time. This is not different from using the fopen()
system call since file()
/ open()
is just a tiny wrapper around this operating system call.
Unless you are writing very small files, you should probably use templates.
Example:
- name: copy upstart script
template:
src: myCompany-service.conf.j2
dest: "/etc/init/myCompany-service.conf"
Sorry, misunderstood your question.
According to Javascript - capturing onsubmit when calling form.submit():
I was recently asked: "Why doesn't the form.onsubmit event get fired when I submit my form using javascript?"
The answer: Current browsers do not adhere to this part of the html specification. The event only fires when it is activated by a user - and does not fire when activated by code.
(emphasis added).
Note: "activated by a user" also includes hitting submit buttons (probably including default submit behaviour from the enter key but I haven't tried this). Nor, I believe, does it get triggered if you (with code) click a submit button.
It is documented in jQuery API Documentation. Check for Internet Explorer with $.browser.msie
and then check its version with $.browser.version
.
UPDATE: $.browser removed in jQuery 1.9
The jQuery.browser() method has been deprecated since jQuery 1.3 and is removed in 1.9. If needed, it is available as part of the jQuery Migrate plugin. We recommend using feature detection with a library such as Modernizr.
Install package : Microsoft.AspNet.WebApi.Cors
go to : App_Start --> WebApiConfig
Add :
var cors = new EnableCorsAttribute("http://localhost:4200", "", ""); config.EnableCors(cors);
Note : If you add '/' as end of the particular url not worked for me.
s = "BINGO"
print(s.replace("", " ")[1: -1])
Timings below
$ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]'
1000000 loops, best of 3: 0.584 usec per loop
$ python -m timeit -s's = "BINGO"' '" ".join(s)'
100000 loops, best of 3: 1.54 usec per loop
Yes each consumer can receive the same messages. have a look at http://www.rabbitmq.com/tutorials/tutorial-three-python.html http://www.rabbitmq.com/tutorials/tutorial-four-python.html http://www.rabbitmq.com/tutorials/tutorial-five-python.html
for different ways to route messages. I know they are for python and java but its good to understand the principles, decide what you are doing and then find how to do it in JS. Its sounds like you want to do a simple fanout (tutorial 3), which sends the messages to all queues connected to the exchange.
The difference with what you are doing and what you want to do is basically that you are going to set up and exchange or type fanout. Fanout excahnges send all messages to all connected queues. Each queue will have a consumer that will have access to all the messages separately.
Yes this is commonly done, it is one of the features of AMPQ.
You can style li
elements differently based on their class
, their id
or their ancestor elements:
li { /* styles all li elements*/
list-style-type: none;
}
#ParentListID li { /* styles the li elements that have an ancestor element
of id="ParentListID" */
list-style-type: bullet;
}
li.className { /* styles li elements of class="className" */
list-style-type: bullet;
}
Or, to use the ancestor elements:
#navigationContainerID li { /* specifically styles the li elements with an ancestor of
id="navigationContainerID" */
list-style-type: none;
}
li { /* then styles all other li elements that don't have that ancestor element */
list-style-type: bullet;
}
You can use filter like this
angular.module('app').filter('trustAs', ['$sce',
function($sce) {
return function (input, type) {
if (typeof input === "string") {
return $sce.trustAs(type || 'html', input);
}
console.log("trustAs filter. Error. input isn't a string");
return "";
};
}
]);
usage
<div ng-bind-html="myData | trustAs"></div>
it can be used for other resource types, for example source link for iframes and other types declared here
contentType: 'application/json; charset=utf-8'
Is not good. At least it doesnt work for me. The other syntax is ok. The parameter you supply is in the right format.
Try Emacs. It has good support for indentation needed in Python. Please check this link http://python.about.com/b/2007/09/24/emacs-tips-for-python-programmers.htm
The solution presented in this answer works, but it could become problematic with memory if the sample size is small, but the population is huge (e.g. random.sample(insanelyLargeNumber, 10)
).
To fix that, I would go with this:
answer = set()
sampleSize = 10
answerSize = 0
while answerSize < sampleSize:
r = random.randint(0,100)
if r not in answer:
answerSize += 1
answer.add(r)
# answer now contains 10 unique, random integers from 0.. 100
You can try CustomScrollView
. Put your CustomScrollView inside Column Widget.
Just for example -
class App extends StatelessWidget {
App({Key key}): super(key: key);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: const Text('AppBar'),
),
body: new Container(
constraints: BoxConstraints.expand(),
decoration: new BoxDecoration(
image: new DecorationImage(
alignment: Alignment.topLeft,
image: new AssetImage('images/main-bg.png'),
fit: BoxFit.cover,
)
),
child: new Column(
children: <Widget>[
Expanded(
child: new CustomScrollView(
scrollDirection: Axis.vertical,
shrinkWrap: false,
slivers: <Widget>[
new SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 0.0),
sliver: new SliverList(
delegate: new SliverChildBuilderDelegate(
(context, index) => new YourRowWidget(),
childCount: 5,
),
),
),
],
),
),
],
)),
);
}
}
In above code I am displaying a list of items ( total 5) in CustomScrollView.
YourRowWidget
widget gets rendered 5 times as list item. Generally you should render each row based on some data.
You can remove decoration property of Container widget, it is just for providing background image.
I use it for two reasons:
I can force a refresh of the icon by adding a query parameter for example ?v=2
. like this:
<link rel="icon" href="/favicon.ico?v=2" type="image/x-icon" />
In case I need to specify the path.
I think Tim said it quite well, but let's step back:
A DOM element is an object, a thing in memory. Like most objects in OOP, it has properties. It also, separately, has a map of the attributes defined on the element (usually coming from the markup that the browser read to create the element). Some of the element's properties get their initial values from attributes with the same or similar names (value
gets its initial value from the "value" attribute; href
gets its initial value from the "href" attribute, but it's not exactly the same value; className
from the "class" attribute). Other properties get their initial values in other ways: For instance, the parentNode
property gets its value based on what its parent element is; an element always has a style
property, whether it has a "style" attribute or not.
Let's consider this anchor in a page at http://example.com/testing.html
:
<a href='foo.html' class='test one' name='fooAnchor' id='fooAnchor'>Hi</a>
Some gratuitous ASCII art (and leaving out a lot of stuff):
+-------------------------------------------+ | HTMLAnchorElement | +-------------------------------------------+ | href: "http://example.com/foo.html" | | name: "fooAnchor" | | id: "fooAnchor" | | className: "test one" | | attributes: | | href: "foo.html" | | name: "fooAnchor" | | id: "fooAnchor" | | class: "test one" | +-------------------------------------------+
Note that the properties and attributes are distinct.
Now, although they are distinct, because all of this evolved rather than being designed from the ground up, a number of properties write back to the attribute they derived from if you set them. But not all do, and as you can see from href
above, the mapping is not always a straight "pass the value on", sometimes there's interpretation involved.
When I talk about properties being properties of an object, I'm not speaking in the abstract. Here's some non-jQuery code:
var link = document.getElementById('fooAnchor');
alert(link.href); // alerts "http://example.com/foo.html"
alert(link.getAttribute("href")); // alerts "foo.html"
(Those values are as per most browsers; there's some variation.)
The link
object is a real thing, and you can see there's a real distinction between accessing a property on it, and accessing an attribute.
As Tim said, the vast majority of the time, we want to be working with properties. Partially that's because their values (even their names) tend to be more consistent across browsers. We mostly only want to work with attributes when there is no property related to it (custom attributes), or when we know that for that particular attribute, the attribute and the property are not 1:1 (as with href
and "href" above).
The standard properties are laid out in the various DOM specs:
These specs have excellent indexes and I recommend keeping links to them handy; I use them all the time.
Custom attributes would include, for instance, any data-xyz
attributes you might put on elements to provide meta-data to your code (now that that's valid as of HTML5, as long as you stick to the data-
prefix). (Recent versions of jQuery give you access to data-xyz
elements via the data
function, but that function is not just an accessor for data-xyz
attributes [it does both more and less than that]; unless you actually need its features, I'd use the attr
function to interact with data-xyz
attribute.)
The attr
function used to have some convoluted logic around getting what they thought you wanted, rather than literally getting the attribute. It conflated the concepts. Moving to prop
and attr
was meant to de-conflate them. Briefly in v1.6.0 jQuery went too far in that regard, but functionality was quickly added back to attr
to handle the common situations where people use attr
when technically they should use prop
.
In at least in ubuntu 16.10, the default python3
is python3.5
. As such, all of the python3-X
packages will be installed for python3.5 and not for python3.6.
You can verify this by checking the shebang of pip3
:
$ head -n1 $(which pip3)
#!/usr/bin/python3
Fortunately, the pip installed by the python3-pip
package is installed into the "shared" /usr/lib/python3/dist-packages
such that python3.6 can also take advantage of it.
You can install packages for python3.6 by doing:
python3.6 -m pip install ...
For example:
$ python3.6 -m pip install requests
$ python3.6 -c 'import requests; print(requests.__file__)'
/usr/local/lib/python3.6/dist-packages/requests/__init__.py
Alternatively, you could go with pgrep
or Process Grep. (Busybox is needed)
You could do a adb shell pgrep com.example.app
and it would display just the process Id.
As a suggestion, since Android is Linux, you can use most basic Linux commands with adb shell
to navigate/control around. :D
you can run your past mysql with run /PATH_PAST_MYSQL/bin/mysqld.exe
it run your last mysql and you can see it in phpmyadmin and other section of your system.
notice: stop your current mysql version.
S F My English.
Here is a work around for inner bordered rect
using symbol
and use
.
Example: https://jsbin.com/yopemiwame/edit?html,output
SVG:
<svg>
<symbol id="inner-border-rect">
<rect class="inner-border" width="100%" height="100%" style="fill:rgb(0,255,255);stroke-width:10;stroke:rgb(0,0,0)">
</symbol>
...
<use xlink:href="#inner-border-rect" x="?" y="?" width="?" height="?">
</svg>
Note: Make sure to replace the ?
in use
with real values.
Background: The reason why this works is because symbol establishes a new viewport by replacing symbol
with svg
and creating an element in the shadow DOM. This svg
of the shadow DOM is then linked into your current SVG
element. Note that svg
s can be nested and every svg
creates a new viewport, which clips everything that overlaps, including the overlapping border. For a much more detailed overview of whats going on read this fantastic article by Sara Soueidan.
You should remove the references to it by assigning null or leaving the block where it was declared. After that, it will be automatically deleted by the garbage collector (not immediately, but eventually).
Example 1:
Object a = new Object();
a = null; // after this, if there is no reference to the object,
// it will be deleted by the garbage collector
Example 2:
if (something) {
Object o = new Object();
} // as you leave the block, the reference is deleted.
// Later on, the garbage collector will delete the object itself.
Not something that you are currently looking for, but FYI: you can invoke the garbage collector with the call System.gc()
To summarize, it sounds like these are them:
var blocks = [
[0x3400, 0x4DB5],
[0x4E00, 0x62FF],
[0x6300, 0x77FF],
[0x7800, 0x8CFF],
[0x8D00, 0x9FCC],
[0x2e80, 0x2fd5],
[0x3190, 0x319f],
[0x3400, 0x4DBF],
[0x4E00, 0x9FCC],
[0xF900, 0xFAAD],
[0x20000, 0x215FF],
[0x21600, 0x230FF],
[0x23100, 0x245FF],
[0x24600, 0x260FF],
[0x26100, 0x275FF],
[0x27600, 0x290FF],
[0x29100, 0x2A6DF],
[0x2A700, 0x2B734],
[0x2B740, 0x2B81D]
]
I wrote with parameters that are predefined
They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:
Alter Procedure [Test]
@StartDate AS varchar(6) = NULL,
@EndDate AS varchar(6) = NULL
AS
...
NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.
Now you can call it without passing any arguments e.g.
exec dbo.TEST
By using ''.join
list1 = ['1', '2', '3']
str1 = ''.join(list1)
Or if the list is of integers, convert the elements before joining them.
list1 = [1, 2, 3]
str1 = ''.join(str(e) for e in list1)
I guess problem is in width attributes in table and td remove 'px' for example
<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">
Should be
<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">
Windows 7 has the arp command within it. arp -a should show you the static and dynamic type interfaces connected to your system.
I was going through some details related to tuple
and list
, and what I understood is:
Heterogeneous
collection data typeSo for appending new item to a tuple, need to cast it to list
, and do append()
operation on it, then again cast it back to tuple.
But personally what I felt about the Question is, if Tuples are supposed to be finite, fixed length items and if we are using those data types in our application logics then there should not be a scenario to appending new items OR updating an item value in it. So instead of list of tuples it should be list of list itself, Am I right on this?
You are ready to do with php zip lib, and can use zend zip lib too,
<?PHP
// create object
$zip = new ZipArchive();
// open archive
if ($zip->open('app-0.09.zip') !== TRUE) {
die ("Could not open archive");
}
// get number of files in archive
$numFiles = $zip->numFiles;
// iterate over file list
// print details of each file
for ($x=0; $x<$numFiles; $x++) {
$file = $zip->statIndex($x);
printf("%s (%d bytes)", $file['name'], $file['size']);
print "
";
}
// close archive
$zip->close();
?>
http://devzone.zend.com/985/dynamically-creating-compressed-zip-archives-with-php/
and there is also php pear lib for this http://www.php.net/manual/en/class.ziparchive.php
With the latest versions of mock, you can use the really useful mock_open helper:
mock_open(mock=None, read_data=None)
A helper function to create a mock to replace the use of open. It works for open called directly or used as a context manager.
The mock argument is the mock object to configure. If None (the default) then a MagicMock will be created for you, with the API limited to methods or attributes available on standard file handles.
read_data is a string for the read method of the file handle to return. This is an empty string by default.
>>> from mock import mock_open, patch
>>> m = mock_open()
>>> with patch('{}.open'.format(__name__), m, create=True):
... with open('foo', 'w') as h:
... h.write('some stuff')
>>> m.assert_called_once_with('foo', 'w')
>>> handle = m()
>>> handle.write.assert_called_once_with('some stuff')
"The complexity should be O(nLog n)... for each item we "heapify", it has the potential to have to filter down once for each level for the heap so far (which is log n levels)."
Not quite. Your logic does not produce a tight bound -- it over estimates the complexity of each heapify. If built from the bottom up, insertion (heapify) can be much less than O(log(n))
. The process is as follows:
( Step 1 ) The first n/2
elements go on the bottom row of the heap. h=0
, so heapify is not needed.
( Step 2 ) The next n/22
elements go on the row 1 up from the bottom. h=1
, heapify filters 1 level down.
( Step i )
The next n/2i
elements go in row i
up from the bottom. h=i
, heapify filters i
levels down.
( Step log(n) ) The last n/2log2(n) = 1
element goes in row log(n)
up from the bottom. h=log(n)
, heapify filters log(n)
levels down.
NOTICE: that after step one, 1/2
of the elements (n/2)
are already in the heap, and we didn't even need to call heapify once. Also, notice that only a single element, the root, actually incurs the full log(n)
complexity.
The Total steps N
to build a heap of size n
, can be written out mathematically.
At height i
, we've shown (above) that there will be n/2i+1
elements that need to call heapify, and we know heapify at height i
is O(i)
. This gives:
The solution to the last summation can be found by taking the derivative of both sides of the well known geometric series equation:
Finally, plugging in x = 1/2
into the above equation yields 2
. Plugging this into the first equation gives:
Thus, the total number of steps is of size O(n)
Not a simple way, no.
Let's say that by "active" you mean "hasn't passed the maximum lifetime" and hasn't been explicitly destroyed and that you're using the default session handler.
If you really need this, you must implement some sort of custom session handler. See session_set_save_handler
.
Take also in consideration that you'll have no feedback if the user just closes the browser or moves away from your site without explciitly logging out. Depending on much inactivity you consider the threshold to deem a session "inactive", the number of false positives you'll get may be very high.
There are already many ways specified above but one of my favourite is missing..
GO
IF OBJECT_ID('nView', 'V') IS NOT NULL
DROP VIEW nView;
GO
WHERE nView
is the name of view
UPDATE 2017-03-25: as @hanesjw suggested to drop a Store Procedure use P
instead of V
as the second argument of OBJECT_ID
GO
IF OBJECT_ID( 'nProcedure', 'P' ) IS NOT NULL
DROP PROCEDURE dbo.sprocName;
GO
I use sbt assembly to package my project. I also meet this problem. My solution is here. Step1: add META-INF mergestrategy in your build.sbt
case PathList("META-INF", "MANIFEST.MF") => MergeStrategy.discard
case PathList("META-INF", ps @ _*) => MergeStrategy.first
Step2: add hadoop-hdfs lib to build.sbt
"org.apache.hadoop" % "hadoop-hdfs" % "2.4.0"
Step3: sbt clean; sbt assembly
Hope the above information can help you.
if (navigator.geolocation) { //Checks if browser supports geolocation
navigator.geolocation.getCurrentPosition(function (position) {
var latitude = position.coords.latitude; //users current
var longitude = position.coords.longitude; //location
var coords = new google.maps.LatLng(latitude, longitude); //Creates variable for map coordinates
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = //Sets map options
{
zoom: 15, //Sets zoom level (0-21)
center: coords, //zoom in on users location
mapTypeControl: true, //allows you to select map type eg. map or satellite
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL //sets map controls size eg. zoom
},
mapTypeId: google.maps.MapTypeId.ROADMAP //sets type of map Options:ROADMAP, SATELLITE, HYBRID, TERRIAN
};
map = new google.maps.Map( /*creates Map variable*/ document.getElementById("map"), mapOptions /*Creates a new map using the passed optional parameters in the mapOptions parameter.*/);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
var request = {
origin: coords,
destination: 'BT42 1FL',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
});
}
To get the column names from pandas dataframe in python3- Here I am creating a data frame from a fileName.csv file
>>> import pandas as pd
>>> df = pd.read_csv('fileName.csv')
>>> columnNames = list(df.head(0))
>>> print(columnNames)
The other answers will give you a good idea how to accomplish what you have asked for....
However
There are not many cases where this is a good idea. It is usually better to store only the filename in the database and the file on the file system.
That way your database is much smaller, can be transported around easier and more importantly is quicker to backup / restore.
To answer your direct question, it is:
Range("A1").NumberFormat = "@"
Or
Cells(1,1).NumberFormat = "@"
However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.
-- My default settings (this is basically a single-session machine, so work_mem is pretty high)
SET effective_cache_size='2048MB';
SET work_mem='16MB';
\echo original
EXPLAIN ANALYZE
SELECT
COUNT (distinct val) as aantal
FROM one
;
\echo group by+count(*)
EXPLAIN ANALYZE
SELECT
distinct val
-- , COUNT(*)
FROM one
GROUP BY val;
\echo with CTE
EXPLAIN ANALYZE
WITH agg AS (
SELECT distinct val
FROM one
GROUP BY val
)
SELECT COUNT (*) as aantal
FROM agg
;
Results:
original QUERY PLAN
----------------------------------------------------------------------------------------------------------------------
Aggregate (cost=36448.06..36448.07 rows=1 width=4) (actual time=1766.472..1766.472 rows=1 loops=1)
-> Seq Scan on one (cost=0.00..32698.45 rows=1499845 width=4) (actual time=31.371..185.914 rows=1499845 loops=1)
Total runtime: 1766.642 ms
(3 rows)
group by+count(*)
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------
HashAggregate (cost=36464.31..36477.31 rows=1300 width=4) (actual time=412.470..412.598 rows=1300 loops=1)
-> HashAggregate (cost=36448.06..36461.06 rows=1300 width=4) (actual time=412.066..412.203 rows=1300 loops=1)
-> Seq Scan on one (cost=0.00..32698.45 rows=1499845 width=4) (actual time=26.134..166.846 rows=1499845 loops=1)
Total runtime: 412.686 ms
(4 rows)
with CTE
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------
Aggregate (cost=36506.56..36506.57 rows=1 width=0) (actual time=408.239..408.239 rows=1 loops=1)
CTE agg
-> HashAggregate (cost=36464.31..36477.31 rows=1300 width=4) (actual time=407.704..407.847 rows=1300 loops=1)
-> HashAggregate (cost=36448.06..36461.06 rows=1300 width=4) (actual time=407.320..407.467 rows=1300 loops=1)
-> Seq Scan on one (cost=0.00..32698.45 rows=1499845 width=4) (actual time=24.321..165.256 rows=1499845 loops=1)
-> CTE Scan on agg (cost=0.00..26.00 rows=1300 width=0) (actual time=407.707..408.154 rows=1300 loops=1)
Total runtime: 408.300 ms
(7 rows)
The same plan as for the CTE could probably also be produced by other methods (window functions)
string
does not name a type. The class in the string
header is called std::string
.
Please do not put using namespace std
in a header file, it pollutes the global namespace for all users of that header. See also "Why is 'using namespace std;' considered a bad practice in C++?"
Your class should look like this:
#include <string>
class Game
{
private:
std::string white;
std::string black;
std::string title;
public:
Game(std::istream&, std::ostream&);
void display(colour, short);
};
To accomplish this in all browsers you need to use a combination of @energee, @Richard and @Feuermurmel methods.
<a href="" style="display: block; z-index: 1;">
<object data="" style="z-index: -1; pointer-events: none;" />
</a>
Adding:
pointer-events: none;
makes it work in Firefox.display: block;
gets it working in Chrome, and Safari.z-index: 1; z-index: -1;
makes it work in IE as well.The set of paths where the compiler looks for the header files can be checked by the command:-
cpp -v
If you declare #include "" , the compiler first searches in current directory of source file and if not found, continues to search in the above retrieved directories.
If you declare #include <> , the compiler searches directly in those directories obtained from the above command.
Source:- http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art026
If someone looks for this…
I wanted to rsync only specific files and folders and managed to do it with this command: rsync --include-from=rsync-files
With rsync-files:
my-dir/
my-file.txt
- /*
Ensure you have set the name for your ComboBox in your XAML file:
<ComboBox Height="23" Name="comboBox" />
In your code you can access selected item using SelectedItem
property:
MessageBox.Show(comboBox.SelectedItem.ToString());
I had the same problem, but I had my activity declared in the Manifest file, with the correct name.
My problem was that I didn't have to imported a third party libraries in a "libs" folder, and I needed reference them in my proyect (Right-click, properties, Java Build Path, Libraries, Add Jar...).
because, a static members are not part of any specific class and that main method, not requires to create its Object, but can still refer to all other classes.
You can use ajax upload to preview your selected file.. http://zurb.com/playground/ajax-upload
You can use length
:
if($("#one").length) { // 0 == false; >0 == true
alert('yes');
}
All you need is a reluctant quantifier:
regex: /aa.*?aa/
aabbabcaabda => aabbabcaa
aaaaaabda => aaaa
aabbabcaabda => aabbabcaa
aababaaaabdaa => aababaa, aabdaa
You could use negative lookahead, too, but in this case it's just a more verbose way accomplish the same thing. Also, it's a little trickier than gpojd made it out to be. The lookahead has to be applied at each position before the dot is allowed to consume the next character.
/aa(?:(?!aa).)*aa/
As for the approach suggested by Claudiu and finnw, it'll work okay when the sentinel string is only two characters long, but (as Claudiu acknowledged) it's too unwieldy for longer strings.
How about String.format("%.2f", i2)
?
Big O is the upper bound, while Omega is the lower bound. Theta requires both Big O and Omega, so that's why it's referred to as a tight bound (it must be both the upper and lower bound).
For example, an algorithm taking Omega(n log n)
takes at least n log n
time, but has no upper limit. An algorithm taking Theta(n log n)
is far preferential since it takes at least n log n
(Omega n log n) and no more than n log n
(Big O n log n).
Off topic, this can be done using the grep also, just posting it here in case if anyone is looking for grep solution
echo 'xxx yyy zzze ' | grep -oE 'yyy'
Swift 5.0 + , Simple and Short
example:
Style 1
func methodName(completionBlock: () -> Void) {
print("block_Completion")
completionBlock()
}
Style 2
func methodName(completionBlock: () -> ()) {
print("block_Completion")
completionBlock()
}
Use:
override func viewDidLoad() {
super.viewDidLoad()
methodName {
print("Doing something after Block_Completion!!")
}
}
Output
block_Completion
Doing something after Block_Completion!!
print_r($this->session->userdata);
or
print_r($this->session->all_userdata());
It started to work for me only when I checked all the spaces.
So, it didn't work like this: width: calc(100%- 20px)
or calc(100%-20px)
and perfectly worked with width: calc(100% - 20px)
.
If you want a one-liner:
{**dictionary1, **{'level1':{**dictionary1['level1'], **{'level2':{**dictionary1['level1']['level2'], **{'levelB':10}}}}}}
Assuming the following method to test:
public boolean doSomething(SomeClass arg);
Mockito documentation says that you should not use captor in this way:
when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));
Because you can just use matcher during stubbing:
when(someObject.doSomething(eq(expected))).thenReturn(true);
But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor
and this is the case for which it is designed:
ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));
On the Mac, I found the keystore file path, password, key alias and key password in an earlier log report before I updated Android Studio.
I launched the Console utility and scrolled down to ~/Library/Logs -> AndroidStudioBeta ->idea.log.1 (or any old log number)
Then I searched for “android.injected.signing.store” and found this from an earlier date:
-Pandroid.injected.signing.store.file=/Users/myuserid/AndroidStudioProjects/keystore/keystore.jks,
-Pandroid.injected.signing.store.password=mystorepassword,
-Pandroid.injected.signing.key.alias=myandroidkey,
-Pandroid.injected.signing.key.password=mykeypassword,
On Windows
you can find your lost key password in below path
Project\.gradle\2.14.1\taskArtifacts\taskArtifacts.bin
or ..taskHistory\taskHistory.bin
open the file using appropriate tools e.g. NotePad++ and search with the part of the password that you remember. You will find it definitely. Else, try searching with this string "signingConfig.storePassword".
Note: I have experienced the same and i am able to find it. In case if you didn't find may be you cleared all the cache and temp files.
Read all file content. Make a replacement with String.Replace
. Write content back to file.
string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);
I have a similar problem specifucally : ERR! enoent ENOENT: no such file or directory, chmod 'node_modules/npm/node_modules/request/node_modules/http-signature/node_modules/sshpk/bin/sshpk-conv I tried all above solutions but no luck. I was using vagrant box, and the project was in a shared folder. The problems seems to be only there, when I move the project to another not shared folder (woth host), voila! problem solved. Just in case another person was using also vagrant
Add this to onCreate
// Getting application context
Context context = getActivity();
It used to be generally recommended best practice1 to use pass by const ref for all types, except for builtin types (char
, int
, double
, etc.), for iterators and for function objects (lambdas, classes deriving from std::*_function
).
This was especially true before the existence of move semantics. The reason is simple: if you passed by value, a copy of the object had to be made and, except for very small objects, this is always more expensive than passing a reference.
With C++11, we have gained move semantics. In a nutshell, move semantics permit that, in some cases, an object can be passed “by value” without copying it. In particular, this is the case when the object that you are passing is an rvalue.
In itself, moving an object is still at least as expensive as passing by reference. However, in many cases a function will internally copy an object anyway — i.e. it will take ownership of the argument.2
In these situations we have the following (simplified) trade-off:
“Pass by value” still causes the object to be copied, unless the object is an rvalue. In the case of an rvalue, the object can be moved instead, so that the second case is suddenly no longer “copy, then move” but “move, then (potentially) move again”.
For large objects that implement proper move constructors (such as vectors, strings …), the second case is then vastly more efficient than the first. Therefore, it is recommended to use pass by value if the function takes ownership of the argument, and if the object type supports efficient moving.
A historical note:
In fact, any modern compiler should be able to figure out when passing by value is expensive, and implicitly convert the call to use a const ref if possible.
In theory. In practice, compilers can’t always change this without breaking the function’s binary interface. In some special cases (when the function is inlined) the copy will actually be elided if the compiler can figure out that the original object won’t be changed through the actions in the function.
But in general the compiler can’t determine this, and the advent of move semantics in C++ has made this optimisation much less relevant.
1 E.g. in Scott Meyers, Effective C++.
2 This is especially often true for object constructors, which may take arguments and store them internally to be part of the constructed object’s state.
Run below commands from app's home directory:
rake db:migrate:down VERSION="20140311142212"
(here version is the timestamp prepended by rails when migration was created. This action will revert DB changes due to this migration)
Run "rails destroy migration migration_name"
(migration_name is the one use chose while creating migration. Remove "timestamp_" from your migration file name to get it)
this will work
String myName="domanokz";
String p=myName.replace(myName.charAt(4),'x');
System.out.println(p);
Output : domaxokz
Try this:
$('[id$=lblVessel]').text("NewText");
The id$=
will match the elements that end with that text, which is how ASP.NET auto-generates IDs. You can make it safer using span[id=$=lblVessel]
but usually this isn't necessary.
You have to use GROUP BY
so you will have multiple records returned,
SELECT COUNT(*) TotalCount,
b.category_id,
b.category_name
FROM table1 a
INNER JOIN table2 b
ON a.category_id = b.category_id
WHERE a.colour <> 'red'
GROUP BY b.category_id, b.category_name
Use the DATEDIFF()
function.
Example from documentation:
SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');
-> 1
If it's a huuge array and it would take too much memory to serialize it to a string before writing, you can use streams:
var fs = require('fs');
var file = fs.createWriteStream('array.txt');
file.on('error', function(err) { /* error handling */ });
arr.forEach(function(v) { file.write(v.join(', ') + '\n'); });
file.end();
Are you missing a using directive for System.Linq
?
You can also use the same syntax for an array. For example, searching within a Pandas series:
ser = pd.Series(['some', 'strings', 'to', 'query'])
if item in ser.values:
# do stuff
DECLARE @dt1 datetime='2012/06/13 08:11:12', @dt2 datetime='2012/06/12 02:11:12'
SELECT CAST((@dt2-@dt1) as time(0))
Try this:
<script>
window.onbeforeunload = function(e) {
return 'Dialog text here.';
};
</script>
more info here MDN.
<VirtualHost *:80>
DocumentRoot /var/www/app1
ServerName app1.example.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/example
ServerName example.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/wildcard
ServerName other.example.com
ServerAlias *.example.com
</VirtualHost>
Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.
The SQL is somewhat like the syntax of MS SQL.
SELECT * FROM [table$] WHERE *;
It is important that the table name is ended with a $ sign and the whole thing is put into brackets. As conditions you can use any value, but so far Excel didn't allow me to use what I call "SQL Apostrophes" (´), so a column title in one word is recommended.
If you have users listed in a table called "Users", and the id is in a column titled "id" and the name in a column titled "Name", your query will look like this:
SELECT Name FROM [Users$] WHERE id = 1;
Hope this helps.
For the purpose of completeness, I thought the answers to this question required an update. "My guess is that using do.call("rbind", ...)
is going to be the fastest approach that you will find..." It was probably true for May 2010 and some time after, but in about Sep 2011 a new function rbindlist
was introduced in the data.table
package version 1.8.2, with a remark that "This does the same as do.call("rbind",l)
, but much faster". How much faster?
library(rbenchmark)
benchmark(
do.call = do.call("rbind", listOfDataFrames),
plyr_rbind.fill = plyr::rbind.fill(listOfDataFrames),
plyr_ldply = plyr::ldply(listOfDataFrames, data.frame),
data.table_rbindlist = as.data.frame(data.table::rbindlist(listOfDataFrames)),
replications = 100, order = "relative",
columns=c('test','replications', 'elapsed','relative')
)
test replications elapsed relative
4 data.table_rbindlist 100 0.11 1.000
1 do.call 100 9.39 85.364
2 plyr_rbind.fill 100 12.08 109.818
3 plyr_ldply 100 15.14 137.636
startInfo.Arguments = "/c \"netsh http add sslcert ipport=127.0.0.1:8085 certhash=0000000000003ed9cd0c315bbb6dc1c08da5e6 appid={00112233-4455-6677-8899-AABBCCDDEEFF} clientcertnegotiation=enable\"";
and...
startInfo.Arguments = "/c \"makecert -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer\"";
The /c
tells cmd to quit once the command has completed. Everything after /c
is the command you want to run (within cmd
), including all of the arguments.