The solutions so far don't work because the POST data is stored in the headers. A redirect solves this issue according this this post.
How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?
I had the same problem and it was due to the end of line. I had copied from another document. I put everythng on the same line, then split them again and it worked.
Note: This is Flask specific!
I know this post is quite old, but there are better methods of doing this in the newer versions of Flask using context processors.
Variables can easily be created:
@app.context_processor
def example():
return dict(myexample='This is an example')
The above can be used in a Jinja2 template with Flask like so:
{{ myexample }}
(Which outputs This is an example
)
As well as full fledged functions:
@app.context_processor
def utility_processor():
def format_price(amount, currency=u'€'):
return u'{0:.2f}{1}'.format(amount, currency)
return dict(format_price=format_price)
The above when used like so:
{{ format_price(0.33) }}
(Which outputs the input price with the currency symbol)
Alternatively, you can use jinja filters, baked into Flask. E.g. using decorators:
@app.template_filter('reverse')
def reverse_filter(s):
return s[::-1]
Or, without decorators, and manually registering the function:
def reverse_filter(s):
return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter
Filters applied with the above two methods can be used like this:
{% for x in mylist | reverse %}
{% endfor %}
It seems that now you can just mark the method parameter with @RequestParam
and it will do the job for you.
@PostMapping( "some/request/path" )
public void someControllerMethod( @RequestParam Map<String, String> body ) {
//work with Map
}
Code:
List<String> list = new ArrayList<String>();
list.add("a");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
obj.put("result", array);
} catch (JSONException e) {
e.printStackTrace();
}
A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
You can just go for String
replace method.-
line1 = line1.replace("\"", "");
Rather than using a DisplayFilter you could use a very simple CaptureFilter like
port 53
See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.
All apps will continue to work in the vertically stretched screen from what I could tell in today's presentation. They will be letterboxed or basically the extra 88 points in height would simply be black.
If you only plan to support iOS 6+, then definitely consider using Auto Layout. It removes all fixed layout handling and instead uses constraints to lay things out. Nothing will be hard-coded, and your life will become a lot simpler.
However, if you have to support older iOS's, then it really depends on your application. A majority of applications that use a standard navigation bar, and/or tab bar, could simply expand the content in the middle to use up that extra points. Set the autoresizing mask of the center content to expand in both directions.
view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
It works great out of the box for table views, however, if your app used pixel-perfect layout for displaying content, then your best bet would be to re-imagine the content so that it can accommodate varying heights.
If that's not a possibility, then the only remaining option is to have two UIs (pre iPhone 5, and iPhone 5).
If that sounds ugly, then you could go with the default letterboxed model where the extra points/pixels just show up black.
Edit
To enable your apps to work with iPhone 5, you need to add a retina version of the launcher image. It should be named [email protected]
. And it has to be retina quality - there's no backward compatibility here :)
You could also select this image from within Xcode. Go to the target, and under the Summary section, look for Launch Images. The image has to be 640x1136 pixels in size. Here's a screenshot of where to find it, if that helps.
Try @ sign at start of expression. So you wont need to type escape characters just copy paste the regular expression in "" and put @ sign. Like so:
[RegularExpression(@"([a-zA-Z\d]+[\w\d]*|)[a-zA-Z]+[\w\d.]*", ErrorMessage = "Invalid username")]
public string Username { get; set; }
I recommend another option. jQuery UI has a new position feature that allows you to position elements relative to each other. For complete documentation and demo see: http://jqueryui.com/demos/position/#option-offset.
Here's one way to position your elements using the position feature:
var options = {
"my": "top left",
"at": "top left",
"of": ".layer1"
};
$(".layer2").position(options);
I just simply forget running the Docker Desktop in my mac, after running Docker Desktop, you will be good to go.
Try wrapping expression with:
$scope.$apply(function() {
$scope.foo.bar=true;
})
There was no year 0000 and there is no month 00 or day 00. I suggest you try
0001-01-01 00:00:00
While a year 0 has been defined in some standards, it is more likely to be confusing than useful IMHO.
new[] { "item" }.ToList();
It's shorter than
new List<string> { "item" };
and you don't have to specify the type.
dictionary['key'] = dictionary.get('key', []) + list_to_append
Taking a point from both Boycs Answer and mtmurdock's subsequent answer I have the following stored proc on all of my development or staging databases. I've added some switches to fit my own requirement if I need to add in statements to reseed the data for certain columns.
(Note: I would have added this as a comment to Boycs brilliant answer but I haven't got enough reputation to do that yet. So please accept my apologies for adding this as an entirely new answer.)
ALTER PROCEDURE up_ResetEntireDatabase
@IncludeIdentReseed BIT,
@IncludeDataReseed BIT
AS
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
IF @IncludeIdentReseed = 1
BEGIN
EXEC sp_MSForEachTable 'DBCC CHECKIDENT (''?'' , RESEED, 1)'
END
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
IF @IncludeDataReseed = 1
BEGIN
-- Populate Core Data Table Here
END
GO
And then once ready the execution is really simple:
EXEC up_ResetEntireDatabase 1, 1
You can use onBackPressedDispatcher
of parent activity like this:
val backpress = requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, true) {
// here dispatcher works for any action when back pressed
}
you can also enable/disable backpress button from fragment any time like this:
backpress.isEnabled = true/false
maybe:
import numpy as np
a=[[1,1],[2,2]]
b=np.asarray(a)
print(type(b))
output:
<class 'numpy.ndarray'>
There are several ways you can achieve this. One would be something like:
for filepath in /path/to/dir/*
do
filename=$(basename $filepath)
... whatever you want to do with the file here
done
Here's a custom hook that I use which I believe is more intuitive than using usePrevious
.
import { useRef, useEffect } from 'react'
// useTransition :: Array a => (a -> Void, a) -> Void
// |_______| |
// | |
// callback deps
//
// The useTransition hook is similar to the useEffect hook. It requires
// a callback function and an array of dependencies. Unlike the useEffect
// hook, the callback function is only called when the dependencies change.
// Hence, it's not called when the component mounts because there is no change
// in the dependencies. The callback function is supplied the previous array of
// dependencies which it can use to perform transition-based effects.
const useTransition = (callback, deps) => {
const func = useRef(null)
useEffect(() => {
func.current = callback
}, [callback])
const args = useRef(null)
useEffect(() => {
if (args.current !== null) func.current(...args.current)
args.current = deps
}, deps)
}
You'd use useTransition
as follows.
useTransition((prevRate, prevSendAmount, prevReceiveAmount) => {
if (sendAmount !== prevSendAmount || rate !== prevRate && sendAmount > 0) {
const newReceiveAmount = sendAmount * rate
// do something
} else {
const newSendAmount = receiveAmount / rate
// do something
}
}, [rate, sendAmount, receiveAmount])
Hope that helps.
In AVD Manager,
Go to Edit Icon on AVD Manager for selected Device.
Click on show advanced settings and increase ram size from 1500 mb to 2 GB.
Then it works.
NOTE: Some virtual devices do not allow you to update RAM, but if so, try installing Nexus 4. because it does.
NOTE2: If still doesnt work, dont give up. just uninstall and reinstall the device with changing RAM again. in some cases this is how it works
NOTE3: If still doesnt work, this means your pc doesnt have enough ram space. so increase the ram to 3gb. it might work but it will suffer
NOTE4: If still doesnt work, try it with multicore 2 instead of 4.
NOTE5: Still doesnt work. Close the Android Studio and NEVER open it back :)
As of AngularJS 1.2 there's a directive called ng-repeat-start
that does exactly what you ask for. See my answer in this question for a description of how to use it.
Test::StaticTest()
is called exactly once during global static initialization.
Caller only has to add one line to the function that is to be their static constructor.
static_constructor<&Test::StaticTest>::c;
forces initialization of c
during global static initialization.
template<void(*ctor)()>
struct static_constructor
{
struct constructor { constructor() { ctor(); } };
static constructor c;
};
template<void(*ctor)()>
typename static_constructor<ctor>::constructor static_constructor<ctor>::c;
/////////////////////////////
struct Test
{
static int number;
static void StaticTest()
{
static_constructor<&Test::StaticTest>::c;
number = 123;
cout << "static ctor" << endl;
}
};
int Test::number;
int main(int argc, char *argv[])
{
cout << Test::number << endl;
return 0;
}
The problem I was having with the rewrite is that some .htaccess files for Codeigniter, etc come with
RewriteBase /
Which doesn't seem to work in MAMP...at least for me.
This extension method eliminates the need to sort the entire list.
Instead, it inserts each new item in place. So the list is always remains sorted.
It turns out that this method just works when a lot of the other methods fail due to missing notifications when the collection changes. And it is rather fast.
The code below should be bulletproof; it has been extensively tested in a large-scale production environment.
To use:
// Call on dispatcher.
ObservableCollection<MyClass> collectionView = new ObservableCollection<MyClass>();
var p1 = new MyClass() { Key = "A" }
var p2 = new MyClass() { Key = "Z" }
var p3 = new MyClass() { Key = "D" }
collectionView.InsertInPlace(p1, o => o.Key);
collectionView.InsertInPlace(p2, o => o.Key);
collectionView.InsertInPlace(p3, o => o.Key);
// The list will always remain ordered on the screen, e.g. "A, D, Z" .
// Insertion speed is Log(N) as it uses a binary search.
And the extension method:
/// <summary>
/// Inserts an item into a list in the correct place, based on the provided key and key comparer. Use like OrderBy(o => o.PropertyWithKey).
/// </summary>
public static void InsertInPlace<TItem, TKey>(this ObservableCollection<TItem> collection, TItem itemToAdd, Func<TItem, TKey> keyGetter)
{
int index = collection.ToList().BinarySearch(keyGetter(itemToAdd), Comparer<TKey>.Default, keyGetter);
collection.Insert(index, itemToAdd);
}
And the binary search extension method:
/// <summary>
/// Binary search.
/// </summary>
/// <returns>Index of item in collection.</returns>
/// <notes>This version tops out at approximately 25% faster than the equivalent recursive version. This 25% speedup is for list
/// lengths more of than 1000 items, with less performance advantage for smaller lists.</notes>
public static int BinarySearch<TItem, TKey>(this IList<TItem> collection, TKey keyToFind, IComparer<TKey> comparer, Func<TItem, TKey> keyGetter)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
int lower = 0;
int upper = collection.Count - 1;
while (lower <= upper)
{
int middle = lower + (upper - lower) / 2;
int comparisonResult = comparer.Compare(keyToFind, keyGetter.Invoke(collection[middle]));
if (comparisonResult == 0)
{
return middle;
}
else if (comparisonResult < 0)
{
upper = middle - 1;
}
else
{
lower = middle + 1;
}
}
// If we cannot find the item, return the item below it, so the new item will be inserted next.
return lower;
}
Let's break it down:
So the GAC must be a place to store code libraries so they're accessible to all applications running on the machine.
These answers are all outdated for those utilizing the HttpClient rather than Http. I was starting to go crazy thinking, "I have done the import of URLSearchParams but it still doesn't work without .toString() and the explicit header!"
With HttpClient, use HttpParams instead of URLSearchParams and note the body = body.append()
syntax to achieve multiple params in the body since we are working with an immutable object:
login(userName: string, password: string): Promise<boolean> {
if (!userName || !password) {
return Promise.resolve(false);
}
let body: HttpParams = new HttpParams();
body = body.append('grant_type', 'password');
body = body.append('username', userName);
body = body.append('password', password);
return this.http.post(this.url, body)
.map(res => {
if (res) {
return true;
}
return false;
})
.toPromise();
}
Here's a quicker way than multi-layer menus without resorting to plug-ins:
Use the Quick Access tool at the upper left corner.
Type in "font", then, from the list that drops down, click on the link for "Preferences->Colors and Fonts->General->Appearance".
One click replaces the 4 needed to get there through menus. I do it so often, my Quick Access tool pulls it up as a previous choice right at the top of the list so I can just type "font" with a tap on the enter key and Boom!, I'm there.
If you want a keyboard shortcut, Ctrl+3 sets the focus to the Quick Access tool. Better yet, this even automatically brings up a list with your previous choices. The last one you chose will be on top, in which case a simple Ctrl+3 followed by enter would bring you straight there! I use this all the time to make it bigger during long typing or reading sessions to ease eye strain, or to make it smaller if I need more text on the screen at one time to make it easier to find something.
It's not quite as nice as zooming with the scroll wheel or with a simple Ctrl+ or Ctrl-, but it's a lot better than navigating through the menus every time!
It's because there is no long
in javascript.
List images:
ahanjura@ubuntu:~$ sudo docker images
REPOSITORY TAG IMAGE ID CREATED SIZE 88282f8eda00 19 seconds ago 308.5 MB 13e5d3d682f4 19 hours ago 663 MB busybox2 latest 05fe66bb1144 20 hours ago 1.129 MB ubuntu 16.04 00fd29ccc6f1 5 days ago 110.5 MB ubuntu 14.04 67759a80360c 5 days ago 221.4 MB python 2.7 9e92c8430ba0 7 days ago 680.7 MB busybox latest 6ad733544a63 6 weeks ago 1.129 MB ubuntu 16.10 7d3f705d307c 5 months ago 106.7 MB
Delete images:
ahanjura@ubuntu:~$ sudo docker rmi 88282f8eda00
Deleted: sha256:88282f8eda0036f85b5652c44d158308c6f86895ef1345dfa788318e6ba31194 Deleted: sha256:4f211a991fb392cd794bc9ad8833149cd9400c5955958c4017b1e2dc415e25e9 Deleted: sha256:8cc6917ac7f0dcb74969ae7958fe80b4a4ea7b3223fc888dfe1aef42f43df6f8 Deleted: sha256:b74a8932cff5e61c3fd2cc39de3c0989bdfd5c2e5f72b8f99f2807595f8ece43
ahanjura@ubuntu:~$ sudo docker rmi 13e5d3d682f4
Error response from daemon: conflict: unable to delete 13e5d3d682f4 (must be forced) - image is being used by stopped container 5593e25eb638
Delete by force:
ahanjura@ubuntu:~$ sudo docker rmi -f 13e5d3d682f4
Deleted: sha256:13e5d3d682f4de973780b35a3393c46eb314ef3db45d3ae83baf2dd9d702747e Deleted: sha256:3ad9381c7041c03768ccd855ec86caa6bc0244223f10b0465c4898bdb21dc378 Deleted: sha256:5ccb917bce7bc8d3748eccf677d7b60dd101ed3e7fd2aedebd521735276606af Deleted: sha256:18356d19b91f0abcc04496729c9a4c49e695dbfe3f0bb1c595f30a7d4d264ebf
#region TextBoxIDCard selection
private bool textBoxIDCardGotFocus = false;
private void TextBoxIDCard_GotFocus(object sender, RoutedEventArgs e)
{
this.TextBoxIDCard.SelectAll();
}
private void TextBoxIDCard_LostFocus(object sender, RoutedEventArgs e)
{
textBoxIDCardGotFocus = false;
}
private void TextBoxIDCard_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (textBoxIDCardGotFocus == false)
{
e.Handled = true;
this.TextBoxIDCard.Focus();
textBoxIDCardGotFocus = true;
}
}
#endregion
When creating AVD,
Now, after creating the AVD, you should see the google play icon .
You can create your own JSONObject
then toString()
.
Remember run it in the background thread like doInBackground
in AsyncTask
.
OkHttp version > 4:
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
val client = OkHttpClient()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jsonObject.toString().toRequestBody(mediaType)
val request: Request = Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build()
var response: Response? = null
try {
response = client.newCall(request).execute()
val resStr = response.body!!.string()
} catch (e: IOException) {
e.printStackTrace()
}
OkHttp version 3:
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// put your json here
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String resStr = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
PHP syntax is little different in case of concatenation from JavaScript.
Instead of (+) plus
a (.) period
is used for string concatenation.
<?php
$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
$selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
$selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;
?>
I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.
There is an interesting point you need to catch about csv.reader() object. The csv.reader object is not list
type, and not subscriptable.
This works:
for r in csv.reader(file_obj): # file not closed
print r
This does not:
r = csv.reader(file_obj)
print r[0]
So, you first have to convert to list type in order to make the above code work.
r = list( csv.reader(file_obj) )
print r[0]
I got this error for multi-threading scenario (specifically when dealing with ZMQ). It turned out that socket was still being connected on one thread while another thread already started sending data. The events that occured due to another thread tried to access variables that weren't created yet. If your scenario involves multi-threading and if things work if you add bit of delay then you might have similar issue.
You need debounce!
Here is a jQuery plugin, and here is all you need to know about debounce. If you are coming here from Google and Underscore has found its way into the JSoup of your app, it has debounce baked right in!
Thanks for the question. For YouTube iframe the first issue is the URL you have given, is it embedded URL or URL link from address bar. this error for non embed URL but if you want to give non embed URL then you need to code in "safe Pipe" like(for both non embedded or embed URL ) :
import {Pipe, PipeTransform} from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';
@Pipe({name: 'safe'})
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {
}
transform(value: any, url: any): any {
if (value && !url) {
const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
let match = value.match(regExp);
if (match && match[2].length == 11) {
console.log(match[2]);
let sepratedID = match[2];
let embedUrl = '//www.youtube.com/embed/' + sepratedID;
return this.sanitizer.bypassSecurityTrustResourceUrl(embedUrl);
}
}
}
}
it will split out "vedioId". You have to get video id then set to URL as embedded. In Html
<div>
<iframe width="100%" height="300" [src]="video.url | safe"></iframe>
</div>
Angular 2/5 thanks again.
It happened with me when I was using Databinding for Activity and Fragments.
For fragment - in onCreateView we can inflate the layout in traditional way using inflater. and in onViewCreated method, binding object can be updated as
binding = DataBindingUtil.getBinding<FragmentReceiverBinding>(view) as FragmentReceiverBinding
It solved my issue
@echo off
echo somethink
echo Press enter to exit
set /p input=
To find all local IPv4 addresses:
IPAddress[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
a => a.AddressFamily == AddressFamily.InterNetwork);
or use Array.Find
or Array.FindLast
if you just want one.
If you are planning to get the image from its path, it's better to use Assets instead of trying to figure out the path of the drawable folder.
InputStream stream = getAssets().open("image.png");
Drawable d = Drawable.createFromStream(stream, null);
The accepted answer calls the draw
function twice. I can't see why that would be needed. In fact, if your new data has the same columns as the old data, you can accomplish this in one line:
datatable.clear().rows.add(newData).draw();
SELECT t1.a, t2.b
FROM t1
JOIN t2 ON t1.a LIKE '%'+t2.b +'%'
because the last answer not work
You can do that with StringUtils
(from Apache Commons Lang). It avoids index-magic, so it's easier to understand. Unfortunately substringAfterLast
returns empty string when there is no separator in the input string so we need the if
statement for that case.
public static String getLastWord(String input) {
String wordSeparator = " ";
boolean inputIsOnlyOneWord = !StringUtils.contains(input, wordSeparator);
if (inputIsOnlyOneWord) {
return input;
}
return StringUtils.substringAfterLast(input, wordSeparator);
}
The reason the code isn't working is because lastrow is measured from whatever sheet is currently active, and "A:A500" (or other number) is not a valid range reference.
Private Sub CommandButton1_Click()
Dim lastrow As Long
lastrow = Sheets("Summary Info").Range("A65536").End(xlUp).Row ' or + 1
Range("A3:E3").Copy Destination:=Sheets("Summary Info").Range("A" & lastrow)
End Sub
So here is my solution (similar to John Vance's answer):
First go here and get a function to detect mobile browsers.
http://detectmobilebrowsers.com/
They have a lot of different ways to detect if you are on mobile, so find one that works with what you are using.
Your HTML page (pseudo code):
If Mobile Then
<input id="selling-date" type="date" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />
else
<input id="selling-date" type="text" class="date-picker" readonly="readonly" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />
JQuery:
$( ".date-picker" ).each(function() {
var min = $( this ).attr("min");
var max = $( this ).attr("max");
$( this ).datepicker({
dateFormat: "yy-mm-dd",
minDate: min,
maxDate: max
});
});
This way you can still use native date selectors in mobile while still setting the min and max dates either way.
The field for non mobile should be read only because if a mobile browser like chrome for ios "requests desktop version" then they can get around the mobile check and you still want to prevent the keyboard from showing up.
However if the field is read only it could look to a user like they cant change the field. You could fix this by changing the CSS to make it look like it isn't read only (ie change border-color to black) but unless you are changing the CSS for all input tags you will find it hard to keep the look consistent across browsers.
To get arround that I just add a calendar image button to the date picker. Just change your JQuery code a bit:
$( ".date-picker" ).each(function() {
var min = $( this ).attr("min");
var max = $( this ).attr("max");
$( this ).datepicker({
dateFormat: "yy-mm-dd",
minDate: min,
maxDate: max,
showOn: "both",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
buttonText: "Select date"
});
});
Note: you will have to find a suitable image.
var a = A.parentNode.replaceChild(document.createElement("span"), A);
a is the replaced A element.
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
/**********************************************************************
Naziv procedure : sp_rfv_FIND
Ime i prezime autora: Srdjan Nadrljanski
Datum kreiranja : 13.06.2013.
Namena : Traži sql objekat na celom serveru
Tabele :
Ulazni parametri :
Izlazni parametri :
Datum zadnje izmene :
Opis izmene :
exec sp_rfv_FIND 'TUN',''
**********************************************************************/
CREATE PROCEDURE [dbo].[sp_rfv_FIND] ( @SEARCHSTRING VARCHAR(255),
@notcontain Varchar(255)
)
AS
declare @text varchar(1500),@textinit varchar (1500)
set @textinit=
'USE @sifra
insert into ##temp2
select ''@sifra''as dbName,a.[Object Name],a.[Object Type]
from(
SELECT DISTINCT sysobjects.name AS [Object Name] ,
case
when sysobjects.xtype = ''C'' then ''CHECK constraint''
when sysobjects.xtype = ''D'' then ''Default or DEFAULT constraint''
when sysobjects.xtype = ''F'' then ''Foreign Key''
when sysobjects.xtype = ''FN'' then ''Scalar function''
when sysobjects.xtype = ''P'' then ''Stored Procedure''
when sysobjects.xtype = ''PK'' then ''PRIMARY KEY constraint''
when sysobjects.xtype = ''S'' then ''System table''
when sysobjects.xtype = ''TF'' then ''Function''
when sysobjects.xtype = ''TR'' then ''Trigger''
when sysobjects.xtype = ''U'' then ''User table''
when sysobjects.xtype = ''UQ'' then ''UNIQUE constraint''
when sysobjects.xtype = ''V'' then ''View''
when sysobjects.xtype = ''X'' then ''Extended stored procedure''
end as [Object Type]
FROM sysobjects
WHERE
sysobjects.type in (''C'',''D'',''F'',''FN'',''P'',''K'',''S'',''TF'',''TR'',''U'',''V'',''X'')
AND sysobjects.category = 0
AND CHARINDEX(''@SEARCHSTRING'',sysobjects.name)>0
AND ((CHARINDEX(''@notcontain'',sysobjects.name)=0 or
CHARINDEX(''@notcontain'',sysobjects.name)<>0))
)a'
set @textinit=replace(@textinit,'@SEARCHSTRING',@SEARCHSTRING)
set @textinit=replace(@textinit,'@notcontain',@notcontain)
SELECT name AS dbName,cast(null as varchar(255)) as ObjectName,cast(null as varchar(255)) as ObjectType
into ##temp1
from master.dbo.sysdatabases order by name
SELECT * INTO ##temp2 FROM ##temp1 WHERE 1 = 0
declare @sifra VARCHAR(255),@suma int,@brojac int
set @suma=(select count(dbName) from ##temp1)
DECLARE c_k CURSOR LOCAL FAST_FORWARD FOR
SELECT dbName FROM ##temp1 ORDER BY dbName DESC
OPEN c_k
FETCH NEXT FROM c_K INTO @sifra
SET @brojac = 1
WHILE (@@fetch_status = 0 ) AND (@brojac <= @suma)
BEGIN
set @text=replace(@textinit,'@sifra',@sifra)
exec (@text)
SET @brojac = @brojac +1
DELETE FROM ##temp1 WHERE dbName = @sifra
FETCH NEXT FROM c_k INTO @sifra
END
close c_k
DEALLOCATE c_k
select * from ##temp2
order by dbName,ObjectType
drop table ##temp2
drop table ##temp1
I believe this is what you want:
table.groupby('YEARMONTH').CLIENTCODE.nunique()
Example:
In [2]: table
Out[2]:
CLIENTCODE YEARMONTH
0 1 201301
1 1 201301
2 2 201301
3 1 201302
4 2 201302
5 2 201302
6 3 201302
In [3]: table.groupby('YEARMONTH').CLIENTCODE.nunique()
Out[3]:
YEARMONTH
201301 2
201302 3
public class UserCustomAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
ArrayList<User> data = new ArrayList<User>();
public UserCustomAdapter(Context context, int layoutResourceId,
ArrayList<User> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textName = (TextView) row.findViewById(R.id.textView1);
holder.textAddress = (TextView) row.findViewById(R.id.textView2);
holder.textLocation = (TextView) row.findViewById(R.id.textView3);
holder.btnEdit = (Button) row.findViewById(R.id.button1);
holder.btnDelete = (Button) row.findViewById(R.id.button2);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
User user = data.get(position);
holder.textName.setText(user.getName());
holder.textAddress.setText(user.getAddress());
holder.textLocation.setText(user.getLocation());
holder.btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Edit button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
return row;
}
static class UserHolder {
TextView textName;
TextView textAddress;
TextView textLocation;
Button btnEdit;
Button btnDelete;
}
}
Hey Please have a look here-
I have same answer here on my blog ..
This may work:
public override bool IsValid(DateTime value)
{
_dateOfBirth = value;
var yearsOld = (double) (DateTime.Now.Subtract(_dateOfBirth).TotalDays/365);
if (yearsOld > 18)
return true;
return false;
}
Email tech support at your client's hosting provider and ask for the information.
Here's a correction to Mehdiway's answer. The new width and/or height were not being set to the max value. A good test case is the following (1768 x 1075 pixels): http://spacecoastsports.com/wp-content/uploads/2014/06/sportsballs1.png. (I wasn't able to comment on it above due to lack of reputation points.)
// Make sure image doesn't exceed 100x100 pixels
// note: takes jQuery img object not HTML: so width is a function
// not a property.
function resize_image (image) {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var ratio = 0; // Used for aspect ratio
// Get current dimensions
var width = image.width()
var height = image.height();
console.log("dimensions: " + width + "x" + height);
// If the current width is larger than the max, scale height
// to ratio of max width to current and then set width to max.
if (width > maxWidth) {
console.log("Shrinking width (and scaling height)")
ratio = maxWidth / width;
height = height * ratio;
width = maxWidth;
image.css("width", width);
image.css("height", height);
console.log("new dimensions: " + width + "x" + height);
}
// If the current height is larger than the max, scale width
// to ratio of max height to current and then set height to max.
if (height > maxHeight) {
console.log("Shrinking height (and scaling width)")
ratio = maxHeight / height;
width = width * ratio;
height = maxHeight;
image.css("width", width);
image.css("height", height);
console.log("new dimensions: " + width + "x" + height);
}
}
I uninstalled my Node.js and showed hidden files.
Then, I went to C:\Users\yourpcname\AppData\Roaming\
and deleted the npm
and npm-cache
folders.
Finally, I installed a new version of Node.js.
I found a new error code which is not documented above: CFNetworkErrorCode -1022
Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection."
You can set the default search_path
at the database level:
ALTER DATABASE <database_name> SET search_path TO schema1,schema2;
Or at the user or role level:
ALTER ROLE <role_name> SET search_path TO schema1,schema2;
Or if you have a common default schema in all your databases you could set the system-wide default in the config file with the search_path option.
When a database is created it is created by default from a hidden "template" database named template1, you could alter that database to specify a new default search path for all databases created in the future. You could also create another template database and use CREATE DATABASE <database_name> TEMPLATE <template_name>
to create your databases.
As far as you're concerned once you've "pulled out" the contents with something like .html() it's just a string. You can test that with
<html>
<head>
<title>runthis</title>
<script type="text/javascript" language="javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready( function() {
var x = $("#foo").html();
alert( typeof(x) );
});
</script>
</head>
<body>
<div id="foo"><table><tr><td>x</td></tr></table><span>xyz</span></div>
</body>
</html>
The alert text is string. As long as you don't pass it to a parser there's no magic about it, it's a string like any other string.
There's nothing that hinders you from using .post() to send this string back to the server.
edit: Don't pass a string as the parameter data to .post() but an object, like
var data = {
id: currid,
html: div_html
};
$.post("http://...", data, ...);
jquery will handle the encoding of the parameters.
If you (for whatever reason) want to keep your string you have to encode the values with something like escape().
var data = 'id='+ escape(currid) +'&html='+ escape(div_html);
This SQL request works for me :
ALTER TABLE users
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT ;
From here:
http://www.christianengvall.se/undo-pushed-merge-git/
git revert -m 1 <merge commit hash>
Git revert adds a new commit that rolls back the specified commit.
Using -m 1 tells it that this is a merge and we want to roll back to the parent commit on the master branch. You would use -m 2 to specify the develop branch.
If you use jQuery you can do this with scrollTop
#modal {_x000D_
bottom: 0;_x000D_
position: fixed;_x000D_
overflow-y: scroll;_x000D_
overflow-x: hidden;_x000D_
top: 0;_x000D_
width: 100%;_x000D_
}
_x000D_
$('.open-modal').click(function (e) {_x000D_
e.preventDefault();_x000D_
$('#modal').toggle();_x000D_
scrollTo = $('body').scrollTop();_x000D_
$('body').css("position", "fixed");_x000D_
});_x000D_
_x000D_
$('.close-modal').click(function (e) {_x000D_
e.preventDefault();_x000D_
$('#modal').toggle();_x000D_
$('body').css("position", "static");_x000D_
$('body').animate({scrollTop: scrollTo}, 0);_x000D_
});
_x000D_
Please see the python shell script which has been executed in sequence, here you will get the attributes of a class in string format separated by comma.
>>> class new_class():
... def __init__(self, number):
... self.multi = int(number)*2
... self.str = str(number)
...
>>> a = new_class(4)
>>> ",".join(a.__dict__.keys())
'str,multi'<br/>
I am using python 3.4
Async/Await with axios
useEffect(() => {
const getData = async () => {
await axios.get('your_url')
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
});
}
getData()
}, [])
You can compose all the functions into one and call them.Libraries like Ramdajs has a function to compose multiple functions into one.
<a href="#" onclick="R.compose(fn1,fn2,fn3)()">Click me To fire some functions</a>
or you can put the composition as a seperate function in js file and call it
const newFunction = R.compose(fn1,fn2,fn3);
<a href="#" onclick="newFunction()">Click me To fire some functions</a>
I'd say the code you need is:
test = input("enter the test")
print(test)
Otherwise it shouldn't run at all, due to a syntax error. The print
function requires brackets in python 3. I cannot reproduce your error, though. Are you sure it's those lines causing that error?
If you want to do it from code behind, try this:
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Message');", true);
I'm using Visual Studio 2019. I used the shortcut below:
Shift + Insert
The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
If you would like to use System.Data instead of System.LINQ, then you can do something like this.
List<string> BrandsInDataTable = new List<string>();
DataTable g = Access._ME_G_BrandsInPop();
if (g.Rows.Count > 0)
{
for (int x = 0; x < g.Rows.Count; x++)
BrandsInDataTable.Add(g.Rows[x]["Name"].ToString());
}
else return;
No. You can't send headers after they were sent. Try to use hooks in wordpress
Modified!
SELECT distinct contract, activity from @t a
WHERE (SELECT COUNT(DISTINCT activity) FROM @t b WHERE b.contract = a.contract) = 1
And here's another one -- shorter/cleaner without subquery
select contract, max(activity) from @t
group by contract
having count(distinct activity) = 1
Delete rows from dbo_MigrationHistory table or delete the table and run
update-database -verbose
It will run all the migrations in your project one by one
in HQL you can use query parameter and set Collection with setParameterList method.
Query q = session.createQuery("SELECT entity FROM Entity entity WHERE name IN (:names)");
q.setParameterList("names", names);
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
Try this:
ls -l | awk -F : '{sum+=$5} END {print "AVG=",sum/NR}'
NR is an AWK builtin variable to count the no. of records
I not be able to find squid number in sonar 5.6, with this annotation also works:
@SuppressWarnings({"pmd:AvoidCatchingGenericException", "checkstyle:com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheck"})
window.location.href.slice(window.location.href.indexOf('?') + 1);
it is better to use json after post your resuest like below
var clien = new RestClient("https://smple.com/");
var request = new RestRequest("index", Method.POST);
request.AddHeader("Sign", signinstance);
request.AddJsonBody(JsonConvert.SerializeObject(yourclass));
var response = client.Execute<YourReturnclassSample>(request);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
{
return Ok(response.Content);
}
One 'elegant' solution would be to use full text search: http://www.postgresql.org/docs/9.0/interactive/textsearch.html. Then you would use full text search queries.
In order to create a .jar file, you need to use jar
instead of java
:
jar cf myJar.jar myClass.class
Additionally, if you want to make it executable, you need to indicate an entry point (i.e., a class with public static void main(String[] args)
) for your application. This is usually accomplished by creating a manifest file that contains the Main-Class
header (e.g., Main-Class: myClass
).
However, as Mark Peters pointed out, with JDK 6, you can use the e
option to define the entry point:
jar cfe myJar.jar myClass myClass.class
Finally, you can execute it:
java -jar myJar.jar
Though I upvoted the answer marked as correct. I wanted to touch on a few things for anyone stumbling upon this.
In general, if you're filtering specifically on Date values alone. Microsoft recommends using the language neutral format of ymd
or y-m-d
.
Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.
To do a date comparison using the aforementioned approach is simple. Consider the following, contrived example.
--112 is ISO format 'YYYYMMDD'
declare @filterDate char(8) = CONVERT(char(8), GETDATE(), 112)
select
*
from
Sales.Orders
where
CONVERT(char(8), OrderDate, 112) = @filterDate
In a perfect world, performing any manipulation to the filtered column should be avoided because this can prevent SQL Server from using indexes efficiently. That said, if the data you're storing is only ever concerned with the date and not time, consider storing as DATETIME
with midnight as the time. Because:
When SQL Server converts the literal to the filtered column’s type, it assumes midnight when a time part isn’t indicated. If you want such a filter to return all rows from the specified date, you need to ensure that you store all values with midnight as the time.
Thus, assuming you are only concerned with date, and store your data as such. The above query can be simplified to:
--112 is ISO format 'YYYYMMDD'
declare @filterDate char(8) = CONVERT(char(8), GETDATE(), 112)
select
*
from
Sales.Orders
where
OrderDate = @filterDate
I had the same problem (on Linux) which could be solved changing the proxy settings.
If you are behind a proxy server check the configuration using Sys.getenv("http_proxy")
within R.
In my ~/.Renviron
I had the following lines (from https://support.rstudio.com/hc/en-us/articles/200488488-Configuring-R-to-Use-an-HTTP-or-HTTPS-Proxy) causing the problem:
http_proxy=https://proxy.dom.com:port
http_proxy_user=user:passwd
Changing it to
http_proxy="http://user:[email protected]:port"
solved the problem. You can do the same for https
.
It was not the first thought when I read "package xxx is not available for r version-x-y-z" ...
HTH
This error just means that myapp.views.home
is not something that can be called, like a function. It is a string in fact. While your solution works in django 1.9, nevertheless it throws a warning saying this will deprecate from version 1.10 onwards, which is exactly what has happened. The previous solution by @Alasdair imports the necessary view functions into the script through either
from myapp import views as myapp_views
or
from myapp.views import home, contact
One of the first differences that I can recall from top of my head are multiple domains running in the same server, partial resource retrieval, this allows you to retrieve and speed up the download of a resource (it's what almost every download accelerator does).
If you want to develop an application like a website or similar, you don't need to worry too much about the differences but you should know the difference between GET
and POST
verbs at least.
Now if you want to develop a browser then yes, you will have to know the complete protocol as well as if you are trying to develop a HTTP server.
If you are only interested in knowing the HTTP protocol I would recommend you starting with HTTP/1.1 instead of 1.0.
Try:
#!/bin/bash
if [ "$#" -eq "0" ]
then
echo "No arguments supplied"
else
echo "Hello world"
fi
You just need to install Android development kit from http://developer.android.com/sdk/installing/studio.html#Updating
and also Download and install Java JDK (Choose the Java platform)
define the environment variable in windows System setting https://confluence.atlassian.com/display/DOC/Setting+the+JAVA_HOME+Variable+in+Windows
Voila ! You are Donezo !
First of all you need to understand that final output of both the statements will be same i.e. to remove all the spaces from given string.
However x.replaceAll("\\s+", "");
will be more efficient way of trimming spaces (if string can have multiple contiguous spaces) because of potentially less no of replacements due the to fact that regex \\s+
matches 1 or more spaces at once and replaces them with empty string.
So even though you get the same output from both it is better to use:
x.replaceAll("\\s+", "");
Try something like this
document.getElementById("vid-holder").style.width=300 + "px";
Either set $/
to undef
(see jrockway's answer) or just concatenate all the file's lines:
$content = join('', <$fh>);
It's recommended to use scalars for filehandles on any Perl version that supports it.
Did you, by any chance, deleted stuff from your workspace, or moved it around?
When you create a server for the first time, either globally or through the project's "run on server" settings, Eclipse creates a project in the Servers view, as BalusC pointed out. Eclipse stores this server inside your workspace, in a project called Servers. The project needs to be open for tomcat to run.
(If you want, you can store the server settings elsewher. You can right click and open the server instance from the Servers view and configure various parameters and locations)
You have two options, a PL/SQL block or SQL*Plus bind variables:
var z number
execute my_stored_proc (-1,2,0.01,:z)
print z
JWPL - Java-based Wikipedia Library -- An application programming interface for Wikipedia
I Got AutoFlash light with below simple Three Steps.
<uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> <uses-permission android:name="android.permission.FLASHLIGHT"/> <uses-feature android:name="android.hardware.camera.flash" android:required="false" />
In your Camera Code do this way.
//Open Camera
Camera mCamera = Camera.open();
//Get Camera Params for customisation
Camera.Parameters parameters = mCamera.getParameters();
//Check Whether device supports AutoFlash, If you YES then set AutoFlash
List<String> flashModes = parameters.getSupportedFlashModes();
if (flashModes.contains(android.hardware.Camera.Parameters.FLASH_MODE_AUTO))
{
parameters.setFlashMode(Parameters.FLASH_MODE_AUTO);
}
mCamera.setParameters(parameters);
mCamera.startPreview();
Build + Run —> Now Go to Dim light area and Snap photo, you should get auto flash light if device supports.
They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.
Two steps worked for me : - going Macintosh HD > Applications > Python3.7 folder - click on "Install Certificates.command"
First, let's clear up some terminology: "asynchronous" (async
) means that it may yield control back to the calling thread before it starts. In an async
method, those "yield" points are await
expressions.
This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".
To futher confuse the issue, async
is very different than "awaitable"; there are some async
methods whose return types are not awaitable, and many methods returning awaitable types that are not async
.
Enough about what they aren't; here's what they are:
async
keyword allows an asynchronous method (that is, it allows await
expressions). async
methods may return Task
, Task<T>
, or (if you must) void
.Task
and Task<T>
.So, if we reformulate your question to "how can I run an operation on a background thread in a way that it's awaitable", the answer is to use Task.Run
:
private Task<int> DoWorkAsync() // No async because the method does not need await
{
return Task.Run(() =>
{
return 1 + 2;
});
}
(But this pattern is a poor approach; see below).
But if your question is "how do I create an async
method that can yield back to its caller instead of blocking", the answer is to declare the method async
and use await
for its "yielding" points:
private async Task<int> GetWebPageHtmlSizeAsync()
{
var client = new HttpClient();
var html = await client.GetAsync("http://www.example.com/");
return html.Length;
}
So, the basic pattern of things is to have async
code depend on "awaitables" in its await
expressions. These "awaitables" can be other async
methods or just regular methods returning awaitables. Regular methods returning Task
/Task<T>
can use Task.Run
to execute code on a background thread, or (more commonly) they can use TaskCompletionSource<T>
or one of its shortcuts (TaskFactory.FromAsync
, Task.FromResult
, etc). I don't recommend wrapping an entire method in Task.Run
; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a Task.Run
:
private int DoWork()
{
return 1 + 2;
}
private void MoreSynchronousProcessing()
{
// Execute it directly (synchronously), since we are also a synchronous method.
var result = DoWork();
...
}
private async Task DoVariousThingsFromTheUIThreadAsync()
{
// I have a bunch of async work to do, and I am executed on the UI thread.
var result = await Task.Run(() => DoWork());
...
}
I have an async
/await
intro on my blog; at the end are some good followup resources. The MSDN docs for async
are unusually good, too.
The multi-column index can be used for queries referencing all the columns:
SELECT *
FROM TableName
WHERE Column1=1 AND Column2=2 AND Column3=3
This can be looked up directly using the multi-column index. On the other hand, at most one of the single-column index can be used (it would have to look up all records having Column1=1, and then check Column2 and Column3 in each of those).
EDIT: As pointed out in recent comments, this solution may BREAK your system.
You most likely don't want to remove python3.
Please refer to the other answers for possible solutions.
Outdated answer (not recommended)
sudo apt-get remove 'python3.*'
Looking at :help tabs it doesn't look like vim wants to work the way you do...
Buffers are shared across tabs, so it doesn't seem possible to lock a given buffer to appear only on a certain tab.
It's a good idea, though.
You could probably get the effect you want by using a terminal that supports tabs, like multi-gnome-terminal, then running vim instances in each terminal tab. Not perfect, though...
Two Alternative Options:
Fix 1
@singleton pointed me in this direction. Instead of changing the target in Visual Studio you should change it in Unity since the project is auto-generated.
First delete the auto generated Visual Studio files: .csproj .user .sln
Then from within Unity go to PlayerSettings and under 'Other Settings' change the 'Scripting Runtime Version' from Stable 3.5 to Experimental 4.6.
However, that didn't fix it for me.
Fix 2
I noticed all of the references to Unity related code was marked with a yellow warning. Check your error logs and see if this is the case. In particular see if you get the following error: getreferenceNearestTargetframeworkTask
If so try: Start Visual Studio Installer again.
On the Build Tools 2017, click Modify,
Ensure that "Nuget targets and build tasks" are ticked. This should become ticked if you click on Universal Windows Platform development.
In addition to Idriss answer:
In CSS we write code as depicted bellow, in full length.
body{
width: 800px;
color: #ffffff;
}
body content{
width:750px;
background:#ffffff;
}
In SCSS we can shorten this code using a @mixin
so we don’t have to write color
and width
properties again and again. We can define this through a function, similarly to PHP or other languages.
$color: #ffffff;
$width: 800px;
@mixin body{
width: $width;
color: $color;
content{
width: $width;
background:$color;
}
}
In SASS however, the whole structure is visually quicker and cleaner than SCSS.
It seems that it doesn't support inline CSS currently.
$color: #ffffff
$width: 800px
$stack: Helvetica, sans-serif
body
width: $width
color: $color
font: 100% $stack
content
width: $width
background:$color
you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"')
,if you want to know more detail, please refer to $sce
This is a simpler one
$('#some_select_box').find('option:selected').remove().end();
Assuming your Data frame is like 'Data' you have to consider if your data is a string or an integer. Both are treated differently. So in this case you need be specific about that.
import pandas as pd
data = [('001','xxx'), ('002','xxx'), ('003','xxx'), ('004','xxx'), ('005','xxx')]
df = pd.DataFrame(data,columns=['issueid', 'industry'])
print("Old DataFrame")
print(df)
df.loc[:,'industry'] = str('yyy')
print("New DataFrame")
print(df)
Now if want to put numbers instead of letters you must create and array
list_of_ones = [1,1,1,1,1]
df.loc[:,'industry'] = list_of_ones
print(df)
Or if you are using Numpy
import numpy as np
n = len(df)
df.loc[:,'industry'] = np.ones(n)
print(df)
Call After would be a better name than the stupid name, callback. When or if condition gets met within a function, call another function, the Call After function, the one received as argument.
Rather than hard-code an inner function within a function, one writes a function to accept an already-written Call After function as argument. The Call After might get called based on state changes detected by code in the function receiving the argument.
Something like:
clients.stream.filter(c->{
users.stream.filter(u->u.getName().equals(c.getName()).count()>0
}).collect(Collectors.toList());
This is however not an awfully efficient way to do it. Unless the collections are very small, you will be better of building a set of user names and using that in the condition.
Hey, What you can do is apply a fixed width to both the containers and then use another div class where clear:both, like
div#left {
width: 600px;
float: left;
}
div#right {
width: 240px;
float: right;
}
div.clear {
clear:both;
}
place a the clear div under left and right container.
create view view_clients_credit_usage as
select client_id, sum(credits_used) as credits_used
from credit_usage
group by client_id
create view view_credit_status as
select
credit_orders.client_id,
sum(credit_orders.number_of_credits) as purchased,
ifnull(t1.credits_used,0) as used
from credit_orders
left outer join view_clients_credit_usage as t1 on t1.client_id = credit_orders.client_id
where credit_orders.payment_status='Paid'
group by credit_orders.client_id)
There are probably embedded tabs (CHAR(9)
) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:
DECLARE @var NVARCHAR(255), @i INT;
SET @i = 1;
SELECT @var = AccountType FROM dbo.Account
WHERE AccountNumber = 200
AND AccountType LIKE '%Daily%';
CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));
WHILE @i <= LEN(@var)
BEGIN
INSERT #x
SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));
SET @i = @i + 1;
END
SELECT i,c,a FROM #x ORDER BY i;
You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.
Under Linux, What worked for me was John Anderson's (sontek) guide, which you can find at this link. However, I cheated and just used his easy configuration setup from his Git repostiory:
git clone -b vim https://github.com/sontek/dotfiles.git
cd dotfiles
./install.sh vim
His configuration is fairly up to date as of today.
Git clone is the command you're looking for:
git clone [email protected]:username/repo.git
Update: And this is the official guide: https://help.github.com/articles/fork-a-repo
Take a look at: https://help.github.com/
It has really useful content
I use div by adding contenteditable true instead of using textarea.
Hope can help you.
$("#your_textarea").on('keydown', function(e){//textarea keydown events
if(e.key == "Enter")
{
if(e.shiftKey)//jump new line
{
// do nothing
}
else // do sth,like send message or else
{
e.preventDefault();//cancell the deafult events
}
}
})
According to the docs:
A variable or parameter whose value is never changed after it is initialized is effectively final.
Basically, if the compiler finds a variable does not appear in assignments outside of its initialization, then the variable is considered effectively final.
For example, consider some class:
public class Foo {
public void baz(int bar) {
// While the next line is commented, bar is effectively final
// and while it is uncommented, the assignment means it is not
// effectively final.
// bar = 2;
}
}
I had a broken symlink to node_modules in a subfolder
When you install Entity Framework 6 through Nuget
. EntityFramework.SqlServer sometime miss for another executable. Simply add the Nuget
package to that project.
Sometimes above does not work for Test Project
To solve this issue in Test Project just place this Method inside Test Project:
public void FixEfProviderServicesProblem()
{
var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
}
This method is never been called, but as my observations, the compiler will remove all "unnecessary" assemblies and without using the EntityFramework.SqlServer
stuff the test fails.
When using JOIN
against an entity associations, JPA will generate a JOIN between the parent entity and the child entity tables in the generated SQL statement.
So, taking your example, when executing this JPQL query:
FROM Employee emp
JOIN emp.department dep
Hibernate is going to generate the following SQL statement:
SELECT emp.*
FROM employee emp
JOIN department dep ON emp.department_id = dep.id
Note that the SQL
SELECT
clause contains only theemployee
table columns, and not thedepartment
ones. To fetch thedepartment
table columns, we need to useJOIN FETCH
instead ofJOIN
.
So, compared to JOIN
, the JOIN FETCH
allows you to project the joining table columns in the SELECT
clause of the generated SQL statement.
So, in your example, when executing this JPQL query:
FROM Employee emp
JOIN FETCH emp.department dep
Hibernate is going to generate the following SQL statement:
SELECT emp.*, dept.*
FROM employee emp
JOIN department dep ON emp.department_id = dep.id
Note that, this time, the
department
table columns are selected as well, not just the ones associated with the entity listed in theFROM
JPQL clause.
Also, JOIN FETCH
is a great way to address the LazyInitializationException
when using Hibernate as you can initialize entity associations using the FetchType.LAZY
fetching strategy along with the main entity you are fetching.
For those who use the RecyclerView
within a fragment and inflate it from other views: when inflating the whole fragment view, make sure that you bind the RecyclerView
to its root view.
I was connecting and doing everything for the adapter correctly, but I never did the binding. This answer by @Prateek Agarwal has it all for me, but here is more elaboration.
Kotlin
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater?.inflate(R.layout.fragment_layout, container, false)
recyclerView = rootView?.findViewById(R.id.recycler_view_id)
// rest of my stuff
recyclerView?.setHasFixedSize(true)
recyclerView?.layoutManager = viewManager
recyclerView?.adapter = viewAdapter
// return the root view
return rootView
}
Java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView= inflater.inflate(R.layout.fragment_layout,container,false);
recyclerview= rootView.findViewById(R.id.recycler_view_id);
return rootView;
}
file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
file.write("This will be added to the next line\n")
or
log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")
When you use a TemplateField and bind literal text to it like you are doing, asp.net will actually insert a control FOR YOU! It gets put into a DataBoundLiteralControl. You can see this if you look in the debugger near your line of code that is getting the empty text.
So, to access the information without changing your template to use a control, you would cast like this:
string percentage = ((DataBoundLiteralControl)e.Row.Cells[7].Controls[0]).Text;
That will get you your text!
date +"%T.%N"
returns the current time with nanoseconds.
06:46:41.431857000
date +"%T.%6N"
returns the current time with nanoseconds rounded to the first 6 digits, which is microseconds.
06:47:07.183172
date +"%T.%3N"
returns the current time with nanoseconds rounded to the first 3 digits, which is milliseconds.
06:47:42.773
In general, every field of the date
command's format can be given an optional field width.
You can use header to send the right Content-type :
header('Content-Type: ' . $type);
And readfile
to output the content of the image :
readfile($file);
And maybe (probably not necessary, but, just in case) you'll have to send the Content-Length header too :
header('Content-Length: ' . filesize($file));
Note : make sure you don't output anything else than your image data (no white space, for instance), or it will no longer be a valid image.
What about
ls {*.py,*.html}
It lists out all the files ending with .py or .html in their filenames
The previous answers show 3 approaches
Let me show #4 approach "By using "cbind" and "rename" that works for my case
df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
new_column = c(0, 0, 0)
df <- cbind(new_column, df)
colnames(df)[1] <- "a"
I was having issues because I updated my AdHoc provisioning profile with some new devices for use on TestFlight. Assumedly this is happening because Xcode has an old reference to your provisioning profile in either the codesigning build settings for the project or the targets. The way I fixed mine was to:
count the carriage returns/line feeds. I believe in unicode they are still 0x000D and 0x000A respectively. that way you can be as efficient or as inefficient as you want, and decide if you have to deal with both characters or not
The code below also solves otherwise
.on("change", function(e) {
var lastValue = e.currentTarget.value;
var lastText = e.currentTarget.textContent;
});
Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec
Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec
, as I have ~/bin
in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...
Launch it from the root of your project, where you can see src and target dirs.
The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)
$ mvnexec
1) org.jmeld.ui.JMeldComponent
2) org.jmeld.ui.text.FileDocument
3) org.jmeld.JMeld
4) org.jmeld.util.UIDefaultsPrint
5) org.jmeld.util.PrintProperties
6) org.jmeld.util.file.DirectoryDiff
7) org.jmeld.util.file.VersionControlDiff
8) org.jmeld.vc.svn.InfoCmd
9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#?
If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P
)
By default it compiles project every run. but you can avoid that using mvnexec -B
It allows to search only in test classes -M
or --no-main
, or only in main classes -T
or --no-test
. also has a filter by name option -f <whatever>
Hope this could save you some time, for me it does.
can you try to run svn checkout
once manually to your URL https://yoururl/trunk C:\ant-1.8.1\Test_Checkout
using command line
and accept certificate.
Or as @AndrewSpear says below
Rather than checking out manually run svn list https://your.repository.url
from Terminal (Mac) / Command Line (Win) to get the option to accept the certificate permanently
svn will ask you for confirmation. accept it permanently.
After that this should work for subsequent requests from ant script.
I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).
If you have configured ssh key to connect to your remote server, you could use the following command:
rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/
Where v
option is --verbose
, a
option is --archive
- archive mode, P
option same as --partial
- keep partially transferred files, e
option is --rsh=COMMAND
- specifying the remote shell to use.
There could be many reason why document.getElementById
doesn't work
You have an invalid ID
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (resource: What are valid values for the id attribute in HTML?)
you used some id that you already used as <meta>
name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at
(resource: http://www.phpied.com/getelementbyid-description-in-ie/)
you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument
before looking for the element
(resource: Calling a specific id inside a frame)
you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling
I doubt you used same ID twice or more: in that case document.getElementById
should return at least the first element
That selects the row number per country code, account, and currency. So, the rows with country code "US", account "XYZ" and currency "$USD" will each get a row number assigned from 1-n; the same goes for every other combination of those columns in the result set.
This query is kind of funny, because the order by clause does absolutely nothing. All the rows in each partition have the same country code, account, and currency, so there's no point ordering by those columns. The ultimate row numbers assigned in this particular query will therefore be unpredictable.
Hope that helps...
You could also use the linux sh
command and pass it a command that includes the redirection:
string cmd = "/bin/ls > " + filepath;
execl("/bin/sh", "sh", "-c", cmd.c_str(), 0);
<input type="text" id="txtCode" name="name" class="text_cs">
and js:
<script type="text/javascript">
$('.text_cs').on('change', function () {
var pid = $(this).val();
console.log("Value text: " + pid);
});
</script>
There is now a beta available of Google Maps KML Importing Utility.
It is part of the Google Maps Android API Utility Library. As documented it allows loading KML files from streams
KmlLayer layer = new KmlLayer(getMap(), kmlInputStream, getApplicationContext());
or local resources
KmlLayer layer = new KmlLayer(getMap(), R.raw.kmlFile, getApplicationContext());
After you have created a KmlLayer, call addLayerToMap() to add the imported data onto the map.
layer.addLayerToMap();
You can use PowerShell as well; this is what I did. As I needed to download a file based on a pattern I dynamically created a command file and then let ftp
do the rest.
I used basic PowerShell commands. I did not need to download any additional components. I first checked if the requisite number of files existed. If they I invoked the FTP the second time with an Mget. I run this from a Windows Server 2008 connecting to a Windows XP remote server.
function make_ftp_command_file($p_file_pattern,$mget_flag)
{
# This function dynamically prepares the FTP file.
# The file needs to be prepared daily because the
# pattern changes daily.
# PowerShell default encoding is Unicode.
# Unicode command files are not compatible with FTP so
# we need to make sure we create an ASCII file.
write-output "USER" | out-file -filepath C:\fc.txt -encoding ASCII
write-output "ftpusername" | out-file -filepath C:\fc.txt -encoding ASCII -Append
write-output "password" | out-file -filepath C:\fc.txt -encoding ASCII -Append
write-output "ASCII" | out-file -filepath C:\fc.txt -encoding ASCII -Append
If ($mget_flag -eq "Y")
{
write-output "prompt" | out-file -filepath C:\fc.txt -encoding ASCII -Append
write-output "mget $p_file_pattern" | out-file -filepath C:\fc.txt -encoding ASCII -Append
}
else
{
write-output "ls $p_file_pattern" | out-file -filepath C:\fc.txt -encoding ASCII -Append
}
write-output quit | out-file -filepath C:\fc.txt -encoding ASCII -Append
}
########################### Init Section ###############################
$yesterday = (get-date).AddDays(-1)
$yesterday_fmt = date $yesterday -format "yyyyMMdd"
$file_pattern = "BRAE_GE_*" + $yesterday_fmt + "*.csv"
$file_log = $yesterday_fmt + ".log"
echo $file_pattern
echo $file_log
############################## Main Section ############################
# Change location to folder where the files need to be downloaded
cd c:\remotefiles
# Dynamically create the FTP Command to get a list of files from
# the remote servers
echo "Call function that creates a FTP Command "
make_ftp_command_file $file_pattern N
#echo "Connect to remote site via FTP"
# Connect to Remote Server and get file listing
ftp -n -v -s:C:\Clover\scripts\fc.txt 10.129.120.31 > C:\logs\$file_log
$matches=select-string -pattern "BRAE_GE_[A-Z][A-Z]*" C:\logs\$file_log
# Check if the required number of Files available for download
if ($matches.count -eq 36)
{
# Create the FTP command file
# This time the command file has an mget rather than an ls
make_ftp_command_file $file_pattern Y
# Change directory if not done so
cd c:\remotefiles
# Invoke ftp with newly created command file
ftp -n -v -s:C:\Clover\scripts\fc.txt 10.129.120.31 > C:\logs\$file_log
}
else
{
echo "The full set of files is not available"
}
In Java 11, we can use the Collection.toArray(generator)
method. The following code will create a new array of strings:
List<String> list = List.of("one", "two", "three");
String[] array = list.toArray(String[]::new)
I've just used Deferred in real code. In project jQuery Terminal I have function exec that call commands defined by user (like he was entering it and pressing enter), I've added Deferreds to the API and call exec with arrays. like this:
terminal.exec('command').then(function() {
terminal.echo('command finished');
});
or
terminal.exec(['command 1', 'command 2', 'command 3']).then(function() {
terminal.echo('all commands finished');
});
the commands can run async code, and exec need to call user code in order. My first api use pair of pause/resume calls and in new API I call those automatic when user return promise. So user code can just use
return $.get('/some/url');
or
var d = new $.Deferred();
setTimeout(function() {
d.resolve("Hello Deferred"); // resolve value will be echoed
}, 500);
return d.promise();
I use code like this:
exec: function(command, silent, deferred) {
var d;
if ($.isArray(command)) {
return $.when.apply($, $.map(command, function(command) {
return self.exec(command, silent);
}));
}
// both commands executed here (resume will call Term::exec)
if (paused) {
// delay command multiple time
d = deferred || new $.Deferred();
dalyed_commands.push([command, silent, d]);
return d.promise();
} else {
// commands may return promise from user code
// it will resolve exec promise when user promise
// is resolved
var ret = commands(command, silent, true, deferred);
if (!ret) {
if (deferred) {
deferred.resolve(self);
return deferred.promise();
} else {
d = new $.Deferred();
ret = d.promise();
ret.resolve();
}
}
return ret;
}
},
dalyed_commands is used in resume function that call exec again with all dalyed_commands.
and part of the commands function (I've stripped not related parts)
function commands(command, silent, exec, deferred) {
var position = lines.length-1;
// Call user interpreter function
var result = interpreter.interpreter(command, self);
// user code can return a promise
if (result != undefined) {
// new API - auto pause/resume when using promises
self.pause();
return $.when(result).then(function(result) {
// don't echo result if user echo something
if (result && position === lines.length-1) {
display_object(result);
}
// resolve promise from exec. This will fire
// code if used terminal::exec('command').then
if (deferred) {
deferred.resolve();
}
self.resume();
});
}
// this is old API
// if command call pause - wait until resume
if (paused) {
self.bind('resume.command', function() {
// exec with resume/pause in user code
if (deferred) {
deferred.resolve();
}
self.unbind('resume.command');
});
} else {
// this should not happen
if (deferred) {
deferred.resolve();
}
}
}
We can do this by setting access to JsonProperty.Access.WRITE_ONLY
while declaring the property.
@JsonProperty( value = "password", access = JsonProperty.Access.WRITE_ONLY)
@SerializedName("password")
private String password;
This is much easier:
<textarea onKeyPress="return ( this.value.length < 1000 );"></textarea>
_x000D_
int i = 65;
char c = Convert.ToChar(i);
This is the best way to implement Onclicklistener for many buttons in a row implement View.onclicklistener.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
This is a button in the MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_submit = (Button) findViewById(R.id.submit);
bt_submit.setOnClickListener(this);
}
This is an override method
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.submit:
//action
break;
case R.id.secondbutton:
//action
break;
}
}
You need to use font-url
in your @font-face block, not url
@font-face {
font-family: 'Inconsolata';
src:font-url('Inconsolata-Regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
as well as this line in application.rb, as you mentioned (for fonts in app/assets/fonts
config.assets.paths << Rails.root.join("app", "assets", "fonts")
I would do it by creating a variable that points to the nodes that have the proper value in Value1 then referring to t
<xsl:variable name="myVarANode" select="root//DataSet/Data[@Value1='2']" />
<xsl:value-of select="$myVarANode/@Value2"/>
Everyone else's answers are right too - more right in fact since I didn't notice the extra slash in your XPATH that would mess things up. Still, this will also work , and might work for different things, so keep this method in your toolbox.
I'm hitting Microsoft SQL Server 2008 R2 from a single-threaded JDBC-based application and pulling back the last ID without using the RETURN_GENERATED_KEYS property or any PreparedStatement. Looks something like this:
private int insertQueryReturnInt(String SQLQy) {
ResultSet generatedKeys = null;
int generatedKey = -1;
try {
Statement statement = conn.createStatement();
statement.execute(SQLQy);
} catch (Exception e) {
errorDescription = "Failed to insert SQL query: " + SQLQy + "( " + e.toString() + ")";
return -1;
}
try {
generatedKey = Integer.parseInt(readOneValue("SELECT @@IDENTITY"));
} catch (Exception e) {
errorDescription = "Failed to get ID of just-inserted SQL query: " + SQLQy + "( " + e.toString() + ")";
return -1;
}
return generatedKey;
}
This blog post nicely isolates three main SQL Server "last ID" options: http://msjawahar.wordpress.com/2008/01/25/how-to-find-the-last-identity-value-inserted-in-the-sql-server/ - haven't needed the other two yet.
Since JavaMail version 1.4, there is an overload of setText
method that accepts the subtype.
// Passing null for second argument in order for the method to determine
// the actual charset on-the fly.
// If you know the charset, pass it. "utf-8" should be fine
msg.setText( message, null, "html" );
HANDLE hnd;
is the same as void * ptr;
HANDLE is a typedef defined in the winnt.h file in Visual Studio (Windows):
typedef void *HANDLE;
Read more about HANDLE
Here is the answer to the question here
Actually we have to get it from the sharable ContentProvider of Camera Application.
EDIT . Copying answer that worked for me
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
Use
__DIR__
to get the current path of the script and this should fix your problem.
So:
require_once(__DIR__.'/../class/user.php');
This will prevent cases where you can run a PHP script from a different folder and therefore the relatives paths will not work.
Edit: slash problem fixed
The selected attribute is a boolean attribute.
When present, it specifies that an option should be pre-selected when the page loads.
The pre-selected option will be displayed first in the drop-down list.
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi" selected>Audi</option>
</select>
Here's something else I found interesting. If your source is a DataTable, you can use dynamic sorting without using Dynamic Linq
DataTable orders = dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection<DataRow> query = from order in orders.AsEnumerable()
orderby order.Field<DateTime>("OrderDate")
select order;
DataView view = query.AsDataView();
bindingSource1.DataSource = view;
reference: http://msdn.microsoft.com/en-us/library/bb669083.aspx (Using DataSetExtensions)
Here is one more way to do it by converting it to a DataView:
DataTable contacts = dataSet.Tables["Contact"];
DataView view = contacts.AsDataView();
view.Sort = "LastName desc, FirstName asc";
bindingSource1.DataSource = view;
dataGridView1.AutoResizeColumns();
If you have Model or transfer object passed to GET method but still have this error, check naming of your variables. Use entity/transfer object names in camelcase. I had BusinessTripDTO object and named it 'trip' for short. It caused this error to occure, even I had all other parts in place. Renaming varaibles to businessTripDTO in Java and Thymeleaf solved this problem for me.
chmod 400 mykey.pem
ssh -i mykey.pem [email protected]
Will connect you over ssh using a .pem file to any server.
Private constructor and static methods on a class marked as final.
int randomWithRange(int min, int max)
{
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
Output of randomWithRange(2, 5)
10 times:
5
2
3
3
2
4
4
4
5
4
The bounds are inclusive, ie [2,5], and min
must be less than max
in the above example.
EDIT: If someone was going to try and be stupid and reverse min
and max
, you could change the code to:
int randomWithRange(int min, int max)
{
int range = Math.abs(max - min) + 1;
return (int)(Math.random() * range) + (min <= max ? min : max);
}
EDIT2: For your question about double
s, it's just:
double randomWithRange(double min, double max)
{
double range = (max - min);
return (Math.random() * range) + min;
}
And again if you want to idiot-proof it it's just:
double randomWithRange(double min, double max)
{
double range = Math.abs(max - min);
return (Math.random() * range) + (min <= max ? min : max);
}
The problem is, your value cannot be stored accurately in single precision floating point type. Proof:
public class test{
public static void main(String[] args){
Float a = Float.valueOf("23423424666767");
System.out.printf("%f\n", a); //23423424135168,000000
System.out.println(a); //2.34234241E13
}
}
Another thing is: you don't get "2.3423424666767E13", it's just the visual representation of the number stored in memory. "How you print out" and "what is in memory" are two distinct things. Example above shows you how to print the number as float, which avoids scientific notation you were getting.
set encoding=utf-8 " The encoding displayed.
set fileencoding=utf-8 " The encoding written to file.
You may as well set both in your ~/.vimrc
if you always want to work with utf-8.
You do not want the '='
Use .libPaths("C:/R/library")
in you Rprofile
.site file
And make sure you have correct " symbol (Shift-2)
Adding on from the answer below i have created this method:
public static bool ContainsInvalidStrings(IList<string> invalidStrings,string stringToCheck)
{
foreach (string invalidString in invalidStrings)
{
var index = stringToCheck.IndexOf(invalidString, StringComparison.InvariantCultureIgnoreCase);
if (index != -1)
{
return true;
}
}
return false;
}
it can be used like this:
var unsupportedTypes = new List<string>()
{
"POINT Empty",
"MULTIPOINT",
"MULTILINESTRING",
"MULTIPOLYGON",
"GEOMETRYCOLLECTION",
"CIRCULARSTRING",
"COMPOUNDCURVE",
"CURVEPOLYGON",
"MULTICURVE",
"TRIANGLE",
"TIN",
"POLYHEDRALSURFACE"
};
bool hasInvalidValues = ContainsInvalidStrings(unsupportedTypes,possibleWKT);
you can check for multiple invalid values this way.
If your date column is a string of the format '2017-01-01' you can use pandas astype to convert it to datetime.
df['date'] = df['date'].astype('datetime64[ns]')
or use datetime64[D] if you want Day precision and not nanoseconds
print(type(df_launath['date'].iloc[0]))
yields
<class 'pandas._libs.tslib.Timestamp'>
the same as when you use pandas.to_datetime
You can try it with other formats then '%Y-%m-%d' but at least this works.
Use ThisWorkbook
which will refer to the original workbook which holds the code.
Alternatively at code start
Dim Wb As Workbook
Set Wb = ActiveWorkbook
sample code that activates all open books before returning to ThisWorkbook
Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
Wb2.Activate
Next
Wb.Activate
End Sub
You can define instance method for js class, via prototype of the constructor.
Following is the sample code:
// BaseClass
var BaseClass = function(name) {
// instance property
this.name = name;
};
// instance method
BaseClass.prototype.getName = function() {
return this.name;
};
BaseClass.prototype.setName = function(name) {
return this.name = name;
};
// test - start
function test() {
var b1 = new BaseClass("b1");
var b2 = new BaseClass("b2");
console.log(b1.getName());
console.log(b2.getName());
b1.setName("b1_new");
console.log(b1.getName());
console.log(b2.getName());
}
test();
// test - end
And, this should work for any browser, you can also simply use nodejs to run this code.
jQuery has two methods
// First. Get content as HTML
$("#my_div_id").html();
// Second. Get content as text
$("#my_div_id").text();
create .htaccess file on project root directory and put below code for remove index.php
RewriteEngine on
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
document.forms["form_name"].getElementsByTagName("input");
This trick is useful for missing commands or functions. The name of the missing function (or executable) will be passed in $_
function handle_error {
status=$?
last_call=$1
# 127 is 'command not found'
(( status != 127 )) && return
echo "you tried to call $last_call"
return
}
# Trap errors.
trap 'handle_error "$_"' ERR
Make sure you're calling super()
as the first thing in your constructor.
You should set this
for setAuthorState
method
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
constructor(props) {
super(props);
this.handleAuthorChange = this.handleAuthorChange.bind(this);
}
handleAuthorChange(event) {
let {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
Another alternative based on arrow function
:
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
handleAuthorChange = (event) => {
const {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
After beating my head on this for at least an hour, I offer this answer to try to expand on the comments some others have made. To ignore a folder/directory, do the following: if you don't have a .gitignore file in the root of your project (that name exactly ".gitignore"), create a dummy text file in the folder you want to exclude. Inside of Source Tree, right click on it and select Ignore. You'll get a popup that looks like this.
Select "Everything underneath" and select the folder you want to ignore from the drop-down list. This will create a .gitignore file in your root directory and put the folder specification in it.
If you do have a .gitignore folder already in your root folder, you could follow the same approach above, or you can just edit the .gitignore file and add the folder you want to exclude. It's just a text file. Note that it uses forward slashes in path names rather than backslashes, as we Windows users are accustomed to. I tried creating a .gitignore text file by hand in Windows Explorer, but it didn't let me create a file without a name (i.e. with only the extension).
Note that adding the .gitignore and the file specification will have no effect on files that are already being tracked. If you're already tracking these, you'll have to stop tracking them. (Right-click on the folder or file and select Stop Tracking.) You'll then see them change from having a green/clean or amber/changed icon to a red/removed icon. On your next commit the files will be removed from the repository and thereafter appear with a blue/ignored icon. Another contributor asked why Ignore was disabled for particular files and I believe it was because he was trying to ignore a file that was already being tracked. You can only ignore a file that has a blue question mark icon.
git diff --name-only --diff-filter=U
To fix, I deleted the app from Simulator.
I also ran Clean first.
I do not think anything orientation-related triggered it. The biggest thing that changed before this symptom started is that a Swift framework started calling NSLog
on worker threads instead of main thread.
Instead of getting IMEI from TelephonyManager use ANDROID_ID.
Settings.Secure.ANDROID_ID
This works for each android device irrespective of having telephony.
the best you export it as sql file and open it with editor such as visual studio code and find and repalace your words. i replace in 1 gig file sql in 1 minutes for 16 word that total is 14600 word. its the best way. and after replace it save and import it again. do not forget compress it with zip for import.
If you have IIS URL Rewriting installed it could be to do with that. I suffered issues after a Windows 10 Update.
This StackOverflow post helped me.
Go to Windows Control Panel
> Programs and Features
> IIS URL Rewrite Module 2
> Repair
.
JNDI needs to be approached with the understanding that it is a service locator. When the desired service is hosted on the same server/node as the application, then your use of InitialContext may work.
What makes it more complicated is that defining a Data Source in Web Sphere (at least back in 4.0) allowed you to define the visibility to various degrees. Basically it adds namespaces to the environment and clients have to know where the resource is hosted.
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/DataSourceAlias");
Here is IBM's reference page.
If you are trying to reference a data source from an app that is NOT in the J2EE container, you'll need a slightly different approach starting with needing some J2EE client jars in your classpath. http://www.coderanch.com/t/75386/Websphere/lookup-datasources-JNDI-outside-EE
if you are anything like me coming from a google search and looking to remove an html element with cool animation, then this could help you:
$(document).ready(function() {_x000D_
_x000D_
var $deleteButton = $('.deleteItem');_x000D_
_x000D_
$deleteButton.on('click', function(event) {_x000D_
_x000D_
event.preventDefault();_x000D_
_x000D_
var $button = $(this);_x000D_
_x000D_
if(confirm('Are you sure about this ?')) {_x000D_
_x000D_
var $item = $button.closest('tr.item');_x000D_
_x000D_
$item.addClass('removed-item')_x000D_
_x000D_
.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {_x000D_
_x000D_
$(this).remove();_x000D_
});_x000D_
}_x000D_
_x000D_
});_x000D_
_x000D_
});
_x000D_
/**_x000D_
* Credit to Sara Soueidan_x000D_
* @link https://github.com/SaraSoueidan/creative-list-effects/blob/master/css/styles-3.css_x000D_
*/_x000D_
_x000D_
.removed-item {_x000D_
-webkit-animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29);_x000D_
-o-animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29);_x000D_
animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29)_x000D_
}_x000D_
_x000D_
@keyframes removed-item-animation {_x000D_
0% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(0);_x000D_
-ms-transform: translateX(0);_x000D_
-o-transform: translateX(0);_x000D_
transform: translateX(0)_x000D_
}_x000D_
_x000D_
30% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(50px);_x000D_
-ms-transform: translateX(50px);_x000D_
-o-transform: translateX(50px);_x000D_
transform: translateX(50px)_x000D_
}_x000D_
_x000D_
80% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(-800px);_x000D_
-ms-transform: translateX(-800px);_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 0;_x000D_
-webkit-transform: translateX(-800px);_x000D_
-ms-transform: translateX(-800px);_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
}_x000D_
_x000D_
@-webkit-keyframes removed-item-animation {_x000D_
0% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(0);_x000D_
transform: translateX(0)_x000D_
}_x000D_
_x000D_
30% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(50px);_x000D_
transform: translateX(50px)_x000D_
}_x000D_
_x000D_
80% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 0;_x000D_
-webkit-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
}_x000D_
_x000D_
@-o-keyframes removed-item-animation {_x000D_
0% {_x000D_
opacity: 1;_x000D_
-o-transform: translateX(0);_x000D_
transform: translateX(0)_x000D_
}_x000D_
_x000D_
30% {_x000D_
opacity: 1;_x000D_
-o-transform: translateX(50px);_x000D_
transform: translateX(50px)_x000D_
}_x000D_
_x000D_
80% {_x000D_
opacity: 1;_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 0;_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table class="table table-striped table-bordered table-hover">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>id</th>_x000D_
<th>firstname</th>_x000D_
<th>lastname</th>_x000D_
<th>@twitter</th>_x000D_
<th>action</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
_x000D_
<tr class="item">_x000D_
<td>1</td>_x000D_
<td>Nour-Eddine</td>_x000D_
<td>ECH-CHEBABY</td>_x000D_
<th>@__chebaby</th>_x000D_
<td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
</tr>_x000D_
_x000D_
<tr class="item">_x000D_
<td>2</td>_x000D_
<td>John</td>_x000D_
<td>Doe</td>_x000D_
<th>@johndoe</th>_x000D_
<td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
</tr>_x000D_
_x000D_
<tr class="item">_x000D_
<td>3</td>_x000D_
<td>Jane</td>_x000D_
<td>Doe</td>_x000D_
<th>@janedoe</th>_x000D_
<td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE
Edit: On the model overview it's under Physical Schemata
Screenshot:
Javascript arrays have a length property. Use it like this:
st.itemb.length
You can also add hash when page is loading:
location.hash = "noBack";
Then just handle location hash change to add another hash:
$(window).on('hashchange', function() {
location.hash = "noBack";
});
That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.
Fore readability sake in the code use an array and implode it to a comma separated string:-
$recipients = array(
"[email protected]",
// more emails
);
$email_to = implode(',', $recipients); // your email address
$email_subject = "Contact Form Message"; // email subject line
$thankyou = "thankyou.htm"; // thank you page
Since your issue is mostly stylistic (not wanting to fill up the constructor with a bunch of declarations) it can be solved stylistically as well.
The way I view it, many class based languages have the constructor be a function named after the class name itself. Stylistically we could use that that to make an ES6 class that stylistically still makes sense but does not group the typical actions taking place in the constructor with all the property declarations we're doing. We simply use the actual JS constructor as the "declaration area", then make a class named function that we otherwise treat as the "other constructor stuff" area, calling it at the end of the true constructor.
"use strict"; class MyClass { // only declare your properties and then call this.ClassName(); from here constructor(){ this.prop1 = 'blah 1'; this.prop2 = 'blah 2'; this.prop3 = 'blah 3'; this.MyClass(); } // all sorts of other "constructor" stuff, no longer jumbled with declarations MyClass() { doWhatever(); } }
Both will be called as the new instance is constructed.
Sorta like having 2 constructors where you separate out the declarations and the other constructor actions you want to take, and stylistically makes it not too hard to understand that's what is going on too.
I find it's a nice style to use when dealing with a lot of declarations and/or a lot of actions needing to happen on instantiation and wanting to keep the two ideas distinct from each other.
NOTE: I very purposefully do not use the typical idiomatic ideas of "initializing" (like an init()
or initialize()
method) because those are often used differently. There is a sort of presumed difference between the idea of constructing and initializing. Working with constructors people know that they're called automatically as part of instantiation. Seeing an init
method many people are going to assume without a second glance that they need to be doing something along the form of var mc = MyClass(); mc.init();
, because that's how you typically initialize. I'm not trying to add an initialization process for the user of the class, I'm trying to add to the construction process of the class itself.
While some people may do a double-take for a moment, that's actually the bit of the point: it communicates to them that the intent is part of construction, even if that makes them do a bit of a double take and go "that's not how ES6 constructors work" and take a second looking at the actual constructor to go "oh, they call it at the bottom, I see", that's far better than NOT communicating that intent (or incorrectly communicating it) and probably getting a lot of people using it wrong, trying to initialize it from the outside and junk. That's very much intentional to the pattern I suggest.
For those that don't want to follow that pattern, the exact opposite can work too. Farm the declarations out to another function at the beginning. Maybe name it "properties" or "publicProperties" or something. Then put the rest of the stuff in the normal constructor.
"use strict"; class MyClass { properties() { this.prop1 = 'blah 1'; this.prop2 = 'blah 2'; this.prop3 = 'blah 3'; } constructor() { this.properties(); doWhatever(); } }
Note that this second method may look cleaner but it also has an inherent problem where properties
gets overridden as one class using this method extends another. You'd have to give more unique names to properties
to avoid that. My first method does not have this problem because its fake half of the constructor is uniquely named after the class.
Assuming a list like below - and assuming some of the options were selected ... (this is a multi select, but this will also work on a single select.
<select multiple='multiple' id='selectListName'>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
In some function called based on some event, the following code would clear all selected options.
$("#selectListName").prop('selectedIndex', -1);
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
Here's a stored proc to do it:
CREATE OR REPLACE function timestamp_diff(a timestamp, b timestamp) return number is
begin
return extract (day from (a-b))*24*60*60 +
extract (hour from (a-b))*60*60+
extract (minute from (a-b))*60+
extract (second from (a-b));
end;
/
Up Vote if you also wanted to beat the crap out of the Oracle developer who negated to his job!
BECAUSE comparing timestamps for the first time should take everyone an hour or so...
This is based on the assumption that you're getting an error about the date format, such as an invalid month value or non-numeric character when numeric expected.
Dates stored in the database do not have formats. When you query the date your client is formatting the date for display, as 4/16/2011
. Normally the same date format is used for selecting and updating dates, but in this case they appear to be different - so your client is apparently doing something more complicated that SQL*Plus, for example.
When you try to update it it's using a default date format model. Because of how it's displayed you're assuming that is MM/DD/YYYY
, but it seems not to be. You could find out what it is, but it's better not to rely on the default or any implicit format models at all.
Whether that is the problem or not, you should always specify the date model:
UPDATE PASOFDATE SET ASOFDATE = TO_DATE('11/21/2012', 'MM/DD/YYYY');
Since you aren't specifying a time component - all Oracle DATE
columns include a time, even if it's midnight - you could also use a date literal:
UPDATE PASOFDATE SET ASOFDATE = DATE '2012-11-21';
You should maybe check that the current value doesn't include a time, though the column name suggests it doesn't.
sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename
sudo update-rc.d filename defaults
Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln
).
At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename
) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*
. Updated above code to reflect this.
Also as pointed out in the comments (by Charles Brandt), /filename
must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.
Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts
As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.
According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering
", in which case you have to pass sequence and runlevel configuration through command line arguments.
The equivalent argument set for the above example is
sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .
select * from table where length(RTRIM(LTRIM(column_name))) > 0
The keypress event from jQuery is meant to do this sort of work. You can trigger the event by passing a string "keypress" to .trigger(). However to be more specific you can actually pass a jQuery.Event object (specify the type as "keypress") as well and provide any properties you want such as the keycode being the spacebar.
http://docs.jquery.com/Events/trigger#eventdata
Read the above documentation for more details.
1) Instead of PreparedStatement
use Statement
2) After executing query in ResultSet
, extract values with the help of rs.getString()
as :
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
rs.getString(1); //or rs.getString("column name");
}
In my case the error was appearing as I removed the KEY attribute of the ID field.
// [Key]
public long Id { get; set; }
So just putting the attribute back in it's place, made everything working again!
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
If using Tomcat 6 and earlier, make sure the keystore password and the key password are same. If using Tomcat 7 and later, make sure they are the same or that the key password is specified in the server.xml
file.
You can specify the cookie file with a curl opt. You could use a unique file for each user.
curl_setopt( $curl_handle, CURLOPT_COOKIESESSION, true );
curl_setopt( $curl_handle, CURLOPT_COOKIEJAR, uniquefilename );
curl_setopt( $curl_handle, CURLOPT_COOKIEFILE, uniquefilename );
The best way to handle it would be to stick your request logic into a curl function and just pass the unique file name in as a parameter.
function fetch( $url, $z=null ) {
$ch = curl_init();
$useragent = isset($z['useragent']) ? $z['useragent'] : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2';
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_POST, isset($z['post']) );
if( isset($z['post']) ) curl_setopt( $ch, CURLOPT_POSTFIELDS, $z['post'] );
if( isset($z['refer']) ) curl_setopt( $ch, CURLOPT_REFERER, $z['refer'] );
curl_setopt( $ch, CURLOPT_USERAGENT, $useragent );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, ( isset($z['timeout']) ? $z['timeout'] : 5 ) );
curl_setopt( $ch, CURLOPT_COOKIEJAR, $z['cookiefile'] );
curl_setopt( $ch, CURLOPT_COOKIEFILE, $z['cookiefile'] );
$result = curl_exec( $ch );
curl_close( $ch );
return $result;
}
I use this for quick grabs. It takes the url and an array of options.
in my case, I had a <TEXTAREA>
tag from old html while converting to angular. Had to change to <textarea>
.
rbind()
needs the two object names to be the same. For example, the first object names: ID Age
, the next object names: ID Gender
,if you want to use rbind()
, it will print out:
names do not match previous names
Blockquote
Using concatenation in Oracle SQL is very easy and interesting. But don't know much about MS-SQL.
Blockquote
Here we go for Oracle :
Syntax:
SQL> select First_name||Last_Name as Employee
from employees;
EllenAbel SundarAnde MozheAtkinson
Here AS: keyword used as alias. We can concatenate with NULL values. e.g. : columnm1||Null
Suppose any of your columns contains a NULL value then the result will show only the value of that column which has value.
You can also use literal character string in concatenation.
e.g.
select column1||' is a '||column2
from tableName;
Result: column1 is a column2.
in between literal should be encolsed in single quotation. you cna exclude numbers.
NOTE: This is only for oracle server//SQL.
I've spent some time on it and thanks to @chrismarx, I saw that angular's default filterFilter
allows you to pass your own comparator. Here's the edited comparator for multiple values:
function hasCustomToString(obj) {
return angular.isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
}
var comparator = function (actual, expected) {
if (angular.isUndefined(actual)) {
// No substring matching against `undefined`
return false;
}
if ((actual === null) || (expected === null)) {
// No substring matching against `null`; only match against `null`
return actual === expected;
}
// I edited this to check if not array
if ((angular.isObject(expected) && !angular.isArray(expected)) || (angular.isObject(actual) && !hasCustomToString(actual))) {
// Should not compare primitives against objects, unless they have custom `toString` method
return false;
}
// This is where magic happens
actual = angular.lowercase('' + actual);
if (angular.isArray(expected)) {
var match = false;
expected.forEach(function (e) {
e = angular.lowercase('' + e);
if (actual.indexOf(e) !== -1) {
match = true;
}
});
return match;
} else {
expected = angular.lowercase('' + expected);
return actual.indexOf(expected) !== -1;
}
};
And if we want to make a custom filter for DRY:
angular.module('myApp')
.filter('filterWithOr', function ($filter) {
var comparator = function (actual, expected) {
if (angular.isUndefined(actual)) {
// No substring matching against `undefined`
return false;
}
if ((actual === null) || (expected === null)) {
// No substring matching against `null`; only match against `null`
return actual === expected;
}
if ((angular.isObject(expected) && !angular.isArray(expected)) || (angular.isObject(actual) && !hasCustomToString(actual))) {
// Should not compare primitives against objects, unless they have custom `toString` method
return false;
}
console.log('ACTUAL EXPECTED')
console.log(actual)
console.log(expected)
actual = angular.lowercase('' + actual);
if (angular.isArray(expected)) {
var match = false;
expected.forEach(function (e) {
console.log('forEach')
console.log(e)
e = angular.lowercase('' + e);
if (actual.indexOf(e) !== -1) {
match = true;
}
});
return match;
} else {
expected = angular.lowercase('' + expected);
return actual.indexOf(expected) !== -1;
}
};
return function (array, expression) {
return $filter('filter')(array, expression, comparator);
};
});
And then we can use it anywhere we want:
$scope.list=[
{name:'Jack Bauer'},
{name:'Chuck Norris'},
{name:'Superman'},
{name:'Batman'},
{name:'Spiderman'},
{name:'Hulk'}
];
<ul>
<li ng-repeat="item in list | filterWithOr:{name:['Jack','Chuck']}">
{{item.name}}
</li>
</ul>
Finally here's a plunkr.
Note: Expected array should only contain simple objects like String, Number etc.
All you need is
e.preventDefault();
on child element.