Because you're trying to add a click event to a submit input you will need to prevent the normal flow that this will do that is submit the form.
You can also use $(document).ready()
But since you have your script tag at the end of the page the DOM is already loaded.
To prevent the default you will need something like this:
$("form").on('submit',function(e){
e.preventDefault();
$("#dsf").val("changed value")
})
If the element wasn't a submit input it will be as simple as
$("#cd").click(function(){
$("#dsf").val("changed value")
})
See this Fiddle
IDP Initiated SSO
From PingFederate documentation :- https://docs.pingidentity.com/bundle/pf_sm_supportedStandards_pf82/page/task/idpInitiatedSsoPOST.html
In this scenario, a user is logged on to the IdP and attempts to access a resource on a remote SP server. The SAML assertion is transported to the SP via HTTP POST.
Processing Steps:
SP Initiated SSO
From PingFederate documentation:- http://documentation.pingidentity.com/display/PF610/SP-Initiated+SSO--POST-POST
In this scenario a user attempts to access a protected resource directly on an SP Web site without being logged on. The user does not have an account on the SP site, but does have a federated account managed by a third-party IdP. The SP sends an authentication request to the IdP. Both the request and the returned SAML assertion are sent through the user’s browser via HTTP POST.
Processing Steps:
Additional information about the user may be retrieved from the user data store for inclusion in the SAML response. (These attributes are predetermined as part of the federation agreement between the IdP and the SP)
The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP. NOTE: SAML specifications require that POST responses be digitally signed.
(Not shown) If the signature and assertion are valid, the SP establishes a session for the user and redirects the browser to the target resource.
const router = new VueRouter({
mode: 'history',
routes: [...]
})
And if you are using AWS amplify, check this article on how to configure server: Vue router’s history mode and AWS Amplify
You can use an instance of the StringFormat
object passed into the DrawString
method to center the text.
You need to use the __getitem__
method.
class MyClass:
def __getitem__(self, key):
return key * 2
myobj = MyClass()
myobj[3] #Output: 6
And if you're going to be setting values you'll need to implement the __setitem__
method too, otherwise this will happen:
>>> myobj[5] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'
I encountered a similar issue, but putting it in my page’s module didn’t work.
I had created a component, which needed a pipe. This component was declared and exported in a ComponentsModule file, which holds all of the app’s custom components.
I had to put my PipesModule in my ComponentsModule as an import, in order for these components to use these pipes and not in the page’s module using that component.
Credits: enter link description here Answer by: tumain
Yes - just do it this way:
WITH DependencedIncidents AS
(
....
),
lalala AS
(
....
)
You don't need to repeat the WITH
keyword
User order by with that field, and then do distinct.
ProductOrder.objects.order_by('category').values_list('category', flat=True).distinct()
further to S.Lott's reply, class variables get passed to metaclass new method and can be accessed through the dictionary when a metaclass is defined. So, class variables can be accessed even before classes are created and instantiated.
for example:
class meta(type):
def __new__(cls,name,bases,dicto):
# two chars missing in original of next line ...
if dicto['class_var'] == 'A':
print 'There'
class proxyclass(object):
class_var = 'A'
__metaclass__ = meta
...
...
I've read the popular wordpress website linked in some of the above popular answers at the top. From what I've understood, I'd like to share a simple observation I made.
You can find all the details in the article here, but assume the following holds true:
A general hashmap implementation wants 2 things to be unique.
How do we get the unique index? By making the initial size of the internal container a prime as well. So basically, prime is involved because it possesses this unique trait of producing unique numbers which we end up using to ID objects and finding indexes inside the internal container.
Example:
key = "key"
value = "value"
uniqueId = "k" * 31 ^ 2 +
"e" * 31 ^ 1` +
"y"
maps to unique id
Now we want a unique location for our value - so we
uniqueId % internalContainerSize == uniqueLocationForValue
, assuming internalContainerSize
is also a prime.
I know this is simplified, but I'm hoping to get the general idea through.
I tried to write up 3 following functions, you can test them for different cases of yours. This is the data I tested with:
Function getLastRow1 and getLastRow2 will return 0 for column B Function getLastRow3 will return 1 for column B
Depend on your case, you will tweak them for your needs.
function getLastRow1(sheet, column) {
var data = sheet.getRange(1, column, sheet.getLastRow()).getValues();
while(typeof data[data.length-1] !== 'undefined'
&& data[data.length-1][0].length === 0){
data.pop();
}
return data.length;
}
function test() {
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet6');
Logger.log('Cách 1');
Logger.log("Dòng cu?i cùng c?a c?t A là: " + getLastRow1(sh, 1));
Logger.log("Dòng cu?i cùng c?a c?t B là: " + getLastRow1(sh, 2));
Logger.log("Dòng cu?i cùng c?a c?t C là: " + getLastRow1(sh, 3));
Logger.log("Dòng cu?i cùng c?a c?t D là: " + getLastRow1(sh, 4));
Logger.log("Dòng cu?i cùng c?a c?t E là: " + getLastRow1(sh, 5));
Logger.log('Cách 2');
Logger.log("Dòng cu?i cùng c?a c?t A là: " + getLastRow2(sh, 1));
Logger.log("Dòng cu?i cùng c?a c?t B là: " + getLastRow2(sh, 2));
Logger.log("Dòng cu?i cùng c?a c?t C là: " + getLastRow2(sh, 3));
Logger.log("Dòng cu?i cùng c?a c?t D là: " + getLastRow2(sh, 4));
Logger.log("Dòng cu?i cùng c?a c?t E là: " + getLastRow2(sh, 5));
Logger.log('Cách 3');
Logger.log("Dòng cu?i cùng c?a c?t A là: " + getLastRow3(sh, 'A'));
Logger.log("Dòng cu?i cùng c?a c?t B là: " + getLastRow3(sh, 'B'));
Logger.log("Dòng cu?i cùng c?a c?t C là: " + getLastRow3(sh, 'C'));
Logger.log("Dòng cu?i cùng c?a c?t D là: " + getLastRow3(sh, 'D'));
Logger.log("Dòng cu?i cùng c?a c?t E là: " + getLastRow3(sh, 'E'));
}
function getLastRow2(sheet, column) {
var lr = sheet.getLastRow();
var data = sheet.getRange(1, column, lr).getValues();
while(lr > 0 && sheet.getRange(lr , column).isBlank()) {
lr--;
}
return lr;
}
function getLastRow3(sheet, column) {
var lastRow = sheet.getLastRow();
var range = sheet.getRange(column + lastRow);
if (range.getValue() !== '') {
return lastRow;
} else {
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
}
}
Is not recommended but.... you can use componentWillMount from your app class to add your global variables trough it... a bit like so:
componentWillMount: function () {
window.MyVars = {
ajax: require('../helpers/ajax.jsx'),
utils: require('../helpers/utils.jsx')
};
}
still consider this a hack... but it will get your job done
btw componentWillMount executes once before rendering, see more here: https://reactjs.org/docs/react-component.html#mounting-componentwillmount
I wanted to keep the formulas in place, which the above code did not do.
Here's what I've been doing, note that this leaves one empty row in the table.
Sub DeleteTableRows(ByRef Table As ListObject, KeepFormulas as boolean)
On Error Resume Next
if not KeepFormulas then
Table.DataBodyRange.clearcontents
end if
Table.DataBodyRange.Rows.Delete
On Error GoTo 0
End Sub
(PS don't ask me why!)
Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.
Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.
Incase of string literals(character arrays defined at declaration), they are automatically
appended by \0
.
printf
prints using the format specifier and the address provided. Since, you use %s
it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'
You could create a shell function, e.g. in your .zshrc
or .bashrc
:
filepath() {
echo $PWD/$1
}
filepath2() {
for i in $@; do
echo $PWD/$i
done
}
The first one would work on single files only, obviously.
Write the JSON object to the response object's output stream.
You should also set the content type as follows, which will specify what you are returning:
response.setContentType("application/json");
// Get the printwriter object from response to write the required json object to the output stream
PrintWriter out = response.getWriter();
// Assuming your json object is **jsonObject**, perform the following, it will return your json object
out.print(jsonObject);
out.flush();
Thank you WiredPrairie!
Just to expand on your answer a bit, here is a complete example of defining a constants class.
// CYConstants.ts
class CYConstants {
public static get NOT_FOUND(): number { return -1; }
public static get EMPTY_STRING(): string { return ""; }
}
export = CYConstants;
To use
// main.ts
import CYConstants = require("./CYConstants");
console.log(CYConstants.NOT_FOUND); // Prints -1
console.log(CYConstants.EMPTY_STRING); // Prints "" (Nothing!)
Here's a more verbose solution. Less elegant, but probably faster:
public static String stripNonDigits(
final CharSequence input /* inspired by seh's comment */){
final StringBuilder sb = new StringBuilder(
input.length() /* also inspired by seh's comment */);
for(int i = 0; i < input.length(); i++){
final char c = input.charAt(i);
if(c > 47 && c < 58){
sb.append(c);
}
}
return sb.toString();
}
Test Code:
public static void main(final String[] args){
final String input = "0-123-abc-456-xyz-789";
final String result = stripNonDigits(input);
System.out.println(result);
}
Output:
0123456789
BTW: I did not use Character.isDigit(ch) because it accepts many other chars except 0 - 9.
Thanks to some answers above, I experimented and ultimately found that all you need to do is edit the "position" attribute in the Modal Dialog's definition:
position:['middle',20],
JQuery had no problems with the "middle" text for the horizontal "X" value and my dialog popped up in the middle, 20px down from the top.
I heart JQuery.
Using islice
and chain.from_iterable
:
>>> from itertools import chain, islice
>>> elements = [(1,1,1),(2,3,7),(3,5,10)]
>>> list(chain.from_iterable(islice(item, 1, 2) for item in elements))
[1, 3, 5]
This can be useful when you need more than one element:
>>> elements = [(0, 1, 2, 3, 4, 5),
(10, 11, 12, 13, 14, 15),
(20, 21, 22, 23, 24, 25)]
>>> list(chain.from_iterable(islice(tuple_, 2, 5) for tuple_ in elements))
[2, 3, 4, 12, 13, 14, 22, 23, 24]
Well what you have to "import" (use) is the namespace of MyClass
not the class name itself. If both classes are in the same namespace, you don't have to "import" it.
Definition MyClass.cs
namespace Ns1
{
public class MyClass
{
...
}
}
Usage AnotherClass.cs
using Ns1;
namespace AnotherNs
{
public class AnotherClass
{
public AnotherClass()
{
var myInst = new MyClass();
}
}
}
If you want all packages in that repository, use ...
to signify that, like:
go get code.google.com/p/go.text/...
use Class="NO-CACHE"
sample html:
<div>
<img class="NO-CACHE" src="images/img1.jpg" />
<img class="NO-CACHE" src="images/imgLogo.jpg" />
</div>
jQuery:
$(document).ready(function ()
{
$('.NO-CACHE').attr('src',function () { return $(this).attr('src') + "?a=" + Math.random() });
});
javascript:
var nods = document.getElementsByClassName('NO-CACHE');
for (var i = 0; i < nods.length; i++)
{
nods[i].attributes['src'].value += "?a=" + Math.random();
}
Result: src="images/img1.jpg" => src="images/img1.jpg?a=0.08749723793963926"
According to WWDC2015 Distribution Whats New
Setting "ITSAppUsesNonExemptEncryption" to "NO" in info.plist works fine. if no cryptographic content in your app.
I had got this pop up During selecting build for internal testing i didn't included "ITSAppUsesNonExemptEncryption" key in my info.plist but still worked for me.
Even i successfully uploaded new application didn't included "ITSEncryptionExportComplianceCode" and "ITSAppUsesNonExemptEncryption" keys.
Also Apple Doc.
Important: If your app requires that you provide additional documents for the encryption review, your app won’t have the Ready for Sale status on the store until Export Compliance has reviewed and approved your documents. The app can’t be distributed for prerelease testing until Export Compliance has reviewed and approved it.
If your app is not using encryption and you don’t want to have to answer these questions at the time of submission, you can provide export compliance information with your build. You can also provide new or updated documentation via iTunes Connect to receive the appropriate key string value to include with your build before uploading it to iTunes Connect.
To add export compliance documentation in iTunes Connect:
Go to the Encryption section under Features. Click the plus sign next to the appropriate platform section. Answer the questions appropriately. Attach the file when prompted. Click Save. Your documents will then be sent for review immediately and the status of your document will show in Compliance Review. A key value will also be generated automatically that you can include in your Info.plist file. For more information on including the key value with your build, see the Resources and Help section Trade Compliance.
You can upload a build without an export compliance key. If you include a key, it can indicate that you do not need export compliance documentation; this requires no approval. If you include a key that references a specific export compliance document, that document must be approved; it cannot be in In Review or Rejected.
You can review your answers at any time by clicking the document file name and selecting More Information. If you need to update your documentation or change any of the answers to the questions, you will need to repeat the steps above to add a new document that corresponds with your changes.
This is a derivative of @Ralph suggestion that I've been using. Add the c:url
to the top of your JSP.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:url value="/" var="root" />
Then just reference the root variable in your page:
<link rel="stylesheet" href="${root}templates/style/main.css">
In the latest Bootstrap 3 version (bootstrap-datepicker.js) beforeShowDay
expects a result in this format:
{ enabled: false, classes: "class-name", tooltip: "Holiday!" }
Alternatively, if you don't care about the CSS and tooltip then simply return a boolean false
to make the date unselectable.
Also, there is no $.datepicker.noWeekends
, so you need to do something along the lines of this:
var HOLIDAYS = { // Ontario, Canada holidays
2017: {
1: { 1: "New Year's Day"},
2: { 20: "Family Day" },
4: { 17: "Easter Monday" },
5: { 22: "Victoria Day" },
7: { 1: "Canada Day" },
8: { 7: "Civic Holiday" },
9: { 4: "Labour Day" },
10: { 9: "Thanksgiving" },
12: { 25: "Christmas", 26: "Boxing Day"}
}
};
function filterNonWorkingDays(date) {
// Is it a weekend?
if ([ 0, 6 ].indexOf(date.getDay()) >= 0)
return { enabled: false, classes: "weekend" };
// Is it a holiday?
var h = HOLIDAYS;
$.each(
[ date.getYear() + 1900, date.getMonth() + 1, date.getDate() ],
function (i, x) {
h = h[x];
if (typeof h === "undefined")
return false;
}
);
if (h)
return { enabled: false, classes: "holiday", tooltip: h };
// It's a regular work day.
return { enabled: true };
}
$("#datePicker").datepicker({ beforeShowDay: filterNonWorkingDays });
There should be svn
utility on you box, if installed:
$ svn checkout http://example.com/svn/somerepo somerepo
This will check out a working copy from a specified repository to a directory somerepo
on our file system.
You may want to print commands, supported by this utility:
$ svn help
uname -a
output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm
or the following command:
$ sudo yum install subversion
From what you printed, it seems var2
is an array containing one string. Or actually, it appears to hold the result of running .inspect
on an array containing one string. It would be helpful to show how you are initializing them.
irb(main):005:0* v1 = "test"
=> "test"
irb(main):006:0> v2 = ["test"]
=> ["test"]
irb(main):007:0> v3 = v2.inspect
=> "[\"test\"]"
irb(main):008:0> puts v1,v2,v3
test
test
["test"]
EDIT 2013-12-11 - This answer is very old. It is still valid and correct, but people looking at this should prefer the new format syntax.
You can use string formatting like this:
>>> print '%5s' % 'aa'
aa
>>> print '%5s' % 'aaa'
aaa
>>> print '%5s' % 'aaaa'
aaaa
>>> print '%5s' % 'aaaaa'
aaaaa
Basically:
%
character informs python it will have to substitute something to a tokens
character informs python the token will be a string5
(or whatever number you wish) informs python to pad the string with spaces up to 5 characters.In your specific case a possible implementation could look like:
>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
... print 'value %3s - num of occurances = %d' % item # %d is the token of integers
...
value a - num of occurances = 1
value ab - num of occurances = 1
value abc - num of occurances = 1
SIDE NOTE: Just wondered if you are aware of the existence of the itertools
module. For example you could obtain a list of all your combinations in one line with:
>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']
and you could get the number of occurrences by using combinations
in conjunction with count()
.
C# is a little different in this respect with JavaScript. Because of the strict checks, you define the size of the array and you are supposed to know everything about the array such as its bounds, where the last item was put and what items are unused. You are supposed to copy all the elements of the array into a new, bigger one, if you want to resize it.
So, if you use a raw array, there's no other way other than to maintain the last empty, available index
assign items to the array at this index, like you're already doing.
However, if you'd like to have the runtime maintain this information and completely abstract away the array, but still use an array underneath, then C# provides a class named ArrayList
that provides this abstraction.
The ArrayList
abstracts a loosely typed array of Object
s. See the source here.
It takes care of all the issues like resizing the array, maintaining the last index that is available, etc. However, it abstracts / encapsulates this information from you. All you use is the ArrayList
.
To push an item of any type into the underlying array at the end of the underlying array, call the Add
method on the ArrayList
like so:
/* you may or may not define a size using a constructor overload */
var arrayList = new ArrayList();
arrayList.Add("Foo");
EDIT: A note about type restriction
Like every programming language and runtime does, C# categorizes heap objects from those that will not go on the heap and will only stay on the function's argument stack. C# notes this distinction by the name Value types vs. Reference types. All things whose value goes on the stack are called Value types, and those that will go on the heap are called Reference types. This is loosely similar to JavaScript's distinction between objects and literals.
You can put anything into an ArrayList
in C#, whether the thing is a value type or a reference type. This makes it closest to the JavaScript array in terms of typelessness, although neither of the three -- the JavaScript array, the JavaScript language and the C# ArrayList -- are actually type-less.
So, you could put a number literal, a string literal, an object of a class you made up, a boolean, a float, a double, a struct, just about anything you wanted into an ArrayList
.
That is because the ArrayList
internally maintains and stores all that you put into it, into an array of Object
s, as you will have noted in my original answer and the linked source code.
And when you put something that isn't an object, C# creates a new object of type Object
, stores the value of the thing you put into the ArrayList
into this new Object
type object. This process is called boxing and isn't very much unlike the JavaScript boxing mechanism.
For e.g. in JavaScript, while you could use a numeric literal to invoke a function on the Number
object, you couldn't add something to the number literal's prototype.
// Valid javascript
var s = 4.toString();
// Invalid JavaScript code
4.prototype.square = () => 4 * 4;
var square = 4.square();
Just like JavaScript boxes the numeric literal 4 in the call to the toString
method, C# boxes all things that are not objects into an Object
type when putting them into an ArrayList
.
var arrayList = new ArrayList();
arrayList.Add(4); // The value 4 is boxed into a `new Object()` first and then that new object is inserted as the last element in the `ArrayList`.
This involves a certain penalty, as it does in the case of JavaScript as well.
In C#, you can avoid this penalty as C# provides a strongly typed version of the ArrayList
, known as the List<T>
. So it follows that you cannot put anything into a List<T>
; just T
types.
However, I assume from your question's text that you already knew that C# had generic structures for strongly typed items. And your question was to have a JavaScript like data structure exhibiting the semantics of typelessness and elasticity, like the JavaScript Array
object. In this case, the ArrayList
comes closest.
It is also clear from your question that your interest was academic and not to use the structure in a production application.
So, I assume that for a production application, you would already know that a generic / strongly typed data structure (List<T>
for example) is better performing than its non-typed one (ArrayList
for example).
let's consider the final output rendered to the user of what we want to achieve: a padded textarea with both a border and a padding, which characteristics are that being clicked they pass the focus to our textarea, and the advantage of an automatic 100% width typical of block elements.
The best approach in my opinion is to use low level solutions as far as possible, to reach the maximum browsers support. In this case the only HTML could work fine, avoiding the use of Javascript (which anyhow we all love).
The LABEL tag comes in our help because has such behaviour and is allowed to contain the input elements it must address to. Its default style is the one of inline elements, so, giving to the label a block display style we can avail ourselves of the automatic 100% width including padding and borders, while the inner textarea has no border, no padding and a 100% width.
Taking a look at the W3C specifics other advantages we may notice are:
See W3C specifics for more detailed information.
Simple example:
.container { _x000D_
width: 400px; _x000D_
border: 3px _x000D_
solid #f7c; _x000D_
}_x000D_
.textareaContainer {_x000D_
display: block;_x000D_
border: 3px solid #38c;_x000D_
padding: 10px;_x000D_
}_x000D_
textarea { _x000D_
width: 100%; _x000D_
margin: 0; _x000D_
padding: 0; _x000D_
border-width: 0; _x000D_
}
_x000D_
<body>_x000D_
<div class="container">_x000D_
I am the container_x000D_
<label class="textareaContainer">_x000D_
<textarea name="text">I am the padded textarea with a styled border...</textarea>_x000D_
</label>_x000D_
</div>_x000D_
</body>
_x000D_
The padding and border of the .textareaContainer elements are the ones we want to give to the textarea. Try editing them to style it as you want. I gave large and visible padding and borders to the .textareaContainer element to let you see their behaviour when clicked.
Here is some methods I've been used in the past to trim strings in js:
String.prototype.ltrim = function( chars ) {
chars = chars || "\\s*";
return this.replace( new RegExp("^[" + chars + "]+", "g"), "" );
}
String.prototype.rtrim = function( chars ) {
chars = chars || "\\s*";
return this.replace( new RegExp("[" + chars + "]+$", "g"), "" );
}
String.prototype.trim = function( chars ) {
return this.rtrim(chars).ltrim(chars);
}
Note that you can build your own cross-platform library in python using conditional imports. e.g.
import platform
if platform.system() == 'Linux':
import LinuxMac
mac_address = LinuxMac.get_mac_address()
elif platform.system() == 'Windows':
# etc
This will allow you to use os.system calls or platform-specific libraries.
Run 'go env' and see where your GOPATH is currently pointing towards. If you change to that directory, your 'go get..etc' command should work.
Did you try something like:
body {background: url('[url to your image]') no-repeat right bottom;}
df.loc[df.LastName == 'Smith']
will return the row
ClientID LastName
1 67 Smith
and
df.loc[df.LastName == 'Smith'].index
will return the index
Int64Index([1], dtype='int64')
NOTE: Column names 'LastName' and 'Last Name' or even 'lastname' are three unique names. The best practice would be to first check the exact name using df.columns. If you really need to strip the column names of all the white spaces, you can first do
df.columns = [x.strip().replace(' ', '') for x in df.columns]
Often, you will want a fast install from local archives, without probing PyPI.
First, download the archives that fulfill your requirements:
$ pip install --download <DIR> -r requirements.txt
Then, install using –find-links
and –no-index
:
$ pip install --no-index --find-links=[file://]<DIR> -r requirements.txt
Fast and clean way using LINQ
int total = dataGridView1.Rows.Cast<DataGridViewRow>()
.Sum(t => Convert.ToInt32(t.Cells[1].Value));
verified on VS2013
For make responsive table you can make 100% of each ‘td’ and insert related heading in the ‘td’ on the mobile(less the ’768px’ width).
See More:
http://wonderdesigners.com/?p=227
To demonstrate how this works--
CREATE TABLE T1 (ID INT NOT NULL, SomeVal CHAR(1));
ALTER TABLE T1 ADD CONSTRAINT [PK_ID] PRIMARY KEY CLUSTERED (ID);
CREATE TABLE T2 (FKID INT, SomeOtherVal CHAR(2));
INSERT T1 (ID, SomeVal) SELECT 1, 'A';
INSERT T1 (ID, SomeVal) SELECT 2, 'B';
INSERT T2 (FKID, SomeOtherVal) SELECT 1, 'A1';
INSERT T2 (FKID, SomeOtherVal) SELECT 1, 'A2';
INSERT T2 (FKID, SomeOtherVal) SELECT 2, 'B1';
INSERT T2 (FKID, SomeOtherVal) SELECT 2, 'B2';
INSERT T2 (FKID, SomeOtherVal) SELECT 3, 'C1'; --orphan
INSERT T2 (FKID, SomeOtherVal) SELECT 3, 'C2'; --orphan
--Add the FK CONSTRAINT will fail because of existing orphaned records
ALTER TABLE T2 ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID); --fails
--Same as ADD above, but explicitly states the intent to CHECK the FK values before creating the CONSTRAINT
ALTER TABLE T2 WITH CHECK ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID); --fails
--Add the CONSTRAINT without checking existing values
ALTER TABLE T2 WITH NOCHECK ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID); --succeeds
ALTER TABLE T2 CHECK CONSTRAINT FK_T2_T1; --succeeds since the CONSTRAINT is attributed as NOCHECK
--Attempt to enable CONSTRAINT fails due to orphans
ALTER TABLE T2 WITH CHECK CHECK CONSTRAINT FK_T2_T1; --fails
--Remove orphans
DELETE FROM T2 WHERE FKID NOT IN (SELECT ID FROM T1);
--Enabling the CONSTRAINT succeeds
ALTER TABLE T2 WITH CHECK CHECK CONSTRAINT FK_T2_T1; --succeeds; orphans removed
--Clean up
DROP TABLE T2;
DROP TABLE T1;
In Jan2018 the only solution worked for me:
<?php
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){
echo "<br> Line to show.";
echo str_pad('',4096)."\n";
ob_flush();
flush();
sleep(2);
}
echo "Done.";
ob_end_flush();
?>
First, this is not an error. The 3xx
denotes a redirection. The real errors are 4xx
(client error) and 5xx
(server error).
If a client gets a 304 Not Modified
, then it's the client's responsibility to display the resouce in question from its own cache. In general, the proxy shouldn't worry about this. It's just the messenger.
This works when factor will always be positive:
int round_up(int num, int factor)
{
return num + factor - 1 - (num + factor - 1) % factor;
}
Edit: This returns round_up(0,100)=100
. Please see Paul's comment below for a solution that returns round_up(0,100)=0
.
Go to bin directory of Zookeeper and type
./zkServer.sh status
For More info go through below link:
http://www.ibm.com/developerworks/library/bd-zookeeper/
Hope this could help you.
The documentation says:
Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is,
> $("form").validate() is called first.
Did you do that? The error message kind of indicates that you didn't.
mov cx,3
loopstart:
do stuff
dec cx ;Note: decrementing cx and jumping on result is
jnz loopstart ;much faster on Intel (and possibly AMD as I haven't
;tested in maybe 12 years) rather than using loop loopstart
for me it was a problem with lfs files that were not downloaded
git lfs fetch --all
fixed the problem.
Didn't quite see this variation in the answers yet. I had an additional constraint where I needed, given an initial seed, to select the same set of rows each time.
For MS SQL:
Minimum example:
select top 10 percent *
from table_name
order by rand(checksum(*))
Normalized execution time: 1.00
NewId() example:
select top 10 percent *
from table_name
order by newid()
Normalized execution time: 1.02
NewId()
is insignificantly slower than rand(checksum(*))
, so you may not want to use it against large record sets.
Selection with Initial Seed:
declare @seed int
set @seed = Year(getdate()) * month(getdate()) /* any other initial seed here */
select top 10 percent *
from table_name
order by rand(checksum(*) % @seed) /* any other math function here */
If you need to select the same set given a seed, this seems to work.
Would like to thank you for some excellent replies. @AR., your a star and it works perfectly. I had noticed last night that the Excel.exe
was not closing; so I did some research and found out about how to release the COM objects. Here is my final code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using Excel;
namespace testExcelconsoleApp
{
class Program
{
private String fileLoc = @"C:\temp\test.xls";
static void Main(string[] args)
{
Program p = new Program();
p.createExcel();
}
private void createExcel()
{
Excel.Application excelApp = null;
Excel.Workbook workbook = null;
Excel.Sheets sheets = null;
Excel.Worksheet newSheet = null;
try
{
FileInfo file = new FileInfo(fileLoc);
if (file.Exists)
{
excelApp = new Excel.Application();
workbook = excelApp.Workbooks.Open(fileLoc, 0, false, 5, "", "",
false, XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
sheets = workbook.Sheets;
//check columns exist
foreach (Excel.Worksheet sheet in sheets)
{
Console.WriteLine(sheet.Name);
sheet.Select(Type.Missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
}
newSheet = (Worksheet)sheets.Add(sheets[1], Type.Missing, Type.Missing, Type.Missing);
newSheet.Name = "My New Sheet";
newSheet.Cells[1, 1] = "BOO!";
workbook.Save();
workbook.Close(null, null, null);
excelApp.Quit();
}
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(newSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
newSheet = null;
sheets = null;
workbook = null;
excelApp = null;
GC.Collect();
}
}
}
}
Thank you for all your help.
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
First up, this has got nothing to do with String
, it is about arrays.. and that too specifically about declarative initialization of arrays.
As discussed by everyone in almost every answer here, you can, while declaring a variable, use:
String names[] = {"x","y","z"};
However, post declaration, if you want to assign an instance of an Array:
names = new String[] {"a","b","c"};
AFAIK, the declaration syntax is just a syntactic sugar and it is not applicable anymore when assigning values to variables because when values are assigned you need to create an instance properly.
However, if you ask us why it is so? Well... good luck getting an answer to that. Unless someone from the Java committee answers that or there is explicit documentation citing the said syntactic sugar.
This should take care of space, tab and newline:
data = data.replaceAll("[ \t\n\r]*", " ");
There are several possible causes.
The other end has deliberately reset the connection, in a way which I will not document here. It is rare, and generally incorrect, for application software to do this, but it is not unknown for commercial software.
More commonly, it is caused by writing to a connection that the other end has already closed normally. In other words an application protocol error.
It can also be caused by closing a socket when there is unread data in the socket receive buffer.
In Windows, 'software caused connection abort', which is not the same as 'connection reset', is caused by network problems sending from your end. There's a Microsoft knowledge base article about this.
The approved solution doesn't work in my case, so my solution is the following one:
''' The column name in the example case is "Unnamed: 7"
but it works with any other name ("Unnamed: 0" for example). '''
df.rename({"Unnamed: 7":"a"}, axis="columns", inplace=True)
# Then, drop the column as usual.
df.drop(["a"], axis=1, inplace=True)
Hope it helps others.
I personally prefer to use the method setImageResource()
like this.
ImageView myImageView = (ImageView)findViewById(R.id.myImage);
myImageView.setImageResource(R.drawable.icon);
You are doing a cartesian join. This means that if you wouldn't have even have the single where clause, the number of results you get would be book_customer size times books size times book_order size times publisher size.
In order words, the result set gets blown up because you didn't add meaningful join clauses. Your correct query should look something like this:
SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date", p.publishername
FROM book_customer bc, books b, book_order bo, publisher p
WHERE bc.book_id = b.book_id
AND bo.book_id = b.book_id
(etc.)
AND publishername = 'PRINTING IS US';
Note: usually it is adviced to not use the implicit joins like in this query, but use the INNER JOIN
syntax. I am assuming however, that this syntax is used in your study material so I've left it in.
Try just getting the underlying PDO instance. If that fails, then Laravel was unable to connect to the database!
// Test database connection
try {
DB::connection()->getPdo();
} catch (\Exception $e) {
die("Could not connect to the database. Please check your configuration. error:" . $e );
}
These work great for reading left / right "n" characters from a string, but, at least with BBC BASIC, the LEFT$()
and RIGHT$()
functions allowed you to change the left / right "n" characters too...
E.g.:
10 a$="00000"
20 RIGHT$(a$,3)="ABC"
30 PRINT a$
Would produce:
00ABC
Edit : Since writing this, I've come up with my own solution...
def left(s, amount = 1, substring = ""):
if (substring == ""):
return s[:amount]
else:
if (len(substring) > amount):
substring = substring[:amount]
return substring + s[:-amount]
def right(s, amount = 1, substring = ""):
if (substring == ""):
return s[-amount:]
else:
if (len(substring) > amount):
substring = substring[:amount]
return s[:-amount] + substring
To return n characters you'd call
substring = left(string,<n>)
Where defaults to 1 if not supplied. The same is true for right()
To change the left or right n characters of a string you'd call
newstring = left(string,<n>,substring)
This would take the first n characters of substring and overwrite the first n characters of string, returning the result in newstring. The same works for right().
You can use the DateTime.Add() method to add the time to the date.
DateTime date = DateTime.Now;
TimeSpan time = new TimeSpan(36, 0, 0, 0);
DateTime combined = date.Add(time);
Console.WriteLine("{0:dddd}", combined);
You can also create your timespan by parsing a String, if that is what you need to do.
Alternatively, you could look at using other controls. You didn't mention if you are using winforms, wpf or asp.net, but there are various date and time picker controls that support selection of both date and time.
Use Integer.toString(tmpInt)
instead.
In Java8 you use the new Time API, and convert an Instant in to a ZonedDateTime Using the UTC TimeZone
The strptime() approach does not work for me. I get another cleaner solution, using cast:
from pyspark.sql.types import DateType
spark_df1 = spark_df.withColumn("record_date",spark_df['order_submitted_date'].cast(DateType()))
#below is the result
spark_df1.select('order_submitted_date','record_date').show(10,False)
+---------------------+-----------+
|order_submitted_date |record_date|
+---------------------+-----------+
|2015-08-19 12:54:16.0|2015-08-19 |
|2016-04-14 13:55:50.0|2016-04-14 |
|2013-10-11 18:23:36.0|2013-10-11 |
|2015-08-19 20:18:55.0|2015-08-19 |
|2015-08-20 12:07:40.0|2015-08-20 |
|2013-10-11 21:24:12.0|2013-10-11 |
|2013-10-11 23:29:28.0|2013-10-11 |
|2015-08-20 16:59:35.0|2015-08-20 |
|2015-08-20 17:32:03.0|2015-08-20 |
|2016-04-13 16:56:21.0|2016-04-13 |
In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.
I'll just add to this answer–above–which solved my issue.
To set AWS/CloudFront Distribution Point to torward the CORS Origin Header, click into the edit interface for the Distribution Point:
Go to the behaviors tab and edit the behavior, changing "Cache Based on Selected Request Headers" from None to Whitelist, then make sure Origin
is added to the whitelisted box. See Configuring CloudFront to Respect CORS Settings in the AWS Docs for more.
...I have a string "-9o0-9909" and I want to replace it with another string.
The code below will do that.
var str = '-9o0-9909';
str = 'new string';
Jokes aside, replacing text nodes is not trivial with JavaScript.
I've written a post about this: Replacing text with JavaScript.
You can do something like:
object.attribute = value
object.save(:validate => false)
As of PHP 7.1 you can simply do this:
$date = new DateTime( "NOW" );
echo $date->format( "m-d-Y H:i:s.u" );
It will display as:
04-11-2018 10:54:01.321688
You can check for IsNull condition.
If IsNull({TABLE.FIELD}) or {TABLE.FIELD} = "" then
// do something
I used this and it worked : it is very simple and works fine.
JTable myTable = new JTable();
myTable.setEnabled(false);
Because $newDate
is an object of type DateTime
, not a string. The documentation is explicit:
Returns new
DateTime
object formatted according to the specified format.
If you want to convert from a string to DateTime
back to string to change the format, call DateTime::format
at the end to get a formatted string out of your DateTime
.
$newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB);
$newDate = $newDate->format('d/m/Y'); // for example
Rules are used to enhance the behaviour of each test method in a generic way. Junit rule intercept the test method and allows us to do something before a test method starts execution and after a test method has been executed.
For example, Using @Timeout rule we can set the timeout for all the tests.
public class TestApp {
@Rule
public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);
......
......
}
@TemporaryFolder rule is used to create temporary folders, files. Every time the test method is executed, a temporary folder is created and it gets deleted after the execution of the method.
public class TempFolderTest {
@Rule
public TemporaryFolder tempFolder= new TemporaryFolder();
@Test
public void testTempFolder() throws IOException {
File folder = tempFolder.newFolder("demos");
File file = tempFolder.newFile("Hello.txt");
assertEquals(folder.getName(), "demos");
assertEquals(file.getName(), "Hello.txt");
}
}
You can see examples of some in-built rules provided by junit at this link.
sklearn.cross_validation
is deprecated since version 0.18, instead you should use sklearn.model_selection
as show below
from sklearn.model_selection import train_test_split
import numpy
with open("datafile.txt", "rb") as f:
data = f.read().split('\n')
data = numpy.array(data) #convert array to numpy type array
x_train ,x_test = train_test_split(data,test_size=0.5) #test_size=0.5(whole_data)
Unfortunately solution provided by @hakani is not two-way binding. It just handles One-way changing model from UI/FrontEnd part.
Instead the simple:
<input [(ngModel)]="checkboxFlag" type="checkbox"/>
will do two-way binding for checkbox.
Afterwards, when Model checkboxFlag is changed from Backend or UI part - voila, checkboxFlag stores actual checkbox state.
To be sure I've prepared Plunker code to present the result : https://plnkr.co/edit/OdEAPWRoqaj0T6Yp0Mfk
Just to complete this answer you should include the import { FormsModule } from '@angular/forms'
into app.module.ts
and add to imports array i.e
import { FormsModule } from '@angular/forms';
[...]
@NgModule({
imports: [
[...]
FormsModule
],
[...]
})
With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:
function getCaret(node) {
if (node.selectionStart) {
return node.selectionStart;
} else if (!document.selection) {
return 0;
}
var c = "\001",
sel = document.selection.createRange(),
dul = sel.duplicate(),
len = 0;
dul.moveToElementText(node);
sel.text = c;
len = dul.text.indexOf(c);
sel.moveStart('character',-1);
sel.text = "";
return len;
}
I also recommend you to check the jQuery FieldSelection Plugin, it allows you to do that and much more...
Edit: I actually re-implemented the above code:
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
Check an example here.
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width_px = Resources.getSystem().getDisplayMetrics().widthPixels;
int height_px =Resources.getSystem().getDisplayMetrics().heightPixels;
int pixeldpi = Resources.getSystem().getDisplayMetrics().densityDpi;
int width_dp = (width_px/pixeldpi)*160;
int height_dp = (height_px/pixeldpi)*160;
You probably need to declare the code below for height:100%
to work for your divs
html, body {margin:0;padding:0;height:100%;}
fiddle: http://jsfiddle.net/5KYC3/
Separate each group of text into its own substring and then concatenate those substrings:
public Address(String street, String city, String state, String zip ) {
this.street = street;
this.city = city;
// Now checking to make sure that state has no spaces...
int position = state.indexOf(" ");
if(position >=0) {
//now putting state back together if it has spaces...
state = state.substring(0, position) + state.substring(position + 1);
}
}
$deleted = $_POST['checkbox'];
$sql = "DELETE FROM $tbl_name WHERE id IN (".implode(",", $deleted ) . ")";
These solutions only partially worked for me because I was doing multiple aggregations. Here is a sample output of my grouped by that I wanted to convert to a dataframe:
Because I wanted more than the count provided by reset_index(), I wrote a manual method for converting the image above into a dataframe. I understand this is not the most pythonic/pandas way of doing this as it is quite verbose and explicit, but it was all I needed. Basically, use the reset_index() method explained above to start a "scaffolding" dataframe, then loop through the group pairings in the grouped dataframe, retrieve the indices, perform your calculations against the ungrouped dataframe, and set the value in your new aggregated dataframe.
df_grouped = df[['Salary Basis', 'Job Title', 'Hourly Rate', 'Male Count', 'Female Count']]
df_grouped = df_grouped.groupby(['Salary Basis', 'Job Title'], as_index=False)
# Grouped gives us the indices we want for each grouping
# We cannot convert a groupedby object back to a dataframe, so we need to do it manually
# Create a new dataframe to work against
df_aggregated = df_grouped.size().to_frame('Total Count').reset_index()
df_aggregated['Male Count'] = 0
df_aggregated['Female Count'] = 0
df_aggregated['Job Rate'] = 0
def manualAggregations(indices_array):
temp_df = df.iloc[indices_array]
return {
'Male Count': temp_df['Male Count'].sum(),
'Female Count': temp_df['Female Count'].sum(),
'Job Rate': temp_df['Hourly Rate'].max()
}
for name, group in df_grouped:
ix = df_grouped.indices[name]
calcDict = manualAggregations(ix)
for key in calcDict:
#Salary Basis, Job Title
columns = list(name)
df_aggregated.loc[(df_aggregated['Salary Basis'] == columns[0]) &
(df_aggregated['Job Title'] == columns[1]), key] = calcDict[key]
If a dictionary isn't your thing, the calculations could be applied inline in the for loop:
df_aggregated['Male Count'].loc[(df_aggregated['Salary Basis'] == columns[0]) &
(df_aggregated['Job Title'] == columns[1])] = df['Male Count'].iloc[ix].sum()
Here is another choice: Chaosreader
So I need to debug an application which posts xml to a 3rd party application. I found a brilliant little perl script which does all the hard work – you just chuck it a tcpdump output file, and it does all the manipulation and outputs everything you need...
The script is called chaosreader0.94. See http://www.darknet.org.uk/2007/11/chaosreader-trace-tcpudp-sessions-from-tcpdump/
It worked like a treat, I did the following:
tcpdump host www.blah.com -s 9000 -w outputfile; perl chaosreader0.94 outputfile
You cannot pass primitives by reference in Java. All variables of object type are actually pointers, of course, but we call them "references", and they are also always passed by value.
In a situation where you really need to pass a primitive by reference, what people will do sometimes is declare the parameter as an array of primitive type, and then pass a single-element array as the argument. So you pass a reference int[1], and in the method, you can change the contents of the array.
Here are clarified instruction combining Dawn Song's answer and Marmor's answer.
Drag a long Press Gesture Recognizer and drop it into your Table Cell. It will jump to the bottom of the list on the left.
Then connect the gesture recognizer the same way you would connect a button.
Add the code from Marmor in the the action handler
- (IBAction)handleLongPress:(UILongPressGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateBegan) {
CGPoint p = [sender locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
if (indexPath == nil) {
NSLog(@"long press on table view but not on a row");
} else {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if (cell.isHighlighted) {
NSLog(@"long press on table view at section %d row %d", indexPath.section, indexPath.row);
}
}
}
}
i know a Class is a bit the overkill
class Foo
{
private $sum = NULL;
public function __construct($array)
{
$this->sum[] = $array;
return $this;
}
public function getSum()
{
$sum = $this->sum;
for($i=0;$i<count($sum);$i++)
{
// get the last array index
$res[$i] = $sum[$i] + $sum[count($sum)-$i];
}
return $res;
}
}
$fo = new Foo($myarray)->getSum();
Combining the regex for the fourth option with any of the others doesn't work within one regex. 4 + 1 would mean either the string starts with @ or doesn't contain @ at all. You're going to need two separate comparisons to do that.
Try -
Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)
As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?
You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.
I am a beginner in iPhone apps and I still have an issue although I followed the above advices. It looks like POST variables are not received by my server - not sure if it comes from php or objective-c code ...
the objective-c part (coded following Chris' protocol methodo)
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.php"]];
// Specify that it will be a POST request
request.HTTPMethod = @"POST";
// This is how we set header fields
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [NSString stringWithFormat:@"user_name=%@&password=%@", self.userNameField.text , self.passwordTextField.text];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
//NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSLog(@"Response: %@",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
Below the php part :
if (isset($_POST['user_name'],$_POST['password']))
{
// Create connection
$con2=mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// retrieve POST vars
$username = $_POST['user_name'];
$password = $_POST['password'];
$sql = "INSERT INTO myTable (user_name, password) VALUES ('$username', '$password')";
$retval = mysqli_query( $sql, $con2 );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysqli_close($con2);
}
}
else
{
echo "No data input in php";
}
I have been stuck the last days on this one.
This means your MySQL table is corrupted and you need to repair it. Use
myisamchk -r /DB_NAME/wp_posts
from the command line. While you running the repair you should shut down your website temporarily so that no new connections are attempted to your database while its being repaired.
You want rows where that condition is true so you need a comma:
data[data$Ozone > 14, ]
It would help if you showed the code you are using for the simple test program. Put directly into the interpreter this seems to work.
>>> def pyth_test (x1, x2):
... print x1 + x2
...
>>> pyth_test(1, 2)
3
>>>
If you load a script block within your div via Ajax like this:
<div id="content">
<script type="text/javascript">
function myFunction() {
//do something
}
myFunction();
</script>
</div>
... it simply updates the DOM of your page, myFunction() does not necessarily get called.
You can use an Ajax callback method such as the one in jQuery's ajax() method to define what to execute when the request finishes.
What you are doing is different from loading a page with JavaScript included in it from the get-go (which does get executed).
An example of how to used the success callback and error callback after fetching some content:
$.ajax({
type: 'GET',
url: 'response.php',
timeout: 2000,
success: function(data) {
$("#content").html(data);
myFunction();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error retrieving content");
}
Another quick and dirty way is to use eval() to execute any script code that you've inserted as DOM text if you don't want to use jQuery or other library.
Ad-hoc Statments are just T-SQL Statements that it has a Where Clause , and that Where clause can actualy have a literal like :
Select * from member where member_no=285;
or a variable :
declare @mno INT=285;
Select * from member where member_no=@mno
Definitely, we cannot override static methods in Java. Because JVM resolves correct overridden method based upon the object at run-time by using dynamic binding in Java.
However, the static method in Java is associated with Class rather than the object and resolved and bonded during compile time.
Google included support for flavors in version 2.0 of the play services plugin. Since this version of the gradle plugin com.google.gms:google-services:2.0.0-alpha3
you can do this
Step 1: add to gradle
// To auto-generate google map api key of google-services.json
implementation 'com.google.android.gms:play-services-maps:17.0.0'
Step 2: add to AndroidManifest.xml in application tag
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_api_key" />
Step 3: download each flavor JSON file from firebase and add it
app/src/
flavor1/google-services.json
flavor2/google-services.json
Version 3.0.0 of the plugin searches for the json file in these locations (considering you have a flavor
flavor1 and a build type debug
):
/app/src/debug/google-services.json
/app/src/debug/flavor1/google-services.json
/app/google-services.json
This worked for me even using flavorDimensions. I have free & paid in one dimension and Mock & Prod in the other dimension. I also have 3 buildTypes: debug, release and staging. This is how it looks in my project for the FreeProd flavor:
How many google-services.json files will depend on your project's characteristics, but you will need at least one json file for every Google project.
If you want more details about what this plugin does with these json files, here it is: https://github.com/googlesamples/google-services/issues/54#issuecomment-165824720
Link to the official docs: https://developers.google.com/android/guides/google-services-plugin
Blog post with updated info: https://firebase.googleblog.com/2016/08/organizing-your-firebase-enabled-android-app-builds.html
And go here to check the latest version of this plugin: https://bintray.com/android/android-tools/com.google.gms.google-services/view
Try this:
$.ajax({
beforeSend: function (xhr){
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","text/json");
},
type: "POST",
//........
});
I solved it by making use of Type Assertions before exporting the component. TypeScript wasn't able to identify after composing it using redux 'compose' therefore I divided props types into IParentProps and IProps and use IParentProps while doing Type Assertions
import { compose } from 'react-redux'
import HOC1 from 'HOCs/HOC1'
import HOC2 from 'HOCs/HOC2'
type IParentProps = {}
type IProps = {}
const Component: React.FC<IProps & IParentProps> = React.memo((props) => {
return <SomeComponent {...props}/>
})
return compose(HOC1,HOC2)(Component) as React.FunctionComponent<IParentProps>
var result = input.GroupBy(x=>x.F1,(key,g)=>g.OrderBy(e=>e.F2).First());
I have used the following:
public static double Index2Freq(int i, double samples, int nFFT) {
return (double) i * (samples / nFFT / 2.);
}
public static int Freq2Index(double freq, double samples, int nFFT) {
return (int) (freq / (samples / nFFT / 2.0));
}
The inputs are:
i
: Bin to accesssamples
: Sampling rate in Hertz (i.e. 8000 Hz, 44100Hz, etc.)nFFT
: Size of the FFT vectorSet args = Wscript.Arguments
For Each arg In args
Wscript.Echo arg
Next
From a command prompt, run the script like this:
CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"
Will give results like this:
1
2
A
B
Arg with spaces
Using Javascript's es6 or node, you can do the following:
var [a,b,c,d] = [0,1,2,3]
And if you want to easily print multiple variables in a single line, just do this:
console.log(a, b, c, d)
0 1 2 3
This is similar to @alex gray 's answer here, but this example is in Javascript instead of CoffeeScript.
Note that this uses Javascript's array destructuring assignment
The accepted answer is short and sweet, but here is an alternate syntax allowing to provide a separator in Python 3.x.
print(*3*('-',), sep='_')
Demo : http://jsfiddle.net/xavi3r/D3prt/
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
Original Answer: Resetting a multi-stage form with jQuery
Mike's suggestion (from the comments) to keep checkbox and selects intact!
Warning: If you're creating elements (so they're not in the dom), replace :hidden
with [type=hidden]
or all fields will be ignored!
$(':input','#myform')
.removeAttr('checked')
.removeAttr('selected')
.not(':button, :submit, :reset, :hidden, :radio, :checkbox')
.val('');
First, declare the output variable:
DECLARE @MyOutputParameter INT;
Then, execute the stored procedure, and you can do it without parameter's names, like this:
EXEC my_stored_procedure 'param1Value', @MyOutputParameter OUTPUT
or with parameter's names:
EXEC my_stored_procedure @param1 = 'param1Value', @myoutput = @MyOutputParameter OUTPUT
And finally, you can see the output result by doing a SELECT
:
SELECT @MyOutputParameter
Eileen: No, it is not var nameVal = form.inputname.val();
. It should be either...
in jQuery:
// you can use IDs (easier)
var nameVal = $(form).find('#id').val();
// or use the [name=Fieldname] to search for the field
var nameVal = $(form).find('[name=Fieldname]').val();
Or in JavaScript:
var nameVal = this.form.FieldName.value;
Or a combination:
var nameVal = $(this.form.FieldName).val();
With jQuery, you could even loop through all of the inputs in the form:
$(form).find('input, select, textarea').each(function(){
var name = this.name;
// OR
var name = $(this).attr('name');
var value = this.value;
// OR
var value = $(this).val();
....
});
How about a function to rewrite the query string by looping through the $_GET array
! Rough outline of a suitable function
function query_string_exclude($exclude, $subject = $_GET, $array_prefix=''){
$query_params = array;
foreach($subject as $key=>$var){
if(!in_array($key,$exclude)){
if(is_array($var)){ //recursive call into sub array
$query_params[] = query_string_exclude($exclude, $var, $array_prefix.'['.$key.']');
}else{
$query_params[] = (!empty($array_prefix)?$array_prefix.'['.$key.']':$key).'='.$var;
}
}
}
return implode('&',$query_params);
}
Something like this would be good to keep handy for pagination links etc.
<a href="?p=3&<?= query_string_exclude(array('p')) ?>" title="Click for page 3">Page 3</a>
DOS/Windows: use Code page
chcp 65001>NUL
type ascii.txt > unicode.txt
Command chcp
can be used to change the code page. Code page 65001 is Microsoft name for UTF-8. After setting code page, the output generated by following commands will be of code page set.
I found using while IFS='=' read -r
to be a bit slow (I don't know why, maybe someone could briefly explain in a comment or point to a SO answer?). I also found @Nicolai answer very neat as a one-liner, but very inefficient as it will scan the entire properties file over and over again for every single call of prop
.
I found a solution that answers the question, performs well and it is a one-liner (bit verbose line though).
The solution does sourcing but massages the contents before sourcing:
#!/usr/bin/env bash
source <(grep -v '^ *#' ./app.properties | grep '[^ ] *=' | awk '{split($0,a,"="); print gensub(/\./, "_", "g", a[1]) "=" a[2]}')
echo $db_uat_user
Explanation:
grep -v '^ *#'
: discard comment lines
grep '[^ ] *='
: discards lines without =
split($0,a,"=")
: splits line at =
and stores into array a
, i.e. a[1] is the key, a[2] is the value
gensub(/\./, "_", "g", a[1])
: replaces .
with _
print gensub... "=" a[2]}
concatenates the result of gensub
above with =
and value.
Edit: As others pointed out, there are some incompatibilities issues (awk) and also it does not validate the contents to see if every line of the property file is actually a kv pair. But the goal here is to show the general idea for a solution that is both fast and clean. Sourcing seems to be the way to go as it loads the properties once that can be used multiple times.
Rails.application.routes.default_url_options[:host]= 'localhost:3000'
In the developemnt.rb / test.rb, can be more concise as following:
Rails.application.configure do
# ... other config ...
routes.default_url_options[:host] = 'localhost:3000'
end
In Angular (currently on Angular-6) .subscribe()
is a method on the Observable type. The Observable type is a utility that asynchronously or synchronously streams data to a variety of components or services that have subscribed to the observable.
The observable is an implementation/abstraction over the promise chain and will be a part of ES7 as a proposed and very supported feature. In Angular it is used internally due to rxjs being a development dependency.
An observable itself can be thought of as a stream of data coming from a source, in Angular this source is an API-endpoint, a service, a database or another observable. But the power it has is that it's not expecting a single response. It can have one or many values that are returned.
Link to rxjs for observable/subscribe docs here: https://rxjs-dev.firebaseapp.com/api/index/class/Observable#subscribe-
Subscribe takes 3 methods as parameters each are functions:
Within each of these, there is the potentional to pipe (or chain) other utilities called operators onto the results to change the form or perform some layered logic.
In the simple example above:
.subscribe(hero => this.hero = hero);
basically says on this observable take the hero being emitted and set it to this.hero
.
Adding this answer to give more context to Observables based off the documentation and my understanding.
It looks like you're trying to run it on a version of ASP.NET which is running CLR v2. It's hard to know exactly what's going on without more information about how you've deployed it, what version of IIS you're running etc (and to be frank I wouldn't be very much help at that point anyway, though others would). But basically, check your IIS and ASP.NET set-up, and make sure that everything is running v4. Check your application pool configuration, etc.
this
inside of doThings
is the window object. Try this instead:
var doThings = function (element) {
var eventHandler = function(ev, func){
if (element[ev] == undefined) {
return;
}
element[ev] = function(e){
func(e, element);
}
};
return {
eventHandler: eventHandler
};
};
A POSIX compliant one using the s
command:
sed '/CLIENTSCRIPT="foo"/s/.*/&\
CLIENTSCRIPT2="hello"/' file
Range("C1:C10").Formula = "=A1+B1"
Simple as that.
It autofills (FillDown) the range with the formula.
Use the -e argument and the escape character \n:
echo -e "This will generate a next line \nThis new line is the result"
The method
setParams()
like
httpget.getParams().setParameter("http.socket.timeout", new Integer(5000));
only adds HttpProtocol parameters.
To execute the httpGet you should append your parameters to the url manually
HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo¶m2=bar");
or use the post request the difference between get and post requests are explained here, if you are interested
You need to define something in the interface, such as:
public interface ITest
{
string Name { get; }
}
Implement ITest
in your classes:
public class MyClass1 : ITest
{
public string Name { get { return "Test1"; } }
}
public class MyClass2 : ITest
{
public string Name { get { return "Test2"; } }
}
Then restrict your generic Print
function, to ITest
:
public void Print<T>(T test) where T : ITest
{
}
As in Swift 3.x for upload image with parameter we can use below alamofire upload method-
static func uploadImageData(inputUrl:String,parameters:[String:Any],imageName: String,imageFile : UIImage,completion:@escaping(_:Any)->Void) {
let imageData = UIImageJPEGRepresentation(imageFile , 0.5)
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData!, withName: imageName, fileName: "swift_file\(arc4random_uniform(100)).jpeg", mimeType: "image/jpeg")
for key in parameters.keys{
let name = String(key)
if let val = parameters[name!] as? String{
multipartFormData.append(val.data(using: .utf8)!, withName: name!)
}
}
}, to:inputUrl)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
})
upload.responseJSON { response in
if let JSON = response.result.value {
completion(JSON)
}else{
completion(nilValue)
}
}
case .failure(let encodingError):
completion(nilValue)
}
}
}
Note: Additionally if our parameter is array of key-pairs then we can use
var arrayOfKeyPairs = [[String:Any]]()
let json = try? JSONSerialization.data(withJSONObject: arrayOfKeyPairs, options: [.prettyPrinted])
let jsonPresentation = String(data: json!, encoding: .utf8)
You can also use indexValue attribute for passing multiple parameters via object:
var someData = "hello";
jQuery.ajax({
url: "http://maps.google.com/maps/api/js?v=3",
indexValue: {param1:someData, param2:"Other data 2", param3: "Other data 3"},
dataType: "script"
}).done(function() {
console.log(this.indexValue.param1);
console.log(this.indexValue.param2);
console.log(this.indexValue.param3);
});
You can also use StringBuilder class
String b = new StringBuilder(a).toString();
Use of String or StringBuilder varies with your method requirements.
Personally, I would fix this in the .htaccess file. You should have access to that.
Define your CSS URL as such:
url(/image_dir/image.png);
In your .htacess file, put:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^image_dir/(.*) subdir/images/$1
or
RewriteRule ^image_dir/(.*) images/$1
depending on the site.
Uninlstallation
sudo apt remove nodejs
sudo apt remove npm
Fresh Installation
sudo apt install nodejs
sudo apt install npm
Configuration optional, in some cases users may face permission errors.
user defined directory where npm will install packages
mkdir ~/.npm-global
configure npm
npm config set prefix '~/.npm-global'
add directory to path
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.profile
refresh path for the current session
source ~/.profile
cross-check npm and node modules installed successfully in our system
node -v
npm -v
npx
sudo npm i -g npx
npx -v
Well-done we are ready to go... now you can easily use npx
anywhere in your system.
In my case, the annotation was on the getter() method instead of the field itself (ported from a legacy application).
Spring ignores the annotation in this case as well but doesn't complain. The solution was to move it to the field instead of the getter.
This is a simple solution for opening a new tab, changing focus to it, closing the tab and return focus to the old/original tab:
@Test
public void testTabs() {
driver.get("https://business.twitter.com/start-advertising");
assertStartAdvertising();
// considering that there is only one tab opened in that point.
String oldTab = driver.getWindowHandle();
driver.findElement(By.linkText("Twitter Advertising Blog")).click();
ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles());
newTab.remove(oldTab);
// change focus to new tab
driver.switchTo().window(newTab.get(0));
assertAdvertisingBlog();
// Do what you want here, you are in the new tab
driver.close();
// change focus back to old tab
driver.switchTo().window(oldTab);
assertStartAdvertising();
// Do what you want here, you are in the old tab
}
private void assertStartAdvertising() {
assertEquals("Start Advertising | Twitter for Business", driver.getTitle());
}
private void assertAdvertisingBlog() {
assertEquals("Twitter Advertising", driver.getTitle());
}
using label with label text changed
<input type="file" id="files" name="files" class="hidden"/>
<label for="files" id="lable_file">Select file</label>
add jquery
<script>
$("#files").change(function(){
$("#lable_file").html($(this).val().split("\\").splice(-1,1)[0] || "Select file");
});
</script>
Even though @Ignacio gave you a straightforward solution, I thought I might add an answer that gives you some more details about the issues with your code...
# You are not saving this result into a variable to reuse
os.path.join(src_dir, f)
# Should be
src_path = os.path.join(src_dir, f)
# you open the file but you dont again use a variable to reference
with open(f)
# should be
with open(src_path) as fh
# this is actually just looping over each character
# in each result of your os.listdir
for line in f
# you should loop over lines in the open file handle
for line in fh
# write? Is this a method you wrote because its not a python builtin function
write(line)
# write to the file
fh.write(line)
Erm, after understanding your question: are you sure that the signature-method only creates a SHA1 and encrypts it? GPG et al offer to compress/clear sign the data. Maybe this java-signature-alg also creates a detachable/attachable signature.
I know I am late to the party but here is a way to center a div with unknown dimension inside a parent of unknown dimension.
style:
<style>
.table {
display: table;
height: 100%;
margin: 0 auto;
}
.table-cell {
display: table-cell;
vertical-align: middle;
}
.centered {
background-color: red;
}
</style>
HTML:
<div class="table">
<div class="table-cell"><div class="centered">centered</div></div>
</div>
DEMO:
Check out this demo.
Connect with your mongodb instance from local system
It ll let you know all connected clients and their details
db.currentOp(true)
This will call add()
for each member. If you can find a more efficient way to put items into a hash set, then use that. Note that the inner class will likely generate garbage, if you're sensitive about that.
It seems to me as if the context is the object returned by new
, which is the HashSet
.
If you need to ask... More likely: will the people who come after you know this or not? Is it easy to understand and explain? If you can answer "yes" to both, feel free to use it.
If you're tired of this error. You can make Chrome not act out like this. I'm not saying it's the best way just saying it's a way.
As a workaround, a Windows registry key can be created to allow Google Chrome to use the commonName of a server certificate to match a hostname if the certificate is missing a subjectAlternativeName extension, as long as it successfully validates and chains to a locally-installed CA certificates.
Data type: Boolean [Windows:REG_DWORD] Windows registry location: HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome Windows/Mac/Linux/Android preference name: EnableCommonNameFallbackForLocalAnchors Value: 0x00000001 (Windows), true(Linux), true (Android), (Mac) To create a Windows registry key, simply follow these steps:
Open Notepad Copy and paste the following content into notepad Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome] "EnableCommonNameFallbackForLocalAnchors"=dword:00000001 Go to File > Save as Filename: any_filename.reg Save as type: All Files
Select a preferred location for the file
Click on Save
Double click on the saved file to run
Click on Yes on the Registry Editor warning
Found this information on Symantec support page: https://support.symantec.com/en_US/article.TECH240507.html
kramdown does exactly what you describe:
https://kramdown.gettalong.org/syntax.html#math-blocks
And it's way more reliable and well-defined than Markdown.
I've create a solution, mixed the information of varius post.
Its a form, that contains a label and one textbox. The console output is redirected to the textbox.
There are too a class called ConsoleView that implements three publics methods: Show(), Close(), and Release(). The last one is for leave open the console and activate the Close button for view results.
The forms is called FrmConsole. Here are the XAML and the c# code.
The use is very simple:
ConsoleView.Show("Title of the Console");
For open the console. Use:
System.Console.WriteLine("The debug message");
For output text to the console.
Use:
ConsoleView.Close();
For Close the console.
ConsoleView.Release();
Leaves open the console and enables the Close button
XAML
<Window x:Class="CustomControls.FrmConsole"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:CustomControls"
mc:Ignorable="d"
Height="500" Width="600" WindowStyle="None" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Topmost="True" Icon="Images/icoConsole.png">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="*"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Name="lblTitulo" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" FontFamily="Arial" FontSize="14" FontWeight="Bold" Content="Titulo"/>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="1" Name="txtInner" FontFamily="Arial" FontSize="10" ScrollViewer.CanContentScroll="True" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible" TextWrapping="Wrap"/>
</Grid>
<Button Name="btnCerrar" Grid.Row="2" Content="Cerrar" Width="100" Height="30" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center"/>
</Grid>
The code of the Window:
partial class FrmConsole : Window
{
private class ControlWriter : TextWriter
{
private TextBox textbox;
public ControlWriter(TextBox textbox)
{
this.textbox = textbox;
}
public override void WriteLine(char value)
{
textbox.Dispatcher.Invoke(new Action(() =>
{
textbox.AppendText(value.ToString());
textbox.AppendText(Environment.NewLine);
textbox.ScrollToEnd();
}));
}
public override void WriteLine(string value)
{
textbox.Dispatcher.Invoke(new Action(() =>
{
textbox.AppendText(value);
textbox.AppendText(Environment.NewLine);
textbox.ScrollToEnd();
}));
}
public override void Write(char value)
{
textbox.Dispatcher.Invoke(new Action(() =>
{
textbox.AppendText(value.ToString());
textbox.ScrollToEnd();
}));
}
public override void Write(string value)
{
textbox.Dispatcher.Invoke(new Action(() =>
{
textbox.AppendText(value);
textbox.ScrollToEnd();
}));
}
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
//DEFINICIONES DE LA CLASE
#region DEFINICIONES DE LA CLASE
#endregion
//CONSTRUCTORES DE LA CLASE
#region CONSTRUCTORES DE LA CLASE
public FrmConsole(string titulo)
{
InitializeComponent();
lblTitulo.Content = titulo;
Clear();
btnCerrar.Click += new RoutedEventHandler(BtnCerrar_Click);
Console.SetOut(new ControlWriter(txtInner));
DesactivarCerrar();
}
#endregion
//PROPIEDADES
#region PROPIEDADES
#endregion
//DELEGADOS
#region DELEGADOS
private void BtnCerrar_Click(object sender, RoutedEventArgs e)
{
Close();
}
#endregion
//METODOS Y FUNCIONES
#region METODOS Y FUNCIONES
public void ActivarCerrar()
{
btnCerrar.IsEnabled = true;
}
public void Clear()
{
txtInner.Clear();
}
public void DesactivarCerrar()
{
btnCerrar.IsEnabled = false;
}
#endregion
}
the code of ConsoleView class
static public class ConsoleView
{
//DEFINICIONES DE LA CLASE
#region DEFINICIONES DE LA CLASE
static FrmConsole console;
static Thread StatusThread;
static bool isActive = false;
#endregion
//CONSTRUCTORES DE LA CLASE
#region CONSTRUCTORES DE LA CLASE
#endregion
//PROPIEDADES
#region PROPIEDADES
#endregion
//DELEGADOS
#region DELEGADOS
#endregion
//METODOS Y FUNCIONES
#region METODOS Y FUNCIONES
public static void Show(string label)
{
if (isActive)
{
return;
}
isActive = true;
//create the thread with its ThreadStart method
StatusThread = new Thread(() =>
{
try
{
console = new FrmConsole(label);
console.ShowDialog();
//this call is needed so the thread remains open until the dispatcher is closed
Dispatcher.Run();
}
catch (Exception)
{
}
});
//run the thread in STA mode to make it work correctly
StatusThread.SetApartmentState(ApartmentState.STA);
StatusThread.Priority = ThreadPriority.Normal;
StatusThread.Start();
}
public static void Close()
{
isActive = false;
if (console != null)
{
//need to use the dispatcher to call the Close method, because the window is created in another thread, and this method is called by the main thread
console.Dispatcher.InvokeShutdown();
console = null;
StatusThread = null;
}
console = null;
}
public static void Release()
{
isActive = false;
if (console != null)
{
console.Dispatcher.Invoke(console.ActivarCerrar);
}
}
#endregion
}
I hope this result usefull.
Things are much easier nowadays: the builtin Snippet Generator supports the 'build' step (I don't know since when though).
Piggy backing on @MikkaS answer for Mongo Client v3.x, I just needed the async / await format, which looks slightly modified as this:
const myFunc = async () => {
// Prepping here...
// Connect
let client = await MongoClient.connect('mongodb://localhost');
let db = await client.db();
// Run the query
let cursor = await db.collection('customers').find({});
// Do whatever you want on the result.
}
So, pretty much here is your problem. The close button on the upper right of a window frame is not part of the WPF window, but it belongs to the part of the window frame that is controled by your OS. This means you will have to use Win32 interop to do it.
alternativly, you can use the noframe and either provide your own "frame" or have no frame at all.
To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):
import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"
evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)
in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script
. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.
Based on the built-in Powershell examples, this is what Microsoft suggests. Tested and verified:
To stop:
(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StopService()
To start:
(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StartService()
The /
operator can be used for integer division or floating point division. You're giving it two integer operands, so it's doing integer division and then the result is being stored in a double.
For what it's worth, for Gecko-based browsers you can't condition this thing off of :visited
due to the resulting privacy leaks. See http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/
If you're coding in an ASP.NET MVC Controller, use
using Microsoft.AspNet.Identity;
...
User.Identity.GetUserId();
Worth mentioning that User.Identity.IsAuthenticated
and User.Identity.Name
will work without adding the above mentioned using
statement. But GetUserId()
won't be present without it.
If you're in a class other than a Controller, use
HttpContext.Current.User.Identity.GetUserId();
In the default template of MVC 5, user ID is a GUID stored as a string.
No best practice yet, but found some valuable info on extending the user profile:
Identity
: https://devblogs.microsoft.com/aspnet/introducing-asp-net-identity-a-membership-system-for-asp-net-applications/This works in May 2020 using PDFminer six in Python3.
$ pip install pdfminer.six
from pdfminer.high_level import extract_text
text = extract_text('report.pdf')
Or alternatively:
with open('report.pdf','rb') as f:
text = extract_text(f)
If the PDF is already in memory, for example if retrieved from the web with the requests library, it can be converted to a stream using the io
library:
import io
response = requests.get(url)
text = extract_text(io.BytesIO(response.content))
PDFminer.six works more reliably than PyPDF2 (which fails with certain types of PDFs), in particular PDF version 1.7
However, text extraction with PDFminer.six is significantly slower than PyPDF2 by a factor of 6.
I timed text extraction with timeit
on a 15" MBP (2018), timing only the extraction function (no file opening etc.) with a 10 page PDF and got the following results:
PDFminer.six: 2.88 sec
PyPDF2: 0.45 sec
pdfminer.six also has a huge footprint, requiring pycryptodome which needs GCC and other things installed pushing a minimal install docker image on Alpine Linux from 80 MB to 350 MB. PyPDF2 has no noticeable storage impact.
sp_helplogins will give you the logins along with the DBs and the rights on them.
This is sonxurxo's solution in Kotlin, if anyone needs it.
private fun getUnsafeOkHttpClient(): OkHttpClient {
// Create a trust manager that does not validate certificate chains
val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
}
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
}
override fun getAcceptedIssuers() = arrayOf<X509Certificate>()
})
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, java.security.SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
return OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
.hostnameVerifier { _, _ -> true }.build()
}
First of all Arrays class is an utility class which contains no. of utility methods to operate on Arrays (thanks to Arrays class otherwise we would have needed to create our own methods to act on Array objects)
asList
method is one of the utility methods of Array
class ,it is static method thats why we can call this method by its class name (like Arrays.asList(T...a)
)ArrayList
object, it just returns a List reference to existing Array
object(so now after using asList
method, two references to existing Array
object gets created)List
object , may NOT work on this Array object using List
reference like
for example, Array
s size is fixed in length, hence you obviously can not add or remove elements from Array
object using this List
reference (like list.add(10)
or list.remove(10);
else it will throw UnsupportedOperationException)Array
s object ( as you are operating on existing Array object by using list reference)In first case you are creating a new Arraylist
object (in 2nd case only reference to existing Array object is created but not a new ArrayList
object) ,so now there are two different objects one is Array
object and another is ArrayList
object and no connection between them ( so changes in one object will not be reflected/affected in another object ( that is in case 2 Array
and Arraylist
are two different objects)
Integer [] ia = {1,2,3,4};
System.out.println("Array : "+Arrays.toString(ia));
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); // new ArrayList object is created , no connection between existing Array Object
list1.add(5);
list1.add(6);
list1.remove(0);
list1.remove(0);
System.out.println("list1 : "+list1);
System.out.println("Array : "+Arrays.toString(ia));
Integer [] ia = {1,2,3,4};
System.out.println("Array : "+Arrays.toString(ia));
List<Integer> list2 = Arrays.asList(ia); // creates only a (new ) List reference to existing Array object (and NOT a new ArrayList Object)
// list2.add(5); // it will throw java.lang.UnsupportedOperationException - invalid operation (as Array size is fixed)
list2.set(0,10); // making changes in existing Array object using List reference - valid
list2.set(1,11);
ia[2]=12; // making changes in existing Array object using Array reference - valid
System.out.println("list2 : "+list2);
System.out.println("Array : "+Arrays.toString(ia));
First, Jonathan's point about vectorizing is correct. If your getWellID() function is vectorized, then you can skip the loop and just use cat or write.csv:
write.csv(data.frame(wellid=getWellID(well$name, well$plate),
value1=well$value1, value2=well$value2), file=outputFile)
If getWellID() isn't vectorized, then Jonathan's recommendation of using by
or knguyen's suggestion of apply
should work.
Otherwise, if you really want to use for
, you can do something like this:
for(i in 1:nrow(dataFrame)) {
row <- dataFrame[i,]
# do stuff with row
}
You can also try to use the foreach
package, although it requires you to become familiar with that syntax. Here's a simple example:
library(foreach)
d <- data.frame(x=1:10, y=rnorm(10))
s <- foreach(d=iter(d, by='row'), .combine=rbind) %dopar% d
A final option is to use a function out of the plyr
package, in which case the convention will be very similar to the apply function.
library(plyr)
ddply(dataFrame, .(x), function(x) { # do stuff })
I'm now using RxJS 5.5.7 in an Angular application and using finalize
operator has a weird behavior for my use case since is fired before success or error callbacks.
Simple example:
// Simulate an AJAX callback...
of(null)
.pipe(
delay(2000),
finalize(() => {
// Do some work after complete...
console.log('Finalize method executed before "Data available" (or error thrown)');
})
)
.subscribe(
response => {
console.log('Data available.');
},
err => {
console.error(err);
}
);
I have had to use the add
medhod in the subscription to accomplish what I want. Basically a finally
callback after the success or error callbacks are done. Like a try..catch..finally
block or Promise.finally
method.
Simple example:
// Simulate an AJAX callback...
of(null)
.pipe(
delay(2000)
)
.subscribe(
response => {
console.log('Data available.');
},
err => {
console.error(err);
}
);
.add(() => {
// Do some work after complete...
console.log('At this point the success or error callbacks has been completed.');
});
You need to use the change directory command 'cd' to change directory
cd C:\Users\MyName\Desktop
you can use cd \d
to change the drive as well.
link for additional resources http://ss64.com/nt/cd.html
You must handle ArrayIndexOutOfBounds by yourself when adding to a certain position.
For convenience, you may use this extension function in Kotlin
/**
* Adds an [element] to index [index] or to the end of the List in case [index] is out of bounds
*/
fun <T> MutableList<T>.insert(index: Int, element: T) {
if (index <= size) {
add(index, element)
} else {
add(element)
}
}
Here is a complete solution based on the LocationManager and as fallbacks the TelephonyManager and the Network Provider's locations. I used the above answer from @Marco W. for the fallback part(great answer as itself!).
Note: the code contains PreferencesManager, this is a helper class that saves and loads data from SharedPrefrences. I'm using it to save the country to S"P, I'm only getting the country if it is empty. For my product I don't really care for all the edge cases(user travels abroad and so on).
public static String getCountry(Context context) {
String country = PreferencesManager.getInstance(context).getString(COUNTRY);
if (country != null) {
return country;
}
LocationManager locationManager = (LocationManager) PiplApp.getInstance().getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location == null) {
log.w("Couldn't get location from network and gps providers")
return
}
Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (addresses != null && !addresses.isEmpty()) {
country = addresses.get(0).getCountryName();
if (country != null) {
PreferencesManager.getInstance(context).putString(COUNTRY, country);
return country;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
country = getCountryBasedOnSimCardOrNetwork(context);
if (country != null) {
PreferencesManager.getInstance(context).putString(COUNTRY, country);
return country;
}
return null;
}
/**
* Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
*
* @param context Context reference to get the TelephonyManager instance from
* @return country code or null
*/
private static String getCountryBasedOnSimCardOrNetwork(Context context) {
try {
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final String simCountry = tm.getSimCountryIso();
if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
return simCountry.toLowerCase(Locale.US);
} else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
String networkCountry = tm.getNetworkCountryIso();
if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
return networkCountry.toLowerCase(Locale.US);
}
}
} catch (Exception e) {
}
return null;
}
Pair would be a good stuff, to be a basic construction unit for a complex generics, for instance, this is from my code:
WeakHashMap<Pair<String, String>, String> map = ...
It is just the same as Haskell's Tuple
As your example is linking to an external domain, if you are using HTTPS then you should verify that the external domain is setup for SSL as well. Otherwise, your users may see SSL errors and/or 404 errors (e.g. older versions of Plesk store HTTP and HTTPS in separate folders). For CDNs, it shouldn't be an issue but for any other website it could be.
On a side note, tested while updated an old website and also works in the url= part of a META REFRESH.
Maybe someone else need to change color in the XML without create multiple drawables like I needed. Then make a circle drawable without color and then specify backgroundTint for the ImageView.
circle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
</shape>
And in your layout:
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/circle"
android:backgroundTint="@color/red"/>
Edit:
There is a bug regarding this method that prevents it from working on Android Lollipop 5.0 (API level 21). But have been fixed in newer versions.
My .zip file was formatted correctly (I think) but it wasn't working. Even unchecking "Group items by category" didn't work
To install it I did so:
At this point Eclipse read the plugin correctly, I went ahead, accepted the conditions and then asked me to restart the IDE.
To avoid getting expections at run time , do something like this.
There are chances of having empty string sometimes,
string a = "abc,xyz,wer";
string b=string.Empty;
if(!string.IsNullOrEmpty(a ))
{
b = a.Split(',')[0];
}
After trying a few of these answers and finding they don't scale well with multiple links (for example the accepted answer requires a line of jquery for every link you have), I came across a way that requires minimal code to get working, and it also appears to work perfectly, at least on Chrome.
You add this line to activate it:
$('[data-toggle="popover"]').popover();
And these settings to your anchor links:
data-toggle="popover" data-trigger="hover"
See it in action here, I'm using the same imports as the accepted answer so it should work fine on older projects.
Did I mention Ruby has an EPIC community of developers. Ninja theme inspired by Object Oriented Ruby: Classes, Mixins and Jedi.
Ruby gets inheritance right with Single Inheritance! Needing to use multiple inheritance to express domain relationships is a symptom of an improperly designed system. The confusion multiple inheritance creates isn't worth the added functionality.
Say you have a method called kick:
def kick
puts "kick executed."
end
What if kick is defined in both class Ninjutsu and class Shaolin? Multiple Inheritance fails here and that's why Python fails:
class Mortal < Ninjutsu, Shaolin
def initialize
puts "mortal pwnage."
end
end
In Ruby if you need a Ninja, you create an instance of the Ninja class. If you need a Shaolin master, you create an instance of the Shaolin class.
ninja = Ninjutsu.new
ninja.kick
or
master = Shaolin.new
master.kick
There might be the off chance that both a Ninja and a Shaolin master share the same kick technique. Read that again - both share the same behavior - nothing else! Python would encourage you to roll a whole new class. Not with Ruby! In Ruby you simply use a Mixin:
module Katas
def kick
puts "Temporal Whip Kick."
end
end
and simply Mixin the Katas module into your Ruby Class:
require 'Katas'
class Moral < Ninjutsu
include Katas
def initialize
puts "mortal pwnage."
end
end
Then the behavior gets shared - which is what you were really going for. Not an entire class. That's the biggest difference between Ruby and Python - Ruby gets inheritance right!
If we don't have the meta tag at all, then we can use the following:
var _desc = 'Out description';
var meta = document.createElement('meta');
meta.setAttribute('name', 'description');
meta.setAttribute('content', _desc);
document.getElementsByTagName('head')[0].appendChild(meta);
Try changing it to "subdomain -> subdomain.hosttwo.com"
The CNAME
is an alias for a certain domain, so when you go to the control panel for hostone.com, you shouldn't have to enter the whole name into the CNAME
alias.
As far as the error you are getting, can you log onto subdomain.hostwo.com and check the logs?
Input the following to your Apache configuration:
php_value memory_limit 2048M
I assume you want to pass the Order ID in. So:
CREATE PROCEDURE [dbo].[Procedure_Name]
(
@OrderID INT
) AS
BEGIN
Declare @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END
You can't use it in the way you describe. The point about generic types, is that although you may not know them at "coding time", the compiler needs to be able to resolve them at compile time. Why? Because under the hood, the compiler will go away and create a new type (sometimes called a closed generic type) for each different usage of the "open" generic type.
In other words, after compilation,
DoesEntityExist<int>
is a different type to
DoesEntityExist<string>
This is how the compiler is able to enfore compile-time type safety.
For the scenario you describe, you should pass the type as an argument that can be examined at run time.
The other option, as mentioned in other answers, is that of using reflection to create the closed type from the open type, although this is probably recommended in anything other than extreme niche scenarios I'd say.
You can add these style's and it works just as expected.
.btn {
white-space:normal !important;
word-wrap: break-word;
word-break: normal;
}
This is the given array.
int myIntegerNumbers[] = {1,2,3,4,5,6,7,8,9,10};
// If you want print the last element in the array.
int lastNumerOfArray= myIntegerNumbers[9];
Log.i("MyTag", lastNumerOfArray + "");
// If you want to print the number of element in the array.
Log.i("MyTag", "The number of elements inside" +
"the array " +myIntegerNumbers.length);
// Second method to print the last element inside the array.
Log.i("MyTag", "The last elements inside " +
"the array " + myIntegerNumbers[myIntegerNumbers.length-1]);
I am using Visual Studio 2013 and I have the same issue but it occurs when I try to open a solution that was made using Visual Studio 2010.
The solution for me is to open the solution file (.sln), using notepad and change this line:
[# Visual Studio 2010]
to this:
[# Visual Studio 2013]
It's likely that the device is no longer authorized on ADB for whatever reason.
1. Check if authorized:
<ANDROID_SDK_HOME>\platform-tools>adb devices
List of devices attached
4df798d76f98cf6d unauthorized
2. Revoke USB Debugging on phone
If the device is shown as unauthorized, go to the developer options on the phone and click "Revoke USB debugging authorization" (tested with JellyBean & Samsung GalaxyIII).
3. Restart ADB Server:
Then restarted adb server
adb kill-server
adb start-server
4. Reconnect the device
The device will ask if you are agree to connect the computer id. You need to confirm it.
5. Now Check the device
It is now authorized!
adb devices
<ANDROID_SDK_HOME>\platform-tools>adb devices
List of devices attached
4df798d76f98cf6d device
CSS properties should be set by cssText
property or setAttribute
method.
// Set multiple styles in a single statement
elt.style.cssText = "color: blue; border: 1px solid black";
// Or
elt.setAttribute("style", "color:red; border: 1px solid blue;");
Styles should not be set by assigning a string directly to the style
property (as in elt.style = "color: blue;"
), since it is considered read-only, as the style
attribute returns a CSSStyleDeclaration
object which is also read-only.
Consider using a Spinner instead of a Number Picker in a Dialog. It's not exactly what was asked for, but it's much easier to implement, more contextual UI design, and should fulfill most use cases. The equivalent code for a Spinner is:
Spinner picker = new Spinner(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, yourStringList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
picker.setAdapter(adapter);
There is a built-in library called pickle
. Using pickle
you can dump objects to a file and load them later.
import pickle
f = open('store.pckl', 'wb')
pickle.dump(obj, f)
f.close()
f = open('store.pckl', 'rb')
obj = pickle.load(f)
f.close()
No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.
SQL stands for Structured Query Language, and is the basis for which all Relational Database Management Systems allow the user to add, remove, update, or select records. Things like MySQ are the actual Management Systems which allow you to store and retrieve your data, whereas SQL is the actual language to do so.
The basic SQL is somewhat universal - Selects usually look the same, Inserts, Updates, Deletes, etc. Once you get beyond the basics, the commands and abilities of your individual Databases vary, and this is where you get people who are Oracle experts, MySQL, SQL Server, etc.
Basically, MySQL is one of many books holding everything, and SQL is how you go about reading that book.
You May Try this
if (isset($_COOKIE['remember_user'])) {
unset($_COOKIE['remember_user']);
setcookie('remember_user', null, -1, '/');
return true;
} else {
return false;
}
try this
sudo chmod -R 0777 /opt/lampp/htdocs/testproject
In case the WebSocket server initiative disconnects the
ws
link after a few minutes there no messages sent between the server and client.
client sends a custom ping
message, to keep alive by using the keepAlive
function
server ignore the ping
message and response a custom pong
message
var timerID = 0;
function keepAlive() {
var timeout = 20000;
if (webSocket.readyState == webSocket.OPEN) {
webSocket.send('');
}
timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
if (timerId) {
clearTimeout(timerId);
}
}
It depends on the Markdown rendering engine and the Markdown flavour. There is no standard for this. If you mean GitHub flavoured Markdown for example, shell
should work fine. Aliases are sh
, bash
or zsh
. You can find the list of available syntax lexers here.
To convert the private key from PKCS#1 to PKCS#8 with openssl:
# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key
That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.
["The", animal, action, "the", second_animal].join(" ")
is another way to do it.
May be the better way is
UIColor *color = [UIColor greenColor];
[self.myLabel setTextColor:color];
Thus we have colored text
$filename = pathinfo( parse_url( $url, PHP_URL_PATH ), PATHINFO_FILENAME );
Use parse_url to extract the path from the URL, then pathinfo returns the filename from the path
@robertc has it right, but you also need to notice that svg, #container
causes the svg to be scaled exponentially for anything but 100% (once for #container
and once for svg
).
In other words, if I applied 50% h/w to both elements, it's actually 50% of 50%, or .5 * .5, which equals .25, or 25% scale.
One selector works fine when used as @robertc suggests.
svg {
width:50%;
height:50%;
}
I know it's an old question, but for single line text setting display: inline-block
and then setting the height
has worked well for me to control the distance between a border and the text.
I'm successfully using the following to update options dynamically:
$control.select2('destroy').empty().select2({data: [{id: 1, text: 'new text'}]});
In order to read a csv in that doesn't have a header and for only certain columns you need to pass params header=None
and usecols=[3,6]
for the 4th and 7th columns:
df = pd.read_csv(file_path, header=None, usecols=[3,6])
See the docs
<?php
$to1 = '[email protected]';
$subject = 'Tester subject';
// To send HTML mail, the Content-type header must be set
$headers .= "Reply-To: The Sender <[email protected]>\r\n";
$headers .= "Return-Path: The Sender <[email protected]>\r\n";
$headers .= "From: [email protected]" ."\r\n" .
$headers .= "Organization: Sender Organization\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
?>
Try following code that worked fine for me
global $current_user;
get_currentuserinfo();
Then, use following code to check whether user has logged in or not.
if ($current_user->ID == '') {
//show nothing to user
}
else {
//write code to show menu here
}
I don't think Facebook's Open Graph Object i.e. "og_object" provides anything more than comment_count & share_count for a URL. Try this; replace $YOUR_URL with the URL and $ACCESS_TOKEN with your access token in the below link https://graph.facebook.com/v2.5/$YOUR_URL?access_token=$ACCESS_TOKEN
For example:
{
og_object: {
id: "956517601094822",
description: "Naughty or nice, every NFL team deserves something for Christmas. So in lieu of Santa Claus, Bill Barnwell is here to distribute some gifts.",
title: "Barnwell: Handing out holiday gifts to all 32 teams",
type: "article",
updated_time: "2015-12-23T17:20:55+0000",
url: "http://espn.go.com/nfl/story/_/id/14424066"
},
share: {
comment_count: 0,
share_count: 354
},
id: "http://espn.go.com/nfl/story/_/id/14424066/handing-holiday-gifts-all-32-nfl-teams-nfl"
}
Also, if you try to get likes, you would get the following error https://graph.facebook.com/http://rottentomatoes.com?fields=likes&summary=1&access_token=$ACCESS_TOKEN
{
error: {
message: "(#100) Tried accessing nonexisting field (likes) on node type (URL)",
type: "OAuthException",
code: 100,
fbtrace_id: "H+KksDn+mCf"
}
}
I understand that this is a response to an old post-
I like the If() function combined with Index()/Match():
=IF(B2>0,"x",INDEX($H$2:$I$9,MATCH(A2,$H$2:$H$9,0),2))
The if function compare what is in column b and if it is greater than 0, it returns x, if not it uses the array (table of information) identified by the Index() function and selected by Match() to return the value that a corresponds to.
The Index array has the absolute location set $H$2:$I$9
(the dollar signs) so that the place it points to will not change as the formula is copied. The row with the value that you want returned is identified by the Match() function. Match() has the added value of not needing a sorted list to look through that Vlookup() requires. Match() can find the value with a value: 1 less than, 0 exact, -1 greater than. I put a zero in after the absolute Match() array $H$2:$H$9
to find the exact match. For the column that value of the Index() array that one would like returned is entered. I entered a 2 because in my array the return value was in the second column. Below my index array looked like this:
32 1420
36 1650
40 1790
44 1860
55 2010
The value in your 'a' column to search for in the list is in the first column in my example and the corresponding value that is to be return is to the right. The look up/reference table can be on any tab in the work book - or even in another file. -Book2 is the file name, and Sheet2 is the 'other tab' name.
=IF(B2>0,"x",INDEX([Book2]Sheet2!$A$1:$B$8,MATCH(A2,[Book2]Sheet2!$A$1:$A$8,0),2))
If you do not want x return when the value of b is greater than zero delete the x for a 'blank'/null equivalent or maybe put a 0 - not sure what you would want there.
Below is beginning of the function with the x deleted.
=IF(B2>0,"",INDEX...
Use cut
. Eg. to strip the first 4 characters of each line (i.e. start on the 5th char):
tail -f logfile | grep org.springframework | cut -c 5-
"unblocking" the file fixes the problem. Screenshot:
Here's a variation of Oscar's first version that doesn't use a for-each loop.
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == 'q') {
// do something
break;
}
}
You could have a boolean variable that gets set to false before the loop, then make "do something" set the variable to true, which you could test for after the loop. The loop could also be wrapped in a function call then just use 'return true' instead of the break, and add a 'return false' statement after the for loop.
Updated answer, from Peter in comments :
This is de "old terminology", use directally the WSDL2 "endepoint" definition (WSDL2 translated "port" to "endpoint").
Maybe you find an answer in this document : http://www.w3.org/TR/wsdl.html
A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:
- Types– a container for data type definitions using some type system (such as XSD).
- Message– an abstract, typed definition of the data being communicated.
- Operation– an abstract description of an action supported by the service.
- Port Type–an abstract set of operations supported by one or more endpoints.
- Binding– a concrete protocol and data format specification for a particular port type.
- Port– a single endpoint defined as a combination of a binding and a network address.
- Service– a collection of related endpoints.
http://www.ehow.com/info_12212371_definition-service-endpoint.html
The endpoint is a connection point where HTML files or active server pages are exposed. Endpoints provide information needed to address a Web service endpoint. The endpoint provides a reference or specification that is used to define a group or family of message addressing properties and give end-to-end message characteristics, such as references for the source and destination of endpoints, and the identity of messages to allow for uniform addressing of "independent" messages. The endpoint can be a PC, PDA, or point-of-sale terminal.
You can use numeric_limits<float>::quiet_NaN( )
defined in the limits
standard library to test with. There's a separate constant defined for double
.
#include <iostream>
#include <math.h>
#include <limits>
using namespace std;
int main( )
{
cout << "The quiet NaN for type float is: "
<< numeric_limits<float>::quiet_NaN( )
<< endl;
float f_nan = numeric_limits<float>::quiet_NaN();
if( isnan(f_nan) )
{
cout << "Float was Not a Number: " << f_nan << endl;
}
return 0;
}
I don't know if this works on all platforms, as I only tested with g++ on Linux.
$('#div1').attr('class')
will return a string of the classes. Turn it into an array of class names
var classNames = $('#div1').attr('class').split(' ');
I want to give a shoutout for using re
module for this. Specially in the case of case sensitivity.
We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.
>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
However try to always use the in
operator for string comparison as detailed in this post
faster-operation-re-match-or-str
Also detailed in the one of the best books to start learning python with
This is a slightly modified version of http://jdewit.github.io/bootstrap-timepicker/ which supports bootstrap 3. You can check it out here. https://github.com/m3wolf/bootstrap3-timepicker Let me know if it does not work and I will try to find an alternative.
Update. Here is another one based off of the same version, but modified for bootstrap 3. https://github.com/rendom/bootstrap-3-timepicker
Update 2. Here is yet another one. http://bootstrapformhelpers.com/timepicker/
Yes, it is possible. The steps are:
First Put the .mdf
and .ldf
file in C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\
folder
Then go to sql software , Right-click “Databases” and click the “Attach” option to open the Attach Databases dialog box
Click the “Add” button to open and Locate Database Files From C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\
folder
Click the "OK" button. SQL Server Management Studio loads the database from the .MDF
file.
What you could do is, a validation of the values, for example:
if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");
// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");
// Form
let contactForm = document.getElementById("form");
// Event listener
contactForm.addEventListener("submit", function (e) {
let messageName = [];
let messageAddress = [];
if (fullname.value === "" || fullname.value === null) {
messageName.push("* This field is required");
}
if (address.value === "" || address.value === null) {
messageAddress.push("* This field is required");
}
// Statement to shows the errors
if (messageName.length || messageAddress.length > 0) {
e.preventDefault();
errorElement.innerText = messageName;
errorElementAddress.innerText = messageAddress;
}
// if the values length is filled and it's greater than 2 then redirect to this page
if (
(fullname.value.length > 2,
address.value.length > 2)
) {
e.preventDefault();
window.location.assign("https://www.google.com");
}
});
_x000D_
.error {
color: #000;
}
.input-container {
display: flex;
flex-direction: column;
margin: 1rem auto;
}
_x000D_
<html>
<body>
<form id="form" method="POST">
<div class="input-container">
<label>Full name:</label>
<input type="text" id="fullname" name="fullname">
<div class="error" id="name_error"></div>
</div>
<div class="input-container">
<label>Address:</label>
<input type="text" id="address" name="address">
<div class="error" id="address_error"></div>
</div>
<button type="submit" id="submit_button" value="Submit request" >Submit</button>
</form>
</body>
</html>
_x000D_
setColor(). Assuming you use Graphics g in an AWT context.
Please refer to the documentation for additional information.
The best way is to use layers insted of views:
AVPlayer *player = [AVPlayer playerWithURL:[NSURL url...]]; //
AVPlayerLayer *layer = [AVPlayerLayer layer];
[layer setPlayer:player];
[layer setFrame:CGRectMake(10, 10, 300, 200)];
[layer setBackgroundColor:[UIColor redColor].CGColor];
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[self.view.layer addSublayer:layer];
[player play];
Don't forget to add frameworks:
#import <QuartzCore/QuartzCore.h>
#import "AVFoundation/AVFoundation.h"
You could look into using BrowserStack: http://www.browserstack.com
While not free, it is rather cheap. It allows you to test against several iOS versions on both iPhone and iPad, along with Android, and various desktop browsers and OSs. It has proved quite invaluable to my workplace for doing just these sort of tests.
Step 1: Open IIS and click the server name Step 2. Double click “ISAPI and CGI Restrictions” Step 3. Right click ASP.NET v4.0.30319 and select “allow”
After Stopping and Starting the World Wide Web Publishing Service
1.Go to Start > All Programs > Administrative Tools > Services. 2.In the services list, right-click World Wide Web Publishing Service, and then click Stop (to stop the service), Start (to start it after it has been stopped), or Restart (to restart the service when it is running).
Pramesh
Decryption (directly getting the the plain text from the hashed value, in an algorithmic way), no.
There are, however, methods that use what is known as a rainbow table. It is pretty feasible if your passwords are hashed without a salt.
I had similar issue, my code was:
function RadioInput(props) {
return (
<div className="form-check form-check-inline">
<input className="form-check-input" type="radio" name="inlineRadioOptions" id={props.id} onClick={props.onClick} value={props.label}></input>
<label className="form-check-label" htmlFor={props.id}>{props.label}</label>
</div>
);
}
class ScheduleType extends React.Component
{
renderRadioInput(id,label)
{
id = "inlineRadio"+id;
return(
<RadioInput
id = {id}
label = {label}
onClick = {this.props.onClick}
/>
);
}
Where it should be
onClick = {() => this.props.onClick()}
in RenderRadioInput
It fixed the issue for me.