I got this error on my ASP.Net 4.5 app on Windows Server 2012 R2.
Go to start menu -> "Turn windows features on or off". A wizard popped up for me.
Click Next to Server Roles
I had to check these to get this to work, located under Web Server IIS->Web Server-> Application Development (these are based on Jeremy Cook's answer above):
Then click next to Features and make sure the following is checked:
Then click next and Install. At this point, the error went away for me. Good luck!
Same issue happened with me when i mistakenly added some text in front of the top directive of the master page all the controls across all the page included in my project started showing, does not exist in the current context. After spending much time across the forum and self analysis, i found the mistakenly added text and removed but it does not solved the problem. Then i had to click on each error to open the associated page so that VS can load the page and recognize it, once the code was loaded in VS, error from those particular page started disappearing because VS recognized it. clicking on each error, loading each page in VS editor did the trick for me and you have to do it only once because later it will be automatically recognized by VS. I would say it is a Visual Studio Glitch.
First, set customErrors = "Off" in the web.config and redeploy to get a more detailed error message that will help us diagnose the problem. You could also RDP into the instance and browse to the site from IIS locally to view the errors.
<system.web>
<customErrors mode="Off" />
First guess though - you have some references (most likely Azure SDK references) that are not set to Copy Local = true. So, all your dependencies are not getting deployed.
Get to the detailed error first and update your question.
UPDATE: A second option now available in VS2013 is Remote Debugging a Cloud Service or Virtual Machine.
This happens when the files inside the Debug and Release folder are not created properly(Either they are having wrong reference or having overwritten many times). I have faced the same problem in which, i everything works fine when we build the solution, but when i publish the website it gives me same error. I have solved this in following manner:
Cause
ASP.NET by default validates all input controls for potentially unsafe contents that can lead to cross-site scripting (XSS) and SQL injections. Thus it disallows such content by throwing the above exception. By default it is recommended to allow this check to happen on each postback.
Solution
On many occasions you need to submit HTML content to your page through Rich TextBoxes or Rich Text Editors. In that case you can avoid this exception by setting the ValidateRequest tag in the @Page
directive to false.
<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest = "false" %>
This will disable the validation of requests for the page you have set the ValidateRequest flag to false. If you want to disable this, check throughout your web application; you’ll need to set it to false in your web.config <system.web> section
<pages validateRequest ="false" />
For .NET 4.0 or higher frameworks you will need to also add the following line in the <system.web> section to make the above work.
<httpRuntime requestValidationMode = "2.0" />
That’s it. I hope this helps you in getting rid of the above issue.
Reference by: ASP.Net Error: A potentially dangerous Request.Form value was detected from the client
A tangential note on the approaches here that load use setTimeout
or setInterval
. In those cases it's possible that when your check runs again, the DOM will already have loaded, and the browser's DOMContentLoaded
event will have been fired, so you can't detect that event reliably using these approaches. What I found is that jQuery's ready
still works, though, so you can embed your usual
jQuery(document).ready(function ($) { ... }
inside your setTimeout
or setInterval
and everything should work as normal.
All you need is a <clear />
tag. Here's an example:
<configuration>
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="default.aspx" />
</files>
</defaultDocument>
</system.webServer>
</configuration>
In addition to having more registers, 64-bit has SSE2 by default. This means that you can indeed perform some calculations in parallel. The SSE extensions had other goodies too. But I guess the main benefit is not having to check for the presence of the extensions. If it's x64, it has SSE2 available. ...If my memory serves me correctly.
When issue happening on Mac VS 2017 (Which I faced).
Run your application code now.
For me, the main difference is that a script is interpreted, while a program is executed (i.e. the source is first compiled, and the result of that compilation is expected).
Wikipedia seems to agree with me on this :
Script :
"Scripts" are distinct from the core code of the application, which is usually written in a different language, and are often created or at least modified by the end-user.
Scripts are often interpreted from source code or bytecode, whereas the applications they control are traditionally compiled to native machine code.
Program :
The program has an executable form that the computer can use directly to execute the instructions.
The same program in its human-readable source code form, from which executable programs are derived (e.g., compiled)
People have mentioned make
but bjam
also supports a similar concept. Using bjam -jx
instructs bjam to build up to x
concurrent commands.
We use the same build scripts on Windows and Linux and using this option halves our build times on both platforms. Nice.
To declare different layouts and bitmaps you'd like to use for the different screens, you must place these alternative resources in separate directories/folders.
This means that if you generate a 200x200
image for xhdpi
devices, you should generate the same resource in 150x150
for hdpi
, 100x100
for mdpi
, and 75x75
for ldpi
devices.
Then, place the files in the appropriate drawable resource directory:
MyProject/
res/
drawable-xhdpi/
awesomeimage.png
drawable-hdpi/
awesomeimage.png
drawable-mdpi/
awesomeimage.png
drawable-ldpi/
awesomeimage.png
Any time you reference @drawable/awesomeimage
, the system selects the appropriate bitmap based on the screen's density.
My hint:
FIND IF EXISTS in .env:
APP_URL=http://yourhost.dev
REPLACE TO (OR ADD)
APP_DOMAIN=yourhost.dev
FIND in config/app.php:
'url' => env('APP_URL'),
REPLACE TO
'domain' => env('APP_DOMAIN'),
'url' => 'http://' . env('APP_DOMAIN'),
USE:
Config::get('app.domain'); // yourhost.dev
Config::get('app.url') // http://yourhost.dev
Do your magic!
This is the simplest one.
#divid {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
There does not seem to be a way to set up a GitLab account within SourceTree, but if you just clone a remote repo it will use your SSH key correctly.
Edit: After SourceTree 3.0 it is possible to add various non-Atlassian git accounts, including GitLab.
gcc -I/path -L/path
-I /path
path to include, gcc will find .h files in this path
-L /path
contains library files, .a
, .s
o
I think the only way will be to stop the process which has opened the port.
From the output of java -X
:
-Xloggc:<file> log GC status to a file with time stamps
Documented here:
-Xloggc:filename
Sets the file to which verbose GC events information should be redirected for logging. The information written to this file is similar to the output of
-verbose:gc
with the time elapsed since the first GC event preceding each logged event. The-Xloggc
option overrides-verbose:gc
if both are given with the samejava
command.Example:
-Xloggc:garbage-collection.log
So the output looks something like this:
0.590: [GC 896K->278K(5056K), 0.0096650 secs] 0.906: [GC 1174K->774K(5056K), 0.0106856 secs] 1.320: [GC 1670K->1009K(5056K), 0.0101132 secs] 1.459: [GC 1902K->1055K(5056K), 0.0030196 secs] 1.600: [GC 1951K->1161K(5056K), 0.0032375 secs] 1.686: [GC 1805K->1238K(5056K), 0.0034732 secs] 1.690: [Full GC 1238K->1238K(5056K), 0.0631661 secs] 1.874: [GC 62133K->61257K(65060K), 0.0014464 secs]
Try installing the 32 bit version of Java 6. This works for version Install4J 4.0.5. Should fire right up, or allow you to re-run the installer.
Any newer version or the 64-bit version of 6 will fail, complaining that the java.exe is damaged.
git push --set-upstream origin <branch_name>_test
--set-upstream
sets the association between your local branch and the remote. You only have to do it the first time. On subsequent pushes you can just do:
git push
If you don't have origin
set yet, use:
git remote add origin <repository_url>
then retry the above command.
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
When you're going to work with such time series in Python, pandas
is indispensable. And here's the good news: it comes with a historical data downloader for Yahoo: pandas.io.data.DataReader
.
from pandas.io.data import DataReader
from datetime import datetime
ibm = DataReader('IBM', 'yahoo', datetime(2000, 1, 1), datetime(2012, 1, 1))
print(ibm['Adj Close'])
Here's an example from the pandas
documentation.
Update for pandas >= 0.19:
The pandas.io.data
module has been removed from pandas>=0.19
onwards. Instead, you should use the separate pandas-datareader
package. Install with:
pip install pandas-datareader
And then you can do this in Python:
import pandas_datareader as pdr
from datetime import datetime
ibm = pdr.get_data_yahoo(symbols='IBM', start=datetime(2000, 1, 1), end=datetime(2012, 1, 1))
print(ibm['Adj Close'])
Also, I add to do the following steps so that the git repo would be correctly linked with the IDE:
$ git reset <commit #>
$ git checkout <file/path>
I hope this was helpful!!
I think this is actually what you're looking for:
.my_container ul
{
list-style: initial;
margin: initial;
padding: 0 0 0 40px;
}
.my_container li
{
display: list-item;
}
too late to answer but here is my approach since no one mentioned this here:
why note a client side solution ?
a javascript implementation to store the mac in a cookie (you can encrypt it before that)
then each request must include that cookie name, else it will be rejected.
to make this even more fun you can make a server side verification
from the mac address you get the manifacturer (there are plenty of free APIs for this)
then compare it with the user_agent value to see if there was some sort of manipulation:
a mac address of HP + a user agent of Safari = reject request.
The reverse() is used to adhere the django DRY principle i.e if you change the url in future then you can reference that url using reverse(urlname).
I must have arrived at the party late, none of the solutions here seemed helpful to me - too messy and felt like too much of a workaround.
What I ended up doing is using Angular 4.0.0-beta.6
's ngComponentOutlet.
This gave me the shortest, simplest solution all written in the dynamic component's file.
import {
Component, OnInit, Input, NgModule, NgModuleFactory, Compiler
} from '@angular/core';
@Component({
selector: 'my-component',
template: `<ng-container *ngComponentOutlet="dynamicComponent;
ngModuleFactory: dynamicModule;"></ng-container>`,
styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
dynamicComponent;
dynamicModule: NgModuleFactory<any>;
@Input()
text: string;
constructor(private compiler: Compiler) {
}
ngOnInit() {
this.dynamicComponent = this.createNewComponent(this.text);
this.dynamicModule = this.compiler.compileModuleSync(this.createComponentModule(this.dynamicComponent));
}
protected createComponentModule (componentType: any) {
@NgModule({
imports: [],
declarations: [
componentType
],
entryComponents: [componentType]
})
class RuntimeComponentModule
{
}
// a module for just this Type
return RuntimeComponentModule;
}
protected createNewComponent (text:string) {
let template = `dynamically created template with text: ${text}`;
@Component({
selector: 'dynamic-component',
template: template
})
class DynamicComponent implements OnInit{
text: any;
ngOnInit() {
this.text = text;
}
}
return DynamicComponent;
}
}
my-component
- the component in which a dynamic component is renderingDynamicComponent
- the component to be dynamically built and it is rendering inside my-componentDon't forget to upgrade all the angular libraries to ^Angular 4.0.0
Hope this helps, good luck!
UPDATE
Also works for angular 5.
As I know the diference u can find the slice(or the other funcitons of Array) like code1.and code2 show u Array and his instances:
code1:
[].slice; // find slice here
var arr = new Array();
arr.slice // find slice here
Array.prototype.slice // find slice here
code2:
[].__proto__ == Array.prototype; // true
var arr = new Array();
arr.__proto__ == Array.prototype; // true
conclusion:
as u can see []
and new Array()
create a new instance of Array.And they all get the prototype functions from Array.prototype
They are just different instance of Array.so this explain why
[] != []
:)
I was a great fan of submit()
but not anymore.
In the web page that I test, I enter username and password and click Login. When I invoked usernametextbox.submit()
, password textbox is cleared (becomes empty) and login keeps failing.
After breaking my head for sometime, when I replaced usernametextbox.submit()
with loginbutton.click()
, it worked like a magic.
Or, just set the output field separator (OFS) to double newlines, and then make sure you get a string when you send it to file:
$OFS = "`r`n`r`n"
"$( gci -path hklm:\software\microsoft\windows\currentversion\uninstall |
ForEach-Object -Process { write-output $_.GetValue('DisplayName') } )" |
out-file addrem.txt
Beware to use the ` and not the '. On my keyboard (US-English Qwerty layout) it's located left of the 1.
(Moved here from the comments - Thanks Koen Zomers)
If I use exit()
in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing.
See here
But sys.exit()
is better in this case. It closes the program and doesn't create any dialogue box.
In order to navigate to a different drive/directory you can do it in convenient way (instead of typing cd /e/Study/Codes), just type in cd[Space], and drag-and-drop your directory Codes with your mouse to git bash, hit [Enter].
In the activity:
mAdapter.updateAt(pos, text, completed);
mAdapter.removeAt(pos);
In the your adapter:
void removeAt(int position) {
list.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, list.size());
}
void updateAt(int position, String text, Boolean completed) {
TodoEntity todoEntity = list.get(position);
todoEntity.setText(text);
todoEntity.setCompleted(completed);
notifyItemChanged(position);
}
If you are using Ubuntu, there is need to install requests
run this command:
pip install requests
if you face permission denied error, use sudo before command:
sudo pip install requests
I'm currently working on such a statement and figured out another fact to notice: INSERT OR REPLACE will replace any values not supplied in the statement. For instance if your table contains a column "lastname" which you didn't supply a value for, INSERT OR REPLACE will nullify the "lastname" if possible (constraints allow it) or fail.
Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.
How to check that Intel VT-x is supported in CPU:
Open Terminal application from Application/Utilities
Copy/paste command bellow
sysctl -a | grep machdep.cpu.features
Mac:~ user$ sysctl -a | grep machdep.cpu.features
kern.exec: unknown type returned
machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM
If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.
Refer to this link on Apple.com to enable hardware support for virtualization:
There are few modes to open file (read, write etc..)
If you want to read from file you should type file = open("File.txt","r")
, if write than file = open("File.txt","w")
. You need to give the right permission regarding your usage.
more modes:
Find an explanation below. You can check this link for more details - http://www.dotnetbull.com/2013/10/public-protected-private-internal-access-modifier-in-c.html
Private: - Private members are only accessible within the own type (Own class).
Internal: - Internal member are accessible only within the assembly by inheritance (its derived type) or by instance of class.
Reference :
How are you generating your data?
See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.
In [31]: data
Out[31]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
Freq: <1 DateOffset>
Columns: 360 entries, -89.75 to 89.75
dtypes: object(360)
look ?
Did you initialize an empty DataFrame first and then filled it? If so that's probably why it changed with the new version as before 0.9 empty DataFrames were initialized to float type but now they are of object type. If so you can change the initialization to DataFrame(dtype=float)
.
You can also call frame.astype(float)
You could also check using the age()
function
select * from mytable where age( mydate, now() ) > '1 year';
age()
wil return an interval.
For example age( '2015-09-22', now() )
will return -1 years -7 days -10:56:18.274131
This has changed in the newer versions of Ember.
For arrays:
{{#each array}}
{{_view.contentIndex}}: {{this}}
{{/each}}
It looks like the #each block no longer works on objects. My suggestion is to roll your own helper function for it.
Thanks for this tip.
Use the map
-function instead. It transforms the value inside the optional.
Like this:
private String getStringIfObjectIsPresent(Optional<Object> object) {
return object.map(() -> {
String result = "result";
//some logic with result and return it
return result;
}).orElseThrow(MyCustomException::new);
}
I use a method like that to check duplicated entrys in a string:
public static IEnumerable<string> CheckForDuplicated(IEnumerable<string> listString)
{
List<string> duplicateKeys = new List<string>();
List<string> notDuplicateKeys = new List<string>();
foreach (var text in listString)
{
if (notDuplicateKeys.Contains(text))
{
duplicateKeys.Add(text);
}
else
{
notDuplicateKeys.Add(text);
}
}
return duplicateKeys;
}
Maybe it's not the most shorted or elegant way, but I think that is very readable.
You are returning Observable<Product>
and expecting it to be Product[]
inside subscribe
callback.
The Type returned from http.get()
and getProducts()
should be Observable<Product[]>
public getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`api/products/v1/`);
}
Try this regex:
\d+\.?\d*
\d+ digits before optional decimal
.? optional decimal(optional due to the ? quantifier)
\d* optional digits after decimal
In order for that to work $time
has to be a timestamp. You cannot pass in "10:00" or something like $time = date('H:i', '10:00');
which is what you seem to do, because then I get 0:30 and 1:30 as results too.
Try
$time = strtotime('10:00');
As an alternative, consider using DateTime (the below requires PHP 5.3 though):
$dt = DateTime::createFromFormat('H:i', '10:00'); // create today 10 o'clock
$dt->sub(new DateInterval('PT30M')); // substract 30 minutes
echo $dt->format('H:i'); // echo modified time
$dt->add(new DateInterval('PT1H')); // add 1 hour
echo $dt->format('H:i'); // echo modified time
or procedural if you don't like OOP
$dateTime = date_create_from_format('H:i', '10:00');
date_sub($dateTime, date_interval_create_from_date_string('30 minutes'));
echo date_format($dateTime, 'H:i');
date_add($dateTime, date_interval_create_from_date_string('1 hour'));
echo date_format($dateTime, 'H:i');
As mentioned in the other answers, here and here, the cache can be cleared by using:
$templateCache.removeAll();
However as suggested by gatoatigrado in the comment, this only appears to work if the html template was served without any cache headers.
So this works for me:
In angular:
app.run(['$templateCache', function ( $templateCache ) {
$templateCache.removeAll(); }]);
You may be adding cache headers in a variety of ways but here are a couple of solutions that work for me.
If using IIS
, add this to your web.config:
<location path="scripts/app/views">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
If using Nginx, you can add this to your config:
location ^~ /scripts/app/views/ {
expires -1;
}
Edit
I just realised that the question mentioned dev
machine but hopefully this may still help somebody...
Recently I was also having this issue, then I contacted Google Support and they gave me this link to provide required info, I posted and within 24 hours my problem was fixed.
Link: https://support.google.com/payments/contact/alt_account_verification
headers = { 'User-Agent' : 'Mozilla/5.0' }
req = urllib2.Request('www.example.com', None, headers)
html = urllib2.urlopen(req).read()
Or, a bit shorter:
req = urllib2.Request('www.example.com', headers={ 'User-Agent': 'Mozilla/5.0' })
html = urllib2.urlopen(req).read()
Problem: My VS 2015 was throwing up error after I installed SSDT. Whenever I clicked on Tools >> Extensions and Update it was throwing "Object reference not set to an instance of an object" error. When I tried to open a solution it threw some provider not set correctly.
Solution: After many hours of research trying out all the solutions previously mentioned by others didn't solve my problem. Every time the error popup was pointing to check the ActivityLog.xml. But I was ignoring it. After hours of frustration I decided to read the error carefully and looked into ActivitLog.xml and found that it was looking for "Could not load file or assembly 'System.Collections.Immutable, Version=1.1.37.0". So I just started searching for this assembly and stumbled upon this link https://sergeytihon.com/2015/12/01/how-to-restore-viual-studio-2015-after-update-1-dependency-dance/ and followed the steps there, which fixed my issue.
Went into %LOCALAPPDATA%/Local\Microsoft\VisualStudio\14.0\devenv.exe.config and searched for "System.Collections.Immutable" and change newVersion from 1.1.36.0 to 1.1.37.0
Final config should look like this
<dependentAssembly>
<assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="1.0.27.0-1.1.65535.65535" newVersion="1.1.37.0"/>
</dependentAssembly>
The unwanted side effects of simple folder delete or installing over existing installation have been removed by a script written by Kyle Fuller - deintegrate and here is the proper workflow:
Install clean:
$ sudo gem install cocoapods-clean
Run deintegrate in the folder of the project:
$ pod deintegrate
Clean (this tool is no longer available):
$ pod clean
Modify your podfile (delete the lines with the pods you don't want to use anymore) and run:
$ pod install
Done.
A priority queue is an abstract data type that captures the idea of a container whose elements have "priorities" attached to them. An element of highest priority always appears at the front of the queue. If that element is removed, the next highest priority element advances to the front.
The C++ standard library defines a class template priority_queue, with the following operations:
push: Insert an element into the prioity queue.
top: Return (without removing it) a highest priority element from the priority queue.
pop: Remove a highest priority element from the priority queue.
size: Return the number of elements in the priority queue.
empty: Return true or false according to whether the priority queue is empty or not.
The following code snippet shows how to construct two priority queues, one that can contain integers and another one that can contain character strings:
#include <queue>
priority_queue<int> q1;
priority_queue<string> q2;
The following is an example of priority queue usage:
#include <string>
#include <queue>
#include <iostream>
using namespace std; // This is to make available the names of things defined in the standard library.
int main()
{
piority_queue<string> pq; // Creates a priority queue pq to store strings, and initializes the queue to be empty.
pq.push("the quick");
pq.push("fox");
pq.push("jumped over");
pq.push("the lazy dog");
// The strings are ordered inside the priority queue in lexicographic (dictionary) order:
// "fox", "jumped over", "the lazy dog", "the quick"
// The lowest priority string is "fox", and the highest priority string is "the quick"
while (!pq.empty()) {
cout << pq.top() << endl; // Print highest priority string
pq.pop(); // Remmove highest priority string
}
return 0;
}
The output of this program is:
the quick
the lazy dog
jumped over
fox
Since a queue follows a priority discipline, the strings are printed from highest to lowest priority.
Sometimes one needs to create a priority queue to contain user defined objects. In this case, the priority queue needs to know the comparison criterion used to determine which objects have the highest priority. This is done by means of a function object belonging to a class that overloads the operator (). The overloaded () acts as < for the purpose of determining priorities. For example, suppose we want to create a priority queue to store Time objects. A Time object has three fields: hours, minutes, seconds:
struct Time {
int h;
int m;
int s;
};
class CompareTime {
public:
bool operator()(Time& t1, Time& t2) // Returns true if t1 is earlier than t2
{
if (t1.h < t2.h) return true;
if (t1.h == t2.h && t1.m < t2.m) return true;
if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
return false;
}
}
A priority queue to store times according the the above comparison criterion would be defined as follows:
priority_queue<Time, vector<Time>, CompareTime> pq;
Here is a complete program:
#include <iostream>
#include <queue>
#include <iomanip>
using namespace std;
struct Time {
int h; // >= 0
int m; // 0-59
int s; // 0-59
};
class CompareTime {
public:
bool operator()(Time& t1, Time& t2)
{
if (t1.h < t2.h) return true;
if (t1.h == t2.h && t1.m < t2.m) return true;
if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
return false;
}
};
int main()
{
priority_queue<Time, vector<Time>, CompareTime> pq;
// Array of 4 time objects:
Time t[4] = { {3, 2, 40}, {3, 2, 26}, {5, 16, 13}, {5, 14, 20}};
for (int i = 0; i < 4; ++i)
pq.push(t[i]);
while (! pq.empty()) {
Time t2 = pq.top();
cout << setw(3) << t2.h << " " << setw(3) << t2.m << " " <<
setw(3) << t2.s << endl;
pq.pop();
}
return 0;
}
The program prints the times from latest to earliest:
5 16 13
5 14 20
3 2 40
3 2 26
If we wanted earliest times to have the highest priority, we would redefine CompareTime like this:
class CompareTime {
public:
bool operator()(Time& t1, Time& t2) // t2 has highest prio than t1 if t2 is earlier than t1
{
if (t2.h < t1.h) return true;
if (t2.h == t1.h && t2.m < t1.m) return true;
if (t2.h == t1.h && t2.m == t1.m && t2.s < t1.s) return true;
return false;
}
};
As of Python 3.7, datetime.datetime.fromisoformat()
can handle your format:
>>> import datetime
>>> datetime.datetime.fromisoformat('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
In older Python versions you can't, not without a whole lot of painstaking manual timezone defining.
Python does not include a timezone database, because it would be outdated too quickly. Instead, Python relies on external libraries, which can have a far faster release cycle, to provide properly configured timezones for you.
As a side-effect, this means that timezone parsing also needs to be an external library. If dateutil
is too heavy-weight for you, use iso8601
instead, it'll parse your specific format just fine:
>>> import iso8601
>>> iso8601.parse_date('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=<FixedOffset '-04:00'>)
iso8601
is a whopping 4KB small. Compare that tot python-dateutil
's 148KB.
As of Python 3.2 Python can handle simple offset-based timezones, and %z
will parse -hhmm
and +hhmm
timezone offsets in a timestamp. That means that for a ISO 8601 timestamp you'd have to remove the :
in the timezone:
>>> from datetime import datetime
>>> iso_ts = '2012-11-01T04:16:13-04:00'
>>> datetime.strptime(''.join(iso_ts.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))
The lack of proper ISO 8601 parsing is being tracked in Python issue 15873.
Another way is to create a patch with the differences and apply it in the master branch For instance. Let's say the last commit before you started working on app.js is 00000aaaaa and the commit containg the version you want is 00000bbbbb
The you run this on the experiment branch:
git diff 00000aaaaa 00000bbbbb app.js > ~/app_changes.git
This will create a file with all the differences between those two commits for app.js that you can apply wherever you want. You can keep that file anywhere outside the project
Then, in master you just run:
git apply ~/app_changes.git
now you are gonna see the changes in the projects as if you had made them manually.
In the box is working on being able to convert android projects to iOS
I had similiar issue but only with Chrome, Firefox was working. I noticed that Chrome was adding an Origin parameter in the header request.
So in my nginx.conf I added the parameter to avoid it under location/ block
proxy_set_header Origin "";
Additionally to what Tomasz W wrote, by starting your application you could use settings:
-Dorg.apache.logging.log4j.simplelog.StatusLogger.level=TRACE
to get most of configuration problems.
For details see Log4j2 FAQ: How do I debug my configuration?
If you use Pycharm, renaming an app is very easy with refactoring(Shift
+F6
default) for all project files.
But make sure you delete the __pycache__
folders in the project directory & its sub-directories. Also be careful as it also renames comments too which you can exclude in the refactor preview window it will show you.
And you'll have to rename OldNameConfig(AppConfig): in apps.py
of your renamed app in addition.
If you do not want to lose data of your database, you'll have to manually do it with query in database like the aforementioned answer.
If you are using a framework like Ruby on Rails or Spring MVC you may need to use divs with square braces or other chars, that are not allowed you can use document.getElementById
and this solution still works if you have multiple inputs with the same type.
var div = document.getElementById(divID);
$(div).find('input:text, input:password, input:file, select, textarea')
.each(function() {
$(this).val('');
});
$(div).find('input:radio, input:checkbox').each(function() {
$(this).removeAttr('checked');
$(this).removeAttr('selected');
});
This examples shows how to clear the inputs, for you example you'll need to change it.
check this out https://forum.jquery.com/topic/get-index-of-same-class-element-on-click then http://jsfiddle.net/me2loveit2/d6rFM/2/
var index = $('selector').index(this);
console.log(index)
This is a pretty old post, but none of the answers here really answered the question in my opinion, so I hope my post will help people!
I found this solution on another question that works really well for me:
mysql -Nse 'show tables' DB_NAME | while read table; do mysql -e "SET FOREIGN_KEY_CHECKS=0; truncate table \`$table\`" DB_NAME; done
That will actually empty all your tables in the database DB_NAME
, and not only display the TRUNCATE
command line.
Hope this helps!
I asked in #machomebrew and learned that you can switch between versions using brew switch.
$ brew switch libfoo mycopy
to get version mycopy of libfoo.
On Windows install http://chocolatey.org/ then
choco install python
Open a new cmd-window with the updated PATH. Next, do
choco install pip
After that you can
pip install pyside
pip install ipython
...
.rightfloat {_x000D_
color: red;_x000D_
background-color: #BBBBBB;_x000D_
float: right;_x000D_
width: 200px;_x000D_
}_x000D_
_x000D_
.left {_x000D_
font-size: 20pt;_x000D_
}_x000D_
_x000D_
.separator {_x000D_
clear: both;_x000D_
width: 100%;_x000D_
border-top: 1px solid black;_x000D_
}
_x000D_
<div class="separator">_x000D_
<div class="rightfloat">_x000D_
Some really short content._x000D_
</div>_x000D_
<div class="left"> _x000D_
Some really really really really really really_x000D_
really really really really big content_x000D_
</div>_x000D_
</div>_x000D_
<div class="separator">_x000D_
<div class="rightfloat">_x000D_
Some more short content._x000D_
</div>_x000D_
<div class="left"> _x000D_
Some really really really really really really_x000D_
really really really really big content_x000D_
</div>_x000D_
</div>
_x000D_
You can update two tables in one query.
UPDATE Table1, Table2
SET Table1.LastName="DR. XXXXXX", Table2.WAprrs="start,stop"
WHERE Table1.id=Table2.id AND Table1.id="010008";
There is one hacky way that should work on any activity, including the main one.
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
When orientation changes, Android generally will recreate your activity (unless you override it). This method is useful for 180 degree rotations, when Android doesn't recreate your activity.
text2 = text2.textureName.replacingOccurrences(of: "\"", with: "", options: NSString.CompareOptions.literal, range:nil)
Latest documents updated to Swift 3.0.1 have:
- Null Character (
\0
)- Backslash (
\\
)- Horizontal Tab (
\t
)- Line Feed (
\n
)- Carriage Return (
\r
)- Double Quote (
\"
)- Single Quote (
\'
)- Unicode scalar (
\u{n}
), where n is between one and eight hexadecimal digits
If you need more details you can take a look to the official docs here
I know you don't want a jQuery solution but including javascript inside HTML is a big no no.
I mean you can do it but there are lots of reasons why you shouldn't (read up on unobtrusive javascript if you want the details).
So in the interest of other people who may see this question, here is the jQuery solution:
$(document).ready(function() {
$('area').mouseover(function(event) {
$('#preview').attr('src', 'images/' + $(event.srcElement).attr('id'));
});
});
The major benefit is you don't mix javascript code with HTML. Further more, you only need to write this once and it will work for all tags as opposed to having to specify the handler for each separately.
Additional benefit is that every jQuery handler receives an event object that contains a lot of useful data - such as the source of the event, type of the event and so on making it much easier to write the kind of code you are after.
Finally since it's jQuery you don't need to think about cross-browser stuff - a major benefit especially when dealing with events.
@Sheridan thx.. if I try your example with "DisplayedImagePath" on both sides, it works with absolute path as you show.
As for the relative paths, this is how I always connect relative paths, I first include the subdirectory (!) and the image file in my project.. then I use ~ character to denote the bin-path..
public string DisplayedImagePath
{
get { return @"~\..\images\osc.png"; }
}
This was tested, see below my Solution Explorer in VS2015..
Note: if you want a Click event, use the Button tag around the image,
<Button Click="image_Click" Width="128" Height="128" Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Left">_x000D_
<Image x:Name="image" Source="{Binding DisplayedImagePath}" Margin="0,0,0,0" />_x000D_
</Button>
_x000D_
On Angular to update a component including its template, there is a straight forward solution to this, having an @Input
property on your ChildComponent and add to your @Component
decorator changeDetection: ChangeDetectionStrategy.OnPush
as follows:
import { ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'master',
templateUrl: templateUrl,
styleUrls:[styleUrl1],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent{
@Input() data: MyData;
}
This will do all the work of check if Input data have changed and re-render the component
I approached this in a slightly different way and it worked for me;
I needed to remove secure_links
from my table that referenced the conditions
table where there were no longer any condition rows left. A housekeeping script basically. This gave me the error - You cannot specify target table for delete.
So looking here for inspiration I came up with the below query and it works just fine.
This is because it creates a temporary table sl1
that is used as the reference for the DELETE.
DELETE FROM `secure_links` WHERE `secure_links`.`link_id` IN
(
SELECT
`sl1`.`link_id`
FROM
(
SELECT
`sl2`.`link_id`
FROM
`secure_links` AS `sl2`
LEFT JOIN `conditions` ON `conditions`.`job` = `sl2`.`job`
WHERE
`sl2`.`action` = 'something' AND
`conditions`.`ref` IS NULL
) AS `sl1`
)
Works for me.
What is your output when you do java -version
? This will tell you what version the running JVM is.
The Unsupported major.minor version 51.0 error could mean:
Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor
error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)
See: http://www.java.com/en/download/manual.jsp (7 Update 25 )
and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)
for the latest version of the JRE and JDK respectively.
EDIT:
Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.
Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.
You can prevent the crash from happening by safely unwrapping cell.labelTitle
with an if let
statement.
if let label = cell.labelTitle{
label.text = "This is a title"
}
You will still have to do some debugging to see why you are getting a nil value there though.
Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.
I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.
If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.
You have to specify 0
(meaning false) or 1
(meaning true) as the default. Here is an example:
create table mytable (
mybool boolean not null default 0
);
FYI: boolean
is an alias for tinyint(1)
.
Here is the proof:
mysql> create table mytable (
-> mybool boolean not null default 0
-> );
Query OK, 0 rows affected (0.35 sec)
mysql> insert into mytable () values ();
Query OK, 1 row affected (0.00 sec)
mysql> select * from mytable;
+--------+
| mybool |
+--------+
| 0 |
+--------+
1 row in set (0.00 sec)
FYI: My test was done on the following version of MySQL:
mysql> select version();
+----------------+
| version() |
+----------------+
| 5.0.18-max-log |
+----------------+
1 row in set (0.00 sec)
If you installed pip like this:
- sudo apt install python-pip
- sudo apt install python3-pip
Uninstall them like this:
- sudo apt remove python-pip
- sudo apt remove python3-pip
Select your database - Right Click - Select Properties
Select FILE in left side of page
In the OWNER box, select button which has three dots (…) in it
Now select user ‘sa and Click OK
Disclamier: I'm the author of the open source project
This functionality is supported by: https://github.com/chrissound/Human-Friendly-Commands essentially it is this script:
#!/usr/bin/env bash
# Create a repo named by the current directory
# Accepts 1 STRING parameter for the repo description
# Depends on bin: jq
# Depends on env: GITHUB_USER, GITHUB_API_TOKEN
github_createRepo() {
projName="$(basename "$PWD")"
json=$(jq -n \
--arg name "$projName" \
--arg description "$1" \
'{"name":$name, "description":$description}')
curl -u "$GITHUB_USER":"$GITHUB_API_TOKEN" https://api.github.com/user/repos -d "$json"
git init
git remote add origin [email protected]:"$GITHUB_USER"/"$projName".git
git push origin master
};
return
returns a value. It doesn't matter what name you gave to that value. Returning it just "passes it out" so that something else can use it. If you want to use it, you have to grab it from outside:
lst = defineAList()
useTheList(lst)
Returning list
from inside defineAList
doesn't mean "make it so the whole rest of the program can use that variable". It means "pass this variable out and give the rest of the program one chance to grab it and use it". You need to assign that value to something outside the function in order to make use of it. Also, because of this, there is no need to define your list ahead of time with list = []
. Inside defineAList
, you create a new list and return it; this list has no relationship to the one you defined with list = []
at the beginning.
Incidentally, I changed your variable name from list
to lst
. It's not a good idea to use list
as a variable name because that is already the name of a built-in Python type. If you make your own variable called list
, you won't be able to access the builtin one anymore.
Nicholas Westby provided a great solution in a awesome article.
If you want Deserializing JSON to one of many possible classes that implement an interface like that:
public class Person
{
public IProfession Profession { get; set; }
}
public interface IProfession
{
string JobTitle { get; }
}
public class Programming : IProfession
{
public string JobTitle => "Software Developer";
public string FavoriteLanguage { get; set; }
}
public class Writing : IProfession
{
public string JobTitle => "Copywriter";
public string FavoriteWord { get; set; }
}
public class Samples
{
public static Person GetProgrammer()
{
return new Person()
{
Profession = new Programming()
{
FavoriteLanguage = "C#"
}
};
}
}
You can use a custom JSON converter:
public class ProfessionConverter : JsonConverter
{
public override bool CanWrite => false;
public override bool CanRead => true;
public override bool CanConvert(Type objectType)
{
return objectType == typeof(IProfession);
}
public override void WriteJson(JsonWriter writer,
object value, JsonSerializer serializer)
{
throw new InvalidOperationException("Use default serialization.");
}
public override object ReadJson(JsonReader reader,
Type objectType, object existingValue,
JsonSerializer serializer)
{
var jsonObject = JObject.Load(reader);
var profession = default(IProfession);
switch (jsonObject["JobTitle"].Value())
{
case "Software Developer":
profession = new Programming();
break;
case "Copywriter":
profession = new Writing();
break;
}
serializer.Populate(jsonObject.CreateReader(), profession);
return profession;
}
}
And you will need to decorate the "Profession" property with a JsonConverter attribute to let it know to use your custom converter:
public class Person
{
[JsonConverter(typeof(ProfessionConverter))]
public IProfession Profession { get; set; }
}
And then, you can cast your class with an Interface:
Person person = JsonConvert.DeserializeObject<Person>(jsonString);
You need to use filter
package dataframe
import org.apache.spark.sql.SparkSession
/**
* @author [email protected]
*/
//
object DataFrameExample{
//
case class Employee(id: Integer, name: String, address: String, salary: Double, state: String,zip:Integer)
//
def main(args: Array[String]) {
val spark =
SparkSession.builder()
.appName("DataFrame-Basic")
.master("local[4]")
.getOrCreate()
import spark.implicits._
// create a sequence of case class objects
// (we defined the case class above)
val emp = Seq(
Employee(1, "vaquar khan", "111 algoinquin road chicago", 120000.00, "AZ",60173),
Employee(2, "Firdos Pasha", "1300 algoinquin road chicago", 2500000.00, "IL",50112),
Employee(3, "Zidan khan", "112 apt abcd timesqure NY", 50000.00, "NY",55490),
Employee(4, "Anwars khan", "washington dc", 120000.00, "VA",33245),
Employee(5, "Deepak sharma ", "rolling edows schumburg", 990090.00, "IL",60172),
Employee(6, "afaq khan", "saeed colony Bhopal", 1000000.00, "AZ",60173)
)
val employee=spark.sparkContext.parallelize(emp, 4).toDF()
employee.printSchema()
employee.show()
employee.select("state", "zip").show()
println("*** use filter() to choose rows")
employee.filter($"state".equalTo("IL")).show()
println("*** multi contidtion in filer || ")
employee.filter($"state".equalTo("IL") || $"state".equalTo("AZ")).show()
println("*** multi contidtion in filer && ")
employee.filter($"state".equalTo("AZ") && $"zip".equalTo("60173")).show()
}
}
This is how I installed it on my machine (ubuntu):
php 7:
sudo apt-get install php7.0-zip
php 5:
sudo apt-get install php5-zip
Edit:
Make sure to restart your server afterwards.
sudo /etc/init.d/apache2 restart
or sudo service nginx restart
PS: If you are using centOS, please check above cweiske's answer
But if you are using a Debian derivated OS, this solution should help you installing php zip extension.
Initialize k = j+1. You won't compare elements to themselves and you'll also not duplicate comparisons. For example, j = 0, k = 1 and k = 0, j = 1 compare the same set of elements. This would remove the k = 0, j = 1 comparison.
Not the perfect answer but works better for people using Github:
Go to your repo: Insights -> Network
If a linked server is not allowed by your dba, you can use OPENROWSET. Books Online will provide the syntax you need.
Try this to read a file:
BufferedReader reader = null;
try {
File file = new File("sample-file.dat");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This doesn't quite match the OP requirements, though hopefully it helps. With Laravel you can define your rules in an easy-to-maintain format like so:
$inputs = [
'email' => 'foo',
'password' => 'bar',
];
$rules = [
'email' => 'required|email',
'password' => [
'required',
'string',
'min:10', // must be at least 10 characters in length
'regex:/[a-z]/', // must contain at least one lowercase letter
'regex:/[A-Z]/', // must contain at least one uppercase letter
'regex:/[0-9]/', // must contain at least one digit
'regex:/[@$!%*#?&]/', // must contain a special character
],
];
$validation = \Validator::make( $inputs, $rules );
if ( $validation->fails() ) {
print_r( $validation->errors()->all() );
}
Would output:
[
'The email must be a valid email address.',
'The password must be at least 10 characters.',
'The password format is invalid.',
]
(The regex rules share an error message by default—i.e. four failing regex rules result in one error message)
You can use .empty()
, like this:
$("#foo").empty();
Remove all child nodes of the set of matched elements from the DOM.
I just realized, I think people shouldn't be exposed to the concept of "static" very early.
Static methods should probably be the exception rather than the norm. Especially early on anyways if you want to learn OOP. (Why start with an exception to the rule?) That's very counter-pedagogical of Java, that the "first" thing you should learn is the public static void main thing. (Few real Java applications have their own main methods anyways.)
SELECT <select_list>
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key
WHERE B.Key IS NULL
Full image of join
From aticle : http://www.codeproject.com/KB/database/Visual_SQL_Joins.aspx
Additional information
Sometimes it is necessary to bind a model into a view models and give a type conversion error. In this situation you should use ToList()
method.
var list = (from t in ctn.Items
where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
orderby t.Delivery.SubmissionDate
select t).Take(5).ToList();
You can specify relative path to the log file, using the work directory:
appender.file.fileName = ${sys:user.dir}/log/application.log
This is independent from the servlet container and does not require passing custom variable to the system environment.
I use
setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
to add entries at the bottom, and older entries scroll off the top, like a chat transcript
I actually once pushed with --force
and .git
repository and got scolded by Linus BIG TIME. In general this will create a lot of problems for other people. A simple answer is "Don't do it".
I see others gave the recipe for doing so anyway, so I won't repeat them here. But here is a tip to recover from the situation after you have pushed out the amended commit with --force (or +master).
git reflog
to find the old commit that you amended (call it old
, and we'll call the new commit you created by amending new
).old
and new
, recording the tree of new
, like git checkout new && git merge -s ours old
.git merge master
git push . HEAD:master
Then people who were unfortunate enough to have based their work on the commit you obliterated by amending and forcing a push will see the resulting merge will see that you favor new
over old
. Their later merges will not see the conflicts between old
and new
that resulted from your amending, so they do not have to suffer.
You don't need to have bunch of subscriptions and unsubscribe manually. Use Subject and takeUntil combo to handle subscriptions like a boss:
import { Subject } from "rxjs"
import { takeUntil } from "rxjs/operators"
@Component({
moduleId: __moduleName,
selector: "my-view",
templateUrl: "../views/view-route.view.html"
})
export class ViewRouteComponent implements OnInit, OnDestroy {
componentDestroyed$: Subject<boolean> = new Subject()
constructor(private titleService: TitleService) {}
ngOnInit() {
this.titleService.emitter1$
.pipe(takeUntil(this.componentDestroyed$))
.subscribe((data: any) => { /* ... do something 1 */ })
this.titleService.emitter2$
.pipe(takeUntil(this.componentDestroyed$))
.subscribe((data: any) => { /* ... do something 2 */ })
//...
this.titleService.emitterN$
.pipe(takeUntil(this.componentDestroyed$))
.subscribe((data: any) => { /* ... do something N */ })
}
ngOnDestroy() {
this.componentDestroyed$.next(true)
this.componentDestroyed$.complete()
}
}
Alternative approach, which was proposed by @acumartini in comments, uses takeWhile instead of takeUntil. You may prefer it, but mind that this way your Observable execution will not be cancelled on ngDestroy of your component (e.g. when you make time consuming calculations or wait for data from server). Method, which is based on takeUntil, doesn't have this drawback and leads to immediate cancellation of request. Thanks to @AlexChe for detailed explanation in comments.
So here is the code:
@Component({
moduleId: __moduleName,
selector: "my-view",
templateUrl: "../views/view-route.view.html"
})
export class ViewRouteComponent implements OnInit, OnDestroy {
alive: boolean = true
constructor(private titleService: TitleService) {}
ngOnInit() {
this.titleService.emitter1$
.pipe(takeWhile(() => this.alive))
.subscribe((data: any) => { /* ... do something 1 */ })
this.titleService.emitter2$
.pipe(takeWhile(() => this.alive))
.subscribe((data: any) => { /* ... do something 2 */ })
// ...
this.titleService.emitterN$
.pipe(takeWhile(() => this.alive))
.subscribe((data: any) => { /* ... do something N */ })
}
ngOnDestroy() {
this.alive = false
}
}
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
To get employee names starting with A or B listed in order...
select employee_name
from employees
where employee_name LIKE 'A%' OR employee_name LIKE 'B%'
order by employee_name
If you are using Microsoft SQL Server you could use
....
where employee_name LIKE '[A-B]%'
order by employee_name
This is not standard SQL though it just gets translated to the following which is.
WHERE employee_name >= 'A'
AND employee_name < 'C'
For all variants you would need to consider whether you want to include accented variants such as Á
and test whether the queries above do what you want with these on your RDBMS and collation options.
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
path
is simply new in Django 2.0, which was only released a couple of weeks ago. Most tutorials won't have been updated for the new syntax.
It was certainly supposed to be a simpler way of doing things; I wouldn't say that URL is more powerful though, you should be able to express patterns in either format.
Actually VBA can be used to compile DLLs. The Office 2000 and Office XP Developer editions included a VBA editor that could be used for making DLLs for use as COM Addins.
This functionality was removed in later versions (2003 and 2007) with the advent of the VSTO (VS Tools for Office) software, although obviously you could still create COM addins in a similar fashion without the use of VSTO (or VS.Net) by using VB6 IDE.
Right, click on the project. Go to Maven -> Update Project.
The dependencies will automatically be installed.
You have two possibilities:
org.springframework.beans.factory.config.MethodInvokingFactoryBean
to invoke a static setter.In the first option you have a bean with a regular setter but instead setting an instance property you set the static property/field.
public void setTheProperty(Object value) {
foo.bar.Class.STATIC_VALUE = value;
}
but in order to do this you need to have an instance of a bean that will expose this setter (its more like an workaround).
In the second case it would be done as follows:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="foo.bar.Class.setTheProperty"/> <property name="arguments"> <list> <ref bean="theProperty"/> </list> </property> </bean>
On you case you will add a new setter on the Utils
class:
public static setDataBaseAttr(Properties p)
and in your context you will configure it with the approach exemplified above, more or less like:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="foo.bar.Utils.setDataBaseAttr"/> <property name="arguments"> <list> <ref bean="dataBaseAttr"/> </list> </property> </bean>
First I did alias setup on bash / zsh profile.
alias composer="php /usr/local/bin/composer.phar"
Then I moved composer.phar to /usr/local/bin/
cd /usr/local/bin
mv composer.phar composer
Then made composer executable by running
sudo chmod +x composer
The default port 1433 is used when there is only one SQL Server named instance running on the computer.
When multiple SQL Server named instances are running, they run by default under a dynamic port (49152–65535). In this scenario, an application will connect to the SQL Server Browser service port (UDP 1434) to get the dynamic port and then connect to the dynamic port directly.
Version 3 of the YouTube Data API has concrete quota numbers listed in the Google API Console where you register for your API Key. You can use 10,000 units per day. Projects that had enabled the YouTube Data API before April 20, 2016, have a default quota of 50M/day.
You can read about what a unit is here: https://developers.google.com/youtube/v3/getting-started#quota
If you hit the limits, Google will stop returning results until your quota is reset. You can apply for more than 1M requests per day, but you will have to pay for those extra requests.
Also, you can read about why Google has deferred support to StackOverflow on their YouTube blog here: https://youtube-eng.googleblog.com/2012/09/the-youtube-api-on-stack-overflow_14.html
There are a number of active members on the YouTube Developer Relations team here including Jeff Posnick, Jarek Wilkiewicz, and Ibrahim Ulukaya who all have knowledge of Youtube internals...
UPDATE: Increased the quota numbers to reflect current limits on December 10, 2013.
UPDATE: Decreased the quota numbers from 50M to 1M per day to reflect current limits on May 13, 2016.
UPDATE: Decreased the quota numbers from 1M to 10K per day as of January 11, 2019.
MSSQL requires that variables within procedures be DECLAREd and folks use the @Variable syntax (DECLARE @TEXT VARCHAR(25) = 'text'). Also, MS allows for declares within any block in the procedure, unlike mySQL which requires all the DECLAREs at the top.
While good on the command line, I feel using the "set = @variable" within stored procedures in mySQL is risky. There is no scope and variables live across scope boundaries. This is similar to variables in JavaScript being declared without the "var" prefix, which are then the global namespace and create unexpected collisions and overwrites.
I am hoping that the good folks at mySQL will allow DECLARE @Variable at various block levels within a stored procedure. Notice the @ (at sign). The @ sign prefix helps to separate variable names from table column names - as they are often the same. Of course, one can always add an "v" or "l_" prefix, but the @ sign is a handy and succinct way to have the variable name match the column you might be extracting the data from without clobbering it.
MySQL is new to stored procedures and they have done a good job for their first version. It will be a pleaure to see where they take it form here and to watch the server side aspects of the language mature.
I strongly recommend you learn how to use layout managers to get the layout you want to see. null
layouts are fragile, and cause no end of trouble.
Try this source & check the comments.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class VolumeCalculator extends JFrame implements ActionListener {
private JTabbedPane jtabbedPane;
private JPanel options;
JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
myTitle;
JTextArea labelTubStatus;
public VolumeCalculator(){
setSize(400, 250);
setVisible(true);
setSize(400, 250);
setVisible(true);
setTitle("Volume Calculator");
setSize(300, 200);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
createOptions();
jtabbedPane = new JTabbedPane();
jtabbedPane.addTab("Options", options);
topPanel.add(jtabbedPane, BorderLayout.CENTER);
}
/* CREATE OPTIONS */
public void createOptions(){
options = new JPanel();
//options.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
options.add(labelOptions);
JTextField newTitle = new JTextField("Some Title");
//newTitle.setBounds(80, 40, 225, 20);
options.add(newTitle);
myTitle = new JTextField(20);
// myTitle WAS NEVER ADDED to the GUI!
options.add(myTitle);
//myTitle.setBounds(80, 40, 225, 20);
//myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
//newName.setBounds(60, 80, 150, 20);
newName.addActionListener(this);
options.add(newName);
JButton Exit = new JButton("Exit");
//Exit.setBounds(250, 80, 80, 20);
Exit.addActionListener(this);
options.add(Exit);
}
public void actionPerformed(ActionEvent event){
JButton button = (JButton) event.getSource();
String buttonLabel = button.getText();
if ("Exit".equalsIgnoreCase(buttonLabel)){
Exit_pressed();
return;
}
if ("Set New Name".equalsIgnoreCase(buttonLabel)){
New_Name();
return;
}
}
private void Exit_pressed(){
System.exit(0);
}
private void New_Name(){
System.out.println("'" + myTitle.getText() + "'");
this.setTitle(myTitle.getText());
}
private void Options(){
}
public static void main(String[] args){
JFrame frame = new VolumeCalculator();
frame.pack();
frame.setSize(380, 350);
frame.setVisible(true);
}
}
My habit is to use function myName() as property storage, and then var myName as "method" holder...
Whether this is legitimate enough or not, beat me! I am relying on my PHP logic all the time, and things simply work. :D
function myObj() {
this.prop1 = 1;
this.prop2 = 2;
this.prop3 = 'string';
}
var myObj = (
(myObj instanceof Function !== false)
? Object.create({
$props: new myObj(),
fName1: function() { /* code.. */ },
fName2: function() { /* code ...*/ }
})
: console.log('Object creation failed!')
);
if (this !== that) myObj.fName1(); else myObj.fName2();
You can also do it in a 'vice versa' way to check before object creation which is much better:
function myObj() {
this.prop1 = 1;
this.prop2 = 2;
this.prop3 = 'string';
}
var myObj = (
(typeof(myObj) !== "function" || myObj instanceof Function === false)
? new Boolean()
: Object.create({
$props: new myObj(),
init: function () { return; },
fName1: function() { /* code.. */ },
fName2: function() { /* code ...*/ }
})
);
if (myObj instanceof Boolean) {
Object.freeze(myObj);
console.log('myObj failed!');
debugger;
}
else
myObj.init();
Reference to this: JavaScript: Creating Object with Object.create()
Instead of using re.search
use re.findall
it will return you all matches in a List
. Or you could also use re.finditer
(which i like most to use) it will return an Iterator Object
and you can just use it to iterate over all found matches.
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
for match in re.finditer('<form>(.*?)</form>', line, re.S):
print match.group(1)
you need to use display = none
value hidden is connected with attributet called visibility
so your code should look like this
<script type="text/javascript">
function hide(){
document.getElementById("test").style.display="none";
}
</script>
The parametric equation for a circle is
x = cx + r * cos(a)
y = cy + r * sin(a)
Where r is the radius, cx,cy the origin, and a the angle.
That's pretty easy to adapt into any language with basic trig functions. Note that most languages will use radians for the angle in trig functions, so rather than cycling through 0..360 degrees, you're cycling through 0..2PI radians.
To add to x4u answer, which gives you the floor of the binary log of a number, this function return the ceil of the binary log of a number :
public static int ceilbinlog(int number) // returns 0 for bits=0
{
int log = 0;
int bits = number;
if ((bits & 0xffff0000) != 0) {
bits >>>= 16;
log = 16;
}
if (bits >= 256) {
bits >>>= 8;
log += 8;
}
if (bits >= 16) {
bits >>>= 4;
log += 4;
}
if (bits >= 4) {
bits >>>= 2;
log += 2;
}
if (1 << log < number)
log++;
return log + (bits >>> 1);
}
For me, the simplest way to use ALIAS in WHERE class is to create a subquery and select from it instead.
Example:
WITH Q1 AS (
SELECT LENGTH(name) AS name_length,
id,
name
FROM any_table
)
SELECT id, name, name_length form Q1 where name_length > 0
Cheers, Kel
apt-get install python2.7
will work on debian-like linuxes. The python website describes a whole bunch of other ways to get Python.
convert to Array
var array = like.ToArray();
var first = array[0];
Easy, you can use a Post request and submit your file as binary (byte array).
String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
"yourfile");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
} catch (Exception e) {
// show error
}
If you don't want to use the random
module, you can also try popitem():
>> d = {'a': 1, 'b': 5, 'c': 7}
>>> d.popitem()
('a', 1)
>>> d
{'c': 7, 'b': 5}
>>> d.popitem()
('c', 7)
Since the dict
doesn't preserve order, by using popitem
you get items in an arbitrary (but not strictly random) order from it.
Also keep in mind that popitem
removes the key-value pair from dictionary, as stated in the docs.
popitem() is useful to destructively iterate over a dictionary
Using this,
String s = "03/24/2013 21:54";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("date : "+simpleDateFormat.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
If any doubt in this code, please ask your questions(Here for gmail Port number is 587)
// code to Send Mail
// Add following Lines in your web.config file
// <system.net>
// <mailSettings>
// <smtp>
// <network host="smtp.gmail.com" port="587" userName="[email protected]" password="yyy" defaultCredentials="false"/>
// </smtp>
// </mailSettings>
// </system.net>
// Add below lines in your config file inside appsetting tag <appsetting></appsetting>
// <add key="emailFromAddress" value="[email protected]"/>
// <add key="emailToAddress" value="[email protected]"/>
// <add key="EmailSsl" value="true"/>
// Namespace Used
using System.Net.Mail;
public static bool SendingMail(string subject, string content)
{
// getting the values from config file through c#
string fromEmail = ConfigurationSettings.AppSettings["emailFromAddress"];
string mailid = ConfigurationSettings.AppSettings["emailToAddress"];
bool useSSL;
if (ConfigurationSettings.AppSettings["EmailSsl"] == "true")
{
useSSL = true;
}
else
{
useSSL = false;
}
SmtpClient emailClient;
MailMessage message;
message = new MailMessage();
message.From = new MailAddress(fromEmail);
message.ReplyTo = new MailAddress(fromEmail);
if (SetMailAddressCollection(message.To, mailid))
{
message.Subject = subject;
message.Body = content;
message.IsBodyHtml = true;
emailClient = new SmtpClient();
emailClient.EnableSsl = useSSL;
emailClient.Send(message);
}
return true;
}
// if you are sending mail in group
private static bool SetMailAddressCollection(MailAddressCollection toAddresses, string mailId)
{
bool successfulAddressCreation = true;
toAddresses.Add(new MailAddress(mailId));
return successfulAddressCreation;
}
You can use a library called select2
You also can look at this Stackoverflow Question & Answer
<select id="selectBox" style="width: 500px">
<option value="1" data-desc="this is my <br> multiple line 1">option 1</option>
<option value="2" data-desc="this is my <br> multiple line 2">option 2</option>
</select>
In javascript
$(function(){
$("#selectBox").select2({
templateResult: formatDesc
});
function formatDesc (opt) {
var optdesc = $(opt.element).attr('data-desc');
var $opt = $(
'<div><strong>' + opt.text + '</strong></div><div>' + optdesc + '</div>'
);
return $opt;
};
});
>>> txt = '7061756c'
>>> ''.join([chr(int(''.join(c), 16)) for c in zip(txt[0::2],txt[1::2])])
'paul'
i'm just having fun, but the important parts are:
>>> int('0a',16) # parse hex
10
>>> ''.join(['a', 'b']) # join characters
'ab'
>>> 'abcd'[0::2] # alternates
'ac'
>>> zip('abc', '123') # pair up
[('a', '1'), ('b', '2'), ('c', '3')]
>>> chr(32) # ascii to character
' '
will look at binascii now...
>>> print binascii.unhexlify('7061756c')
paul
cool (and i have no idea why other people want to make you jump through hoops before they'll help).
Yes - just do it this way:
WITH DependencedIncidents AS
(
....
),
lalala AS
(
....
)
You don't need to repeat the WITH
keyword
You want to 'inherit' from Person's prototype object:
var Person = function (name) {
this.name = name;
this.type = 'human';
};
Person.prototype.info = function () {
console.log("Name:", this.name, "Type:", this.type);
};
var Robot = function (name) {
Person.apply(this, arguments);
this.type = 'robot';
};
Robot.prototype = Person.prototype; // Set prototype to Person's
Robot.prototype.constructor = Robot; // Set constructor back to Robot
person = new Person("Bob");
robot = new Robot("Boutros");
person.info();
// Name: Bob Type: human
robot.info();
// Name: Boutros Type: robot
"ABCDEFG".First
returns "A"
Dim s as string
s = "Rajan"
s.First
'R
s = "Sajan"
s.First
'S
scp is best for one file.
OR a combination of tar
& compression for smaller data sets
like source code trees with small resources (ie: images, sqlite etc).
It becomes impractical to build a zip/tar.gz file to transfer with scp at this point do to the physical limits of the hosted server.
As an exercise, you can do some gymnastics like piping tar
into ssh
and redirecting the results into a remote file. (saving the need to build
a swap or temporary clone aka zip or tar.gz)
However,
rsync simplify's this process and allows you to transfer data without consuming any additional disc space.
Also,
Continuous (cron?) updates use minimal changes vs full cloned copies speed up large data migrations over time.
tl;dr
scp
== small scale (with room to build compressed files on the same drive)
rsync
== large scale (with the necessity to backup large data and no room left)
This is a function based on @DamienFennelly's answer above. If you give me a thumbs up, give him a thumbs up too! :P
Function outColLetterFromNumber(iCol as Integer) as String
sAddr = Cells(1, iCol).Address
aSplit = Split(sAddr, "$")
outColLetterFromNumber = aSplit(1)
End Function
var names = [{_x000D_
name: "Joe",_x000D_
age: 20,_x000D_
email: "[email protected]"_x000D_
},_x000D_
{_x000D_
name: "Mike",_x000D_
age: 50,_x000D_
email: "[email protected]"_x000D_
},_x000D_
{_x000D_
name: "Joe",_x000D_
age: 45,_x000D_
email: "[email protected]"_x000D_
}_x000D_
];_x000D_
const res = _.filter(names, (name) => {_x000D_
return name.name == "Joe" && name.age < 30;_x000D_
_x000D_
});_x000D_
console.log(res);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
_x000D_
iloc
works based on integer positioning. So no matter what your row labels are, you can always, e.g., get the first row by doing
df.iloc[0]
or the last five rows by doing
df.iloc[-5:]
You can also use it on the columns. This retrieves the 3rd column:
df.iloc[:, 2] # the : in the first position indicates all rows
You can combine them to get intersections of rows and columns:
df.iloc[:3, :3] # The upper-left 3 X 3 entries (assuming df has 3+ rows and columns)
On the other hand, .loc
use named indices. Let's set up a data frame with strings as row and column labels:
df = pd.DataFrame(index=['a', 'b', 'c'], columns=['time', 'date', 'name'])
Then we can get the first row by
df.loc['a'] # equivalent to df.iloc[0]
and the second two rows of the 'date'
column by
df.loc['b':, 'date'] # equivalent to df.iloc[1:, 1]
and so on. Now, it's probably worth pointing out that the default row and column indices for a DataFrame
are integers from 0 and in this case iloc
and loc
would work in the same way. This is why your three examples are equivalent. If you had a non-numeric index such as strings or datetimes, df.loc[:5]
would raise an error.
Also, you can do column retrieval just by using the data frame's __getitem__
:
df['time'] # equivalent to df.loc[:, 'time']
Now suppose you want to mix position and named indexing, that is, indexing using names on rows and positions on columns (to clarify, I mean select from our data frame, rather than creating a data frame with strings in the row index and integers in the column index). This is where .ix
comes in:
df.ix[:2, 'time'] # the first two rows of the 'time' column
I think it's also worth mentioning that you can pass boolean vectors to the loc
method as well. For example:
b = [True, False, True]
df.loc[b]
Will return the 1st and 3rd rows of df
. This is equivalent to df[b]
for selection, but it can also be used for assigning via boolean vectors:
df.loc[b, 'name'] = 'Mary', 'John'
Try this:
Update MasterTbl Set
TotalX = Sum(D.X),
TotalY = Sum(D.Y),
TotalZ = Sum(D.Z)
From MasterTbl M Join DetailTbl D
On D.MasterID = M.MasterID
Depending on which database you are using, if that doesn't work, then try this (this is non-standard SQL but legal in SQL Server):
Update M Set
TotalX = Sum(D.X),
TotalY = Sum(D.Y),
TotalZ = Sum(D.Z)
From MasterTbl M Join DetailTbl D
On D.MasterID = M.MasterID
I did not have a servlet-api.jar in the application's WEB-INF/lib directory (or any other jar there). The problem was that in WEB-INF/web.xml I had this...
...
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.bizooka.net.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
...
...according to a tutorial. Removing that still allowed the servlet to function, and did not get the error.
The answer posted above/earlier that was reported to replace CHAR(13)CHAR(10) carriage return:
REPLACE(REPLACE(REPLACE(MyField, CHAR(13) + CHAR(10), 'something else'), CHAR(13), 'something else'), CHAR(10), 'something else')
Will never get to the REPLACE(MyField, CHAR(13) + CHAR(10), 'something else')
portion of the code and will return the unwanted result of:
'something else''something else'
And NOT the desired result of a single:
'something else'
That would require the REPLACE script to be rewritten as such:
REPLACE(REPLACE(REPLACE(MyField, CHAR(10), 'something else'), CHAR(13), 'something else'), CHAR(13) + CHAR(10), 'something else')
As the flow first tests the 1st/Furthest Left REPLACE statement, then upon failure will continue to test the next REPLACE statement.
You can either use:
<button onclick="window.history.back()">Back</button>
or..
<button onclick="window.history.go(-1)">Back</button>
The difference, of course, is back()
only goes back 1 page but go()
goes back/forward the number of pages you pass as a parameter, relative to your current page.
For your first method change ws.Range("A")
to ws.Range("A:A")
which will search the entirety of column a, like so:
Sub Find_Bingo()
Dim wb As Workbook
Dim ws As Worksheet
Dim FoundCell As Range
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Const WHAT_TO_FIND As String = "Bingo"
Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
If Not FoundCell Is Nothing Then
MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
Else
MsgBox (WHAT_TO_FIND & " not found")
End If
End Sub
For your second method, you are using Bingo
as a variable instead of a string literal. This is a good example of why I add Option Explicit
to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.
Additionally, when you are using With...End With
you need a period .
before you reference Cells
, so Cells
should be .Cells
. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)
Change Bingo
to "Bingo"
and change Cells
to .Cells
With Sheet1
Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not FoundCell Is Nothing Then
MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
MsgBox ("Bingo not found")
End If
In my
With Sheet1
.....
End With
The Sheet1
refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1
. I can refer to that in code either with the code name of Sheet1
or I can refer to it with the index of Sheets("Sheet1")
. The advantage to using a codename is that it does not change if you change the name of the worksheet.
Continuing this example, let's say I renamed Sheet1
to Data
. Using Sheet1
would continue to work, as the code name doesn't change, but now using Sheets("Sheet1")
would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data")
.
In the VB Editor you would see something like this:
Notice how, even though I changed the name to Data
, there is still a Sheet1
to the left. That is what I mean by codename.
The Data
worksheet can be referenced in two ways:
Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name
Both should return Data
More discussion on worksheet code names can be found here.
<span>You have {{products|length}} products</span>
You can also use this syntax in expressions like
{% if products|length > 1 %}
jinja2's builtin filters are documented here; and specifically, as you've already found, length
(and its synonym count
) is documented to:
Return the number of items of a sequence or mapping.
So, again as you've found, {{products|count}}
(or equivalently {{products|length}}
) in your template will give the "number of products" ("length of list")
HTML
<body>
<div id="load"></div>
<div id="contents">
jlkjjlkjlkjlkjlklk
</div>
</body>
JS
document.onreadystatechange = function () {
var state = document.readyState
if (state == 'interactive') {
document.getElementById('contents').style.visibility="hidden";
} else if (state == 'complete') {
setTimeout(function(){
document.getElementById('interactive');
document.getElementById('load').style.visibility="hidden";
document.getElementById('contents').style.visibility="visible";
},1000);
}
}
CSS
#load{
width:100%;
height:100%;
position:fixed;
z-index:9999;
background:url("https://www.creditmutuel.fr/cmne/fr/banques/webservices/nswr/images/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}
Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.
DEMO
http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)
update
You don't need to use character codes; just use UTF-8 and put them in literally; like so:
??
If you absolutely must use the entites, they are ▲
and ▼
, respectively.
no need for the padding or the corners.
here's a sample:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
android:angle="270"/>
</shape>
based on :
Here is a trick though. You can map the Ctrl+Z keys.
This can be achieved by editing the .vimrc
file. Add the following lines in the '.vimrc` file.
nnoremap <c-z> :u<CR> " Avoid using this**
inoremap <c-z> <c-o>:u<CR>
This may not the a preferred way, but can be used.
** Ctrl+Z is used in Linux to suspend the ongoing program/process.
Strings are immutable, so when you manipulate them you need to assign the result to a string:
String id = fileR.getName();
id = id.replace(".xml", ""); // this is the key line
idList.add(id);
Few lines solution without redundant pairs of variables:
corr_matrix = df.corr().abs()
#the matrix is symmetric so we need to extract upper triangle matrix without diagonal (k = 1)
sol = (corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
.stack()
.sort_values(ascending=False))
#first element of sol series is the pair with the biggest correlation
Then you can iterate through names of variables pairs (which are pandas.Series multi-indexes) and theirs values like this:
for index, value in sol.items():
# do some staff
After installation you need to connect to Server Name : localhost to start using the local instance of SQL Server.
Once you are connected to the local instance, right click on Databases and create a new database.
From the standpoint of a method which receives a parameter, the difference between ref
and out
is that C# requires that methods must write to every out
parameter before returning, and must not do anything with such a parameter, other than passing it as an out
parameter or writing to it, until it has been either passed as an out
parameter to another method or written directly. Note that some other languages do not impose such requirements; a virtual or interface method which is declared in C# with an out
parameter may be overridden in another language which does not impose any special restrictions on such parameters.
From the standpoint of the caller, C# will in many circumstances assume when calling a method with an out
parameter will cause the passed variable to be written without having been read first. This assumption may not be correct when calling methods written in other languages. For example:
struct MyStruct
{
...
myStruct(IDictionary<int, MyStruct> d)
{
d.TryGetValue(23, out this);
}
}
If myDictionary
identifies an IDictionary<TKey,TValue>
implementation written in a language other than C#, even though MyStruct s = new MyStruct(myDictionary);
looks like an assignment, it could potentially leave s
unmodified.
Note that constructors written in VB.NET, unlike those in C#, make no assumptions about whether called methods will modify any out
parameters, and clear out all fields unconditionally. The odd behavior alluded to above won't occur with code written entirely in VB or entirely in C#, but can occur when code written in C# calls a method written in VB.NET.
I was faces this issue but after change object into str, problem solved. str(fname).isalpha():
I have created this easy to use library that does exactly what you are looking for: ss-search
import { search } from "ss-search"
const data = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor",
"bar" : "amet"
}
]
const searchKeys = ["foor", "bar"]
const searchText = "dolor"
const results = search(data, keys, searchText)
// results: [{ "foo": "dolor", "bar": "amet" }]
Starting from C# 2.0, you can use the nullable generic type Nullable, and in C# there is a shorthand notation the type followed by ?
e.g.
private void Example(int? arg1, int? arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
I had this problem since updating to the iOS 9 SDK when I was calling a block that did UI updates within an NSURLConnection async request completion handler. Putting the block call in a dispatch_async using dispatch_main_queue solved the issue.
It worked fine in iOS 8.
add the parameter -expandproperty after the select-object, it will return only data without header.
Here is the latest example of how to do it. From react docs, plus auto-binding "fat-arrow" method syntax.
class FlavorForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
}
handleChange = (event) =>
this.setState({value: event.target.value});
handleSubmit = (event) => {
alert('Your favorite flavor is: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
// Create a new StringBuilder.
StringBuilder builder = new StringBuilder();
// Loop and append values.
for (int i = 0; i < 5; i++) {
builder.append("abc ");
}
// Convert to string.
String result = builder.toString();
// Print result.
System.out.println(result);
}
}
You can use the following code to get last cell.
UITableViewCell *cell = [tableView cellForRowAtIndexPath:lastIndexPath];
install TypeScript :
npm install typescript
add tsc script to package.json:
"scripts": {
"tsc": "tsc"
},
run this:
npx tsc --init
Local Windows 10 ActiveMQ server :
@echo off
start /min "" "C:\Install\apache-activemq\5.15.10\bin\win64\activemq.bat" start
var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);
I agree with the other answerers that in most cases (almost always) it is necessary to sanitize Your input.
But consider such code (it is for a REST controller):
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
return $this->doGet($request, $object);
case 'POST':
return $this->doPost($request, $object);
case 'PUT':
return $this->doPut($request, $object);
case 'DELETE':
return $this->doDelete($request, $object);
default:
return $this->onBadRequest();
}
It would not be very useful to apply sanitizing here (although it would not break anything, either).
So, follow recommendations, but not blindly - rather understand why they are for :)
to build on stu's answer. here's how i found the frame rate for a video from my mobile phone. i ran the following command for a while. i let the frame count get up to about ~ 10,000 before i got impatient and hit ^C:
$ ffmpeg -i 2013-07-07\ 12.00.59.mp4 -f null /dev/null 2>&1
...
Press [q] to stop, [?] for help
[null @ 0x7fcc80836000] Encoder did not produce proper pts, making some up.
frame= 7989 fps= 92 q=0.0 Lsize=N/A time=00:04:26.30 bitrate=N/A dup=10 drop=0
video:749kB audio:49828kB subtitle:0 global headers:0kB muxing overhead -100.000042%
Received signal 2: terminating.
$
then, i grabbed two pieces of information from that line which starts with "frame=", the frame count, 7989, and the time, 00:04:26.30. You first need to convert the time into seconds and then divide the number of frames by seconds to get "frames per second". "frames per second" is your frame rate.
$ bc -l
0*60*60 + 4*60 + 26.3
266.3
7989/(4*60+26.3)
30.00000000000000000000
$
the framerate for my video is 30 fps.
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView
- I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model
property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name
for the new class, it worked fine.
I have a feeling that your ClientID
is not of a string type (zero-terminated char*
or std::string
) but some integral type (e.g. int
) so you need to convert number to the string first:
std::stringstream ss;
ss << ClientID;
query.append(ss.str());
But you can use operator+
as well (instead of append
):
query += ss.str();
So you really want:
for each tweet
unless tweet is in db
insert tweet
If so, just write it down in your programming language. Hint: The loop over the array is to be done before the insert, which is done depending on the outcome.
What you want to test is that all array elements are not equal to the current one. But your for loop does not do that.
To access MySQL in Windows you need to install the XAMPP.
Now go to the command prompt and open
C:\>cd xampp
C:\xampp>cd MySQL
C:\xampp\mysql>cd bin
C:\xampp\mysql\bin>mysql -h localhost -u root
Your database is now ready to be executed.
I agree with Jason.
I got caught out doing this:
#import <sys/time.h> // to use gettimeofday() function
#import <time.h> // to use time() function
For GNU gcc, it kept complaining that time() function was not defined.
So then I changed #import to #include and all went ok.
Reason:
You #import <sys/time.h>:
<sys/time.h> includes only a part of <time.h> by using #defines
You #import <time.h>:
No go. Even though only part of <time.h> was already included, as
far as #import is concerned, that file is now already completely included.
Bottom line:
C/C++ headers traditionally includes parts of other include files.
So for C/C++ headers, use #include.
For objc/objc++ headers, use #import.
git branch --set-upstream <remote-branch>
sets the default remote branch for the current local branch.
Any future git pull
command (with the current local branch checked-out),
will attempt to bring in commits from the <remote-branch>
into the current local branch.
One way to avoid having to explicitly type --set-upstream
is to use its shorthand flag -u
as follows:
git push -u origin local-branch
This sets the upstream association for any future push/pull attempts automatically.
For more details, checkout this detailed explanation about upstream branches and tracking.
To avoid confusion, recent versions of
git
deprecate this somewhat ambiguous--set-upstream
option in favour of a more verbose--set-upstream-to
option with identical syntax and behaviourgit branch --set-upstream-to <origin/remote-branch>
From the spec:
All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus [backslash] (U+005C), and the control characters U+0000 to U+001F
Just because e.g. Bell (U+0007) doesn't have a single-character escape code does not mean that you don't need to escape it. Use the Unicode escape sequence \u0007
.
Will something like this work for you? What this does is query the content resolver to find the file path data that is stored for that content entry
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
This will end up giving you an absolute file path that you can construct a file uri from
Configure your package.json file
"test": "jest --coverage",
Now run:
yarn test
All the test will start running and you will get the report.
If you want to allow a user to add a bunch of new MyObjects to the list, you can do it with a for loop: Let's say I'm creating an ArrayList of Rectangle objects, and each Rectangle has two parameters- length and width.
//here I will create my ArrayList:
ArrayList <Rectangle> rectangles= new ArrayList <>(3);
int length;
int width;
for(int index =0; index <3;index++)
{JOptionPane.showMessageDialog(null, "Rectangle " + (index + 1));
length = JOptionPane.showInputDialog("Enter length");
width = JOptionPane.showInputDialog("Enter width");
//Now I will create my Rectangle and add it to my rectangles ArrayList:
rectangles.add(new Rectangle(length,width));
//This passes the length and width values to the rectangle constructor,
which will create a new Rectangle and add it to the ArrayList.
}
if you state a.redLink{color:red;}
then to keep this on hover and such add a.redLink:hover{color:red;}
This will make sure no other hover states will change the color of your links
merge into x as target using y as Source on target.ID = Source.ID
when not matched by target then insert
when matched then update
when not matched by source and target.ID is not null then
update whatevercolumn = 'isdeleted' ;
For Netbeans 2020 September version. JDK 11
(Suggesting this for Gradle project only)
1. create libs
folder in src/main/java
folder of the project
2. copy past all library jars in there
3. open build.gradle in files
tab of project window in project's root
4. correct main class (mine is mainClassName = 'uz.ManipulatorIkrom'
)
5. and in dependencies
add next string:
apply plugin: 'java'
apply plugin: 'jacoco'
apply plugin: 'application'
description = 'testing netbeans'
mainClassName = 'uz.ManipulatorIkrom' //4th step
repositories {
jcenter()
}
dependencies {
implementation fileTree(dir: 'src/main/java/libs', include: '*.jar') //5th step
}
6. save, clean-build and then run the app
AES encrypt/decrypt in android
String encData= encrypt("keykey".getBytes("UTF-16LE"), ("0123000000000215").getBytes("UTF-16LE"));
String decData= decrypt("keykey",Base64.decode(encData.getBytes("UTF-16LE"), Base64.DEFAULT));
encrypt function
private static String encrypt(byte[] key, byte[] clear) throws Exception
{
MessageDigest md = MessageDigest.getInstance("md5");
byte[] digestOfPassword = md.digest(key);
SecretKeySpec skeySpec = new SecretKeySpec(digestOfPassword, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return Base64.encodeToString(encrypted,Base64.DEFAULT);
}
decrypt function
private static String decrypt(String key, byte[] encrypted) throws Exception
{
MessageDigest md = MessageDigest.getInstance("md5");
byte[] digestOfPassword = md.digest(key.getBytes("UTF-16LE"));
SecretKeySpec skeySpec = new SecretKeySpec(digestOfPassword, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return new String(decrypted, "UTF-16LE");
}
AES encrypt/decrypt in c#
static void Main(string[] args)
{
string enc = encryptAES("0123000000000215", "keykey");
string dec = decryptAES(enc, "keykey");
Console.ReadKey();
}
encrypt function
public static string encryptAES(string input, string key)
{
var plain = Encoding.Unicode.GetBytes(input);
// 128 bits
AesCryptoServiceProvider provider = new AesCryptoServiceProvider();
provider.KeySize = 128;
provider.Mode = CipherMode.ECB;
provider.Padding = PaddingMode.PKCS7;
provider.Key = CalculateMD5Hash(key);
var enc = provider.CreateEncryptor().TransformFinalBlock(plain, 0, plain.Length);
return Convert.ToBase64String(enc);
}
decrypt function
public static string decryptAES(string encryptText, string key)
{
byte[] enc = Convert.FromBase64String(encryptText);
// 128 bits
AesCryptoServiceProvider provider = new AesCryptoServiceProvider();
provider.KeySize = 128;
provider.Mode = CipherMode.ECB;
provider.Padding = PaddingMode.PKCS7;
provider.Key = CalculateMD5Hash(key);
var dec = provider.CreateDecryptor().TransformFinalBlock(enc, 0, enc.Length);
return Encoding.Unicode.GetString(dec);
}
create md5
public static byte[] CalculateMD5Hash(string input)
{
MD5 md5 = MD5.Create();
byte[] inputBytes = Encoding.Unicode.GetBytes(input);
return md5.ComputeHash(inputBytes);
}
You are 90% of the way there.
^[0-9,;]+$
Starting with the carat ^
indicates a beginning of line.
The [
indicates a character set
The 0-9
indicates characters 0 through 9, the comma ,
indicates comma, and the semicolon indicates a ;
.
The closing ]
indicates the end of the character set.
The plus +
indicates that one or more of the "previous item" must be present. In this case it means that you must have one or more of the characters in the previously declared character set.
The dollar $
indicates the end of the line.
To add Tomer and Charles answers,
Syntax to run nginx in forground in Docker container using Entrypoint:
ENTRYPOINT nginx -g 'daemon off;'
Not directly related but to run multiple commands with Entrypoint:
ENTRYPOINT /bin/bash -x /myscripts/myscript.sh && nginx -g 'daemon off;'
Not tested but should work
products.sort((a,b)=>a.title.rendered > b.title.rendered)
Something like this will do the trick. Don't know about performance, so do make some tests.
select
id, name, city
from
[stuff] s
where
1 < (select count(*) from [stuff] i where i.city = s.city and i.name = s.name)
Just in case it may help somebody, you may also try this animator ViewPropertyAnimator as below
myView.animate().x(50f).y(100f);
myView.animate().translateX(pixelInScreen)
Note: This pixel is not relative to the view. This pixel is the pixel position in the screen.
credits to bpr10 answer
phpize
./configure
make
make install (as root)
This worked for me
Simple and effective alternative:
public class ClassName
{
public List<dynamic> MyProperty { get; set; }
}
or
public class ClassName
{
public List<object> MyProperty { get; set; }
}
For differences see this post: List<Object> vs List<dynamic>
ASCII has 128 code points, 0 through 127. It can fit in a single 8-bit byte, the values 128 through 255 tended to be used for other characters. With incompatible choices, causing the code page disaster. Text encoded in one code page cannot be read correctly by a program that assumes or guessed at another code page.
Unicode came about to solve this disaster. Version 1 started out with 65536 code points, commonly encoded in 16 bits. Later extended in version 2 to 1.1 million code points. The current version is 6.3, using 110,187 of the available 1.1 million code points. That doesn't fit in 16 bits anymore.
Encoding in 16-bits was common when v2 came around, used by Microsoft and Apple operating systems for example. And language runtimes like Java. The v2 spec came up with a way to map those 1.1 million code points into 16-bits. An encoding called UTF-16, a variable length encoding where one code point can take either 2 or 4 bytes. The original v1 code points take 2 bytes, added ones take 4.
Another variable length encoding that's very common, used in *nix operating systems and tools is UTF-8, a code point can take between 1 and 4 bytes, the original ASCII codes take 1 byte the rest take more. The only non-variable length encoding is UTF-32, takes 4 bytes for a code point. Not often used since it is pretty wasteful. There are other ones, like UTF-1 and UTF-7, widely ignored.
An issue with the UTF-16/32 encodings is that the order of the bytes will depend on the endian-ness of the machine that created the text stream. So add to the mix UTF-16BE, UTF-16LE, UTF-32BE and UTF-32LE.
Having these different encoding choices brings back the code page disaster to some degree, along with heated debates among programmers which UTF choice is "best". Their association with operating system defaults pretty much draws the lines. One counter-measure is the definition of a BOM, the Byte Order Mark, a special codepoint (U+FEFF, zero width space) at the beginning of a text stream that indicates how the rest of the stream is encoded. It indicates both the UTF encoding and the endianess and is neutral to a text rendering engine. Unfortunately it is optional and many programmers claim their right to omit it so accidents are still pretty common.
Featured graphics guidelines:
http://android-developers.blogspot.cz/2011/10/android-market-featured-image.html
List of graphics assets for your application:
http://support.google.com/googleplay/android-developer/bin/answer.py?hl=en&answer=1078870
You could also check our blog post summarizing all graphical assets for both Android and iOS:
http://www.skoumal.net/en/how-to-prepare-graphical-design-for-mobile-app/
On apache you need to edit security.conf:
nano /etc/apache2/conf-enabled/security.conf
and set:
Header set X-Frame-Options: "sameorigin"
Then enable mod_headers:
cd /etc/apache2/mods-enabled
ln -s ../mods-available/headers.load headers.load
And restart Apache:
service apache2 restart
And voila!
Although I am not 100% sure what you want (probably my brain is slow today), here is an example of a similar use to what you describe:
function GetProcedureById(procedureId)
{
var includeMaster = true;
pString = '{"procedureId":"' + procedureId.toString() + '","includeMaster":"' + includeMaster.toString() + '"}';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: pString,
datatype: "json",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "webservice/ProcedureCodesService.asmx/GetProcedureById",
success: function(msg)
{
LoadProcedure(msg);
},
failure: function(msg)
{
// $("#sometextplace").text("Procedure did not load");
}
});
};
/* build the Procedure option list */
function LoadProcedure(jdata)
{
if (jdata.length < 10)
{
$("select#cptIcdProcedureSelect").attr('size', jdata.length);
}
else
{
$("select#cptIcdProcedureSelect").attr('size', '10');
};
var options = '';
for (var i = 0; i < jdata.length; i++)
{
options += '<option value="' + jdata[i].Description + '">' + jdata[i].Description + ' (' + jdata[i].ProcedureCode + ')' + '</option>';
};
$("select#cptIcdProcedureSelect").html(options);
};
I also think chart.Boxplot is the best option, it gives you the position of the mean but if you have a matrix with returns all you need is one line of code to get all the boxplots in one graph.
Here is a small ETF portfolio example.
library(zoo)
library(PerformanceAnalytics)
library(tseries)
library(xts)
VTI.prices = get.hist.quote(instrument = "VTI", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
VEU.prices = get.hist.quote(instrument = "VEU", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
VWO.prices = get.hist.quote(instrument = "VWO", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
VNQ.prices = get.hist.quote(instrument = "VNQ", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
TLT.prices = get.hist.quote(instrument = "TLT", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
TIP.prices = get.hist.quote(instrument = "TIP", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
index(VTI.prices) = as.yearmon(index(VTI.prices))
index(VEU.prices) = as.yearmon(index(VEU.prices))
index(VWO.prices) = as.yearmon(index(VWO.prices))
index(VNQ.prices) = as.yearmon(index(VNQ.prices))
index(TLT.prices) = as.yearmon(index(TLT.prices))
index(TIP.prices) = as.yearmon(index(TIP.prices))
Prices.z=merge(VTI.prices, VEU.prices, VWO.prices, VNQ.prices,
TLT.prices, TIP.prices)
colnames(Prices.z) = c("VTI", "VEU", "VWO" , "VNQ", "TLT", "TIP")
returnscc.z = diff(log(Prices.z))
start(returnscc.z)
end(returnscc.z)
colnames(returnscc.z)
head(returnscc.z)
Return Matrix
ret.mat = coredata(returnscc.z)
class(ret.mat)
colnames(ret.mat)
head(ret.mat)
Box Plot of Return Matrix
chart.Boxplot(returnscc.z, names=T, horizontal=TRUE, colorset="darkgreen", as.Tufte =F,
mean.symbol = 20, median.symbol="|", main="Return Distributions Comparison",
element.color = "darkgray", outlier.symbol = 20,
xlab="Continuously Compounded Returns", sort.ascending=F)
You can try changing the mean.symbol, and remove or change the median.symbol. Hope it helped. :)
The methods are "basically" the same, except handling null.
Pen pen = null;
Convert.ToString(pen); // No exception thrown
pen.ToString(); // Throws NullReferenceException
From MSDN :
Convert.ToString Method
Converts the specified value to its equivalent string representation.
Returns a string that represents the current object.
cd C:\Users\mxsof\AppData\Local\Android\Sdk\emulator
emulator -avd pixel_2_api_29
That's all. Happy coding!
If you are on SQL Server 2008 or later you can use the date datatype:
SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2014-02-07'
It should be noted that if date column is indexed then this will still utilise the index and is SARGable. This is a special case for dates and datetimes.
You can see that SQL Server actually turns this into a > and < clause:
I've just tried this on a large table, with a secondary index on the date column as per @kobik's comments and the index is still used, this is not the case for the examples that use BETWEEN or >= and <:
SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2016-07-05'
Enable the "strip" extension and type the following:
hg strip #changeset# --keep
Where #changeset#
is the hash for the changeset you want to remove. This will remove the said changeset including changesets that descend from it and will leave your working directory untouched. If you wish to also revert your committed code changes remove the --keep
option.
For more information, check the Strip Extension.
If you get "unkown command 'strip'" you may need to enable it. To do so find the .hgrc
or Mercurial.ini
file and add the following to it:
[extensions]
strip =
Note that (as Juozas mentioned in his comment) having multiple heads is normal workflow in Mercurial. You should not use the strip command to battle that. Instead, you should merge your head with the incoming head, resolve any conflicts, test, and then push.
The strip
command is useful when you really want to get rid of changesets that pollute the branch. In fact, if you're in this question's situation and you want to completely remove all "draft" change sets permanently, check out the top answer, which basically suggests doing:
hg strip 'roots(outgoing())'
Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.
As noted in the comments, when you loop over a list with something like for member in my_list
the member
variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:
my_list = [1,2,3]
for member in my_list:
member = 42
print my_list
Output:
[1, 2, 3]
If you want to change a list containing immutable types, you need to do something like:
my_list = [1,2,3]
for ndx, member in enumerate(my_list):
my_list[ndx] += 42
print my_list
Output:
[43, 44, 45]
If your list contains mutable objects, you can modify the current member
object directly:
class C:
def __init__(self, n):
self.num = n
def __repr__(self):
return str(self.num)
my_list = [C(i) for i in xrange(3)]
for member in my_list:
member.num += 42
print my_list
[42, 43, 44]
Note that you are still not changing the list, simply modifying the objects in the list.
You might benefit from reading Naming and Binding.
I modified the solution of Andre Luis IM I achieved this one:
I created a utility method to hide the soft keyboard the same way Andre Luiz IM did:
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
But instead of register an OnTouchListener for every view, that give a poor performance, I registered the OnTouchListener for just the root view. Since the event bubbles until it's consumed (EditText is one of the views that consumes it by default), if it arrives to the root view, it's because it wasn't consumed, so I close the soft keyboard.
findViewById(android.R.id.content).setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Utils.hideSoftKeyboard(activity);
return false;
}
});
You want a check constraint.
CHECK constraints determine the valid values from a logical expression that is not based on data in another column. For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows for only data that ranges from $15,000 through $100,000. This prevents salaries from being entered beyond the regular salary range.
You want something like:
ALTER TABLE dbo.Table ADD CONSTRAINT CK_Table_Frequency
CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))
You can also implement check constraints with scalar functions, as described in the link above, which is how I prefer to do it.
Use the std::getline()
from <string>
.
istream & getline(istream & is,std::string& str)
So, for your case it would be:
std::getline(read,x);
A solution would be to declare your key as nvarchar(20)
.
Not as a command, but this information is in the registry:
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
CurrentVersion
REG_SZJava Runtime Environment
named with the CurrentVersion
valueJavaHome
REG_SZ to get the pathFor example on my workstation i have
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
JavaHome = "C:\Program Files\Java\jre6"
So my current JRE is in C:\Program Files\Java\jre6
In MySQL, these symbols are used to delimit a query `
,"
,'
and ()
.
"
or '
are used for enclosing string-like values "26-01-2014 00:00:00"
or '26-01-2014 00:00:00'
. These symbols are only for strings, not aggregate functions like now
, sum
, or max
.
`
is used for enclosing table or column names, e.g. select `column_name` from `table_name` where id='2'
(
and )
simply enclose parts of a query e.g. select `column_name` from `table_name` where (id='2' and gender='male') or name='rakesh'
.
nodeName will give you the tag name in uppercase, while localName will give you the lower case.
$("yourelement")[0].localName
will give you : yourelement instead of YOURELEMENT
You can use an IF statement to check the referenced cell(s) and return one result for zero or blank, and otherwise return your formula result.
A simple example:
=IF(B1=0;"";A1/B1)
This would return an empty string if the divisor B1 is blank or zero; otherwise it returns the result of dividing A1 by B1.
In your case of running an average, you could check to see whether or not your data set has a value:
=IF(SUM(K23:M23)=0;"";AVERAGE(K23:M23))
If there is nothing entered, or only zeros, it returns an empty string; if one or more values are present, you get the average.
I use
Math.floor(new Date().valueOf() * Math.random())
So if by any chance the code is fired at the same time there is also a teeny chance that the random numbers will be the same.
Adding to Aditya Guru's answer here. There is no need of using map. You can do it simply by:
pd.DataFrame(list(zip(lst1, lst2, lst3)))
This will set the column's names as 0,1,2. To set your own column names, you can pass the keyword argument columns
to the method above.
pd.DataFrame(list(zip(lst1, lst2, lst3)),
columns=['lst1_title','lst2_title', 'lst3_title'])
I've also seen
x <- {}
Now you can concatenate or bind a vector of any dimension to x
rbind(x, 1:10)
cbind(x, 1:10)
c(x, 10)
There is already a command in the ssh suite to do this automatically for you. I.e log into a remote host and add the public key to that computers authorized_keys file.
ssh-copy-id -i /path/to/key/file [email protected]
If the key you are installing is ~/.ssh/id_rsa
then you can even drop the -i
flag completely.
Much better than manually doing it!
You can split on an empty string:
var chars = "overpopulation".split('');
If you just want to access a string in an array-like fashion, you can do that without split
:
var s = "overpopulation";
for (var i = 0; i < s.length; i++) {
console.log(s.charAt(i));
}
You can also access each character with its index using normal array syntax. Note, however, that strings are immutable, which means you can't set the value of a character using this method, and that it isn't supported by IE7 (if that still matters to you).
var s = "overpopulation";
console.log(s[3]); // logs 'r'
This is an interesting problem to which I hoped there was an elegant solution. Sadly, I end up with a solution similar to Mr. Leffler, but I'll add that you can call useless from inside a Bash function for improved readability:
#!/bin/bash function useless { /tmp/useless.sh | sed 's/Output/Useless/' } ERROR=$(useless) echo $ERROR
All other kind of output redirection must be backed by a temporary file.
Try this:
div.topmenu-design ul
{
display:block;
width:600px; /* or whatever width value */
margin:0px auto;
}
You may drag'n'drop your folder to Side bar. To enable Side bar you should do View -> Side bar -> show opened files. You'll got opened files (tabs) tree and folder structure at Side bar.
With splitext there are problems with files with double extension (e.g. file.tar.gz
, file.tar.bz2
, etc..)
>>> fileName, fileExtension = os.path.splitext('/path/to/somefile.tar.gz')
>>> fileExtension
'.gz'
but should be: .tar.gz
The possible solutions are here