I had faced a similar issue with NodeJS, where the culprit was a forEach loop. Note that forEach is a synchronous function (NOT Asynchronous). Therefore it just ignores the promise returned. The solution was to use a for-of loop instead: Code where I got the error:
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
is as follows:
permissionOrders.forEach( async(order) => {
const requestPermissionOrder = new RequestPermissionOrderSchema({
item: order.item,
item_desc: order.item_desc,
quantity: order.quantity,
unit_price: order.unit_price,
total_cost: order.total_cost,
status: order.status,
priority: order.priority,
directOrder: order.directOrder
});
try {
const dat_order = await requestPermissionOrder.save();
res.json(dat_order);
} catch(err){
res.json({ message : err});
}
});
Solution for the above issue is as follows:
for (let order of permissionOrders){
const requestPermissionOrder = new RequestPermissionOrderSchema({
item: order.item,
item_desc: order.item_desc,
quantity: order.quantity,
unit_price: order.unit_price,
total_cost: order.total_cost,
status: order.status,
priority: order.priority,
directOrder: order.directOrder
});
try {
const dat_order = await requestPermissionOrder.save();
res.json(dat_order);
} catch(err){
res.json({ message : err});
}
};
child:
setInterval(function() {
process.stdout.write("hi");
}, 1000); // or however else you want to run a timer
parent:
require('child_process').fork('./childfile.js');
// fork'd children use the parent's stdio
env
option?Then look at this answer.
I was trying to spawn a node process and TIL that you should spread the existing environment variables when you spawn else you'll loose the PATH
environment variable and possibly other important ones.
This was the fix for me:
const nodeProcess = spawn('node', ['--help'], {
env: {
// by default, spawn uses `process.env` for the value of `env`
// you can _add_ to this behavior, by spreading `process.env`
...process.env,
OTHER_ENV_VARIABLE: 'test',
}
});
You can use jquery for this:
$('body').bind('copy paste',function(e) {
e.preventDefault(); return false;
});
Using jQuery bind()
and specififying your desired eventTypes
.
Here's some succinct Powershell code to apply new permissions to a folder by modifying it's existing ACL (Access Control List).
# Get the ACL for an existing folder
$existingAcl = Get-Acl -Path 'C:\DemoFolder'
# Set the permissions that you want to apply to the folder
$permissions = $env:username, 'Read,Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow'
# Create a new FileSystemAccessRule object
$rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permissions
# Modify the existing ACL to include the new rule
$existingAcl.SetAccessRule($rule)
# Apply the modified access rule to the folder
$existingAcl | Set-Acl -Path 'C:\DemoFolder'
Each of the values in the $permissions
variable list pertain to the parameters of this constructor for the FileSystemAccessRule class.
Courtesy of this page.
The bash script should be something like this:
#!/bin/bash
/usr/bin/php /path/to/php/file.php
You need the php executable (usually found in /usr/bin) and the path of the php script to be ran. Now you only have to put this bash script on crontab and you're done!
Hands down the best IDE for PHP is NuSphere PHPEd. It's a no contest. It is so good that I use WINE to run it on my Mac. PHPEd has an awesome debugger built into it that can be used with their local webserver (totally automatic) or you can just install the dbg module for XAMPP or any other Apache you want to run.
If you are producing the entire output yourself, you can use sprintf()
, e.g.
> sprintf("%.10f",0.25)
[1] "0.2500000000"
specifies that you want to format a floating point number with ten decimal points (in %.10f
the f
is for float and the .10
specifies ten decimal points).
I don't know of any way of forcing R's higher level functions to print an exact number of digits.
Displaying 100 digits does not make sense if you are printing R's usual numbers, since the best accuracy you can get using 64-bit doubles is around 16 decimal digits (look at .Machine$double.eps on your system). The remaining digits will just be junk.
Use ng-show
and toggle the value of a show
scope variable in the ng-click
handler.
Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/
<ul class="procedures">
<li ng-repeat="procedure in procedures">
<h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
<div class="procedure-details" ng-show="show">
<p>Number of patient discharges: {{procedure.discharges}}</p>
<p>Average amount covered by Medicare: {{procedure.covered}}</p>
<p>Average total payments: {{procedure.payments}}</p>
</div>
</li>
</ul>
The message error means that you have a self referencing loop.
The json you produce is like this example (with a list of one employee) :
[
employee1 : {
name: "name",
department : {
name: "departmentName",
employees : [
employee1 : {
name: "name",
department : {
name: "departmentName",
employees : [
employee1 : {
name: "name",
department : {
and again and again....
}
]
}
}
]
}
}
]
You have to tell the db context that you don't want to get all linked entities when you request something.
The option for DbContext is Configuration.LazyLoadingEnabled
The best way I found is to create a context for serialization :
public class SerializerContext : LabEntities
{
public SerializerContext()
{
this.Configuration.LazyLoadingEnabled = false;
}
}
Would be safer to do this.
@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}
So the controller for that action runs as well, to populate any model the view needs.
Although as @Satpal mentioned, I do recommend you do the redirecting on your controller.
You can chain class selectors without a space between them:
.a.b {
color: #666;
}
Note that, if it matters to you, IE6 treats .a.b
as .b
, so in that browser both div.a.b
and div.b
will have gray text. See this answer for a comparison between proper browsers and IE6.
It is apparently possible to manually install offline voice recognition by downloading the files directly and installing them in the right locations manually. I guess this is just a way to bypass Google hardware requirements. However, personally I didn't have to reboot or anything, simply changing to UK and back again did it.
Another variation using MS SQL:
SELECT TYPE_NAME(system_type_id)
FROM sys.columns
WHERE name = 'column_name'
AND [object_id] = OBJECT_ID('[dbo].[table_name]');
I guess what you need is np.set_printoptions(suppress=True)
, for details see here:
http://pythonquirks.blogspot.fr/2009/10/controlling-printing-in-numpy.html
For SciPy.org numpy documentation, which includes all function parameters (suppress isn't detailed in the above link), see here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html
The ideal way is not to use ioutil.ReadAll
, but rather use a decoder on the reader directly. Here's a nice function that gets a url and decodes its response onto a target
structure.
var myClient = &http.Client{Timeout: 10 * time.Second}
func getJson(url string, target interface{}) error {
r, err := myClient.Get(url)
if err != nil {
return err
}
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(target)
}
Example use:
type Foo struct {
Bar string
}
func main() {
foo1 := new(Foo) // or &Foo{}
getJson("http://example.com", foo1)
println(foo1.Bar)
// alternately:
foo2 := Foo{}
getJson("http://example.com", &foo2)
println(foo2.Bar)
}
You should not be using the default *http.Client
structure in production as this answer originally demonstrated! (Which is what http.Get
/etc call to). The reason is that the default client has no timeout set; if the remote server is unresponsive, you're going to have a bad day.
You can just use Tab
and Shift+Tab
char c = 10; // 1 byte
int *p = (int*)&c; // 4 bytes
Since this results in a 4-byte pointer pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.
*p = 5; // run-time error: stack corruption
In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.
int *q = static_cast<int*>(&c); // compile-time error
To force the pointer conversion, in the same way as the C-style cast does in the background, the reinterpret cast would be used instead.
int *r = reinterpret_cast<int*>(&c); // forced conversion
This cast handles conversions between certain unrelated types, such as from one pointer type to another incompatible pointer type. It will simply perform a binary copy of the data without altering the underlying bit pattern. Note that the result of such a low-level operation is system-specific and therefore not portable. It should be used with caution if it cannot be avoided altogether.
This one is only used to convert object pointers and object references into other pointer or reference types in the inheritance hierarchy. It is the only cast that makes sure that the object pointed to can be converted, by performing a run-time check that the pointer refers to a complete object of the destination type. For this run-time check to be possible the object must be polymorphic. That is, the class must define or inherit at least one virtual function. This is because the compiler will only generate the needed run-time type information for such objects.
Dynamic cast examples
In the example below, a MyChild pointer is converted into a MyBase pointer using a dynamic cast. This derived-to-base conversion succeeds, because the Child object includes a complete Base object.
class MyBase
{
public:
virtual void test() {}
};
class MyChild : public MyBase {};
int main()
{
MyChild *child = new MyChild();
MyBase *base = dynamic_cast<MyBase*>(child); // ok
}
The next example attempts to convert a MyBase pointer to a MyChild pointer. Since the Base object does not contain a complete Child object this pointer conversion will fail. To indicate this, the dynamic cast returns a null pointer. This gives a convenient way to check whether or not a conversion has succeeded during run-time.
MyBase *base = new MyBase();
MyChild *child = dynamic_cast<MyChild*>(base);
if (child == 0)
std::cout << "Null pointer returned";
If a reference is converted instead of a pointer, the dynamic cast will then fail by throwing a bad_cast exception. This needs to be handled using a try-catch statement.
#include <exception>
// …
try
{
MyChild &child = dynamic_cast<MyChild&>(*base);
}
catch(std::bad_cast &e)
{
std::cout << e.what(); // bad dynamic_cast
}
The advantage of using a dynamic cast is that it allows the programmer to check whether or not a conversion has succeeded during run-time. The disadvantage is that there is a performance overhead associated with doing this check. For this reason using a static cast would have been preferable in the first example, because a derived-to-base conversion will never fail.
MyBase *base = static_cast<MyBase*>(child); // ok
However, in the second example the conversion may either succeed or fail. It will fail if the MyBase object contains a MyBase instance and it will succeed if it contains a MyChild instance. In some situations this may not be known until run-time. When this is the case dynamic cast is a better choice than static cast.
// Succeeds for a MyChild object
MyChild *child = dynamic_cast<MyChild*>(base);
If the base-to-derived conversion had been performed using a static cast instead of a dynamic cast the conversion would not have failed. It would have returned a pointer that referred to an incomplete object. Dereferencing such a pointer can lead to run-time errors.
// Allowed, but invalid
MyChild *child = static_cast<MyChild*>(base);
// Incomplete MyChild object dereferenced
(*child);
This one is primarily used to add or remove the const modifier of a variable.
const int myConst = 5;
int *nonConst = const_cast<int*>(&myConst); // removes const
Although const cast allows the value of a constant to be changed, doing so is still invalid code that may cause a run-time error. This could occur for example if the constant was located in a section of read-only memory.
*nonConst = 10; // potential run-time error
Const cast is instead used mainly when there is a function that takes a non-constant pointer argument, even though it does not modify the pointee.
void print(int *p)
{
std::cout << *p;
}
The function can then be passed a constant variable by using a const cast.
print(&myConst); // error: cannot convert
// const int* to int*
print(nonConst); // allowed
Just use CLng(Date)
.
Note that you need to use Long
not Integer
for this as the value for the current date is > 32767
Try:
next(g)
Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.
Just a follow up to @LisaD's answer.
As of 2016 (Django 1.9
), you need to type:
heroku pg:reset DATABASE_URL
heroku run python manage.py makemigrations
heroku run python manage.py migrate
This will give you a fresh new database within Heroku.
There are two ways to do this. The System.Diagnostics.StackTrace()
will give you a stack trace for the current thread. If you have a reference to a Thread
instance, you can get the stack trace for that via the overloaded version of StackTrace()
.
You may also want to check out Stack Overflow question How to get non-current thread's stacktrace?.
One issue I've had, and it was horribly tricky, was that the OCI call to describe a column attributes behaves diffrently depending on Oracle versions. Describing a simple NUMBER column created without any prec or scale returns differenlty on 9i, 1Og and 11g
Nimgoble's is the version I used in 2015. Thought I'd put it here as this question was top of the list in google for "wpf autocomplete textbox"
Install nuget package for project in Visual Studio
Add a reference to the library in the xaml:
xmlns:behaviors="clr-namespace:WPFTextBoxAutoComplete;assembly=WPFTextBoxAutoComplete"
Create a textbox and bind the AutoCompleteBehaviour to List<String>
(TestItems):
<TextBox Text="{Binding TestText, UpdateSourceTrigger=PropertyChanged}"
behaviors:AutoCompleteBehavior.AutoCompleteItemsSource="{Binding TestItems}" />
IMHO this is much easier to get started and manage than the other options listed above.
You could use p2pkit, or the free solution it was based on: https://github.com/GitGarage. Doesn't work very well, and its a fixer-upper for sure, but its, well, free. Works for small amounts of data transfer right now.
You can comma-separate shadows:
box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;
1st way is to use props
<Row id = "someRandomID">
Wherein, in the Definition, you may just go
const Row = props => {
div id = {props.id}
}
The same could be done with class, replacing id with className in the above example.
You might as well use react-html-id
, that is an npm package.
This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.
Ref: react-html-id
Peace.
None of the about answers works for my case. I got the answer from here, and my SQL is:
INSERT INTO product (id, catalog_id, status_id, name, measure_unit_id, description, create_time)
VALUES (
(SELECT id FROM (SELECT COALESCE(MAX(id),0)+1 AS id FROM product) AS temp),
(SELECT id FROM product_catalog WHERE name="AppSys1"),
(SELECT id FROM product_status WHERE name ="active"),
"prod_name_x",
(SELECT id FROM measure_unit WHERE name ="unit"),
"prod_description_y",
UNIX_TIMESTAMP(NOW())
)
I needed to convert a single column of strings of form nn.n% to float. I needed to remove the % from the element in each row. The attend data frame has two columns.
attend.iloc[:,1:2]=attend.iloc[:,1:2].applymap(lambda x: float(x[:-1]))
Its an extenstion to the original answer. In my case it takes a dataframe and applies a function to each value in a specific column. The function removes the last character and converts the remaining string to float.
You need to use this function.
JSON.parse(yourJsonString);
And it will return the object / array that was contained within the string.
Notice that "cex" does change things when the plot is made with text. For example, the plot of an agglomerative hierarchical clustering:
library(cluster)
data(votes.repub)
agn1 <- agnes(votes.repub, metric = "manhattan", stand = TRUE)
plot(agn1, which.plots=2)
will produce a plot with normal sized text:
and plot(agn1, which.plots=2, cex=0.5)
will produce this one:
The OP needed to cast as string outside the {% set ... %}
.
But if that not your case you can do:
{% set curYear = 2013 | string() %}
Note that you need the parenthesis on that jinja filter.
If you're concatenating 2 variables, you can also use the ~
custom operator.
Catching Exception
will catch a RuntimeException
Perhaps you could try ([^ ]+) .*
, which should give you everything to the first blank in your first group.
if you want UTC try some of the gm
functions:
import time
import calendar
date_time = '29.08.2011 11:05:02'
pattern = '%d.%m.%Y %H:%M:%S'
utc_epoch = calendar.timegm(time.strptime(date_time, pattern))
print utc_epoch
There are two big difference the sorting and the character matching:
Sorting:
utf8mb4_general_ci
removes all accents and sorts one by one which may create incorrect sort results.utf8mb4_unicode_ci
sorts accurate.Character Matching
They match characters differently.
For example, in utf8mb4_unicode_ci
you have i != i
, but in utf8mb4_general_ci
it holds i=i
.
For example, imagine you have a row with name="Yilmaz"
. Then
select id from users where name='Yilmaz';
would return the row if collocation is utf8mb4_general_ci
, but if it is collocated with utf8mb4_unicode_ci
it would not return the row!
On the other hand we have that a=ª
and ß=ss
in utf8mb4_unicode_ci
which is not the case in utf8mb4_general_ci
. So imagine you have a row with name="ªßi"
, then
select id from users where name='assi';
would return the row if collocation is utf8mb4_unicode_ci
, but would not return a row if collocation is set to utf8mb4_general_ci
.
A full list of matches for each collocation may be found here.
Multiplying each element in my_list
by k
:
k = 5
my_list = [1,2,3,4]
result = list(map(lambda x: x * k, my_list))
resulting in: [5, 10, 15, 20]
Delete the folder .android
from C:/users/<user name>/.android
. It solved the issue for me.
TL;DR: Specify key file in group variable file, since 'tag_Name_server1' is a group.
Note: I'm assuming you're using the EC2 external inventory script. If you're using some other dynamic inventory approach, you might need to tweak this solution.
This is an issue I've been struggling with, on and off, for months, and I've finally found a solution, thanks to Brian Coca's suggestion here. The trick is to use Ansible's group variable mechanisms to automatically pass along the correct SSH key file for the machine you're working with.
The EC2 inventory script automatically sets up various groups that you can use to refer to hosts. You're using this in your playbook: in the first play, you're telling Ansible to apply 'role1' to the entire 'tag_Name_server1' group. We want to direct Ansible to use a specific SSH key for any host in the 'tag_Name_server1' group, which is where group variable files come in.
Assuming that your playbook is located in the 'my-playbooks' directory, create files for each group under the 'group_vars' directory:
my-playbooks
|-- test.yml
+-- group_vars
|-- tag_Name_server1.yml
+-- tag_Name_server2.yml
Now, any time you refer to these groups in a playbook, Ansible will check the appropriate files, and load any variables you've defined there.
Within each group var file, we can specify the key file to use for connecting to hosts in the group:
# tag_Name_server1.yml
# --------------------
#
# Variables for EC2 instances named "server1"
---
ansible_ssh_private_key_file: /path/to/ssh/key/server1.pem
Now, when you run your playbook, it should automatically pick up the right keys!
Using environment vars for portability
I often run playbooks on many different servers (local, remote build server, etc.), so I like to parameterize things. Rather than using a fixed path, I have an environment variable called SSH_KEYDIR that points to the directory where the SSH keys are stored.
In this case, my group vars files look like this, instead:
# tag_Name_server1.yml
# --------------------
#
# Variables for EC2 instances named "server1"
---
ansible_ssh_private_key_file: "{{ lookup('env','SSH_KEYDIR') }}/server1.pem"
Further Improvements
There's probably a bunch of neat ways this could be improved. For one thing, you still need to manually specify which key to use for each group. Since the EC2 inventory script includes details about the keypair used for each server, there's probably a way to get the key name directly from the script itself. In that case, you could supply the directory the keys are located in (as above), and have it choose the correct keys based on the inventory data.
Why nobody mentions matchMedia?
if (window.matchMedia("(min-width: 400px)").matches) {
/* the viewport is at least 400 pixels wide */
} else {
/* the viewport is less than 400 pixels wide */
}
Did not test that much, but tested with android default and android chrome browsers, desktop chrome, so far it looks like it works well.
Of course it does not return number value, but returns boolean - if matches or not, so might not exactly fit the question but that's what we want anyway and probably the author of question wants.
While all of the answers are good and correct, simple solution in one line is:
$check = 9;
either:
echo ($check & 1 ? 'Odd' : 'Even');
or:
echo ($check % 2 ? 'Odd' : 'Even');
works very well.
select top(3) min(Name),TotalSalary,ROW_NUMBER() OVER (Order by TotalSalary desc) AS RowNumber FROM tbl_EmployeeProfile group by TotalSalary
You don't really need the MockitoAnnotations.initMocks(this);
if you're using mockito 1.9 ( or newer ) - all you need is this:
@InjectMocks
private MyTestObject testObject;
@Mock
private MyDependentObject mockedObject;
The @InjectMocks
annotation will inject all your mocks to the MyTestObject
object.
What you asked for is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
If the FileInfo class has more than one ancestor class then you should definitely call all of their __init__() functions. You should also do the same for the __del__() function, which is a destructor.
You can use the following attributes for webkit, which reach into the shadow DOM:
::-webkit-scrollbar { /* 1 */ }
::-webkit-scrollbar-button { /* 2 */ }
::-webkit-scrollbar-track { /* 3 */ }
::-webkit-scrollbar-track-piece { /* 4 */ }
::-webkit-scrollbar-thumb { /* 5 */ }
::-webkit-scrollbar-corner { /* 6 */ }
::-webkit-resizer { /* 7 */ }
Here's a working fiddle with a red scrollbar, based on code from this page explaining the issues.
http://jsfiddle.net/hmartiro/Xck2A/1/
Using this and your solution, you can handle all browsers except Firefox, which at this point I think still requires a javascript solution.
If you use Knockout, then you could use the following custom binding to bind the current viewport breakpoint (xs, sm, md or lg) to an observable in your model. The binding...
divs
with visible-??
class in a div with id detect-viewport
and adds it to the body if it doesn't exist already (so you could reuse this binding without duplicating these divs)ko.bindingHandlers['viewport'] = {_x000D_
init: function(element, valueAccessor) {_x000D_
if (!document.getElementById('detect-viewport')) {_x000D_
let detectViewportWrapper = document.createElement('div');_x000D_
detectViewportWrapper.id = 'detect-viewport';_x000D_
_x000D_
["xs", "sm", "md", "lg"].forEach(function(breakpoint) {_x000D_
let breakpointDiv = document.createElement('div');_x000D_
breakpointDiv.className = 'visible-' + breakpoint;_x000D_
detectViewportWrapper.appendChild(breakpointDiv);_x000D_
});_x000D_
_x000D_
document.body.appendChild(detectViewportWrapper);_x000D_
}_x000D_
_x000D_
let setCurrentBreakpoint = function() {_x000D_
valueAccessor()($('#detect-viewport div:visible')[0].className.substring('visible-'.length));_x000D_
}_x000D_
_x000D_
$(window).resize(setCurrentBreakpoint);_x000D_
setCurrentBreakpoint();_x000D_
}_x000D_
};_x000D_
_x000D_
ko.applyBindings({_x000D_
currentViewPort: ko.observable()_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
<div data-bind="viewport: currentViewPort"></div>_x000D_
<div> _x000D_
Current viewport breakpoint: <strong data-bind="text: currentViewPort"></strong>_x000D_
</div>_x000D_
<div>_x000D_
(Click the <em>full page</em> link of this snippet to test the binding with different window sizes)_x000D_
</div>
_x000D_
Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?
As so:
Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False
For Each element In sArray
XLSMToXLSX(element)
Next element
Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub
Sub XLSMToXLSX(ByVal file As String)
Do While WorkFile <> ""
If Right(WorkFile, 4) <> "xlsx" Then
Workbooks.Open Filename:=myPath & WorkFile
Application.DisplayAlerts = False
Application.EnableEvents = False
ActiveWorkbook.SaveAs Filename:= _
modifiedFileName, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False, _
ConflictResolution:=xlLocalSessionChanges
Application.DisplayAlerts = True
Application.EnableEvents = True
ActiveWorkbook.Close
End If
WorkFile = Dir()
Loop
End Sub
((SelectionListViewController *)myEditController).list
More examples:
int i = (int)19.5f; // (precision is lost)
id someObject = [NSMutableArray new]; // you don't need to cast id explicitly
I was tearing my hair out over this one, now I found a solution which does what i want:
1 encrypted file per host containing the sudo password
/etc/ansible/hosts:
[all:vars]
ansible_ssh_connection=ssh ansible_ssh_user=myuser ansible_ssh_private_key_file=~/.ssh/id_rsa
[some_service_group]
node-0
node-1
then you create for each host an encrypted var-file like so:
ansible-vault create /etc/ansible/host_vars/node-0
with content
ansible_sudo_pass: "my_sudo_pass_for_host_node-0"
how you organize the vault password (enter via --ask-vault-pass) or by cfg is up to you
based on this i suspect you can just encrypt the whole hosts file...
You can also consider to reverse your array and take the first element. That way you don't have to know about the length, but it brings no real benefits and the disadvantage that the reverse operation might take longer with big arrays:
array1.split(",").reverse()[0]
It's easy though, but also modifies the original array in question. That might or might not be a problem.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
Probably you might want to use this though:
array1.split(",").pop()
If you search into one directory, you can do it:
select-string -Path "c:\temp\*.*" -Pattern "result" -List | select Path
There are a number of approaches here- and though the position is that typically users should not be restricted when it comes to zooming for accessibility purposes, there may be incidences where is it required:
Render the page at the width of the device, dont scale:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Prevent scaling- and prevent the user from being able to zoom:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
Removing all zooming, all scaling
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
You're most likely using this on a local file over the file://
URI scheme, which cannot have cookies set. Put it on a local server so you can use http://localhost
.
I would not change the constraints, instead, you can insert a new record in the table_1 with the primary key (id_no = 7008255601088). This is nothing but a duplicate row of the id_no = 8008255601088. so now patient_address with the foreign key constraint (id_no = 8008255601088) can be updated to point to the record with the new ID(ID which needed to be updated), which is updating the id_no to id_no =7008255601088.
Then you can remove the initial primary key row with id_no =7008255601088.
Three steps include:
<div class="container">
<h1>About me</h1>
<div class="row">
<div class="pull-left ">
<img src="http://lorempixel.com/200/200" class="col-lg-3" class="img- responsive" alt="Responsive image">
<p class="col-md-4">Lots of text here... </p>
</div>
</div>
</div>
</div>
b = a(find(a~=0))
(in answer to the second question) By only using a sign bit (and not 2's complement), you can end up with -0. Not very pretty.
I just created the following method (based on the ideas of Chase) which might help you if you want to draw text to any canvas:
private static void drawText(Canvas canvas, int xStart, int yStart,
int xWidth, int yHeigth, String textToDisplay,
TextPaint paintToUse, float startTextSizeInPixels,
float stepSizeForTextSizeSteps) {
// Text view line spacing multiplier
float mSpacingMult = 1.0f;
// Text view additional line spacing
float mSpacingAdd = 0.0f;
StaticLayout l = null;
do {
paintToUse.setTextSize(startTextSizeInPixels);
startTextSizeInPixels -= stepSizeForTextSizeSteps;
l = new StaticLayout(textToDisplay, paintToUse, xWidth,
Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
} while (l.getHeight() > yHeigth);
int textCenterX = xStart + (xWidth / 2);
int textCenterY = (yHeigth - l.getHeight()) / 2;
canvas.save();
canvas.translate(textCenterX, textCenterY);
l.draw(canvas);
canvas.restore();
}
This could be used e.g. in any onDraw() method of any custom view.
A relation schema is the logical definition of a table - it defines what the name of the table is, and what the name and type of each column is. It's like a plan or a blueprint. A database schema is the collection of relation schemas for a whole database.
A table is a structure with a bunch of rows (aka "tuples"), each of which has the attributes defined by the schema. Tables might also have indexes on them to aid in looking up values on certain columns.
A database is, formally, any collection of data. In this context, the database would be a collection of tables. A DBMS (Database Management System) is the software (like MySQL, SQL Server, Oracle, etc) that manages and runs a database.
#if defined(CONDITION1) || defined(CONDITION2)
should work. :)
#ifdef
is a bit less typing, but doesn't work well with more complex conditions
The tel:
scheme was used in the late 1990s and documented in early 2000 with RFC 2806 (which was obsoleted by the more-thorough RFC 3966 in 2004) and continues to be improved. Supporting tel:
on the iPhone was not an arbitrary decision.
callto:
, while supported by Skype, is not a standard and should be avoided unless specifically targeting Skype users.
Me? I'd just start including properly-formed tel:
URIs on your pages (without sniffing the user agent) and wait for the rest of the world's phones to catch up :) .
Example:
<a href="tel:+18475555555">1-847-555-5555</a>
_x000D_
The latest dwr (http://directwebremoting.org/dwr/index.html) has ajax file uploads, complete with examples and nice stuff for users (like progress indicators and such).
It looks pretty nifty and dwr is fairly easy to use in general so this will be pretty good as well.
The link provided in the accepted answer shows a nice way to implement the pub/sub system using jQuery, but I found the code somewhat difficult to read, so here is my simplified version of the code:
$(document).on('testEvent', function(e, eventInfo) {
subscribers = $('.subscribers-testEvent');
subscribers.trigger('testEventHandler', [eventInfo]);
});
$('#myButton').on('click', function() {
$(document).trigger('testEvent', [1011]);
});
$('#notifier1').on('testEventHandler', function(e, eventInfo) {
alert('(notifier1)The value of eventInfo is: ' + eventInfo);
});
$('#notifier2').on('testEventHandler', function(e, eventInfo) {
alert('(notifier2)The value of eventInfo is: ' + eventInfo);
});
There are several way to approach globals:
Webpack evaluates modules only once, so your instance remains global and carries changes through from module to module. So if you create something like a globals.js
and export an object of all your globals then you can import './globals'
and read/write to these globals. You can import into one module, make changes to the object from a function and import into another module and read those changes in a function. Also remember the order things happen. Webpack will first take all the imports and load them up in order starting in your entry.js
. Then it will execute entry.js
. So where you read/write to globals is important. Is it from the root scope of a module or in a function called later?
config.js
export default {
FOO: 'bar'
}
somefile.js
import CONFIG from './config.js'
console.log(`FOO: ${CONFIG.FOO}`)
Note: If you want the instance to be new
each time, then use an ES6 class. Traditionally in JS you would capitalize classes (as opposed to the lowercase for objects) like
import FooBar from './foo-bar' // <-- Usage: myFooBar = new FooBar()
Here's how you can do it using Webpack's ProvidePlugin (which makes a module available as a variable in every module and only those modules where you actually use it). This is useful when you don't want to keep typing import Bar from 'foo'
again and again. Or you can bring in a package like jQuery or lodash as global here (although you might take a look at Webpack's Externals).
Step 1) Create any module. For example, a global set of utilities would be handy:
utils.js
export function sayHello () {
console.log('hello')
}
Step 2) Alias the module and add to ProvidePlugin:
webpack.config.js
var webpack = require("webpack");
var path = require("path");
// ...
module.exports = {
// ...
resolve: {
extensions: ['', '.js'],
alias: {
'utils': path.resolve(__dirname, './utils') // <-- When you build or restart dev-server, you'll get an error if the path to your utils.js file is incorrect.
}
},
plugins: [
// ...
new webpack.ProvidePlugin({
'utils': 'utils'
})
]
}
Now just call utils.sayHello()
in any js file and it should work. Make sure you restart your dev-server if you are using that with Webpack.
Note: Don't forget to tell your linter about the global, so it won't complain. For example, see my answer for ESLint here.
If you just want to use const with string values for your globals, then you can add this plugin to your list of Webpack plugins:
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
VERSION: JSON.stringify("5fa3b9"),
BROWSER_SUPPORTS_HTML5: true,
TWO: "1+1",
"typeof window": JSON.stringify("object")
})
Use it like:
console.log("Running App version " + VERSION);
if(!BROWSER_SUPPORTS_HTML5) require("html5shiv");
window.foo = 'bar' // For SPA's, browser environment.
global.foo = 'bar' // Webpack will automatically convert this to window if your project is targeted for web (default), read more here: https://webpack.js.org/configuration/node/
You'll see this commonly used for polyfills, for example: window.Promise = Bluebird
(For server side projects) The dotenv package will take a local configuration file (which you could add to your .gitignore if there are any keys/credentials) and adds your configuration variables to Node's process.env object.
// As early as possible in your application, require and configure dotenv.
require('dotenv').config()
Create a .env
file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE
. For example:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
That's it.
process.env
now has the keys and values you defined in your .env
file.
var db = require('db')
db.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS
})
Regarding Webpack's Externals, use it if you want to exclude some modules from being included in your built bundle. Webpack will make the module globally available but won't put it in your bundle. This is handy for big libraries like jQuery (because tree shaking external packages doesn't work in Webpack) where you have these loaded on your page already in separate script tags (perhaps from a CDN).
import pandas as pd
import os
files = os.listdir('path/to/files/directory/')
desiredFile = files[i]
filePath = 'path/to/files/directory/%s'
Ofile = filePath % desiredFile
xls_import = pd.read_csv(Ofile)
Now you can use the power of pandas DataFrames!
var days = [
"Sunday",
"Monday",
"...", //etc
"Saturday"
];
console.log(days[new Date().getDay()]);
Simple, read the Date object in JavaScript manual
To do other things with date, like get a readable string from it, I use:
var d = new Date();
d.toLocaleString();
If you just want time or date use:
d.toLocaleTimeString();
d.toLocaleDateString();
You can parse dates either by doing:
var d = new Date(dateToParse);
or
var d = Date.parse(dateToParse);
Using tail:
#dmesg
...
...
...
[132059.017752] cfg80211: (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
[132116.566238] cfg80211: Calling CRDA to update world regulatory domain
[132116.568939] cfg80211: World regulatory domain updated:
[132116.568942] cfg80211: (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132116.568944] cfg80211: (2402000 KHz - 2472000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568945] cfg80211: (2457000 KHz - 2482000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568947] cfg80211: (2474000 KHz - 2494000 KHz @ 20000 KHz), (300 mBi, 2000 mBm)
[132116.568948] cfg80211: (5170000 KHz - 5250000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132116.568949] cfg80211: (5735000 KHz - 5835000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
[132120.288218] cfg80211: Calling CRDA for country: GB
[132120.291143] cfg80211: Regulatory domain changed to country: GB
[132120.291146] cfg80211: (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132120.291148] cfg80211: (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211: (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211: (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211: (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211: (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | head 2
head: cannot open ‘2’ for reading: No such file or directory
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -2
[132120.291153] cfg80211: (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211: (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -5
[132120.291148] cfg80211: (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211: (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211: (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211: (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211: (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$ dmesg | grep cfg8021 | tail -6
[132120.291146] cfg80211: (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
[132120.291148] cfg80211: (2402000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291150] cfg80211: (5170000 KHz - 5250000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291152] cfg80211: (5250000 KHz - 5330000 KHz @ 40000 KHz), (N/A, 2000 mBm)
[132120.291153] cfg80211: (5490000 KHz - 5710000 KHz @ 40000 KHz), (N/A, 2700 mBm)
[132120.291155] cfg80211: (57240000 KHz - 65880000 KHz @ 2160000 KHz), (N/A, 4000 mBm)
alex@ubuntu:~/bugs/navencrypt/dev-tools$
Ok, after the information that your Activity extends ListActivity here's a way to implement OnItemClickListener:
public class newListView extends ListView {
public newListView(Context context) {
super(context);
}
@Override
public void setOnItemClickListener(
android.widget.AdapterView.OnItemClickListener listener) {
super.setOnItemClickListener(listener);
//do something when item is clicked
}
}
Seems your resource POST
method won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).
Since in you already add Access-Control-Allow-Origin
headers to your Response, you can add new OPTIONS
method to your resource class.
@OPTIONS
@Path("{path : .*}")
public Response options() {
return Response.ok("")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "2000")
.build();
}
I have faced a similar problem, I searched everywhere online for solutions and I tried to follow them. None worked for me. These were the steps I took to the problem.
Make new repo and push the existing code again to the new repo
git init doesn’t initialize if you already have a .git/ folder in your repository. So, for your case, do -
(1) rm -rf .git/
(2) git init
(3) git remote add origin https://repository.remote.url
(4) git commit -m “Commit message”
(5) git push -f origin master
Note that all git configs like remote repositories for this repository are cleared in step 1. So, you have to set up all remote repository URLs again.
Also, take care of the -f in step 5: The remote already has some code base with n commits, and you’re trying to make all those changes into a single commit. So, force-pushing the changes to remote is necessary.
Seems related to this issue IDEA-117518
I realise it says not to use this for 'responding to other answers' but unfortunately I don't have enough rep to add a comment onto the appropriate answer (!) but ...
If you are having problems in asp.net with the answer from 'My Head Hurts' - you need to add 'height : 100%' to the main generated FORM tag as well as HTML and BODY tags in order for this to work.
Well, personally I do not use numeric datatype to store phone numbers or related info.
How do you store a number say 001234567? It'll end up as 1234567, losing the leading zeros.
Of course you can always left-pad it up, but that's provided you know exactly how many digits the number should be.
This doesn't answer your entire post,
Just my 2 cents
Another difference not pointed out is that giving the struct a name (i.e. struct myStruct) also enables you to provide forward declarations of the struct. So in some other file, you could write:
struct myStruct;
void doit(struct myStruct *ptr);
without having to have access to the definition. What I recommend is you combine your two examples:
typedef struct myStruct{
int one;
int two;
} myStruct;
This gives you the convenience of the more concise typedef name but still allows you to use the full struct name if you need.
best answer written by Dmitri Korotkevitch:
Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.
If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:
Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode
Go to security/logins, open SA login properties
a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password
b. Assign password to SA user
c. Open "Status" tab and enable login.
I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.
Even shorter variant is to use
$(()=>{
});
where $
stands for jQuery and ()=>{}
is so called 'arrow function' that inherits this
from the closure. (So that in this
you'll probably have window
instead of document
.)
You can use sqlcmd to run a backup, or any other T-SQL script. You can find the detailed instructions and examples on various useful sqlcmd switches in this article: Working with the SQL Server command line (sqlcmd)
with prototype and without space :
String.prototype.trimToLength = function (trimLenght) {
return this.length > trimLenght ? this.substring(0, trimLenght - 3) + '...' : this
};
For anyone using Assets.xcassets and Swift 3, it'd be like this (no need for .png)
let buttonDone = UIButton(type: .Custom)
if let image = UIImage(named: "Done") {
self.buttonDone.setImage(image, for: .normal)
}
Should we include a little JS? Because CSS was not basically created for this job. CSS was just a style sheet to add styles to the HTML, but its pseudo classes can do something that the basic CSS can't do. For example button:active
active is pseudo.
Reference:
http://css-tricks.com/pseudo-class-selectors/ You can learn more about pseudo here!
Your code:
The code that you're having the basic but helpfull. And yes :active
will only occur once the click event is triggered.
button {
font-size: 18px;
border: 2px solid gray;
border-radius: 100px;
width: 100px;
height: 100px;
}
button:active {
font-size: 18px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}
This is what CSS would do, what rlemon suggested is good, but that would as he suggested would require a
tag.
How to use CSS:
You can use :focus
too. :focus
would work once the click is made and would stay untill you click somewhere else, this was the CSS, you were trying to use CSS, so use :focus
to make the buttons change.
What JS would do:
The JavaScript's jQuery library is going to help us for this code. Here is the example:
$('button').click(function () {
$(this).css('border', '1px solid red');
}
This will make sure that the button stays red even if the click gets out. To change the focus type (to change the color of red to other) you can use this:
$('button').click(function () {
$(this).css('border', '1px solid red');
// find any other button with a specific id, and change it back to white like
$('button#red').css('border', '1px solid white');
}
This way, you will create a navigation menu. Which will automatically change the color of the tabs as you click on them. :)
Hope you get the answer. Good luck! Cheers.
Addition to the accepted answer:
if you are going to use
@Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 },null)
this will create actionlink where you can't create new custom attribute or style for the link.
However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.
@Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 }, new { @class = "btn btn-info", @target = "_blank" })
Looks like you weren't providing the correct options. For wrapping labels, provide at least:
CGRect paragraphRect =
[attributedText boundingRectWithSize:CGSizeMake(300.f, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil];
Note: if the original text width is under 300.f there won't be line wrapping, so make sure the bound size is correct, otherwise you will still get wrong results.
use tar to split into multiple archives
there are plenty of programs that will work with tar files on windows, including cygwin.
Similar to one post above, (except I was using admin credentials) to get S3 uploads to work with large 50M file.
Initially my error was:
An error occurred (AccessDenied) when calling the CreateMultipartUpload operation: Access Denied
I switched the multipart_threshold to be above the 50M
aws configure set default.s3.multipart_threshold 64MB
and I got:
An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
I checked bucket public access settings and all was allowed. So I found that public access can be blocked on account level for all S3 buckets:
The second line is transformed to the following code:
s = (new StringBuilder()).append((String)null).append("hello").toString();
The append methods can handle null
arguments.
This should work:
unsigned char reverse(unsigned char b) {
b = (b & 0xF0) >> 4 | (b & 0x0F) << 4;
b = (b & 0xCC) >> 2 | (b & 0x33) << 2;
b = (b & 0xAA) >> 1 | (b & 0x55) << 1;
return b;
}
First the left four bits are swapped with the right four bits. Then all adjacent pairs are swapped and then all adjacent single bits. This results in a reversed order.
Although this is an old thread, here are two examples for solving the problem in Java8.
sorting by the first column ([][0]):
double[][] myArr = new double[mySize][2];
// ...
java.util.Arrays.sort(myArr, java.util.Comparator.comparingDouble(a -> a[0]));
sorting by the first two columns ([][0], [][1]):
double[][] myArr = new double[mySize][2];
// ...
java.util.Arrays.sort(myArr, java.util.Comparator.<double[]>comparingDouble(a -> a[0]).thenComparingDouble(a -> a[1]));
Text decoration affects the underline, not the color.
To set the visited color to the same as the default, try:
a {
color: blue;
}
Or
a {
text-decoration: none;
}
a:link, a:visited {
color: blue;
}
a:hover {
color: red;
}
This will only return 1 row, because you're just selecting a COUNT()
. you will use mysql_num_rows()
on the $query
in this case.
If you want to get a count of each of the ID
's, add GROUP BY id
to the end of the string.
Performance-wise, don't ever ever ever use *
in your queries. If there is 100 unique fields in a table and you want to get them all, you write out all 100, not *
. This is because *
has to recalculate how many fields it has to go, every single time it grabs a field, which takes a lot more time to call.
FirstOrDefault
returns the default value of a type if no item matches the predicate. For reference types that is null
. Thats the reason for the exception.
So you just have to check for null
first:
string displayName = null;
var keyValue = Dictionary
.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID));
if(keyValue != null)
{
displayName = keyValue.Value.DisplayName;
}
But what is the key of the dictionary if you are searching in the values? A Dictionary<tKey,TValue>
is used to find a value by the key. Maybe you should refactor it.
Another option is to provide a default value with DefaultIfEmpty
:
string displayName = Dictionary
.Where(kv => kv.Value.ID == long.Parse(options.ID))
.Select(kv => kv.Value.DisplayName) // not a problem even if no item matches
.DefaultIfEmpty("--Option unknown--") // or no argument -> null
.First(); // cannot cause an exception
I am generally using the way posted by Barry Wark and Rahul Gupta.
Although, I do not like repeating the same words in both .h and .m file. Note, that in the following example the line is almost identical in both files:
// file.h
extern NSString* const MyConst;
//file.m
NSString* const MyConst = @"Lorem ipsum";
Therefore, what I like to do is to use some C preprocessor machinery. Let me explain through the example.
I have a header file which defines the macro STR_CONST(name, value)
:
// StringConsts.h
#ifdef SYNTHESIZE_CONSTS
# define STR_CONST(name, value) NSString* const name = @ value
#else
# define STR_CONST(name, value) extern NSString* const name
#endif
The in my .h/.m pair where I want to define the constant I do the following:
// myfile.h
#import <StringConsts.h>
STR_CONST(MyConst, "Lorem Ipsum");
STR_CONST(MyOtherConst, "Hello world");
// myfile.m
#define SYNTHESIZE_CONSTS
#import "myfile.h"
et voila, I have all the information about the constants in .h file only.
Use slf4android lib.
It's simple implementation of slf4j api using android java.util.logging.*.
Features:
LoggerConfiguration.configuration().addHandlerToLogger
slf4android is maintained mainly by @miensol.
Read more about slf4android on our blog:
In all filesystems that I am familiar with, you can't do this in-place. You have to use an auxiliary file (which you can then rename to take the name of the original file).
Use this function:
function repeatElement(element, count) {
return Array(count).fill(element)
}
>>> repeatElement('#', 5).join('')
"#####"
Or for a more compact version:
const repeatElement = (element, count) =>
Array(count).fill(element)
>>> repeatElement('#', 5).join('')
"#####"
Or for a curry-able version:
const repeatElement = element => count =>
Array(count).fill(element)
>>> repeatElement('#')(5).join('')
"#####"
You can use this function with a list:
const repeatElement = (element, count) =>
Array(count).fill(element)
>>> ['a', 'b', ...repeatElement('c', 5)]
['a', 'b', 'c', 'c', 'c', 'c', 'c']
Seriously? You folks have never used
where (t.MyTableId == 1 || t.MyTableId == 2 || t.MyTableId == 3)
if (Build.VERSION.SDK_INT >= 24) {
Html.fromHtml(String, flag) // for 24 API and more
} else {
Html.fromHtml(String) // or for older API
}
for 24 API and more (flag)
public static final int FROM_HTML_MODE_COMPACT = 63;
public static final int FROM_HTML_MODE_LEGACY = 0;
public static final int FROM_HTML_OPTION_USE_CSS_COLORS = 256;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_BLOCKQUOTE = 32;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_DIV = 16;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_HEADING = 2;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST = 8;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM = 4;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH = 1;
public static final int TO_HTML_PARAGRAPH_LINES_CONSECUTIVE = 0;
public static final int TO_HTML_PARAGRAPH_LINES_INDIVIDUAL = 1;
I ran into the same problem but in a case where I do not have control of the output to string, which was taken care of by a library. After looking into details in the implementation of the Decimal type (see http://msdn.microsoft.com/en-us/library/system.decimal.getbits.aspx), I came up with a neat trick (here as an extension method):
public static decimal Normalize(this decimal value)
{
return value/1.000000000000000000000000000000000m;
}
The exponent part of the decimal is reduced to just what is needed. Calling ToString() on the output decimal will write the number without any trailing 0. E.g.
1.200m.Normalize().ToString();
(answered Nov 23 '10 at 19:48) I'm not really a big Pythoner - but I found this syntax once, forgot where from, so I thought I'd document it:
if you use sys.stdout.write
instead of print
(the difference being, sys.stdout.write
takes arguments as a function, in parenthesis - whereas print
doesn't), then for a one-liner, you can get away with inverting the order of the command and the for
, removing the semicolon, and enclosing the command in square brackets, i.e.:
python -c "import sys; [sys.stdout.write('rob\n') for r in range(10)]"
Have no idea how this syntax would be called in Python :)
Hope this helps,
Cheers!
(EDIT Tue Apr 9 20:57:30 2013) Well, I think I finally found what these square brackets in one-liners are about; they are "list comprehensions" (apparently); first note this in Python 2.7:
$ STR=abc
$ echo $STR | python -c "import sys,re; a=(sys.stdout.write(line) for line in sys.stdin); print a"
<generator object <genexpr> at 0xb771461c>
So the command in round brackets/parenthesis is seen as a "generator object"; if we "iterate" through it by calling next()
- then the command inside the parenthesis will be executed (note the "abc" in the output):
$ echo $STR | python -c "import sys,re; a=(sys.stdout.write(line) for line in sys.stdin); a.next() ; print a"
abc
<generator object <genexpr> at 0xb777b734>
If we now use square brackets - note that we don't need to call next()
to have the command execute, it executes immediately upon assignment; however, later inspection reveals that a
is None
:
$ echo $STR | python -c "import sys,re; a=[sys.stdout.write(line) for line in sys.stdin]; print a"
abc
[None]
This doesn't leave much info to look for, for the square brackets case - but I stumbled upon this page which I think explains:
Python Tips And Tricks – First Edition - Python Tutorials | Dream.In.Code:
If you recall, the standard format of a single line generator is a kind of one line 'for' loop inside brackets. This will produce a 'one-shot' iterable object which is an object you can iterate over in only one direction and which you can't re-use once you reach the end.
A 'list comprehension' looks almost the same as a regular one-line generator, except that the regular brackets - ( ) - are replaced by square brackets - [ ]. The major advanatge of alist comprehension is that produces a 'list', rather than a 'one-shot' iterable object, so that you can go back and forth through it, add elements, sort, etc.
And indeed it is a list - it's just its first element becomes none as soon as it is executed:
$ echo $STR | python -c "import sys,re; print [sys.stdout.write(line) for line in sys.stdin].__class__"
abc
<type 'list'>
$ echo $STR | python -c "import sys,re; print [sys.stdout.write(line) for line in sys.stdin][0]"
abc
None
List comprehensions are otherwise documented in 5. Data Structures: 5.1.4. List Comprehensions — Python v2.7.4 documentation as "List comprehensions provide a concise way to create lists"; presumably, that's where the limited "executability" of lists comes into play in one-liners.
Well, hope I'm not terribly too off the mark here ...
EDIT2: and here is a one-liner command line with two non-nested for-loops; both enclosed within "list comprehension" square brackets:
$ echo $STR | python -c "import sys,re; a=[sys.stdout.write(line) for line in sys.stdin]; b=[sys.stdout.write(str(x)) for x in range(2)] ; print a ; print b"
abc
01[None]
[None, None]
Notice that the second "list" b
now has two elements, since its for loop explicitly ran twice; however, the result of sys.stdout.write()
in both cases was (apparently) None
.
Initialize empty frame with column names
import pandas as pd
col_names = ['A', 'B', 'C']
my_df = pd.DataFrame(columns = col_names)
my_df
Add a new record to a frame
my_df.loc[len(my_df)] = [2, 4, 5]
You also might want to pass a dictionary:
my_dic = {'A':2, 'B':4, 'C':5}
my_df.loc[len(my_df)] = my_dic
Append another frame to your existing frame
col_names = ['A', 'B', 'C']
my_df2 = pd.DataFrame(columns = col_names)
my_df = my_df.append(my_df2)
Performance considerations
If you are adding rows inside a loop consider performance issues. For around the first 1000 records "my_df.loc" performance is better, but it gradually becomes slower by increasing the number of records in the loop.
If you plan to do thins inside a big loop (say 10M? records or so), you are better off using a mixture of these two; fill a dataframe with iloc until the size gets around 1000, then append it to the original dataframe, and empty the temp dataframe. This would boost your performance by around 10 times.
This is not explicitly mentioned, but based on the following docs, I think it is implied that an app needs to declare and implement a BackupAgent in order for data backup to work, even in the case when allowBackup is set to true (which is the default value).
http://developer.android.com/reference/android/R.attr.html#allowBackup http://developer.android.com/reference/android/app/backup/BackupManager.html http://developer.android.com/guide/topics/data/backup.html
C:\Users\<Username>\AppData\Local\Continuum\anaconda2
For me this was the default installation directory on Windows 7. Found it via Rusy's answer
Try setting this before you print:
setvbuf (stdout, NULL, _IONBF, 0);
By default, Ctrl+Tab in Visual Studio Code cycles through tabs in order of most recently used. This is confusing because it depends on hidden state.
Web browsers cycle through tabs in visible order. This is much more intuitive.
To achieve this in Visual Studio Code, you have to edit keybindings.json
. Use the Command Palette with CTRL+SHIFT+P, enter "Preferences: Open Keyboard Shortcuts (JSON)", and hit Enter.
Then add to the end of the file:
[
// ...
{
"key": "ctrl+tab",
"command": "workbench.action.nextEditor"
},
{
"key": "ctrl+shift+tab",
"command": "workbench.action.previousEditor"
}
]
Alternatively, to only cycle through tabs of the current window/split view, you can use:
[
{
"key": "ctrl+tab",
"command": "workbench.action.nextEditorInGroup"
},
{
"key": "ctrl+shift+tab",
"command": "workbench.action.previousEditorInGroup"
}
]
Alternatively, you can use Ctrl+PageDown (Windows) or Cmd+Option+Right (Mac).
This is the most simple solution for me:
$tStamp = Get-Date -format yyyy_MM_dd_HHmmss
$tStamp = Get-Date (get-date).AddMonths(6).Date -Format yyyyMMdd
IF vertical align won't work use padding.
padding-top: 10px;
it will shift the text to the bottom or
padding-bottom: 10px;
to shift the text in the text box to top
adjust the padding size till it suit the size you want. Thats the hack
Since Google updates sometimes the name of fixed object properties, the best practice is to use GMaps V3 methods to get coordinates event.overlay.getPath().getArray() and to get lat latlng.lat() and lng latlng.lng().
So, I just wanted to improve this answer a bit exemplifying with polygon and POSTGIS insert case scenario:
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
var str_input ='POLYGON((';
if (event.type == google.maps.drawing.OverlayType.POLYGON) {
console.log('polygon path array', event.overlay.getPath().getArray());
$.each(event.overlay.getPath().getArray(), function(key, latlng){
var lat = latlng.lat();
var lon = latlng.lng();
console.log(lat, lon);
str_input += lat +' '+ lon +',';
});
}
str_input = str_input.substr(0,str_input.length-1) + '))';
console.log('the str_input will be:', str_input);
// YOU CAN THEN USE THE str_inputs AS IN THIS EXAMPLE OF POSTGIS POLYGON INSERT
// INSERT INTO your_table (the_geom, name) VALUES (ST_GeomFromText(str_input, 4326), 'Test')
});
here is the solution
Put your html and css in your /assets/ folder, then load the html file like so:
WebView wv = new WebView(this);
wv.loadUrl("file:///android_asset/yourHtml.html");
then in your html you can reference your css in the usual way
<link rel="stylesheet" type="text/css" href="main.css" />
In my case it was due to 'lower_case_table_names' parameter.
The error number 39 thrown out when I tried to drop the databases which consists upper case table names with lower_case_table_names parameter is enabled.
This is fixed by reverting back the lower case parameter changes to the previous state.
You can use https://ip-api.io/ to get city Name. It supports IPv6.
As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.
Javascript Code:
$(document).ready(function () {
$('#btnGetIpDetail').click(function () {
if ($('#txtIP').val() == '') {
alert('IP address is reqired');
return false;
}
$.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
function (result) {
alert('City Name: ' + result.city)
console.log(result);
});
});
});
HTML Code
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div>
<input type="text" id="txtIP" />
<button id="btnGetIpDetail">Get Location of IP</button>
</div>
JSON Output
{
"ip": "64.30.228.118",
"country_code": "US",
"country_name": "United States",
"region_code": "FL",
"region_name": "Florida",
"city": "Fort Lauderdale",
"zip_code": "33309",
"time_zone": "America/New_York",
"latitude": 26.1882,
"longitude": -80.1711,
"metro_code": 528,
"suspicious_factors": {
"is_proxy": false,
"is_tor_node": false,
"is_spam": false,
"is_suspicious": false
}
}
I just upgraded a WXWindows project to Python 2.7 and had no end of trouble getting Pydev to recognize the new interpreter. Did the same thing as above configuring the interpreter, made a fresh install of Eclipse and Pydev. Thought some part of python must have been corrupt, so I re-installed everything again. Arghh! Closed and reopened the project, and restarted Eclipse between all of these changes.
FINALLY noticed you can 'remove the PyDev project config' by right clicking on project. Then it can be made into a PyDev project again, now it is good as gold!
you can also pyramid of stars like this
for (var i = 5; i >= 1; i--) {
var py = "";
for (var j = i; j >= 1; j--) {
py += j;
}
console.log(py);
}
let double = 1.5
let string = double.description
update Xcode 7.1 • Swift 2.1:
Now Double is also convertible to String so you can simply use it as you wish:
let double = 1.5
let doubleString = String(double) // "1.5"
Swift 3 or later we can extend LosslessStringConvertible
and make it generic
Xcode 11.3 • Swift 5.1 or later
extension LosslessStringConvertible {
var string: String { .init(self) }
}
let double = 1.5
let string = double.string // "1.5"
For a fixed number of fraction digits we can extend FloatingPoint
protocol:
extension FloatingPoint where Self: CVarArg {
func fixedFraction(digits: Int) -> String {
.init(format: "%.*f", digits, self)
}
}
If you need more control over your number format (minimum and maximum fraction digits and rounding mode) you can use NumberFormatter
:
extension Formatter {
static let number = NumberFormatter()
}
extension FloatingPoint {
func fractionDigits(min: Int = 2, max: Int = 2, roundingMode: NumberFormatter.RoundingMode = .halfEven) -> String {
Formatter.number.minimumFractionDigits = min
Formatter.number.maximumFractionDigits = max
Formatter.number.roundingMode = roundingMode
Formatter.number.numberStyle = .decimal
return Formatter.number.string(for: self) ?? ""
}
}
2.12345.fractionDigits() // "2.12"
2.12345.fractionDigits(min: 3, max: 3, roundingMode: .up) // "2.124"
#some example data
set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))
#calculate mean, min and max for each x-value
library(plyr)
df2 <- ddply(df,.(x),function(df) c(mean=mean(df$y),min=min(df$y),max=max(df$y)))
#plot error bars
library(Hmisc)
with(df2,errbar(x,mean,max,min))
grid(nx=NA,ny=NULL)
There is a possibility also that you added another local repository with the same alias. As an example, you now have 2 local folders referred to as origin
so when you try to push, the remote repository will not accept you credentials.
Rename the local repository aliases, you can follow this link https://stackoverflow.com/a/26651835/2270348
Maybe you can leave 1 local repository of your liking as origin
and the others rename them for example from origin
to anotherorigin
. Remember these are just aliases and all you need to do is remember the new aliases and their respective remote branches.
You need to specify which object you're calling getElementById from. In this case you can use document. You also can't just call .value on any element directly. For example if the element is textbox .value will return the value, but if it's a div it will not have a value.
You also have a wrong condition, you're checking
if (myEle == null)
which you should change to
if (myEle != null)
var myEle = document.getElementById("myElement");
if(myEle != null) {
var myEleValue= myEle.value;
}
I'd like to do this way :)
const sthError = () => Promise.reject('sth error');
const test = opts => {
return (async () => {
// do sth
await sthError();
return 'ok';
})().catch(err => {
console.error(err); // error will be catched there
});
};
test().then(ret => {
console.log(ret);
});
It's similar to handling error with co
const test = opts => {
return co(function*() {
// do sth
yield sthError();
return 'ok';
}).catch(err => {
console.error(err);
});
};
I had as same problem . afer lot of R&D i found the problem.
but as long as your configuration are finne mean that aspnet 64 bit and the IIS well then the only problem i saw is the path " web api taking the local directiry path" so that you need to avid it. by like this.. ~../../../api/products/
thank you very much for posting the problem. i leanred alot abt iis and other setting in config file.
For me what happened was that I generated the app with rails new rails new chapter_2 but the RVM --default had rails 4.0.2 gem, but my chapter_2 project use a new gemset with rails 3.2.16.
So when I ran
rails generate scaffold User name:string email:string
the console showed
Usage:
rails new APP_PATH [options]
So I fixed the RVM and the gemset with the rails 3.2.16 gem , and then generated the app again then I executed
rails generate scaffold User name:string email:string
and it worked
Under TARGETS
in your project, right-click on your project target (should be the same name as your project) and choose GET INFO
, then on GENERAL
tab you will see DIRECT DEPENDENCIES
, simply click the [+]
and select SoundCloudAPI
.
This is what I use (usually wrapped in something I stuff in Model):
Select
[Parent] = Left((Case When Tr.Parent_Class = 0 Then '(Database)' Else Object_Name(Tr.Parent_ID) End), 32),
[Schema] = Left(Coalesce(Object_Schema_Name(Tr.Object_ID), '(None)'), 16),
[Trigger name] = Left(Tr.Name, 32),
[Type] = Left(Tr.Type_Desc, 3), -- SQL or CLR
[MS?] = (Case When Tr.Is_MS_Shipped = 1 Then 'X' Else ' ' End),
[On?] = (Case When Tr.Is_Disabled = 0 Then 'X' Else ' ' End),
[Repl?] = (Case When Tr.Is_Not_For_Replication = 0 Then 'X' Else ' ' End),
[Event] = Left((Case When Tr.Parent_Class = 0
Then (Select Top 1 Left(Te.Event_Group_Type_Desc, 40)
From Sys.Trigger_Events As Te
Where Te.Object_ID = Tr.Object_ID)
Else ((Case When Tr.Is_Instead_Of_Trigger = 1 Then 'Instead Of ' Else 'After ' End)) +
SubString(Cast((Select [text()] = ', ' + Left(Te.Type_Desc, 1) + Lower(SubString(Te.Type_Desc, 2, 32)) +
(Case When Te.Is_First = 1 Then ' (First)' When Te.Is_Last = 1 Then ' (Last)' Else '' End)
From Sys.Trigger_Events As Te
Where Te.Object_ID = Tr.Object_ID
Order By Te.[Type]
For Xml Path ('')) As Character Varying), 3, 60) End), 60)
-- If you like:
-- , [Get text with] = 'Select Object_Definition(' + Cast(Tr.Object_ID As Character Varying) + ')'
From
Sys.Triggers As Tr
Order By
Tr.Parent_Class, -- database triggers first
Parent -- alphabetically by parent
As you see it is a skosh more McGyver, but I think it's worth it:
Parent Schema Trigger name Type MS? On? Repl? Event
-------------------------------- ---------------- -------------------------------- ---- ---- ---- ----- -----------------------------------------
(Database) (None) ddlDatabaseTriggerLog SQL X DDL_DATABASE_LEVEL_EVENTS
Employee HumanResources dEmployee SQL X Instead Of Delete
Person Person iuPerson SQL X After Insert, Update
PurchaseOrderDetail Purchasing iPurchaseOrderDetail SQL X X After Insert
PurchaseOrderDetail Purchasing uPurchaseOrderDetail SQL X X After Update
PurchaseOrderHeader Purchasing uPurchaseOrderHeader SQL X X After Update
SalesOrderDetail Sales iduSalesOrderDetail SQL X X After Insert, Update, Delete
SalesOrderHeader Sales uSalesOrderHeader SQL X After Update (First)
Vendor Purchasing dVendor SQL X Instead Of Delete
WorkOrder Production iWorkOrder SQL X X After Insert
WorkOrder Production uWorkOrder SQL X X After Update
(Scroll right to see the final and most useful column)
Close to your solution would be this:
var largest = 0
for (i <- 999 to 1 by -1;
j <- i to 1 by -1;
product = i * j;
if (largest <= product && product.toString.reverse.equals (product.toString.reverse.reverse)))
largest = product
println (largest)
The j-iteration is made without a new scope, and the product-generation as well as the condition are done in the for-statement (not a good expression - I don't find a better one). The condition is reversed which is pretty fast for that problem size - maybe you gain something with a break for larger loops.
String.reverse implicitly converts to RichString, which is why I do 2 extra reverses. :) A more mathematical approach might be more elegant.
By default, all paths you define will be relative. The question is: relative to what? There are several options:
Please note that following a macro such as $(SolutionDir) there is no need to add a backward slash "\". Just use $(SolutionDir)mylibdir\mylib.lib. In case you just can't get it to work, open the project file externally from Notepad and check it.
Like the other answers said, sp_reset_connection
indicates that connection pool is being reused. Be aware of one particular consequence!
Jimmy Mays' MSDN Blog said:
sp_reset_connection does NOT reset the transaction isolation level to the server default from the previous connection's setting.
UPDATE: Starting with SQL 2014, for client drivers with TDS version 7.3 or higher, the transaction isolation levels will be reset back to the default.
ref: SQL Server: Isolation level leaks across pooled connections
Here is some additional information:
What does sp_reset_connection do?
Data access API's layers like ODBC, OLE-DB and System.Data.SqlClient all call the (internal) stored procedure sp_reset_connection when re-using a connection from a connection pool. It does this to reset the state of the connection before it gets re-used, however nowhere is documented what things get reset. This article tries to document the parts of the connection that get reset.
sp_reset_connection resets the following aspects of a connection:
All error states and numbers (like @@error)
Stops all EC's (execution contexts) that are child threads of a parent EC executing a parallel query
Waits for any outstanding I/O operations that is outstanding
Frees any held buffers on the server by the connection
Unlocks any buffer resources that are used by the connection
Releases all allocated memory owned by the connection
Clears any work or temporary tables that are created by the connection
Kills all global cursors owned by the connection
Closes any open SQL-XML handles that are open
Deletes any open SQL-XML related work tables
Closes all system tables
Closes all user tables
Drops all temporary objects
Aborts open transactions
Defects from a distributed transaction when enlisted
Decrements the reference count for users in current database which releases shared database locks
Frees acquired locks
Releases any acquired handles
Resets all SET options to the default values
Resets the @@rowcount value
Resets the @@identity value
Resets any session level trace options using dbcc traceon()
Resets CONTEXT_INFO to
NULL
in SQL Server 2005 and newer [ not part of the original article ]sp_reset_connection will NOT reset:
Security context, which is why connection pooling matches connections based on the exact connection string
Application roles entered using sp_setapprole, since application roles could not be reverted at all prior to SQL Server 2005. Starting in SQL Server 2005, app roles can be reverted, but only with additional information that is not part of the session. Before closing the connection, application roles need to be manually reverted via sp_unsetapprole using a "cookie" value that is captured when
sp_setapprole
is executed.
Note: I am including the list here as I do not want it to be lost in the ever transient web.
Here are slightly different options to accomplish the task at hand.
using toMap
:
list.stream()
.collect(Collectors.toMap(Function.identity(), e -> 1, Math::addExact));
using Map::merge
:
Map<String, Integer> accumulator = new HashMap<>();
list.forEach(s -> accumulator.merge(s, 1, Math::addExact));
com.nhaarman.mockitokotlin2.mock {}
This error occurs when, for example, we create a mock inside another mock
mock {
on { x() } doReturn mock {
on { y() } doReturn z()
}
}
The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.
val liveDataMock = mock {
on { y() } doReturn z()
}
mock {
on { x() } doReturn liveDataMock
}
GL
One more reason I found (vague as it may sound). The below did not work.
LinearLayout vertical
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
EndLinearLayout
What did work was
RelativeLayout
LinearLayout vertical
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
EndLinearLayout
EndRelativeLayout
It sounds vague by a root layout with Linear and weights under it did not work. And when I say "did not work", I mean, that after I viewed the graphical layout between various resolutions the screen consistency broke big time.
A conditional insert for use typically in a MySQL script would be:
insert into t1(col1,col2,col3,...)
select val1,val2,val3,...
from dual
where [conditional predicate];
You need to use dummy table dual.
In this example, only the second insert-statement will actually insert data into the table:
create table t1(col1 int);
insert into t1(col1) select 1 from dual where 1=0;
insert into t1(col1) select 2 from dual where 1=1;
select * from t1;
+------+
| col1 |
+------+
| 2 |
+------+
1 row in set (0.00 sec)
I did all the answers above and it just didn't solve my problem.
Finally, I solved my slow site loading problem with setting PrecompileBeforePublish in Publish Profile to true. If you want to use msbuild you can use this argument:
/p:PrecompileBeforePublish=true
It really help a lot. Now my MVC ASP.NET loads 10 times faster.
Combining the input from everyone else (use not, no parens, use os.mkdir
) you'd get...
special_path_for_john = "/usr/share/sounds/blues"
if not os.path.exists(special_path_for_john):
os.mkdir(special_path_for_john)
This is because str.index(ch)
will return the index where ch
occurs the first time. Try:
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
This will return a list of all indexes you need.
P.S. Hugh's answer shows a generator function (it makes a difference if the list of indexes can get large). This function can also be adjusted by changing []
to ()
.
I doubt that this is what you want but your question is a little bit vague
Dim totalCount As Int32 = DataTable1.Columns.Count * DataTable1.Rows.Count
If all your columns are numeric-columns you might want this:
You could use DataTable.Compute to Sum
all values in the column.
Dim totalCount As Double
For Each col As DataColumn In DataTable1.Columns
totalCount += Double.Parse(DataTable1.Compute(String.Format("SUM({0})", col.ColumnName), Nothing).ToString)
Next
After you've edited your question and added more informations, this should work:
Dim totalRow = DataTable1.NewRow
For Each col As DataColumn In DataTable1.Columns
totalRow(col.ColumnName) = Double.Parse(DataTable1.Compute("SUM(" & col.ColumnName & ")", Nothing).ToString)
Next
DataTable1.Rows.Add(totalRow)
This is the most neat way in my opinion.
(for some reason Array.map doesn't work inside .then functions for me. But you can use a .forEach and [].concat() or something similar)
Promise.all([
fetch('/user/4'),
fetch('/user/5'),
fetch('/user/6'),
fetch('/user/7'),
fetch('/user/8')
]).then(responses => {
return responses.map(response => {response.json()})
}).then((values) => {
console.log(values);
})
AForge.net is a free (open-source) library with Fast Fourier Transform support. (See Sources/Imaging/ComplexImage.cs for usage, Sources/Math/FourierTransform.cs for implemenation)
Use:
h1 {_x000D_
margin: 0;_x000D_
position: absolute;_x000D_
left: 50%;_x000D_
top: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
}_x000D_
.container {_x000D_
height: 200px;_x000D_
width: 500px;_x000D_
position: relative;_x000D_
border: 1px solid #eee;_x000D_
}
_x000D_
<div class="container">_x000D_
<h1>Vertical align text</h1>_x000D_
</div>
_x000D_
With this trick, you can align anything if you don't want to make it center add "left:0" to align left.
Here is another fancy way of doing this:
$ ls | grep .java | xargs -I {} javac {} ; jar -cf myJar.jar *.class
Which will grab all the .java files ( ls | grep .java
) from your current directory and compile them into .class (xargs -I {} javac {}
) and then create the jar file from the previously compiled classes (jar -cf myJar.jar *.class
).
Remember - if you set the buttons to vbOkOnly
- it will always return 1.
So you can't decide if a user clicked on the close or the OK button. You just have to add a vbOk
option.
You need to use a regular expression, so that you can specify the global (g) flag:
var s = 'some+multi+word+string'.replace(/\+/g, ' ');
(I removed the $()
around the string, as replace
is not a jQuery method, so that won't work at all.)
DataTable dt=new DataTable();
DataColumn Name = new DataColumn("Name",typeof(string));
dt.Columns.Add(Name);
DataColumn Age = new DataColumn("Age", typeof(int));`
dt.Columns.Add(Age);
DataRow dr=dt.NewRow();
dr["Name"]="Kavitha Reddy";
dr["Age"]=24;
dt.add.Rows(dr);
dr=dt.NewRow();
dr["Name"]="Kiran Reddy";
dr["Age"]=23;
dt.Rows.add(dr);
Gv.DataSource=dt;
Gv.DataBind();
If you want to change the title as a response to being tapped you can try this inside the IBAction method of the button in your view controller delegate. This toggles a voice chat on and off. Setting up the voice chat is not covered here!
- (IBAction)startChat:(id)sender {
UIButton *chatButton = (UIButton*)sender;
if (!voiceChat.active) {
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Voice Chat"
message:@"Voice Chat will become live. Please be careful with feedback if your friend is nearby."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
[voiceChat start];
voiceChat.active = YES;
[chatButton setTitle:@"Stop Chat" forState:UIControlStateNormal];
}
else {
[voiceChat stop];
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Voice Chat"
message:@"Voice Chat is closed"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
voiceChat.active = NO;
[chatButton setTitle:@"Chat" forState:UIControlStateNormal];
}
}
voiceChat is specific to voice chat of course, but you can use your ow local boolean property to control the switch.
== is what you want, "is" just happens to work on your examples.
Note that for large values, hex()
still works (some other answers don't):
x = hex(349593196107334030177678842158399357)
print(x)
Python 2: 0x4354467b746f6f5f736d616c6c3f7dL
Python 3: 0x4354467b746f6f5f736d616c6c3f7d
For a decrypted RSA message, one could do the following:
import binascii
hexadecimals = hex(349593196107334030177678842158399357)
print(binascii.unhexlify(hexadecimals[2:-1])) # python 2
print(binascii.unhexlify(hexadecimals[2:])) # python 3
I was struggling with this problem, and I learned (thanks to this post) that:
div:first-child {_x000D_
opacity: .99; _x000D_
}_x000D_
_x000D_
.red, .green, .blue {_x000D_
position: absolute;_x000D_
width: 100px;_x000D_
color: white;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.red {_x000D_
z-index: 1;_x000D_
top: 20px;_x000D_
left: 20px;_x000D_
background: red;_x000D_
}_x000D_
_x000D_
.green {_x000D_
top: 60px;_x000D_
left: 60px;_x000D_
background: green;_x000D_
}_x000D_
_x000D_
.blue {_x000D_
top: 100px;_x000D_
left: 100px;_x000D_
background: blue;_x000D_
}
_x000D_
<div>_x000D_
<span class="red">Red</span>_x000D_
</div>_x000D_
<div>_x000D_
<span class="green">Green</span>_x000D_
</div>_x000D_
<div>_x000D_
<span class="blue">Blue</span>_x000D_
</div>
_x000D_
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server
argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
If you even plan on merging your branch, I highly suggest you look at this:
I hear Subversion 1.5 builds more of the merge tracking in, I have no experience with that. My project is on 1.4.x and svnmerge.py is a life saver!
Try this instead:
(SolidColorBrush)(new BrushConverter().ConvertFrom("#ffaacc"));
If you have two values yanked into two different registers (for example register a
and register b
) then you can simply set a variable c
and do the operation on it.
For example, :set c = str2float(@a) + str2float(@b)
and then you can paste the content of c
anywhere.
For example whilst in INSERT mode, CTRL + R
then type =
to enter into the expression register and just type c
after equal sign and hit ENTER. Done you should now have the total of a
and b
registers.
All these can be recorded in a macro and repeated over!
The str2float
function is used if you are working with floats, if you don't, you will get integers instead.
I am not sure if this is idiomatic but it worked for my case where I needed to add 2 numbers in a row and repeat it for 500 more lines.
You have a few different options:
I can confirm that this bug is still present in Ubuntu 19.04 (Disco Dingo). The workaround suggested by VonC worked perfectly, summarizing for my version:
Next, I tried ssh-add -D
again, and after reboot ssh-add -l
told me The agent has no identities. I confirmed that I still had the ssh-agent
daemon running with ps aux | grep agent
. So I added the key I most frequently used with GitHub (ssh-add ~/.ssh/id_ecdsa
) and all was good!
Now I can do the normal operations with my most frequently used repository, and if I occasionally require access to the other repository which uses the RSA key, I just dedicate one terminal for it with export GIT_SSH_COMMAND="ssh -i /home/me/.ssh/id_rsa.pub"
. Solved! Credit goes to VonC for pointing out the bug and the solution.
The whole thing to em is, that the size is relative to the base. So I would say you could keep the font sizes by altering the base.
Example: If you base is 16px, and p is .75em (which is 12px) you would have to raise the base to about 20px. In this case p would then equal about 15px which is the minimum I personally require for mobile phones.
Use double quotes:
$i = 1;
echo "
<p class=\"paragraph$i\">
</p>
";
++i;
I know this question was for SQL Server 2005, but I thought I'd mention- as of SQL 2012, there now is an EOMONTH()
function that gets the last day of the month. To get it in the format specified by the original asker you'd have to cast to a datetime
.
SELECT CAST(eomonth(GETDATE()) AS datetime)
Model–View–Controller (usually known as MVC) is a software design pattern commonly used for developing user interfaces that divide the related program logic into three interconnected elements. This is done to separate internal representations of information from the ways information is presented to and accepted by the user. Following the MVC architectural pattern decouples these major components allowing for code reuse and parallel development.
Traditionally used for desktop graphical user interfaces (GUIs), this pattern has become popular for designing web applications. Popular programming languages like JavaScript, Python, Ruby, PHP, Java, and C# have MVC frameworks that are used in web application development straight out of the box.
Model
The central component of the pattern. It is the application's dynamic data structure, independent of the user interface. It directly manages the data, logic, and rules of the application.
View
Any representation of information such as a chart, diagram or table. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants.
Controller
Accepts input and converts it to commands for the model or view.
In addition to dividing the application into these components, the model–view–controller design defines the interactions between them.
The model is responsible for managing the data of the application. It receives user input from the controller.
The view means a presentation of the model in a particular format.
The controller responds to the user input and performs interactions on the data model objects. The controller receives the input, optionally validates it and then passes the input to the model.
Model–View–ViewModel (MVVM) is a software architectural pattern.
MVVM facilitates a separation of development of the graphical user interface – be it via a markup language or GUI code – from the development of the business logic or back-end logic (the data model). The view model of MVVM is a value converter, meaning the view model is responsible for exposing (converting) the data objects from the model in such a way that objects are easily managed and presented. In this respect, the view model is more model than a view and handles most if not all of the view's display logic. The view model may implement a mediator pattern, organizing access to the back-end logic around the set of use cases supported by the view.
MVVM is a variation of Martin Fowler's Presentation Model design pattern. MVVM abstracts a view's state and behavior in the same way, but a Presentation Model abstracts a view (creates a view model) in a manner not dependent on a specific user-interface platform.
MVVM was invented by Microsoft architects Ken Cooper and Ted Peters specifically to simplify event-driven programming of user interfaces. The pattern was incorporated into Windows Presentation Foundation (WPF) (Microsoft's .NET graphics system) and Silverlight (WPF's Internet application derivative). John Gossman, one of Microsoft's WPF and Silverlight architects, announced MVVM on his blog in 2005.
Model–View–ViewModel is also referred to as model–view–binder, especially in implementations not involving the .NET platform. ZK (a web application framework written in Java) and KnockoutJS (a JavaScript library) use model–view–binder.
Your class needs to extend from ActionBarActivity
, rather than a plain Activity
in order to use the getSupport*()
methods.
Update [2015/04/23]: With the release of Android Support Library 22.1, you should now extend AppCompatActivity.
Also, you no longer have to extend ActionBarActivity
or AppCompatActivity
, as you can now incorporate an AppCompatDelegate
instance in any activity.
Try This:
table.table tr th{background-color:blue !important; font-color:white !important;}
hope this helps..
You can try the following and it worked for me.
Import following scripts and css files as there are used by the date picker.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
The JS coding for the Date Picker I use.
<script>
$(document).ready(function(){
// alert ('Cliecked');
var date_input=$('input[name="orangeDateOfBirthForm"]'); //our date input has the name "date"
var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body";
var options={
format: 'dd/mm/yyyy', //format of the date
container: container,
changeYear: true, // you can change the year as you need
changeMonth: true, // you can change the months as you need
todayHighlight: true,
autoclose: true,
yearRange: "1930:2100" // the starting to end of year range
};
date_input.datepicker(options);
});
</script>
The HTML Coding:
<input type="text" id="orangeDateOfBirthForm" name="orangeDateOfBirthForm" class="form-control validate" required>
<label data-error="wrong" data-success="right" for="orangeForm-email">Date of Birth</label>
hdpi 480x800 px Samsung S2
xhdpi 720x1280 px - Nexus 4 phone - 4.7,4.8 inches Samsung Galaxy S3 Motorola Moto G
xxhdpi 1080x1920 px - Nexus 5 phone - 4.95 inches
Samsung Galaxy S4
Samsung Galaxy S5
Samsung Galaxy Note 3 - 5.7 inches
LG G2
HTC One M8
HTC One M9
Sony Xperia Z1
Sony Xperia Z2
Sony Xperia Z3
Sony Xperia Z3+
xxxhdpi 1440x2560 px - Nexus 6 phablet - 6 inches
Samsung S6
Samsung S6 Edge
Samsung Galaxy Note 4 - 5.7 inches
LG G3
LG G4
xxhdpi 1920×1200 px - Nexus 7 tablet - 7 inches Sony Z3 Tablet Compact LG G Pad 8.3 - 8.3 inches Sony Xperia Z2 Tablet - 10.1 inches
xxxhdpi 2560×1600 px - Nexus 10 tablet - 10.1 inches ~Google Nexus 9 Sony Xperia Z4 tablet Samsung Galaxy Note Pro 12.2 Samsung Galaxy Note 10.1 Samsung Galaxy Tab S 10.5 Dell Venue 8 7840
void foo<TOne, TTwo>()
where TOne : BaseOne
where TTwo : BaseTwo
More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx
import os, time, datetime
file = "somefile.txt"
print(file)
print("Modified")
print(os.stat(file)[-2])
print(os.stat(file).st_mtime)
print(os.path.getmtime(file))
print()
print("Created")
print(os.stat(file)[-1])
print(os.stat(file).st_ctime)
print(os.path.getctime(file))
print()
modified = os.path.getmtime(file)
print("Date modified: "+time.ctime(modified))
print("Date modified:",datetime.datetime.fromtimestamp(modified))
year,month,day,hour,minute,second=time.localtime(modified)[:-3]
print("Date modified: %02d/%02d/%d %02d:%02d:%02d"%(day,month,year,hour,minute,second))
print()
created = os.path.getctime(file)
print("Date created: "+time.ctime(created))
print("Date created:",datetime.datetime.fromtimestamp(created))
year,month,day,hour,minute,second=time.localtime(created)[:-3]
print("Date created: %02d/%02d/%d %02d:%02d:%02d"%(day,month,year,hour,minute,second))
prints
somefile.txt
Modified
1429613446
1429613446.0
1429613446.0
Created
1517491049
1517491049.28306
1517491049.28306
Date modified: Tue Apr 21 11:50:46 2015
Date modified: 2015-04-21 11:50:46
Date modified: 21/04/2015 11:50:46
Date created: Thu Feb 1 13:17:29 2018
Date created: 2018-02-01 13:17:29.283060
Date created: 01/02/2018 13:17:29
I received the error "Unable to allocate memory for pool" after moving an OpenCart installation to a different server. I also tried raising the memory_limit.
The error stopped after I changed the permissions of the file in the error message to have write access by the user that apache runs as (apache, www-data, etc.). Instead of modifying /etc/group directly (or chmod-ing the files to 0777), I used usermod:
usermod -a -G vhost-user-group apache-user
Then I had to restart apache for the change to take effect:
apachectl restart
Or
sudo /etc/init.d/httpd restart
Or whatever your system uses to restart apache.
If the site is on shared hosting, maybe you must change the file permissions with an FTP program, or contact the hosting provider?
Both of the options you provided are the same. Both of them will still point to the same object in memory and have the same array values. You should treat the state object as immutable as you said, however you need to re-create the array so its pointing to a new object, set the new item, then reset the state. Example:
onChange(event){
var newArray = this.state.arr.slice();
newArray.push("new value");
this.setState({arr:newArray})
}
Your statement is calling SELECT and WHERE but does not specify which TABLE or record set you would like to SELECT FROM.
SELECT DISTINCT Description, Date as treatmentDate
FROM (TABLE_NAME or SUBQUERY)<br> --This is missing from your query.
WHERE doothey.Patient P, doothey.Account A, doothey.AccountLine AL, doothey.Item.I
AND P.PatientID = A.PatientID
AND A.AccountNo = AL.AccountNo
AND AL.ItemNo = I.ItemNo
AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');
The command is gradle dependencies
, and its output is much improved in Gradle 1.2. (You can already try 1.2-rc-1 today.)
crypt()
as suggested and store salt in some configuration file, Start salt from 1 and if you find duplicate move to next value 2. You can use 2 chars, but that will give you enough combination for salt.
You can generate string from openssl_random_pseudo_bytes(8)
. So this should give random and short string (11 char) when run with crypt()
.
Remove salt from result and there will be only 11 chars that should be enough random for 100+ millions if you change salt on every fail of random.
If you are planning to run the angular project in custom host/IP and Port there is no need of making changes in config file
The following command worked for me
ng serve --host aaa.bbb.ccc.ddd --port xxxx
Where,
aaa.bbb.ccc.ddd --> IP you want to run the project
xxx --> Port you want to run the project
Example
ng serve --host 192.168.322.144 --port 6300
Result for me was
date('Y-m-d H:i:s')
. See the manual for more.
It’s a bit late but here is a wrapper class that simplifies scraping proxies and then making an http POST or GET:
ProxyRequests
https://github.com/rootVIII/proxy_requests
Since none of the answers exactly covered my need (using MSVS Code), I add here my experience with this IDE and CMAKE build tools too.
Step 1: Make sure in your .cpp, (or .hpp if needed) you have included:
#include <functional>
Step 2 For MSVSCode IDE users: Add this line to your c_cpp_properties.json file:
"compilerArgs": ["-pthread"],
Step 2 For CMAKE build tools users: Add this line to your CMakeLists.txt
set(CMAKE_CXX_FLAGS "-pthread")
Note: Adding flag -lpthread (instead of -pthread) results in failed linking.
The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).
Define a Java class that resembles the JSON you will be expecting.
e.g. this JSON:
{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}
could be mapped to this class:
public class Fizzle{
private List<String> foo;
private boolean bar;
private int baz;
// getters and setters omitted
}
Now if you have a Controller method like this:
@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
return new Fozzle(input);
}
and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json
.
For a full working example see this previous answer of mine.
With the help of Vonc's answer above I created the following bash script named check.sh
:
#!/bin/bash
image_and_tag="$1"
image_and_tag_array=(${image_and_tag//:/ })
if [[ "$(docker images ${image_and_tag_array[0]} | grep ${image_and_tag_array[1]} 2> /dev/null)" != "" ]]; then
echo "exists"
else
echo "doesn't exist"
fi
Using it for an existing image and tag will print exists
, for example:
./check.sh rabbitmq:3.4.4
Using it for a non-existing image and tag will print doesn't exist
, for example:
./check.sh rabbitmq:3.4.3
I try to explain it more understandably than the referred PostgreSQL documentation.
Neither TIMESTAMP
variants store a time zone (or an offset), despite what the names suggest. The difference is in the interpretation of the stored data (and in the intended application), not in the storage format itself:
TIMESTAMP WITHOUT TIME ZONE
stores local date-time (aka. wall calendar date and wall clock time). Its time zone is unspecified as far as PostgreSQL can tell (though your application may knows what it is). Hence, PostgreSQL does no time zone related conversion on input or output. If the value was entered into the database as '2011-07-01 06:30:30'
, then no mater in what time zone you display it later, it will still say year 2011, month 07, day 01, 06 hours, 30 minutes, and 30 seconds (in some format). Also, any offset or time zone you specify in the input is ignored by PostgreSQL, so '2011-07-01 06:30:30+00'
and '2011-07-01 06:30:30+05'
are the same as just '2011-07-01 06:30:30'
.
For Java developers: it's analogous to java.time.LocalDateTime
.
TIMESTAMP WITH TIME ZONE
stores a point on the UTC time line. How it looks (how many hours, minutes, etc.) depends on your time zone, but it always refers to the same "physical" instant (like the moment of an actual physical event). The
input is internally converted to UTC, and that's how it's stored. For that, the offset of the input must be known, so when the input contains no explicit offset or time zone (like '2011-07-01 06:30:30'
) it's assumed to be in the current time zone of the PostgreSQL session, otherwise the explicitly specified offset or time zone is used (as in '2011-07-01 06:30:30+05'
). The output is displayed converted to the current time zone of the PostgreSQL session.
For Java developers: It's analogous to java.time.Instant
(with lower resolution though), but with JDBC and JPA 2.2 you are supposed to map it to java.time.OffsetDateTime
(or to java.util.Date
or java.sql.Timestamp
of course).
Some say that both TIMESTAMP
variations store UTC date-time. Kind of, but it's confusing to put it that way in my opinion. TIMESTAMP WITHOUT TIME ZONE
is stored like a TIMESTAMP WITH TIME ZONE
, which rendered with UTC time zone happens to give the same year, month, day, hours, minutes, seconds, and microseconds as they are in the local date-time. But it's not meant to represent the point on the time line that the UTC interpretation says, it's just the way the local date-time fields are encoded. (It's some cluster of dots on the time line, as the real time zone is not UTC; we don't know what it is.)
$('#userZipFiles option').prop('selected', function() {
return this.defaultSelected;
});
If you've accidentally or not mixed integers with text data you should at first execute below update command (if not above alter table will fail):
UPDATE the_table SET col_name = replace(col_name, 'some_string', '');
The PDF engine used in Google Chrome, called PDFium, is open source under the "BSD 3-clause" license. I believe this allows redistribution when used in a commercial product.
There is a .NET wrapper for it called PdfiumViewer (NuGet) which works well to the extent I have tried it. It is under the Apache license which also allows redistribution.
(Note that this is NOT the same 'wrapper' as https://pdfium.patagames.com/ which requires a commercial license*)
(There is one other PDFium .NET wrapper, PDFiumSharp, but I have not evaluated it.)
In my opinion, so far, this may be the best choice of open-source (free as in beer) PDF libraries to do the job which do not put restrictions on the closed-source / commercial nature of the software utilizing them. I don't think anything else in the answers here satisfy that criteria, to the best of my knowledge.
Try this:
SELECT RAND(convert(varbinary, newid()))*(b-a)+a magic_number
Where a
is the lower number and b
is the upper number
Here you will get list of diffrent ways of applying the click event. You can select accordingly as suaitable or if your click is not working just try an alternative out of these.
$('.clickHere').click(function(){
// this is flat click. this event will be attatched
//to element if element is available in
//dom at the time when JS loaded.
// do your stuff
});
$('.clickHere').on('click', function(){
// same as first one
// do your stuff
})
$(document).on('click', '.clickHere', function(){
// this is diffrent type
// of click. The click will be registered on document when JS
// loaded and will delegate to the '.clickHere ' element. This is
// called event delegation
// do your stuff
});
$('body').on('click', '.clickHere', function(){
// This is same as 3rd
// point. Here we used body instead of document/
// do your stuff
});
$('.clickHere').off().on('click', function(){ //
// deregister event listener if any and register the event again. This
// prevents the duplicate event resistration on same element.
// do your stuff
})
This is the Method to get contact list Name and Number
private void getAllContacts() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//At here You can add phoneNUmber and Name to you listView ,ModelClass,Recyclerview
phoneCursor.close();
}
}
}
}
}
}
If the list to compare against is large, (ie the manilaListRange range in the example above), it is a smart move to use the match function. It avoids the use of a loop which could slow down the procedure. If you can ensure that the manilaListRange is all upper or lower case then this seems to be the best option to me. It is quick to apply 'UCase' or 'LCase' as you do your match.
If you did not have control over the ManilaListRange then you might have to resort to looping through this range in which case there are many ways to compare 'search', 'Instr', 'replace' etc.
Think about what you're asking!
The max of {1, 2, 3, -1, -2, -3} is obviously 3. The max of {2} is obviously 2. But what is the max of the empty set { }? Obviously that is a meaningless question. The max of the empty set is simply not defined. Attempting to get an answer is a mathematical error. The max of any set must itself be an element in that set. The empty set has no elements, so claiming that some particular number is the max of that set without being in that set is a mathematical contradiction.
Just as it is correct behavior for the computer to throw an exception when the programmer asks it to divide by zero, so it is correct behavior for the computer to throw an exception when the programmer asks it to take the max of the empty set. Division by zero, taking the max of the empty set, wiggering the spacklerorke, and riding the flying unicorn to Neverland are all meaningless, impossible, undefined.
Now, what is it that you actually want to do?
My mistake was that I was keeping the Javascript file ( tag) above the html declaration.
It worked by placing the js script tag at the bottom of the body inside the body. (I did not the script on load of the page.)
This code should handle your needs up to 64 bits.
char* pBinFill(long int x,char *so, char fillChar); // version with fill
char* pBin(long int x, char *so); // version without fill
#define width 64
char* pBin(long int x,char *so)
{
char s[width+1];
int i=width;
s[i--]=0x00; // terminate string
do
{ // fill in array from right to left
s[i--]=(x & 1) ? '1':'0'; // determine bit
x>>=1; // shift right 1 bit
} while( x > 0);
i++; // point to last valid character
sprintf(so,"%s",s+i); // stick it in the temp string string
return so;
}
char* pBinFill(long int x,char *so, char fillChar)
{ // fill in array from right to left
char s[width+1];
int i=width;
s[i--]=0x00; // terminate string
do
{
s[i--]=(x & 1) ? '1':'0';
x>>=1; // shift right 1 bit
} while( x > 0);
while(i>=0) s[i--]=fillChar; // fill with fillChar
sprintf(so,"%s",s);
return so;
}
void test()
{
char so[width+1]; // working buffer for pBin
long int val=1;
do
{
printf("%ld =\t\t%#lx =\t\t0b%s\n",val,val,pBinFill(val,so,0));
val*=11; // generate test data
} while (val < 100000000);
}
Output:
00000001 = 0x000001 = 0b00000000000000000000000000000001
00000011 = 0x00000b = 0b00000000000000000000000000001011
00000121 = 0x000079 = 0b00000000000000000000000001111001
00001331 = 0x000533 = 0b00000000000000000000010100110011
00014641 = 0x003931 = 0b00000000000000000011100100110001
00161051 = 0x02751b = 0b00000000000000100111010100011011
01771561 = 0x1b0829 = 0b00000000000110110000100000101001
19487171 = 0x12959c3 = 0b00000001001010010101100111000011
When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:
%PATH%
environment variable for the executable file.If the file isn't found in either of those options you will need to either:
%PATH%
by apending it, (recommended only with extreme caution).You can see which locations are specified in %PATH%
from the Command prompt, Echo %Path%
.
Because of your reported error we can assume that Mobile.exe
is not in the current directory or in a location specified within the %Path%
variable, so you need to use 1.
, 2.
or 3.
.
Examples for 1.
C:\directory_path_without_spaces\My-App\Mobile.exe
or:
"C:\directory path with spaces\My-App\Mobile.exe"
Alternatively you may try:
Start C:\directory_path_without_spaces\My-App\Mobile.exe
or
Start "" "C:\directory path with spaces\My-App\Mobile.exe"
Where ""
is an empty title, (you can optionally add a string between those doublequotes).
Examples for 2.
CD /D C:\directory_path_without_spaces\My-App
Mobile.exe
or
CD /D "C:\directory path with spaces\My-App"
Mobile.exe
You could also use the /D
option with Start
to change the working directory for the executable to be run by the start command
Start /D C:\directory_path_without_spaces\My-App Mobile.exe
or
Start "" /D "C:\directory path with spaces\My-App" Mobile.exe
List<string> myCollection = new List<string>()
{
"Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};
myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}
output: Abdi 3 Alex 2 Bob 4
I have found that using ._getexif
doesn't work in higher python versions, moreover, it is a protected class and one should avoid using it if possible.
After digging around the debugger this is what I found to be the best way to get the EXIF data for an image:
from PIL import Image
def get_exif(path):
return Image.open(path).info['parsed_exif']
This returns a dictionary of all the EXIF data of an image.
Note: For Python3.x use Pillow instead of PIL
with bash:
shopt -s globstar nullglob
rename _dbg.txt .txt **/*dbg*
You need to use a pointer or a reference as the proper type is not known at this time the compiler can not instantiate it.
Instead try:
void action(const typename Subclass::mytype &var) {
(static_cast<Subclass*>(this))->do_action();
}
You can just as easily access each element in the list using e.g. path[[1]]
. You can't put a set of matrices into an atomic vector and access each element. A matrix is an atomic vector with dimension attributes. I would use the list structure returned by split
, it's what it was designed for. Each list element can hold data of different types and sizes so it's very versatile and you can use *apply
functions to further operate on each element in the list. Example below.
# For reproducibile data
set.seed(1)
# Make some data
userid <- rep(1:2,times=4)
data1 <- replicate(8 , paste( sample(letters , 3 ) , collapse = "" ) )
data2 <- sample(10,8)
df <- data.frame( userid , data1 , data2 )
# Split on userid
out <- split( df , f = df$userid )
#$`1`
# userid data1 data2
#1 1 gjn 3
#3 1 yqp 1
#5 1 rjs 6
#7 1 jtw 5
#$`2`
# userid data1 data2
#2 2 xfv 4
#4 2 bfe 10
#6 2 mrx 2
#8 2 fqd 9
Access each element using the [[
operator like this:
out[[1]]
# userid data1 data2
#1 1 gjn 3
#3 1 yqp 1
#5 1 rjs 6
#7 1 jtw 5
Or use an *apply
function to do further operations on each list element. For instance, to take the mean of the data2
column you could use sapply like this:
sapply( out , function(x) mean( x$data2 ) )
# 1 2
#3.75 6.25
This happened to me yesterday and in my case was because I was following a PDF manual to develop some module to communicate with an API and while copying the link directly from the manual, for some odd reason, the hyphen
from the copied link was in a different encoding and hence the curl_exec()
was always returning false
because it was unable to communicate with the server.
It took me a couple hours to finally understand the diference in the characters bellow:
https://www.e-example.com/api
https://www.e-example.com/api
Every time I tried to access the link directly from a browser it converted to something likehttps://www.xn--eexample-0m3d.com/api
.
It may seem to you that they are equal but if you check the encoding of the hyphens
here you'll see that the first hyphen
is a unicode characters U+2010 and the other is a U+002D.
Hope this helps someone.
Added a few optional parameters for creating "future safe" sequences.
CREATE SEQUENCE <NAME>
START WITH 1
INCREMENT BY 1
NO MAXVALUE
NO CYCLE
CACHE 10;
Maybe you have a hardware problem.
I had the same problem on my old system (AMD 1800 MHz CPU ,1GB RAM ,Windows 7 Ultimate) ,until I changed the 2x 512 MB RAM to 2x 1GB RAM. Haven't had any problems since. Also other (minor) problems disappeared. Guess those two 512 MB modules didn't like each other that much ,because 2x 512 MB + 1GB or 1x 512 MB + 2x 1GB didn't work properly either.
Here is the code to mock this functionality using PowerMockito API.
Second mockedSecond = PowerMockito.mock(Second.class);
PowerMockito.whenNew(Second.class).withNoArguments().thenReturn(mockedSecond);
You need to use Powermockito runner and need to add required test classes (comma separated ) which are required to be mocked by powermock API .
@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class,Second.class})
class TestClassName{
// your testing code
}
Set this in the constructor:
public class SearchModel
{
public bool IsMale { get; set; }
public bool IsFemale { get; set; }
public SearchModel()
{
IsMale = true;
IsFemale = true;
}
}
Then pass it to the view in your GET action:
[HttpGet]
public ActionResult Search()
{
return new View(new SearchModel());
}
Here is my two cents:
final String CENT_1 = new Random().nextInt(2) == 0 ? "HEADS" : "TAILS";
final static String CENT_2 = new Random().nextInt(2) == 0 ? "HEADS" : "TAILS";
Example:
package test;
public class Test {
final long OBJECT_ID = new Random().nextLong();
final static long CLASSS_ID = new Random().nextLong();
public static void main(String[] args) {
Test[] test = new Test[5];
for (int i = 0; i < test.length; i++){
test[i] = new Test();
System.out.println("Class id: "+test[i].CLASSS_ID);//<- Always the same value
System.out.println("Object id: "+test[i].OBJECT_ID);//<- Always different
}
}
}
The key is that variables and functions can return different values.Therefore final variables can be assigned with different values.
Open the Terminal
->
copy
below command
sudo gem install cocoapods
It will install the latest stable version of cocoapods
.
after that, you need to update pod using below command
pod setup
You can check pod version using below command
pod --version
I use this. I think this is the simpliest way to do it:
textBoxName.Clear();
I just had this problem myself, even though i couldn't find the reason for it in my case, when changing from POST
to GET
, the problem 500 error disappeared!
type:'POST'