You really need to keep two issues apart:
1) the primary key is a logical construct - one of the candidate keys that uniquely and reliably identifies every row in your table. This can be anything, really - an INT, a GUID, a string - pick what makes most sense for your scenario.
2) the clustering key (the column or columns that define the "clustered index" on the table) - this is a physical storage-related thing, and here, a small, stable, ever-increasing data type is your best pick - INT or BIGINT as your default option.
By default, the primary key on a SQL Server table is also used as the clustering key - but that doesn't need to be that way!
One rule of thumb I would apply is this: any "regular" table (one that you use to store data in, that is a lookup table etc.) should have a clustering key. There's really no point not to have a clustering key. Actually, contrary to common believe, having a clustering key actually speeds up all the common operations - even inserts and deletes (since the table organization is different and usually better than with a heap - a table without a clustering key).
Kimberly Tripp, the Queen of Indexing has a great many excellent articles on the topic of why to have a clustering key, and what kind of columns to best use as your clustering key. Since you only get one per table, it's of utmost importance to pick the right clustering key - and not just any clustering key.
Marc
This statement works for me
ALTER TABLE table_name DROP UNIQUE (column_name);
Clustered Index - A clustered index defines the order in which data is physically stored in a table. Table data can be sorted in only way, therefore, there can be only one clustered index per table. In SQL Server, the primary key constraint automatically creates a clustered index on that particular column.
Non-Clustered Index - A non-clustered index doesn’t sort the physical data inside the table. In fact, a non-clustered index is stored at one place and table data is stored in another place. This is similar to a textbook where the book content is located in one place and the index is located in another. This allows for more than one non-clustered index per table.It is important to mention here that inside the table the data will be sorted by a clustered index. However, inside the non-clustered index data is stored in the specified order. The index contains column values on which the index is created and the address of the record that the column value belongs to.When a query is issued against a column on which the index is created, the database will first go to the index and look for the address of the corresponding row in the table. It will then go to that row address and fetch other column values. It is due to this additional step that non-clustered indexes are slower than clustered indexes
Differences between clustered and Non-clustered index
For more information refer to this article.
A clustered index is essentially a sorted copy of the data in the indexed columns.
The main advantage of a clustered index is that when your query (seek) locates the data in the index then no additional IO is needed to retrieve that data.
The overhead of maintaining a clustered index, especially in a frequently updated table, can lead to poor performance and for that reason it may be preferable to create a non-clustered index.
As per my understanding data structure is any data residing in memory of any electronic system that can be efficiently managed. Many times it is a game of memory or faster accessibility of data. In terms of memory again, there are tradeoffs done with the management of data based on cost to the company of that end product. Efficiently managed tells us how best the data can be accessed based on the primary requirement of the end product. This is a very high level explanation but data structures is a vast subjects. Most of the interviewers dive into data structures that they can afford to discuss in the interviews depending on the time they have, which are linked lists and related subjects.
Now, these data types can be divided into primitive, abstract, composite, based on the way they are logically constructed and accessed.
I hope this helps you dive in.
Make sure the process (account) that the site is running under has privileges to write to the output directory.
In IIS 7 and above this is configured on the application pool and is normally the AppPool Identity, which will not normally have permission to write to all directories.
Check your event logs (application and security) to see if any exceptions were thrown.
A quick trick to use for me is using the find duplicates query SQL and changing 1 to 0 in Having expression. Like this:
SELECT COUNT([UniqueField]) AS DistinctCNT FROM
(
SELECT First([FieldName]) AS [UniqueField]
FROM TableName
GROUP BY [FieldName]
HAVING (((Count([FieldName]))>0))
);
Hope this helps, not the best way I am sure, and Access should have had this built in.
We can add the following to a particular tag in CSS:
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
In case of half rotation change 90
to 45
.
Use pax.
Pax is a deprecated package but does the job perfectly and in a simple fashion.
pax -w > mydir.tar mydir
Code 1:
dict = { key: key * 10 for key in range(0, 100) }
d1 = {}
for key, value in dict.items():
if key % 2 == 0:
d1[key] = value
Code 2:
dict = { key: key * 10 for key in range(0, 100) }
d2 = {key: value for key, value in dict.items() if key % 2 == 0}
Code 3:
dict = { key: key * 10 for key in range(0, 100) }
d3 = { key: dict[key] for key in dict.keys() if key % 2 == 0}
All pieced of code performance are measured with timeit using number=1000, and collected 1000 times for each piece of code.
For python 3.6 the performance of three ways of filter dict keys almost the same. For python 2.7 code 3 is slightly faster.
Sub Check_DT_ForNull()
Debug.Print WS_FE.ListObjects.Item(1).DataBodyRange.Item(1).Value
If Not WS_FE.ListObjects.Item(1).DataBodyRange.Item(1).Value = "" Then
Debug.Print WS_FE.ListObjects.Item(1).DataBodyRange.Rows.Count
End If
End Sub
This checks the first row value in the DataBodyRange for Null and Count the total rows This worked for me as I downloaded my datatable from server It had not data's but table was created with blanks and Rows.Count was not 0 but blank rows.
The conflict message:
CONFLICT (delete/modify): res/layout/dialog_item.xml deleted in dialog and modified in HEAD
means that res/layout/dialog_item.xml
was deleted in the 'dialog' branch you are merging, but was modified in HEAD (in the branch you are merging to).
So you have to decide whether
git rm res/layout/dialog_item.xml
"or
git add res/layout/dialog_item.xml
"Then you finalize merge with "git commit
".
Note that git will warn you that you are creating a merge commit, in the (rare) case where it is something you don't want. Probably remains from the days where said case was less rare.
You could overlay one element above the blurred element like so
div {
position: absolute;
left:0;
top: 0;
}
p {
position: absolute;
left:0;
top: 0;
}
you can use the custom datetime by using...
create table noteTable3
(created_at DATETIME DEFAULT (STRFTIME('%d-%m-%Y %H:%M', 'NOW','localtime')),
title text not null, myNotes text not null);
use 'NOW','localtime' to get the current system date else it will show some past or other time in your Database after insertion time in your db.
Thanks You...
Here is a simple filter pipe for array of objects that contain attributes with string values (ES6)
filter-array-pipe.js
import {Pipe} from 'angular2/core';
// # Filter Array of Objects
@Pipe({ name: 'filter' })
export class FilterArrayPipe {
transform(value, args) {
if (!args[0]) {
return value;
} else if (value) {
return value.filter(item => {
for (let key in item) {
if ((typeof item[key] === 'string' || item[key] instanceof String) &&
(item[key].indexOf(args[0]) !== -1)) {
return true;
}
}
});
}
}
}
Your component
myobjComponent.js
import {Component} from 'angular2/core';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {FilterArrayPipe} from 'filter-array-pipe';
@Component({
templateUrl: 'myobj.list.html',
providers: [HTTP_PROVIDERS],
pipes: [FilterArrayPipe]
})
export class MyObjList {
static get parameters() {
return [[Http]];
}
constructor(_http) {
_http.get('/api/myobj')
.map(res => res.json())
.subscribe(
data => this.myobjs = data,
err => this.logError(err))
);
}
resetQuery(){
this.query = '';
}
}
In your template
myobj.list.html
<input type="text" [(ngModel)]="query" placeholder="... filter" >
<div (click)="resetQuery()"> <span class="icon-cross"></span> </div>
</div>
<ul><li *ngFor="#myobj of myobjs| filter:query">...<li></ul>
If you happens to change the columns and stumbled on
'Doctrine\DBAL\Driver\PDOMySql\Driver' not found
then just install
composer require doctrine/dbal
$query= "INSERT INTO table ( " . implode(', ',array_keys($insData)) . ") VALUES (" . implode(', ',array_values($insData)) . ")";
Only need to write this line to insert an array into a database.
implode(', ',array_keys($insData))
: Gives you all keys as string format
implode(', ',array_values($insData))
: Gives you all values as string format
Code:
/**
* sort keys like in key list
* filter: remove keys are not listed in keyList
* ['c'=>'red', 'd'=>'2016-12-29'] = sortAndFilterKeys(['d'=>'2016-12-29', 'c'=>'red', 'a'=>3 ]], ['c', 'd', 'z']){
*
* @param array $inputArray
* @param string[]|int[] $keyList
* @param bool $removeUnknownKeys
* @return array
*/
static public function sortAndFilterKeys($inputArray, $keyList, $removeUnknownKeys=true){
$keysAsKeys = array_flip($keyList);
$result = array_replace($keysAsKeys, $inputArray); // result = sorted keys + values from input +
$result = array_intersect_key($result, $inputArray); // remove keys are not existing in inputArray
if( $removeUnknownKeys ){
$result = array_intersect_key($result, $keysAsKeys); // remove keys are not existing in keyList
}
return $result;
}
And in clean javascript:
var texts = [], lis = document.getElementsByTagName("li");
for(var i=0, im=lis.length; im>i; i++)
texts.push(lis[i].firstChild.nodeValue);
alert(texts);
TLDR: You cannot reliably convert that date-only value, send a string instead...
...or at least that is how almost all of these answers should start off.
There is a number of conversion issues that are happening here.
This Is a Date Without Time
Something everybody seems to be missing is how many trailing zeros there are in the question - it is almost certainly started out as a date without time:
/Date(1224043200000)/
When executing this from a javascript console as a new Date (the basis of many answers)
new Date(1224043200000)
You get:
The original asker was probably in EST and had a pure date (sql) or a DateTime (not DateTimeOffset) with midnight.
In other words, the intention here is that the time portion is meaningless. However, if the browser executes this in the same timezone as the server that generated it it doesn't matter and most of the answers work.
Bit By Timezone
But, if you execute the code above on a machine with a different timezone (PST for example):
You'll note that we are now a day behind in this other timezone. This will not be fixed by changing the serializer (which will still include timezone in the iso format)
The Problem
Date (sql) and DateTime (.net) do not have timezone on them, but as soon as you convert them to something that does (javascript inferred thru json in this case), the default action in .net is to assume the current timezone.
The number that the serialization is creating is milliseconds since unix epoch or:
(DateTimeOffset.Parse("10/15/2008 00:00:00Z") - DateTimeOffset.Parse("1/1/1970 00:00:00Z")).TotalMilliseconds;
Which is something that new Date() in javascript takes as a parameter. Epoch is from UTC, so now you've got timezone info in there whether you wanted it or not.
Possible solutions:
It might be safer to create a string property on your serialized object that represents the date ONLY - a string with "10/15/2008" is not likely to confuse anybody else with this mess. Though even there you have to be careful on the parsing side: https://stackoverflow.com/a/31732581
However, in the spirit of providing an answer to the question asked, as is:
function adjustToLocalMidnight(serverMidnight){
var serverOffset=-240; //injected from model? <-- DateTimeOffset.Now.Offset.TotalMinutes
var localOffset=-(new Date()).getTimezoneOffset();
return new Date(date.getTime() + (serverOffset-localOffset) * 60 * 1000)
}
var localMidnightDate = adjustToLocalMidnight(new Date(parseInt(jsonDate.substr(6))));
package com.example.helloandroid;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
public class HelloAndroid2Activity extends Activity {
/** Called when the activity is first created. */
DrawView drawView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
paint.setColor(Color.BLUE);
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(10, 20, 30, 40, paint);
canvas.drawLine(20, 10, 50, 20, paint);
}
}
}
Looking for EventHandling, ActionListener?
or code?
JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
textfield.setText("");
//textfield.setText(null); //or use this
}
});
Also See
How to Use Buttons
As many have stated, relying on the moving target of the user agent data is problematic. The same can be said for counting on screen size.
My approach is borrowed from a CSS technique to determine if the interface is touch:
Using only javascript (support by all modern browsers), a media query match can easily infer whether the device is mobile.
function isMobile() {
var match = window.matchMedia || window.msMatchMedia;
if(match) {
var mq = match("(pointer:coarse)");
return mq.matches;
}
return false;
}
I think it's important to note here that onBlur() fires regardless.
This is a helpful thread but the only thing it doesn't clarify is that onBlur() will fire every single time.
onChange() will only fire when the value is changed.
http://www.velocityreviews.com/forums/t123353-configuration-error.html
If you want to use inetpub/wwwroot/aspnet as your application, remove this line :
Line 26: and any other lines which define MachineToApplication beyond application level
If you want to use d:\inetpub\wwwroot\aspnet\begin\chapter02\ as your application, create an IIS Application which points to d:\inetpub\wwwroot\aspnet\begin\chapter02\
maybe you can refer link above. For my application, my web.config store in d:\inetpub\wwwroot\aspnet\begin\chapter02\ and when i move the web.config to d:\inetpub\wwwroot\aspnet and the problem is solve. Please check also does your application have two web.config file.
I have written Python bindings for libssh2. Libssh2 is a client-side library implementing the SSH2 protocol.
import socket
import libssh2
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('exmaple.com', 22))
session = libssh2.Session()
session.startup(sock)
session.userauth_password('john', '******')
channel = session.channel()
channel.execute('ls -l')
print channel.read(1024)
(As of 2018, I would advise trying out JupyterHub/JupyterLab. It uses the full width of the monitor. If this is not an option, maybe since you are using one of the cloud-based Jupyter-as-a-service providers, keep reading)
(Stylish is accused of stealing user data, I have moved on to using Stylus plugin instead)
I recommend using Stylish Browser Plugin. This way you can override css for all notebooks, without adding any code to notebooks. We don't like to change configuration in .ipython/profile_default, since we are running a shared Jupyter server for the whole team and width is a user preference.
I made a style specifically for vertically-oriented high-res screens, that makes cells wider and adds a bit of empty-space in the bottom, so you can position the last cell in the centre of the screen. https://userstyles.org/styles/131230/jupyter-wide You can, of course, modify my css to your liking, if you have a different layout, or you don't want extra empty-space in the end.
Last but not least, Stylish is a great tool to have in your toolset, since you can easily customise other sites/tools to your liking (e.g. Jira, Podio, Slack, etc.)
@media (min-width: 1140px) {
.container {
width: 1130px;
}
}
.end_space {
height: 800px;
}
Error
Cannot redirect after HTTP headers have been sent.
System.Web.HttpException (0x80004005): Cannot redirect after HTTP headers have been sent.
Suggestion
If we use asp.net mvc and working on same controller and redirect to different Action then you do not need to write..
Response.Redirect("ActionName","ControllerName");
its better to use only
return RedirectToAction("ActionName");
or
return View("ViewName");
Run it like this on the command line:
java -jar /path/to/your/jar/jarFile.jar
It could be done purely by CSS
using vh
:
#page {
display:block;
width:100%;
height:95vh !important;
overflow:hidden;
}
#tdcontent {
float:left;
width:100%;
display:block;
}
#content {
float:left;
width:100%;
height:100%;
display:block;
overflow:scroll;
}
and the HTML
<div id="page">
<div id="tdcontent"></div>
<div id="content"></div>
</div>
I checked it, It works in all major browsers: Chrome
, IE
, and FireFox
In responsive.less, you can comment out the line that imports responsive-1200px-min.less.
// Large desktops
@import "responsive-1200px-min.less";
Like so:
// Large desktops
// @import "responsive-1200px-min.less";
Dim text As String = "123.45"
Dim value As Double
If Double.TryParse(text, value) Then
' text is convertible to Double, and value contains the Double value now
Else
' Cannot convert text to Double
End If
There isn't any built-in way to handle this (although actionpack might have a helper for that). I would advise something like this
def to_boolean(s)
s and !!s.match(/^(true|t|yes|y|1)$/i)
end
# or (as Pavling pointed out)
def to_boolean(s)
!!(s =~ /^(true|t|yes|y|1)$/i)
end
What works as well is to use 0 and non-0 instead of false/true literals:
def to_boolean(s)
!s.to_i.zero?
end
You can commit in the current branch, checkout to another branch, and finally cherry-pick that commit (in lieu of merge).
Bootstrap sometimes uses contextual class constructs. Those are what you should target to change styling.
You don't need to create your own custom class as suggested in the answer from Kiran Varti.
So you only need:
CSS:
.panel-default > .panel-heading {
background: #black;
}
HTML:
<div class="panel panel-default">
Explanation here. Also see contextual class section here.
To match navbar-inverse use #222. Panel-inverse was requested in V3, but rejected due to larger priorities.
You can change the foreground color in that heading override or you can do it separately for panel titles. Depends what you are trying to achieve.
.panel-title {
color: white;
}
You can set values from html like this. I don't think there is a direct solution from angular yet.
<div style="visibility: hidden;">{{activeTitle='home'}}</div>
Yes, Google Custom Search has now replaced the old Search API, but you can still use Google Custom Search to search the entire web, although the steps are not obvious from the Custom Search setup.
To create a Google Custom Search engine that searches the entire web:
Now your custom search engine will search the entire web.
Pricing
Source: https://developers.google.com/custom-search/json-api/v1/overview#Pricing
(2019) I used $('#'+id).removeAttr().off('click').on('click', function(){...});
I tried $('#'+id).off().on(...)
, but it wouldn't work to reset the onClick attribute every time it was called to be reset.
I use .on('click',function(){...});
to stay away from having to quote block all my javascript functions.
The O.P. could now use:
$(this).removeAttr('onclick').off('click').on('click', function(){
displayCalendar(document.prjectFrm[ia + 'dtSubDate'],'yyyy-mm-dd', this);
});
Where this came through for me is when my div was set with the onClick attribute set statically:
<div onclick = '...'>
Otherwise, if I only had a dynamically attached a listener to it, I would have used the $('#'+id).off().on('click', function(){...});
.
Without the off('click') my onClick listeners were being appended not replaced.
D:\projects\Phonegap\Example> cordova plugin rm org.apache.cordova.console --save
add the --save
so that it removes the plugin from the config.xml
file.
To generate a release build for Android, we first need to make a small change to the AndroidManifest.xml
file found in platforms/android. Edit the file and change the line:
<application android:debuggable="true" android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name">
and change android:debuggable
to false
:
<application android:debuggable="false" android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name">
As of cordova 6.2.0 remove the android:debuggable tag completely. Here is the explanation from cordova:
Explanation for issues of type "HardcodedDebugMode": It's best to leave out the android:debuggable attribute from the manifest. If you do, then the tools will automatically insert android:debuggable=true when building an APK to debug on an emulator or device. And when you perform a release build, such as Exporting APK, it will automatically set it to false.
If on the other hand you specify a specific value in the manifest file, then the tools will always use it. This can lead to accidentally publishing your app with debug information.
Now we can tell cordova to generate our release build:
D:\projects\Phonegap\Example> cordova build --release android
Then, we can find our unsigned APK file in platforms/android/ant-build
. In our example, the file was platforms/android/ant-build/Example-release-unsigned.apk
Note : We have our keystore keystoreNAME-mobileapps.keystore
in this Git Repo, if you want to create another, please proceed with the following steps.
keytool -genkey -v -keystore <keystoreName>.keystore -alias <Keystore AliasName> -keyalg <Key algorithm> -keysize <Key size> -validity <Key Validity in Days>
keytool -genkey -v -keystore NAME-mobileapps.keystore -alias NAMEmobileapps -keyalg RSA -keysize 2048 -validity 10000
keystore password? : xxxxxxx
What is your first and last name? : xxxxxx
What is the name of your organizational unit? : xxxxxxxx
What is the name of your organization? : xxxxxxxxx
What is the name of your City or Locality? : xxxxxxx
What is the name of your State or Province? : xxxxx
What is the two-letter country code for this unit? : xxx
Then the Key store has been generated with name as NAME-mobileapps.keystore
Place the generated keystore in
old version cordova
D:\projects\Phonegap\Example\platforms\android\ant-build
New version cordova
D:\projects\Phonegap\Example\platforms\android\build\outputs\apk
To sign the unsigned APK, run the jarsigner tool which is also included in the JDK:
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <keystorename> <Unsigned APK file> <Keystore Alias name>
D:\projects\Phonegap\Example\platforms\android\ant-build> jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore NAME-mobileapps.keystore Example-release-unsigned.apk xxxxxmobileapps
OR
D:\projects\Phonegap\Example\platforms\android\build\outputs\apk> jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore NAME-mobileapps.keystore Example-release-unsigned.apk xxxxxmobileapps
Enter KeyPhrase as 'xxxxxxxx'
This signs the apk in place.
Finally, we need to run the zip align tool to optimize the APK:
D:\projects\Phonegap\Example\platforms\android\ant-build> zipalign -v 4 Example-release-unsigned.apk Example.apk
OR
D:\projects\Phonegap\Example\platforms\android\ant-build> C:\Phonegap\adt-bundle-windows-x86_64-20140624\sdk\build-tools\android-4.4W\zipalign -v 4 Example-release-unsigned.apk Example.apk
OR
D:\projects\Phonegap\Example\platforms\android\build\outputs\apk> C:\Phonegap\adt-bundle-windows-x86_64-20140624\sdk\build-tools\android-4.4W\zipalign -v 4 Example-release-unsigned.apk Example.apk
Now we have our final release binary called example.apk and we can release this on the Google Play Store.
location / {
is the most general location (with location {
). It will match anything, AFAIU. I doubt that it would be useful to have location / { index index.html; }
because of a lot of duplicate content for every subdirectory of your site.
The approach with
try_files $uri $uri/index.html index.html;
is bad, as mentioned in a comment above, because it returns index.html
for pages which should not exist on your site (any possible $uri
will end up in that).
Also, as mentioned in an answer above, there is an internal redirect in the last argument of try_files
.
Your approach
location = / { index index.html;
is also bad, since index
makes an internal redirect too. In case you want that, you should be able to handle that in a specific location
. Create e.g.
location = /index.html {
as was proposed here. But then you will have a working link http://example.org/index.html
, which may be not desired. Another variant, which I use, is:
root /www/my-root;
# http://example.org
# = means exact location
location = / {
try_files /index.html =404;
}
# disable http://example.org/index as a duplicate content
location = /index { return 404; }
# This is a general location.
# (e.g. http://example.org/contacts <- contacts.html)
location / {
# use fastcgi or whatever you need here
# return 404 if doesn't exist
try_files $uri.html =404;
}
P.S. It's extremely easy to debug nginx (if your binary allows that). Just add into the server {
block:
error_log /var/log/nginx/debug.log debug;
and see there all internal redirects etc.
[(UITableViewCell *)[(UITableView *)self cellForRowAtIndexPath:nowIndex]
will give you uitableviewcell. But I am not sure what exactly you are asking for! Because you have this code and still you asking how to get uitableviewcell. Some more information will help to answer you :)
ADD: Here is an alternate syntax that achieves the same thing without the cast.
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:nowIndex];
Try passing width=200
as additional paramater when creating the Label.
This should work in creating label with specified width.
If you want to change it later, you can use:
label.config(width=200)
As you want to change the size of font itself you can try:
label.config(font=("Courier", 44))
How does the server know that it should pull image.png from the /pictures folder when you visit the website and browse to the /system/files/images folder in your web browser? A so-called symbolic link is the guy that is responsible for this behavior. Somewhere in your system, there is a symlink that tells your server "If a visitor requests /system/files/images/image.png then show him /pictures/image.png."
And what is the role of the FollowSymLinks setting in this?
FollowSymLinks relates to server security. When dealing with web servers, you can't just leave things undefined. You have to tell who has access to what. The FollowSymLinks setting tells your server whether it should or should not follow symlinks. In other words, if FollowSymLinks was disabled in our case, browsing to the /system/files/images/image.png file would return depending on other settings either the 403 (access forbidden) or 404 (not found) error.
XML version for @Asher Aslan cool effect.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<gradient
android:angle="180"
android:startColor="#00000000"
android:centerColor="#FFFF0000"
android:endColor="#00000000"/>
</shape>
Name for that shape as: list_driver.xml under drawable folder
<ListView
android:id="@+id/category_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="@drawable/list_driver"
android:dividerHeight="5sp" />
if you run from cmd on windows check the path System Variable value must have inside C:\Program Files\Git\bin or the path of you git installation on cmd type set to see the variables
For firefox links appear to be "special". The only way I was able to get this working was to use the createEvent described here on MDN and call the initMouseEvent function. Even that didn't work completely, I had to manually tell the browser to open a link...
var theEvent = document.createEvent("MouseEvent");
theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
var element = document.getElementById('link');
element.dispatchEvent(theEvent);
while (element)
{
if (element.tagName == "A" && element.href != "")
{
if (element.target == "_blank") { window.open(element.href, element.target); }
else { document.location = element.href; }
element = null;
}
else
{
element = element.parentElement;
}
}
If you are converting a varchar to int make sure you do not have decimal places.
For example, if you are converting a varchar field with value (12345.0) to an integer then you get this conversion error. In my case I had all my fields with .0 as ending so I used the following statement to globally fix the problem.
CONVERT(int, replace(FIELD_NAME,'.0',''))
inputString.splitlines()
Will give you a list with each item, the splitlines()
method is designed to split each line into a list element.
It's a placeholder in the string.
For example,
string b = "world.";
Console.WriteLine("Hello {0}", b);
would produce this output:
Hello world.
Also, you can have as many placeholders as you wish. This also works on String.Format
:
string b = "world.";
string a = String.Format("Hello {0}", b);
Console.WriteLine(a);
And you would still get the very same output.
Try this way:
<div class="container">
<div class="col-md-4" style="padding-left: 0px; padding-right: 0px;">
<img src="images/food1.jpg" class="img-responsive">
</div>
</div>
UPDATE:
In Bootstrap 4 img-responsive
becomes img-fluid
, so the solution using Bootstrap 4 is:
<div class="container">
<div class="col-md-4 px-0">
<img src="images/food1.jpg" class="img-fluid">
</div>
</div>
Write the telnet session inside a BAT Dos file and execute.
Date and time as String to Long (millis):
String dateTimeString = "2020-12-12T14:34:18.000Z";
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDateTime localDateTime = LocalDateTime
.parse(dateTimeString, formatter);
Long dateTimeMillis = localDateTime
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();
I can run on my device at last, just I enabled the "USB debugging" and "Allow mock location" options from the Debug Menu of my device.
I was facing such a problem, look at the picture below
and here is its HTML
<tr class="li1">
<td valign="top">1.</td>
<td colspan="5" valign="top">
<p>How to build e-book learning environment</p>
</td>
</tr>
so I fix it by changing valign Attribute in both td
tags to baseline
and it worked
hope this help you
To kill process on a specific port, you can try this
npx kill-port [port-number]
For anyone coming across this thread, here's a script called thatsNotYoChild.js that I just wrote that solves this problem automatically:
http://www.impressivewebs.com/fixing-parent-child-opacity/
Basically, it separates children from the parent element, but keeps the element in the same physical location on the page.
This has been described in some of the other answers, but here's (in code) how to combine scrollViewDidEndDecelerating
and scrollViewDidEndDragging:willDecelerate
to perform some operation when scrolling has finished:
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self stoppedScrolling];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView
willDecelerate:(BOOL)decelerate
{
if (!decelerate) {
[self stoppedScrolling];
}
}
- (void)stoppedScrolling
{
// done, do whatever
}
$cmd = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=".$new." ".implode(" ", $files);
shell_exec($cmd);
A simplified version of Chauhan's answer
My rule of thumb is:
Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.
Use references otherwise.
Copied from Web Applications:
=QUERY(Responses!B1:I, "Select B where G contains '"&$B1&"'")
Compiling it with gcc
requires you to pass a number of command line options. Compile it with g++
instead.
If you don't want to stretch the image, fit it into div container without overflow and center it by adjusting it's margin if needed.
<div id="app">
<div id="container">
<img src="#" alt="something">
</div>
<div id="container">
<img src="#" alt="something">
</div>
<div id="container">
<img src="#" alt="something">
</div>
</div>
div#container {
height: 200px;
width: 200px;
border: 1px solid black;
margin: 4px;
}
img {
max-width: 100%;
max-height: 100%;
display: block;
margin: 0 auto;
}
for me @"^[\w ]+$" is working, allow number, alphabet and space, but need to type at least one letter or number.
Performetrics provides a convenient Stopwatch class, just the way you need. It can measure wall-clock time and more: it also measures CPU time (user time and system time) if you need. It's small, free and you can download from Maven Central. More information and examples can be found here: https://obvj.net/performetrics
Stopwatch sw = new Stopwatch();
sw.start();
// Your code
sw.stop();
sw.printStatistics(System.out);
// Sample output:
// +-----------------+----------------------+--------------+
// | Counter | Elapsed time | Time unit |
// +-----------------+----------------------+--------------+
// | Wall clock time | 85605718 | nanoseconds |
// | CPU time | 78000500 | nanoseconds |
// | User time | 62400400 | nanoseconds |
// | System time | 15600100 | nanoseconds |
// +-----------------+----------------------+--------------+
You can convert the metrics to any time unit (nanoseconds, milliseconds, seconds, etc...)
PS: I am the author of the tool.
I know this question was specific to JavaScript, however, there seems to be no good, clean way to ALWAYS detect when a textarea changes in all current browsers. I've learned jquery has taken care of it for us. It even handles contextual menu changes to text areas. The same syntax is used regardless of input type.
$('div.lawyerList').on('change','textarea',function(){
// Change occurred so count chars...
});
or
$('textarea').on('change',function(){
// Change occurred so count chars...
});
When you see this error message, you might not have accepted the Xcode license agreement yet after an upgrade.
First of all, make sure you have upgraded your commandline tools:
$ xcode-select --install
Now Apple wants you to agree to their license before you can use these tools:
$ gcc
Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.
$ sudo gcc
You have not agreed to the Xcode license agreements. You must agree to both license agreements below in order to use Xcode.
[...]
After you have accepted it, the commandline tools will work as expected.
Here you go:
$('td[id^="' + value +'"]')
so if the value is for instance 'foo'
, then the selector will be 'td[id^="foo"]'
.
Note that the quotes are mandatory: [id^="...."]
.
Source: http://api.jquery.com/attribute-starts-with-selector/
A browser's default styles are defined in its user agent stylesheet, the sources of which you can find here. Unfortunately, the Cascading and Inheritance level 3 spec does not appear to propose a way to reset a style property to its browser default. However there are plans to reintroduce a keyword for this in Cascading and Inheritance level 4 — the working group simply hasn't settled on a name for this keyword yet (the link currently says revert
, but it is not final). Information about browser support for revert
can be found on caniuse.com.
While the level 3 spec does introduce an initial
keyword, setting a property to its initial value resets it to its default value as defined by CSS, not as defined by the browser. The initial value of display
is inline
; this is specified here. The initial
keyword refers to that value, not the browser default. The spec itself makes this note under the all
property:
For example, if an author specifies
all: initial
on an element it will block all inheritance and reset all properties, as if no rules appeared in the author, user, or user-agent levels of the cascade.This can be useful for the root element of a "widget" included in a page, which does not wish to inherit the styles of the outer page. Note, however, that any "default" style applied to that element (such as, e.g.
display: block
from the UA style sheet on block elements such as<div>
) will also be blown away.
So I guess the only way right now using pure CSS is to look up the browser default value and set it manually to that:
div.foo { display: inline-block; }
div.foo.bar { display: block; }
(An alternative to the above would be div.foo:not(.bar) { display: inline-block; }
, but that involves modifying the original selector rather than an override.)
Comparing the MSDN articles "What's New in the C# 2.0 Language and Compiler" and "What's New in Visual C# 2005", it is possible to deduce that "C# major_version.minor_version" is coined according to the compiler's version numbering.
There is C# 1.2 corresponding to .NET 1.1 and VS 2003 and also named as Visual C# .NET 2003.
But further on Microsoft stopped to increment the minor version (after the dot) numbers or to have them other than zero, 0
. Though it should be noted that C# corresponding to .NET 3.5 is named in msdn.microsoft.com as "Visual C# 2008 Service Pack 1".
There are two parallel namings: By major .NET/compiler version numbering and by Visual Studio numbering.
C# 2.0 is a synonym for Visual C# 2005
C# 3.0 corresponds (or, more correctly, can target) to:
As a common misconception, a ||= b
is not equivalent to a = a || b
, but it behaves like a || a = b
.
But here comes a tricky case. If a
is not defined, a || a = 42
raises NameError
, while a ||= 42
returns 42
. So, they don't seem to be equivalent expressions.
It's actually Document Object Model. HTML is used to build the DOM which is an in-memory representation of the page (while closely related to HTML, they are not exactly the same thing). Things like CSS and Javascript interact with the DOM.
You should use States to store the value of input fields. https://facebook.github.io/react-native/docs/state.html
setState
onChangeText={(value) => this.setState({username: value})}
this.state.username
Sample code
export default class Login extends Component {
state = {
username: 'demo',
password: 'demo'
};
<Text style={Style.label}>User Name</Text>
<TextInput
style={Style.input}
placeholder="UserName"
onChangeText={(value) => this.setState({username: value})}
value={this.state.username}
/>
<Text style={Style.label}>Password</Text>
<TextInput
style={Style.input}
placeholder="Password"
onChangeText={(value) => this.setState({password: value})}
value={this.state.password}
/>
<Button
title="LOGIN"
onPress={() =>
{
if(this.state.username.localeCompare('demo')!=0){
ToastAndroid.show('Invalid UserName',ToastAndroid.SHORT);
return;
}
if(this.state.password.localeCompare('demo')!=0){
ToastAndroid.show('Invalid Password',ToastAndroid.SHORT);
return;
}
//Handle LOGIN
}
}
/>
You are using it as a regular component, but it's actually a function that returns a component.
Try doing something like this:
const NewComponent = NewHOC(Movie)
And you will use it like this:
<NewComponent someProp="someValue" />
Here is a running example:
const NewHOC = (PassedComponent) => {
return class extends React.Component {
render() {
return (
<div>
<PassedComponent {...this.props} />
</div>
)
}
}
}
const Movie = ({name}) => <div>{name}</div>
const NewComponent = NewHOC(Movie);
function App() {
return (
<div>
<NewComponent name="Kill Bill" />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"/>
_x000D_
So basically NewHOC
is just a function that accepts a component and returns a new component that renders the component passed in. We usually use this pattern to enhance components and share logic or data.
You can read about HOCS in the docs and I also recommend reading about the difference between react elements and components
I wrote an article about the different ways and patterns of sharing logic in react.
That should work. Better if you pass a function to val
:
$('#replyBox').val(function(i, text) {
return text + quote;
});
This way you avoid searching the element and calling val
twice.
You can use an IF statement to check the referenced cell(s) and return one result for zero or blank, and otherwise return your formula result.
A simple example:
=IF(B1=0;"";A1/B1)
This would return an empty string if the divisor B1 is blank or zero; otherwise it returns the result of dividing A1 by B1.
In your case of running an average, you could check to see whether or not your data set has a value:
=IF(SUM(K23:M23)=0;"";AVERAGE(K23:M23))
If there is nothing entered, or only zeros, it returns an empty string; if one or more values are present, you get the average.
Both will generate the same columns when you run the migration. In rails console, you can see that this is the case:
:001 > Micropost
=> Micropost(id: integer, user_id: integer, created_at: datetime, updated_at: datetime)
The second command adds a belongs_to :user
relationship in your Micropost model whereas the first does not. When this relationship is specified, ActiveRecord will assume that the foreign key is kept in the user_id
column and it will use a model named User
to instantiate the specific user.
The second command also adds an index on the new user_id
column.
try this
<script type="text/javascript">
window.onload = function(){
var auto_refresh = setInterval(
function ()
{
$('.View').html('');
$('.View').load('Small.php').fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds
}
</script>
All functions in Java are virtual by default.
You have to go out of your way to write non-virtual functions by adding the "final" keyword.
This is the opposite of the C++/C# default. Class functions are non-virtual by default; you make them so by adding the "virtual" modifier.
You need to call tf.global_variables_initializer()
on you session, like
init = tf.global_variables_initializer()
sess.run(init)
Full example is available in this great tutorial https://www.tensorflow.org/get_started/mnist/mechanics
None of the answers here solved my issue (as at February 2020), so I raised an issue at https://issues.apache.org/jira/browse/NETBEANS-3903 and Netbeans fixed the issue!
They're working on a pull request so the fix will be in a future .dmg installer soon, but in the meantime you can copy a file referenced in the bug and replace one in your netbeans modules folder.
Tip - if you right click on Applications > Netbeans and choose Show Package Contents then you can find and replace the file org-netbeans-modules-tomcat5.jar that they refer to in your Netbeans folder, e.g. within /Applications/NetBeans/Apache NetBeans 11.2.app/Contents/Resources/NetBeans/netbeans/enterprise/modules
Set the separatorStyle
of the tableview to UITableViewCellSeparatorStyleNone
. Add your separator image as subview to each cell and set the frame properly.
If you were using JGraph, you should give a try to JGraphT which is designed for algorithms. One of its features is visualization using the JGraph library. It's still developed, but pretty stable. I analyzed the complexity of JGraphT algorithms some time ago. Some of them aren't the quickest, but if you're going to implement them on your own and need to display your graph, then it might be the best choice. I really liked using its API, when I quickly had to write an app that was working on graph and displaying it later.
The official csv
documentation recommends open
ing the file with newline=''
on all platforms to disable universal newlines translation:
with open('output.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
...
The CSV writer terminates each line with the lineterminator
of the dialect, which is \r\n
for the default excel
dialect on all platforms.
On Windows, always open your files in binary mode ("rb"
or "wb"
), before passing them to csv.reader
or csv.writer
.
Although the file is a text file, CSV is regarded a binary format by the libraries involved, with \r\n
separating records. If that separator is written in text mode, the Python runtime replaces the \n
with \r\n
, hence the \r\r\n
observed in the file.
See this previous answer.
In my cases, I solved the problem when using the labs()
instead of abs()
.
You can set UIButton title color with hex code
btn.setTitleColor(UIColor(hexString: "#95469F"), for: .normal)
With HttpClient 4.5 you can do this:
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager()).build();
Note that this one implements Closeable (for shutting down of the connection manager).
Use text-center
class in the parent container for Bootstrap 4
I solved this issue with commands bellow:
$ sudo apt-get install php7.3-intl
$ sudo /etc/init.d/php7.3-fpm restart
These commands works for me in homestead with php7.3
If you run npm config edit
, you'll get an editor showing the current configuration, and also a list of options and their default values.
But I don't think there's a 'reset' command.
Note that %in%
returns a logical vector of TRUE
and FALSE
. To negate it, you can use !
in front of the logical statement:
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
!where_case_travelled_1 %in%
c('Outside Canada','Outside province/territory of residence but within Canada'))
Regarding your original approach with -c(...)
, -
is a unary operator that "performs arithmetic on numeric or complex vectors (or objects which can be coerced to them)" (from help("-")
). Since you are dealing with a character vector that cannot be coerced to numeric or complex, you cannot use -
.
Use is
when you want to check against an object's identity (e.g. checking to see if var
is None
). Use ==
when you want to check equality (e.g. Is var
equal to 3
?).
You can have custom classes where my_var == None
will return True
e.g:
class Negator(object):
def __eq__(self,other):
return not other
thing = Negator()
print thing == None #True
print thing is None #False
is
checks for object identity. There is only 1 object None
, so when you do my_var is None
, you're checking whether they actually are the same object (not just equivalent objects)
In other words, ==
is a check for equivalence (which is defined from object to object) whereas is
checks for object identity:
lst = [1,2,3]
lst == lst[:] # This is True since the lists are "equivalent"
lst is lst[:] # This is False since they're actually different objects
One can always go for analytical functions as well which will give you more control
select tmp.row from ( select row, rank() over(partition by id order by id desc ) as rnk from table) tmp where tmp.rnk=1
If you face issue with rank() function depending on the type of data then one can choose from row_number() or dense_rank() too.
Simply type:
. ~/.bash_profile
However, if you want to source it to run automatically when terminal starts instead of running it every time you open terminal, you might add . ~/.bash_profile
to ~/.bashrc
file.
Note:
When you open a terminal, the terminal starts bash in (non-login) interactive mode, which means it will source ~/.bashrc
.
~/.bash_profile
is only sourced by bash when started in interactive login mode. That is typically only when you login at the console (Ctrl+Alt+F1..F6), or connecting via ssh
.
Try to use the empty()
function:
<xsl:if test="empty(node/ABC/node()) and empty(node/DEF/node())">
<xsl:text>This should work</xsl:text>
</xsl:if>
This identifies ABC
and DEF
as empty in the sense that they do not have any child nodes (no elements, no text nodes, no processing instructions, no comments).
But, as pointed out by @Ian, your elements might not be empty really or that might not be your actual problem - you did not show what your input XML looks like.
Another cause of error could be your relative position in the tree. This way of testing conditions only works if the surrounding template matches the parent element of node
or if you iterate over the parent element of node
.
i just switched positions and worked for me (showing only mobile )
<style>_x000D_
.MobileContent {_x000D_
_x000D_
display: none;_x000D_
text-align:center;_x000D_
_x000D_
}_x000D_
_x000D_
@media screen and (max-width: 768px) {_x000D_
_x000D_
.MobileContent {_x000D_
_x000D_
display:block;_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
</style>_x000D_
<div class="MobileContent"> Something </div>
_x000D_
I had the same problem: The point here is to point on the java.exe binary under Oracle client installation and not the JDK installation under Program Files.
This should do it:
cat ~/Desktop/myfile.txt | sed s/:/\\n/g
webview.loadDataWithBaseURL(null, text, "text/html", "UTF-8", null);
/**
* Assigns the specified char value to each element of the specified array
* of chars.
*
* @param a the array to be filled
* @param val the value to be stored in all elements of the array
*/
public static void fill(char[] a, char val) {
for (int i = 0, len = a.length; i < len; i++)
a[i] = val;
}
That's the way Arrays.fill does it.
(I suppose you could drop into JNI and use memset
.)
It issue can be sorted by using, No need to set editText inputType to any values, just add the below line, editText.setTextIsSelectable(true);
That attribute is basically the persistence for the "Associated Activity" selection above the layout. At runtime, a layout is always associated with an activity. It can of course be associated with more than one, but at least one. In the tool, we need to know about this mapping (which at runtime happens in the other direction; an activity can call setContentView(layout) to display a layout) in order to drive certain features.
Right now, we're using it for one thing only: Picking the right theme to show for a layout (since the manifest file can register themes to use for an activity, and once we know the activity associated with the layout, we can pick the right theme to show for the layout). In the future, we'll use this to drive additional features - such as rendering the action bar (which is associated with the activity), a place to add onClick handlers, etc.
The reason this is a tools: namespace attribute is that this is only a designtime mapping for use by the tool. The layout itself can be used by multiple activities/fragments etc. We just want to give you a way to pick a designtime binding such that we can for example show the right theme; you can change it at any time, just like you can change our listview and fragment bindings, etc.
(Here's the full changeset which has more details on this)
And yeah, the link Nikolay listed above shows how the new configuration chooser looks and works
One more thing: The "tools" namespace is special. The android packaging tool knows to ignore it, so none of those attributes will be packaged into the APK. We're using it for extra metadata in the layout. It's also where for example the attributes to suppress lint warnings are stored -- as tools:ignore.
rawgit.com solves this problem nicely. For each request, it retrieves the appropriate document from GitHub and, crucially, serves it with the correct Content-Type header.
Assuming that you know the table name, and want the names of the data columns you can use the listed code will do it in a simple and elegant way to my taste:
import sqlite3
def get_col_names():
#this works beautifully given that you know the table name
conn = sqlite3.connect("t.db")
c = conn.cursor()
c.execute("select * from tablename")
return [member[0] for member in c.description]
It is very simple.
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by Belal on 9/14/2017.
*/
//we need to extend the ArrayAdapter class as we are building an adapter
public class MyListAdapter extends ArrayAdapter<Hero> {
//the list values in the List of type hero
List<Hero> heroList;
//activity context
Context context;
//the layout resource file for the list items
int resource;
//constructor initializing the values
public MyListAdapter(Context context, int resource, List<Hero> heroList) {
super(context, resource, heroList);
this.context = context;
this.resource = resource;
this.heroList = heroList;
}
//this will return the ListView Item as a View
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
//we need to get the view of the xml for our list item
//And for this we need a layoutinflater
LayoutInflater layoutInflater = LayoutInflater.from(context);
//getting the view
View view = layoutInflater.inflate(resource, null, false);
//getting the view elements of the list from the view
ImageView imageView = view.findViewById(R.id.imageView);
TextView textViewName = view.findViewById(R.id.textViewName);
TextView textViewTeam = view.findViewById(R.id.textViewTeam);
Button buttonDelete = view.findViewById(R.id.buttonDelete);
//getting the hero of the specified position
Hero hero = heroList.get(position);
//adding values to the list item
imageView.setImageDrawable(context.getResources().getDrawable(hero.getImage()));
textViewName.setText(hero.getName());
textViewTeam.setText(hero.getTeam());
//adding a click listener to the button to remove item from the list
buttonDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//we will call this method to remove the selected value from the list
//we are passing the position which is to be removed in the method
removeHero(position);
}
});
//finally returning the view
return view;
}
//this method will remove the item from the list
private void removeHero(final int position) {
//Creating an alert dialog to confirm the deletion
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Are you sure you want to delete this?");
//if the response is positive in the alert
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//removing the item
heroList.remove(position);
//reloading the list
notifyDataSetChanged();
}
});
//if response is negative nothing is being done
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
//creating and displaying the alert dialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
Source: Custom ListView Android Tutorial
Concerning more advanced usage, I find these two pages a must read:
You can use full datetime
variables with timedelta
, and by providing a dummy date then using time
to just get the time value.
For example:
import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.
print(a.time())
print(b.time())
results in the two values, three seconds apart:
11:34:59
11:35:02
You could also opt for the more readable
b = a + datetime.timedelta(seconds=3)
if you're so inclined.
If you're after a function that can do this, you can look into using addSecs
below:
import datetime
def addSecs(tm, secs):
fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
fulldate = fulldate + datetime.timedelta(seconds=secs)
return fulldate.time()
a = datetime.datetime.now().time()
b = addSecs(a, 300)
print(a)
print(b)
This outputs:
09:11:55.775695
09:16:55
You can additionally implement IDataErrorInfo
as follows in the view model. If you implement IDataErrorInfo
, you can do the validation in that instead of the setter of a particular property, then whenever there is a error, return an error message so that the text box which has the error gets a red box around it, indicating an error.
class ViewModel : INotifyPropertyChanged, IDataErrorInfo
{
private string m_Name = "Type Here";
public ViewModel()
{
}
public string Name
{
get
{
return m_Name;
}
set
{
if (m_Name != value)
{
m_Name = value;
OnPropertyChanged("Name");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public string Error
{
get { return "...."; }
}
/// <summary>
/// Will be called for each and every property when ever its value is changed
/// </summary>
/// <param name="columnName">Name of the property whose value is changed</param>
/// <returns></returns>
public string this[string columnName]
{
get
{
return Validate(columnName);
}
}
private string Validate(string propertyName)
{
// Return error message if there is error on else return empty or null string
string validationMessage = string.Empty;
switch (propertyName)
{
case "Name": // property name
// TODO: Check validiation condition
validationMessage = "Error";
break;
}
return validationMessage;
}
}
And you have to set ValidatesOnDataErrors=True
in the XAML in order to invoke the methods of IDataErrorInfo
as follows:
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
If you get a model instance from the database, then calling the save method will always update that instance. For example:
t = TemperatureData.objects.get(id=1)
t.value = 999 # change field
t.save() # this will update only
If your goal is prevent any INSERTs, then you can override the save
method, test if the primary key exists and raise an exception. See the following for more detail:
As mentioned by alko989, there is a major security flaw with _blank
(details here).
To avoid it from pure JS code:
const openInNewTab = (url) => {
const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
if (newWindow) newWindow.opener = null
}
Then add to your onClick
onClick={() => openInNewTab('https://stackoverflow.com')}
The third param can also take these optional values, based on your needs.
Add
<form target="_blank" ...></form>
or
form.setAttribute("target", "_blank");
to your form's definition.
To match regexes you need to use the =~
operator.
Try this:
[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched
Alternatively, you can use wildcards (instead of regexes) with the ==
operator:
[[ sed-4.2.2.tar.bz2 == *tar.bz2 ]] && echo matched
If portability is not a concern, I recommend using [[
instead of [
or test
as it is safer and more powerful. See What is the difference between test, [ and [[ ? for details.
For making alert just put below javascript code in footer.
<script>
$(document).ready(function(){
alert('Hi');
});
</script>
You need to also load jquery min file. Please insert this script in header.
<script type='text/javascript' src='https://code.jquery.com/jquery-1.12.0.min.js'></script>
Dim FindRow as Range
Set FindRow = Range("A:A").Find(What:="ProjTemp", _' This is what you are searching for
After:=.Cells(.Cells.Count), _ ' This is saying after the last cell in the_
' column i.e. the first
LookIn:=xlValues, _ ' this says look in the values of the cell not the formula
LookAt:=xlWhole, _ ' This look s for EXACT ENTIRE MATCH
SearchOrder:=xlByRows, _ 'This look down the column row by row
'Larger Ranges with multiple columns can be set to
' look column by column then down
MatchCase:=False) ' this says that the search is not case sensitive
If Not FindRow Is Nothing Then ' if findrow is something (Prevents Errors)
FirstRow = FindRow.Row ' set FirstRow to the first time a match is found
End If
If you would like to get addition ones you can use:
Do Until FindRow Is Nothing
Set FindRow = Range("A:A").FindNext(after:=FindRow)
If FindRow.row = FirstRow Then
Exit Do
Else ' Do what you'd like with the additional rows here.
End If
Loop
You can also use "or" operator,
for( int i = 0 ; i < 100 || someOtherCondition() ; i++ ) {
...
}
Just searched for the docs, and found this:
Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:
{# returns true #}
{{ 1 in [1, 2, 3] }}
{{ 'cd' in 'abcde' }}
Generally I find that it's a code-gen issue and most of the time it's because I've got a type name conflict it couldn't resolve.
If you right-click on your service reference and click configure and uncheck "Reuse Types in Referenced Assemblies" it'll likely resolve the issue.
If you were using some aspect of this feature, you might need to make sure your names are cleaned up.
To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.
SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC
If you care for it to be in the same order as before you can use a common table expression for that:
;WITH CTE AS (
SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC
)
SELECT *
FROM CTE
ORDER BY MySortColumn
If you are linking to many files, create a whitelist, and then use sendFile():
app.get('/npm/:pkg/:file', (req, res) => {
const ok = ['jquery','bootstrap','interactjs'];
if (!ok.includes(req.params.pkg)) res.status(503).send("Not Permitted.");
res.sendFile(__dirname + `/node_modules/${req.params.pkg}/dist/${req.params.file}`);
});
For example, You can then safely link to /npm/bootstrap/bootsrap.js, /npm/bootstrap/bootsrap.css, etc.
As an aside, I would love to know if there was a way to whitelist using express.static
It appears that you can do this in influxdb 0.9. For instance, here's a query that just succeeded for me:
DROP SERIES FROM temperature WHERE machine='zagbar'
(Per generous comment by @MuratCorlu, I'm reposting my earlier comment as an answer...)
The using syntax has an advantage when used within templates. If you need the type abstraction, but also need to keep template parameter to be possible to be specified in future. You should write something like this.
template <typename T> struct whatever {};
template <typename T> struct rebind
{
typedef whatever<T> type; // to make it possible to substitue the whatever in future.
};
rebind<int>::type variable;
template <typename U> struct bar { typename rebind<U>::type _var_member; }
But using syntax simplifies this use case.
template <typename T> using my_type = whatever<T>;
my_type<int> variable;
template <typename U> struct baz { my_type<U> _var_member; }
Got this error when I was setting up Posgtres with Django, I'm using Back Track and it comes with Postgres installed. I assume the settings are the issue. I fixed it by removing it completely then reinstalling like so.
sudo apt-get remove postgresql
sudo apt-get purge postgresql
Now run:
apt-get --purge remove postgresql\*
to remove everything PostgreSQL from your system. Just purging the postgres package isn't enough since it's just an empty meta-package.
Once all PostgreSQL packages have been removed, run:
rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/
userdel -r postgres
groupdel postgres
You should now be able to:
apt-get install postgresql
I'm a little late on the party, but its actualy possible to emulate borders using a box-shadow
.border {_x000D_
background-color: #ededed;_x000D_
padding: 10px;_x000D_
margin-bottom: 5px;_x000D_
}_x000D_
_x000D_
.border-top {_x000D_
box-shadow: inset 0 3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-right {_x000D_
box-shadow: inset -3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-bottom {_x000D_
box-shadow: inset 0 -3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-left {_x000D_
box-shadow: inset 3px 0 0 cornflowerblue;_x000D_
}
_x000D_
<div class="border border-top">border-top</div>_x000D_
<div class="border border-right">border-right</div>_x000D_
<div class="border border-bottom">border-bottom</div>_x000D_
<div class="border border-left">border-left</div>
_x000D_
EDIT: I understood this question wrong, but I will leave the awnser as more people might misunderstand the question and came for the awnser I supplied.
Additional thoughts :
Ramdisk - setting the temp drive MySQL uses as a RAM disk, very easy to set up.
memcache - memcache server is easy to set up, use it to store the results of your queries for X amount of time.
Little-endian, reverse the result or the range if you want Big-endian:
def int_to_bytes(val, num_bytes):
return [(val & (0xff << pos*8)) >> pos*8 for pos in range(num_bytes)]
Big-endian:
def int_to_bytes(val, num_bytes):
return [(val & (0xff << pos*8)) >> pos*8 for pos in reversed(range(num_bytes))]
In httpd.conf
on /Applications/MAMP/conf/apache
, find:
<Directory />
Options Indexes FollowSymLinks
AllowOverride None
</Directory>
Replace None
with All
.
Restart MAMP servers.
*nix provides a nice little command which makes our lives a lot easier.
GET:
with JSON:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource
with XML:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource
POST:
For posting data:
curl --data "param1=value1¶m2=value2" http://hostname/resource
For file upload:
curl --form "[email protected]" http://hostname/resource
RESTful HTTP Post:
curl -X POST -d @filename http://hostname/resource
For logging into a site (auth):
curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/
Pretty-printing the curl results:
For JSON:
If you use npm
and nodejs
, you can install json
package by running this command:
npm install -g json
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json
If you use pip
and python
, you can install pjson
package by running this command:
pip install pjson
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson
If you use Python 2.6+, json tool is bundled within.
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool
If you use gem
and ruby
, you can install colorful_json
package by running this command:
gem install colorful_json
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson
If you use apt-get
(aptitude package manager of your Linux distro), you can install yajl-tools
package by running this command:
sudo apt-get install yajl-tools
Usage:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json_reformat
For XML:
If you use *nix with Debian/Gnome envrionment, install libxml2-utils
:
sudo apt-get install libxml2-utils
Usage:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -
or install tidy
:
sudo apt-get install tidy
Usage:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -
Saving the curl response to a file
curl http://hostname/resource >> /path/to/your/file
or
curl http://hostname/resource -o /path/to/your/file
For detailed description of the curl command, hit:
man curl
For details about options/switches of the curl command, hit:
curl -h
You could also use XPCOM
, say in XUL
based apps like Firefox, Thunderbird or Komodo.
There is no CREATE TABLE IF NOT EXISTS... but you can write a simple procedure for that, something like:
CREATE OR REPLACE FUNCTION prc_create_sch_foo_table() RETURNS VOID AS $$
BEGIN
EXECUTE 'CREATE TABLE /* IF NOT EXISTS add for PostgreSQL 9.1+ */ sch.foo (
id serial NOT NULL,
demo_column varchar NOT NULL,
demo_column2 varchar NOT NULL,
CONSTRAINT pk_sch_foo PRIMARY KEY (id));
CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column ON sch.foo(demo_column);
CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column2 ON sch.foo(demo_column2);'
WHERE NOT EXISTS(SELECT * FROM information_schema.tables
WHERE table_schema = 'sch'
AND table_name = 'foo');
EXCEPTION WHEN null_value_not_allowed THEN
WHEN duplicate_table THEN
WHEN others THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
END; $$ LANGUAGE plpgsql;
With Jackson > 1.9.11 and < 2.x use @JsonSerialize
annotation to do that:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
Found this workaround
.row {
margin-left: 0;
margin-right: 0;
}
[class^="col-"] > [class^="col-"]:first-child,
[class^="col-"] > [class*=" col-"]:first-child
[class*=" col-"] > [class^="col-"]:first-child,
[class*=" col-"]> [class*=" col-"]:first-child,
.row > [class^="col-"]:first-child,
.row > [class*=" col-"]:first-child{
padding-left: 0px;
}
[class^="col-"] > [class^="col-"]:last-child,
[class^="col-"] > [class*=" col-"]:last-child
[class*=" col-"] > [class^="col-"]:last-child,
[class*=" col-"]> [class*=" col-"]:last-child,
.row > [class^="col-"]:last-child,
.row > [class*=" col-"]:last-child{
padding-right: 0px;
}
The solutions so far use ls
. Here's an all bash solution:
#!/bin/bash
shopt -s nullglob dotglob # To include hidden files
files=(/some/dir/*)
if [ ${#files[@]} -gt 0 ]; then echo "huzzah"; fi
In Swift 4.2
UIApplication.shared.keyWindow!.bringSubviewToFront(yourView)
Source: https://developer.apple.com/documentation/uikit/uiview/1622541-bringsubviewtofront#declarations
You can use CSS3 RGBA in this way:
rgba(255, 0, 0, 0.7);
0.7
means 70% opacity.
SimpleConfigFile is a library that does exactly what you require and it is very simple to use.
# File file.cfg
url = http://example.com
file = main.exe
true = 0
The following program reads the previous configuration file:
#include<iostream>
#include<string>
#include<vector>
#include "config_file.h"
int main(void)
{
// Variables that we want to read from the config file
std::string url, file;
bool true_false;
// Names for the variables in the config file. They can be different from the actual variable names.
std::vector<std::string> ln = {"url","file","true"};
// Open the config file for reading
std::ifstream f_in("file.cfg");
CFG::ReadFile(f_in, ln, url, file, true_false);
f_in.close();
std::cout << "url: " << url << std::endl;
std::cout << "file: " << file << std::endl;
std::cout << "true: " << true_false << std::endl;
return 0;
}
The function CFG::ReadFile
uses variadic templates. This way, you can pass the variables you want to read and the corresponding type is used for reading the data in the appropriate way.
Presumably you have it in a variable and are using JSON.parse(data);
. In which case, use:
JSON.parse(data.replace(/"/g,'"'));
You might want to fix your JSON-writing script though, because "
is not valid in a JSON object.
It's all in the tutorial how to do that:
ContentValues args = new ContentValues();
args.put(columnName, newValue);
db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null);
Use ContentValues
to set the updated columns and than the update()
method in which you have to specifiy, the table and a criteria to only update the rows you want to update.
You can create an interface
, pass it to AsyncTask
(in constructor), and then call method in onPostExecute()
For example:
Your interface:
public interface OnTaskCompleted{
void onTaskCompleted();
}
Your Activity:
public class YourActivity implements OnTaskCompleted{
// your Activity
}
And your AsyncTask:
public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
private OnTaskCompleted listener;
public YourTask(OnTaskCompleted listener){
this.listener=listener;
}
// required methods
protected void onPostExecute(Object o){
// your stuff
listener.onTaskCompleted();
}
}
EDIT
Since this answer got quite popular, I want to add some things.
If you're a new to Android development, AsyncTask
is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:
Activity
, it will stay in memory even after user left the screen (or rotated the device).AsyncTask
is not delivering result to Activity
if Activity
was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.Activity
When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.
With regard to Peter Lawrey's note that you don't need instanceof for final classes and can just use a reference equality, be careful! Even though the final classes cannot be extended, they are not guaranteed to be loaded by the same classloader. Only use x.getClass() == SomeFinal.class or its ilk if you are absolutely positive that there is only one classloader in play for that section of code.
Why not use Html.RenderAction()
?
Then you could put the following into any controller (even creating a new controller for it):
[ChildActionOnly]
public ActionResult MyActionThatGeneratesAPartial(string parameter1)
{
var model = repository.GetThingByParameter(parameter1);
var partialViewModel = new PartialViewModel(model);
return PartialView(partialViewModel);
}
Then you could create a new partial view and have your PartialViewModel
be what it inherits from.
For Razor, the code block in the view would look like this:
@{ Html.RenderAction("Index", "Home"); }
For the WebFormsViewEngine, it would look like this:
<% Html.RenderAction("Index", "Home"); %>
Consider a scenario where Test1, Test2 and Test3 are three classes. The Test3 class inherits Test2 and Test1 classes. If Test1 and Test2 classes have same method and you call it from child class object, there will be ambiguity to call method of Test1 or Test2 class but there is no such ambiguity for interface as in interface no implementation is there.
There is a trick that always worked for me:
If you got and unexpected indent and you see that all the code is perfectly indented, try opening it with another editor and you will see what line of code is not indented.
It happened to me when used vim, gedit or editors like that.
Try to use only 1 editor for your code.
Adding alternative base R approach, which remains fast under various cases.
rowsummean <- function(df) {
rowsum(df$speed, df$dive) / tabulate(df$dive)
}
Borrowing the benchmarks from @Ari:
10 rows, 2 groups
10 million rows, 10 groups
10 million rows, 1000 groups
I have same issue. Error message for me is not complete. But in my case, I've added generation jar with sources. By placing this code in pom.xml:
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
<executions>
<execution>
<phase>deploy</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
So in deploy phase I execute source:jar goal which produces jar with sources. And deploy ends with BUILD SUCCESS
Using onunload
allows you to display messages, but will not interrupt the navigation (because it is too late). However, using onbeforeunload
will interrupt navigation:
window.onbeforeunload = function() {
return "";
}
Note: An empty string is returned because newer browsers provide a message such as "Any unsaved changes will be lost" that cannot be overridden.
In older browsers you could specify the message to display in the prompt:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
Hint
DataTable table = new DataTable();
table.Columns.Add("Column#1", typeof(int));
table.Columns.Add("Column#2", typeof(string));
table.Rows.Add(5, "Cell1-1");
table.Rows.Add(130, "Cell2-2");
EDIT: Added more
string cellValue = table.Rows[0].GetCellValueByName<string>("Column#2");
public static class DataRowExtensions
{
public static T GetCellValueByName<T>(this DataRow row, string columnName)
{
int index = row.Table.Columns.IndexOf(columnName);
return (index < 0 || index > row.ItemArray.Count())
? default(T)
: (T) row[index];
}
}
MySQL Installer Community -> MySQL Server Reconfigure -> Next -> Next -> Connection Name [Local instance or any other name] -> Click on Password - Store in Vault... and add a password and then -> Test connection. It works for me :)
You are asking about the &&
operator, not the if
statement.
&&
short-circuits, meaning that if while working it meets a condition which results in only one answer, it will stop working and use that answer.
So, 0 && x
will execute 0
, then terminate because there is no way for the expression to evaluate non-zero regardless of what is the second parameter to &&
.
As an alternative to sed or perl you may consider to use ed(1) and POSIX character classes.
Note: ed(1) reads the entire file into memory to edit it in-place, so for really large files you should use sed -i ..., perl -i ...
# see:
# - http://wiki.bash-hackers.org/doku.php?id=howto:edit-ed
# - http://en.wikipedia.org/wiki/Regular_expression#POSIX_character_classes
# test
echo $'aaa \177 bbb \200 \214 ccc \254 ddd\r\n' > testfile
ed -s testfile <<< $',l'
ed -s testfile <<< $'H\ng/[^[:graph:][:space:][:cntrl:]]/s///g\nwq'
ed -s testfile <<< $',l'
dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);
The parameter TRUE preserve the changes.
For more details refer to MSDN.
In .NET 4 you don't need the ToArray()
call - string.Join
is overloaded to accept IEnumerable<T>
or just IEnumerable<string>
.
There are potentially more efficient ways of doing it before .NET 4, but do you really need them? Is this actually a bottleneck in your code?
You could iterate over the list, work out the final size, allocate a StringBuilder
of exactly the right size, then do the join yourself. That would avoid the extra array being built for little reason - but it wouldn't save much time and it would be a lot more code.
From http://support.microsoft.com/kb/262499
Example:
CREATE PROCEDURE Myproc
@parm varchar(10),
**@parm1OUT varchar(30) OUTPUT**,
**@parm2OUT varchar(30) OUTPUT**
AS
SELECT @parm1OUT='parm 1' + @parm
SELECT @parm2OUT='parm 2' + @parm
GO
DECLARE @SQLString NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)
DECLARE @parmIN VARCHAR(10)
DECLARE @parmRET1 VARCHAR(30)
DECLARE @parmRET2 VARCHAR(30)
SET @parmIN=' returned'
SET @SQLString=N'EXEC Myproc @parm,
@parm1OUT OUTPUT, @parm2OUT OUTPUT'
SET @ParmDefinition=N'@parm varchar(10),
@parm1OUT varchar(30) OUTPUT,
@parm2OUT varchar(30) OUTPUT'
EXECUTE sp_executesql
@SQLString,
@ParmDefinition,
@parm=@parmIN,
@parm1OUT=@parmRET1 OUTPUT,@parm2OUT=@parmRET2 OUTPUT
SELECT @parmRET1 AS "parameter 1", @parmRET2 AS "parameter 2"
GO
DROP PROCEDURE Myproc
Hope this helps!
The biggest clue is the rows are all being returned on one line. This indicates line terminators are being ignored or are not present.
You can specify the line terminator for csv_reader. If you are on a mac the lines created will end with \r
rather than the linux standard \n
or better still the suspenders and belt approach of windows with \r\n
.
pandas.read_csv(filename, sep='\t', lineterminator='\r')
You could also open all your data using the codecs package. This may increase robustness at the expense of document loading speed.
import codecs
doc = codecs.open('document','rU','UTF-16') #open for reading with "universal" type set
df = pandas.read_csv(doc, sep='\t')
In PostgreSQL 9.1, the idle connections with following query. It helped me to ward off the situation which warranted in restarting the database. This happens mostly with JDBC connections opened and not closed properly.
SELECT
pg_terminate_backend(procpid)
FROM
pg_stat_activity
WHERE
current_query = '<IDLE>'
AND
now() - query_start > '00:10:00';
See .offset()
here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset()
and .position()
confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop()
and .scrollLeft()
values to account for the scrolled position.
Here's an excerpt from the doc:
The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.
To combine these:
var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft();
You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/
Add following trait to your project and append it to your model class as a trait. This is helpful, because this adds functionality to use multiple pivots. Probably someone can clean this up a little and improve on it ;)
namespace App\Traits;
trait AppTraits
{
/**
* Create pivot array from given values
*
* @param array $entities
* @param array $pivots
* @return array combined $pivots
*/
public function combinePivot($entities, $pivots = [])
{
// Set array
$pivotArray = [];
// Loop through all pivot attributes
foreach ($pivots as $pivot => $value) {
// Combine them to pivot array
$pivotArray += [$pivot => $value];
}
// Get the total of arrays we need to fill
$total = count($entities);
// Make filler array
$filler = array_fill(0, $total, $pivotArray);
// Combine and return filler pivot array with data
return array_combine($entities, $filler);
}
}
Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Example extends Model
{
use Traits\AppTraits;
// ...
}
Usage:
// Get id's
$entities = [1, 2, 3];
// Create pivots
$pivots = [
'price' => 634,
'name' => 'Example name',
];
// Combine the ids and pivots
$combination = $model->combinePivot($entities, $pivots);
// Sync the combination with the related model / pivot
$model->relation()->sync($combination);
enum builder class
public class XEnum
{
private EnumBuilder enumBuilder;
private int index;
private AssemblyBuilder _ab;
private AssemblyName _name;
public XEnum(string enumname)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
_name = new AssemblyName("MyAssembly");
_ab = currentDomain.DefineDynamicAssembly(
_name, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder mb = _ab.DefineDynamicModule("MyModule");
enumBuilder = mb.DefineEnum(enumname, TypeAttributes.Public, typeof(int));
}
/// <summary>
/// adding one string to enum
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public FieldBuilder add(string s)
{
FieldBuilder f = enumBuilder.DefineLiteral(s, index);
index++;
return f;
}
/// <summary>
/// adding array to enum
/// </summary>
/// <param name="s"></param>
public void addRange(string[] s)
{
for (int i = 0; i < s.Length; i++)
{
enumBuilder.DefineLiteral(s[i], i);
}
}
/// <summary>
/// getting index 0
/// </summary>
/// <returns></returns>
public object getEnum()
{
Type finished = enumBuilder.CreateType();
_ab.Save(_name.Name + ".dll");
Object o1 = Enum.Parse(finished, "0");
return o1;
}
/// <summary>
/// getting with index
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public object getEnum(int i)
{
Type finished = enumBuilder.CreateType();
_ab.Save(_name.Name + ".dll");
Object o1 = Enum.Parse(finished, i.ToString());
return o1;
}
}
create an object
string[] types = { "String", "Boolean", "Int32", "Enum", "Point", "Thickness", "long", "float" };
XEnum xe = new XEnum("Enum");
xe.addRange(types);
return xe.getEnum();
Via Environment.OSVersion
which "Gets an System.OperatingSystem object that contains the current platform identifier and version number."
You could use the method
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target
withString:(NSString *)replacement
...to get a new string with a substring replaced (See NSString
documentation for others)
Example use
NSString *str = @"This is a string";
str = [str stringByReplacingOccurrencesOfString:@"string"
withString:@"duck"];
Here is an example of how I did this. This gets the index at the for each loop. Hope this helps.
public class CheckForEachLoop {
public static void main(String[] args) {
String[] months = new String[] { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST",
"SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };
for (String s : months) {
if (s == months[2]) { // location where you can change
doSomethingWith(s); // however many times s and months
// doSomethingWith(s) will be completed and
// added together instead of counter
}
}
System.out.println(s);
}
}
i also faced with this problem,you could solve it in 2 ways , as mentioned earlier use reflection to create the socket Second one is, client is looking for a server with given UUID and if your server isn't running parallel to client then this happens. Create a server with given client UUID and then listen and accept the client from server side.It will work.
select p.pid, p.cid, c1.name,c2.name
from product p
left outer join customer1 c1 on c1.cid=p.cid
left outer join customer2 c2 on c2.cid=p.cid
If I've understood your problem correctly, there are two possible problems here:
resultset
is null
- I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.resultset.getString(i++)
will get columns 1,2,3 and so on from each subsequent row.I think that the second point is probably your problem here.
Lets say you only had 1 row returned, as follows:
Col 1, Col 2, Col 3
A , B, C
Your code as it stands would only get A - it wouldn't get the rest of the columns.
I suggest you change your code as follows:
ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>();
while (resultset.next()) {
int i = 1;
while(i <= numberOfColumns) {
arrayList.add(resultset.getString(i++));
}
System.out.println(resultset.getString("Col 1"));
System.out.println(resultset.getString("Col 2"));
System.out.println(resultset.getString("Col 3"));
System.out.println(resultset.getString("Col n"));
}
Edit:
To get the number of columns:
ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();
String toAdd = "toAdd";
StringBuilder s = new StringBuilder();
for(int count = 0; count < MAX; count++) {
s.append(toAdd);
}
String output = s.toString();
If you are concerned about speed (say you have a looong list of strings) and you know the nature of the newline char, string slicing is actually faster than rstrip. A little test to illustrate this:
import time
loops = 50000000
def method1(loops=loops):
test_string = 'num\n'
t0 = time.time()
for num in xrange(loops):
out_sting = test_string[:-1]
t1 = time.time()
print('Method 1: ' + str(t1 - t0))
def method2(loops=loops):
test_string = 'num\n'
t0 = time.time()
for num in xrange(loops):
out_sting = test_string.rstrip()
t1 = time.time()
print('Method 2: ' + str(t1 - t0))
method1()
method2()
Output:
Method 1: 3.92700004578
Method 2: 6.73000001907
Any suggestions/examples? I followed
SwingWorker
... The code was very messy and I don't like this approach.
Instead of get()
, which waits for completion, use process()
and setProgress()
to show intermediate results, as suggested in this simple example or this related example.
Classic C (the early dialect of C described by Brian Kernighan and Dennis Ritchie in The C Programming Language, Prentice-Hall, 1978) didn't provide size_t
. The C standards committee introduced size_t
to eliminate a portability problem
Explained in detail at embedded.com (with a very good example)
I suggest removing the below code from getMails
.catch(error => { throw error})
In your main function you should put await and related code in Try block and also add one catch block where you failure code.
you function gmaiLHelper.getEmails should return a promise which has reject and resolve in it.
Now while calling and using await put that in try catch block(remove the .catch) as below.
router.get("/emailfetch", authCheck, async (req, res) => {
//listing messages in users mailbox
try{
let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
}
catch (error) {
// your catch block code goes here
})
Put your wait() function in a loop and wait for all the child processes. The wait function will return -1 and errno will be equal to ECHILD if no more child processes are available.
I've ran across this problem recently while trying to retrieve a null decimal from a DataTable
object from db and I haven't seen this answer here. I find this easier and shorter:
var value = rdrSelect.Field<decimal?>("ColumnName") ?? 0;
This was useful in my case since i didn't have a nullable decimal in the model, but needed a quick check against one. If the db value happens to be null, it'll just assign the default value.
As mentioned above @NotNull
does nothing on its own. A good way of using @NotNull
would be using it with Objects.requireNonNull
public class Foo {
private final Bar bar;
public Foo(@NotNull Bar bar) {
this.bar = Objects.requireNonNull(bar, "bar must not be null");
}
}
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Why is floatval the best option for financial comparison data? bc functions only accurately turn strings into real numbers.
With python 3 interpreter the history is written to
~/.python_history
if you add an #include <algorithm>
then you can use the for_each
function and a lambda function like so:
for_each(data.begin(), data.end(), [](Student *it)
{
std::cout<<it->name;
});
you can read more about the algorithm library at https://en.cppreference.com/w/cpp/algorithm
and about lambda functions in cpp at https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=vs-2019
(Posted on behalf of the OP).
I believe I figured it out.
In my case, I added [class*="col-"] {padding: 0 7.5px;};
.
Then added .row {margin: 0 -7.5px;}
.
This works pretty well, except there is 1px margin on both sides. So I just make .row {margin: 0 -7.5px;}
to .row {margin: 0 -8.5px;}
, then it works perfectly.
I have no idea why there is a 1px margin. Maybe someone can explain it?
See the sample I created:
You can use model.save(filepath)
to save a Keras model into a single HDF5 file which will contain:
In your Python code probable the last line should be:
model.save("m.hdf5")
This allows you to save the entirety of the state of a model in a single file.
Saved models can be reinstantiated via keras.models.load_model()
.
The model returned by load_model()
is a compiled model ready to be used (unless the saved model was never compiled in the first place).
model.save()
arguments:
Try this
-moz-box-shadow:0 5px 5px rgba(182, 182, 182, 0.75);
-webkit-box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
You can see it in http://jsfiddle.net/wJ7qp/
Try it like this:
Sub testIt()
Dim r As Long, endRow as Long, pasteRowIndex As Long
endRow = 10 ' of course it's best to retrieve the last used row number via a function
pasteRowIndex = 1
For r = 1 To endRow 'Loop through sheet1 and search for your criteria
If Cells(r, Columns("B").Column).Value = "YourCriteria" Then 'Found
'Copy the current row
Rows(r).Select
Selection.Copy
'Switch to the sheet where you want to paste it & paste
Sheets("Sheet2").Select
Rows(pasteRowIndex).Select
ActiveSheet.Paste
'Next time you find a match, it will be pasted in a new row
pasteRowIndex = pasteRowIndex + 1
'Switch back to your table & continue to search for your criteria
Sheets("Sheet1").Select
End If
Next r
End Sub
Layout inflator inflates/adds external XML to your current view.
getView() is called numerous times including when scrolled. So if it already has view inflated we don't wanna do it again since inflating is a costly process.. thats why we check if its null and then inflate it.
The parent view is single cell of your List..
The command free
is nice. Takes a short while to understand the "+/- buffers/cache", but the idea is that cache and buffers doesn't really count when evaluating "free", as it can be dumped right away. Therefore, to see how much free (and used) memory you have, you need to remove the cache/buffer usage - which is conveniently done for you.
The easiest way to get rid of this is to:
Ex :
<script>
function loadUrl(location)
{
this.document.location.href = location;
}</script>
<div onclick="loadUrl('company_page.jsp')">Abc</div>
This worked very well for me. Cheers
The normal way to control this is with git config
For example
git config --global core.autocrlf true
For details, scroll down in this link to Pro Git to the section named "core.autocrlf"
If you want to know what file this is saved in, you can run the command:
git config --global --edit
and the git global config file should open in a text editor, and you can see where that file was loaded from.
To change the color via:
Put these styles in your stylesheet after the bootstrap styles:
.modal-backdrop {
background-color: red;
}
Changes the bootstrap-variables to:
@modal-backdrop-bg: red;
Changes the bootstrap-variables to:
$modal-backdrop-bg: red;
Change @modal-backdrop-bg
to your desired color:
You can also remove the backdrop via Javascript or by setting the color to transparent
.
For Apache 2.4, you would use the Require IP directive. So to only allow machines from the 192.168.0.0/24 network (range 192.168.0.0 - 192.168.0.255)
<VirtualHost *:80>
<Location />
Require ip 192.168.0.0/24
</Location>
...
</VirtualHost>
And if you just want the localhost machine to have access, then there's a special Require local directive.
The local provider allows access to the server if any of the following conditions is true:
- the client address matches 127.0.0.0/8
- the client address is ::1
- both the client and the server address of the connection are the same
This allows a convenient way to match connections that originate from the local host:
<VirtualHost *:80>
<Location />
Require local
</Location>
...
</VirtualHost>
Maybe is late now but following Spacedman, did you try duplicate="strip" or any other option?
x=runif(1000)
y=runif(1000)
z=rnorm(1000)
s=interp(x,y,z,duplicate="strip")
surface3d(s$x,s$y,s$z,color="blue")
points3d(s)
By value, what worked for me with jQuery 1.7 was the below code, try this:
$('#id option[value=theOptionValue]').prop('selected', 'selected').change();
In Android Studio it is very simple to adjust color and opacity using a built-in tool:
Start by registering your custom browser/uploader when you instantiate CKEditor. You can designate different URLs for an image browser vs. a general file browser.
<script type="text/javascript">
CKEDITOR.replace('content', {
filebrowserBrowseUrl : '/browser/browse/type/all',
filebrowserUploadUrl : '/browser/upload/type/all',
filebrowserImageBrowseUrl : '/browser/browse/type/image',
filebrowserImageUploadUrl : '/browser/upload/type/image',
filebrowserWindowWidth : 800,
filebrowserWindowHeight : 500
});
</script>
Your custom code will receive a GET parameter called CKEditorFuncNum. Save it - that's your callback function. Let's say you put it into $callback
.
When someone selects a file, run this JavaScript to inform CKEditor which file was selected:
window.opener.CKEDITOR.tools.callFunction(<?php echo $callback; ?>,url)
Where "url" is the URL of the file they picked. An optional third parameter can be text that you want displayed in a standard alert dialog, such as "illegal file" or something. Set url to an empty string if the third parameter is an error message.
CKEditor's "upload" tab will submit a file in the field "upload" - in PHP, that goes to $_FILES['upload']. What CKEditor wants your server to output is a complete JavaScript block:
$output = '<html><body><script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$callback.', "'.$url.'","'.$msg.'");</script></body></html>';
echo $output;
Again, you need to give it that callback parameter, the URL of the file, and optionally a message. If the message is an empty string, nothing will display; if the message is an error, then url should be an empty string.
The official CKEditor documentation is incomplete on all this, but if you follow the above it'll work like a champ.
Thread.Sleep(50);
The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.
This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.
Thread.Join
Started a jsFiddle here.
It seems the horizontal alignment works with a text-align : center
. Still trying to get the vertical align to work; might have to use absolute
positioning and something like top: 50%
or a pre-calculated padding
from the top.
If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest
android:exported="true"
Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.
finish();
The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class
in the code, so compile will fail.
I searched on the web and found something like this below, and it works well.
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);
You can also use the setClassName method:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();
You can also pass the values from one app to another app :
Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
launchIntent.putExtra("AppID", "MY-CHILD-APP1");
launchIntent.putExtra("UserID", "MY-APP");
launchIntent.putExtra("Password", "MY-PASSWORD");
startActivity(launchIntent);
finish();
} else {
Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}
I too encountered the same scenario and found out two solutions after googling for several times. Hope this helps.
Way 01:
Before trying to open the file in Excel, find it in Windows' File Explorer. Right-click the file and select Properties. At the bottom of the General tab, click the Unblock button. Once you unblock a file, Windows should remember and Excel should not ask you again. This option is available for some file types, but not others. If you don't have an Unblock button, use Way 2.
Way 02:
This option is better if you usually store your downloaded Excel files in one folder. In Excel, click File » Options » Trust Center » Trust Center Settings » Trusted Locations. Click Add new location. Browse to the folder where you store your Excel files, select Subfolders of this location are also trusted, and click OK.
simply click
'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'
and run the below query is :
Query:alter Table 'TableName' drop constraint PK__TableName__30242045
I encountered this error during refactoring where I renamed some files/folders and the prexisiting *.g.cs files needed to be re-generated.
You shouldn't use both ngRoute
and UI-router
. Here's a sample code for UI-router:
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
_x000D_
$stateProvider_x000D_
.state('state1', {_x000D_
url: "/state1",_x000D_
templateUrl: "partials/state1.html",_x000D_
controller: 'YourCtrl'_x000D_
})_x000D_
_x000D_
.state('state2', {_x000D_
url: "/state2",_x000D_
templateUrl: "partials/state2.html",_x000D_
controller: 'YourOtherCtrl'_x000D_
});_x000D_
$urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?
You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router
var input = '/var/www/site/Brand new document.docx';
//remove space
input = input.replace(/\s/g, '');
//make string lower
input = input.toLowerCase();
alert(input);
On Windows 8.1 or 10 include the .Net framework 4.5 or above as shown below
This error will also occur if you call .ps1
file from a .bat
file and file path has spaces.
The fix is to make sure there are no spaces in the path of .ps1
file.
I have tried everything but could not make it work. Finally I have used pyenv
and it worked directly like a charm.
So having homebrew
installed, juste do:
brew install pyenv
pyenv install 3.6.5
to manage virtualenvs:
brew install pyenv-virtualenv
pyenv virtualenv 3.6.5 env_name
See pyenv and pyenv-virtualenv for more info.
I have found using the pyenv-installer easier than homebrew to install pyenv and pyenv-virtualenv direclty:
curl https://pyenv.run | bash
To manage python version, either globally:
pyenv global 3.6.5
or locally in a given directory:
pyenv local 3.6.5
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.