The methods that say to remove files and muck about with moving the .git directory are not clean and not using the "git" method of doing something that's should be simple. This is the cleanest method I have found to convert a normal repo into a bare repo.
First clone /path/to/normal/repo into a bare repo called repo.git
git clone --bare /path/to/normal/repo
Next remove the origin that points to /path/to/normal/repo
cd repo.git
git remote rm origin
Finally you can remove your original repo. You could rename repo.git to repo at that point, but the standard convention to signify a git repository is something.git, so I'd personally leave it that way.
Once you've done all that, you can clone your new bare repo (which in effect creates a normal repo, and is also how you would convert it from bare to normal)
Of course if you have other upstreams, you'll want to make a note of them, and update your bare repo to include it. But again, it can all be done with the git command. Remember the man pages are your friend.
A non-bare repository simply has a checked-out working tree. The working tree does not store any information about the state of the repository (branches, tags, etc.); rather, the working tree is just a representation of the actual files in the repo, which allows you to work on (edit, etc.) the files.
By default there will be no branches listed and pops up only after some file is placed. You don't have to worry much about it. Just run all your commands like creating folder structures, adding/deleting files, commiting files, pushing it to server or creating branches. It works seamlessly without any issue.
Seekbar called onProgressChanged method when we initialize first time. We can skip by using below code We need to check boolean it return false when initialize automatically
volumeManager.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if(b){
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
If you are using JAX-WS on JDK6, use the following properties:
com.sun.xml.internal.ws.connect.timeout
com.sun.xml.internal.ws.request.timeout
line = line.translate(None, " ?.!/;:")
The SPE IDE has built-in UML creator. Just open the files in SPE and click on the UML tab.
I don't know how comprhensive it is for your needs, but it doesn't require any additional downloads or configurations to use.
Making sleep.sh executable and adding shell=True
to the parameter list (as suggested in previous answers) works ok. Depending on the search path, you may also need to add ./
or some other appropriate path. (Ie, change "sleep.sh"
to "./sleep.sh"
.)
The shell=True
parameter is not needed (under a Posix system like Linux) if the first line of the bash script is a path to a shell; for example, #!/bin/bash
.
In the code you posted, you're sending the setDownloadURL:
setter to ClassA
— that is, the class itself. You want to set the property of an instance.
The no-js class is used to style a webpage, dependent on whether the user has JS disabled or enabled in the browser.
As per the Modernizr docs:
no-js
By default, Modernizr will rewrite
<html class="no-js"> to <html class="js">
. This lets hide certain elements that should only be exposed in environments that execute JavaScript. If you want to disable this change, you can set enableJSClass to false in your config.
Update: I still get upvotes on this question, which is still the accepted answer and which I think I answered poorly. In the spirit of making sure the best info is out there, I have decided to update this answer.
In modern Android I would use ConstraintLayout
to do this. It is more performant and straightforward.
<ConstraintLayout>
<View
android:id="@+id/view1"
...other attributes elided... />
<View
android:id="@id/view2"
app:layout_constraintTop_toBottomOf="@id/view1" />
...other attributes elided... />
...etc for other views that should be aligned top to bottom...
<TextView
app:layout_constraintBottom_toBottomOf="parent" />
If you don't want to use a ConstraintLayout, using a LinearLayout with an expanding view is a straightforward and great way to handle taking up the extra space (see the answer by @Matthew Wills). If you don't want to expand the background of any of the Views above the bottom view, you can add an invisible View to take up the space.
The answer I originally gave works but is inefficient. Inefficiency may not be a big deal for a single top level layout, but it would be a terrible implementation in a ListView
or RecyclerView
, and there just isn't any reason to do it since there are better ways to do it that are roughly the same level of effort and complexity if not simpler.
Take the TextView out of the LinearLayout, then put the LinearLayout and the TextView inside a RelativeLayout. Add the attribute android:layout_alignParentBottom="true"
to the TextView. With all the namespace and other attributes except for the above attribute elided:
<RelativeLayout>
<LinearLayout>
<!-- All your other elements in here -->
</LinearLayout>
<TextView
android:layout_alignParentBottom="true" />
</RelativeLayout>
All proposed solutions didn't work for me but the closest one was from @Rishii.
I'm using AngularJS 1.4.4 and UI Bootstrap 0.13.3.
.directive('jsr310Compatible', ['dateFilter', 'dateParser', function(dateFilter, dateParser) {
return {
restrict: 'EAC',
require: 'ngModel',
priority: 1,
link: function(scope, element, attrs, ngModel) {
var dateFormat = 'yyyy-MM-dd';
ngModel.$parsers.push(function(viewValue) {
return dateFilter(viewValue, dateFormat);
});
ngModel.$validators.date = function (modelValue, viewValue) {
var value = modelValue || viewValue;
if (!attrs.ngRequired && !value) {
return true;
}
if (angular.isNumber(value)) {
value = new Date(value);
}
if (!value) {
return true;
}
else if (angular.isDate(value) && !isNaN(value)) {
return true;
}
else if (angular.isString(value)) {
var date = dateParser.parse(value, dateFormat);
return !isNaN(date);
}
else {
return false;
}
};
}
};
}])
What about x *= -1
? I like its simplicity.
You can also use :checked
for <select>
elements
e.g.,
document.querySelector('select option:checked')
document.querySelector('select option:checked').getAttribute('value')
You don't even have to get the index and then reference the element by its sibling index.
You shouldn't do this in most cases. Depending on your transaction level you have created a race condition, now in your example here it wouldn't matter to much, but the data can be changed from the first select to the update. And all you've done is forced SQL to do more work
The best way to know for sure is to test the two differences and see which one gives you the appropriate performance.
session_start();
if(!empty($_SESSION['user']))
{
//code;
}
else
{
header("location:index.php");
}
A New Laravel Blade Error Directive comes to Laravel 5.8.13
// Before
@if ($errors->has('email'))
<span>{{ $errors->first('email') }}</span>
@endif
// After:
@error('email')
<span>{{ $message }}</span>
@enderror
The problem I had accessing the sqlite db file I created in my java (jersey) server had solely to due with path. Some of the docs say the jdbc connect url should look like "jdbc:sqlite://path-to-file/sample.db". I thought the double-slash was part of a htt protocol-style path and would map properly when deployed, but in actuality, it's an absolute or relative path. So, when I placed the file at the root of the WebContent folder (tomcat project), a uri like this worked "jdbc:sqlite:sample.db".
The one thing that was throwing me was that when I was stepping through the debugger, I received a message that said "opening db: ... permission denied". I thought it was a matter of file system permissions or perhaps sql user permissions. After finding out that SQLite doesn't have the concept of roles/permissions like MySQL, etc, I did eventually change the file permissions before I came to what I believe was the correct solution, but I think it was just a bad message (i.e. permission denied, instead of File not found).
Hope this helps someone.
This is because JavaScript uses type coercion in Boolean contexts and your code
if ("0")
will be coerced to true in boolean contexts.
There are other truthy values in Javascript which will be coerced to true in boolean contexts, and thus execute the if block are:-
if (true)
if ({})
if ([])
if (42)
if ("0")
if ("false")
if (new Date())
if (-42)
if (12n)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)
Quentin is correct, it can't be done with CSS. If you want to add a title
attribute, you can do it with JavaScript. Here's an example using jQuery:
$('label').attr('title','mandatory');
Essentially the same as Mike Ramirez's answer, but simpler and closer in stylistics to django standard get_absolute_url
method:
from django.urls import reverse
def get_admin_url(self):
return reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name),
args=[self.id])
Sometimes a soft delete mechanism is used where a date is recorded to indicate the deleted date. In this case an UPDATE
statement may be used to update this field based on duplicate entries.
UPDATE MY_TABLE
SET DELETED = getDate()
WHERE TABLE_ID IN (
SELECT x.TABLE_ID
FROM MY_TABLE x
JOIN (SELECT min(TABLE_ID) id, COL_1, COL_2, COL_3
FROM MY_TABLE d
GROUP BY d.COL_1, d.COL_2, d.COL_3
HAVING count(*) > 1) AS d ON d.COL_1 = x.COL_1
AND d.COL_2 = x.COL_2
AND d.COL_3 = x.COL_3
AND d.TABLE_ID <> x.TABLE_ID
/*WHERE x.COL_4 <> 'D' -- Additional filter*/)
This method has served me well for fairly moderate tables containing ~30 million rows with high and low amounts of duplications.
isset()
will return true if the variable has been initialised. If you have a form field with its name
value set to userName
, when that form is submitted the value will always be "set", although there may not be any data in it.
Instead, trim()
the string and test its length
if("" == trim($_POST['userName'])){
$username = 'Anonymous';
}
Note: This answer was for a previous version of this question where the question asker was trying to use JavaScript to apply css styles… which can simply be done with CSS.
css
-only solution.For applying basic styles, CSS is simpler and more performant that JS solutions 99% of the time. (Though more modern CSS-in-JS solutions — eg. React Components, etc — are arguably more maintainable.)
Run this code snippet to see it in action…
.hover-button .hover-button--on,_x000D_
.hover-button:hover .hover-button--off {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.hover-button:hover .hover-button--on {_x000D_
display: inline;_x000D_
}
_x000D_
<button class='hover-button'>_x000D_
<span class='hover-button--off'>Default</span>_x000D_
<span class='hover-button--on'>Hover!</span>_x000D_
</button>
_x000D_
The code below will create an outlook message & keep the auto signature
Dim OApp As Object, OMail As Object, signature As String
Set OApp = CreateObject("Outlook.Application")
Set OMail = OApp.CreateItem(0)
With OMail
.Display
End With
signature = OMail.body
With OMail
'.To = "[email protected]"
'.Subject = "Type your email subject here"
'.Attachments.Add
.body = "Add body text here" & vbNewLine & signature
'.Send
End With
Set OMail = Nothing
Set OApp = Nothing
SeleniumWaiter:
import com.google.common.base.Function;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SeleniumWaiter {
private WebDriver driver;
public SeleniumWaiter(WebDriver driver) {
this.driver = driver;
}
public WebElement waitForMe(By locatorname, int timeout){
WebDriverWait wait = new WebDriverWait(driver, timeout);
return wait.until(SeleniumWaiter.presenceOfElementLocated(locatorname));
}
public static Function<WebDriver, WebElement> presenceOfElementLocated(final By locator) {
// TODO Auto-generated method stub
return new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
};
}
}
And to you use it:
_waiter = new SeleniumWaiter(_driver);
try {
_waiter.waitForMe(By.xpath("//..."), 10);
}
catch (Exception e) {
// Error
}
Put it this way
where ("R"."TIME_STAMP">=TO_DATE ('03-02-2013 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
AND "R"."TIME_STAMP"<=TO_DATE ('09-02-2013 23:59:59', 'DD-MM-YYYY HH24:MI:SS'))
Where
R is table name.
TIME_STAMP is FieldName in Table R.
Your .gitignore file should look like this:
# Ignore Mac DS_Store files
.DS_Store
As long as you don't include a slash, it is matched against the file name in all directories. (from here)
If the array is sorted, you can use BinarySearch. This is a O(log n) operation, so it is faster as looping. If you need to apply multiple searches and speed is a concern, you could sort it (or a copy) before using it.
On checking add the value for checkbox and on dechecking subtract the value
$('#myDiv').change(function() {_x000D_
var values = 0.00;_x000D_
{_x000D_
$('#myDiv :checked').each(function() {_x000D_
//if(values.indexOf($(this).val()) === -1){_x000D_
values=values+parseFloat(($(this).val()));_x000D_
// }_x000D_
});_x000D_
console.log( parseFloat(values));_x000D_
}_x000D_
});
_x000D_
<div id="myDiv">_x000D_
<input type="checkbox" name="type" value="4.00" />_x000D_
<input type="checkbox" name="type" value="3.75" />_x000D_
<input type="checkbox" name="type" value="1.25" />_x000D_
<input type="checkbox" name="type" value="5.50" />_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
_x000D_
I have a single checkbox named chkDueDate
and an HTML object with a click event as follows:
$('#chkDueDate').attr('checked', !$('#chkDueDate').is(':checked'));
Clicking the HTML object (in this case a <span>
) toggles the checked property of the checkbox.
Unable to resolve host “”; No address associated with hostname
you must have to check below code here on your manifest :
<uses-permission android:name="android.permission.INTERNET" />
and most important at least for me:-
enabled wifi connection or internet connection on your mobile device
Since the count is the intended final value, in your query pass
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get()->result_array();
return count($query);
The count the retuned value
An empty string has one single null byte. So test if (s[0] == (char)0)
FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :
strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"
Here's a method for getting the version from the pom.properties, falling back to getting it from the manifest
public synchronized String getVersion() {
String version = null;
// try to load from maven properties first
try {
Properties p = new Properties();
InputStream is = getClass().getResourceAsStream("/META-INF/maven/com.my.group/my-artefact/pom.properties");
if (is != null) {
p.load(is);
version = p.getProperty("version", "");
}
} catch (Exception e) {
// ignore
}
// fallback to using Java API
if (version == null) {
Package aPackage = getClass().getPackage();
if (aPackage != null) {
version = aPackage.getImplementationVersion();
if (version == null) {
version = aPackage.getSpecificationVersion();
}
}
}
if (version == null) {
// we could not compute the version so use a blank
version = "";
}
return version;
}
This is what I used for similar type of use case as yours.
<style type="text/css">
#element1 {display:inline-block; width:45%; padding:10px}
#element2 {display:inline-block; width:45%; padding:10px}
</style>
<div id="element1">
element 1 markup
</div>
<div id="element2">
element 2 markup
</div>
Adjust your width and padding as per your requirement. Note - Do not exceed 'width' more than 100% altogether (ele1_width+ ele2_width) to add 'padding', keep it less than 100%.
if you just want the part between http:// and the first slash
string url = Request.Url.Host;
would return stackoverflow.com if called from this page
Here's the complete breakdown
You need
test.split("\\|");
split
uses regular expression and in regex |
is a metacharacter representing the OR
operator. You need to escape that character using \
(written in String as "\\"
since \
is also a metacharacter in String literals and require another \
to escape it).
You can also use
test.split(Pattern.quote("|"));
and let Pattern.quote
create the escaped version of the regex representing |
.
You need a whole input match here.
System.out.println(test.matches("^(http|https|ftp)://.*$"));
Edit:(Based on @davidchambers's comment)
System.out.println(test.matches("^(https?|ftp)://.*$"));
While its not bad practice to use break and there are many excellent uses for it, it should not be all you rely upon. Almost any use of a break can be written into the loop condition. Code is far more readable when real conditions are used, but in the case of a long-running or infinite loop, breaks make perfect sense. They also make sense when searching for data, as shown above.
For me, the problem was I had two installations of Apache Tomcat
The following steps solved my problem:
You need to move the unique_ptr
:
vec.push_back(std::move(ptr2x));
unique_ptr
guarantees that a single unique_ptr
container has ownership of the held pointer. This means that you can't make copies of a unique_ptr
(because then two unique_ptr
s would have ownership), so you can only move it.
Note, however, that your current use of unique_ptr
is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:
std::unique_ptr<int> ptr(new int(1));
In C++14 we have an even better way to do so:
make_unique<int>(5);
Use the Oracle documentation and search for keyword "trigger" in your browser.
This approach should work with other metadata type questions.
check this Twig Reference.
You can do it that simple:
{% if (a or b) %}
...
{% endif %}
It's as simple as:
if (value.compareTo(BigDecimal.ZERO) > 0)
The documentation for compareTo
actually specifies that it will return -1, 0 or 1, but the more general Comparable<T>.compareTo
method only guarantees less than zero, zero, or greater than zero for the appropriate three cases - so I typically just stick to that comparison.
Stole this from here. I found it very useful!
DECLARE @DB_USers TABLE
(DBName sysname, UserName sysname, LoginType sysname, AssociatedRole varchar(max),create_date datetime,modify_date datetime)
INSERT @DB_USers
EXEC sp_MSforeachdb
'
use [?]
SELECT ''?'' AS DB_Name,
case prin.name when ''dbo'' then prin.name + '' (''+ (select SUSER_SNAME(owner_sid) from master.sys.databases where name =''?'') + '')'' else prin.name end AS UserName,
prin.type_desc AS LoginType,
isnull(USER_NAME(mem.role_principal_id),'''') AS AssociatedRole ,create_date,modify_date
FROM sys.database_principals prin
LEFT OUTER JOIN sys.database_role_members mem ON prin.principal_id=mem.member_principal_id
WHERE prin.sid IS NOT NULL and prin.sid NOT IN (0x00) and
prin.is_fixed_role <> 1 AND prin.name NOT LIKE ''##%'''
SELECT
dbname,username ,logintype ,create_date ,modify_date ,
STUFF(
(
SELECT ',' + CONVERT(VARCHAR(500),associatedrole)
FROM @DB_USers user2
WHERE
user1.DBName=user2.DBName AND user1.UserName=user2.UserName
FOR XML PATH('')
)
,1,1,'') AS Permissions_user
FROM @DB_USers user1
GROUP BY
dbname,username ,logintype ,create_date ,modify_date
ORDER BY DBName,username
Instead of exceptions, just use:
if (Build.VERSION.SDK_INT >= 11)
and use
@SuppressLint("NewApi")
to suppress the warnings.
"{0:b}".format(100) # bin: 1100100
"{0:x}".format(100) # hex: 64
"{0:o}".format(100) # oct: 144
The best thing is probably to create a variable that holds your binaries:
binaries=code1 code2
Then use that in the all
-target, to avoid repeating:
all: clean $(binaries)
Now, you can use this with the clean
-target, too, and just add some globs to catch object files and stuff:
.PHONY: clean
clean:
rm -f $(binaries) *.o
Note use of the .PHONY
to make clean
a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.
I have simply replaced the "\n
" with "<br>
" tag. Worked fine. It seems TCPDF render the text as HTML
$strText = str_replace("\n","<br>",$strText);
$pdf->MultiCell($width, $height,$strText, 0, 'J', 0, 1, '', '', true, null, true);
If you really want to process your file line by line, a solution might be to use fgetl
:
fopen
fgetl
sscanf
on the character array you just readUnlike the previous answer, this is not very much in the style of Matlab but it might be more efficient on very large files.
Hope this will help.
target_compile_options
solution above is wrong, it won't link the library.
Use:
SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")
OR
target_link_libraries(XXX PUBLIC pthread)
OR
set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)
(If you are using NetBeans IDE) Just create a folder in your project but out side of src folder. Named the folder Images. And then put the image into the Images folder and write code below.
// Import ImageIcon
ImageIcon iconLogo = new ImageIcon("Images/YourCompanyLogo.png");
// In init() method write this code
jLabelYourCompanyLogo.setIcon(iconLogo);
Now run your program.
I think you want to speed up your cell loading at the time of image loading for cell in the background. For that we have done the following steps:
Checking the file exists in the document directory or not.
If not then loading the image for the first time, and saving it to our phone document directory. If you don't want to save the image in the phone then you can load cell images directlyin the background.
Now the loading process:
Just include: #import "ManabImageOperations.h"
The code is like below for a cell:
NSString *imagestr=[NSString stringWithFormat:@"http://www.yourlink.com/%@",[dictn objectForKey:@"member_image"]];
NSString *docDir=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSLog(@"Doc Dir: %@",docDir);
NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@",docDir,[dictn objectForKey:@"member_image"]];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:pngFilePath];
if (fileExists)
{
[cell1.memberimage setImage:[UIImage imageWithContentsOfFile:pngFilePath] forState:UIControlStateNormal];
}
else
{
[ManabImageOperations processImageDataWithURLString:imagestr andBlock:^(NSData *imageData)
{
[cell1.memberimage setImage:[[UIImage alloc]initWithData: imageData] forState:UIControlStateNormal];
[imageData writeToFile:pngFilePath atomically:YES];
}];
}
ManabImageOperations.h:
#import <Foundation/Foundation.h>
@interface ManabImageOperations : NSObject
{
}
+ (void)processImageDataWithURLString:(NSString *)urlString andBlock:(void (^)(NSData *imageData))processImage;
@end
ManabImageOperations.m:
#import "ManabImageOperations.h"
#import <QuartzCore/QuartzCore.h>
@implementation ManabImageOperations
+ (void)processImageDataWithURLString:(NSString *)urlString andBlock:(void (^)(NSData *imageData))processImage
{
NSURL *url = [NSURL URLWithString:urlString];
dispatch_queue_t callerQueue = dispatch_get_main_queue();
dispatch_queue_t downloadQueue = dispatch_queue_create("com.myapp.processsmagequeue", NULL);
dispatch_async(downloadQueue, ^{
NSData * imageData = [NSData dataWithContentsOfURL:url];
dispatch_async(callerQueue, ^{
processImage(imageData);
});
});
// downloadQueue=nil;
dispatch_release(downloadQueue);
}
@end
Please check the answer and comment if there is any problem occurs....
I was searching about how stack works in terms of function and i found this blog its awesome and its explain concept of stack from scratch and how stack store value in stack.
Now on your answer . I will explain with python but you will get good idea how stack works in any language.
Its a program :
def hello(x):
if x==1:
return "op"
else:
u=1
e=12
s=hello(x-1)
e+=1
print(s)
print(x)
u+=1
return e
hello(3)
Source : Cryptroix
some of its topic which it cover in blog:
How Function work ?
Calling a Function
Functions In a Stack
What is Return Address
Stack
Stack Frame
Call Stack
Frame Pointer (FP) or Base Pointer (BP)
Stack Pointer (SP)
Allocation stack and deallocation of stack
StackoverFlow
What is Heap?
But its explain with python language so if you want you can take a look.
If global tab/spaces indentation settings no longer fit your needs (I.E. you find yourself working with legacy codebases with varied indentation formats, and you need to quickly switch between them, and the auto-detect isn't working) you might try the tab-control plugin, which sort of duplicates the functionality of the menu in your screenshot.
{{-- Google Language Translator START --}}
<style>
.google-translate {
display: inline-block;
vertical-align: top;
padding-top: 15px;
}
.goog-logo-link {
display: none !important;
}
.goog-te-gadget {
color: transparent !important;
}
#google_translate_element {
display: none;
}
.goog-te-banner-frame.skiptranslate {
display: none !important;
}
body {
top: 0px !important;
}
</style>
<script src="{{asset('js/translate-google.js')}}"></script>
<script type="text/javascript">
function googleTranslateElementInit2(){
new google.translate.TranslateElement({
pageLanguage:'en',
includedLanguages: 'en,es',
// https://ctrlq.org/code/19899-google-translate-languages
// includedLanguages: 'en,it,la,fr',
// layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
autoDisplay:true
},'google_translate_element2');
var a = document.querySelector("#google_translate_element select");
// console.log(a);
if(a){
a.selectedIndex=1;
a.dispatchEvent(new Event('change'));
}
}
</script>
<ul class="navbar-nav my-lg-0 m-r-10">
<li>
<div class="google-translate">
<div id="google_translate_element2"></div>
</div>
</li>
{{-- Google Language Translator ENDS --}}
// translate-google.js
(function () {
var gtConstEvalStartTime = new Date();
function d(b) {
var a = document.getElementsByTagName("head")[0];
a || (a = document.body.parentNode.appendChild(document.createElement("head")));
a.appendChild(b)
}
function _loadJs(b) {
// console.log(b);
var a = document.createElement("script");
a.type = "text/javascript";
a.charset = "UTF-8";
a.src = b;
d(a)
}
function _loadCss(b) {
var a = document.createElement("link");
a.type = "text/css";
a.rel = "stylesheet";
a.charset = "UTF-8";
a.href = b;
d(a)
}
function _isNS(b) {
b = b.split(".");
for (var a = window, c = 0; c < b.length; ++c)
if (!(a = a[b[c]])) return !1;
return !0
}
function _setupNS(b) {
b = b.split(".");
for (var a = window, c = 0; c < b.length; ++c) a.hasOwnProperty ? a.hasOwnProperty(b[c]) ? a = a[b[c]] : a = a[b[c]] = {} : a = a[b[c]] || (a[b[c]] = {});
return a
}
window.addEventListener && "undefined" == typeof document.readyState && window.addEventListener("DOMContentLoaded", function () {
document.readyState = "complete"
}, !1);
if (_isNS('google.translate.Element')) {
return
}(function () {
var c = _setupNS('google.translate._const');
c._cest = gtConstEvalStartTime;
gtConstEvalStartTime = undefined;
c._cl = 'en';
c._cuc = 'googleTranslateElementInit2';
c._cac = '';
c._cam = '';
c._ctkk = eval('((function(){var a\x3d3002255536;var b\x3d-2533142796;return 425386+\x27.\x27+(a+b)})())');
var h = 'translate.googleapis.com';
var s = (true ? 'https' : window.location.protocol == 'https:' ? 'https' : 'http') + '://';
var b = s + h;
c._pah = h;
c._pas = s;
c._pbi = b + '/translate_static/img/te_bk.gif';
c._pci = b + '/translate_static/img/te_ctrl3.gif';
c._pli = b + '/translate_static/img/loading.gif';
c._plla = h + '/translate_a/l';
c._pmi = b + '/translate_static/img/mini_google.png';
c._ps = b + '/translate_static/css/translateelement.css';
c._puh = 'translate.google.com';
_loadCss(c._ps);
_loadJs(b + '/translate_static/js/element/main.js');
})();
})();
Using an element-wise logical or and setting the take_last argument of the pandas duplicated method to both True and False you can obtain a set from your dataframe that includes all of the duplicates.
df_bigdata_duplicates =
df_bigdata[df_bigdata.duplicated(cols='ID', take_last=False) |
df_bigdata.duplicated(cols='ID', take_last=True)
]
We can write directly too...
DECLARE @SearchLetter CHAR(1)
SET @SearchLetter = 'A'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE @SearchLetter + '%'
AND REGION = 'WY'
or the following way as well if we have to append all the search characters then,
DECLARE @SearchLetter CHAR(1)
SET @SearchLetter = 'A' + '%'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE @SearchLetter
AND REGION = 'WY'
Both these will work
For me, the trick was extraData and drilling down into the item component one more time
state = {
uniqueValue: 0
}
<FlatList
keyExtractor={(item, index) => item + index}
data={this.props.photos}
renderItem={this.renderItem}
ItemSeparatorComponent={this.renderSeparator}
/>
renderItem = (item) => {
if(item.item.selected) {
return ( <Button onPress={this.itemPressed.bind(this, item)}>Selected</Button> );
}
return ( <Button onPress={this.itemPressed.bind(this, item)}>Not selected</Button>);
}
itemPressed (item) {
this.props.photos.map((img, i) => {
if(i === item.index) {
if(img['selected') {
delete img.selected;
} else {
img['selected'] = true;
}
this.setState({ uniqueValue: this.state.uniqueValue +1 });
}
}
}
On Mac I could not find the pgrep and pkill neither was killall working so wrote a simple one liner script:-
export pid=`ps | grep process_name | awk 'NR==1{print $1}' | cut -d' ' -f1`;kill $pid
If there's an easier way of doing this then please share.
You can try this
$('#select_id').select2({ minimumResultsForSearch: -1 });
it closes the search results box and then set control unvisible
You can check here in select2 document select2 documents
if you want to access table cell
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[1]"));
If you want to access nested table cell -
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[2]"+//table/tbody/tr[1]/td[2]));
For more details visit this Tutorial
I'm not sure about changing the tint vs the background color but this is how you change the tint color of the Navigation Bar:
Try this code..
[navigationController.navigationBar setTintColor:[UIColor redColor];
//Red as an example.
A good way to debug this is the next time it happens, SSH into the remote repo, cd into the objects folder and do an ls -al
.
If you see 2-3 files with different user:group ownership than this is the problem.
It's happened to me in the past with some legacy scripts access our git repo and usually means a different (unix) user pushed / modified files last and your user doesn't have permissions to overwrite those files. You should create a shared git group that all git-enabled users are in and then recursively chgrp
the objects
folder and it's contents so that it's group ownership is the shared git
group.
You should also add a sticky bit on the folder so that all the files created in the folder will always have the group of git
.
chmod g+s directory-name
Update: I didn't know about core.sharedRepository. Good to know, though it probably just does the above.
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
if (INSTANCE != null)
throw new IllegalStateException(“Already instantiated...”);
}
public synchronized static Singleton getInstance() {
return INSTANCE;
}
}
As we have added the Synchronized keyword before getInstance, we have avoided the race condition in the case when two threads call the getInstance at the same time.
There are different methods to achieve this goal. I've tried some of them and found really working one with just git and svn installed on Windows OS.
Prerequisites:
svnadmin dump /path/to/repository > repo_name.svn_dump
Steps to achieve final goal (move all repository with history to a git, firstly local git, then remote)
Create empty repository (using console tools or tortoiseSVN) in directory REPO_NAME_FOLDER
cd REPO_NAME_PARENT_FOLDER
, put dumpfile.dump into REPO_NAME_PARENT_FOLDER
svnadmin load REPO_NAME_FOLDER < dumpfile.dump
Wait for this operation, it may be long
This command is silent, so open second cmd window : svnserve -d -R --root REPO_NAME_FOLDER
Why not just use file:///...... ? Cause next command will fail with Unable to open ... to URL:
, thanks to the answer https://stackoverflow.com/a/6300968/4953065
Create new folder SOURCE_GIT_FOLDER
cd SOURCE_GIT_FOLDER
Finally, what do we got?
Lets check our Local repository :
git log
See your previous commits? If yes - okay
So now you have fully functional local git repository with your sources and old svn history. Now, if you want to move it to some server, use the following commands :
git remote add origin https://fullurlpathtoyourrepo/reponame.git
git push -u origin --all # pushes up the repo and its refs for the first time
git push -u origin --tags # pushes up any tags
In my case, I've dont need tags command cause my repo dont have tags.
Good luck!
It looks like the string contains an array with a single MyStok
object in it. If you remove square brackets from both ends of the input, you should be able to deserialize the data as a single object:
MyStok myobj = JSON.Deserialize<MyStok>(sc.Substring(1, sc.Length-2));
You could also deserialize the array into a list of MyStok
objects, and take the object at index zero.
var myobjList = JSON.Deserialize<List<MyStok>>(sc);
var myObj = myobjList[0];
I get the same error in WP when I use php ver 7.1.6 - just take your php version back to 7.0.20 and the error will disappear.
One idiom is:
cd some_dir && ./configure --some-flags && make && make install
I realize that can get long, but for larger scripts you could break it into logical functions.
This is just too complicated. Maps were not supposed to do such job as sorting them by Value. The easiest way is to create your own Class so it fits your requirement.
In example lower you are supposed to add TreeMap a comparator at place where * is. But by java API it gives comparator only keys, not values. All of examples stated here is based on 2 Maps. One Hash and one new Tree. Which is odd.
The example:
Map<Driver driver, Float time> map = new TreeMap<Driver driver, Float time>(*);
So change the map into a set this way:
ResultComparator rc = new ResultComparator();
Set<Results> set = new TreeSet<Results>(rc);
You will create class Results
,
public class Results {
private Driver driver;
private Float time;
public Results(Driver driver, Float time) {
this.driver = driver;
this.time = time;
}
public Float getTime() {
return time;
}
public void setTime(Float time) {
this.time = time;
}
public Driver getDriver() {
return driver;
}
public void setDriver (Driver driver) {
this.driver = driver;
}
}
and the Comparator class:
public class ResultsComparator implements Comparator<Results> {
public int compare(Results t, Results t1) {
if (t.getTime() < t1.getTime()) {
return 1;
} else if (t.getTime() == t1.getTime()) {
return 0;
} else {
return -1;
}
}
}
This way you can easily add more dependencies.
And as the last point I'll add simple iterator:
Iterator it = set.iterator();
while (it.hasNext()) {
Results r = (Results)it.next();
System.out.println( r.getDriver().toString
//or whatever that is related to Driver class -getName() getSurname()
+ " "
+ r.getTime()
);
}
As the error message says, non-default argument til
should not follow default argument hgt
.
Changing order of parameters (function call also be adjusted accordingly) or making hgt
non-default parameter will solve your problem.
def a(len1, hgt=len1, til, col=0):
->
def a(len1, hgt, til, col=0):
UPDATE
Another issue that is hidden by the SyntaxError.
os.system
accepts only one string parameter.
def a(len1, hgt, til, col=0):
system('mode con cols=%s lines=%s' % (len1, hgt))
system('title %s' % til)
system('color %s' % col)
Sample code block for strong password:
(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?=\\S+$).{6,18}
The answers that suggest using variations of $window.history.back()
have all missed a crucial part of the question: How to restore the application's state to the correct state-location as the history jumps (back/forward/refresh). With that in mind; please, read on.
Yes, it is possible to have the browser back/forward (history) and refresh whilst running a pure ui-router
state-machine but it takes a bit of doing.
You need several components:
Unique URLs. The browser only enables the back/forward buttons when you change urls, so you must generate a unique url per visited state. These urls need not contain any state information though.
A Session Service. Each generated url is correlated to a particular state so you need a way to store your url-state pairs so that you can retrieve the state information after your angular app has been restarted by back / forward or refresh clicks.
A State History. A simple dictionary of ui-router states keyed by unique url. If you can rely on HTML5 then you can use the HTML5 History API, but if, like me, you can't then you can implement it yourself in a few lines of code (see below).
A Location Service. Finally, you need to be able manage both ui-router state changes, triggered internally by your code, and normal browser url changes typically triggered by the user clicking browser buttons or typing stuff into the browser bar. This can all get a bit tricky because it is easy to get confused about what triggered what.
Here is my implementation of each of these requirements. I have bundled everything up into three services:
The Session Service
class SessionService
setStorage:(key, value) ->
json = if value is undefined then null else JSON.stringify value
sessionStorage.setItem key, json
getStorage:(key)->
JSON.parse sessionStorage.getItem key
clear: ->
@setStorage(key, null) for key of sessionStorage
stateHistory:(value=null) ->
@accessor 'stateHistory', value
# other properties goes here
accessor:(name, value)->
return @getStorage name unless value?
@setStorage name, value
angular
.module 'app.Services'
.service 'sessionService', SessionService
This is a wrapper for the javascript sessionStorage
object. I have cut it down for clarity here. For a full explanation of this please see: How do I handle page refreshing with an AngularJS Single Page Application
The State History Service
class StateHistoryService
@$inject:['sessionService']
constructor:(@sessionService) ->
set:(key, state)->
history = @sessionService.stateHistory() ? {}
history[key] = state
@sessionService.stateHistory history
get:(key)->
@sessionService.stateHistory()?[key]
angular
.module 'app.Services'
.service 'stateHistoryService', StateHistoryService
The StateHistoryService
looks after the storage and retrieval of historical states keyed by generated, unique urls. It is really just a convenience wrapper for a dictionary style object.
The State Location Service
class StateLocationService
preventCall:[]
@$inject:['$location','$state', 'stateHistoryService']
constructor:(@location, @state, @stateHistoryService) ->
locationChange: ->
return if @preventCall.pop('locationChange')?
entry = @stateHistoryService.get @location.url()
return unless entry?
@preventCall.push 'stateChange'
@state.go entry.name, entry.params, {location:false}
stateChange: ->
return if @preventCall.pop('stateChange')?
entry = {name: @state.current.name, params: @state.params}
#generate your site specific, unique url here
url = "/#{@state.params.subscriptionUrl}/#{Math.guid().substr(0,8)}"
@stateHistoryService.set url, entry
@preventCall.push 'locationChange'
@location.url url
angular
.module 'app.Services'
.service 'stateLocationService', StateLocationService
The StateLocationService
handles two events:
locationChange. This is called when the browsers location is changed, typically when the back/forward/refresh button is pressed or when the app first starts or when the user types in a url. If a state for the current location.url exists in the StateHistoryService
then it is used to restore the state via ui-router's $state.go
.
stateChange. This is called when you move state internally. The current state's name and params are stored in the StateHistoryService
keyed by a generated url. This generated url can be anything you want, it may or may not identify the state in a human readable way. In my case I am using a state param plus a randomly generated sequence of digits derived from a guid (see foot for the guid generator snippet). The generated url is displayed in the browser bar and, crucially, added to the browser's internal history stack using @location.url url
. Its adding the url to the browser's history stack that enables the forward / back buttons.
The big problem with this technique is that calling @location.url url
in the stateChange
method will trigger the $locationChangeSuccess
event and so call the locationChange
method. Equally calling the @state.go
from locationChange
will trigger the $stateChangeSuccess
event and so the stateChange
method. This gets very confusing and messes up the browser history no end.
The solution is very simple. You can see the preventCall
array being used as a stack (pop
and push
). Each time one of the methods is called it prevents the other method being called one-time-only. This technique does not interfere with the correct triggering of the $ events and keeps everything straight.
Now all we need to do is call the HistoryService
methods at the appropriate time in the state transition life-cycle. This is done in the AngularJS Apps .run
method, like this:
Angular app.run
angular
.module 'app', ['ui.router']
.run ($rootScope, stateLocationService) ->
$rootScope.$on '$stateChangeSuccess', (event, toState, toParams) ->
stateLocationService.stateChange()
$rootScope.$on '$locationChangeSuccess', ->
stateLocationService.locationChange()
Generate a Guid
Math.guid = ->
s4 = -> Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
"#{s4()}#{s4()}-#{s4()}-#{s4()}-#{s4()}-#{s4()}#{s4()}#{s4()}"
With all this in place, the forward / back buttons and the refresh button all work as expected.
You can just delete .git. Typically:
rm -rf .git
Then, recreate as the right user.
Try like that may you get your solution
String table = "beaconTable";
String whereClause = "_id=?";
String[] whereArgs = new String[] { String.valueOf(row) };
db.delete(table, whereClause, whereArgs);
Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:
WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);
foo(driver,startURL);
/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
String previousURL = driver.getCurrentUrl();
driver.findElement(By.xpath("//*[@id='someID']")).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
ExpectedCondition e = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return (d.getCurrentUrl() != previousURL);
}
};
wait.until(e);
currentURL = driver.getCurrentUrl();
System.out.println(currentURL);
}
var page_url = windws.location.href;
var page_id = page_url.substring(page_url.lastIndexOf("#") + 1);
if (page_id == "") {
$("html, body").animate({
scrollTop: $("#scroll-" + page_id).offset().top
}, 2000)
} else if (page_id == "") {
$("html, body").animate({
scrollTop: $("#scroll-" + page_id).offset().top
}, 2000)
}
});
You can simply compare 2 strings
function isLater(dateString1, dateString2) {
return dateString1 > dateString2
}
Then
isLater("2012-12-01", "2012-11-01")
returns true while
isLater("2012-12-01", "2013-11-01")
returns false
Use Assembly.GetTypes
. For example:
Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
Console.WriteLine(type.FullName);
}
I had this problem when having a Nginx server that exposing the node-js application to the external world. The Nginx made the file (css, js, ...) compressed with gzip
and with Chrome it looked like the same.
The problem solved when we found that the node-js server is also compressed the content with gzip. In someway, this double compressing leading to this problem. Canceling node-js compression solved the issue.
More "Try it Yourself" examples below.
Definition and Usage The split() method is used to split a string into an array of substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is split between each character.
Note: The split() method does not change the original string.
var res = str.split(",");
Build.SERIAL
can be empty or sometimes return a different value (proof 1, proof 2) than what you can see in your device's settings.
If you want a more complete and robust solution, I've compiled every possible solution I could found in a single gist. Here's a simplified version of it :
public static String getSerialNumber() {
String serialNumber;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class);
serialNumber = (String) get.invoke(c, "gsm.sn1");
if (serialNumber.equals(""))
serialNumber = (String) get.invoke(c, "ril.serialnumber");
if (serialNumber.equals(""))
serialNumber = (String) get.invoke(c, "ro.serialno");
if (serialNumber.equals(""))
serialNumber = (String) get.invoke(c, "sys.serialnumber");
if (serialNumber.equals(""))
serialNumber = Build.SERIAL;
// If none of the methods above worked
if (serialNumber.equals(""))
serialNumber = null;
} catch (Exception e) {
e.printStackTrace();
serialNumber = null;
}
return serialNumber;
}
I try to update the gist regularly whenever I can test on a new device or Android version. Contributions are welcome too.
You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :
BEGIN TRANSACTION
update A
set A.ORG_NAME = @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
COMMIT
id -u
is much better than whoami
, since some systems like android may not provide the word root.
Example:
# whoami
whoami
whoami: unknown uid 0
jquery.ajax({
url: `//your api url`
type: "GET",
dataType: "json",
success: function(data) {
jQuery.each(data, function(index, value) {
console.log(data);
`All you API data is here`
}
}
});
What do you mean by ‘hang state’? Typically, a process that is unresponsive and using 100% of a CPU is stuck in an endless loop. But there's no way to determine whether that has happened or whether the process might not eventually reach a loop exit state and carry on.
Desktop hang detectors just work by sending a message to the application's event loop and seeing if there's any response. If there's not for a certain amount of time they decide the app has ‘hung’... but it's entirely possible it was just doing something complicated and will come back to life in a moment once it's done. Anyhow, that's not something you can use for any arbitrary process.
There are several approaches.
One is to use a non-capturing group in the regex: (?:/(?P<title>[a-zA-Z]+)/)?
Making a Regex Django URL Token Optional
Another, easier to follow way is to have multiple rules that matches your needs, all pointing to the same view.
urlpatterns = patterns('',
url(r'^project_config/$', views.foo),
url(r'^project_config/(?P<product>\w+)/$', views.foo),
url(r'^project_config/(?P<product>\w+)/(?P<project_id>\w+)/$', views.foo),
)
Keep in mind that in your view you'll also need to set a default for the optional URL parameter, or you'll get an error:
def foo(request, optional_parameter=''):
# Your code goes here
Because when I use one or another I get a window prompt asking me to download the file for both of them.
This behavior depends on the browser and the file you are trying to serve. With inline, the browser will try to open the file within the browser.
For example, if you have a PDF file and Firefox/Adobe Reader, an inline disposition will open the PDF within Firefox, whereas attachment will force it to download.
If you're serving a .ZIP file, browsers won't be able to display it inline, so for inline and attachment dispositions, the file will be downloaded.
The withColumn function in pyspark enables you to make a new variable with conditions, add in the when and otherwise functions and you have a properly working if then else structure. For all of this you would need to import the sparksql functions, as you will see that the following bit of code will not work without the col() function. In the first bit, we declare a new column -'new column', and then give the condition enclosed in when function (i.e. fruit1==fruit2) then give 1 if the condition is true, if untrue the control goes to the otherwise which then takes care of the second condition (fruit1 or fruit2 is Null) with the isNull() function and if true 3 is returned and if false, the otherwise is checked again giving 0 as the answer.
from pyspark.sql import functions as F
df=df.withColumn('new_column',
F.when(F.col('fruit1')==F.col('fruit2'), 1)
.otherwise(F.when((F.col('fruit1').isNull()) | (F.col('fruit2').isNull()), 3))
.otherwise(0))
This happens when Elasticsearch thinks the disk is running low on space so it puts itself into read-only mode.
By default Elasticsearch's decision is based on the percentage of disk space that's free, so on big disks this can happen even if you have many gigabytes of free space.
The flood stage watermark is 95% by default, so on a 1TB drive you need at least 50GB of free space or Elasticsearch will put itself into read-only mode.
For docs about the flood stage watermark see https://www.elastic.co/guide/en/elasticsearch/reference/6.2/disk-allocator.html.
The right solution depends on the context - for example a production environment vs a development environment.
Freeing up enough disk space so that more than 5% of the disk is free will solve this problem. Elasticsearch won't automatically take itself out of read-only mode once enough disk is free though, you'll have to do something like this to unlock the indices:
$ curl -XPUT -H "Content-Type: application/json" https://[YOUR_ELASTICSEARCH_ENDPOINT]:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
Change the "cluster.routing.allocation.disk.watermark.flood_stage"
setting to something else. It can either be set to a lower percentage or to an absolute value. Here's an example of how to change the setting from the docs:
PUT _cluster/settings
{
"transient": {
"cluster.routing.allocation.disk.watermark.low": "100gb",
"cluster.routing.allocation.disk.watermark.high": "50gb",
"cluster.routing.allocation.disk.watermark.flood_stage": "10gb",
"cluster.info.update.interval": "1m"
}
}
Again, after doing this you'll have to use the curl command above to unlock the indices, but after that they should not go into read-only mode again.
You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?
this.Controls.Add(dataGridView1);
By the way the code is a bit confused
String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql = "SELECT Clients FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
conn.Open();
DataSet ds = new DataSet();
DataGridView dataGridView1 = new DataGridView();
using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds;
// Of course, before addint the datagrid to the hosting form you need to
// set position, location and other useful properties.
// Why don't you create the DataGrid with the designer and use that instance instead?
this.Controls.Add(dataGridView1);
}
}
EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as
SELECT field_names_list FROM _tablename_
so the correct syntax to use for retrieving all the clients data is
string sql = "SELECT * FROM Clients";
where the *
means -> all the fields present in the table
If the difference between endTime and startTime is greater than or equal to 60 Minutes , the statement:endTime.Subtract(startTime).Minutes;
will always return (minutesDifference % 60)
. Obviously which is not desired when we are only talking about minutes (not hours here).
Here are some of the ways if you want to get total number of minutes
(in different typecasts):
// Default value that is returned is of type *double*
double double_minutes = endTime.Subtract(startTime).TotalMinutes;
int integer_minutes = (int)endTime.Subtract(startTime).TotalMinutes;
long long_minutes = (long)endTime.Subtract(startTime).TotalMinutes;
string string_minutes = (string)endTime.Subtract(startTime).TotalMinutes;
HttpClient was deprecated in API Level 22 and removed in API Level 23. You can still use it in API Level 23 and onwards if you must, however it is best to move to supported methods to handle HTTP. So, if you're compiling with 23, add this in your build.gradle:
android {
useLibrary 'org.apache.http.legacy'
}
I know that OP has listed this on his checklist, but it's easy to overlook that point while doing clean install of Visual Studio 2017 and setting up new project. Apart from NUnit project template and NUnit Framework one needs to install NUnit adaptor separately, e.g. using NuGet command Install-Package NUnit3TestAdapter -Version 3.9.0
. After that Visual Studio Community 2017 started discovering unit tests without any issues.
You can set the default time out in the server.xml
<Connector URIEncoding="UTF-8"
acceptCount="100"
connectionTimeout="20000"
disableUploadTimeout="true"
enableLookups="false"
maxHttpHeaderSize="8192"
maxSpareThreads="75"
maxThreads="150"
minSpareThreads="25"
port="7777"
redirectPort="8443"/>
#include <bits/stdc++.h> // to include all libraries
using namespace std;
int main()
{
double a,b;
cin>>a>>b;
double x=a/b; //say we want to divide a/b
cout<<fixed<<setprecision(10)<<x; //for precision upto 10 digit
return 0;
}
input: 1987 31
output: 662.3333333333 10 digits after decimal point
I recommend the SwifterSwift Library. However, if you don't want to use the entire library and all its great additions you can just make use of their extension of Dictionary:
public extension Dictionary {
public static func +=(lhs: inout [Key: Value], rhs: [Key: Value]) {
rhs.forEach({ lhs[$0] = $1})
}
}
I think you could do:
$('#google_translate_element').find('*').each(function(){
$(this).unbind('click');
});
but it would cause a lot of overhead
Found a solution on this website
All you need is to add the following to your web.config
<configuration>
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</configuration>
More info from Microsoft
JSON.stringify
's third parameter defines white-space insertion for pretty-printing. It can be a string or a number (number of spaces). Node can write to your filesystem with fs
. Example:
var fs = require('fs');
fs.writeFile('test.json', JSON.stringify({ a:1, b:2, c:3 }, null, 4));
/* test.json:
{
"a": 1,
"b": 2,
"c": 3,
}
*/
See the JSON.stringify() docs at MDN, Node fs docs
I have found the solution else where:
SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32)
The recommended way to create random integers with NumPy these days is to use numpy.random.Generator.integers
. (documentation)
import numpy as np
import pandas as pd
rng = np.random.default_rng()
df = pd.DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list('ABCD'))
df
----------------------
A B C D
0 58 96 82 24
1 21 3 35 36
2 67 79 22 78
3 81 65 77 94
4 73 6 70 96
... ... ... ... ...
95 76 32 28 51
96 33 68 54 77
97 76 43 57 43
98 34 64 12 57
99 81 77 32 50
100 rows × 4 columns
This is a good and a tricky question. The topic of URI design is at the same time the most prominent part of a REST API and, therefore, a potentially long-term commitment towards the users of that API.
Since evolution of an application and, to a lesser extent, its API is a fact of life and that it's even similar to the evolution of a seemingly complex product like a programming language, the URI design should have less natural constraints and it should be preserved over time. The longer the application's and API's lifespan, the greater the commitment to the users of the application and API.
On the other hand, another fact of life is that it is hard to foresee all the resources and their aspects that would be consumed through the API. Luckily, it is not necessary to design the entire API which will be used until Apocalypse. It is sufficient to correctly define all the resource end-points and the addressing scheme of every resource and resource instance.
Over time you may need to add new resources and new attributes to each particular resource, but the method that API users follow to access a particular resources should not change once a resource addressing scheme becomes public and therefore final.
This method applies to HTTP verb semantics (e.g. PUT should always update/replace) and HTTP status codes that are supported in earlier API versions (they should continue to work so that API clients that have worked without human intervention should be able to continue to work like that).
Furthermore, since embedding of API version into the URI would disrupt the concept of hypermedia as the engine of application state (stated in Roy T. Fieldings PhD dissertation) by having a resource address/URI that would change over time, I would conclude that API versions should not be kept in resource URIs for a long time meaning that resource URIs that API users can depend on should be permalinks.
Sure, it is possible to embed API version in base URI but only for reasonable and restricted uses like debugging a API client that works with the the new API version. Such versioned APIs should be time-limited and available to limited groups of API users (like during closed betas) only. Otherwise, you commit yourself where you shouldn't.
A couple of thoughts regarding maintenance of API versions that have expiration date on them. All programming platforms/languages commonly used to implement web services (Java, .NET, PHP, Perl, Rails, etc.) allow easy binding of web service end-point(s) to a base URI. This way it's easy to gather and keep a collection of files/classes/methods separate across different API versions.
From the API users POV, it's also easier to work with and bind to a particular API version when it's this obvious but only for limited time, i.e. during development.
From the API maintainer's POV, it's easier to maintain different API versions in parallel by using source control systems that predominantly work on files as the smallest unit of (source code) versioning.
However, with API versions clearly visible in URI there's a caveat: one might also object this approach since API history becomes visible/aparent in the URI design and therefore is prone to changes over time which goes against the guidelines of REST. I agree!
The way to go around this reasonable objection, is to implement the latest API version under versionless API base URI. In this case, API client developers can choose to either:
develop against the latest one (committing themselves to maintain the application protecting it from eventual API changes that might break their badly designed API client).
bind to a specific version of the API (which becomes apparent) but only for a limited time
For example, if API v3.0 is the latest API version, the following two should be aliases (i.e. behave identically to all API requests):
http://shonzilla/api/customers/1234 http://shonzilla/api/v3.0/customers/1234 http://shonzilla/api/v3/customers/1234
In addition, API clients that still try to point to the old API should be informed to use the latest previous API version, if the API version they're using is obsolete or not supported anymore. So accessing any of the obsolete URIs like these:
http://shonzilla/api/v2.2/customers/1234 http://shonzilla/api/v2.0/customers/1234 http://shonzilla/api/v2/customers/1234 http://shonzilla/api/v1.1/customers/1234 http://shonzilla/api/v1/customers/1234
should return any of the 30x HTTP status codes that indicate redirection that are used in conjunction with Location
HTTP header that redirects to the appropriate version of resource URI which remain to be this one:
http://shonzilla/api/customers/1234
There are at least two redirection HTTP status codes that are appropriate for API versioning scenarios:
301 Moved permanently indicating that the resource with a requested URI is moved permanently to another URI (which should be a resource instance permalink that does not contain API version info). This status code can be used to indicate an obsolete/unsupported API version, informing API client that a versioned resource URI been replaced by a resource permalink.
302 Found indicating that the requested resource temporarily is located at another location, while requested URI may still supported. This status code may be useful when the version-less URIs are temporarily unavailable and that a request should be repeated using the redirection address (e.g. pointing to the URI with APi version embedded) and we want to tell clients to keep using it (i.e. the permalinks).
other scenarios can be found in Redirection 3xx chapter of HTTP 1.1 specification
For completeness, using cut
cut -d : -f 2 <<< $var
And using only bash:
IFS=: read a b <<< $var ; echo $b
From the manual entry for PDOStatement::bindParam
:
[With
bindParam
] UnlikePDOStatement::bindValue()
, the variable is bound as a reference and will only be evaluated at the time thatPDOStatement::execute()
is called.
So, for example:
$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindParam(':sex', $sex); // use bindParam to bind the variable
$sex = 'female';
$s->execute(); // executed with WHERE sex = 'female'
or
$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindValue(':sex', $sex); // use bindValue to bind the variable's value
$sex = 'female';
$s->execute(); // executed with WHERE sex = 'male'
the @Alt-Cat answer work for me!
R.attr.borderlessButtonStyle doesn't contain shadow.
and the document of button is great.
Also, you can set this style on your custom button, in second constructor.
public CustomButton(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.borderlessButtonStyle);
}
Just my two cents. If you are using Bootstrap 3 then I would just add an extra style into your own site's stylesheet which controls the text-left
style of the control-label
.
If you were to add text-left
to the label, by default there is another style which overrides this .form-horizontal .control-label
. So if you add:
.form-horizontal .control-label.text-left{
text-align: left;
}
Then the built in text-left
style is applied to the label correctly.
RollingFileAppender
does this. You just need to set maxBackupIndex
to the highest value for the backup file.
dumps
takes an object and produces a string:
>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'
load
would take a file-like object, read the data from that object, and use that string to create an object:
with open('file.json') as fh:
a = json.load(fh)
Note that dump
and load
convert between files and objects, while dumps
and loads
convert between strings and objects. You can think of the s
-less functions as wrappers around the s
functions:
def dump(obj, fh):
fh.write(dumps(obj))
def load(fh):
return loads(fh.read())
You should implement the IEnumerable interface (CarBootSaleList should impl it in your case).
http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx
But it is usually easier to subclass System.Collections.ObjectModel.Collection and friends
http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx
Your code also seems a bit strange, like you are nesting lists?
There are two solutions for it.
Solution number one: 1.Recreate the project. While creating a project ensure that precompiled header is checked(Application settings... *** Do not check empty project)
Solution Number two: 1.Create stdafx.h and stdafx.cpp in your project 2 Right click on project -> properties -> C/C++ -> Precompiled Headers 3.select precompiled header to create(/Yc) 4.Rebuild the solution
Drop me a message if you encounter any issue.
When a
and b
are 1-dimensional sequences, numpy.cov(a,b)[0][1]
is equivalent to your cov(a,b)
.
The 2x2 array returned by np.cov(a,b)
has elements equal to
cov(a,a) cov(a,b)
cov(a,b) cov(b,b)
(where, again, cov
is the function you defined above.)
filter_input(INPUT_POST, 'var_name')
instead of $_POST['var_name']
filter_input_array(INPUT_POST)
instead of $_POST
something along this?
function dump(x, indent) {
var indent = indent || '';
var s = '';
if (Array.isArray(x)) {
s += '[';
for (var i=0; i<x.length; i++) {
s += dump(x[i], indent)
if (i < x.length-1) s += ', ';
}
s +=']';
} else if (x === null) {
s = 'NULL';
} else switch(typeof x) {
case 'undefined':
s += 'UNDEFINED';
break;
case 'object':
s += "{ ";
var first = true;
for (var p in x) {
if (!first) s += indent + ' ';
s += p + ': ';
s += dump(x[p], indent + ' ');
s += "\n"
first = false;
}
s += '}';
break;
case 'boolean':
s += (x) ? 'TRUE' : 'FALSE';
break;
case 'number':
s += x;
break;
case 'string':
s += '"' + x + '"';
break;
case 'function':
s += '<FUNCTION>';
break;
default:
s += x;
break;
}
return s;
}
In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.
Here is an example I have just written to demonstrate how you could do it using deferreds/promises.
Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.
Hope this helps!
$(function(){
function1().done(function(){
// function1 is done, we can now call function2
console.log('function1 is done!');
function2().done(function(){
//function2 is done
console.log('function2 is done!');
});
});
});
function function1(){
var dfrd1 = $.Deferred();
var dfrd2= $.Deferred();
setTimeout(function(){
// doing async stuff
console.log('task 1 in function1 is done!');
dfrd1.resolve();
}, 1000);
setTimeout(function(){
// doing more async stuff
console.log('task 2 in function1 is done!');
dfrd2.resolve();
}, 750);
return $.when(dfrd1, dfrd2).done(function(){
console.log('both tasks in function1 are done');
// Both asyncs tasks are done
}).promise();
}
function function2(){
var dfrd1 = $.Deferred();
setTimeout(function(){
// doing async stuff
console.log('task 1 in function2 is done!');
dfrd1.resolve();
}, 2000);
return dfrd1.promise();
}
This generic function encodes every non alphabetic character to its htmlcode (numeric):
function HTMLEncode(str) {
var i = str.length,
aRet = [];
while (i--) {
var iC = str[i].charCodeAt();
if (iC < 65 || iC > 127 || (iC>90 && iC<97)) {
aRet[i] = '&#'+iC+';';
} else {
aRet[i] = str[i];
}
}
return aRet.join('');
}
This solution uses the windows mysql installer.
I have tried every other way mentioned here and other related posts, but it did not solve my problem, the service just wont start, but the below approach with the mysql-installer did.
If you still have your installer or atleast remember the version then follow below steps:
You can check from the window's services that the MySqL Server has started.
Hope it helps someone.
It serves as padding.
A more complete answer is that a base64 encoded string doesn't always end with a =
, it will only end with one or two =
if they are required to pad the string out to the proper length.
You're getting the error because result
defined as Sequential()
is just a container for the model and you have not defined an input for it.
Given what you're trying to build set result
to take the third input x3
.
first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))
second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))
third = Sequential()
# of course you must provide the input to result which will be your x3
third.add(Dense(1, input_shape=(1,), activation='sigmoid'))
# lets say you add a few more layers to first and second.
# concatenate them
merged = Concatenate([first, second])
# then concatenate the two outputs
result = Concatenate([merged, third])
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
result.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
However, my preferred way of building a model that has this type of input structure would be to use the functional api.
Here is an implementation of your requirements to get you started:
from keras.models import Model
from keras.layers import Concatenate, Dense, LSTM, Input, concatenate
from keras.optimizers import Adagrad
first_input = Input(shape=(2, ))
first_dense = Dense(1, )(first_input)
second_input = Input(shape=(2, ))
second_dense = Dense(1, )(second_input)
merge_one = concatenate([first_dense, second_dense])
third_input = Input(shape=(1, ))
merge_two = concatenate([merge_one, third_input])
model = Model(inputs=[first_input, second_input, third_input], outputs=merge_two)
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
model.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
To answer the question in the comments:
Concatenation works like this:
a b c
a b c g h i a b c g h i
d e f j k l d e f j k l
i.e rows are just joined.
x1
is input to first, x2
is input into second and x3
input into third.What you saw in Firefox was not the actual request; note that the HTTP method is OPTIONS, not POST. It was actually the 'pre-flight' request that the browser makes to determine whether a cross-domain AJAX request should be allowed:
The Access-Control-Request-Headers header in the pre-flight request includes the list of headers in the actual request. The server is then expected to report back whether these headers are supported in this context or not, before the browser submits the actual request.
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"defer</script>
Add Defer to the end of your Script tag, it worked for me (;
Everything needs to be loaded in the correct order (:
This works for me in Ansible 2.9:
variable1 = www.example.com.
variable2 = www.example.org.
when: ".com" in variable1
and for not:
when: not ".com" in variable2
Here is my solution. Works in most browsers
document.getElementById("scrollHere").scrollIntoView({behavior: "smooth"});
document.getElementById("end").scrollIntoView({behavior: "smooth"});
_x000D_
body {margin: 0px; display: block; height: 100%; background-image: linear-gradient(red, yellow);}_x000D_
.start {display: block; margin: 100px 10px 1000px 0px;}_x000D_
.end {display: block; margin: 0px 0px 100px 0px;}
_x000D_
<div class="start">Start</div>_x000D_
<div class="end" id="end">End</div>
_x000D_
I think the answer from cheez (https://stackoverflow.com/users/122933/cheez) is the easiest and most effective one. I'd elaborate a little bit over it so it would not modify a numpy function for the whole session period.
My suggestion is below. I´m using it to download the reuters dataset from keras which is showing the same kind of error:
old = np.load
np.load = lambda *a,**k: old(*a,**k,allow_pickle=True)
from keras.datasets import reuters
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)
np.load = old
del(old)
To edit Date in oracle you can try
select to_char(<columnName> + 5 / 24 + 30 / (24 * 60),
'DD/MM/RRRR hh:mi AM') AS <logicalName> from <tableName>
Note: the selected answer is changing the array order which is not preferred, here I provide more different variations that achieving the same result and keeping the array in order
given [98.88, .56, .56]
how do you want to round it? you have four option
1- round things up and subtract what is added from the rest of the numbers, so the result becomes [98, 1, 1]
this could be a good answer, but what if we have [97.5, .5, .5, .5, .5, .5]
? then you need to round it up to [95, 1, 1, 1, 1, 1]
do you see how it goes? if you add more 0-like numbers, you will lose more value from the rest of your numbers. this could be very troublesome when you have a big array of zero-like number like [40, .5, .5 , ... , .5]
. when you round up this, you could end up with an array of ones: [1, 1, .... , 1]
so round-up isn't a good option.
2- you round down the numbers. so [98.88, .56, .56]
becomes [98, 0, 0]
, then you are 2 less than 100. you ignore anything that is already 0, then add up the difference to the biggest numbers. so bigger numbers will get more.
3- same as previous, round down numbers, but you sort descending based on the decimals, divide up the diff based on the decimal, so biggest decimal will get the diff.
4- you round up, but you add what you added to the next number. so like a wave what you have added will be redirected to the end of your array. so [98.88, .56, .56]
becomes [99, 0, 1]
none of these are ideal, so be mindful that your data is going to lose its shape.
here I provide a code for cases 2 and 3 (as case No.1 is not practical when you have a lot of zero-like numbers). it's modern Js and doesn't need any library to use
const v1 = [13.626332, 47.989636, 9.596008, 28.788024];// => [ 14, 48, 9, 29 ]
const v2 = [16.666, 16.666, 16.666, 16.666, 16.666, 16.666] // => [ 17, 17, 17, 17, 16, 16 ]
const v3 = [33.333, 33.333, 33.333] // => [ 34, 33, 33 ]
const v4 = [33.3, 33.3, 33.3, 0.1] // => [ 34, 33, 33, 0 ]
const v5 = [98.88, .56, .56] // =>[ 100, 0, 0 ]
const v6 = [97.5, .5, .5, .5, .5, .5] // => [ 100, 0, 0, 0, 0, 0 ]
const normalizePercentageByNumber = (input) => {
const rounded: number[] = input.map(x => Math.floor(x));
const afterRoundSum = rounded.reduce((pre, curr) => pre + curr, 0);
const countMutableItems = rounded.filter(x => x >=1).length;
const errorRate = 100 - afterRoundSum;
const deductPortion = Math.ceil(errorRate / countMutableItems);
const biggest = [...rounded].sort((a, b) => b - a).slice(0, Math.min(Math.abs(errorRate), countMutableItems));
const result = rounded.map(x => {
const indexOfX = biggest.indexOf(x);
if (indexOfX >= 0) {
x += deductPortion;
console.log(biggest)
biggest.splice(indexOfX, 1);
return x;
}
return x;
});
return result;
}
const normalizePercentageByDecimal = (input: number[]) => {
const rounded= input.map((x, i) => ({number: Math.floor(x), decimal: x%1, index: i }));
const decimalSorted= [...rounded].sort((a,b)=> b.decimal-a.decimal);
const sum = rounded.reduce((pre, curr)=> pre + curr.number, 0) ;
const error= 100-sum;
for (let i = 0; i < error; i++) {
const element = decimalSorted[i];
element.number++;
}
const result= [...decimalSorted].sort((a,b)=> a.index-b.index);
return result.map(x=> x.number);
}
you just need to calculate how much extra air added or deducted to your numbers on each roundup and, add or subtract it again in the next item.
const v1 = [13.626332, 47.989636, 9.596008, 28.788024];// => [14, 48, 10, 28 ]
const v2 = [16.666, 16.666, 16.666, 16.666, 16.666, 16.666] // => [17, 16, 17, 16, 17, 17]
const v3 = [33.333, 33.333, 33.333] // => [33, 34, 33]
const v4 = [33.3, 33.3, 33.3, 0.1] // => [33, 34, 33, 0]
const normalizePercentageByWave= v4.reduce((pre, curr, i, arr) => {
let number = Math.round(curr + pre.decimal);
let total = pre.total + number;
const decimal = curr - number;
if (i == arr.length - 1 && total < 100) {
const diff = 100 - total;
total += diff;
number += diff;
}
return { total, numbers: [...pre.numbers, number], decimal };
}, { total: 0, numbers: [], decimal: 0 });
One solution is to put them inside <center>
, like this:
<center>
<a href="http//www.google.com">Search</a>
<a href="Contact Us">Contact Us</a>
</center>
I've also created a jsfiddle for you: https://jsfiddle.net/9acgLf8e/
If you want to rotate a vector you should construct what is known as a rotation matrix.
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
The role you have created is not allowed to log in. You have to give the role permission to log in.
One way to do this is to log in as the postgres
user and update the role:
psql -U postgres
Once you are logged in, type:
ALTER ROLE "asunotest" WITH LOGIN;
Here's the documentation http://www.postgresql.org/docs/9.0/static/sql-alterrole.html
For Java 8 and above, it's easy:
when(mock.process(Matchers.anyList()));
For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz)
:
when(mock.process(Matchers.anyListOf(Bar.class)));
File f1 = new File("..\\..\\..\\config.properties");
this path trying to access file is in Project directory then just access file like this.
File f=new File("filename.txt");
if your file is in OtherSources/Resources
this.getClass().getClassLoader().getResource("relative path");//-> relative path from resources folder
Via jQuery plugins ;)
C:\Users\<Username>\AppData\Local\Continuum\anaconda2
For me this was the default installation directory on Windows 7. Found it via Rusy's answer
Your makefile should ideally be named makefile
, not make
. Note that you can call your makefile anything you like, but as you found, you then need the -f
option with make
to specify the name of the makefile. Using the default name of makefile
just makes life easier.
There are no conventions. There are some logical structure.
The only one thing that I can say: Never use camelCase file and directory names. Why? It works but on Mac and Windows there are no different between someAction and some action. I met this problem, and not once. I require'd a file like this:
var isHidden = require('./lib/isHidden');
But sadly I created a file with full of lowercase: lib/ishidden.js
. It worked for me on mac. It worked fine on mac of my co-worker. Tests run without errors. After deploy we got a huge error:
Error: Cannot find module './lib/isHidden'
Oh yeah. It's a linux box. So camelCase directory structure could be dangerous. It's enough for a colleague who is developing on Windows or Mac.
So use underscore (_) or dash (-) separator if you need.
toLocaleUpperCase() or lower case functions don't behave like they should do.
For example in my system, Safari 4, Chrome 4 Beta, Firefox 3.5.x it converts strings with Turkish characters incorrectly.
The browsers respond to navigator.language as "en-US", "tr", "en-US" respectively.
But there is no way to get user's Accept-Lang setting in the browser as far as I could find.
Only Chrome gives me trouble although I have configured every browser as tr-TR locale preferred.
I think these settings only affect HTTP header, but we can't access to these settings via JS.
In the Mozilla documentation it says "The characters within a string are converted to ... while respecting the current locale.
For most languages, this will return the same as ...".
I think it's valid for Turkish, it doesn't differ it's configured as en or tr.
In Turkish it should convert "DINÇ" to "dinç" and "DINÇ" to "dinç" or vice-versa.
The original idea comes from groovy. It was proposed for Java 7 as part of Project Coin: https://wiki.openjdk.java.net/display/Coin/2009+Proposals+TOC (Elvis and Other Null-Safe Operators), but hasn't been accepted yet.
The related Elvis operator ?: was proposed to make x ?: y
shorthand for x != null ? x : y
, especially useful when x is a complex expression.
I believe it depends on what json interpreter you're using... in plain javascript you could use line terminators
{
"testCases" :
{
"case.1" :
{
"scenario" : "this the case 1.",
"result" : "this is a very long line which is not easily readble. \
so i would like to write it in multiple lines. \
but, i do NOT require any new lines in the output."
}
}
}
You should use CSS to align the textbox. The reason your code above does not work is because by default a div's width is the same as the container it's in, therefore in your example it is pushed below.
The following would work.
<td colspan="2" class="cell">
<asp:Label ID="Label6" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server" CssClass="righttextbox"></asp:TextBox>
</td>
In your CSS file:
.cell
{
text-align:left;
}
.righttextbox
{
float:right;
}
If you're using Bash or zsh, use this:
type -a lshw
This will show whether the target is a builtin, a function, an alias or an external executable. If the latter, it will show each place it appears in your PATH
.
bash$ type -a lshw
lshw is /usr/bin/lshw
bash$ type -a ls
ls is aliased to `ls --color=auto'
ls is /bin/ls
bash$ zsh
zsh% type -a which
which is a shell builtin
which is /usr/bin/which
In Bash, for functions type -a
will also display the function definition. You can use declare -f functionname
to do the same thing (you have to use that for zsh, since type -a
doesn't).
Check for correct IP address in the cassandra.yaml file. Majority of times the error is due to incorrect IP address of your system also the username and password too.
After doing so initiate cqlsh by the command :-
cqlsh 10.31.79.1 -u cassandra -p cassandra
I'd like to contribute to this question by pointing out that the recommended way to share data between controllers, and even directives, is by using services (factories) as it has been already pointed out, but also I'd like to provide a working practical example of how to that should be done.
Here is the working plunker: http://plnkr.co/edit/Q1VdKJP2tpvqqJL1LF6m?p=info
First, create your service, that will have your shared data:
app.factory('SharedService', function() {
return {
sharedObject: {
value: '',
value2: ''
}
};
});
Then, simply inject it on your controllers and grab the shared data on your scope:
app.controller('FirstCtrl', function($scope, SharedService) {
$scope.model = SharedService.sharedObject;
});
app.controller('SecondCtrl', function($scope, SharedService) {
$scope.model = SharedService.sharedObject;
});
app.controller('MainCtrl', function($scope, SharedService) {
$scope.model = SharedService.sharedObject;
});
You can also do that for your directives, it works the same way:
app.directive('myDirective',['SharedService', function(SharedService){
return{
restrict: 'E',
link: function(scope){
scope.model = SharedService.sharedObject;
},
template: '<div><input type="text" ng-model="model.value"/></div>'
}
}]);
Hope this practical and clean answer can be helpful to someone.
you definitively want a List:
The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based.
Also
Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a > list is typically preferable to indexing through it if the caller does not know the implementation.
If you need the index in order to modify your collection you should note that List provides a special ListIterator that allow you to get the index:
List<String> names = Arrays.asList("Davide", "Francesco", "Angelocola");
ListIterator<String> i = names.listIterator();
while (i.hasNext()) {
System.out.format("[%d] %s\n", i.nextIndex(), i.next());
}
The report from SSLabs says:
This server's certificate chain is incomplete. Grade capped to B.
....
Chain Issues Incomplete
Desktop browsers often have chain certificates cached from previous connections or download them from the URL specified in the certificate. Mobile browsers and other applications usually don't.
Fix your chain by including the missing certificates and everything should be right.
First you store your text file in to raw folder.
private void loadWords() throws IOException {
Log.d(TAG, "Loading words...");
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 2)
continue;
long id = addWord(strings[0].trim(), strings[1].trim());
if (id < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
Log.d(TAG, "DONE loading words.");
}
This error will also appear if you omit the semicolon after the fbAsyncInit definition.
window.fbAsyncInit = function() {
FB.init({
appId: 'YOUR APP ID',
status: true,
cookie: true,
xfbml: true
});
//do stuff
}; //<-- semicolon required!
Without the semicolon, the situation is the same as in this shorter example:
var x = function () {
console.log('This is never called. Or is it?');
}
('bar');
The function gets called, because without the semicolon the ('bar') part is seen as a call to the function just defined.
you need a return statement in your first function.
function first(){
var nameContent = document.getElementById('full_name').value;
return nameContent;
}
and then in your second function can be:
function second(){
alert(first());
}
I was wondering, if there is any difference between RemoveAll
and Except
and the pros of using HashSet
, so I have done quick performance check :)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace ListRemoveTest
{
class Program
{
private static Random random = new Random( (int)DateTime.Now.Ticks );
static void Main( string[] args )
{
Console.WriteLine( "Be patient, generating data..." );
List<string> list = new List<string>();
List<string> toRemove = new List<string>();
for( int x=0; x < 1000000; x++ )
{
string randString = RandomString( random.Next( 100 ) );
list.Add( randString );
if( random.Next( 1000 ) == 0 )
toRemove.Insert( 0, randString );
}
List<string> l1 = new List<string>( list );
List<string> l2 = new List<string>( list );
List<string> l3 = new List<string>( list );
List<string> l4 = new List<string>( list );
Console.WriteLine( "Be patient, testing..." );
Stopwatch sw1 = Stopwatch.StartNew();
l1.RemoveAll( toRemove.Contains );
sw1.Stop();
Stopwatch sw2 = Stopwatch.StartNew();
l2.RemoveAll( new HashSet<string>( toRemove ).Contains );
sw2.Stop();
Stopwatch sw3 = Stopwatch.StartNew();
l3 = l3.Except( toRemove ).ToList();
sw3.Stop();
Stopwatch sw4 = Stopwatch.StartNew();
l4 = l4.Except( new HashSet<string>( toRemove ) ).ToList();
sw3.Stop();
Console.WriteLine( "L1.Len = {0}, Time taken: {1}ms", l1.Count, sw1.Elapsed.TotalMilliseconds );
Console.WriteLine( "L2.Len = {0}, Time taken: {1}ms", l1.Count, sw2.Elapsed.TotalMilliseconds );
Console.WriteLine( "L3.Len = {0}, Time taken: {1}ms", l1.Count, sw3.Elapsed.TotalMilliseconds );
Console.WriteLine( "L4.Len = {0}, Time taken: {1}ms", l1.Count, sw3.Elapsed.TotalMilliseconds );
Console.ReadKey();
}
private static string RandomString( int size )
{
StringBuilder builder = new StringBuilder();
char ch;
for( int i = 0; i < size; i++ )
{
ch = Convert.ToChar( Convert.ToInt32( Math.Floor( 26 * random.NextDouble() + 65 ) ) );
builder.Append( ch );
}
return builder.ToString();
}
}
}
Results below:
Be patient, generating data...
Be patient, testing...
L1.Len = 985263, Time taken: 13411.8648ms
L2.Len = 985263, Time taken: 76.4042ms
L3.Len = 985263, Time taken: 340.6933ms
L4.Len = 985263, Time taken: 340.6933ms
As we can see, best option in that case is to use RemoveAll(HashSet)
For environment variable in Maven, you can set below.
http://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html#environmentVariables http://maven.apache.org/surefire/maven-failsafe-plugin/integration-test-mojo.html#environmentVariables
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
...
<configuration>
<includes>
...
</includes>
<environmentVariables>
<WSNSHELL_HOME>conf</WSNSHELL_HOME>
</environmentVariables>
</configuration>
</plugin>
Just make sure put single space before and after "and" Keyword..
The top voted answer, while effective, is not what I would consider to be the angular way, nor is it using bootstrap's own classes that are meant to deal with this situation. As @claies mentioned, the .clearfix
class is meant for situations such as these. In my opinion, the cleanest implementation is as follows:
<div class="row">
<div ng-repeat="product in products">
<div class="clearfix" ng-if="$index % 3 == 0"></div>
<div class="col-sm-4">
<h2>{{product.title}}</h2>
</div>
</div>
</div>
This structure avoids messy indexing of the products array, allows for clean dot notation, and makes use of the clearfix class for its intended purpose.
From Evans DDD:
An AGGREGATE is a cluster of associated objects that we treat as a unit for the purpose of data changes. Each AGGREGATE has a root and a boundary. The boundary defines what is inside the AGGREGATE. The root is a single, specific ENTITY contained in the AGGREGATE.
And:
The root is the only member of the AGGREGATE that outside objects are allowed to hold references to[.]
This means that aggregate roots are the only objects that can be loaded from a repository.
An example is a model containing a Customer
entity and an Address
entity. We would never access an Address
entity directly from the model as it does not make sense without the context of an associated Customer
. So we could say that Customer
and Address
together form an aggregate and that Customer
is an aggregate root.
From a Spring point of view, none of the HttpMessageConverter
instances registered with the RestTemplate
can convert text/html
content to a ProductList
object. The method of interest is HttpMessageConverter#canRead(Class, MediaType)
. The implementation for all of the above returns false
, including Jaxb2RootElementHttpMessageConverter
.
Since no HttpMessageConverter
can read your HTTP response, processing fails with an exception.
If you can control the server response, modify it to set the Content-type
to application/xml
, text/xml
, or something matching application/*+xml
.
If you don't control the server response, you'll need to write and register your own HttpMessageConverter
(which can extend the Spring classes, see AbstractXmlHttpMessageConverter
and its sub classes) that can read and convert text/html
.
Always use new in C++. If you need a block of untyped memory, you can use operator new directly:
void *p = operator new(size);
...
operator delete(p);
SELECT CONVERT(DATE,DATEADD(MM, DATEDIFF(MM, 0, GETDATE())-1, 0)) AS FirstDayOfPrevMonth
SELECT CONVERT(DATE,DATEADD(MS, -3, DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) , 0))) AS LastDayOfPrevMonth
You should not map score to player. You should map player (or his name) to score:
Map<Player, Integer> player2score = new HashMap<Player, Integer>();
Then add players to map: int score = .... Player player = new Player(); player.setName("John"); // etc. player2score.put(player, score);
In this case the task is trivial:
int score = player2score.get(player);
Use the Find method if item_manuf_id
is a primary key:
var result = dtPs.Rows.Find("some value");
If you only want to know if the value is in there then use the Contains method.
if (dtPs.Rows.Contains("some value"))
{
...
}
Primary key restriction applies to Contains
aswell.
try this
<?php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
getActivity()- Return the Activity this fragment is currently associated with.
First of all, you would have to allocate memory:
char * S = new char[R.length() + 1];
then you can use strcpy
with S
and R.c_str()
:
std::strcpy(S,R.c_str());
You can also use R.c_str()
if the string doesn't get changed or the c string is only used once. However, if S
is going to be modified, you should copy the string, as writing to R.c_str()
results in undefined behavior.
Note: Instead of strcpy
you can also use str::copy
.
This works for me and you don't need the inline script:
Javascript:
$(document).ready(function() {
$('.showme').bind('click', function() {
var id=$(this).attr("id");
var num=$(this).attr("class");
var poststr="request="+num+"&moreinfo="+id;
$.ajax({
url:"testme.php",
cache:0,
data:poststr,
success:function(result){
document.getElementById("stuff").innerHTML=result;
}
});
});
});
HTML:
<div class='request_1 showme' id='rating_1'>More stuff 1</div>
<div class='request_2 showme' id='rating_2'>More stuff 2</div>
<div class='request_3 showme' id='rating_3'>More stuff 3</div>
<div id="stuff">Here is some stuff that will update when the links above are clicked</div>
The request is sent to testme.php:
header("Cache-Control: no-cache");
header("Pragma: nocache");
$request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']);
$request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']);
if($request_id=="1")
{
echo "show 1";
}
elseif($request_id=="2")
{
echo "show 2";
}
else
{
echo "show 3";
}
<script type="text/javascript">
$(document).ready(function () {
$('.selecctall').click(function (event) {
if (this.checked) {
$('.checkbox1').each(function () {
this.checked = true;
});
} else {
$('.checkbox1').each(function () {
this.checked = false;
});
}
});
});
</script>
There are commercial products such as ionCube (which I use), source guardian, and Zen Guard.
There are also postings on the net which claim they can reverse engineer the encoded programs. How reliable they are is questionable, since I have never used them.
Note that most of these solutions require an encoder to be installed on their servers. So you may want to make sure your client is comfortable with that.
Java is only pass-by-value. (or better - pass-reference-by-value)
So the passed argument and the argument within the method are two different handlers pointing to the same object (value).
Therefore if you change the state of the object, it is reflected to every other variable that's referencing it. But if you re-assign a new object (value) to the argument, then other variables pointing to this object (value) do not get re-assigned.
I have created a working CodePen example to demonstrate how you might accomplish your goals.
I added ng-click
to the <form>
and removed the logic from your button:
<form name="addRelation" data-ng-click="save(model)">
...
<input class="btn" type="submit" value="SAVE" />
Here's the updated template:
<section ng-app="app" ng-controller="MainCtrl">
<form class="well" name="addRelation" data-ng-click="save(model)">
<label>First Name</label>
<input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
<label>Last Name</label>
<input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
<label>Email</label>
<input type="email" placeholder="Email" data-ng-model="model.email" id="Email" name="Email" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.email">Email address is not valid</span><br/>
<input class="btn" type="submit" value="SAVE" />
</form>
</section>
and controller code:
app.controller('MainCtrl', function($scope) {
$scope.save = function(model) {
$scope.addRelation.submitted = true;
if($scope.addRelation.$valid) {
// submit to db
console.log(model);
} else {
console.log('Errors in form data');
}
};
});
I hope this helps.
I think this would be good as well it gets any color available
$color= substr(str_shuffle('AABBCCDDEEFF00112233445566778899AABBCCDDEEFF00112233445566778899AABBCCDDEEFF00112233445566778899'), 0, 6);
In Xamarin, all above solution does not work for me. This is what I use instead:
public static bool IsRemoteNotificationsEnabled() {
return UIApplication.SharedApplication.CurrentUserNotificationSettings.Types != UIUserNotificationType.None;
}
It's getting a live update also after you've changed the notification status in Settings.
you can do it simply with PHP opendir
function.
example:
$handle = opendir(dirname(realpath(__FILE__)).'/pictures/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="pictures/'.$file.'" border="0" />';
}
}
Given the string foobarbarfoo
:
bar(?=bar) finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar) finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar finds the 2nd bar ("bar" which does not have "foo" before it)
You can also combine them:
(?<=foo)bar(?=bar) finds the 1st bar ("bar" with "foo" before it and "bar" after it)
(?=)
Find expression A where expression B follows:
A(?=B)
(?!)
Find expression A where expression B does not follow:
A(?!B)
(?<=)
Find expression A where expression B precedes:
(?<=B)A
(?<!)
Find expression A where expression B does not precede:
(?<!B)A
(?>)
An atomic group exits a group and throws away alternative patterns after the first matched pattern inside the group (backtracking is disabled).
(?>foo|foot)s
applied to foots
will match its 1st alternative foo
, then fail as s
does not immediately follow, and stop as backtracking is disabledA non-atomic group will allow backtracking; if subsequent matching ahead fails, it will backtrack and use alternative patterns until a match for the entire expression is found or all possibilities are exhausted.
(foo|foot)s
applied to foots
will:
foo
, then fail as s
does not immediately follow in foots
, and backtrack to its 2nd alternative;foot
, then succeed as s
immediately follows in foots
, and stop.Here's what I've done:
.resize {
width: 400px;
height: auto;
}
.resize {
width: 300px;
height: auto;
}
<img class="resize" src="example.jpg"/>
This will keep the image aspect ratio the same.
To merge the sets in the array Sets, you can do
var Sets = [set1, set2, set3];
var merged = new Set([].concat(...Sets.map(set => Array.from(set))));
It is slightly mysterious to me why the following, which should be equivalent, fails at least in Babel:
var merged = new Set([].concat(...Sets.map(Array.from)));
if you are using VirtualBox and UBUNTU in it or you are simply using UBUNTU then it can be useful
wget https://github.com/andrewvc/ee-datasets/archive/master.zip
sudo apt-get install unzip (only if unzip module is not installed)
unzip master.zip
cd ee-datasets
java -jar elastic-loader.jar http://localhost:9200 datasets/movie_db.eloader
Here's my solution to the no default constructor dilemma. I know this is a late solution, but I think it's worth noting this is a solution.
public struct Point2D {
public static Point2D NULL = new Point2D(-1,-1);
private int[] Data;
public int X {
get {
return this.Data[ 0 ];
}
set {
try {
this.Data[ 0 ] = value;
} catch( Exception ) {
this.Data = new int[ 2 ];
} finally {
this.Data[ 0 ] = value;
}
}
}
public int Z {
get {
return this.Data[ 1 ];
}
set {
try {
this.Data[ 1 ] = value;
} catch( Exception ) {
this.Data = new int[ 2 ];
} finally {
this.Data[ 1 ] = value;
}
}
}
public Point2D( int x , int z ) {
this.Data = new int[ 2 ] { x , z };
}
public static Point2D operator +( Point2D A , Point2D B ) {
return new Point2D( A.X + B.X , A.Z + B.Z );
}
public static Point2D operator -( Point2D A , Point2D B ) {
return new Point2D( A.X - B.X , A.Z - B.Z );
}
public static Point2D operator *( Point2D A , int B ) {
return new Point2D( B * A.X , B * A.Z );
}
public static Point2D operator *( int A , Point2D B ) {
return new Point2D( A * B.Z , A * B.Z );
}
public override string ToString() {
return string.Format( "({0},{1})" , this.X , this.Z );
}
}
ignoring the fact I have a static struct called null, (Note: This is for all positive quadrant only), using get;set; in C#, you can have a try/catch/finally, for dealing with the errors where a particular data type is not initialized by the default constructor Point2D(). I guess this is elusive as a solution to some people on this answer. Thats mostly why i'm adding mine. Using the getter and setter functionality in C# will allow you to bypass this default constructor non-sense and put a try catch around what you dont have initialized. For me this works fine, for someone else you might want to add some if statements. So, In the case where you would want a Numerator/Denominator setup, this code might help. I'd just like to reiterate that this solution does not look nice, probably works even worse from an efficiency standpoint, but, for someone coming from an older version of C#, using array data types gives you this functionality. If you just want something that works, try this:
public struct Rational {
private long[] Data;
public long Numerator {
get {
try {
return this.Data[ 0 ];
} catch( Exception ) {
this.Data = new long[ 2 ] { 0 , 1 };
return this.Data[ 0 ];
}
}
set {
try {
this.Data[ 0 ] = value;
} catch( Exception ) {
this.Data = new long[ 2 ] { 0 , 1 };
this.Data[ 0 ] = value;
}
}
}
public long Denominator {
get {
try {
return this.Data[ 1 ];
} catch( Exception ) {
this.Data = new long[ 2 ] { 0 , 1 };
return this.Data[ 1 ];
}
}
set {
try {
this.Data[ 1 ] = value;
} catch( Exception ) {
this.Data = new long[ 2 ] { 0 , 1 };
this.Data[ 1 ] = value;
}
}
}
public Rational( long num , long denom ) {
this.Data = new long[ 2 ] { num , denom };
/* Todo: Find GCD etc. */
}
public Rational( long num ) {
this.Data = new long[ 2 ] { num , 1 };
this.Numerator = num;
this.Denominator = 1;
}
}
This website contains a much cleaner solution, it leaves pip intact as-well and one can easily switch between 3.5 and 3.6 and then whenever 3.7 is released.
http://ubuntuhandbook.org/index.php/2017/07/install-python-3-6-1-in-ubuntu-16-04-lts/
A short summary:
sudo apt-get install python python-pip python3 python3-pip
sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 2
Then
$ pip -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)
$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)
Then to select python 3.6 run
sudo update-alternatives --config python3
and select '2'. Then
$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)
To update pip select the desired version and
pip3 install --upgrade pip
$ pip3 -V
pip 9.0.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)
Tested on Ubuntu 16.04.
Additional to the above - the QEMU website has good documentation about setting up an ARM based emulator: http://qemu.weilnetz.de/qemu-doc.html#ARM-System-emulator
Assuming that your docker container is up and running, you can run commands as:
docker exec mycontainer /bin/sh -c "cmd1;cmd2;...;cmdn"
To add a rounded border in any button the best way is to add the border-radius
property. I belive this class is better because you can add-it at any button size. If you set the height and widht you will need to create a "rouding" class to each button size.
.btn-circle {_x000D_
border-radius: 50%;_x000D_
}
_x000D_
<button class='btn-circle'>Click Me!</button>_x000D_
<button class='btn-circle'>?</button>
_x000D_
If you want to use Arrays, it's pretty simple.
logs = gson.fromJson(br, JsonLog[].class); // line 6
Provide the JsonLog
as an array JsonLog[].class
I don't think it can. When a service is "stopped", it gets totally unloaded.
Well, OK, there's always a way I suppose. For instance, you could create a detached process to stop the service, then restart it, then exit.
var data = $('<div>').html('[{"Id":1,"Name":"Name}]')[0].textContent;
that should parse all the encoded values you need.
As far as I can tell, you don't necessarily need to specify the axis when using the filter function.
new = old.filter(['A','B','D'])
returns the same dataframe as
new = old.filter(['A','B','D'], axis=1)
Use vector array instead:
vector<vector<int>> array(ROW, vector<int>(COLUMN, 1));
Using NetBeans 7.0:
If you fix imports before R.java has been generated for your project (before building it the first time) it will add the line:
import android.R;
which will override the local R.java that you are trying to reference.
Deleting that line resolved the errors for me.
You can connect two iPhones and transfer data via Bluetooth using either the high-level GameKit framework or the lower-level (but still easy to work with) Bonjour discovery mechanisms. Bonjour also works transparently between Bluetooth and WiFi on the iPhone under 3.0, so it's a good choice if you would like to support iPhone-to-iPhone data transfers on those two types of networks.
For more information, you can also look at the responses to these questions:
Using [a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}
for [email protected]
/ [email protected]
In my case, files were exactly the same (content, line endings, filemodes, md5 checksum, everything), yet were still visible in git status
.
What helped was
# Garbage collect stuffs from .git
git gc
# commit stuff
git add .
git commit -m "temporary"
# this doesn't change contents
git reset HEAD^1 --soft
After that, git status
showed only one editted file that I editted.
it works, all you need:
PHP:
header('Access-Control-Allow-Origin: http://www.example.com');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
JS (jQuery ajax):
var getWBody = $.ajax({ cache: false,
url: URL,
dataType : 'json',
type: 'GET',
xhrFields: { withCredentials: true }
});
Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.
ASPX
<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
<ItemTemplate>
<div id="width:50%;height:30px;background:#0f0a0f;">
<asp:Label ID="lblSr" runat="server"
style="width:30%;float:left;text-align:right;text-indent:-2px;" />
<span
style="width:65%;float:right;text-align:left;text-indent:-2px;" >
<%# Eval("Item") %>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
Code Behind:
protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
{
Label l = e.Item.FindControl("lblSr") as Label;
if (l != null)
l.Text = e.Item.ItemIndex + 1+"";
}
That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.
The HTML in your example will be:
<tr>
<td>TEST</td>
</tr>
Read the PHP documentation that explains it.
I'm running Ubuntu 14.04; and apt still couldn't find package; I tried all the answers above and more. The URL that worked for me is this:
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
Source: http://www.liquidweb.com/kb/how-to-install-mongodb-on-ubuntu-14-04/
This should work for you. Infact the one which you are thinking will also work:-
.......
DECLARE @returnvalue INT
EXEC @returnvalue = SP_One
.....
There is no interactive solution in Excel because some functions are not vector-friendly, like CELL, above quoted. For example, it's possible counting all the numbers whose absolute value is less than 3, because ABS is accepted inside a formula array.
So I've used the following array formula (Ctrl+Shift+Enter after edit with no curly brackets)
={SUM(IF(ABS(F1:F15)<3,1,0))}
If Column F has
F
1 ... 2
2 .... 4
3 .... -2
4 .... 1
5 ..... 5
It counts 3! (-2,2 and 1). In order to show how ABS is array-friendly function let's do a simple test: Select G1:G5, digit =ABS(F1:F5) in the formula bar and press Ctrl+Shift+Enter. It's like someone write Abs(F1:F5)(1), Abs(F1:F5)(2), etc.
F G
1 ... 2 =ABS(F1:F5) => 2
2 .... 4 =ABS(F1:F5) => 4
3 .... -2 =ABS(F1:F5) => 2
4 .... 1 =ABS(F1:F5) => 1
5 ..... 5 =ABS(F1:F5) => 5
Now I put some mixed data, including 2 date values.
F
1 ... Fab-25-2012
2 .... 4
3 .... May-5-2013
4 .... Ball
5 ..... 5
In this case, CELL fails and return 1
={SUM(IF(CELL("format",F1:F15)="D4",1,0))}
It happens because CELL return the format of first cell of the range. (D4 is a m-d-y format)
So the only thing left is programming! A UDF(User defined Function) for formula array must return a variant array:
Function TypeCell(R As Range) As Variant
Dim V() As Variant
Dim Cel As Range
Dim I As Integer
Application.Volatile '// For revaluation in interactive environment
ReDim V(R.Cells.Count - 1) As Variant
I = 0
For Each Cel In R
V(I) = VarType(Cel) '// Output array has the same size of input range.
I = I + 1
Next Cel
TypeCell = V
End Function
Now is easy (the constant VbDate is 7):
=SUM(IF(TypeCell(F1:F5)=7,1,0))
It shows 2. That technique can be used for any shape of cells. I've tested vertical, horizontal and rectangular shapes, since you fill using for each order inside the function.
You can use the magic constants __METHOD__
(includes the class name) or __FUNCTION__
(just function name) depending on if it's a method or a function... =)
This will get ALL parameters from the request. For Debugging purposes only:
@RequestMapping (value = "/promote", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView renderPromotePage (HttpServletRequest request) {
Map<String, String[]> parameters = request.getParameterMap();
for(String key : parameters.keySet()) {
System.out.println(key);
String[] vals = parameters.get(key);
for(String val : vals)
System.out.println(" -> " + val);
}
ModelAndView mv = new ModelAndView();
mv.setViewName("test");
return mv;
}
Following command resolved my issue:
sudo chown -R _mysql:mysql /usr/local/var/mysql
sudo mysql.server start