It's even possible to restore without creating a blank database at all.
In Sql Server Management Studio, right click on Databases and select Restore Database...
In the Restore Database dialog, select the Source Database or Device as normal. Once the source database is selected, SSMS will populate the destination database name based on the original name of the database.
It's then possible to change the name of the database and enter a new destination database name.
With this approach, you don't even need to go to the Options tab and click the "Overwrite the existing database" option.
Also, the database files will be named consistently with your new database name and you still have the option to change file names if you want.
Writing the followin code to print anything on LogCat works perfectly fine!!
int score=0;
score++;
System.out.println(score);
prints score on LogCat.Try this
In my own findings, I think it's good to mention that you (as far as I can tell) must declare the full namespace path of a class.
MyClass.php
namespace com\company\lib;
class MyClass {
}
index.php
namespace com\company\lib;
//Works fine
$i = new MyClass();
$cname = 'MyClass';
//Errors
//$i = new $cname;
//Works fine
$cname = "com\\company\\lib\\".$cname;
$i = new $cname;
Code posted by you is correct and should have worked. But check exactly what you have in the char*
. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL
. Check what you have in the char*
against maximum values that float
and double
can represent on your computer.
Check this page for strtod
reference and this page for atof
reference.
I have tried the example you provided in both Windows and Linux and it worked fine.
I was encountering this error while compiling my application with SDL. This was caused by SDL defining it's own main function in SDL_main.h. To prevent SDL define the main function an SDL_MAIN_HANDLED macro has to be defined before the SDL.h header is included.
There are a few ways depending on what version you have - see the oracle documentation on string aggregation techniques. A very common one is to use LISTAGG
:
SELECT pid, LISTAGG(Desc, ' ') WITHIN GROUP (ORDER BY seq) AS description
FROM B GROUP BY pid;
Then join to A
to pick out the pids
you want.
Note: Out of the box, LISTAGG
only works correctly with VARCHAR2
columns.
Using executeUpdate()
on the Query
API is faster because it bypasses the persistent context .However , by-passing persistent context would cause the state of instance in the memory and the actual values of that record in the DB are not synchronized.
Consider the following example :
Employee employee= (Employee)entityManager.find(Employee.class , 1);
entityManager
.createQuery("update Employee set name = \'xxxx\' where id=1")
.executeUpdate();
After flushing, the name in the DB is updated to the new value but the employee instance in the memory still keeps the original value .You have to call entityManager.refresh(employee)
to reload the updated name from the DB to the employee instance.It sounds strange if your codes still have to manipulate the employee instance after flushing but you forget to refresh() the employee instance as the employee instance still contains the original values.
Normally , executeUpdate()
is used in the bulk update process as it is faster due to bypassing the persistent context
The right way to update an entity is that you just set the properties you want to updated through the setters and let the JPA to generate the update SQL for you during flushing instead of writing it manually.
Employee employee= (Employee)entityManager.find(Employee.class ,1);
employee.setName("Updated Name");
var someVr= element[0].querySelector('#showSelector');
myfunction(){
alert("hi");
}
angular.element(someVr).ready(function () {
myfunction();
});
This will do the job.
Operations on integers are exact. double
is a floating point data type, and floating point operations are approximate whenever there's a fraction.
double
also takes up twice as much space as int
in many implementations (e.g. most 32-bit systems) .
After reading all the above answers one by one I cant stop myself from posting that
abstraction involves the facility to define objects that represent abstract "actors" that can perform work, report on and change their state, and "communicate" with other objects in the system.
Encapsulation is quite clear from above however ->
The term encapsulation refers to the hiding of state details, but extending the concept of data type from earlier programming languages to associate behavior most strongly with the data, and standardizing the way that different data types interact, is the beginning of abstraction.
reference wiki
$location won't help you with external URLs, use the $window service instead:
$window.location.href = 'http://www.google.com';
Note that you could use the window object, but it is bad practice since $window is easily mockable whereas window is not.
According to the help of cmake
:
-C <initial-cache>
Pre-load a script to populate the cache.
When cmake is first run in an empty build tree, it creates a CMakeCache.txt file and populates it with customizable settings for the project. This option may be used to specify a file from
which to load cache entries before the first pass through the project's cmake listfiles. The loaded entries take priority over the project's default values. The given file should be a CMake
script containing SET commands that use the CACHE option, not a cache-format file.
You make be able to create files like gcc_compiler.txt
and clang_compiler.txt
to includes all relative configuration in CMake syntax.
Clang Example (clang_compiler.txt):
set(CMAKE_C_COMPILER "/usr/bin/clang" CACHE string "clang compiler" FORCE)
Then run it as
GCC:
cmake -C gcc_compiler.txt XXXXXXXX
Clang:
cmake -C clang_compiler.txt XXXXXXXX
What I did to solve the problem was:
git pull origin [branch]
git push origin [branch]
Also make sure that you are pointing to the right branch by running:
git remote set-url origin [url]
For a given iterable, more_itertools.locate
yields positions of items that satisfy a predicate.
import more_itertools as mit
iterable = [
{"id": "1234", "name": "Jason"},
{"id": "2345", "name": "Tom"},
{"id": "3456", "name": "Art"}
]
list(mit.locate(iterable, pred=lambda d: d["name"] == "Tom"))
# [1]
more_itertools
is a third-party library that implements itertools recipes among other useful tools.
I think most of these solutions are far too complicated. I assume that in your test controller you have this
@Autowired
private ObjectMapper objectMapper;
If its a rest service
@Test
public void test() throws Exception {
mockMvc.perform(post("/person"))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(new Person()))
...etc
}
For spring mvc using a posted form I came up with this solution. (Not really sure if its a good idea yet)
private MultiValueMap<String, String> toFormParams(Object o, Set<String> excludeFields) throws Exception {
ObjectReader reader = objectMapper.readerFor(Map.class);
Map<String, String> map = reader.readValue(objectMapper.writeValueAsString(o));
MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
map.entrySet().stream()
.filter(e -> !excludeFields.contains(e.getKey()))
.forEach(e -> multiValueMap.add(e.getKey(), (e.getValue() == null ? "" : e.getValue())));
return multiValueMap;
}
@Test
public void test() throws Exception {
MultiValueMap<String, String> formParams = toFormParams(new Phone(),
Set.of("id", "created"));
mockMvc.perform(post("/person"))
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.params(formParams))
...etc
}
The basic idea is to
- first convert object to json string to get all the field names easily
- convert this json string into a map and dump it into a MultiValueMap
that spring expects. Optionally filter out any fields you dont want to include (Or you could just annotate fields with @JsonIgnore
to avoid this extra step)
I quote from http://www.php.net/manual/en/language.oop5.visibility.php
Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an
E_STRICT
warning.
To print your context ,you can write code like this :
FILE *fp;
char *of;
sprintf(of,"%s%s",text1,text2);
fp=fopen(of,'w');
fprintf(fp,"your print line");
The answer is to not use a regular expression. This is sets and counting.
Regular expressions are about order.
In your life as a programmer you will asked to do many things that do not make sense. Learn to dig a level deeper. Learn when the question is wrong.
The question (if it mentioned regular expressions) is wrong.
Pseudocode (been switching between too many languages, of late):
if s.length < 8:
return False
nUpper = nLower = nAlphanum = nSpecial = 0
for c in s:
if isUpper(c):
nUpper++
if isLower(c):
nLower++
if isAlphanumeric(c):
nAlphanum++
if isSpecial(c):
nSpecial++
return (0 < nUpper) and (0 < nAlphanum) and (0 < nSpecial)
Bet you read and understood the above code almost instantly. Bet you took much longer with the regex, and are less certain it is correct. Extending the regex is risky. Extended the immediate above, much less so.
Note also the question is imprecisely phrased. Is the character set ASCII or Unicode, or ?? My guess from reading the question is that at least one lowercase character is assumed. So I think the assumed last rule should be:
return (0 < nUpper) and (0 < nLower) and (0 < nAlphanum) and (0 < nSpecial)
(Changing hats to security-focused, this is a really annoying/not useful rule.)
Learning to know when the question is wrong is massively more important than clever answers. A clever answer to the wrong question is almost always wrong.
MongoDB needs data directory to store data.
Default path is /data/db
When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx
permission to user.
If you want to change the path of your data directory then you should specify it while starting mongod server like,
mongod --dbpath /data/<path> --port <port no>
This should help you start your mongod server with custom path and port.
Enable CORS on backend server or add chrome extensions https://chrome.google.com/webstore/search/CORS?utm_source=chrome-ntp-icon and make ON
basically if you already specify the year range there is no need to use mindate
and maxdate
if only year is required
I needed this feature just form my app 'models' (raw backend data converted to objects). So I ended up using a combination of Object.create (create new object from specified prototype) and Object.assign (copy properties between objects). Need to handle the deep copy manually. I created a gist for this.
To return the queryset you retrieved with queryset = Users.objects.all(),
you first need to serialize them.
Serialization is the process of converting one data structure to another. Using Class-Based Views, you could return JSON like this.
from django.core.serializers import serialize
from django.http import JsonResponse
from django.views.generic import View
class JSONListView(View):
def get(self, request, *args, **kwargs):
qs = User.objects.all()
data = serialize("json", qs)
return JsonResponse(data)
This will output a list of JSON. For more detail on how this works, check out my blog article How to return a JSON Response with Django. It goes into more detail on how you would go about this.
Removing the m2 plugin from startup-up plugin's list and doing a Maven->Update Projects on all the projects worked for me.
Note** One should not create additional folders to avoid merging them while using SVN/Git based branches.
Use win APIs in your main function:
Then write another function which handles win's messages (mentioned in #1). When you receive the message WM_CREATE you have to call CreateWindow(). The class is what control is that window, for example "edit" is a text box and "button" is a.. button :). You have to specify an ID for each control (of your choice but unique among all). CreateWindow() returns a handle to that control, which needs to be memorized. When the user clicks on a control you receive the WM_COMMAND message with the ID of that control. Here you can handle that event. You might find useful SetWindowText() and GetWindowText() which allows you to set/get the text of any control.
You will need only the win32 SDK. You can get it here.
I think git pull --rebase
is the cleanest way to set your locally recent commits on top of the remote commits which you don't have at a certain point.
So this way you don't have to pull every time you want to start making changes.
As we see from the javaDoc, BigInteger
is not a subclass of Integer
:
java.lang.Object java.lang.Object
java.lang.Number java.lang.Number
java.math.BigInteger java.lang.Integer
And that's the reason why casting from BigInteger
to Integer
is impossible.
Casting of java primitives will do some conversion (like casting from double
to int
) while casting of types will never transform classes.
Internet Explorer 8 (and earlier versions) doesn't support rounded corners, however there are few other solutions you may consider:
Use Rounded Corners Images
instead (this generator is a good resource)
Use a jQuery Corner plugin
from here
Use a very good script called CSS3 PIE
from here (Pro's & Con's here)
Checkout CSS Juice
from here
Another good script is IE-CSS3
from here
Even though CSS PIE is the most popular solution, I'm suggesting you to review all other solutions and choose what works best for your needs.
Hope it was useful. Good Luck!
@echo off
del /s /f /q %windir%\temp\*.*
rd /s /q %windir%\temp
md %windir%\temp
del /s /f /q %windir%\Prefetch\*.*
rd /s /q %windir%\Prefetch
md %windir%\Prefetch
del /s /f /q %windir%\system32\dllcache\*.*
rd /s /q %windir%\system32\dllcache
md %windir%\system32\dllcache
del /s /f /q "%SysteDrive%\Temp"\*.*
rd /s /q "%SysteDrive%\Temp"
md "%SysteDrive%\Temp"
del /s /f /q %temp%\*.*
rd /s /q %temp%
md %temp%
del /s /f /q "%USERPROFILE%\Local Settings\History"\*.*
rd /s /q "%USERPROFILE%\Local Settings\History"
md "%USERPROFILE%\Local Settings\History"
del /s /f /q "%USERPROFILE%\Local Settings\Temporary Internet Files"\*.*
rd /s /q "%USERPROFILE%\Local Settings\Temporary Internet Files"
md "%USERPROFILE%\Local Settings\Temporary Internet Files"
del /s /f /q "%USERPROFILE%\Local Settings\Temp"\*.*
rd /s /q "%USERPROFILE%\Local Settings\Temp"
md "%USERPROFILE%\Local Settings\Temp"
del /s /f /q "%USERPROFILE%\Recent"\*.*
rd /s /q "%USERPROFILE%\Recent"
md "%USERPROFILE%\Recent"
del /s /f /q "%USERPROFILE%\Cookies"\*.*
rd /s /q "%USERPROFILE%\Cookies"
md "%USERPROFILE%\Cookies"
You Need to take same height and width
and simply use the border-radius:360px;
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
You need to change
onclick='btnClick();'
to
onclick='return btnClick();'
and
cancelFormSubmission();
to
return false;
That said, I'd try to avoid the intrinsic event attributes in favour of unobtrusive JS with a library (such as YUI or jQuery) that has a good event handling API and tie into the event that really matters (i.e. the form's submit event instead of the button's click event).
If the scenario is appending a new row dynamically, you can use this:
var row = $(".myRow").last().clone();
$(".myRow").last().after(row);
.myrow
is the classname of the <tr>
. It makes a copy of the last row and inserts that as a new last row.
This also works in IE7, while the [0].outerHTML
method does not allow assignments in ie7
To complement the Perl one-liner, here's its awk
equivalent:
awk 'NR==FNR{arr[$0];next} $0 in arr' file1 file2
This will read all lines from file1
into the array arr[]
, and then check for each line in file2
if it already exists within the array (i.e. file1
). The lines that are found will be printed in the order in which they appear in file2
.
Note that the comparison in arr
uses the entire line from file2
as index to the array, so it will only report exact matches on entire lines.
You need to git add my_project
to stage your new folder. Then git add my_project/*
to stage its contents. Then commit what you've staged using git commit
and finally push your changes back to the source using git push origin master
(I'm assuming you wish to push to the master branch).
The cleanest way is use a function of janitor
package that is built for exactly this purpose.
janitor::row_to_names(DF,1)
If you want to use any other row than the first one, pass it in the second parameter.
These are some pros of the two most used libraries I would have benefit to know before choosing between them.
standalone="no"
? .node
.sourceline
allows to easily get the line of the XML element you are using.Eclipse Runnable JAR File
Create a Java Project – RunnableJAR
Main Class
public class RunnableMainClass {
public static void main(String[] args) throws InterruptedException {
System.out.println("Name : "+args[0]);
System.out.println(" ID : "+args[1]);
}
}
Run Jar file using java program (cmd) by supplying arguments and get the output and display in eclipse console.
public class RunJar {
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
String jarfile = "D:\\JarLocation\\myRunnable.jar";
String name = "Yash";
String id = "777";
try { // jarname arguments has to be saperated by spaces
Process process = Runtime.getRuntime().exec("cmd.exe start /C java -jar "+jarfile+" "+name+" "+id);
//.exec("cmd.exe /C start dir java -jar "+jarfile+" "+name+" "+id+" dir");
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream ()));
String line = null;
while ((line = br.readLine()) != null){
sb.append(line).append("\n");
}
System.out.println("Console OUTPUT : \n"+sb.toString());
process.destroy();
}catch (Exception e){
System.err.println(e.getMessage());
}
}
}
In Eclipse to find Short cuts:
Help ? Help Contents ? Java development user guide ? References ? Menus and Actions
For the MVC Controller method, use a nullable boolean type:
public ActionResult Index( string responsables, bool? checkResp) { etc. }
Then if the check box is checked, checkResp will be true. If not, it will be null.
A2 = [float(x.strip('"')) for x in A1]
works, @Jake , but there are unnecessary 0s
Blanket.js works perfect too.
npm install --save-dev blanket
in front of your test/tests.js
require('blanket')({
pattern: function (filename) {
return !/node_modules/.test(filename);
}
});
run mocha -R html-cov > coverage.html
For Angular RC5 and RC6 you have to declare component in the module metadata decorator's declarations
key, so add CoursesComponent
in your main module declarations
as below and remove directives
from AppComponent
metadata.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, CoursesComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Use the powershell pipeline to get packages and remove in single statement like this
Get-Package | Uninstall-Package
if you want to uninstall selected packages follow these steps
GetPackages
to get the list of packages GetPackages
in NimbleText(For each row in the list window)(
if requiredUninstall-Package $0
(Substitute using pattern window)That be all folks.
For those late-comers that are looking for a solution that "just works":
#include <utility>
#include <iostream>
template< typename T >
class Y {
template< bool cond, typename U >
using resolvedType = typename std::enable_if< cond, U >::type;
public:
template< typename U = T >
resolvedType< true, U > foo() {
return 11;
}
template< typename U = T >
resolvedType< false, U > foo() {
return 12;
}
};
int main() {
Y< double > y;
std::cout << y.foo() << std::endl;
}
Compile with:
g++ -std=gnu++14 test.cpp
Running gives:
./a.out
11
You must to add a needle headers:
Sample code :
$headers = "From: [email protected]\r\n";
$headers .= "Reply-To: [email protected]\r\n";
$headers .= "Return-Path: [email protected]\r\n";
$headers .= "CC: [email protected]\r\n";
$headers .= "BCC: [email protected]\r\n";
if ( mail($to,$subject,$message,$headers) ) {
echo "The email has been sent!";
} else {
echo "The email has failed!";
}
?>
To send CDATA in a request object use the SoapObject.setInnerText("...");
method.
Must be used convert, not cast:
SELECT
CONVERT(varchar(50), N'æøåáälcçcédnoöruýtžš')
COLLATE Cyrillic_General_CI_AI
Set style= "display:none;"
. By setting visible=false
, it will not render button in the browser. Thus,client side script wont execute.
<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />
html markup should be
<button id="btnsave" onclick="fncsave()">Save</button>
Change javascript to
<script type="text/javascript">
function fncsave()
{
document.getElementById('<%= savebtn.ClientID %>').click();
}
</script>
try this
$('#element').on('scroll touchmove mousewheel', function(e){
e.preventDefault();
e.stopPropagation();
return false;
})
You can execute it just as you select a table using SELECT
clause. In addition you can provide parameters within parentheses.
Try with below syntax:
SELECT * FROM yourFunctionName(parameter1, parameter2)
You can do an interactive rebase:
git rebase -i <commit>
This will bring up your default editor. Just delete the line containing the commit you want to remove to delete that commit.
You will, of course, need access to the remote repository to apply this change there too.
See this question: Git: removing selected commits from repository
3.https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html
The main reason is probably that a C++ string is a struct that includes a current-length value, not just the address of a sequence of chars terminated by a 0 byte. Printf and its relatives expect to find such a sequence, not a struct, and therefore get confused by C++ strings.
Speaking for myself, I believe that printf has a place that can't easily be filled by C++ syntactic features, just as table structures in html have a place that can't easily be filled by divs. As Dykstra wrote later about the goto, he didn't intend to start a religion and was really only arguing against using it as a kludge to make up for poorly-designed code.
It would be quite nice if the GNU project would add the printf family to their g++ extensions.
Define a property of the form like, then use this in other places it would be available with the form instance
public string SetText
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
As I wanted a full fledged BiDirectional Dictionary (and not only a Map), I added the missing functions to make it an IDictionary compatible class. This is based on the version with unique Key-Value Pairs. Here's the file if desired (Most work was the XMLDoc through):
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common
{
/// <summary>Represents a bidirectional collection of keys and values.</summary>
/// <typeparam name="TFirst">The type of the keys in the dictionary</typeparam>
/// <typeparam name="TSecond">The type of the values in the dictionary</typeparam>
[System.Runtime.InteropServices.ComVisible(false)]
[System.Diagnostics.DebuggerDisplay("Count = {Count}")]
//[System.Diagnostics.DebuggerTypeProxy(typeof(System.Collections.Generic.Mscorlib_DictionaryDebugView<,>))]
//[System.Reflection.DefaultMember("Item")]
public class BiDictionary<TFirst, TSecond> : Dictionary<TFirst, TSecond>
{
IDictionary<TSecond, TFirst> _ValueKey = new Dictionary<TSecond, TFirst>();
/// <summary> PropertyAccessor for Iterator over KeyValue-Relation </summary>
public IDictionary<TFirst, TSecond> KeyValue => this;
/// <summary> PropertyAccessor for Iterator over ValueKey-Relation </summary>
public IDictionary<TSecond, TFirst> ValueKey => _ValueKey;
#region Implemented members
/// <Summary>Gets or sets the value associated with the specified key.</Summary>
/// <param name="key">The key of the value to get or set.</param>
/// <Returns>The value associated with the specified key. If the specified key is not found,
/// a get operation throws a <see cref="KeyNotFoundException"/>, and
/// a set operation creates a new element with the specified key.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
/// The property is retrieved and <paramref name="key"/> does not exist in the collection.</exception>
/// <exception cref="T:System.ArgumentException"> An element with the same key already
/// exists in the <see cref="ValueKey"/> <see cref="Dictionary<TFirst,TSecond>"/>.</exception>
public new TSecond this[TFirst key]
{
get { return base[key]; }
set { _ValueKey.Remove(base[key]); base[key] = value; _ValueKey.Add(value, key); }
}
/// <Summary>Gets or sets the key associated with the specified value.</Summary>
/// <param name="val">The value of the key to get or set.</param>
/// <Returns>The key associated with the specified value. If the specified value is not found,
/// a get operation throws a <see cref="KeyNotFoundException"/>, and
/// a set operation creates a new element with the specified value.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="val"/> is null.</exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
/// The property is retrieved and <paramref name="val"/> does not exist in the collection.</exception>
/// <exception cref="T:System.ArgumentException"> An element with the same value already
/// exists in the <see cref="KeyValue"/> <see cref="Dictionary<TFirst,TSecond>"/>.</exception>
public TFirst this[TSecond val]
{
get { return _ValueKey[val]; }
set { base.Remove(_ValueKey[val]); _ValueKey[val] = value; base.Add(value, val); }
}
/// <Summary>Adds the specified key and value to the dictionary.</Summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="value">The value of the element to add.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> or <paramref name="value"/> is null.</exception>
/// <exception cref="T:System.ArgumentException">An element with the same key or value already exists in the <see cref="Dictionary<TFirst,TSecond>"/>.</exception>
public new void Add(TFirst key, TSecond value) {
base.Add(key, value);
_ValueKey.Add(value, key);
}
/// <Summary>Removes all keys and values from the <see cref="Dictionary<TFirst,TSecond>"/>.</Summary>
public new void Clear() { base.Clear(); _ValueKey.Clear(); }
/// <Summary>Determines whether the <see cref="Dictionary<TFirst,TSecond>"/> contains the specified
/// KeyValuePair.</Summary>
/// <param name="item">The KeyValuePair to locate in the <see cref="Dictionary<TFirst,TSecond>"/>.</param>
/// <Returns>true if the <see cref="Dictionary<TFirst,TSecond>"/> contains an element with
/// the specified key which links to the specified value; otherwise, false.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="item"/> is null.</exception>
public bool Contains(KeyValuePair<TFirst, TSecond> item) => base.ContainsKey(item.Key) & _ValueKey.ContainsKey(item.Value);
/// <Summary>Removes the specified KeyValuePair from the <see cref="Dictionary<TFirst,TSecond>"/>.</Summary>
/// <param name="item">The KeyValuePair to remove.</param>
/// <Returns>true if the KeyValuePair is successfully found and removed; otherwise, false. This
/// method returns false if <paramref name="item"/> is not found in the <see cref="Dictionary<TFirst,TSecond>"/>.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="item"/> is null.</exception>
public bool Remove(KeyValuePair<TFirst, TSecond> item) => base.Remove(item.Key) & _ValueKey.Remove(item.Value);
/// <Summary>Removes the value with the specified key from the <see cref="Dictionary<TFirst,TSecond>"/>.</Summary>
/// <param name="key">The key of the element to remove.</param>
/// <Returns>true if the element is successfully found and removed; otherwise, false. This
/// method returns false if <paramref name="key"/> is not found in the <see cref="Dictionary<TFirst,TSecond>"/>.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
public new bool Remove(TFirst key) => _ValueKey.Remove(base[key]) & base.Remove(key);
/// <Summary>Gets the key associated with the specified value.</Summary>
/// <param name="value">The value of the key to get.</param>
/// <param name="key">When this method returns, contains the key associated with the specified value,
/// if the value is found; otherwise, the default value for the type of the key parameter.
/// This parameter is passed uninitialized.</param>
/// <Returns>true if <see cref="ValueKey"/> contains an element with the specified value;
/// otherwise, false.</Returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="value"/> is null.</exception>
public bool TryGetValue(TSecond value, out TFirst key) => _ValueKey.TryGetValue(value, out key);
#endregion
}
}
Use drawalbeLeft/Right/Bottom/Top in TextView to render image at respective position.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/image"
android:text="@strings/text"
/>
You can try
int sum = list.stream().filter(o->o.field>10).mapToInt(o->o.field).sum();
Like explained here
The command docker build --no-cache .
solved our similar problem.
Our Dockerfile was:
RUN apt-get update
RUN apt-get -y install php5-fpm
But should have been:
RUN apt-get update && apt-get -y install php5-fpm
To prevent caching the update and install separately.
By the looks of it you need to actually pass drawImage an image object like so
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
I've tried it in chrome and it works fine.
In Windows Forms, if your string is in a textbox, you can easily use this:
textBoxcsharp.SelectAll();
textBoxcsharp.Copy();
textBoxcsharp.DeselectAll();
In order to perform chmod, you need to be owner of the file you are trying to modify, or the root user.
Try this:
XmlDocument bodyDoc = new XmlDocument();
bodyDoc.XMLResolver = null;
bodyDoc.Load(body);
The number of column parameters in your insert query is 9, but you've only provided 8 values.
INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
The query should omit the "id" parameter, because it is auto-generated (or should be anyway):
INSERT INTO dbname (Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
Below, is the most clean, comprehensible way of merging multiple dataframe if complex queries aren't involved.
Just simply merge with DATE as the index and merge using OUTER method (to get all the data).
import pandas as pd
from functools import reduce
df1 = pd.read_table('file1.csv', sep=',')
df2 = pd.read_table('file2.csv', sep=',')
df3 = pd.read_table('file3.csv', sep=',')
Now, basically load all the files you have as data frame into a list. And, then merge the files using merge
or reduce
function.
# compile the list of dataframes you want to merge
data_frames = [df1, df2, df3]
Note: you can add as many data-frames inside the above list. This is the good part about this method. No complex queries involved.
To keep the values that belong to the same date you need to merge it on the DATE
df_merged = reduce(lambda left,right: pd.merge(left,right,on=['DATE'],
how='outer'), data_frames)
# if you want to fill the values that don't exist in the lines of merged dataframe simply fill with required strings as
df_merged = reduce(lambda left,right: pd.merge(left,right,on=['DATE'],
how='outer'), data_frames).fillna('void')
Then write the merged data to the csv file if desired.
pd.DataFrame.to_csv(df_merged, 'merged.txt', sep=',', na_rep='.', index=False)
This should give you
DATE VALUE1 VALUE2 VALUE3 ....
Empty lists evaluate to False in boolean contexts (such as if some_list:
).
When you are passing the custom request in the controller method, and your request file doesn't follow the proper syntax or table name is changed, then laravel through this type of exception. I'll show you in Example.
My Request code.
public function rules()
{
return [
'name' => 'required|unique:posts|max:50',
'description' => 'required',
];
}
But my table name is todos not posts so that's why it through "Base table or view not found: 1146 Table Laravel 7
I forgot to change the table name in first index.
public function rules()
{
return [
'name' => 'required|unique:todos|max:50',
'description' => 'required',
];
}
I could not use HtmlAgilityPack, so I wrote a second best solution for myself
private static string HtmlToPlainText(string html)
{
const string tagWhiteSpace = @"(>|$)(\W|\n|\r)+<";//matches one or more (white space or line breaks) between '>' and '<'
const string stripFormatting = @"<[^>]*(>|$)";//match any character between '<' and '>', even when end tag is missing
const string lineBreak = @"<(br|BR)\s{0,1}\/{0,1}>";//matches: <br>,<br/>,<br />,<BR>,<BR/>,<BR />
var lineBreakRegex = new Regex(lineBreak, RegexOptions.Multiline);
var stripFormattingRegex = new Regex(stripFormatting, RegexOptions.Multiline);
var tagWhiteSpaceRegex = new Regex(tagWhiteSpace, RegexOptions.Multiline);
var text = html;
//Decode html specific characters
text = System.Net.WebUtility.HtmlDecode(text);
//Remove tag whitespace/line breaks
text = tagWhiteSpaceRegex.Replace(text, "><");
//Replace <br /> with line breaks
text = lineBreakRegex.Replace(text, Environment.NewLine);
//Strip formatting
text = stripFormattingRegex.Replace(text, string.Empty);
return text;
}
I have added reCaptcha to a project I'm currently working on. I needed it to use the AJAX API as the reCaptcha element was loaded into the page dynamically. I couldn't find any existing controls and the API is simple so I created my own.
I'll post my code here in case anyone finds it useful.
1: Add the script tag to the master page headers
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
2: Add your keys to the web.config
<appSettings>
<add key="ReCaptcha.PrivateKey" value="[key here]" />
<add key="ReCaptcha.PublicKey" value="[key here]" />
</appSettings>
3: Create the Action Attribute and Html Helper extensions
namespace [Your chosen namespace].ReCaptcha
{
public enum Theme { Red, White, BlackGlass, Clean }
[Serializable]
public class InvalidKeyException : ApplicationException
{
public InvalidKeyException() { }
public InvalidKeyException(string message) : base(message) { }
public InvalidKeyException(string message, Exception inner) : base(message, inner) { }
}
public class ReCaptchaAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var userIP = filterContext.RequestContext.HttpContext.Request.UserHostAddress;
var privateKey = ConfigurationManager.AppSettings.GetString("ReCaptcha.PrivateKey", "");
if (string.IsNullOrWhiteSpace(privateKey))
throw new InvalidKeyException("ReCaptcha.PrivateKey missing from appSettings");
var postData = string.Format("&privatekey={0}&remoteip={1}&challenge={2}&response={3}",
privateKey,
userIP,
filterContext.RequestContext.HttpContext.Request.Form["recaptcha_challenge_field"],
filterContext.RequestContext.HttpContext.Request.Form["recaptcha_response_field"]);
var postDataAsBytes = Encoding.UTF8.GetBytes(postData);
// Create web request
var request = WebRequest.Create("http://www.google.com/recaptcha/api/verify");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataAsBytes.Length;
var dataStream = request.GetRequestStream();
dataStream.Write(postDataAsBytes, 0, postDataAsBytes.Length);
dataStream.Close();
// Get the response.
var response = request.GetResponse();
using (dataStream = response.GetResponseStream())
{
using (var reader = new StreamReader(dataStream))
{
var responseFromServer = reader.ReadToEnd();
if (!responseFromServer.StartsWith("true"))
((Controller)filterContext.Controller).ModelState.AddModelError("ReCaptcha", "Captcha words typed incorrectly");
}
}
}
}
public static class HtmlHelperExtensions
{
public static MvcHtmlString GenerateCaptcha(this HtmlHelper helper, Theme theme, string callBack = null)
{
const string htmlInjectString = @"<div id=""recaptcha_div""></div>
<script type=""text/javascript"">
Recaptcha.create(""{0}"", ""recaptcha_div"", {{ theme: ""{1}"" {2}}});
</script>";
var publicKey = ConfigurationManager.AppSettings.GetString("ReCaptcha.PublicKey", "");
if (string.IsNullOrWhiteSpace(publicKey))
throw new InvalidKeyException("ReCaptcha.PublicKey missing from appSettings");
if (!string.IsNullOrWhiteSpace(callBack))
callBack = string.Concat(", callback: ", callBack);
var html = string.Format(htmlInjectString, publicKey, theme.ToString().ToLower(), callBack);
return MvcHtmlString.Create(html);
}
}
}
4: Add the captcha to your view
@using (Html.BeginForm("MyAction", "MyController"))
{
@Html.TextBox("EmailAddress", Model.EmailAddress)
@Html.GenerateCaptcha(Theme.White)
<input type="submit" value="Submit" />
}
5: Add the attribute to your action
[HttpPost]
[ReCaptcha]
public ActionResult MyAction(MyModel model)
{
if (!ModelState.IsValid) // Will have a Model Error "ReCaptcha" if the user input is incorrect
return Json(new { capthcaInvalid = true });
... other stuff ...
}
6: Note you will need to reload the captcha after each post even if it was valid and another part of the form was invalid. Use Recaptcha.reload();
Seriously, question exists five years and no nice facade?
function is_dir(path) {
try {
var stat = fs.lstatSync(path);
return stat.isDirectory();
} catch (e) {
// lstatSync throws an error if path doesn't exist
return false;
}
}
Create key value pairs on the phpsh commandline like this:
php> $keyvalues = array();
php> $keyvalues['foo'] = "bar";
php> $keyvalues['pyramid'] = "power";
php> print_r($keyvalues);
Array
(
[foo] => bar
[pyramid] => power
)
Get the count of key value pairs:
php> echo count($offerarray);
2
Get the keys as an array:
php> echo implode(array_keys($offerarray));
foopyramid
require 'date'
date = DateTime.parse("2011-05-19 10:30:14")
formatted_date = date.strftime('%a %b %d %H:%M:%S %Z %Y')
See strftime() for more information about formatting dates.
To generate classes from WSDL, all you need is build-helper-maven-plugin and jaxws-maven-plugin in your pom.xml
Make sure you have placed wsdl under folder src/main/resources/wsdl and corresponding schema in src/main/resources/schema, run command "mvn generate-sources" from Project root directory.
C:/Project root directory > mvn generate-sources
generated java classes can be located under folder
target/generated/src/main/java/com/raps/code/generate/ws.
pom.xml snippet
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.9</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals><goal>add-source</goal></goals>
<configuration>
<sources>
<source>${project.build.directory}/generated/src/main/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>1.12</version>
<configuration>
<wsdlDirectory>${project.basedir}/src/main/resources/wsdl</wsdlDirectory>
<packageName>com.raps.code.generate.ws</packageName>
<keep>true</keep>
<sourceDestDir>${project.build.directory}/generated/src/main/java</sourceDestDir>
</configuration>
<executions>
<execution>
<id>myImport</id>
<goals><goal>wsimport</goal></goals>
</execution>
</executions>
</plugin>
StringTokenizer separate = new StringTokenizer(s, " ");
String word = separate.nextToken();
System.out.println(word);
Try Following code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[cellIdArray objectAtIndex:indexPath.row] forIndexPath:indexPath];
// Configure the cell...
cell.backgroundView =
[[UIImageView alloc] init] ;
cell.selectedBackgroundView =[[UIImageView alloc] init];
UIImage *rowBackground;
UIImage *selectionBackground;
rowBackground = [UIImage imageNamed:@"cellBackgroundDarkGrey.png"];
selectionBackground = [UIImage imageNamed:@"selectedMenu.png"];
((UIImageView *)cell.backgroundView).image = rowBackground;
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
return cell;
}
//Swift Version:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
cell.selectedBackgroundView = UIImageView()
cell.backgroundView=UIImageView()
let selectedBackground : UIImageView = cell.selectedBackgroundView as! UIImageView
selectedBackground.image = UIImage.init(named:"selected.png");
let backGround : UIImageView = cell.backgroundView as! UIImageView
backGround.image = UIImage.init(named:"defaultimage.png");
return cell
}
If you're using lodash and in the mood for a too-cute-for-its-own-good one-liner:
_.map(_.words('123, 124, 234,252'), _.add.bind(1, 1));
It's surprisingly robust thanks to lodash's powerful parsing capabilities.
If you want one that will also clean non-digit characters out of the string (and is easier to follow...and not quite so cutesy):
_.chain('123, 124, 234,252, n301')
.replace(/[^\d,]/g, '')
.words()
.map(_.partial(_.add, 1))
.value();
2017 edit:
I no longer recommend my previous solution. Besides being overkill and already easy to do without a third-party library, it makes use of _.chain, which has a variety of issues. Here's the solution I would now recommend:
const str = '123, 124, 234,252';
const arr = str.split(',').map(n => parseInt(n, 10) + 1);
My old answer is still correct, so I'll leave it for the record, but there's no need to use it nowadays.
Try with this
for Objective C
- (void)viewDidLoad
{
[super viewDidLoad];
// This will remove extra separators from tableview
self.yourTableView.tableFooterView = [UIView new];
}
for Swift
override func viewDidLoad() {
super.viewDidLoad()
self.yourTableView.tableFooterView = UIView()
}
shorter version of Nurul Akter Towhid's answer (the fp.close is automated):
with open("my.html","w") as fp:
fp.write(html)
You could use CommitMonitor. This little tool uses very little RAM and notifies you of all the commits you've missed.
The only practical effect of the throw specifier is that if something different from myExc
is thrown by your function, std::unexpected
will be called (instead of the normal unhandled exception mechanism).
To document the kind of exceptions that a function can throw, I typically do this:
bool
some_func() /* throw (myExc) */ {
}
Little sum up for searching by row:
This can be useful if you don't know the column values ??or if columns have non-numeric values
if u want get index number as integer u can also do:
item = df[4:5].index.item()
print(item)
4
it also works in numpy / list:
numpy = df[4:7].index.to_numpy()[0]
lista = df[4:7].index.to_list()[0]
in [x] u pick number in range [4:7], for example if u want 6:
numpy = df[4:7].index.to_numpy()[2]
print(numpy)
6
for DataFrame:
df[4:7]
A B
4 5 0.894525
5 6 0.978174
6 7 0.859449
or:
df[(df.index>=4) & (df.index<7)]
A B
4 5 0.894525
5 6 0.978174
6 7 0.859449
You can use this function, but its will return false if website offline.
function isValidUrl($url) {
$url = parse_url($url);
if (!isset($url["host"])) return false;
return !(gethostbyname($url["host"]) == $url["host"]);
}
You don't say which database you are using but in MS SQL Server it would be
WHERE DateField = {d '2008-12-20'}
If it is a timestamp field then you'll need a range:
WHERE DateField BETWEEN {ts '2008-12-20 00:00:00'} AND {ts '2008-12-20 23:59:59'}
Run all Collection in a folder in parallel:
'use strict';
global.Promise = require('bluebird');
const path = require('path');
const newman = Promise.promisifyAll(require('newman'));
const fs = Promise.promisifyAll(require('fs'));
const environment = 'postman_environment.json';
const FOLDER = path.join(__dirname, 'Collections_Folder');
let files = fs.readdirSync(FOLDER);
files = files.map(file=> path.join(FOLDER, file))
console.log(files);
Promise.map(files, file => {
return newman.runAsync({
collection: file, // your collection
environment: path.join(__dirname, environment), //your env
reporters: ['cli']
});
}, {
concurrency: 2
});
git push origin --delete yourBranch
The other answers are fine, but this is a little cleaner, in that it only gives the values like you would get from a DISTINCT query, without any cruft from Django.
>>> set(ProductOrder.objects.values_list('category', flat=True))
{u'category1', u'category2', u'category3', u'category4'}
or
>>> list(set(ProductOrder.objects.values_list('category', flat=True)))
[u'category1', u'category2', u'category3', u'category4']
And, it works without PostgreSQL.
This is less efficient than using a .distinct(), presuming that DISTINCT in your database is faster than a python set
, but it's great for noodling around the shell.
I posted that in jQuery forums (I hope it can help):
Diving into the jQM code i've found this solution. I hope it can help other people:
To refresh a dynamically modified page:
function refreshPage(page){
// Page refresh
page.trigger('pagecreate');
page.listview('refresh');
}
It works even if you create new headers, navbars or footers. I've tested it with jQM 1.0.1.
I think I know what you are asking for. Here is what you can do.
first get the height of the person say h meters.
if you can calculate the height of the camera from ground (using height if the person i.e. h) and get angles A and B using gyroscope or something from android then you can calculate the height of the object using the above formula.
Isn't this what you were looking for???
let me know if you need any explanation.
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
You can use
$(document).ready(function(){
setTimeout(function() {
window.location.href = "http://test.example.com/;"
}, 5000);
});
If you're already using jQuery, you could try this:
$(window).bind("load", function() {
// code here
});
As you're using Python 3, there is no urllib module anymore. It has been split into several modules.
This would be equivalent to urlretrieve:
import urllib.request
data = urllib.request.urlretrieve("http://...")
urlretrieve behaves exactly the same way as it did in Python 2.x, so it'll work just fine.
Basically:
urlretrieve
saves the file to a temporary file and returns a tuple (filename, headers)
urlopen
returns a Request
object whose read
method returns a bytestring containing the file contentsFirefox contains a dns cache. To disable the DNS cache:
When disabled, Firefox will use the DNS cache provided by the OS.
At runtime, no, you can't.
However via reflection the type parameters are accessible. Try
for(Field field : this.getDeclaredFields()) {
System.out.println(field.getGenericType())
}
The method getGenericType()
returns a Type object. In this case, it will be an instance of ParametrizedType
, which in turn has methods getRawType()
(which will contain List.class
, in this case) and getActualTypeArguments()
, which will return an array (in this case, of length one, containing either String.class
or Integer.class
).
This is what I'm doing in TypeScript I have a little utils library where I put things like this
export const arrayToHash = (array: any[], id: string = 'id') =>
array.reduce((obj, item) => (obj[item[id]] = item , obj), {})
usage:
const hash = arrayToHash([{id:1,data:'data'},{id:2,data:'data'}])
or if you have a identifier other than 'id'
const hash = arrayToHash([{key:1,data:'data'},{key:2,data:'data'}], 'key')
`e` in ['a', 'b', 'c'] # evaluates as False
`b` in ['a', 'b', 'c'] # evaluates as True
EDIT: With the clarification, new answer:
Note that PHP arrays are vastly different from Python's, combining arrays and dicts into one confused structure. Python arrays always have indices from 0
to len(arr) - 1
, so you can check whether your index is in that range. try/catch
is a good way to do it pythonically, though.
If you're asking about the hash functionality of PHP "arrays" (Python's dict
), then my previous answer still kind of stands:
`baz` in {'foo': 17, 'bar': 19} # evaluates as False
`foo` in {'foo': 17, 'bar': 19} # evaluates as True
As one person may have already suggested,
I passed the ISO 8601 date string directly to moment like so...
`moment.utc('2019-11-03T05:00:00.000Z').format('MM/DD/YYYY')`
or
`moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')`
either of these solutions will give you the same result.
`console.log(moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')) // 11/3/2019`
You may try something like this.
Sample Markup.
<div id="div1" >
<input type="text" id="edit1" />
<input type="text" id="edit2" />
</div>
<div id="div2" >
<input type="text" id="edit3" />
<input type="text" id="edit4" />
</div>
JavaScript
function GetElementInsideContainer(containerID, childID) {
var elm = {};
var elms = document.getElementById(containerID).getElementsByTagName("*");
for (var i = 0; i < elms.length; i++) {
if (elms[i].id === childID) {
elm = elms[i];
break;
}
}
return elm;
}
Demo: http://jsfiddle.net/naveen/H8j2A/
A better method as suggested by nnnnnn
function GetElementInsideContainer(containerID, childID) {
var elm = document.getElementById(childID);
var parent = elm ? elm.parentNode : {};
return (parent.id && parent.id === containerID) ? elm : {};
}
Demo: http://jsfiddle.net/naveen/4JMgF/
Call it like
var e = GetElementInsideContainer("div1", "edit1");
this is the query you need:
SELECT b.id, a.home,b.[datetime],b.player,a.resource FROM
(SELECT home,MAX(resource) AS resource FROM tbl_1 GROUP BY home) AS a
LEFT JOIN
(SELECT id,home,[datetime],player,resource FROM tbl_1) AS b
ON a.resource = b.resource WHERE a.home =b.home;
Actually, you don't need all that stuff with opacity, visibility, <input>
styling, etc. Just take a look:
<a href="#">Just click me.</a>
<script type="text/javascript">
$("a").click(function() {
// creating input on-the-fly
var input = $(document.createElement("input"));
input.attr("type", "file");
// add onchange handler if you wish to get the file :)
input.trigger("click"); // opening dialog
return false; // avoiding navigation
});
</script>
Demo on jsFiddle. Tested in Chrome 30.0 and Firefox 24.0. Didn't work in Opera 12.16, however.
I've just been encountering a very similar issue in Ubuntu while trying to get Eclipse Mars and Tomcat7 integrated because Eclipse was expecting the tomcat configuration files etc to be all in the same location, and with the necessary permissions to be able to change those files.
The following instructions from this blog article helped me in the end:
cd /usr/share/tomcat7
sudo ln -s /var/lib/tomcat7/conf conf
sudo ln -s /var/log/tomcat7 log
sudo ln -s /etc/tomcat7/policy.d/03catalina.policy conf/catalina.policy
sudo chmod -R a+rwx /usr/share/tomcat7/conf
NOTE: While my advice was true many years ago, Oracle's optimizer has improved so that the location of the where definitely no longer matters here. However preferring UNION ALL
vs UNION
will always be true, and portable SQL should avoid depending on optimizations that may not be in all databases.
Short answer, you want the WHERE
before the UNION
and you want to use UNION ALL
if at all possible. If you are using UNION ALL
then check the EXPLAIN output, Oracle might be smart enough to optimize the WHERE
condition if it is left after.
The reason is the following. The definition of a UNION
says that if there are duplicates in the two data sets, they have to be removed. Therefore there is an implicit GROUP BY
in that operation, which tends to be slow. Worse yet, Oracle's optimizer (at least as of 3 years ago, and I don't think it has changed) doesn't try to push conditions through a GROUP BY
(implicit or explicit). Therefore Oracle has to construct larger data sets than necessary, group them, and only then gets to filter. Thus prefiltering wherever possible is officially a Good Idea. (This is, incidentally, why it is important to put conditions in the WHERE
whenever possible instead of leaving them in a HAVING
clause.)
Furthermore if you happen to know that there won't be duplicates between the two data sets, then use UNION ALL
. That is like UNION
in that it concatenates datasets, but it doesn't try to deduplicate data. This saves an expensive grouping operation. In my experience it is quite common to be able to take advantage of this operation.
Since UNION ALL
does not have an implicit GROUP BY
in it, it is possible that Oracle's optimizer knows how to push conditions through it. I don't have Oracle sitting around to test, so you will need to test that yourself.
No, you should run mysql -u root -p
in bash, not at the MySQL command-line.
If you are in mysql, you can exit by typing exit.
I think the confusion is that on my server I had to right click the Task Scheduler Library on left hand side and right click to get the option to enable or disable all tasks history.
Hope this helps
Scheme doesn't have algebraic data types or pattern matching but it's certainly a functional language. Annoying things about Python from a functional programming perspective:
Crippled Lambdas. Since Lambdas can only contain an expression, and you can't do everything as easily in an expression context, this means that the functions you can define "on the fly" are limited.
Ifs are statements, not expressions. This means, among other things, you can't have a lambda with an If inside it. (This is fixed by ternaries in Python 2.5, but it looks ugly.)
Guido threatens to remove map, filter, and reduce every once in a while
On the other hand, python has lexical closures, Lambdas, and list comprehensions (which are really a "functional" concept whether or not Guido admits it). I do plenty of "functional-style" programming in Python, but I'd hardly say it's ideal.
I'm using EF6, and I find something strange,
Suppose Customer has constructor with parameter ,
if I use new Customer(id, "name")
, and do
using (var db = new EfContext("name=EfSample"))
{
db.Customers.Add( new Customer(id, "name") );
db.SaveChanges();
}
It run through without error, but when I look into the DataBase, I find in fact that the data Is NOT be Inserted,
But if I add the curly brackets, use new Customer(id, "name"){}
and do
using (var db = new EfContext("name=EfSample"))
{
db.Customers.Add( new Customer(id, "name"){} );
db.SaveChanges();
}
the data will then actually BE Inserted,
seems the Curly Brackets make the difference, I guess that only when add Curly Brackets, entity framework will recognize this is a real concrete data.
I made it work with keyup.
$("#id input").trigger('keyup');
Page Control can be contained in Window Control but vice versa is not possible
You can use Page control within the Window control using NavigationWindow and Frame controls. Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications. So if you host Page in NavigationWindow, you will get the navigation implementation built-in. Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer).
WPF provides support for browser style navigation inside standalone application using Page class. User can create multiple pages, navigate between those pages along with data.There are multiple ways available to Navigate through one page to another page.
If you want to iterate over both the keys and the values in a key sorted order, this form is quite succinct
let d = [
"A" : [1, 2],
"Z" : [3, 4],
"D" : [5, 6]
]
Swift 1,2:
for (k,v) in Array(d).sorted({$0.0 < $1.0}) {
println("\(k):\(v)")
}
Swift 3+:
for (k,v) in Array(d).sorted(by: {$0.0 < $1.0}) {
println("\(k):\(v)")
}
You need to be aware of a gotcha. Any class that you pass around as the DataObject in the drag/drop operation has to be Serializable. So if you try and pass an object, and it is not working, ensure it can be serialized as that is almost certainly the problem. This has caught me out a couple of times!
Assuming "current version" is the working directory (uncommitted modifications) and "last version" is HEAD
(last committed modifications for the current branch), simply do
git diff HEAD
Credit for the following goes to user Cerran
.
And if you always skip the staging area with -a
when you commit, then you can simply use git diff
.
Summary
git diff
shows unstaged changes.git diff --cached
shows staged changes.git diff HEAD
shows all changes (both staged and unstaged).Source: git-diff(1) Manual Page – Cerran
Maybe off-topic, but R features two nice, fast and empty-aware functions for reducing logical vectors -- any
and all
:
if(any(x=='dolphin')) stop("Told you, no mammals!")
The output of this query is very clean (original here)
clear screen
accept uname prompt 'Enter User Name : '
accept outfile prompt ' Output filename : '
spool &&outfile..gen
SET LONG 20000 LONGCHUNKSIZE 20000 PAGESIZE 0 LINESIZE 1000 FEEDBACK OFF VERIFY OFF TRIMSPOOL ON
BEGIN
DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SQLTERMINATOR', true);
DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'PRETTY', true);
END;
/
SELECT dbms_metadata.get_ddl('USER','&&uname') FROM dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT','&&uname') from dual;
spool off
The following works for me on Snow Leopard:
Runtime rt = Runtime.getRuntime();
String[] testArgs = {"touch", "TEST"};
rt.exec(testArgs);
Thing is, if you want to read the output of that command, you need to read the input stream of the process. For instance,
Process pr = rt.exec(arguments);
BufferedReader r = new BufferedReader(new InputStreamReader(pr.getInputStream()));
Allows you to read the line-by-line output of the command pretty easily.
The problem might also be that MS-DOS does not interpret your order of arguments to mean "start a new command prompt". Your array should probably be:
{"start", "cmd.exe", "\c"}
To open commands in the new command prompt, you'd have to use the Process reference. But I'm not sure why you'd want to do that when you can just use exec, as the person before me commented.
If you're working with a BitmapSource
:
var resizedBitmap = new TransformedBitmap(
bitmapSource,
new ScaleTransform(scaleX, scaleY));
If you want finer control over quality, run this first:
RenderOptions.SetBitmapScalingMode(
bitmapSource,
BitmapScalingMode.HighQuality);
(Default is BitmapScalingMode.Linear
which is equivalent to BitmapScalingMode.LowQuality
.)
SQL Server does simple counting of cascade paths and, rather than trying to work out whether any cycles actually exist, it assumes the worst and refuses to create the referential actions (CASCADE): you can and should still create the constraints without the referential actions. If you can't alter your design (or doing so would compromise things) then you should consider using triggers as a last resort.
FWIW resolving cascade paths is a complex problem. Other SQL products will simply ignore the problem and allow you to create cycles, in which case it will be a race to see which will overwrite the value last, probably to the ignorance of the designer (e.g. ACE/Jet does this). I understand some SQL products will attempt to resolve simple cases. Fact remains, SQL Server doesn't even try, plays it ultra safe by disallowing more than one path and at least it tells you so.
Microsoft themselves advises the use of triggers instead of FK constraints.
If you're using AD you can use serverless binding to locate a domain controller for the default domain, then use LDAP://rootDSE to get information about the directory server, as described in the linked article.
File-->Settings-->Editor
Check "Show quick doc on mouse"
Now when you put the mouse over a method a tooltip with the documentation will appear. Sometimes the tooltip size is too small and you will have to resize it moving the mouse down to the bottom of the tooltip.
#include <stdio.h>
#include "opencv.hpp"
int main(){
CvCapture *camera=cvCaptureFromFile("http://username:pass@cam_address/axis-cgi/mjpg/video.cgi?resolution=640x480&req_fps=30&.mjpg");
if (camera==NULL)
printf("camera is null\n");
else
printf("camera is not null");
cvNamedWindow("img");
while (cvWaitKey(10)!=atoi("q")){
double t1=(double)cvGetTickCount();
IplImage *img=cvQueryFrame(camera);
double t2=(double)cvGetTickCount();
printf("time: %gms fps: %.2g\n",(t2-t1)/(cvGetTickFrequency()*1000.), 1000./((t2-t1)/(cvGetTickFrequency()*1000.)));
cvShowImage("img",img);
}
cvReleaseCapture(&camera);
}
Step by steps:
To create/edit the .gemrc file from the terminal:
vi ~/.gemrc
You will open a editor called vi. paste in:
gem: --no-ri --no-rdoc
click 'esc'-button.
type in:
:exit
You can check if everything is correct with this command:
sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit ~/.gemrc
I've had a very similar issue using spring-boot-starter-data-redis
. To my implementation there was offered a @Bean
for RedisTemplate
as follows:
@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));
// Add some specific configuration here. Key serializers, etc.
return template;
}
The fix was to specify an array of RoutePlantCache
as following:
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));
Below the exception I had:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]
+1 for everyone who's recommended the RedGate tools, with an additional recommendation and a caveat.
SqlCompare also has a decently documented API: so you can, for instance, write a console app which syncs your source controlled scripts folder with a CI integration testing database on checkin, so that when someone checks in a change to the schema from their scripts folder it's automatically deployed along with the matching application code change. This helps close the gap with developers who are forgetful about propagating changes in their local db up to a shared development DB (about half of us, I think :) ).
A caveat is that with a scripted solution or otherwise, the RedGate tools are sufficiently smooth that it's easy to forget about SQL realities underlying the abstraction. If you rename all the columns in a table, SqlCompare has no way to map the old columns to the new columns and will drop all the data in the table. It will generate warnings but I've seen people click past that. There's a general point here worth making, I think, that you can only automate DB versioning and upgrade so far - the abstractions are very leaky.
I'm late to this party but as nothing above was either viable or working in most cases, here is how this was finally resolved for me.
On the server the site/service was hosted on, a feature was required! HTTP ACTIVATION!!!
Server Manager > Manage > Add Roles and Features > next next next till you get to Features > Under .NET (each version) tick HTTP Activation. Also note there is one hidden under >net > WCF Services.
This then worked instantly! That was melting my brain
If you are removing a specific string from the end, use removeSuffix
(Documentation)
var text = "one(two"
text = text.removeSuffix("(two") // "one"
If the suffix does not exist in the string, it just returns the original
var text = "one(three"
text = text.removeSuffix("(two") // "one(three"
If you want to remove after a character, use
// Each results in "one"
text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")
You can also check out removePrefix
, removeRange
, removeSurrounding
, and replaceAfterLast
which are similar
The Full List is here: (Documentation)
In my case, I had only a single bootstrap.js, jquery.js file included but still getting such type of error, and my code for button was something like this:
<script type="text/javascript">
$(document).ready(function(){
$("#bttn_<?php echo $rnt['id'];?>").click(function(){
$("#myModal_<?php echo $rnt['id'];?>").modal('show');
});
});
</script>
I simple added e.preventDefault(); to it and it worked like charm.
So, my new code was like below:
<script type="text/javascript">
$(document).ready(function(){
e.preventDefault();
$("#bttn_<?php echo $rnt['id'];?>").click(function(){
$("#myModal_<?php echo $rnt['id'];?>").modal('show');
});
});
</script>
You probably don't need this any more, but I recently wrote a java class to do this. Apparently Yanick Rochon did something similar. It will convert numbers up to 999 Novemdecillion (999*10^60). It could do more if I knew what came after Novemdecillion, but I would be willing to bet it's unnecessary. Just feed the number as a string in cents. The output is also grammatically correct.
Came across this question, so here's a quick comparison. Compare these two different ways to extract one frame per minute from a video 38m07s long:
time ffmpeg -i input.mp4 -filter:v fps=fps=1/60 ffmpeg_%0d.bmp
1m36.029s
This takes long because ffmpeg parses the entire video file to get the desired frames.
time for i in {0..39} ; do ffmpeg -accurate_seek -ss `echo $i*60.0 | bc` -i input.mp4 -frames:v 1 period_down_$i.bmp ; done
0m4.689s
This is about 20 times faster. We use fast seeking to go to the desired time index and extract a frame, then call ffmpeg several times for every time index. Note that -accurate_seek
is the default
, and make sure you add -ss
before the input video -i
option.
Note that it's better to use -filter:v -fps=fps=...
instead of -r
as the latter may be inaccurate. Although the ticket is marked as fixed, I still did experience some issues, so better play it safe.
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
Rahul's answer is best fit for your question. Anyway, if you have a group of checkboxes to be checked and not all the checkbox in your form, you can go for it.
Put a classname for all the checkboxes you want to check, say for example, a classname test_check
and now you can check if any of the checkbox is checked belonging to the group by:
$("#formID .test_check:checked").length > 0
If it returns true
, assume that one or more checkboxes are checked having the classname test_check
and none checked if returns false
.
Hope it helps someone. Thanks :)-
You can use Task.WhenAll
as mentioned, or Task.WaitAll
, depending on whether you want the thread to wait. Take a look at the link for an explanation of both.
To get this in excel or csv format- right click the folder and select "copy response"- paste to excel and use text to columns.
I know it's too late but may be its helps some one. on using this take your database offline
ALTER DATABASE dbname SET OFFLINE
None of the above solutions worked for me and I don't have admin rights on my laptop, but they eventually led me to the git tools credential storage doc :
My setup Windows 10 | git version 2.18.0.windows.1 | Clone through HTTPS link
This solution works if you use wincred as credential helper :
> git config --global credential.helper
wincred
Changing the helper to "cache" should do the trick, as it will ask you to provide your credentials again. To set it to cache, just type :
> git config --global credential.helper cache
Check your update is active:
> git config --global credential.helper
cache
You should now be able to clone / pull / fetch as before.
Java with Selenium 2.53.0
driver.getPageSource();
Now you can use nameof
:
public static void Output<T>(IEnumerable<T> dataSource) where T : class
{
string dataSourceName = typeof(T).Name;
switch (dataSourceName)
{
case nameof(CustomerDetails):
var t = 123;
break;
default:
Console.WriteLine("Test");
}
}
nameof(CustomerDetails)
is basically identical to the string literal "CustomerDetails"
, but with a compile-time check that it refers to some symbol (to prevent a typo).
nameof
appeared in C# 6.0, so after this question was asked.
David, Error comes Microsoft Office Excel has stopped working. Two options check online for a solution and close the programme and other option Close the program I am sure error is in my array but I am reading everything and seem this is way to define arrays.
Here is a version with optimization. All the solutions above would require pig to read and write full tuple when counting, this script below just write '1'-s
DEFINE row_count(inBag, name) RETURNS result {
X = FOREACH $inBag generate 1;
$result = FOREACH (GROUP X ALL PARALLEL 1) GENERATE '$name', COUNT(X);
};
The use it like
xxx = row_count(rows, 'rows_count');
I've done this with nock, like so:
import nock from 'nock'
import axios from 'axios'
import httpAdapter from 'axios/lib/adapters/http'
axios.defaults.adapter = httpAdapter
describe('foo', () => {
it('bar', () => {
nock('https://example.com:443')
.get('/example')
.reply(200, 'some payload')
// test...
})
})
although the answer is for Java, but the code can be easily adapted from this Kotlin String extension I came up with (adapted from that @brcolow provided):
private val escapeChars = charArrayOf(
'<',
'(',
'[',
'{',
'\\',
'^',
'-',
'=',
'$',
'!',
'|',
']',
'}',
')',
'?',
'*',
'+',
'.',
'>'
)
fun String.escapePattern(): String {
return this.fold("") {
acc, chr ->
acc + if (escapeChars.contains(chr)) "\\$chr" else "$chr"
}
}
fun main() {
println("(.*)".escapePattern())
}
prints \(\.\*\)
check it in action here https://pl.kotl.in/h-3mXZkNE
Here's a snippet of helpful code:
using System.Diagnostics;
// Prepare the process to run
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = arguments;
// Enter the executable to run, including the complete path
start.FileName = ExeName;
// Do you want to show a console window?
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
int exitCode;
// Run the external process & wait for it to finish
using (Process proc = Process.Start(start))
{
proc.WaitForExit();
// Retrieve the app's exit code
exitCode = proc.ExitCode;
}
There is much more you can do with these objects, you should read the documentation: ProcessStartInfo, Process.
It's been many functions, macros and objects since I posted this question. The way I handled it, which is mentioned in one of the answers here, is by creating a string function that handles the errors that get generate by the vlookup function, and returns either nothing or the vlookup result if any.
Function fsVlookup(ByVal pSearch As Range, ByVal pMatrix As Range, ByVal pMatColNum As Integer) As String
Dim s As String
On Error Resume Next
s = Application.WorksheetFunction.VLookup(pSearch, pMatrix, pMatColNum, False)
If IsError(s) Then
fsVlookup = ""
Else
fsVlookup = s
End If
End Function
One could argue about the position of the error handling or by shortening this code, but it works in all cases for me, and as they say, "if it ain't broke, don't try and fix it".
You cannot invoke JavaScript functions in standard HTML attributes other than onXXX
. Just assign it during window onload.
<script type="text/javascript">
window.onload = function() {
document.myform.action = get_action();
}
function get_action() {
return form_action;
}
</script>
<form name="myform">
...
</form>
You see that I've given the form a name
, so that it's easily accessible in document
.
Alternatively, you can also do it during submit
event:
<script type="text/javascript">
function get_action(form) {
form.action = form_action;
}
</script>
<form onsubmit="get_action(this);">
...
</form>
If stuffs
is a list of strings, just this would work:
{{ stuffs|join(", ") }}
Link to join
filter documentation, link to filters in general documentation.
p.s.
More reader friendly way {{ my ~ ', ' ~ string }}
I think you must also remove security auto config from your @SpringBootApplication
annotated class:
@EnableAutoConfiguration(exclude = {
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class,
org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration.class})
All you need to do is:
Build the mainjava class using the class path if any (optional)
javac *.java [ -cp "wb.jar;"]
Create Manifest.txt file with content is:
Main-Class: mainjava
Package the jar file for mainjava class
jar cfm mainjava.jar Manifest.txt *.class
Then you can run this .jar file from cmd with class path (optional) and put arguments for it.
java [-cp "wb.jar;"] mainjava arg0 arg1
HTH.
You want to create an alias by simply typing:
c:\>alias kgs kubectl get svc
Created alias for kgs=kubectl get svc
And use the alias as follows:
c:\>kgs alfresco-svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
alfresco-svc ClusterIP 10.7.249.219 <none> 80/TCP 8d
Just add the following alias.bat
file to you path. It simply creates additional batch files in the same directory as itself.
@echo off
echo.
for /f "tokens=1,* delims= " %%a in ("%*") do set ALL_BUT_FIRST=%%b
echo @echo off > C:\Development\alias-script\%1.bat
echo echo. >> C:\Development\alias-script\%1.bat
echo %ALL_BUT_FIRST% %%* >> C:\Development\alias-script\%1.bat
echo Created alias for %1=%ALL_BUT_FIRST%
An example of the batch file this created called kgs.bat
is:
@echo off
echo.
kubectl get svc %*
To replace more than one number:
vec <- 1:10
replace(vec, vec== c(2,6), c(0,9)) #2 and 6 will be replaced by 0 and 9.
Edit:
for a continous series, you can do this vec <- c(1:10); replace(vec, vec %in% c(2,6), c(0,9))
but for vec <- c(1:10,2,2,2); replace(vec, vec %in% c(2,6), 0)
we can replace multiple values with one value.
Application.Exit()
kills your application but there are some instances that it won't close the application.
End
is better than Application.Exit()
.
To make print view look like tablet or desktop include bootstrap as .less, not as .css and then you can overwrite bootstrap responsive classes in the end of bootstrap_variables file for example like this:
@container-sm: 1200px;
@container-md: 1200px;
@container-lg: 1200px;
@screen-sm: 0;
Don't worry about putting this variables in the end of the file. LESS supports lazy loading of variables so they will be applied.
Vertex *f=(findvertex(from));
if(!f) {
cerr << "vertex not found" << endl;
exit(1) // or return;
}
Because findVertex
can return NULL
if it can't find the vertex.
Otherwise this f->adj;
is trying to do
NULL->adj;
Which causes access violation.
To change the radio button color programmatically you can use following:
yourradio button name.buttonDrawable?.setColorFilter(Color.parseColor( color_value), PorterDuff.Mode.SRC_ATOP)
For a list of files to be pushed, run:
git diff --stat --cached [remote/branch]
example:
git diff --stat --cached origin/master
For the code diff of the files to be pushed, run:
git diff [remote repo/branch]
To see full file paths of the files that will change, run:
git diff --numstat [remote repo/branch]
If you want to see these diffs in a GUI, you will need to configure git for that. See How do I view 'git diff' output with a visual diff program?.
Please make sure that the version of qmake you are using corresponds to the version of QT you want to use.
To be sure, you can just run :
$qmake -v
Your problem seems to be a symptom of a version conflict between QT 3 and 4, as can be seen here :
http://lists.trolltech.com/qt4-preview-feedback/2005-11/thread00013-0.html
To fix this, you can either delete your old install of QT, or specifically point to qmake-qt4 in your Makefile.
My approach:
define a default constraint on the ModDate
column with a value of GETDATE()
- this handles the INSERT
case
have a AFTER UPDATE
trigger to update the ModDate
column
Something like:
CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
UPDATE dbo.TimeEntry
SET ModDate = GETDATE()
WHERE ID IN (SELECT DISTINCT ID FROM Inserted)
I'll try to make you understand with the help of an example. Suppose you had a relational table (STUDENT) with two columns and ID(int) and NAME(String). Now as ORM you would've made an entity class somewhat like as follows:-
package com.kashyap.default;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author vaibhav.kashyap
*
*/
@Entity
@Table(name = "STUDENT")
public class Student implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1354919370115428781L;
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "NAME")
private String name;
public Student(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Lets assume table already had entries. Now if somebody asks you add another column of "AGE" (int)
ALTER TABLE STUDENT ADD AGE int NULL
You'll have to set default values as NULL to add another column in a pre-filled table. This makes you add another field in the class. Now the question arises whether you'll be using a primitive data type or non primitive wrapper data type for declaring the field.
@Column(name = "AGE")
private int age;
or
@Column(name = "AGE")
private INTEGER age;
you'll have to declare the field as non primitive wrapper data type because the container will try to map the table with the entity. Hence it wouldn't able to map NULL values (default) if you won't declare field as wrapper & would eventually throw "Null value was assigned to a property of primitive type setter" Exception.
You need to put your code into ngOnInit
and use the this
keyword:
ngOnInit() {
this.booksByStoreID = this.books.filter(
book => book.store_id === this.store.id);
}
You need ngOnInit
because the input store
wouldn't be set into the constructor:
ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.
(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)
In your code, the books filtering is directly defined into the class content...
You can either set the timeout when running your test:
mocha --timeout 15000
Or you can set the timeout for each suite or each test programmatically:
describe('...', function(){
this.timeout(15000);
it('...', function(done){
this.timeout(15000);
setTimeout(done, 15000);
});
});
For more info see the docs.
I had similar issue for android-29. My issue occurred because when AS was unzipping one downloaded SDK I had stopped it. For solving the issue disable gradle offline mode then sync with gradle files. You may need to set proxy and enable it.
You can use js fetch
async function send(url,data) {_x000D_
let r= await fetch(url, {_x000D_
method: "POST", _x000D_
headers: {_x000D_
"My-header": "abc" _x000D_
},_x000D_
body: JSON.stringify(data), _x000D_
})_x000D_
return await r.json()_x000D_
}_x000D_
_x000D_
// Example usage_x000D_
_x000D_
let url='https://server.test-cors.org/server?enable=true&status=200&methods=POST&headers=my-header';_x000D_
_x000D_
async function run() _x000D_
{_x000D_
let jsonObj = await send(url,{ some: 'testdata' });_x000D_
console.log(jsonObj[0].request.httpMethod + ' was send - open chrome console > network to see it');_x000D_
}_x000D_
_x000D_
run();
_x000D_
You can push your local branch to a new remote branch like so:
git push origin master:test
(Assuming origin
is your remote, master
is your local branch name and test
is the name of the new remote branch, you wish to create.)
If at the same time you want to set up your local branch to track the newly created remote branch, you can do so with -u
(on newer versions of Git) or --set-upstream
, so:
git push -u origin master:test
or
git push --set-upstream origin master:test
...will create a new remote branch, named test
, in remote repository origin
, based on your local master
, and setup your local master
to track it.
File -> Settings -> Keymap Change keymaps settings to your previous IDE to which you are familiar with
Search() can give a more simplified list of the attached packages in a session (i.e., without the detailed info given by sessionInfo())
search {base}- R Documentation
Description: Gives a list of attached packages. Search()
search()
#[1] ".GlobalEnv" "package:Rfacebook" "package:httpuv"
#"package:rjson"
#[5] "package:httr" "package:bindrcpp" "package:forcats" #
#"package:stringr"
#[9] "package:dplyr" "package:purrr" "package:readr"
#"package:tidyr"
#[13] "package:tibble" "package:ggplot2" "package:tidyverse"
#"tools:rstudio"
#[17] "package:stats" "package:graphics" "package:grDevices"
#"package:utils"
#[21] "package:datasets" "package:methods" "Autoloads"
#"package:base"
A very simple fix that doesn't need to change your code, just add jquery migration script, download here https://github.com/jquery/jquery-migrate/
It supplies jquery deprecated but needed functions like "live", "browser" etc
I ran into this problem when my insert value fields contained tabs and spaces that were not obvious to the naked eye. I had created my value list in Excel, copied, and pasted it to SQL, and run queries to find non-matches on my FK fields.
The match queries did not detect there were tabs and spaces in my FK field, but the INSERT did recognize them and it continued to generate the error.
I tested again by copying the content of the FK field in one record and pasting it into the insert query. When that record also failed, I looked closer at the data and finally detected the tabs/spaces.
Once I cleaned removed tabs/spaces, my issue was resolved. Hope this helps someone!
If anyone is interested, you can have the the offset information for all the consumer groups with the following command:
kafka-consumer-groups --bootstrap-server localhost:9092 --all-groups --describe
The parameter --all-groups is available from Kafka 2.4.0
As others have said the first version, using "this" results in every instance of the class A having its own independent copy of function method "x". Whereas using "prototype" will mean that each instance of class A will use the same copy of method "x".
Here is some code to show this subtle difference:
// x is a method assigned to the object using "this"
var A = function () {
this.x = function () { alert('A'); };
};
A.prototype.updateX = function( value ) {
this.x = function() { alert( value ); }
};
var a1 = new A();
var a2 = new A();
a1.x(); // Displays 'A'
a2.x(); // Also displays 'A'
a1.updateX('Z');
a1.x(); // Displays 'Z'
a2.x(); // Still displays 'A'
// Here x is a method assigned to the object using "prototype"
var B = function () { };
B.prototype.x = function () { alert('B'); };
B.prototype.updateX = function( value ) {
B.prototype.x = function() { alert( value ); }
}
var b1 = new B();
var b2 = new B();
b1.x(); // Displays 'B'
b2.x(); // Also displays 'B'
b1.updateX('Y');
b1.x(); // Displays 'Y'
b2.x(); // Also displays 'Y' because by using prototype we have changed it for all instances
As others have mentioned, there are various reasons to choose one method or the other. My sample is just meant to clearly demonstrate the difference.
I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)
just paste whatever you were earlier pasting in ~/.bashrc to:
~/.zshrc
There are a couple of ways to do it in JavaScript. The first two examples are JavaScript samples. The third one makes use of a JavaScript library, that is, jQuery making use of the .each()
function.
var myStringArray = ["hello", "World"];_x000D_
for(var i in myStringArray) {_x000D_
alert(myStringArray[i]);_x000D_
}
_x000D_
var myStringArray = ["hello", "World"];_x000D_
for (var i=0; i < myStringArray.length; i++) {_x000D_
alert(myStringArray[i]);_x000D_
}
_x000D_
var myStringArray = ["hello", "World"];_x000D_
$.each(myStringArray, function(index, value){_x000D_
alert(value);_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
_x000D_
class MyApp2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: AppBarTheme(
elevation: 0,
color: Colors.blueAccent,
)
),
title: 'Welcome to flutter ',
home: HomePage()
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int number = 0;
void _increment(){
setState(() {
number ++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueAccent,
appBar: AppBar(
title: Text('MyApp2'),
leading: Icon(Icons.menu),
// backgroundColor: Colors.blueAccent,
),
body: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(200.0),
topRight: Radius.circular(200)
),
color: Colors.white,
),
)
);
}
}
If you want Rails 3 or Ruby 1.9 compatibility try the date_validator gem.
Given a data URL, you can create an image (either on the page or purely in JS) by setting the src
of the image to your data URL. For example:
var img = new Image;
img.src = strDataURI;
The drawImage()
method of HTML5 Canvas Context lets you copy all or a portion of an image (or canvas, or video) onto a canvas.
You might use it like so:
var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(img,0,0); // Or at whatever offset you like
};
img.src = strDataURI;
Edit: I previously suggested in this space that it might not be necessary to use the onload
handler when a data URI is involved. Based on experimental tests from this question, it is not safe to do so. The above sequence—create the image, set the onload
to use the new image, and then set the src
—is necessary for some browsers to surely use the results.
for(int index = 0; index < ((ViewGroup) viewGroup).getChildCount(); index++) {
View nextChild = ((ViewGroup) viewGroup).getChildAt(index);
}
Will that do?
The XRegExp library has a plugin named Unicode that helps solve tasks like this.
<script src="xregexp.js"></script>
<script src="addons/unicode/unicode-base.js"></script>
<script>
var unicodeWord = XRegExp("^\\p{L}+$");
unicodeWord.test("???????"); // true
unicodeWord.test("???"); // true
unicodeWord.test("???????"); // true
</script>
It's mentioned in the comments to the question, but it's easy to miss. I've noticed it only after I submitted this answer.
Your code is not doing what I think you think it is doing. The line for item in z:
will iterate through z
, each time making item
equal to one single element of z
. The original item
list is therefore overwritten before you've done anything with it.
I think you want something like this:
item = [0,1,2,3,4,5,6,7,8,9]
for element in item:
if element not in z:
print element
But you could easily do this like:
[x for x in item if x not in z]
or (if you don't mind losing duplicates of non-unique elements):
set(item) - set(z)
Hammer time!
I have used Hammer JS and it work with gesture. Read details from here: https://hammerjs.github.io/
Good thing that it is much more light weight and fast then jQuery mobile. You can test it on their website as well.
This is something of a religious debate. Both approaches have their problems.
Bloch has another relevant piece of advice in Effective Java Second Edition:
To count number of tables just do this:
USE your_db_name; -- set database
SHOW TABLES; -- tables lists
SELECT FOUND_ROWS(); -- number of tables
Sometimes easy things will do the work.
You should use:
protected void btn1_Click(object sender, EventArgs e)
{
Response.Redirect("otherpage.aspx");
}
Online index rebuilds are less intrusive when it comes to locking tables. Offline rebuilds cause heavy locking of tables which can cause significant blocking issues for things that are trying to access the database while the rebuild takes place.
"Table locks are applied for the duration of the index operation [during an offline rebuild]. An offline index operation that creates, rebuilds, or drops a clustered, spatial, or XML index, or rebuilds or drops a nonclustered index, acquires a Schema modification (Sch-M) lock on the table. This prevents all user access to the underlying table for the duration of the operation. An offline index operation that creates a nonclustered index acquires a Shared (S) lock on the table. This prevents updates to the underlying table but allows read operations, such as SELECT statements."
http://msdn.microsoft.com/en-us/library/ms188388(v=sql.110).aspx
Additionally online index rebuilds are a enterprise (or developer) version only feature.
In C++ it is easy.
std::copy(someStr.c_str(), someStr.c_str()+n, std::ostream_iterator<char>(std::cout, ""));
EDIT: It is also safer to use this with string iterators, so you don't run off the end. I'm not sure what happens with printf and string that are too short, but I'm guess this may be safer.
The chosen answer does work however I wanted to make a comment that having 'ngModel' on the html tag causes the checkbox checked to not be set to true.
This occurs when you are trying to do bind using the checked property. i.e.
<mat-checkbox [checked]='var' ngModel name='some_name'></mat-checkbox>
And then inside your app.component.ts file
var = true;
will not work.
TLDR: Remove ngModel if you are setting the checked through the [checked] property
<mat-checkbox [checked]='var' name='some_name'></mat-checkbox>
I'd recommend looking for something such as Forever to restart Node in the event of a crash, and handle daemonizing this for you.
You can also use jQuery('.class-name').attr("href")
, in my case it works better.
Here more information: "jQuery(...)" instead of "$(...)"
The short answer is:
int nBits = ceil(log2(N));
That's simply because pow(2, nBits) is slightly bigger than N.
public ActionResult Questionnaire()
{
return Redirect("~/MedicalHistory.html");
}
You may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project).
This is the code part from this page:
CREATE FUNCTION [fn_ParseText2Table]
(@p_SourceText VARCHAR(MAX)
,@p_Delimeter VARCHAR(100)=',' --default to comma delimited.
)
RETURNS @retTable
TABLE([Position] INT IDENTITY(1,1)
,[Int_Value] INT
,[Num_Value] NUMERIC(18,3)
,[Txt_Value] VARCHAR(MAX)
,[Date_value] DATETIME
)
AS
/*
********************************************************************************
Purpose: Parse values from a delimited string
& return the result as an indexed table
Copyright 1996, 1997, 2000, 2003 Clayton Groom (<A href="mailto:[email protected]">[email protected]</A>)
Posted to the public domain Aug, 2004
2003-06-17 Rewritten as SQL 2000 function.
Reworked to allow for delimiters > 1 character in length
and to convert Text values to numbers
2016-04-05 Added logic for date values based on "new" ISDATE() function, Updated to use XML approach, which is more efficient.
********************************************************************************
*/
BEGIN
DECLARE @w_xml xml;
SET @w_xml = N'<root><i>' + replace(@p_SourceText, @p_Delimeter,'</i><i>') + '</i></root>';
INSERT INTO @retTable
([Int_Value]
, [Num_Value]
, [Txt_Value]
, [Date_value]
)
SELECT CASE
WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST(CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC) AS INT)
END AS [Int_Value]
, CASE
WHEN ISNUMERIC([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST([i].value('.', 'VARCHAR(MAX)') AS NUMERIC(18, 3))
END AS [Num_Value]
, [i].value('.', 'VARCHAR(MAX)') AS [txt_Value]
, CASE
WHEN ISDATE([i].value('.', 'VARCHAR(MAX)')) = 1
THEN CAST([i].value('.', 'VARCHAR(MAX)') AS DATETIME)
END AS [Num_Value]
FROM @w_xml.nodes('//root/i') AS [Items]([i]);
RETURN;
END;
GO
Provide the Directory/Folder path where python.exe is available in Anaconda folder like
C:\Users\user_name\Anaconda3\
This should must work.
I think the easiest way to accomplish it is to use querystring instead of HTTP headers.
Most developers don't have a clue
Yup .. there you go. I've said it. I find that from all the developers that I personally know .. just a handful are actually good. Just a handful understand that code should be tested ... that the Object Oriented approach to developing is actually there to help you. It frustrates me to no end that there are people who get the title of developer while in fact all they can do is copy and paste a bit of source code and then execute it.
Anyway ... I'm glad initiatives like stackoverflow are being started. It's good for developers to wonder. Is there a better way? Am I doing it correctly? Perhaps I could use this technique to speed things up, etc ...
But nope ... the majority of developers just learn a language that they are required by their job and stick with it until they themselves become old and grumpy developers that have no clue what's going on. All they'll get is a big paycheck since they are simply older than you.
Ah well ... life is unjust in the IT community and I'll be taking steps to ignore such people in the future. Hooray!
int mid = 10;
for (double j = 2 * mid; j >= 0; j = j - 0.1) {
if (j == mid) {
System.out.println("Never happens"); // is NOT printed
}
if (Double.compare(j, mid) == 0) {
System.out.println("No way!"); // is NOT printed
}
if (Math.abs(j - mid) < 1e-6) {
System.out.println("Ha!"); // printed
}
}
System.out.println("Gotcha!");
IF you have adapter attached with recyclerView then just do this.
mRecyclerView.smoothScrollToPosition(mRecyclerView.getAdapter().getItemCount());
I strongly disagree with some previous solutions that recommended to run both services in the same container. It's clearly stated in the documentation that it's not a recommended:
It is generally recommended that you separate areas of concern by using one service per container. That service may fork into multiple processes (for example, Apache web server starts multiple worker processes). It’s ok to have multiple processes, but to get the most benefit out of Docker, avoid one container being responsible for multiple aspects of your overall application. You can connect multiple containers using user-defined networks and shared volumes.
There are good use cases for supervisord or similar programs but running a web application + database is not part of them.
You should definitely use docker-compose to do that and orchestrate multiple containers with different responsibilities.
With position fixed, you need to provide values to set where the div will be placed, since it's a fixed position.
Something like....
.test
{
position:fixed;
left:100px;
top:150px;
}
Fixed - Generates an absolutely positioned element, positioned relative to the browser window. The element's position is specified with the "left", "top", "right", and "bottom" properties
More on position here.
"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$"