You can use double quotes if ANSI SQL mode is enabled
CREATE TABLE IF NOT EXISTS misc_info
(
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
"key" TEXT UNIQUE NOT NULL,
value TEXT NOT NULL
)
ENGINE=INNODB;
or the proprietary back tick escaping otherwise. (Where to find the `
character on various keyboard layouts is covered in this answer)
CREATE TABLE IF NOT EXISTS misc_info
(
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
`key` TEXT UNIQUE NOT NULL,
value TEXT NOT NULL
)
ENGINE=INNODB;
in regards to:
Take a look at the open source WordPress application. They have a very re-usable window they have created for displaying an "activity in progress" type display over top of whatever view your application is currently displaying.
note that if you do utilise this code you MUST provide ALL the sourcecode to your own application to any user that requests it. You need to be aware that they may decide to repackage your code and sell it on the store themselves. This is all provided for under the terms of the GNU General Public License (GPL).
If you don't want to be forced into opening your sourcecode then you cannot use anything from the wordpress iphone application including the, referenced activity progress window, without forcing the GPL to apply to your own.
This is a way to invoke one or more JavaScript methods from the code behind. By using Script Manager we can call the methods in sequence. Consider the below code for example.
ScriptManager.RegisterStartupScript(this, typeof(Page), "UpdateMsg",
"$(document).ready(function(){EnableControls();
alert('Overrides successfully Updated.');
DisableControls();});",
true);
In this first method EnableControls() is invoked. Next the alert will be displayed. Next the DisableControls() method will be invoked.
Perhaps:
> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)
For OpenJDK 8 on Linux see: https://askubuntu.com/questions/755853/how-to-install-jdk-sources
The way that worked for me is:
src.zip
is a symbolic link pointing to a non-existing folder ...sudo apt-get install openjdk-8-source
this adds this folderlocate "src.zip"
Window --> Preferences --> Java --> "Installed JREs"
, edit and point to src.zip
(or open any JRE class like for example HashMap and attach source)You should now see the JavaDoc when opening JRE classes via Ctrl+Shift+t, previously this was not possible, Eclipse may have got a docs from the default URL on mouse over methods but this requires a stable internet connection.
What you could do is also to take the next token as a String, converts this string to a char array and test that each character in the array is a digit.
I think that's correct, if you don't want to deal with the exceptions.
To temporarily block JavaScript on a domain :
View site information
)JavaScript
, select Always block on this site
Using setInterval:
setInterval(function() {
// your code goes here...
}, 60 * 1000); // 60 * 1000 milsec
The function returns an id you can clear your interval with clearInterval:
var timerID = setInterval(function() {
// your code goes here...
}, 60 * 1000);
clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.
A "sister" function is setTimeout/clearTimeout look them up.
If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:
function fn60sec() {
// runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);
User Leigh Webber on the social.msdn.microsoft.com site posted VBA code implementing an easy-to-use clipboard interface that uses the Windows API:
http://social.msdn.microsoft.com/Forums/en/worddev/thread/ee9e0d28-0f1e-467f-8d1d-1a86b2db2878
You can get Leigh Webber's source code here
If this link doesn't go through, search for "A clipboard object for VBA" in the Office Dev Center > Microsoft Office for Developers Forums > Word for Developers section.
I created the two classes, ran his test cases, and it worked perfectly inside Outlook 2007 SP3 32-bit VBA under Windows 7 64-bit. It will most likely work for Access. Tip: To rename classes, select the class in the VBA 'Project' window, then click 'View' on the menu bar and click 'Properties Window' (or just hit F4).
With his classes, this is what it takes to copy to/from the clipboard:
Dim myClipboard As New vbaClipboard ' Create clipboard
' Copy text to clipboard as ClipboardFormat TEXT (CF_TEXT)
myClipboard.SetClipboardText "Text to put in clipboard", "CF_TEXT"
' Retrieve clipboard text in CF_TEXT format (CF_TEXT = 1)
mytxt = myClipboard.GetClipboardText(1)
He also provides other functions for manipulating the clipboard.
It also overcomes 32KB MSForms_DataObject.SetText limitation - the main reason why SetText often fails. However, bear in mind that, unfortunatelly, I haven't found a reference on Microsoft recognizing this limitation.
-Jim
You get this error message if a Python file was closed from "the outside", i.e. not from the file object's close()
method:
>>> f = open(".bashrc")
>>> os.close(f.fileno())
>>> del f
close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor
The line del f
deletes the last reference to the file object, causing its destructor file.__del__
to be called. The internal state of the file object indicates the file is still open since f.close()
was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that's not open.
Since the implementation of os.system()
does not create any Python file objects, it does not seem likely that the system()
call is the origin of the error. Maybe you could show a bit more code?
You can add a reference to System.Configuration
in your project and then:
using System.Configuration;
then
string sValue = ConfigurationManager.AppSettings["BatchFile"];
with an app.config
file like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="BatchFile" value="blah.bat" />
</appSettings>
</configuration>
import platform
is_windows = any(platform.win32_ver())
or
import sys
is_windows = hasattr(sys, 'getwindowsversion')
If you're interested, I managed version numbers automatically from git infos here under the format
<major>.<minor>.<patch>-b<build>
where build is the total number of commits. You'll see the interesting code in the Makefile
. Here is the relevant part to access the different part of the version number:
LAST_TAG_COMMIT = $(shell git rev-list --tags --max-count=1)
LAST_TAG = $(shell git describe --tags $(LAST_TAG_COMMIT) )
TAG_PREFIX = "latex-tutorial-v"
VERSION = $(shell head VERSION)
# OR try to guess directly from the last git tag
#VERSION = $(shell git describe --tags $(LAST_TAG_COMMIT) | sed "s/^$(TAG_PREFIX)//")
MAJOR = $(shell echo $(VERSION) | sed "s/^\([0-9]*\).*/\1/")
MINOR = $(shell echo $(VERSION) | sed "s/[0-9]*\.\([0-9]*\).*/\1/")
PATCH = $(shell echo $(VERSION) | sed "s/[0-9]*\.[0-9]*\.\([0-9]*\).*/\1/")
# total number of commits
BUILD = $(shell git log --oneline | wc -l | sed -e "s/[ \t]*//g")
#REVISION = $(shell git rev-list $(LAST_TAG).. --count)
#ROOTDIR = $(shell git rev-parse --show-toplevel)
NEXT_MAJOR_VERSION = $(shell expr $(MAJOR) + 1).0.0-b$(BUILD)
NEXT_MINOR_VERSION = $(MAJOR).$(shell expr $(MINOR) + 1).0-b$(BUILD)
NEXT_PATCH_VERSION = $(MAJOR).$(MINOR).$(shell expr $(PATCH) + 1)-b$(BUILD)
Package
I used html-pdf
Easy to use and allows not only to save pdf as file, but also pipe pdf content to a WriteStream (so I could stream it directly to Google Storage to save there my reports).
Using css + images
It takes css into account. The only problem I faced - it ignored my images. The solution I found was to replace url in src
attrribute value by base64, e.g.
<img src="data:image/png;base64,iVBOR...kSuQmCC">
You can do it with your code or to use one of online converters, e.g. https://www.base64-image.de/
Compile valid html code from html fragment + css
html
document (I just appiled .html() method on jQuery selector).css
file.Using this two values (stored in variables html
and css
accordingly) I've compiled a valid html code using Template string
var htmlContent = `
<!DOCTYPE html>
<html>
<head>
<style>
${css}
</style>
</head>
<body id=direct-sellers-bill>
${html}
</body>
</html>`
and passed it to create
method of html-pdf.
You can do this with the standard Linq.ToLookup()
. This will create a collection of values for each unique key. Just select the first item in the collection
Persons.ToLookup(p => p.Id).Select(coll => coll.First());
You can try a rebase --interactive
session to amend your old commit (provided you did not already push those commits to another repo).
Sometimes the thing fixed in b.2. cannot be amended to the not-quite perfect commit it fixes, because that commit is buried deeply in a patch series.
That is exactly what interactive rebase is for: use it after plenty of "a"s and "b"s, by rearranging and editing commits, and squashing multiple commits into one.Start it with the last commit you want to retain as-is:
git rebase -i <after-this-commit>
An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit.
You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this:
pick deadbee The oneline of this commit
pick fa1afe1 The oneline of the next commit
...
The oneline descriptions are purely for your pleasure; git rebase will not look at them but at the commit names ("deadbee" and "fa1afe1" in this example), so do not delete or edit the names.
By replacing the command "pick" with the command "edit", you can tell git rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.
Lately I've come across yet another way of putting JS code inside PHP code. It involves Heredoc PHP syntax. I hope it'll be helpful for someone.
<?php
$script = <<< JS
$(function() {
// js code goes here
});
JS;
?>
After closing the heredoc construction the $script variable contains your JS code that can be used like this:
<script><?= $script ?></script>
The profit of using this way is that modern IDEs recognize JS code inside Heredoc and highlight it correctly unlike using strings. And you're still able to use PHP variables inside of JS code.
I tried from ubuntu terminal and I don't know why the GUI didn't show up according to tttthomasssss answer. So I followed the comment from KLDavenport and it worked. Here is the summary:
Open your terminal/command-line and type python then
>>> import nltk
.>>> nltk.download("stopwords")
This will store the stopwords corpus under the nltk_data. For my case it was /home/myusername/nltk_data/corpora/stopwords
.
If you need another corpus then visit nltk data and find the corpus with their ID. Then use the ID to download like we did for stopwords.
Eventually found the FontForge Windows installer package and opened the PDF through the installed program. Worked a treat, so happy.
while the popular answer with extends {}
works and is better than extends any
, it forces the T
to be an object
const foo = <T extends {}>(x: T) => x;
to avoid this and preserve the type-safety, you can use extends unknown
instead
const foo = <T extends unknown>(x: T) => x;
Just as an idea of a different style of string manipulation in C, here's an example which does not modify the source string, and does not use malloc
. To find spaces I use the libc function strpbrk
.
int print_words(const char *string, FILE *f)
{
static const char space_characters[] = " \t";
const char *next_space;
// Find the next space in the string
//
while ((next_space = strpbrk(string, space_characters)))
{
const char *p;
// If there are non-space characters between what we found
// and what we started from, print them.
//
if (next_space != string)
{
for (p=string; p<next_space; p++)
{
if(fputc(*p, f) == EOF)
{
return -1;
}
}
// Print a newline
//
if (fputc('\n', f) == EOF)
{
return -1;
}
}
// Advance next_space until we hit a non-space character
//
while (*next_space && strchr(space_characters, *next_space))
{
next_space++;
}
// Advance the string
//
string = next_space;
}
// Handle the case where there are no spaces left in the string
//
if (*string)
{
if (fprintf(f, "%s\n", string) < 0)
{
return -1;
}
}
return 0;
}
I haven't used connect by prior, but a quick search shows it's used for tree structures. In SQL Server, you use common table expressions to get similar functionality.
Yep, performance is the main reason and, as far as I know, the only reason.
If some of your files aren't getting compiled, maybe Python isn't able to write to the .pyc file, perhaps because of the directory permissions or something. Or perhaps the uncompiled files just aren't ever getting loaded... (scripts/modules only get compiled when they first get loaded)
You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.
use each() wrap within another each() until the last array.
for result.data[0].stuff[0].onetype[0]
in jQuery you could do the following:
`
$.each(data.result.data, function(index0, v) {
$.each(v, function (index1, w) {
$.each(w, function (index2, x) {
alert(x.id);
});
});
});
`
The short answer is yes, every implementing type will have to create its own backing variable. This is because an interface is analogous to a contract. All it can do is specify particular publicly accessible pieces of code that an implementing type must make available; it cannot contain any code itself.
Consider this scenario using what you suggest:
public interface InterfaceOne
{
int myBackingVariable;
int MyProperty { get { return myBackingVariable; } }
}
public interface InterfaceTwo
{
int myBackingVariable;
int MyProperty { get { return myBackingVariable; } }
}
public class MyClass : InterfaceOne, InterfaceTwo { }
We have a couple of problems here:
myBackingVariable
will MyClass
use?The most common approach taken is to declare the interface and a barebones abstract class that implements it. This allows you the flexibility of either inheriting from the abstract class and getting the implementation for free, or explicitly implementing the interface and being allowed to inherit from another class. It works something like this:
public interface IMyInterface
{
int MyProperty { get; set; }
}
public abstract class MyInterfaceBase : IMyInterface
{
int myProperty;
public int MyProperty
{
get { return myProperty; }
set { myProperty = value; }
}
}
You can't use brew install to upgrade an installed formula. If you want upgrade all of outdated formulas, you can use the command below.
brew outdated | xargs brew upgrade
In Python there's no POSIX regex classes
There are when using the regex
library: https://pypi.org/project/regex/
It is well maintained and supports Unicode regex, Posix regex and many more. The usage (method signatures) is very similar to Python's re
.
From the documentation:
[[:alpha:]]; [[:^alpha:]]
POSIX character classes are supported. These are normally treated as an alternative form of
\p{...}
.
(I'm not affiliated, just a user.)
CocoaPods' wiki on GitHub has the answer right in their FAQ:
Product > Edit Scheme
Build
<Project Dir>/Pods/<Name of spec you are trying to include>
. If it is empty (it should not be), verify that the ~/.cocoapods/master/<spec>/<spec>.podspec
has the correct github url in it.Preferences -> Locations -> Derived Data -> Advanced
and set build location to "Relative to Workspace".<td class="first"> <?php echo $proxy ?> </td>
is inside a literal string that you are echo
ing. End the string, or concatenate it correctly:
<td class="first">' . $proxy . '</td>
Apparently it does not and I didn't quite expect it would. HOWEVER Ivan brings up a good possibility that has escaped Android people.
What is the purpose of an emulator? to EMULATE, right? I don't see why for testing purposes -provided the tester understands the limitations- the emulator might not add a Wifi emulator.
It could for example emulate WiFi access by using the underlying internet connection of the host. Obviously testing WPA/WEP differencess would not make sense but at least it could toggle access via WiFi.
Or some sort of emulator plugin where there would be a base WiFi emulator that would emulate WiFi access via the underlying connection but then via configuration it could emulate WPA/WEP by providing a list of fake WiFi networks and their corresponding fake passwords that would be matched against a configurable list of credentials.
After all the idea is to do initial testing on the emulator and then move on to the actual device.
If you want the effect of a nested for loop, use:
import itertools
for i, j in itertools.product(range(x), range(y)):
# Stuff...
If you just want to loop simultaneously, use:
for i, j in zip(range(x), range(y)):
# Stuff...
Note that if x
and y
are not the same length, zip
will truncate to the shortest list. As @abarnert pointed out, if you don't want to truncate to the shortest list, you could use itertools.zip_longest
.
UPDATE
Based on the request for "a function that will read lists "t1" and "t2" and return all elements that are identical", I don't think the OP wants zip
or product
. I think they want a set
:
def equal_elements(t1, t2):
return list(set(t1).intersection(set(t2)))
# You could also do
# return list(set(t1) & set(t2))
The intersection
method of a set
will return all the elements common to it and another set (Note that if your lists contains other list
s, you might want to convert the inner list
s to tuples
first so that they are hashable; otherwise the call to set
will fail.). The list
function then turns the set back into a list.
UPDATE 2
OR, the OP might want elements that are identical in the same position in the lists. In this case, zip
would be most appropriate, and the fact that it truncates to the shortest list is what you would want (since it is impossible for there to be the same element at index 9 when one of the lists is only 5 elements long). If that is what you want, go with this:
def equal_elements(t1, t2):
return [x for x, y in zip(t1, t2) if x == y]
This will return a list containing only the elements that are the same and in the same position in the lists.
Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?
Tried it out. ResponseHeaders do not include status code.
If I'm not mistaken, WebClient
is capable of abstracting away multiple distinct requests in a single method call (e.g. correctly handling 100 Continue responses, redirects, and the like). I suspect that without using HttpWebRequest
and HttpWebResponse
, a distinct status code may not be available.
It occurs to me that, if you are not interested in intermediate status codes, you can safely assume the final status code is in the 2xx (successful) range, otherwise, the call would not be successful.
The status code unfortunately isn't present in the ResponseHeaders
dictionary.
One I use (notice this doesnt make "TestString" as "T est String" or " Test String").
function seperateCapitalised(capitalisedString) {
if (typeof capitalisedString !== "string" || capitalisedString.length === 0)
return capitalisedString;
var newStr = capitalisedString[0];
for (var i = 1; i < capitalisedString.length; i++) {
var char = capitalisedString[i];
if (char === char.toUpperCase() && isNaN(char)) {
newStr += ' ' + char;
}
else {
newStr += char;
}
}
return newStr;
}
Microsoft announced the intention to ship .NET Framework 4 on 29 September 2008. The Public Beta was released on 20 May 2009.
After the release of the .NET Framework 4, Microsoft released a set of enhancements, named Windows Server AppFabric, for application server capabilities in the form of AppFabric Hosting and in-memory distributed caching support.
.NET Framework 4.5 was released on 15 August 2012., a set of new or improved features were added into this version. The .NET Framework 4.5 is only supported on Windows Vista or later. The .NET Framework 4.5 uses Common Language Runtime 4.0, with some additional runtime features.
Metro-style apps are designed for specific form factors and leverage the power of the Windows operating system. A subset of the .NET Framework is available for building Metro style apps for Windows 8 using C# or Visual Basic. This subset is called .NET APIs for apps. The version of .NET Framework, runtime and libraries, used for Metro style apps is a part of the new Windows Runtime, which is the new platform and application model for Metro style apps. It is an ecosystem that houses many platforms and languages, including .NET Framework, C++ and HTML5/JavaScript.
In the .NET Framework 4.5, new asynchronous features were added to the C# and Visual Basic languages. These features add a task-based model for performing asynchronous operations.
In the .NET Framework 4.5, the following features have been added to make it simpler to write and maintain Windows Communication Foundation (WCF) applications:
For more information and access to reference links, please visit:
===========.Net 4.5 Poster=========
I have sumup it, here is the three method with example:
while
looplist<int> lst{4, 1, 2, 3, 5};
auto it = lst.begin();
while (it != lst.end()){
if((*it % 2) == 1){
it = lst.erase(it);// erase and go to next
} else{
++it; // go to next
}
}
for(auto it:lst)cout<<it<<" ";
cout<<endl; //4 2
remove_if
member funtion in list:list<int> lst{4, 1, 2, 3, 5};
lst.remove_if([](int a){return a % 2 == 1;});
for(auto it:lst)cout<<it<<" ";
cout<<endl; //4 2
std::remove_if
funtion combining with erase
member function:list<int> lst{4, 1, 2, 3, 5};
lst.erase(std::remove_if(lst.begin(), lst.end(), [](int a){
return a % 2 == 1;
}), lst.end());
for(auto it:lst)cout<<it<<" ";
cout<<endl; //4 2
for
loop , should note update the iterator:list<int> lst{4, 1, 2, 3, 5};
for(auto it = lst.begin(); it != lst.end();++it){
if ((*it % 2) == 1){
it = lst.erase(it); erase and go to next(erase will return the next iterator)
--it; // as it will be add again in for, so we go back one step
}
}
for(auto it:lst)cout<<it<<" ";
cout<<endl; //4 2
__stdcall
is the calling convention used for the function. This tells the compiler the rules that apply for setting up the stack, pushing arguments and getting a return value.
There are a number of other calling conventions, __cdecl
, __thiscall
, __fastcall
and the wonderfully named __declspec(naked)
. __stdcall
is the standard calling convention for Win32 system calls.
Wikipedia covers the details.
It primarily matters when you are calling a function outside of your code (e.g. an OS API) or the OS is calling you (as is the case here with WinMain). If the compiler doesn't know the correct calling convention then you will likely get very strange crashes as the stack will not be managed correctly.
Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects
.
See their examples:
string myJsonString = @"{
"Name": "Apple",
"Expiry": "\/Date(1230375600000+1300)\/",
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}";
// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);
I know this question is pretty old but if someone like me comes here looking for an answer then this might help. I have been able to overcome the above error with this.
1) Remove the below piece of code from the plugin maven-surefire-plugin
<reuseForks>true</reuseForks>
<argLine>-Xmx2048m</argLine>
2) Add the below goal:
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
The warning comes from the fact that you're dereferencing src
in the assignment. The expression *src
has type char
, which is an integral type. The expression "anotherstring"
has type char [14]
, which in this particular context is implicitly converted to type char *
, and its value is the address of the first character in the array. So, you wind up trying to assign a pointer value to an integral type, hence the warning. Drop the *
from *src
, and it should work as expected:
src = "anotherstring";
since the type of src
is char *
.
Create as many comparators as necessary. After, call the method "thenComparing" for each order category. It's a way of doing by Streams. See:
//Sort by first and last name
System.out.println("\n2.Sort list of person objects by firstName then "
+ "by lastName then by age");
Comparator<Person> sortByFirstName
= (p, o) -> p.firstName.compareToIgnoreCase(o.firstName);
Comparator<Person> sortByLastName
= (p, o) -> p.lastName.compareToIgnoreCase(o.lastName);
Comparator<Person> sortByAge
= (p, o) -> Integer.compare(p.age,o.age);
//Sort by first Name then Sort by last name then sort by age
personList.stream().sorted(
sortByFirstName
.thenComparing(sortByLastName)
.thenComparing(sortByAge)
).forEach(person->
System.out.println(person));
Look: Sort user defined object on multiple fields – Comparator (lambda stream)
Something like this might make it a bit easier, you could obviously use a script to generate this, or even excel
DELETE FROM tablename WHERE id IN (
1,
2,
3,
4,
5,
6
);
This topic really helped me, so I'd like to share my improvements. All credits go to the nixda, this is based on his answer.
For those who need to convert multiple csv's in a folder, just modify the directory. Outputfilenames will be identical to input, just with another extension.
Take care of the cleanup in the end, if you like to keep the original csv's you might not want to remove these.
Can be easily modifed to save the xlsx in another directory.
$workingdir = "C:\data\*.csv"
$csv = dir -path $workingdir
foreach($inputCSV in $csv){
$outputXLSX = $inputCSV.DirectoryName + "\" + $inputCSV.Basename + ".xlsx"
### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application
$excel.DisplayAlerts = $False
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
### Set the delimiter (, or ;) according to your regional settings
### $Excel.Application.International(3) = ,
### $Excel.Application.International(5) = ;
$query.TextFileOtherDelimiter = $Excel.Application.International(5)
### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
### Execute & delete the import query
$query.Refresh()
$query.Delete()
### Save & close the Workbook as XLSX. Change the output extension for Excel 2003
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()
}
## To exclude an item, use the '-exclude' parameter (wildcards if needed)
remove-item -path $workingdir -exclude *Crab4dq.csv
<?php
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use SplFileInfo;
# http://stackoverflow.com/a/3352564/283851
# https://gist.github.com/XzaR90/48c6b615be12fa765898
# Forked from https://gist.github.com/mindplay-dk/a4aad91f5a4f1283a5e2
/**
* Recursively delete a directory and all of it's contents - e.g.the equivalent of `rm -r` on the command-line.
* Consistent with `rmdir()` and `unlink()`, an E_WARNING level error will be generated on failure.
*
* @param string $source absolute path to directory or file to delete.
* @param bool $removeOnlyChildren set to true will only remove content inside directory.
*
* @return bool true on success; false on failure
*/
function rrmdir($source, $removeOnlyChildren = false)
{
if(empty($source) || file_exists($source) === false)
{
return false;
}
if(is_file($source) || is_link($source))
{
return unlink($source);
}
$files = new RecursiveIteratorIterator
(
new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
//$fileinfo as SplFileInfo
foreach($files as $fileinfo)
{
if($fileinfo->isDir())
{
if(rrmdir($fileinfo->getRealPath()) === false)
{
return false;
}
}
else
{
if(unlink($fileinfo->getRealPath()) === false)
{
return false;
}
}
}
if($removeOnlyChildren === false)
{
return rmdir($source);
}
return true;
}
You can use CustomMultiChildLayout to draw this kind of layouts. Here you can find a tutorial: How to Create Custom Layout Widgets in Flutter.
var array = $('#searchKeywords').val().split(",");
then
$.each(array,function(i){
alert(array[i]);
});
OR
for (i=0;i<array.length;i++){
alert(array[i]);
}
Did you try this?
myButton.setEnabled(false);
Update: Thanks to Gwen. Almost forgot that android:clickable
can be set in your XML layout to determine whether a button can be clickable or not.
Just weighing in here with a nice solution I have been using. This is similar to Lucky Soni's solution above in that it supports aggregation, but doesn't require hard coding of the field names.
cursor = db.<collection_name>.<my_query_with_aggregation>;
headerPrinted = false;
while (cursor.hasNext()) {
item = cursor.next();
if (!headerPrinted) {
print(Object.keys(item).join(','));
headerPrinted = true;
}
line = Object
.keys(item)
.map(function(prop) {
return '"' + item[prop] + '"';
})
.join(',');
print(line);
}
Save this as a .js
file, in this case we'll call it example.js
and run it with the mongo command line like so:
mongo <database_name> example.js --quiet > example.csv
According to the documentation:
max(iterable[, key])
max(arg1, arg2, *args[, key])
Return the largest item in an iterable or the largest of two or more arguments.If one positional argument is provided, iterable must be a non-empty iterable (such as a non-empty string, tuple or list). The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.
The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, max(a,b,c,key=func)).
What this is saying is that in your case, you are providing a list, in this case players
. Then the max
function will iterate over all the items in the list and compare them to each other to get a "maximum".
As you can imagine, with a complex object like a player
determining its value for comparison is tricky, so you are given the key
argument to determine how the max
function will decide the value of each player
. In this case, you are using a lambda function to say "for each p
in players
get p.totalscore
and use that as his value for comparison".
The pythonic way is to use enumerate
:
for idx,item in enumerate(list):
Use android:textAlignment="center"
<TextView
android:text="HOW WAS\nYOUR\nDAY?"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"
android:id="@+id/textView5"
/>
Decode the string to Unicode. Assuming it's UTF-8-encoded:
str.decode("utf-8")
Call the replace
method and be sure to pass it a Unicode string as its first argument:
str.decode("utf-8").replace(u"\u2022", "*")
Encode back to UTF-8, if needed:
str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
(Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str
shadows the built-in type str
.)
it's worth noting that the Win32_Product WMI class represents products as they are installed by Windows Installer. not every application use windows installer
however "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" represents applications for 32 bit. For 64 bit you also need to traverse "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" and since not every software has a 64 bit version the total applications installed are a union of keys on both locations that have "UninstallString" Value with them.
but the best options remains the same .traverse registry keys is a better approach since every application have an entry in registry[including the ones in Windows Installer].however the registry method is insecure as if anyone removes the corresponding key then you will not know the Application entry.On the contrary Altering the HKEY_Classes_ROOT\Installers is more tricky as it is linked with licensing issues such as Microsoft office or other products. for more robust solution you can always combine registry alternative with the WMI.
Machine learning packages like tensorflow 2.x are designed to work only on 64 bit Python as they are memory intensive.
Another one in Python, it's not in place as @cdiggins's, but I think it's easier to understand
def permute(num):
if len(num) == 2:
# get the permutations of the last 2 numbers by swapping them
yield num
num[0], num[1] = num[1], num[0]
yield num
else:
for i in range(0, len(num)):
# fix the first number and get the permutations of the rest of numbers
for perm in permute(num[0:i] + num[i+1:len(num)]):
yield [num[i]] + perm
for p in permute([1, 2, 3, 4]):
print p
According to String class documentation they are equivalent.
Documentation for String(String original)
also says that: Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.
Look for other responses, because it seems that Java documentation is misleading :(
Updating the ulimit worked for my Kosaraju's SCC implementation by fixing the segfault on both Python (Python segfault.. who knew!) and C++ implementations.
For my MAC, I found out the possible maximum via :
$ ulimit -s -H
65532
numpy has arrays that allow you to use other lists/arrays as indices:
import numpy
S=numpy.array(s)
S[a]=m
I liked the idea of checking a list like:
for i in `cat Hostlist`
do
ping -c1 -w2 $i | grep "PING" | awk '{print $2,$3}'
done
but that snippet doesn't care if a host is unreachable, so is not a great answer IMHO.
I ran with it and wrote
for i in `cat Hostlist`
do
ping -c1 -w2 $i >/dev/null 2>&1 ; echo $i $?
done
And I can then handle each accordingly.
this solved it npm cache clean --force
Ok, You should "construct" the html and find the .content div.
like this:
$.ajax({
url:href,
type:'GET',
success: function(data){
$('#content').html($(data).find('#content').html());
}
});
Simple!
I use GroovyShell in java to parse template with Groovy GString:
Binding binding = new Binding();
GroovyShell gs = new GroovyShell(binding);
// this JSONObject can also be replaced by any Java Object
JSONObject obj = new JSONObject();
obj.put("key", "value");
binding.setProperty("obj", obj)
String str = "${obj.key}";
String exp = String.format("\"%s\".toString()", str);
String res = (String) gs.evaluate(exp);
// value
System.out.println(str);
USE MyDatabase
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';
to get table counts
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'dbName';
this also works
USE databasename;
SHOW TABLES;
SELECT FOUND_ROWS();
This is more readable for me
awk '{if ($2 ~ /findtext/) print $3}' <infile>
You can't have two Content-Type
s (well technically that's what we're doing below, but they are separated with each part of the multipart, but the main type is multipart). That's basically what you are expecting with your method. You are expecting mutlipart and json together as the main media type. The Employee
data needs to be part of the multipart. So you can add a @FormDataParam("emp")
for the Employee
.
@FormDataParam("emp") Employee emp) { ...
Here's the class I used for testing
@Path("/multipart")
public class MultipartResource {
@POST
@Path("/upload2")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadFileWithData(
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition cdh,
@FormDataParam("emp") Employee emp) throws Exception{
Image img = ImageIO.read(fileInputStream);
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(img)));
System.out.println(cdh.getName());
System.out.println(emp);
return Response.ok("Cool Tools!").build();
}
}
First I just tested with the client API to make sure it works
@Test
public void testGetIt() throws Exception {
final Client client = ClientBuilder.newBuilder()
.register(MultiPartFeature.class)
.build();
WebTarget t = client.target(Main.BASE_URI).path("multipart").path("upload2");
FileDataBodyPart filePart = new FileDataBodyPart("file",
new File("stackoverflow.png"));
// UPDATE: just tested again, and the below code is not needed.
// It's redundant. Using the FileDataBodyPart already sets the
// Content-Disposition information
filePart.setContentDisposition(
FormDataContentDisposition.name("file")
.fileName("stackoverflow.png").build());
String empPartJson
= "{"
+ " \"id\": 1234,"
+ " \"name\": \"Peeskillet\""
+ "}";
MultiPart multipartEntity = new FormDataMultiPart()
.field("emp", empPartJson, MediaType.APPLICATION_JSON_TYPE)
.bodyPart(filePart);
Response response = t.request().post(
Entity.entity(multipartEntity, multipartEntity.getMediaType()));
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
response.close();
}
I just created a simple Employee
class with an id
and name
field for testing. This works perfectly fine. It shows the image, prints the content disposition, and prints the Employee
object.
I'm not too familiar with Postman, so I saved that testing for last :-)
It appears to work fine also, as you can see the response "Cool Tools"
. But if we look at the printed Employee
data, we'll see that it's null. Which is weird because with the client API it worked fine.
If we look at the Preview window, we'll see the problem
There's no Content-Type
header for the emp
body part. You can see in the client API I explicitly set it
MultiPart multipartEntity = new FormDataMultiPart()
.field("emp", empPartJson, MediaType.APPLICATION_JSON_TYPE)
.bodyPart(filePart);
So I guess this is really only part of a full answer. Like I said, I am not familiar with Postman So I don't know how to set Content-Type
s for individual body parts. The image/png
for the image was automatically set for me for the image part (I guess it was just determined by the file extension). If you can figure this out, then the problem should be solved. Please, if you find out how to do this, post it as an answer.
See UPDATE below for solution
Basic configurations:
Dependency:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey2.version}</version>
</dependency>
Client config:
final Client client = ClientBuilder.newBuilder()
.register(MultiPartFeature.class)
.build();
Server config:
// Create JAX-RS application.
final Application application = new ResourceConfig()
.packages("org.glassfish.jersey.examples.multipart")
.register(MultiPartFeature.class);
If you're having problems with the server configuration, one of the following posts might help
So as you can see from the Postman client, some clients are unable to set individual parts' Content-Type, this includes the browser, in regards to it's default capabilities when using FormData
(js).
We can't expect the client to find away around this, so what we can do, is when receiving the data, explicitly set the Content-Type before deserializing. For example
@POST
@Path("upload2")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFileAndJSON(@FormDataParam("emp") FormDataBodyPart jsonPart,
@FormDataParam("file") FormDataBodyPart bodyPart) {
jsonPart.setMediaType(MediaType.APPLICATION_JSON_TYPE);
Employee emp = jsonPart.getValueAs(Employee.class);
}
It's a little extra work to get the POJO, but it is a better solution than forcing the client to try and find it's own solution.
Another option is to use a String parameter and use whatever JSON library you use to deserialze the String to the POJO (like Jackson ObjectMapper). With the previous option, we just let Jersey handle the deserialization, and it will use the same JSON library it uses for all the other JSON endpoints (which might be preferred).
from within the directory of "my_script.py" you can simply do:
%run ./my_script.py
This feature has been added in dplyr v0.3. You can now pass a named character vector to the by
argument in left_join
(and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:
left_join(test_data, kantrowitz, by = c("first_name" = "name"))
I made this helper class in C# (Xamarin) to programmatically set the text property. It which works pretty well for me:
internal static class FontAwesomeManager
{
private static readonly Typeface AwesomeFont = Typeface.CreateFromAsset(App.Application.Context.Assets, "FontAwesome.ttf");
private static readonly Dictionary<FontAwesomeIcon, string> IconMap = new Dictionary<FontAwesomeIcon, string>
{
{FontAwesomeIcon.Bars, "\uf0c9"},
{FontAwesomeIcon.Calendar, "\uf073"},
{FontAwesomeIcon.Child, "\uf1ae"},
{FontAwesomeIcon.Cog, "\uf013"},
{FontAwesomeIcon.Eye, "\uf06e"},
{FontAwesomeIcon.Filter, "\uf0b0"},
{FontAwesomeIcon.Link, "\uf0c1"},
{FontAwesomeIcon.ListOrderedList, "\uf0cb"},
{FontAwesomeIcon.PencilSquareOutline, "\uf044"},
{FontAwesomeIcon.Picture, "\uf03e"},
{FontAwesomeIcon.PlayCircleOutline, "\uf01d"},
{FontAwesomeIcon.SignOut, "\uf08b"},
{FontAwesomeIcon.Sliders, "\uf1de"}
};
public static void Awesomify(this TextView view, FontAwesomeIcon icon)
{
var iconString = IconMap[icon];
view.Text = iconString;
view.SetTypeface(AwesomeFont, TypefaceStyle.Normal);
}
}
enum FontAwesomeIcon
{
Bars,
Calendar,
Child,
Cog,
Eye,
Filter,
Link,
ListOrderedList,
PencilSquareOutline,
Picture,
PlayCircleOutline,
SignOut,
Sliders
}
Should be easy enough to convert to Java, I think. Hope it helps someone!
Well the code you've shown doesn't actually include adding any Integers to the ArrayList
- but if you do know that you've got integers, you can use:
sum = (double) ((Integer) marks.get(i)).intValue();
That will convert it to an int
, which can then be converted to double
. You can't just cast directly between the boxed classes.
Note that if you can possibly use generics for your ArrayList
, your code will be clearer.
Just wrap your WebElement into Select Object as shown below
Select dropdown = new Select(driver.findElement(By.id("identifier")));
Once this is done you can select the required value in 3 ways. Consider an HTML file like this
<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>
Now to identify dropdown do
Select dropdown = new Select(driver.findElement(By.id("designation")));
To select its option say 'Programmer' you can do
dropdown.selectByVisibleText("Programmer ");
or
dropdown.selectByIndex(1);
or
dropdown.selectByValue("prog");
Happy Coding :)
Simple solution (ES6)
If you don't have duplicate element
Array.prototype.remove = function(elem) {
var indexElement = this.findIndex(el => el === elem);
if (indexElement != -1)
this.splice(indexElement, 1);
return this;
};
This worked for me, using the latest release of Angular 2 (2.0.0-rc.1):
main.ts
import {enableProdMode} from '@angular/core';
enableProdMode();
bootstrap(....);
Here is the function reference from their docs: https://angular.io/api/core/enableProdMode
Here is a more modular and cleaner way to circle crop your bitmap in Glide:
BitmapTransformation
then override transform
method like this : For Glide 4.x.x
public class CircularTransformation extends BitmapTransformation {
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(null, toTransform);
circularBitmapDrawable.setCircular(true);
Bitmap bitmap = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
circularBitmapDrawable.setBounds(0, 0, outWidth, outHeight);
circularBitmapDrawable.draw(canvas);
return bitmap;
}
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {}
}
For Glide 3.x.x
public class CircularTransformation extends BitmapTransformation {
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(null, toTransform);
circularBitmapDrawable.setCircular(true);
Bitmap bitmap = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
circularBitmapDrawable.setBounds(0, 0, outWidth, outHeight);
circularBitmapDrawable.draw(canvas);
return bitmap;
}
@Override
public String getId() {
// Return some id that uniquely identifies your transformation.
return "CircularTransformation";
}
}
Glide.with(yourActivity)
.load(yourUrl)
.asBitmap()
.transform(new CircularTransformation())
.into(yourView);
Hope this helps :)
No call mp.start with an OnPreparedListener to avoid the zero state i the log..
var node = document.getElementsByClassName("second")[0].firstElementChild
Disclaimer: Browser compliance on getElementsByClassName
and firstElementChild
are shaky. DOM-shims fix those problems though.
Below two commands works for me.
vagrant ssh
sudo mount -t vboxsf -o uid=1000,gid=1000 vagrant /vagrant
The best answer to this could be
Don't use selct for this job use input instead
like this
echo $this->Form->input('field_name', array(
'type' => 'select',
'options' => $options_arr,
'label' => 'label here',
'value' => $id, // default value
'escape' => false, // prevent HTML being automatically escaped
'error' => false,
'class' => 'form-control' // custom class you want to enter
));
Hope it helps.
The :trimAll
subroutine below:
!
, %
, ^
, etc.)Read comments for references and info.
@echo off & setLocal enableExtensions disableDelayedExpansion
:: https://www.dostips.com/forum/viewtopic.php?t=4308
(call;) %= sets errorLevel to 0 =%
(set lf=^
%= BLANK LINE REQUIRED =%
)
:: kudos to Carlos for superior method of capturing CR
:: https://www.dostips.com/forum/viewtopic.php?p=40757#p40757
set "cr=" & if not defined cr for /f "skip=1" %%C in (
'echo(^|replace ? . /w /u'
) do set "cr=%%C"
set ^"orig= !random! ! ^^! ^^^^! ^"^^ ^&^"^& ^^^" %%os%% ^"
call :trimAll res1 orig
setLocal enableDelayedExpansion
call :trimAll res2 orig
echo(orig: [!orig!]
echo(res1: [!res1!]
echo(res2: [!res2!]
endLocal
endLocal & goto :EOF
:trimAll result= original=
:: trims leading and trailing whitespace from a string
:: special thanks to Jeb for
:: https://stackoverflow.com/a/8257951
setLocal
set "ddx=!" %= is delayed expansion enabled or disabled? =%
setLocal enableDelayedExpansion
set "die=" & if not defined %2 (
>&2 echo( ERROR: var "%2" not defined & set "die=1"
) else set "str=!%2!" %= if =%
if not defined die for %%L in ("!lf!") ^
do if "!str!" neq "!str:%%~L=!" (
>&2 echo( ERROR: var "%2" contains linefeeds & set "die=1"
) %= if =%
if not defined die for %%C in ("!cr!") ^
do if "!str!" neq "!str:%%~C=!" (
>&2 echo( ERROR: var "%2" contains carriage returns
set "die=1"
) %= if =%
if defined die goto die
(for /f eol^= %%A in ("!str!") do rem nop
) || (
>&2 echo(WARNING: var "%2" consists entirely of whitespace
endLocal & endLocal & set "%1=" & exit /b 0
) %= cond exec =%
:: prepare string for trimming...
:: double carets
set "str=!str:^=^^^^!"
:: double quotes
set "str=!str:"=""!"
:: escape exclaims
set "str=%str:!=^^^!%" !
:: act of CALLing subfunction with
:: expanded string trims trailing whitespace
call :_trimAll "%%str%%
:: prepare string to be passed over endLocal boundary...
:: double carets again if delayed expansion enabled
if not defined ddx set "str=!str:^=^^^^!"
:: escape exclaims again if delayed expansion enabled
if not defined ddx set "str=%str:!=^^^!%" !
:: restore quotes
set "str=!str:""="!"
:: pass string over endLocal boundary and trim leading whitespace
for /f tokens^=*^ eol^= %%a in ("!str!") do (
endLocal & endLocal & set "%1=%%a" !
) %= for /f =%
exit /b 0
:die
endLocal & endLocal & set "%1=" & exit /b 1
:_trimAll
:: subfunction
:: trailing exclaim is required as explained by Jeb at
:: https://www.dostips.com/forum/viewtopic.php?p=6933#p6933
set "str=%~1" !
exit /b 0
HTH and HNY! ;)
From Dianne Hackborn:
Things That Cannot Change:
The most obvious and visible of these is the “manifest package name,” the unique name you give to your application in its AndroidManifest.xml. The name uses a Java-language-style naming convention, with Internet domain ownership helping to avoid name collisions. For example, since Google owns the domain “google.com”, the manifest package names of all of our applications should start with “com.google.” It’s important for developers to follow this convention in order to avoid conflicts with other developers.
Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application.
More on things you cannot change here
Regarding your question on the URL from Google Play, the package defined there is linked to the app's fully qualified package you have in your AndroidManifest.xml file. More on Google Play's link formats here.
Use filter
, or if the number of dictionaries in exampleSet
is too high, use ifilter
of the itertools
module. It would return an iterator, instead of filling up your system's memory with the entire list at once:
from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
print elem
I was inserting script
tags dynamically with this usual alternative to eval
and simply set a global property currentComponentScript
right before adding to the DOM.
const old = el.querySelector("script")[0];
const replacement = document.createElement("script");
replacement.setAttribute("type", "module");
replacement.appendChild(document.createTextNode(old.innerHTML));
window.currentComponentScript = replacement;
old.replaceWith(replacement);
Doesn't work in a loop though. The DOM doesn't run the scripts until the next macrotask so a batch of them will only see the last value set. You'd have to setTimeout
the whole paragraph, and then setTimeout
the next one after the previous finishes. I.e. chain the setTimeouts, not just call setTimeout
multiple times in a row from a loop.
Swift 5.0 :
var dayComponent = DateComponents()
dayComponent.day = 1 // For removing one day (yesterday): -1
let theCalendar = Calendar.current
let nextDate = theCalendar.date(byAdding: dayComponent, to: Date())
print("nextDate : \(nextDate)")
Objective C :
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = 1;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDate *nextDate = [theCalendar dateByAddingComponents:dayComponent toDate:[NSDate date] options:0];
NSLog(@"nextDate: %@ ...", nextDate);
This should be self-explanatory.
#include <iostream>
#include <deque>
#include <queue>
struct node
{
int data;
node *left;
node *right;
};
bool isBalanced(node *root)
{
if ( !root)
{
return true;
}
std::queue<node *> q1;
std::queue<int> q2;
int level = 0, last_level = -1, node_count = 0;
q1.push(root);
q2.push(level);
while ( !q1.empty() )
{
node *current = q1.front();
level = q2.front();
q1.pop();
q2.pop();
if ( level )
{
++node_count;
}
if ( current->left )
{
q1.push(current->left);
q2.push(level + 1);
}
if ( current->right )
{
q1.push(current->right);
q2.push(level + 1);
}
if ( level != last_level )
{
std::cout << "Check: " << (node_count ? node_count - 1 : 1) << ", Level: " << level << ", Old level: " << last_level << std::endl;
if ( level && (node_count - 1) != (1 << (level-1)) )
{
return false;
}
last_level = q2.front();
if ( level ) node_count = 1;
}
}
return true;
}
int main()
{
node tree[15];
tree[0].left = &tree[1];
tree[0].right = &tree[2];
tree[1].left = &tree[3];
tree[1].right = &tree[4];
tree[2].left = &tree[5];
tree[2].right = &tree[6];
tree[3].left = &tree[7];
tree[3].right = &tree[8];
tree[4].left = &tree[9]; // NULL;
tree[4].right = &tree[10]; // NULL;
tree[5].left = &tree[11]; // NULL;
tree[5].right = &tree[12]; // NULL;
tree[6].left = &tree[13];
tree[6].right = &tree[14];
tree[7].left = &tree[11];
tree[7].right = &tree[12];
tree[8].left = NULL;
tree[8].right = &tree[10];
tree[9].left = NULL;
tree[9].right = &tree[10];
tree[10].left = NULL;
tree[10].right= NULL;
tree[11].left = NULL;
tree[11].right= NULL;
tree[12].left = NULL;
tree[12].right= NULL;
tree[13].left = NULL;
tree[13].right= NULL;
tree[14].left = NULL;
tree[14].right= NULL;
std::cout << "Result: " << isBalanced(tree) << std::endl;
return 0;
}
TimezoneDb provides a free API: http://timezonedb.com/api
GenoNames also has a RESTful API available to get the current time for a given location: http://www.geonames.org/export/ws-overview.html.
You can use Greenwich, UK if you'd like GMT.
Certainly, for combining the advantage of common completeness, dynamics and portability with minimum dependency
you will combine Samuel Neff's static dictionary with a platform specific query as e.g. by Bryan Denny.
E.g. under Linux command line tool ´xdg-mime´ might do the latter part.
Kotlin?
val dialogBuilder = AlertDialog.Builder(this.context)
dialogBuilder.setTitle("Alert")
.setMessage(message)
.setPositiveButton("OK", null)
.create()
.show()
long diffSeconds = (diff / 1000)%60;
try this and let me know if it works correctly...
If you know you're always going to use bash, it's much easier to always use the double bracket conditional compound command [[ ... ]]
, instead of the Posix-compatible single bracket version [ ... ]
. Inside a [[ ... ]]
compound, word-splitting and pathname expansion are not applied to words, so you can rely on
if [[ $aug1 == "and" ]];
to compare the value of $aug1
with the string and
.
If you use [ ... ]
, you always need to remember to double quote variables like this:
if [ "$aug1" = "and" ];
If you don't quote the variable expansion and the variable is undefined or empty, it vanishes from the scene of the crime, leaving only
if [ = "and" ];
which is not a valid syntax. (It would also fail with a different error message if $aug1
included white space or shell metacharacters.)
The modern [[
operator has lots of other nice features, including regular expression matching.
I personally made this python code to change the color of a whole image opened or created with openCV . I am sorry if it's not good enough , I am beginner .
def OpenCvImgColorChanger(img,blue = 0,green = 0,red = 0):
line = 1
ImgColumn = int(img.shape[0])-2
ImgRaw = int(img.shape[1])-2
for j in range(ImgColumn):
for i in range(ImgRaw):
if i == ImgRaw-1:
line +=1
img[line][i][2] = int(red)
img[line][i][1] = int(green)
img[line][i][0] = int(blue)
With n**.5
, you are not squaring n, but taking the square root.
Consider the number 20; the integer factors are 1, 2, 4, 5, 10, and 20. When you divide 20 by 2 and get 10, you know that it is also divisible by 10, without having to check. When you divide it by 4 and get 5, you know it is divisible by both 4 and 5, without having to check for 5.
After reaching this halfway point in the factors, you will have no more numbers to check which you haven't already recognized as factors earlier. Therefore, you only need to go halfway to see if something is prime, and this halfway point can be found by taking the number's square root.
Also, the reason 1 isn't a prime number is because prime numbers are defined as having 2 factors, 1 and itself. i.e 2 is 1*2, 3 is 1*3, 5 is 1*5. But 1 (1*1) only has 1 factor, itself. Therefore, it doesn't meet this definition.
You could try my Beavertail ADSI browser - it should show you the current AD tree, and from it, you should be able to figure out the path and all.
Or if you're on .NET 3.5, using the System.DirectoryServices.AccountManagement
namespace, you could also do it programmatically:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
This would create a basic, default domain context and you should be able to peek at its properties and find a lot of stuff from it.
Or:
UserPrincipal myself = UserPrincipal.Current;
This will give you a UserPrincipal
object for yourself, again, with a ton of properties to inspect. I'm not 100% sure what you're looking for - but you most likely will be able to find it on the context or the user principal somewhere!
You can either
1) Declare printMenu()
, getUserchoice()
and input as static
OR
2) If you want to design it better, move the logic from your main
into a separate instance method. And then from the main
create a new instance of your class and call your instance method(s)
The Problem is with your code formatting,
inorder to use strtotime()
You should replace '06/Oct/2011:19:00:02'
with 06/10/2011 19:00:02
and date('d/M/Y:H:i:s', $date);
with date('d/M/Y H:i:s', $date);
. Note the spaces in between.
So the final code looks like this
$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);
I needed a list with all months between 2 dates for statistics. The 2 dates are the start and enddate from a subscription. So the list shows all months and the amount of subscriptions per month.
MYSQL
CREATE PROCEDURE `get_amount_subscription_per_month`()
BEGIN
-- Select the ultimate start and enddate from subscribers
select @startdate := min(DATE_FORMAT(a.startdate, "%Y-%m-01")),
@enddate := max(DATE_FORMAT(a.enddate, "%Y-%m-01")) + interval 1 MONTH
from subscription a;
-- Tmp table with all months (dates), you can always format them with DATE_FORMAT)
DROP TABLE IF EXISTS tmp_months;
create temporary table tmp_months (
year_month date,
PRIMARY KEY (year_month)
);
set @tempDate=@startdate; #- interval 1 MONTH;
-- Insert every month in tmp table
WHILE @tempDate <= @enddate DO
insert into tmp_months (year_month) values (@tempDate);
set @tempDate = (date(@tempDate) + interval 1 MONTH);
END WHILE;
-- All months
select year_month from tmp_months;
-- If you want the amount of subscription per month else leave it out
select mnd.year_month, sum(subscription.amount) as subscription_amount
from tmp_months mnd
LEFT JOIN subscription ON mnd.year_month >= DATE_FORMAT(subscription.startdate, "%Y-%m-01") and mnd.year_month <= DATE_FORMAT(subscription.enddate, "%Y-%m-01")
GROUP BY mnd.year_month;
END
In case someone needs ternary operator with implicit casting:
/**'[_t]' for ternary operator*/
@Suppress("FunctionName")
@OptIn(ExperimentalContracts::class)
fun <T> _t(bool: Boolean, onTrue: T, onFalse: T): T
{
contract { returns() implies bool }
return if (bool) onTrue else onFalse
}
Although not sure how useful this is
Technically doing:
String myString = "\u0048\u0065\u006C\u006C\u006F World";
automatically converts it to "Hello World"
, so I assume you are reading in the string from some file. In order to convert it to "Hello" you'll have to parse the text into the separate unicode digits, (take the \uXXXX
and just get XXXX
) then do Integer.ParseInt(XXXX, 16)
to get a hex value and then case that to char
to get the actual character.
Edit: Some code to accomplish this:
String str = myString.split(" ")[0];
str = str.replace("\\","");
String[] arr = str.split("u");
String text = "";
for(int i = 1; i < arr.length; i++){
int hexVal = Integer.parseInt(arr[i], 16);
text += (char)hexVal;
}
// Text will now have Hello
Other than the options mentioned above, there are a couple of other Solutions which works well with automated deployments or require fewer configuration changes.
1. Modifying the project file (.CsProj) file
MSBuild supports the EnvironmentName
Property which can help to set the right environment variable as per the Environment you wish to Deploy. The environment name would be added in the web.config during the Publish phase.
Simply open the project file (*.csProj) and add the following XML.
<!-- Custom Property Group added to add the Environment name during publish
The EnvironmentName property is used during the publish for the Environment variable in web.config
-->
<PropertyGroup Condition=" '$(Configuration)' == '' Or '$(Configuration)' == 'Debug'">
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' != '' AND '$(Configuration)' != 'Debug' ">
<EnvironmentName>Production</EnvironmentName>
</PropertyGroup>
Above code would add the environment name as Development
for Debug configuration or if no configuration is specified. For any other Configuration the Environment name would be Production
in the generated web.config file. More details here
2. Adding the EnvironmentName Property in the publish profiles.
We can add the <EnvironmentName>
property in the publish profile as well. Open the publish profile file which is located at the Properties/PublishProfiles/{profilename.pubxml}
This will set the Environment name in web.config when the project is published. More Details here
<PropertyGroup>
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
3. Command line options using dotnet publish
Additionaly, we can pass the property EnvironmentName
as a command line option to the dotnet publish
command. Following command would include the environment variable as Development
in the web.config file.
dotnet publish -c Debug -r win-x64 /p:EnvironmentName=Development
you can use this minified jQuery snippet to detect if your user is viewing using a mobile device. If you need to test for a specific device I’ve included a collection of JavaScript snippets below which can be used to detect various mobile handheld devices such as iPad, iPhone, iPod, iDevice, Andriod, Blackberry, WebOs and Windows Phone.
/**
* jQuery.browser.mobile (http://detectmobilebrowser.com/)
* jQuery.browser.mobile will be true if the browser is a mobile device
**/
(function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|symbian|treo|up.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|e-|e/|-[a-w])|libw|lynx|m1-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(-|2|g)|yas-|your|zeto|zte-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);
Example Usage:
if(jQuery.browser.mobile)
{
console.log(‘You are using a mobile device!’);
}
else
{
console.log(‘You are not using a mobile device!’);
}
Detect iPad
var isiPad = /ipad/i.test(navigator.userAgent.toLowerCase());
if (isiPad)
{
…
}
Detect iPhone
var isiPhone = /iphone/i.test(navigator.userAgent.toLowerCase());
if (isiPhone)
{
…
}
Detect iPod
var isiPod = /ipod/i.test(navigator.userAgent.toLowerCase());
if (isiPod)
{
…
}
Detect iDevice
var isiDevice = /ipad|iphone|ipod/i.test(navigator.userAgent.toLowerCase());
if (isiDevice)
{
…
}
Detect Andriod
var isAndroid = /android/i.test(navigator.userAgent.toLowerCase());
if (isAndroid)
{
…
}
Detect Blackberry
var isBlackBerry = /blackberry/i.test(navigator.userAgent.toLowerCase());
if (isBlackBerry)
{
…
}
Detect WebOs
var isWebOS = /webos/i.test(navigator.userAgent.toLowerCase());
if (isWebOS)
{
…
}
Detect Windows Phone
var isWindowsPhone = /windows phone/i.test(navigator.userAgent.toLowerCase());
if (isWindowsPhone)
{
…
}
Can you try using document.location.replace()
it is used to clear the last entry in the history and replace it with the address of a new url. replace()
removes the URL of the current document from the document history, meaning that it is not possible to use the "back" button to navigate back to the original document.
<script type="text/javascript">
function Navigate(){
window.location.replace('your link');
return false;
}
</script>
HTML:
<button onclick="Navigate()">Replace document</button>
If you are making your own module then add CommonModule in imports in your own module
You don't even need to do the check manually, File.Open does it for you. Try:
using (StreamWriter sw = new StreamWriter(File.Open(path, System.IO.FileMode.Append)))
{
Ref: http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx
Use the ViewPager.onPageChangeListener
:
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.
}
});
You can also use a pretty simple for
loop:
for f in `find . -not -name "*Music*"`
do
cp $f /target/dir
done
With Yglu Structural Templating, your example can be written:
foo: !()
!? $.propname:
type: number
default: !? $.default
bar:
!apply .foo:
propname: "some_prop"
default: "some default"
Disclaimer: I am the author or Yglu.
For newer Android platforms, one can execute a system utility screencap
in /system/bin
to get the screenshot without root permission.
You can try /system/bin/screencap -h
to see how to use it under adb or any shell.
By the way, I think this method is only good for single snapshot. If we want to capture multiple frames for screen play, it will be too slow. I don't know if there exists any other approach for a faster screen capture.
Alternatively you can do:
Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
risultato=rs.getString(1);
}
But use Sean Bright's answer instead for your scenario.
Enabling a previously-installed Sublime Text package
If you have a subdirectory under Sublime Text 2\Packages
for a package that isn't working, you may need to enable it.
Follow these steps to enable an installed package:
Preferences > Package Control > Enable Package
Rather than abusing plot
or annotate
, which will be inefficient for many lines, you can use matplotlib.collections.LineCollection
:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")
# Takes list of lines, where each line is a sequence of coordinates
l1 = [(70, 100), (70, 250)]
l2 = [(70, 90), (90, 200)]
lc = LineCollection([l1, l2], color=["k","blue"], lw=2)
plt.gca().add_collection(lc)
plt.show()
It takes a list of lines [l1, l2, ...]
, where each line is a sequence of N coordinates (N can be more than two).
The standard formatting keywords are available, accepting either a single value, in which case the value applies to every line, or a sequence of M values
, in which case the value for the ith line is values[i % M]
.
Just for completeness, another way is std::string(&v[0])
(although you need to ensure your string is null-terminated and std::string(v.data())
is generally to be preferred.
The difference is that you can use the former technique to pass the vector to functions that want to modify the buffer, which you cannot do with .data().
It's late but all above mentioned solutions didn't worked for me and finally this single line would accept all android licences.
yes | sdkmanager --licenses && sdkmanager --update
you can do like this:
if("merchant_id" in thisSession){ /** will return true if exist */
console.log('Exist!');
}
or
if(thisSession["merchant_id"]){ /** will return its value if exist */
console.log('Exist!');
}
I always use the isoformat()
function for this.
from datetime import date
today = date.today().isoformat()
print(today) # '2018-12-05'
Note that this also works on datetime objects if you need the time in standard format as well.
from datetime import datetime
now = datetime.today().isoformat()
print(now) # '2018-12-05T11:15:55.126382'
Excel has a little known feature called "Web queries" which let you retrieve data from almost every web page without additional programming.
A web query basicly runs a HTTP request directly from within Excel and copies some or all of the received data (and optionally formatting) into the worksheet.
After you've defined the web query you can refresh it at any time without even leaving excel. So you don't have to actually "export" data and save it to a file - you'd rather refresh the data just like from a database.
You can even make use of URL parameters by having excel prompt you for certain filter criteria etc...
However the cons I've noticed so far are:
Here is a question about how to create web queries in Excel. It links to a Microsoft Help site about How-To Get external data from a Web page
File.Create
returns a FileStream
object that you can call Close()
on.
Use the code below:
using Newtonsoft.Json;
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(ds.Tables[0]);
==
is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString
do not contain "a"
, but "a\n"
(if you look closely, you'll see the extra line break in your example output).
You can use the strings.TrimRight
function to remove trailing whitespaces from your input:
if strings.TrimRight(input, "\n") == "a" {
// ...
}
Does this work without alternation?
^((part)1(, \22)?)?(part2)?$
or why not this?
^((part)1(, (\22))?)?(\4)?$
The first works for all conditions the second for all but part2
(using GNU sed 4.1.5)
As King King said, you must add the browser specific prefix. This should cover most browsers:
@keyframes flickerAnimation {_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
-webkit-animation: flickerAnimation 1s infinite;_x000D_
-moz-animation: flickerAnimation 1s infinite;_x000D_
-o-animation: flickerAnimation 1s infinite;_x000D_
animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
One can also make use of the tracemalloc
module from the Python standard library. It seems to work well for objects whose class is implemented in C (unlike Pympler, for instance).
The following selects all descendant elements and disables them:
$("#dcacl").find("*").prop("disabled", true);
But it only really makes sense to disable certain element types: inputs, buttons, etc., so you want a more specific selector:
$("#dcac1").find(":input").prop("disabled",true);
// noting that ":input" gives you the equivalent of
$("#dcac1").find("input,select,textarea,button").prop("disabled",true);
To re-enable you just set "disabled" to false.
I want to Disable them at loading the page and then by a click i can enable them
OK, so put the above code in a document ready handler, and setup an appropriate click handler:
$(document).ready(function() {
var $dcac1kids = $("#dcac1").find(":input");
$dcac1kids.prop("disabled",true);
// not sure what you want to click on to re-enable
$("selector for whatever you want to click").one("click",function() {
$dcac1kids.prop("disabled",false);
}
}
I've cached the results of the selector on the assumption that you're not adding more elements to the div between the page load and the click. And I've attached the click handler with .one()
since you haven't specified a requirement to re-disable the elements so presumably the event only needs to be handled once. Of course you can change the .one()
to .click()
if appropriate.
Here is an example that works on Chrome 5.0.375.125.
The page B (iframe content):
<html>
<head></head>
<body>
<script>
top.postMessage('hello', 'A');
</script>
</body>
</html>
Note the use of top.postMessage
or parent.postMessage
not window.postMessage
here
The page A:
<html>
<head></head>
<body>
<iframe src="B"></iframe>
<script>
window.addEventListener( "message",
function (e) {
if(e.origin !== 'B'){ return; }
alert(e.data);
},
false);
</script>
</body>
</html>
A and B must be something like http://domain.com
EDIT:
From another question, it looks the domains(A and B here) must have a /
for the postMessage
to work properly.
There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.
You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.
When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.
What operating system?
Here on Ubuntu, I have
$ dpkg -S /usr/include/GL/gl.h
mesa-common-dev: /usr/include/GL/gl.h
$
but not the difference in a) capitalization and b) forward/backward slashes. Your example is likely to be wrong in its use of backslashes.
Since Python is a strongly typed language, concatenating a string and an integer as you may do in Perl makes no sense, because there's no defined way to "add" strings and numbers to each other.
Explicit is better than implicit.
...says "The Zen of Python", so you have to concatenate two string objects. You can do this by creating a string from the integer using the built-in str()
function:
>>> "abc" + str(9)
'abc9'
Alternatively use Python's string formatting operations:
>>> 'abc%d' % 9
'abc9'
Perhaps better still, use str.format()
:
>>> 'abc{0}'.format(9)
'abc9'
The Zen also says:
There should be one-- and preferably only one --obvious way to do it.
Which is why I've given three options. It goes on to say...
Although that way may not be obvious at first unless you're Dutch.
I just wrote this to solve a similar (ish) problem. It doesn't exactly do what you may be looking for, ie it doesn't take into account how the interpreter stores the object.
But, if you are using V8, it should give you a fairly ok approximation as the awesome prototyping and hidden classes lick up most of the overhead.
function roughSizeOfObject( object ) {
var objectList = [];
var recurse = function( value )
{
var bytes = 0;
if ( typeof value === 'boolean' ) {
bytes = 4;
}
else if ( typeof value === 'string' ) {
bytes = value.length * 2;
}
else if ( typeof value === 'number' ) {
bytes = 8;
}
else if
(
typeof value === 'object'
&& objectList.indexOf( value ) === -1
)
{
objectList[ objectList.length ] = value;
for( i in value ) {
bytes+= 8; // an assumed existence overhead
bytes+= recurse( value[i] )
}
}
return bytes;
}
return recurse( object );
}
You can invoke reflections and also, set order of sequence for getter for values through annotations
public class Student {
private String grade;
private String name;
private String id;
private String gender;
private Method[] methods;
@Retention(RetentionPolicy.RUNTIME)
public @interface Order {
int value();
}
/**
* Sort methods as per Order Annotations
*
* @return
*/
private void sortMethods() {
methods = Student.class.getMethods();
Arrays.sort(methods, new Comparator<Method>() {
public int compare(Method o1, Method o2) {
Order or1 = o1.getAnnotation(Order.class);
Order or2 = o2.getAnnotation(Order.class);
if (or1 != null && or2 != null) {
return or1.value() - or2.value();
}
else if (or1 != null && or2 == null) {
return -1;
}
else if (or1 == null && or2 != null) {
return 1;
}
return o1.getName().compareTo(o2.getName());
}
});
}
/**
* Read Elements
*
* @return
*/
public void readElements() {
int pos = 0;
/**
* Sort Methods
*/
if (methods == null) {
sortMethods();
}
for (Method method : methods) {
String name = method.getName();
if (name.startsWith("get") && !name.equalsIgnoreCase("getClass")) {
pos++;
String value = "";
try {
value = (String) method.invoke(this);
}
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(name + " Pos: " + pos + " Value: " + value);
}
}
}
// /////////////////////// Getter and Setter Methods
/**
* @param grade
* @param name
* @param id
* @param gender
*/
public Student(String grade, String name, String id, String gender) {
super();
this.grade = grade;
this.name = name;
this.id = id;
this.gender = gender;
}
/**
* @return the grade
*/
@Order(value = 4)
public String getGrade() {
return grade;
}
/**
* @param grade the grade to set
*/
public void setGrade(String grade) {
this.grade = grade;
}
/**
* @return the name
*/
@Order(value = 2)
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the id
*/
@Order(value = 1)
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the gender
*/
@Order(value = 3)
public String getGender() {
return gender;
}
/**
* @param gender the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* Main
*
* @param args
* @throws IOException
* @throws SQLException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void main(String args[]) throws IOException, SQLException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Student student = new Student("A", "Anand", "001", "Male");
student.readElements();
}
}
Output when sorted
getId Pos: 1 Value: 001
getName Pos: 2 Value: Anand
getGender Pos: 3 Value: Male
getGrade Pos: 4 Value: A
import sys
try:
print("stuff")
except:
sys.exit(1) # exiing with a non zero value is better for returning from an error
This error occurs because VMware has a bug that uses the absolute path of the disk file in certain situations.
If you look at the top of that small *.vmdk file you'll likely see an incorrect absolute path to the original VMDK file that needs to be corrected.
Have you tried Context.deleteFile() ?
Something like this, if want to go old-school.
<font color="blue">Sustaining : $60.00 USD - yearly</font>
Though a more modern approach would be to use a css style:
<td style="color:#0000ff">Sustaining : $60.00 USD - yearly</td>
There are of course even more general ways to do it.
After looking around on Google for a long time, trying out several solutions, both CSS, JavaScript and JQuery, i found that most of them were using an Image as the button. Some of them were hard to use, but i did manage to piece together something that ended out working out for me.
The important parts for me was:
This is the solution i came up with. And hope it can be of use to others as well.
Change the width of .file_input_textbox to change the width of the textbox.
Change the width of both .file_input_div, .file_input_button and .file_input_button_hover to change the width of the button. You might need to tweak a bit on the positions also. I never figured out why...
To test this solution, make a new html file and paste the content into it.
<html>
<head>
<style type="text/css">
.file_input_textbox {height:25px;width:200px;float:left; }
.file_input_div {position: relative;width:80px;height:26px;overflow: hidden; }
.file_input_button {width: 80px;position:absolute;top:0px;
border:1px solid #F0F0EE;padding:2px 8px 2px 8px; font-weight:bold; height:25px; margin:0px; margin-right:5px; }
.file_input_button_hover{width:80px;position:absolute;top:0px;
border:1px solid #0A246A; background-color:#B2BBD0;padding:2px 8px 2px 8px; height:25px; margin:0px; font-weight:bold; margin-right:5px; }
.file_input_hidden {font-size:45px;position:absolute;right:0px;top:0px;cursor:pointer;
opacity:0;filter:alpha(opacity=0);-ms-filter:"alpha(opacity=0)";-khtml-opacity:0;-moz-opacity:0; }
</style>
</head>
<body>
<input type="text" id="fileName" class="file_input_textbox" readonly="readonly">
<div class="file_input_div">
<input id="fileInputButton" type="button" value="Browse" class="file_input_button" />
<input type="file" class="file_input_hidden"
onchange="javascript: document.getElementById('fileName').value = this.value"
onmouseover="document.getElementById('fileInputButton').className='file_input_button_hover';"
onmouseout="document.getElementById('fileInputButton').className='file_input_button';" />
</div>
</body>
</html>
You can do this, just wrap it in typeof()
foo.GetColumnValues(typeof(int))
public void GetColumnValues(Type type)
{
//logic
}
Above solution works best if multiple matching sub documents are required. $elemMatch also comes in very use if single matching sub document is required as output
db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1})
Result:
{
"_id": ObjectId("..."),
"list": [{a: 1}]
}
Hi Previously I had Android SDK Build tools 18.1.1
and Windows XP
. then my app was running properly.
But I updated My system to Windows 7
and also updated Android SDK Build tools to 19
to have latest configurations.
But My project has xercesImpl-2.9.1.jar
file so When I started to run my application with new/updated configurations I was getting
Conversion to Dalvik format failed with error 1 while parsing org/apache/xerces/impl/xpath/regex/ParserForXMLSchema.class
So I went through all the answers which are mentioned to this question but was not able to solve . I wondered for 4 days then I found this link which saved my life, after reading this I came to know that problem is due to xercesImpl-2.9.1.jar
with Android SDK Build tools to 19.
So I downgraded it to Android SDK Build tools to 18.1.1. And I got rid of this problem.
i am posting my answer here so that if anyone would face this issue they can get solve it.
It made me frustated. Hope will help others.
In addition to adding these attributes to your Id column:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
in your migration you should change your CreateTable
to add the defaultValueSQL
property to your column i.e.:
Id = c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()"),
This will prevent you from having to manually touch your database which, as you pointed out in the comments, is something you want to avoid with Code First.
Solutions in accepted answer are being deprecated
#4 Calling prop directly
Enzyme simulate is supposed to be removed in version 4. The main maintainer is suggesting directly invoking prop functions, which is what simulate does internally. One solution is to directly test that invoking those props does the right thing; or you can mock out instance methods, test that the prop functions call them, and unit test the instance methods.
You could call click, for example:
wrapper.find('Button').prop('onClick')()
Or
wrapper.find('Button').props().onClick()
Information about deprecation: Deprecation of .simulate() #2173
I got the same error, but when i did as below, it resolved the issue.
Instead of writing like this:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
use the below one:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
Instead of using FileWriter
, create a FileOutputStream
. You can then wrap this in an OutputStreamWriter
, which allows you to pass an encoding in the constructor. Then you can write your data to that inside a try-with-resources Statement:
try (OutputStreamWriter writer =
new OutputStreamWriter(new FileOutputStream(PROPERTIES_FILE), StandardCharsets.UTF_8))
// do stuff
}
String
A simple regex. See: How to check if a string contains only digits in Java. Use javax.constraints.Pattern.
The exception can also occur because of the class path not being defined.
After hours of research and literally going through hundreds of pages, the problem was that the class path of the library was not defined.
Set the class path as follows in your windows machine
set classpath=path\to\your\jdbc\jar\file;.
The accepted way to rename a table in Laravel 4 is to use the Schema builder. So you would want to do:
Schema::rename('photos', 'images');
From http://laravel.com/docs/4.2/schema#creating-and-dropping-tables
If you really want to write out a raw SQL query yourself, you can always do:
DB::statement('alter table photos rename to images');
Note: Laravel's DB class also supports running raw SQL select
, insert
, update
, and delete
queries, like:
$users = DB::select('select id, name from users');
For more info, see http://laravel.com/docs/4.2/database#running-queries.
You have an old password in the settings.xml
. It is trying to connect to the repositories, but is not able to, since the password is not updated. Once you update and re-run the command, you should be good.
I have been using this ExtensionMethod for a while:
public static IEnumerable<T> GetRandom<T>(this IEnumerable<T> list, int count)
{
if (count <= 0)
yield break;
var r = new Random();
int limit = (count * 10);
foreach (var item in list.OrderBy(x => r.Next(0, limit)).Take(count))
yield return item;
}
I'm looking into using SSTJ for FFTs in Java. It can redirect via JNI to FFTW if the library is available or will use a pure Java implementation if not.
You can always JQuery-ize your form.submit, but it may just call the same thing:
$("form").submit(); // probably able to affect multiple forms (good or bad)
// or you can address it by ID
$("#yourFormId").submit();
You can also attach functions to the submit event, but that is a different concept.
Use media queries to separate each browser:
/* IE6/7 uses media, */
@media, {
.dude { color: green; }
.gal { color: red; }
}
/* IE8 uses \0 */
@media all\0 {
.dude { color: brown; }
.gal { color: orange; }
}
/* IE9 uses \9 */
@media all and (monochrome:0) {
.dude { color: yellow\9; }
.gal { color: blue\9; }
}
/* IE10 and IE11 both use -ms-high-contrast */
@media all and (-ms-high-contrast:none)
{
.foo { color: green } /* IE10 */
*::-ms-backdrop, .foo { color: red } /* IE11 */
}
References
Edit 2016: read the next two answers.
element.classList.add('newclass')
works in modern browsersJQuery (less than 3) can't add a class to an SVG.
.attr()
works with SVG, so if you want to depend on jQuery:
// Instead of .addClass("newclass")
$("#item").attr("class", "oldclass newclass");
// Instead of .removeClass("newclass")
$("#item").attr("class", "oldclass");
And if you don't want to depend on jQuery:
var element = document.getElementById("item");
// Instead of .addClass("newclass")
element.setAttribute("class", "oldclass newclass");
// Instead of .removeClass("newclass")
element.setAttribute("class", "oldclass");
Activity
to a Fragment
Activity:
Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();
Fragment:
Reading the value in fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String myValue = this.getArguments().getString("message");
...
...
...
}
But if you want to send values from Fragment to Activity, read the answer of jpardogo, you must need interfaces, more info: Communicating with other Fragments
I found solution. It works fine when I throw away next line from form:
enctype="multipart/form-data"
And now it pass all parameters at request ok:
<form action="/registration" method="post">
<%-- error messages --%>
<div class="form-group">
<c:forEach items="${registrationErrors}" var="error">
<p class="error">${error}</p>
</c:forEach>
</div>
For posterity....I figured out how to get what I needed. Here it is in case it might be useful to somebody else.
$alist = "Name`tAccountName`tDescription`tEmailAddress`tLastLogonDate`tManager`tTitle`tDepartment`tCompany`twhenCreated`tAcctEnabled`tGroups`n"
$userlist = Get-ADUser -Filter * -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,Company,whenCreated,Enabled,MemberOf | Sort-Object -Property Name
$userlist | ForEach-Object {
$grps = $_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
$arec = $_.Name,$_.SamAccountName,$_.Description,$_.EmailAddress,$_LastLogonDate,$_.Manager,$_.Title,$_.Department,$_.Company,$_.whenCreated,$_.Enabled
$aline = ($arec -join "`t") + "`t" + ($grps -join "`t") + "`n"
$alist += $aline
}
$alist | Out-File D:\Temp\ADUsers.csv
It's HTML character references for encoding a character by its decimal code point
Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe
You can use the substring function:
let str = "12345.00";_x000D_
str = str.substring(0, str.length - 1);_x000D_
console.log(str);
_x000D_
This is the accepted answer, but as per the conversations below, the slice syntax is much clearer:
let str = "12345.00";_x000D_
str = str.slice(0, -1); _x000D_
console.log(str);
_x000D_
In order to support refactoring correctly (rename class), then you should use either:
MyClass.class.getName(); // full name with package
or (thanks to @James Van Huis):
MyClass.class.getSimpleName(); // class name and no more
I solved it this way:
Then restart your device. Now enjoy...
It's 100% working.
If you're using jQuery Cookie (https://plugins.jquery.com/cookie/), you can use decimal point or fractions.
As one day is 1
, one minute would be 1 / 1440
(there's 1440 minutes in a day).
So 30 minutes is 30 / 1440 = 0.02083333
.
Final code:
$.cookie("example", "foo", { expires: 30 / 1440, path: '/' });
I've added path: '/'
so that you don't forget that the cookie is set on the current path. If you're on /my-directory/
the cookie is only set for this very directory.
You'll have to pass your arguments as reference types.
#First create the variables (note you have to set them to something)
$global:var1 = $null
$global:var2 = $null
$global:var3 = $null
#The type of the reference argument should be of type [REF]
function foo ($a, $b, [REF]$c)
{
# add $a and $b and set the requested global variable to equal to it
# Note how you modify the value.
$c.Value = $a + $b
}
#You can then call it like this:
foo 1 2 [REF]$global:var3
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,17);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
Date d = cal.getTime();
Also See
Few months ago, I implemented a way to determine if any string is integer, hexadecimal or double.
enum{
STRING_IS_INVALID_NUMBER=0,
STRING_IS_HEXA,
STRING_IS_INT,
STRING_IS_DOUBLE
};
bool isDigit(char c){
return (('0' <= c) && (c<='9'));
}
bool isHexaDigit(char c){
return ((('0' <= c) && (c<='9')) || ((tolower(c)<='a')&&(tolower(c)<='f')));
}
char *ADVANCE_DIGITS(char *aux_p){
while(CString::isDigit(*aux_p)) aux_p++;
return aux_p;
}
char *ADVANCE_HEXADIGITS(char *aux_p){
while(CString::isHexaDigit(*aux_p)) aux_p++;
return aux_p;
}
int isNumber(const string & test_str_number){
bool isHexa=false;
char *str = (char *)test_str_number.c_str();
switch(*str){
case '-': str++; // is negative number ...
break;
case '0':
if(tolower(*str+1)=='x') {
isHexa = true;
str+=2;
}
break;
default:
break;
};
char *start_str = str; // saves start position...
if(isHexa) { // candidate to hexa ...
str = ADVANCE_HEXADIGITS(str);
if(str == start_str)
return STRING_IS_INVALID_NUMBER;
if(*str == ' ' || *str == 0)
return STRING_IS_HEXA;
}else{ // test if integer or float
str = ADVANCE_DIGITS(str);
if(*str=='.') { // is candidate to double
str++;
str = ADVANCE_DIGITS(str);
if(*str == ' ' || *str == 0)
return STRING_IS_DOUBLE;
return STRING_IS_INVALID_NUMBER;
}
if(*str == ' ' || *str == 0)
return STRING_IS_INT;
}
return STRING_IS_INVALID_NUMBER;
}
Then in your program you can easily convert the number in function its type if you do the following,
string val; // the string to check if number...
switch(isNumber(val)){
case STRING_IS_HEXA:
// use strtol(val.c_str(), NULL, 16); to convert it into conventional hexadecimal
break;
case STRING_IS_INT:
// use (int)strtol(val.c_str(), NULL, 10); to convert it into conventional integer
break;
case STRING_IS_DOUBLE:
// use atof(val.c_str()); to convert it into conventional float/double
break;
}
You can realise that the function will return a 0 if the number wasn't detected. The 0 it can be treated as false (like boolean).
I had the same problem and I fixed it by installing nodejs
on my system independent of the gem.
on ubuntu its: sudo apt-get install nodejs
I'm using 64bit ubuntu 11.10
update: From @Galina 's answer below I'm guessing that the latest version of nodejs is required, so @steve98177 your best option on a redhat(or CentOS) box is to install from source code as @Galina did, but as you can't "make/install" on this box ?, I suggest you try to install a fedora rpm(long shot) https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager or find another RH/CentOs box(that you can 'make' on) and create your own rpm and install on original RH box(if old glibc on RH plays nice).
The real issue here(IMHO) is installing Gems that have dependencies on installed packages outside of the ruby environment, is there a way of knowing before installing ? an RFI for Gems or bundler ?
sudo yum install nodejs
public function number_row()
{
$query = $this->db->select("count(user_details.id) as number")
->get('user_details');
if($query-> num_rows()>0)
{
return $query->row();
}
else
{
return false;
}
}
The following example shows commit parents as well:
git log --graph --all \
--format='%C(cyan dim) %p %Cred %h %C(white dim) %s %Cgreen(%cr)%C(cyan dim) <%an>%C(bold yellow)%d%Creset'
You also can use:
element.addEventListener("click", function(){
// call execute function here...
}, false);
And by the way for you fellow googlers for selecting multiple folders in the search input you separate your directories with a comma. Works both for exclude and include
Example: ./src/public/,src/components/
Here is example using xargs
:
$ xargs -d '\n' -I% sh -c 'echo % | wc -c' < file
C array:
NSInteger array[6] = {1, 2, 3, 4, 5, 6};
Objective-C Array:
NSArray *array = @[@1, @2, @3, @4, @5, @6];
// numeric values must in that case be wrapped into NSNumbers
Swift Array:
var array = [1, 2, 3, 4, 5, 6]
This is correct too:
var array = Array(1...10)
NB: arrays are strongly typed in Swift; in that case, the compiler infers from the content that the array is an array of integers. You could use this explicit-type syntax, too:
var array: [Int] = [1, 2, 3, 4, 5, 6]
If you wanted an array of Doubles, you would use :
var array = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] // implicit type-inference
or:
var array: [Double] = [1, 2, 3, 4, 5, 6] // explicit type
Keep in mind when using the group by and order by that MySQL is the ONLY database that allows for columns to be used in the group by and/or order by piece that are not part of the select statement.
So for example: select column1 from table group by column2 order by column3
That will not fly in other databases like Postgres, Oracle, MSSQL, etc. You would have to do the following in those databases
select column1, column2, column3 from table group by column2 order by column3
Just some info in case you ever migrate your current code to another database or start working in another database and try to reuse code.
Or you can just initialize inline in the controller. If you use an init function internal to the controller, it doesn't need to be defined in the scope. In fact, it can be self executing:
function MyCtrl($scope) {
$scope.isSaving = false;
(function() { // init
if (true) { // $routeParams.Id) {
//get an existing object
} else {
//create a new object
}
})()
$scope.isClean = function () {
return $scope.hasChanges() && !$scope.isSaving;
}
$scope.hasChanges = function() { return false }
}
I realize this is a bit late, but I've had success with annotating a timestamp column with
@Column(name="timestamp", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
This should also work with CURRENT_DATE
and CURRENT_TIME
. I'm using JPA/Hibernate with Oracle, so YMMV.
I tried this and dont see any way of doing it.
here is my approach for it.
EXEC sp_rename 'Employee', 'Employee1'
-- Original table name is EmployeeINSERT INTO TABLE2 SELECT * FROM TABLE1
.
-- Insert into Employee select Name, Company from Employee1DROP table Employee1
.alter user hr identified by hr account unlock;
Give connection name as HR_ORCL Username: hr Password: hr Connection Type: Basic Role: default Hostname: localhost Port: 1521 SID: xe
Click on test and Connect
I managed to render the following SELECT with SQLAlchemy on both layers.
SELECT count(*) AS count_1
FROM "table"
from sqlalchemy import select, func, Integer, Table, Column, MetaData
metadata = MetaData()
table = Table("table", metadata,
Column('primary_key', Integer),
Column('other_column', Integer) # just to illustrate
)
print select([func.count()]).select_from(table)
You just subclass Query
(you have probably anyway) and provide a specialized count()
method, like this one.
from sqlalchemy.sql.expression import func
class BaseQuery(Query):
def count_star(self):
count_query = (self.statement.with_only_columns([func.count()])
.order_by(None))
return self.session.execute(count_query).scalar()
Please note that order_by(None)
resets the ordering of the query, which is irrelevant to the counting.
Using this method you can have a count(*)
on any ORM Query, that will honor all the filter
andjoin
conditions already specified.
Interfaces specify behavior of an object.
Static methods do not specify a behavior of an object, but behavior that affects an object in some way.
Another option is to use linear-gradient()
to cover up the edges of your image. Note that this is a stupid solution, so I'm not going to put much effort into explaining it...
.flair {_x000D_
min-width: 50px; /* width larger than sprite */_x000D_
text-indent: 60px;_x000D_
height: 25px;_x000D_
display: inline-block;_x000D_
background:_x000D_
linear-gradient(#F00, #F00) 50px 0/999px 1px repeat-y,_x000D_
url('https://championmains.github.io/dynamicflairs/riven/spritesheet.png') #F00;_x000D_
}_x000D_
_x000D_
.flair-classic {_x000D_
background-position: 50px 0, 0 -25px;_x000D_
}_x000D_
_x000D_
.flair-r2 {_x000D_
background-position: 50px 0, -50px -175px;_x000D_
}_x000D_
_x000D_
.flair-smite {_x000D_
text-indent: 35px;_x000D_
background-position: 25px 0, -50px -25px;_x000D_
}
_x000D_
<img src="https://championmains.github.io/dynamicflairs/riven/spritesheet.png" alt="spritesheet" /><br />_x000D_
<br />_x000D_
<span class="flair flair-classic">classic sprite</span><br /><br />_x000D_
<span class="flair flair-r2">r2 sprite</span><br /><br />_x000D_
<span class="flair flair-smite">smite sprite</span><br /><br />
_x000D_
I'm using this method on this page: https://championmains.github.io/dynamicflairs/riven/ and can't use ::before
or ::after
elements because I'm already using them for another hack.
Here are a three functions that might be useful. First checks the string for a proper numeric format, second and third function converts a string to Long or Double.
Function IsValidNumericEntry(MyString As String) As Boolean
'********************************************************************************
'This function checks the string entry to make sure that valid digits are in the string.
'It checks to make sure the + and - are the first character if entered and no duplicates.
'Valid charcters are 0 - 9, + - and the .
'********************************************************************************
Dim ValidEntry As Boolean
Dim CharCode As Integer
Dim ValidDigit As Boolean
Dim ValidPlus As Boolean
Dim ValidMinus As Boolean
Dim ValidDecimal As Boolean
Dim ErrMsg As String
ValidDigit = False
ValidPlus = False
ValidMinus = False
ValidDecimal = False
ValidEntry = True
For x = 1 To Len(MyString)
CharCode = Asc(Mid(MyString, x, 1))
Select Case CharCode
Case 48 To 57 ' Digits 0 - 9
ValidDigit = True
Case 43 ' Plus sign
If ValidPlus Then 'One has already been detected and this is a duplicate
ErrMsg = "Invalid entry....too many plus signs!"
ValidEntry = False
Exit For
ElseIf x = 1 Then 'if in the first positon it is valide
ValidPlus = True
Else 'Not in first position and it is invalid
ErrMsg = "Invalide entry....Plus sign not in the correct position! "
ValidEntry = False
Exit For
End If
Case 45 ' Minus sign
If ValidMinus Then 'One has already been detected and this is a duplicate
ErrMsg = "Invalide entry....too many minus signs! "
ValidEntry = False
Exit For
ElseIf x = 1 Then 'if in the first position it is valid
ValidMinus = True
Else 'Not in first position and it is invalid
ErrMsg = "Invalide entry....Minus sign not in the correct position! "
ValidEntry = False
Exit For
End If
Case 46 ' Period
If ValidDecimal Then 'One has already been detected and this is a duplicate
ErrMsg = "Invalide entry....too many decimals!"
ValidEntry = False
Exit For
Else
ValidDecimal = True
End If
Case Else
ErrMsg = "Invalid numerical entry....Only digits 0-9 and the . + - characters are valid!"
ValidEntry = False
Exit For
End Select
Next
If ValidEntry And ValidDigit Then
IsValidNumericEntry = True
Else
If ValidDigit = False Then
ErrMsg = "Text string contains an invalid numeric format." & vbCrLf _
& "Use only one of the following formats!" & vbCrLf _
& "(+dd.dd -dd.dd +dd -dd dd.d or dd)! "
End If
MsgBox (ErrMsg & vbCrLf & vbCrLf & "You Entered: " & MyString)
IsValidNumericEntry = False
End If
End Function
Function ConvertToLong(stringVal As String) As Long
'Assumes the user has verified the string contains a valide numeric entry.
'User should call the function IsValidNumericEntry first especially after any user input
'to verify that the user has entered a proper number.
ConvertToLong = CLng(stringVal)
End Function
Function ConvertToDouble(stringVal As String) As Double
'Assumes the user has verified the string contains a valide numeric entry.
'User should call the function IsValidNumericEntry first especially after any user input
'to verify that the user has entered a proper number.
ConvertToDouble = CDbl(stringVal)
End Function
I catch the next case about cors. Maybe it will be useful to somebody. If you add feature 'WebDav Redirector' to your server, PUT and DELETE requests are failed.
So, you will need to remove 'WebDAVModule' from your IIS server:
Or add to your config:
<system.webServer>
<modules>
<remove name="WebDAVModule"/>
</modules>
<handlers>
<remove name="WebDAV" />
...
</handlers>
Extend LinearLayout/RelativeLayout and use it straight on the XML
package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
Paint paint;
public LinearLayoutOutlined(Context context) {
super(context);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
public LinearLayoutOutlined(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
/*
Paint fillPaint = paint;
fillPaint.setARGB(255, 0, 255, 0);
fillPaint.setStyle(Paint.Style.FILL);
canvas.drawPaint(fillPaint) ;
*/
Paint strokePaint = paint;
strokePaint.setARGB(255, 255, 0, 0);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(2);
Rect r = canvas.getClipBounds() ;
Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
canvas.drawRect(outline, strokePaint) ;
}
}
<?xml version="1.0" encoding="utf-8"?>
<com.pkg_name.LinearLayoutOutlined
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=...
android:layout_height=...
>
... your widgets here ...
</com.pkg_name.LinearLayoutOutlined>
That's a lot of questions.
Why EOF
is -1: usually -1 in POSIX system calls is returned on error, so i guess the idea is "EOF is kind of error"
any boolean operation (including !=) returns 1 in case it's TRUE, and 0 in case it's FALSE, so getchar() != EOF
is 0
when it's FALSE, meaning getchar()
returned EOF
.
in order to emulate EOF
when reading from stdin
press Ctrl+D
Your method's return type is int
and you're trying to return an int?
.
Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value.
null
.0
.0.0
false
.'\u0000'
(whose decimal equivalent is 0).When you create an array of something, all entries are also zeroed. So your array contains five zeros right after it is created by new
.
Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.
Find the PID of a process that uses a port on Windows (e.g. port: "9999")
netstat -aon | find "9999"
-a
Displays all connections and listening ports.
-o
Displays the owning process ID associated with each connection.
-n
Displays addresses and port numbers in numerical form.
Output:
TCP 0.0.0.0:9999 0.0.0.0:0 LISTENING 15776
Then kill the process by PID
taskkill /F /PID 15776
/F
- Specifies to forcefully terminate the process(es).
Note: You may need an extra permission (run from administrator) to kill some certain processes
The EF Core doesn't create DBset for the SQL views automatically in the context calss, we can add them manually as below.
public partial class LocalDBContext : DbContext
{
public LocalDBContext(DbContextOptions<LocalDBContext> options) : base(options)
{
}
public virtual DbSet<YourView> YourView { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<YourView>(entity => {
entity.HasKey(e => e.ID);
entity.ToTable("YourView");
entity.Property(e => e.Name).HasMaxLength(50);
});
}
}
The sample view is defined as below with few properties
using System;
using System.Collections.Generic;
namespace Project.Entities
{
public partial class YourView
{
public string Name { get; set; }
public int ID { get; set; }
}
}
After adding a class for the view and DB set in the context class, you are good to use the view object through your context object in the controller.
You can do it using string.indexOf("{item}")
. If the result is greater than -1 {item}
is in the string
<script>
var scrt_var = 10;
document.getElementById("link").setAttribute("href",scrt_var);
</script>
<a id="link">this is a link</a>
Right click the database itself, Tasks -> Generate Scripts...
Then follow the wizard.
For SSMS2008+, if you want to also export the data, on the "Set Scripting Options" step, select the "Advanced" button and change "Types of data to script" from "Schema Only" to "Data Only" or "Schema and Data".
There is nothing wrong with returning a void @ResponseBody
and you should for POST
requests.
Use HTTP status codes to define errors within exception handler routines instead as others are mentioning success status. A normal method as you have will return a response code of 200
which is what you want, any exception handler can then return an error object and a different code (i.e. 500
).
I highly recommend using yarn upgrade-interactive to update React, or any Node project for that matter. It lists your packages, current version, the latest version, an indication of a Minor, Major, or Patch update compared to what you have, plus a link to the respective project.
You run it with yarn upgrade-interactive --latest
, check out release notes if you want, go down the list with your arrow keys, choose which packages you want to upgrade by selecting with the space bar, and hit Enter
to complete.
Npm-upgrade is ok but not as slick.
I was faced with the same issue in windows 10, Updating the environment variable following steps, it's working fine.
I know It is a lengthy answer for the simple environment setups, I thought it's may be useful for the new window 10 users.
1) Open Anaconda Prompt:
2) Check Conda Installed Location.
where conda
3) Open Advanced System Settings
4) Click on Environment Variables
5) Edit Path
6) Add New Path
C:\Users\RajaRama\Anaconda3\Scripts
C:\Users\RajaRama\Anaconda3
C:\Users\RajaRama\Anaconda3\Library\bin
7) Open Command Prompt and Check Versions
8) After 7th step type conda install anaconda-navigator in cmd then press y
You'll need to generate the SQL content dynamically:
declare @tablename varchar(50)
set @tablename = 'test'
declare @sql varchar(500)
set @sql = 'select * from ' + @tablename
exec (@sql)
Here is the code for the functions that will do the work
-- To Base64 string
CREATE FUNCTION [dbo].[fn_str_TO_BASE64]
(
@STRING NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
RETURN (
SELECT
CAST(N'' AS XML).value(
'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
, 'NVARCHAR(MAX)'
) Base64Encoding
FROM (
SELECT CAST(@STRING AS VARBINARY(MAX)) AS bin
) AS bin_sql_server_temp
)
END
GO
-- From Base64 string
CREATE FUNCTION [dbo].[fn_str_FROM_BASE64]
(
@BASE64_STRING NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
RETURN (
SELECT
CAST(
CAST(N'' AS XML).value('xs:base64Binary(sql:variable("@BASE64_STRING"))', 'VARBINARY(MAX)')
AS NVARCHAR(MAX)
) UTF8Encoding
)
END
Example of usage:
DECLARE @CHAR NVARCHAR(256) = N'e.g., ???? ????? or ? ??????'
SELECT [dbo].[fn_str_FROM_BASE64]([dbo].[fn_str_TO_BASE64](@CHAR)) as converted
This is basically Marco Antônio's answer for a React custom hook, but modified to set the dimensions initially and not only after a resize.
export const useContainerDimensions = myRef => {
const getDimensions = () => ({
width: myRef.current.offsetWidth,
height: myRef.current.offsetHeight
})
const [dimensions, setDimensions] = useState({ width: 0, height: 0 })
useEffect(() => {
const handleResize = () => {
setDimensions(getDimensions())
}
if (myRef.current) {
setDimensions(getDimensions())
}
window.addEventListener("resize", handleResize)
return () => {
window.removeEventListener("resize", handleResize)
}
}, [myRef])
return dimensions;
};
Used in the same way:
const MyComponent = () => {
const componentRef = useRef()
const { width, height } = useContainerDimensions(componentRef)
return (
<div ref={componentRef}>
<p>width: {width}px</p>
<p>height: {height}px</p>
<div/>
)
}
Even though I had gcc already installed, I had to run
sudo apt-get install build-essential
to get rid of that error
If the JSON data in your array is sorted in some way, there are a variety of searches you could implement. However, if you're not dealing with a lot of data then you're probably going to be fine with an O(n) operation here (as you have). Anything else would probably be overkill.
C++ doesn't allow virtual template member functions right now. The most likely reason is the complexity of implementing it. Rajendra gives good reason why it can't be done right now but it could be possible with reasonable changes of the standard. Especially working out how many instantiations of a templated function actually exist and building up the vtable seems difficult if you consider the place of the virtual function call. Standards people just have a lot of other things to do right now and C++1x is a lot of work for the compiler writers as well.
When would you need a templated member function? I once came across such a situation where I tried to refactor a hierarchy with a pure virtual base class. It was a poor style for implementing different strategies. I wanted to change the argument of one of the virtual functions to a numeric type and instead of overloading the member function and override every overload in all sub-classes I tried to use virtual template functions (and had to find out they don't exist.)
The question I would ask is, why are you including the extra columns in your DataTable if they aren't required?
Maybe you should modify your SQL select statement so that it is looking at the specific criteria you are looking for as you are populating your DataTable.
You could also use LINQ to query your DataTable as Enumerable and create a List Object that represents only certain columns.
Other than that, hide the DataGridView Columns that you don't require.
Make the (LinearLayout) android:layout_width="match_parent"
and the TextView's android:layout_gravity="right"
In Visual Studio 2019, version 16.8.4, you can just add
<Prefer32Bit>false</Prefer32Bit>
You can calculate screen width. And you can scale bitmap.
public static float getScreenWidth(Activity activity) {
Display display = activity.getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float pxWidth = outMetrics.widthPixels;
return pxWidth;
}
calculate screen width and scaled image height by screen width.
float screenWidth=getScreenWidth(act)
float newHeight = screenWidth;
if (bitmap.getWidth() != 0 && bitmap.getHeight() != 0) {
newHeight = (screenWidth * bitmap.getHeight()) / bitmap.getWidth();
}
After you can scale bitmap.
Bitmap scaledBitmap=Bitmap.createScaledBitmap(bitmap, (int) screenWidth, (int) newHeight, true);
In the version of .NET I am using you also have to do this:
System.Net.ServicePointManager.Expect100Continue = false;
If you don't, the HttpWebRequest
class will automatically add the Expect:100-continue
request header which fouls everything up.
Also I learned the hard way that you have to have the right number of dashes. whatever you say is the "boundary" in the Content-Type
header has to be preceded by two dashes
--THEBOUNDARY
and at the end
--THEBOUNDARY--
exactly as it does in the example code. If your boundary is a lot of dashes followed by a number then this mistake won't be obvious by looking at the http request in a proxy server