I think, the difference is in usage patterns.
I would prefer .on
over .click
because the former can use less memory and work for dynamically added elements.
Consider the following html:
<html>
<button id="add">Add new</button>
<div id="container">
<button class="alert">alert!</button>
</div>
</html>
where we add new buttons via
$("button#add").click(function() {
var html = "<button class='alert'>Alert!</button>";
$("button.alert:last").parent().append(html);
});
and want "Alert!" to show an alert. We can use either "click" or "on" for that.
click
$("button.alert").click(function() {
alert(1);
});
with the above, a separate handler gets created for every single element that matches the selector. That means
.on
$("div#container").on('click', 'button.alert', function() {
alert(1);
});
with the above, a single handler for all elements that match your selector, including the ones created dynamically.
.on
As Adrien commented below, another reason to use .on
is namespaced events.
If you add a handler with .on("click", handler)
you normally remove it with .off("click", handler)
which will remove that very handler. Obviously this works only if you have a reference to the function, so what if you don't ? You use namespaces:
$("#element").on("click.someNamespace", function() { console.log("anonymous!"); });
with unbinding via
$("#element").off("click.someNamespace");
First i tried with this sample code:
$(document).ready(function(){
$('#upload-file').click();
});
It didn't work for me. Then after, tried with this
$(document).ready(function(){
$('#upload-file')[0].click();
});
No change. At last, tried with this
$(document).ready(function(){
$('#upload-file')[0].click(function(){
});
});
Solved my problem. Helpful for anyone.
Very simple method:
.create:before {
content: url(image.png);
}
Works in all modern browsers and IE8+.
Edit
Don't use this on large sites though. The :before pseudo-element is horrible in terms of performance.
There is no way (or at least no reasonably easy and convenient way) to get the raw traffic data from Google Maps Javascript API v3. Even if you could do it, doing so is likely to violate some clause in the Terms Of Service for Google Maps. You would have to get this information from another service. I doubt there is a free service that provides this information at the current time, but I would love it if someone proved me wrong on that.
As @crdzoba points out, Bing Maps API exposes some traffic data. Perhaps that can fill your needs. It's not clear from the documentation how much traffic data that exposes as it's only data about "incidents". Slow traffic due to construction would be in there, but it's not obvious to me whether slow traffic due simply to volume would be.
UPDATE (March 2016): A lot has happened since this answer was written in 2011, but the core points appear to hold up: You won't find raw traffic data in free API services (at least not for the U.S., and probably not most other places). But if you don't mind paying a bit and/or if you just need things like "travel time for a specific route taking traffic into consideration" you have options. @Anto's answer, for example, points to Google's Maps For Work as a paid API service that allows you to get travel times taking traffic into consideration.
This worked for me
$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");
echo "Enter no of terms"
read count
for i in $(seq 1 $count)
do
t=` expr $i - 1 `
for j in $(seq $t -1 0)
do
echo -n " "
done
j=` expr $count + 1 `
x=` expr $j - $i `
for k in $(seq 1 $x)
do
echo -n "* "
done
echo ""
done
If you really want the New Line string as a constant, then you can do this:
public readonly string myVar = Environment.NewLine;
The user of the readonly keyword in C# means that this variable can only be assigned to once. You can find the documentation on it here. It allows the declaration of a constant variable whose value isn't known until execution time.
<a href="javascript:;" onClick="if(confirm('Are you sure you want to delete this product')){del_product(id);}else{ }" class="btn btn-xs btn-danger btn-delete" title="Del Product">Delete Product</a>
<!-- language: lang-js -->
<script>
function del_product(id){
$('.process').css('display','block');
$('.process').html('<img src="./images/loading.gif">');
$.ajax({
'url':'./process.php?action=del_product&id='+id,
'type':"post",
success: function(result){
info=JSON.parse(result);
if(result.status==1){
setTimeout(function(){
$('.process').hide();
$('.tr_'+id).hide();
},3000);
setTimeout(function(){
$('.process').html(result.notice);
},1000);
} else if(result.status==0){
setTimeout(function(){
$('.process').hide();
},3000);
setTimeout(function(){
$('.process').html(result.notice);
},1000);
}
}
});
}
</script>
You are applying the formatting to the workbook that has the code, not the added workbook. You'll want to get in the habit of fully qualifying sheet and range references. The code below does that and works for me in Excel 2010:
Sub test()
Dim wb As Excel.Workbook
Set wb = Workbooks.Add
With wb.Sheets(1)
.Range("A1") = "Acctdate"
.Range("B1") = "Ledger"
.Range("C1") = "CY"
.Range("D1") = "BusinessUnit"
.Range("E1") = "OperatingUnit"
.Range("F1") = "LOB"
.Range("G1") = "Account"
.Range("H1") = "TreatyCode"
.Range("I1") = "Amount"
.Range("J1") = "TransactionCurrency"
.Range("K1") = "USDEquivalentAmount"
.Range("L1") = "KeyCol"
.Range("A2", "A50000").Value = Me.TextBox3.Value
.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
End With
End Sub
You likely have Hyper-V enabled. The manual installer provides this detailed notice when it refuses to install on a Windows with it on.
This computer does not support Intel Virtualization Technology (VT-x) or it is being exclusively used by Hyper-V. HAXM cannot be installed. Please ensure Hyper-V is disabled in Windows Features, or refer to the Intel HAXM documentation for more information.
Try using printf
function or the concatination operator
You will find it by reading the couple of pages of Muthukrishnan - Data Stream Algorithms: Puzzle 1: Finding Missing Numbers. It shows exactly the generalization you are looking for. Probably this is what your interviewer read and why he posed these questions.
Now, if only people would start deleting the answers that are subsumed or superseded by Muthukrishnan's treatment, and make this text easier to find. :)
Also see sdcvvc's directly related answer, which also includes pseudocode (hurray! no need to read those tricky math formulations :)) (thanks, great work!).
For me, the table name and the synonym both existed but under different owner names. I re-created the tables under the owner name that matched the owner name in synonyms.
I used the queries posted by @Mahi_0707
You asked if it is possible to change the circular dependency checking in those slf4j classes.
The simple answer is no.
static
initializer block ... so you can't override the implementation, and you can't stop it happening.So the only way to change this would be to download the source code, modify the core classes to "fix" them, build and use them. That is probably a bad idea (in general) and probably not solution in this case; i.e. you risk triggering the stack overflow problem that the message warns about.
Reference:
The real solution (as you identified in your Answer) is to use the right JARs. My understanding is that the circularity that was detected is real and potentially problematic ... and unnecessary.
Try starting IntelliJ from terminal. You can find application file under: /Applications/IntelliJ\ IDEA\ 14.app/Contents/MacOS
ES6 solution with reduce (fixed):
const arr = [2, 2, 2, 3, 2]_x000D_
_x000D_
const count = arr.reduce((pre, cur) => (cur === 2) ? ++pre : pre, 0)_x000D_
console.log(count) // 4
_x000D_
If server if down, on python 2.7 x86 windows urllib have no timeout and program go to dead lock. So use urllib2
import urllib2
import socket
def check_url( url, timeout=5 ):
try:
return urllib2.urlopen(url,timeout=timeout).getcode() == 200
except urllib2.URLError as e:
return False
except socket.timeout as e:
print False
print check_url("http://google.fr") #True
print check_url("http://notexist.kc") #False
Use -regex
:
From the man page:
-regex pattern
File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named './fubar3', you can use the
regular expression '.*bar.' or '.*b.*3', but not 'b.*r3'.
Also, I don't believe find
supports regex extensions such as \d
. You need to use [0-9]
.
find . -regex '.*test\.log\.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\.zip'
All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.
This is the code fully tested and working for me. You can use it just copy and paste in your aspx page and cs page.
This is my blog you can download full code here. thanks.
<form id="form1" runat="server">_x000D_
<div style="font-size: 30px; padding: 25px; text-align: center;">_x000D_
Get Current Date And Time Of All TimeZones_x000D_
</div>_x000D_
<hr />_x000D_
<div style="font-size: 18px; padding: 25px; text-align: center;">_x000D_
<div class="clsLeft">_x000D_
Select TimeZone :-_x000D_
</div>_x000D_
<div class="clsRight">_x000D_
<asp:DropDownList ID="ddlTimeZone" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlTimeZone_SelectedIndexChanged"_x000D_
Font-Size="18px">_x000D_
</asp:DropDownList>_x000D_
</div>_x000D_
<div class="clearspace">_x000D_
</div>_x000D_
<div class="clsLeft">_x000D_
Selected TimeZone :-_x000D_
</div>_x000D_
<div class="clsRight">_x000D_
<asp:Label ID="lblTimeZone" runat="server" Text="" />_x000D_
</div>_x000D_
<div class="clearspace">_x000D_
</div>_x000D_
<div class="clsLeft">_x000D_
Current Date And Time :-_x000D_
</div>_x000D_
<div class="clsRight">_x000D_
<asp:Label ID="lblCurrentDateTime" runat="server" Text="" />_x000D_
</div>_x000D_
</div>_x000D_
<p>_x000D_
</p>_x000D_
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />_x000D_
</form>
_x000D_
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindTimeZone();
GetSelectedTimeZone();
}
}
protected void ddlTimeZone_SelectedIndexChanged(object sender, EventArgs e)
{
GetSelectedTimeZone();
}
/// <summary>
/// Get all timezone from local system and bind it in dropdownlist
/// </summary>
private void BindTimeZone()
{
foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
{
ddlTimeZone.Items.Add(new ListItem(z.DisplayName, z.Id));
}
}
/// <summary>
/// Get selected timezone and current date & time
/// </summary>
private void GetSelectedTimeZone()
{
DateTimeOffset newTime = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(ddlTimeZone.SelectedValue));
//DateTimeOffset newTime2 = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(ddlTimeZone.SelectedValue));
lblTimeZone.Text = ddlTimeZone.SelectedItem.Text;
lblCurrentDateTime.Text = newTime.ToString();
string str;
str = lblCurrentDateTime.Text;
string s=str.Substring(0, 10);
DateTime dt = new DateTime();
dt = Convert.ToDateTime(s);
// Response.Write(dt.ToString());
Response.Write(ddlTimeZone.SelectedValue);
}
+1 for everyone who's recommended the RedGate tools, with an additional recommendation and a caveat.
SqlCompare also has a decently documented API: so you can, for instance, write a console app which syncs your source controlled scripts folder with a CI integration testing database on checkin, so that when someone checks in a change to the schema from their scripts folder it's automatically deployed along with the matching application code change. This helps close the gap with developers who are forgetful about propagating changes in their local db up to a shared development DB (about half of us, I think :) ).
A caveat is that with a scripted solution or otherwise, the RedGate tools are sufficiently smooth that it's easy to forget about SQL realities underlying the abstraction. If you rename all the columns in a table, SqlCompare has no way to map the old columns to the new columns and will drop all the data in the table. It will generate warnings but I've seen people click past that. There's a general point here worth making, I think, that you can only automate DB versioning and upgrade so far - the abstractions are very leaky.
Option 1: Go to Android SDK Folder --> Extra --> Intel and double click on HAXM installer and install it manually.
Option 2: If you do not have latest version of HAXM then you can open sdk manager in android studio and download it.
Option 3: Download HAXM intaller from Intel site. https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager
Plenty of good ideas on this thread. I have a lot of popups in my page for handling user input. What I use, is a combination of disabling the mousewheel and hiding the scrollbar:
this.disableScrollFn= function(e) {
e.preventDefault(); e.stopPropagation()
};
document.body.style.overflow = 'hidden';
$('body').on('mousewheel', this.disableScrollFn);
Advantage of this is we stop the user from scrolling in any possible way, and without having to change css position and top properties. I'm not concerened about touch events, since touch outside would close the popup.
To disable this, upon closing the popup I do the following.
document.body.style.overflow = 'auto';
$('body').off('mousewheel', this.disableScrollFn);
Note, I store a reference to my disableScrollFn on the existing object (in my case a PopupViewModel), for that gets triggered upon closing the popup to have access to disableScrollFn.
The function I use currently:
/**
* Serializes form or any other element with jQuery.serialize
* @param el
*/
serialize: function(el) {
var serialized = $(el).serialize();
if (!serialized) // not a form
serialized = $(el).
find('input[name],select[name],textarea[name]').serialize();
return serialized;
}
The thing you really want to do is wrap all child elements. In this case you should use an items control and not resort to horrible attached properties which you will end up having a million of for every property you wish to style.
<ItemsControl>
<!-- target the wrapper parent of the child with a style -->
<ItemsControl.ItemContainerStyle>
<Style TargetType="Control">
<Setter Property="Margin" Value="0 0 5 0"></Setter>
</Style>
</ItemsControl.ItemContainerStyle>
<!-- use a stack panel as the main container -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!-- put in your children -->
<ItemsControl.Items>
<Label>Auto Zoom Reset?</Label>
<CheckBox x:Name="AutoResetZoom"/>
<Button x:Name="ProceedButton" Click="ProceedButton_OnClick">Next</Button>
<ComboBox SelectedItem="{Binding LogLevel }" ItemsSource="{Binding LogLevels}" />
</ItemsControl.Items>
</ItemsControl>
First, you should understand the pointer is not complex. A pointer is showing the address of the variable.
Example:
int a = 10;
int *p = &a; // This means giving a pointer of variable "a" to int pointer variable "p"
And, you should understand "Pointer is an address" and "address is numerical value". So, you can get the address of variable as Integer.
int a = 10;
unsigned long address = (unsigned long)&a;
// comparison
printf("%p\n", &a);
printf("%ld\n", address);
output is below
0x7fff1216619c
7fff1216619c
Note:
If you use a 64-bit computer, you can't get pointer by the way below.
int a = 10;
unsigned int address = (unsigned int)&a;
Because pointer is 8 bytes (64 bit) on a 64-bit machine, but int is 4 bytes. So, you can't give an 8-byte memory address to 4 bytes variable.
You have to use long long
or long
to get an address of the variable.
long long
is always 8 bytes.long
is 4 bytes when code was compiled for a 32-bit machine.long
is 8 bytes when code was compiled for a 64-bit machine.Therefore, you should use long
to receive a pointer.
Exception: java.lang.IllegalStateException: Fragment
DeadlineListFragment{ad2ef970} not attached to Activity
Category: Lifecycle
Description: When doing time-consuming operation in background thread(e.g, AsyncTask), a new Fragment has been created in the meantime, and was detached to the Activity before the background thread finished. The code in UI thread(e.g.,onPostExecute) calls upon a detached Fragment, throwing such exception.
Fix solution:
Cancel the background thread when pausing or stopping the Fragment
Use isAdded() to check whether the fragment is attached and then to getResources() from activity.
>>> dict.fromkeys(['a','b','c'],[1,2,3])
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
Assuming your products LINQ class uses a similar yield for enumerating/iterating, the first version is more efficient because its only yielding one value each time its iterated over.
The second example is converting the enumerator/iterator to a list with the ToList() method. This means it manually iterates over all the items in the enumerator and then returns a flat list.
The 1. usecase which comes into my mind, is an api
call, which should't go into the render, because it will run for each
state change. And the API call should be only performed on special state change, and not on every render.
changeSearchParams = (params) => {
this.setState({ params }, this.performSearch)
}
performSearch = () => {
API.search(this.state.params, (result) => {
this.setState({ result })
});
}
Hence for any state change, an action can be performed in the render methods body.
Very bad practice, because the render
-method should be pure, it means no actions, state changes, api calls, should be performed, just composite your view and return it. Actions should be performed on some events only. Render is not an event, but componentDidMount
for example.
There is a new official BottomNavigationView in version 25 of the Design Support Library
https://developer.android.com/reference/android/support/design/widget/BottomNavigationView.html
add in gradle
compile 'com.android.support:design:25.0.0'
XML
<android.support.design.widget.BottomNavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:design="http://schema.android.com/apk/res/android.support.design"
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
design:menu="@menu/my_navigation_items" />
Another possible solution is:
const link = document.createElement('a');
link.target = '_blank';
link.href = 'https://www.google.es';
link.setAttribute('visibility', 'hidden');
link.click();
Another Workaround. Much easier in Angular Router V3 Alpha. by injecting Router
import {Router} from "@angular/router";
export class AppComponent{
constructor(private router : Router){}
routeIsActive(routePath: string) {
return this.router.url == routePath;
}
}
usage
<div *ngIf="routeIsActive('/')"> My content </div>
@dynamic is typically used (as has been said above) when a property is being dynamically created at runtime. NSManagedObject does this (why all its properties are dynamic) -- which suppresses some compiler warnings.
For a good overview on how to create properties dynamically (without NSManagedObject and CoreData:, see: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtDynamicResolution.html#//apple_ref/doc/uid/TP40008048-CH102-SW1
exec sp_msforeachtable 'print ''?'''
Simply add "?callback=?" (or "&callback=?") to your url:
$.getJSON({
url:myUrl + "?callback=?",
data: myData,
success: function(data){
/*My function stuff*/
}
});
When doing the calls (with everything else set properly for cross-domain, as above) this will trigger the proper JSONP formatting.
More in-depth explanation can be found in the answer here.
Your file doesn't actually contain UTF-8 encoded data; it contains some other encoding. Figure out what that encoding is and use it in the open
call.
In Windows-1252 encoding, for example, the 0xe9
would be the character é
.
This is exactly what ajax is for. See here:
Basically, you ajax/test.php and put the returned HTML code to the element which has the result id.
$('#result').load('ajax/test.php');
Of course, you will need to put the functionality which takes time to a new php file (or call the old one with a GET parameter which will activate that functionality only).
Multiple things can cause this, I didn't bother to check your entire repository, so I'm going out on a limb here.
First off, you could be missing an annotation (@Service or @Component) from the implementation of com.example.my.services.user.UserService
, if you're using annotations for configuration. If you're using (only) xml, you're probably missing the <bean>
-definition for the UserService-implementation.
If you're using annotations and the implementation is annotated correctly, check that the package where the implementation is located in is scanned (check your <context:component-scan base-package=
-value).
You should be using below
return Observable.throw(error || 'Internal Server error');
Import the throw
operator using the below line
import 'rxjs/add/observable/throw';
Got the same error recently but was able to fixed it by ensuring to close every wcf client call. eg.
WCFServiceClient client = new WCFServiceClient ();
//More codes here
// Always close the client.
client.Close();
or
using(WCFServiceClient client = new WCFServiceClient ())
{
//More codes here
}
This works, but does not animate.
$('.btn-navbar').addClass('collapsed');
$('.nav-collapse').removeClass('in').css('height', '0');
The R-inferno, or the basic R-documentation will explain why using df$* is not the best approach here. From the help page for "[" :
"Indexing by [ is similar to atomic vectors and selects a list of the specified element(s). Both [[ and $ select a single element of the list. The main difference is that $ does not allow computed indices, whereas [[ does. x$name is equivalent to x[["name", exact = FALSE]]. Also, the partial matching behavior of [[ can be controlled using the exact argument. "
I recommend using the [row,col]
notation instead. Example:
Rgames: foo
x y z
[1,] 1e+00 1 0
[2,] 2e+00 2 0
[3,] 3e+00 1 0
[4,] 4e+00 2 0
[5,] 5e+00 1 0
[6,] 6e+00 2 0
[7,] 7e+00 1 0
[8,] 8e+00 2 0
[9,] 9e+00 1 0
[10,] 1e+01 2 0
Rgames: foo<-as.data.frame(foo)
Rgames: foo[foo$y==2,3]<-foo[foo$y==2,1]
Rgames: foo
x y z
1 1e+00 1 0e+00
2 2e+00 2 2e+00
3 3e+00 1 0e+00
4 4e+00 2 4e+00
5 5e+00 1 0e+00
6 6e+00 2 6e+00
7 7e+00 1 0e+00
8 8e+00 2 8e+00
9 9e+00 1 0e+00
10 1e+01 2 1e+01
Simple Example
In you strings.xml
<string name="str_privacy_policy">This is our Privacy Policy.</string>
if you want to make specifically "Privacy Policy" as bold put the string between the bold tags.
Like this
<string name="str_privacy_policy">This is our <b>Privacy Policy.</b></string>
Result would be
This is our Privacy Policy
innerHTML
is a string representing the contents of the element.
You want to modify the element itself. Drop the .innerHTML
part.
The correct answer to this question has been changed by the publication of RFC 8314. As a result, port 465 and 587 are both valid ports for a mail submission agent (MSA). Port 465 requires negotiation of TLS/SSL at connection setup and port 587 uses STARTTLS if one chooses to negotiate TLS. The IANA registry was updated to allow legitimate use of port 465 for this purpose. For mail relay, only port 25 is used so STARTTLS is the only way to do TLS with mail relay. It's helpful to think of mail relay and mail submission as two very different services (with many behavior differences like requiring auth, different timeouts, different message modification rules, etc.) that happen to use a similar wire protocol.
Set the min SDK version in your project's AndroidManifest.xml file and in the toolbar search for "Sync Projects with Gradle Files" icon. It works for me.
Also look for your project's build.gradle file and update the min sdk version.
Thanks Guy.
With a slight variation I used it to find all the primary keys for all the tables.
SELECT A.Name,Col.Column_Name from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col ,
(select NAME from dbo.sysobjects where xtype='u') AS A
WHERE
Col.Constraint_Name = Tab.Constraint_Name
AND Col.Table_Name = Tab.Table_Name
AND Constraint_Type = 'PRIMARY KEY '
AND Col.Table_Name = A.Name
You have to add this code to your custom key bindings:
{ "keys": ["ctrl+f12"], "command": "set_setting", "args": {"setting": "tab_size", "value": 4} }
by pressing ctrl+f12, it will reindent your file to a tab size of 4. if you want a different tab size, you just change the "value" number. Te format is a simple json.
Found the answer. What I did was was first
sudo apt-get install aptitude
sudo aptitude install libglib2.0-0
sudo aptitude install gcc-4.7 make linux-headers-`uname -r` -y
and tried it but it didn't work so I continued and did
sudo apt-get install build-essential
sudo apt-get install gcc-4.7 linux-headers-`uname -r`
after doing these two steps and trying again, it worked.
Setting the underlying socket ReceiveTimeout
property did the trick. You can access it like this: yourTcpClient.Client.ReceiveTimeout
. You can read the docs for more information.
Now the code will only "sleep" as long as needed for some data to arrive in the socket, or it will raise an exception if no data arrives, at the beginning of a read operation, for more than 20ms. I can tweak this timeout if needed. Now I'm not paying the 20ms price in every iteration, I'm only paying it at the last read operation. Since I have the content-length of the message in the first bytes read from the server I can use it to tweak it even more and not try to read if all expected data has been already received.
I find using ReceiveTimeout much easier than implementing asynchronous read... Here is the working code:
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
var bytes = 0;
client.Client.ReceiveTimeout = 20;
do
{
try
{
bytes = stm.Read(resp, 0, resp.Length);
memStream.Write(resp, 0, bytes);
}
catch (IOException ex)
{
// if the ReceiveTimeout is reached an IOException will be raised...
// with an InnerException of type SocketException and ErrorCode 10060
var socketExept = ex.InnerException as SocketException;
if (socketExept == null || socketExept.ErrorCode != 10060)
// if it's not the "expected" exception, let's not hide the error
throw ex;
// if it is the receive timeout, then reading ended
bytes = 0;
}
} while (bytes > 0);
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
I found myself in the same situation and ended up adding these aliases to my .profile
file:
alias c1="awk '{print \$1}'"
alias c2="awk '{print \$2}'"
alias c3="awk '{print \$3}'"
alias c4="awk '{print \$4}'"
alias c5="awk '{print \$5}'"
alias c6="awk '{print \$6}'"
alias c7="awk '{print \$7}'"
alias c8="awk '{print \$8}'"
alias c9="awk '{print \$9}'"
Which allows me to write things like this:
svn st | c2 | xargs rm
Your problem is comparable to the creation of a file object and opening the file. In fact there are a lot of classes where you have to perform two steps before you can actually use the object: create + Initialize (often called something similar to Open).
The advantage of this is that the constructor can be lightweight. If desired, you can change some properties before actually initializing the object. When all properties are set, the Initialize
/Open
function is called to prepare the object to be used. This Initialize
function can be async.
The disadvantage is that you have to trust the user of your class that he will call Initialize()
before he uses any other function of your class. In fact if you want to make your class full proof (fool proof?) you have to check in every function that the Initialize()
has been called.
The pattern to make this easier is to declare the constructor private and make a public static function that will construct the object and call Initialize()
before returning the constructed object. This way you'll know that everyone who has access to the object has used the Initialize
function.
The example shows a class that mimics your desired async constructor
public MyClass
{
public static async Task<MyClass> CreateAsync(...)
{
MyClass x = new MyClass();
await x.InitializeAsync(...)
return x;
}
// make sure no one but the Create function can call the constructor:
private MyClass(){}
private async Task InitializeAsync(...)
{
// do the async things you wanted to do in your async constructor
}
public async Task<int> OtherFunctionAsync(int a, int b)
{
return await ... // return something useful
}
Usage will be as follows:
public async Task<int> SomethingAsync()
{
// Create and initialize a MyClass object
MyClass myObject = await MyClass.CreateAsync(...);
// use the created object:
return await myObject.OtherFunctionAsync(4, 7);
}
First of all you have to connect with your database like
my database is ubuntu
use this command to connect
\c ubuntu
This message will show
"You are now connected to database "ubuntu" as user "postgres"."
Now
Run this command to show all tables in it
\d+
Add the following code to a shape:
<gradient
android:angle="135"
android:endColor="#FF444444"
android:centerColor="#FFAAAAAA"
android:startColor="#FFFFFFFF"/>
ét voila, you've got a (more or less) indented border, with the light source set to left-top. Fiddle with the size of the bitmap (in relation to the size of the imageview, I used a 200dp x 200dp imageview and a bitmap of 196dp x 196dp in the example, with a radius of 14dp for the corners) and the padding to get the best result. Switch end and startcolor for a bevelled effect.
Here's the full code of the shape you see in the image (save it in res/drawable, e.g. border_shape.xml):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:angle="135"
android:endColor="#FF444444"
android:centerColor="#FFAAAAAA"
android:startColor="#FFFFFFFF"/>
<padding
android:top="2dp"
android:left="2dp"
android:right="2dp"
android:bottom="2dp"/>
<corners
android:radius="30dp"/>
</shape>
And call it in your imageview like this:
android:scaleType="center"
android:background="@drawable/border_shape"
android:cropToPadding="true"
android:adjustViewBounds="true"
And here is the code for the bitmap with rounded corners:
Bitmap getRoundedRectBitmap(Bitmap bitmap, float radius) {
Paint paint = new Paint();
PorterDuffXfermode pdmode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
Bitmap bm = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bm);
Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
RectF rectF = new RectF(rect);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(0xff424242);
canvas.drawRoundRect(rectF, radius, radius, paint);
paint.setXfermode(pdmode);
canvas.drawBitmap(bitmap, rect, rect, paint);
return bm;
}
Based on Daniel's answer, I wrote this SASS mixin with interpolation (#{}
) for a youtube video's iframe that is inside a Bootstrap modal dialog:
@mixin responsive-modal-wiframe($height: 9, $width: 16.5,
$max-w-allowed: 90, $max-h-allowed: 60) {
$sides-adjustment: 1.7;
iframe {
width: #{$width / $height * ($max-h-allowed - $sides-adjustment)}vh;
height: #{$height / $width * $max-w-allowed}vw;
max-width: #{$max-w-allowed - $sides-adjustment}vw;
max-height: #{$max-h-allowed}vh;
}
@media only screen and (max-height: 480px) {
margin-top: 5px;
.modal-header {
padding: 5px;
.modal-title {font-size: 16px}
}
.modal-footer {display: none}
}
}
Usage:
.modal-dialog {
width: 95vw; // the modal should occupy most of the screen's available space
text-align: center; // this will center the titles and the iframe
@include responsive-modal-wiframe();
}
HTML:
<div class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Video</h4>
</div>
<div class="modal-body">
<iframe src="https://www.youtube-nocookie.com/embed/<?= $video_id ?>?rel=0" frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
</div>
<div class="modal-footer">
<button class="btn btn-danger waves-effect waves-light"
data-dismiss="modal" type="button">Close</button>
</div>
</div>
</div>
</div>
This will always display the video without those black parts that youtube adds to the iframe when the width or height is not proportional to the video. Notes:
$sides-adjustment
is a slight adjustment to compensate a tiny part of these black parts showing up on the sides;.modal-footer
;.modal-dialog
;.modal-header
.After a lot of testing, this is working flawlessly for me now.
File
\ Other Settings
\ Default Project Structure...
Project
tab, section Project language level
, choose level from dropdown list, this setting is default for all new project
.raw
folder, if it doesn't exists,
create one.-
or special characters in it.On your activity, you need to have a object MediaPlayer
, inside the onCreate
method or the onclick
method, you have to initialize the MediaPlayer
, like MediaPlayer.create(this, R.raw.name_of_your_audio_file)
, then your audio file ir ready to be played with the call for start()
, in your case, since you want it to be placed in a button, you'll have to put it inside the onClick
method.
Example:
private Button myButton;
private MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
mp = MediaPlayer.create(this, R.raw.gunshot);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
}
}
I have streamlined the answer of @Quirliom above into functions that can be used:
private static boolean hasLength(CharSequence data) {
if (String.valueOf(data).length() >= 8) return true;
else return false;
}
private static boolean hasSymbol(CharSequence data) {
String password = String.valueOf(data);
boolean hasSpecial = !password.matches("[A-Za-z0-9 ]*");
return hasSpecial;
}
private static boolean hasUpperCase(CharSequence data) {
String password = String.valueOf(data);
boolean hasUppercase = !password.equals(password.toLowerCase());
return hasUppercase;
}
private static boolean hasLowerCase(CharSequence data) {
String password = String.valueOf(data);
boolean hasLowercase = !password.equals(password.toUpperCase());
return hasLowercase;
}
To stage modified and deleted files
git add -u
Convert has a style parameter for date to string conversions.
I found that that when I have two Get methods, one parameterless and one with a complex type as a parameter that I got the same error. I solved this by adding a dummy parameter of type int, named Id, as my first parameter, followed by my complex type parameter. I then added the complex type parameter to the route template. The following worked for me.
First get:
public IEnumerable<SearchItem> Get()
{
...
}
Second get:
public IEnumerable<SearchItem> Get(int id, [FromUri] List<string> layers)
{
...
}
WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{layers}",
defaults: new { id = RouteParameter.Optional, layers RouteParameter.Optional }
);
require
will throw a PHP Fatal Error if the file cannot be loaded. (Execution stops)
include
produces a Warning if the file cannot be loaded. (Execution continues)
Here is a nice illustration of include and require difference:
From: Difference require vs. include php (by Robert; Nov 2012)
You can create a DIV
component using the <h:panelGroup/>
.
By default, the <h:panelGroup/>
will generate a SPAN in the HTML code.
However, if you specify layout="block"
, then the component will be a DIV
in the generated HTML code.
<h:panelGroup layout="block"/>
var url = window.location.origin + window.location.pathname;
To change Edittext’s underline color:
If you want the entire app to share this style, then you can do the following way.
(1) go to styles.xml file. Your AppTheme that inherits the parent of Theme.AppCompat.Light.DarkActionBar (in my case) will be the base parent of all they style files in your app. Change the name of it to “AppBaseTheme’. Make another style right under it that has the name of AppTheme and inherits from AppBaseTheme that you just edited. It will look like following:
<!-- Base application theme. -->
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="windowActionBar">false</item>
<!--see http://www.google.com/design/spec/style/color.html#color-color-palette-->
<item name="colorPrimary">@color/material_brown_500</item>
<item name="colorPrimaryDark">@color/material_brown_700</item>
<item name="colorAccent">@color/flamingo</item>
<style name="AppTheme" parent="AppBaseTheme">
<!-- Customize your theme here. -->
</style>
Then change the “colorAccent” to whatever the color you want your EditText line color to be.
(2) If you have other values folders with style.xml, this step is very important. Because that file will inherit from your previous parent xml file. For example, I have values-19/styles.xml. This is specifically for Kitkat and above. Change its parent to AppBaseTheme and make sure to get rid of “colorAccent” so that it doesn’t override the parent’s color. Also you need to keep the items that are specific to version 19. Then it will look like this.
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:windowTranslucentStatus">true</item>
</style>
</resources>
USE DataBaseName; GO --------- CREATE ROLE --------- CREATE ROLE Doctors ; GO ---- Assign Role To users ------- CREATE USER [Username] FOR LOGIN [Domain\Username] EXEC sp_addrolemember N'Doctors', N'Username' ----- GRANT Permission to Users Assinged with this Role----- GRANT ALL ON Table1, Table2, Table3 TO Doctors; GO
You use a compound key (a key with more than one attribute) whenever you want to ensure the uniqueness of a combination of several attributes. A single attribute key would not achieve the same thing.
If you're able to bring in an EXE, I recommend gdate.exe
from GNU CoreUtils for Windows). It can give the current date or the date of a file, in many different formats, and customizable. I use it to get me the last modified date-time of files that I can compare without any parsing (ie. local-independent), using the %s
(seconds since the epoch), optionally with %N
to get nano-second precision.
Some examples:
C:\>dir MyFile.txt
02/10/2021 10:54 PM 4 MyFile.txt
C:\>gdate -r MyFile.txt +%Y-%m-%d
2021-02-10
C:\>gdate -r MyFile.txt "+%Y-%m-%d %H:%M:%S"
2021-02-10 22:54:50
C:\>gdate -r MyFile.txt +%s
1613015690
C:\>gdate -r MyFile.txt +%s.%N
1613015690.093962600
console.log is only defined when the console is open. If you want to check for it in your code make sure you check for for it within the window property
if (window.console)
console.log(msg)
this throws an exception in IE9 and will not work correctly. Do not do this
if (console)
console.log(msg)
I've created a dynamic way to call each event automatically. It perfect to focus a field, because it call the event just once, removing it after use.
function modalEvents() {
var modal = $('#modal');
var events = ['show', 'shown', 'hide', 'hidden'];
$(events).each(function (index, event) {
modal.on(event + '.bs.modal', function (e) {
var callback = modal.data(event + '-callback');
if (typeof callback != 'undefined') {
callback.call();
modal.removeData(event + '-callback');
}
});
});
}
You just need to call modalEvents()
on document ready.
Use:
$('#modal').data('show-callback', function() {
$("input#photo_name").focus();
});
So, you can use the same modal to load what you want without worry about remove events every time.
Using autoview
image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true
You can actually use plyr
's rename
function as part of dplyr
chains. I think every function that a) takes a data.frame
as the first argument and b) returns a data.frame
works for chaining. Here is an example:
library('plyr')
library('dplyr')
DF = data.frame(var=1:5)
DF %>%
# `rename` from `plyr`
rename(c('var'='x')) %>%
# `mutate` from `dplyr` (note order in which libraries are loaded)
mutate(x.sq=x^2)
# x x.sq
# 1 1 1
# 2 2 4
# 3 3 9
# 4 4 16
# 5 5 25
UPDATE: The current version of dplyr
supports renaming directly as part of the select
function (see Romain Francois post above). The general statement about using non-dplyr functions as part of dplyr
chains is still valid though and rename
is an interesting example.
You can get both Position and Dimension of the view on screen
val viewTreeObserver: ViewTreeObserver = videoView.viewTreeObserver;
if (viewTreeObserver.isAlive) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
//Remove Listener
videoView.viewTreeObserver.removeOnGlobalLayoutListener(this);
//View Dimentions
viewWidth = videoView.width;
viewHeight = videoView.height;
//View Location
val point = IntArray(2)
videoView.post {
videoView.getLocationOnScreen(point) // or getLocationInWindow(point)
viewPositionX = point[0]
viewPositionY = point[1]
}
}
});
}
Have a look at ?options
and use warn
:
options( warn = -1 )
Create a Map or a Set, and using "on connection" event set to it each connected socket, in reverse "once disconnect" event delete that socket from the Map we created earlier
import * as Server from 'socket.io';
const io = Server();
io.listen(3000);
const connections = new Set();
io.on('connection', function (s) {
connections.add(s);
s.once('disconnect', function () {
connections.delete(s);
});
});
z-index
is not that simple friend. It doesn't actually matter if you put z-index:999999999999
..... But it matters WHEN you gave it that z-index
. Different dom-elements take precedence over each other as well.
I did one solution where I used jQuery to modify the elements css, and gave it the z-index
only when I needed the element to be on top. That way we can be sure that the z-index
of this item has been given last and the index will be noted. This one requires some action to be handled though, but in your case it seems to be possible.
Not sure if this works, but you could try giving the !important
parameter too:
#desired_element { z-index: 99 !important; }
Edit: Adding a quote from the link for quick clarification:
First of all, z-index only works on positioned elements. If you try to set a z-index on an element with no position specified, it will do nothing. Secondly, z-index values can create stacking contexts, and now suddenly what seemed simple just got a lot more complicated.
Adding the z-index for the element via jQuery, gives the element different stacking context, and thus it tends to work. I do not recommend this, but try to keep the html and css in a such order that all elements are predictable.
The provided link is a must read. Stacking order etc. of html elements was something I was not aware as a newbie coder and that article cleared it for me pretty good.
Reference philipwalton.com
While the answers with List<T>.ForEach
are very good.
I found String.Join<T>(string separator, IEnumerable<T> values)
method more useful.
Example :
List<string> numbersStrLst = new List<string>
{ "One", "Two", "Three","Four","Five"};
Console.WriteLine(String.Join(", ", numbersStrLst));//Output:"One, Two, Three, Four, Five"
int[] numbersIntAry = new int[] {1, 2, 3, 4, 5};
Console.WriteLine(String.Join("; ", numbersIntAry));//Output:"1; 2; 3; 4; 5"
Remarks :
If separator is null, an empty string (String.Empty
) is used instead. If any member of values is null, an empty string is used instead.
Join(String, IEnumerable<String>)
is a convenience method that lets you concatenate each element in an IEnumerable(Of String) collection without first converting the elements to a string array. It is particularly useful with Language-Integrated Query (LINQ) query expressions.
This should work just fine for the problem, whereas for others, having array values. Use other overloads of this same method, String.Join Method (String, Object[])
Reference: https://msdn.microsoft.com/en-us/library/dd783876(v=vs.110).aspx
Do not hold me to this but I am pretty sure it depends on the application it self. I know many always open on the main monitor, some will reopen to the same monitor they were previously run in, and some you can set. I know for example I have shortcuts to open command windows to particular directories, and each has an option in their properties to the location to open the window in. While Outlook just remembers and opens in the last screen it was open in. Then other apps open in what ever window the current focus is in.
So I am not sure there is a way to tell every program where to open. Hope that helps some.
I think what you want to achieve is with the collaboration of "@mouseover and @mouseleave" or "@mouseenter and @mouseleave"
And I think, It's better to use the 2nd pair so that you can achieve the hover effect and call functionlaities on that.
<div @mouseenter="activeHover = true" @mouseleave="activeHover = false" >
<p v-if="activeHover"> This will be showed on hover </p>
<p v-if ="!activeHover"> This will be showed in simple cases </p>
</div>
on vue instance
data : {
activeHover : false
}
I hope, it will help others as well :)
To fix this error I upgraded my MySQL database to utf8mb4 which supports the full Unicode character set by following this detailed tutorial. I suggest going through it carefully, because there are quite a few gotchas (e.g. the index keys can become too large due to the new encodings after which you have to modify field types).
The Statement
gives you the following option:
Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO employees VALUES (1000, 'Joe Jones')");
stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')");
stmt.addBatch("INSERT INTO emp_dept VALUES (1000, 260)");
// submit a batch of update commands for execution
int[] updateCounts = stmt.executeBatch();
<script type="text/javascript">
$(document).ready(function() {
$('#upload').bind("click",function()
{
var imgVal = $('#uploadImage').val();
if(imgVal=='')
{
alert("empty input file");
}
return false;
});
});
</script>
<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload" id="upload" class="send_upload" value="upload" />
You can use below link: New line in javascript
var i;
for(i=10; i>=0; i= i-1){
var s;
for(s=0; s<i; s = s+1){
document.write("*");
}
//i want this to print a new line
/document.write('<br>');
}
To get the value of the selected item of a listbox then use the following.
For Single Column ListBox:
ListBox1.List(ListBox1.ListIndex)
For Multi Column ListBox:
ListBox1.Column(column_number, ListBox1.ListIndex)
This avoids looping and is extremely more efficient.
Seriously add the link featured in Tim's answer in the Stack Overflow post Setup Git Server with Msysgit on Windows.
It flawlessly told me how to setup Git on Windows with msysgit, and is an incredibly detailed article.
I also had messages like No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
I had configured cors properly, but what was missing in webflux in RouterFuncion was accept and contenttype headers APPLICATION_JSON like in this piece of code:
@Bean
RouterFunction<ServerResponse> routes() {
return route(POST("/create")
.and(accept(APPLICATION_JSON))
.and(contentType(APPLICATION_JSON)), serverRequest -> create(serverRequest);
}
For Kotlin fans:
private fun Bitmap.addOverlay(@DimenRes marginTop: Int, @DimenRes marginLeft: Int, overlay: Bitmap): Bitmap? {
val bitmapWidth = this.width
val bitmapHeight = this.height
val marginLeft = shareBitmapWidth - overlay.width - resources.getDimension(marginLeft)
val finalBitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, this
.config)
val canvas = Canvas(finalBitmap)
canvas.drawBitmap(this, Matrix(), null)
canvas.drawBitmap(overlay, marginLeft, resources.getDimension(marginTop), null)
return finalBitmap
}
bitmap.addOverlay( R.dimen.top_margin, R.dimen.left_margin, overlayBitmap)
I'll tackle your second question first. Yes, the indentation can be reset by using a browser reset like Eric Meyers. Or a simple ul { margin: 0; padding: 0;}
as indentation is, by default, enforced on the ul
element.
As to the why, I suspect its to do with the current level of nesting, as unordered lists allow for nesting or maybe to do with the bullets positioning.
Edit: As Guffa mentioned, the list indentation is to ensure that the markers do not fall off the left edge.
It's ok. Also you can use LAST_INSERT_ID()
Using Pygrok, you can define abstracted extensions to the Regular Expression syntax.
The custom patterns can be included in your regex in the format %{PATTERN_NAME}
.
You can also create a label for that pattern, by separating with a colon: %s{PATTERN_NAME:matched_string}
. If the pattern matches, the value will be returned as part of the resulting dictionary (e.g. result.get('matched_string')
)
For example:
from pygrok import Grok
input_string = 'monkey 2010-07-10 love banana'
date_pattern = '%{YEAR:year}-%{MONTHNUM:month}-%{MONTHDAY:day}'
grok = Grok(date_pattern)
print(grok.match(input_string))
The resulting value will be a dictionary:
{'month': '07', 'day': '10', 'year': '2010'}
If the date_pattern does not exist in the input_string, the return value will be None
. By contrast, if your pattern does not have any labels, it will return an empty dictionary {}
References:
I would suppose that you can use a variable in the result, but aside from getting the ORDER BY piece in a view, you will not see a benefit by implicitly stating "TOP 100 PERCENT":
declare @t int
set @t=100
select top (@t) percent * from tableOf
If you just want a count of the distinct pairs.
The simplest way to do that is as follows
SELECT COUNT(DISTINCT a,b) FROM pairs
The previous solutions would list all the pairs and then you'd have to do a second query to count them.
Download it from here:
http://www.iis.net/downloads/microsoft/url-rewrite
or if you already have Web Platform Installer on your machine you can install it from there.
Your debut
and fin
values are floating point values, not integers, because taille
is a float.
Make those values integers instead:
item = plateau[int(debut):int(fin)]
Alternatively, make taille
an integer:
taille = int(sqrt(len(plateau)))
I was not getting the error on 32-bit machines but was on 64-bit so I changed the target platform from x86 to Any CPU and it resolved the issue.
Had a directory by the same name as the file i was trying to write, so people can look out for that as well.
When they say List<T>
is "optimized" I think they want to mean that it doesn't have features like virtual methods which are bit more expensive. So the problem is that once you expose List<T>
in your public API, you loose ability to enforce business rules or customize its functionality later. But if you are using this inherited class as internal within your project (as opposed to potentially exposed to thousands of your customers/partners/other teams as API) then it may be OK if it saves your time and it is the functionality you want to duplicate. The advantage of inheriting from List<T>
is that you eliminate lot of dumb wrapper code that is just never going to be customized in foreseeable future. Also if you want your class to explicitly have exact same semantics as List<T>
for the life of your APIs then also it may be OK.
I often see lot of people doing tons of extra work just because of FxCop rule says so or someone's blog says it's a "bad" practice. Many times, this turns code in to design pattern palooza weirdness. As with lot of guideline, treat it as guideline that can have exceptions.
Using Java
int nDigits = Math.floor(Math.log10(Math.abs(the_integer))) + 1;
use import java.lang.Math.*;
in the beginning
Using C
int nDigits = floor(log10(abs(the_integer))) + 1;
use inclue math.h
in the beginning
I wrote a wrapper, that will cache text surfaces, only re-render when dirty. googlecode/ninmonkey/nin.text/demo/
If you want to get Syntax Error with line number, use this
error: function(xhr, status, error) {
alert(error);
}
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
I would try triming the number to see what you get:
select len(rtrim(ltrim(userid))) from audit
if that return the correct value then just do:
select convert(int, rtrim(ltrim(userid))) from audit
if that doesn't return the correct value then I would do a replace to remove the empty space:
select convert(int, replace(userid, char(0), '')) from audit
Since you are new to Android development you may not know about Content Providers, which are database abstractions. They may not be the right thing for your project, but you should check them out: http://developer.android.com/guide/topics/providers/content-providers.html
if dosen't work after
$ npm install lodash --save
$ npm install --save-dev @types/lodash
you try this and import lodash
typings install lodash --save
The PostgreSQL manual indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too.
If you're using Slony for replication, however, the Slony-I FAQ suggests idle in transaction
may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details.
Change
from urllib.request import urlopen
to
from urllib import urlopen
I was able to solve this problem by changing like this. For Python2.7
in macOS10.14
you can try writing the command using 'sudo':
sudo mkdir DirName
// array of $ids that you need to select
$ids = array('1', '2', '3', '4', '5', '6', '7', '8');
// create sql part for IN condition by imploding comma after each id
$in = '(' . implode(',', $ids) .')';
// create sql
$sql = 'SELECT * FROM products WHERE catid IN ' . $in;
// see what you get
var_dump($sql);
Update: (a short version and update missing comma)
$ids = array('1','2','3','4');
$sql = 'SELECT * FROM products WHERE catid IN (' . implode(',', $ids) . ')';
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
React 16 gets your return as an array so it should be wrapped by one element like div.
Wrong Approach
render(){
return(
<input type="text" value="" onChange={this.handleChange} />
<button className="btn btn-primary" onClick= {()=>this.addTodo(this.state.value)}>Submit</button>
);
}
Right Approach (All elements in one div or other element you are using)
render(){
return(
<div>
<input type="text" value="" onChange={this.handleChange} />
<button className="btn btn-primary" onClick={()=>this.addTodo(this.state.value)}>Submit</button>
</div>
);
}
public ChannelSearchEnum[] getChannelSearchEnum(Response response) {
return response.as(ChannelSearchEnum[].class, ObjectMapperType.GSON);
}
Above will solve and passing response will returned mapped object array of the class
From the Python documentation itself, you can use max
:
>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456
In case if you want to remove all objects with "foo/" prefix using Java AWS SDK 2.0
import java.util.ArrayList;
import java.util.Iterator;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
//...
ListObjectsRequest listObjectsRequest = ListObjectsRequest.builder()
.bucket(bucketName)
.prefix("foo/")
.build()
;
ListObjectsResponse objectsResponse = s3Client.listObjects(listObjectsRequest);
while (true) {
ArrayList<ObjectIdentifier> objects = new ArrayList<>();
for (Iterator<?> iterator = objectsResponse.contents().iterator(); iterator.hasNext(); ) {
S3Object s3Object = (S3Object)iterator.next();
objects.add(
ObjectIdentifier.builder()
.key(s3Object.key())
.build()
);
}
s3Client.deleteObjects(
DeleteObjectsRequest.builder()
.bucket(bucketName)
.delete(
Delete.builder()
.objects(objects)
.build()
)
.build()
);
if (objectsResponse.isTruncated()) {
objectsResponse = s3Client.listObjects(listObjectsRequest);
continue;
}
break;
};
The following will display all 3 buttons on the same line provided there is enough horizontal space to display them:
<button type="submit" class="msgBtn" onClick="return false;" >Save</button>
<button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
<button class="msgBtnBack">Back</button>
// Note the lack of unnecessary divs, floats, etc.
The only reason the buttons wouldn't display inline is if they have had display:block applied to them within your css.
Well I needed something that would reduce seconds into hours minutes and seconds, but would exceed 24 hours, and not reduce further down into days.
Here is a simple function that works. You can probably improve it... But here it is:
function formatSeconds($seconds)
{
$hours = 0;$minutes = 0;
while($seconds >= 60){$seconds -= 60;$minutes++;}
while($minutes >= 60){$minutes -=60;$hours++;}
$hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
$seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);
return $hours.":".$minutes.":".$seconds;
}
I have had to unpack a .ab
-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.
Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab
-file is password-protected.
Usage:java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]
Example:
Let's say, you've got a file test.ab
, which is not password-protected, you're using Windows and want the resulting .tar
-Archive to be called test.tar
. Then your command should be:
java.exe -jar abe.jar unpack test.ab test.tar ""
Now, there is gcc-4.9 available for Ubuntu/precise.
Create a group of compiler alternatives where the distro compiler has a higher priority:
root$ VER=4.6 ; PRIO=60
root$ update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
root$ update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-$VER $PRIO
root$ VER=4.9 ; PRIO=40
root$ update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
root$ update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-$VER $PRIO
NOTE: g++ version is changed automatically with a gcc version switch. cpp-bin has to be done separately as there exists a "cpp" master alternative.
List available compiler alternatives:
root$ update-alternatives --list gcc
root$ update-alternatives --list cpp-bin
To select manually version 4.9 of gcc, g++ and cpp, do:
root$ update-alternatives --config gcc
root$ update-alternatives --config cpp-bin
Check compiler versions:
root$ for i in gcc g++ cpp ; do $i --version ; done
Restore distro compiler settings (here: back to v4.6):
root$ update-alternatives --auto gcc
root$ update-alternatives --auto cpp-bin
It's HTTP Activation feature of .NET framework Windows Process Activation feature is required too
Put it in the viewDidLoad
method
navigationItem.hidesBackButton = true
This pattern should work:
#\d
foreach(var match in System.Text.RegularExpressions.RegEx.Matches(input, "#\d"))
{
Console.WriteLine(match.Value);
}
(I'm not in front of Visual Studio, but even if that doesn't compile as-is, it should be close enough to tweak into something that works).
Definitely should use a dict using the "group" + str(i) key as described in the accepted solution but I wanted to share a solution using exec. Its a way to parse strings into commands & execute them dynamically. It would allow to create these scalar variable names as per your requirement instead of using a dict. This might help in regards what not to do, and just because you can doesn't mean you should. Its a good solution only if using scalar variables is a hard requirement:
l = locals()
for i in xrange(3):
exec("group" + str(i) + "= self.getGroup(selected, header + i)")
Another example where this could work using a Django model example. The exec alternative solution is commented out and the better way of handling such a case using the dict attribute makes more sense:
Class A(models.Model):
....
def __getitem__(self, item): # a.__getitem__('id')
#exec("attrb = self." + item)
#return attrb
return self.__dict__[item]
It might make more sense to extend from a dictionary in the first place to get setattr and getattr functions.
A situation which involves parsing, for example generating & executing python commands dynamically, exec is what you want :) More on exec here.
First things first, you have to install Maven on your workstation. You need also to install M2E, what you obviously did. Not all distributions of Juno have it pre-installed.
Then configure your Eclipse so it can find your Maven install. In the menu Window -> Preferences, then open the Maven section. In your right panel, you have a list of the Maven installations Eclipse knows. Add your installation and select it instead of the embedded Maven provided with M2E. Don't forget to set the "Global settings from installation directory" field with the path to the settings.xml of your Maven installation.
Which leads us to the settings.xml. If the above doesn't solve your problem, you will have to configure your Maven. More infos here.
There is no way to do this in single query. You have to search the document in first query:
If document exists:
db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } ,
{$inc : {"items.$.price" : 1} } ,
false ,
true);
Else
db.bar.update( {user_id : 123456 } ,
{$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
false ,
true);
No need to add condition {$ne : "my_item_two" }
.
Also in multithreaded enviourment you have to be careful that only one thread can execute the second (insert case, if document did not found) at a time, otherwise duplicate embed documents will be inserted.
you need to enable first the App password of your google account -> security section link
then the app password that will be generated copy it and paste it in to .env file
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=app_password
MAIL_ENCRYPTION=ssl
if (date.isBefore(endDate)
&& date.isAfter(startDate)
|| (date.isSame(startDate) || date.isSame(endDate))
is logically the same as
if (!(date.isBefore(startDate) || date.isAfter(endDate)))
which saves you a couple of lines of code and (in some cases) method calls.
Might be easier than pulling in a whole plugin if you only want to do this once or twice.
You can use two elements, one inside the other, and give the outer one overflow: hidden
and a width equal to the inner element together with a bottom padding so that the shadow on all the other sides are "cut off"
#outer {
width: 100px;
overflow: hidden;
padding-bottom: 10px;
}
#outer > div {
width: 100px;
height: 100px;
background: orange;
-moz-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
-webkit-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
}
Alternatively, float the outer element to cause it to shrink to the size of the inner element. See: http://jsfiddle.net/QJPd5/1/
Type hint are a recent addition to a dynamic language where for decades folks swore naming conventions as simple as Hungarian (object label with first letter b = Boolean, c = character, d = dictionary, i = integer, l = list, n = numeric, s = string, t= tuple) were not needed, too cumbersome, but now have decided that, oh wait ... it is way too much trouble to use the language (type()) to recognize objects, and our fancy IDEs need help doing anything that complicated, and that dynamically assigned object values make them completely useless anyhow, whereas a simple naming convention could have resolved all of it, for any developer, at a mere glance.
Some answers suggested to use pattern: check if role does not exist and if not then issue CREATE ROLE
command. This has one disadvantage: race condition. If somebody else creates a new role between check and issuing CREATE ROLE
command then CREATE ROLE
obviously fails with fatal error.
To solve above problem, more other answers already mentioned usage of PL/pgSQL
, issuing CREATE ROLE
unconditionally and then catching exceptions from that call. There is just one problem with these solutions. They silently drop any errors, including those which are not generated by fact that role already exists. CREATE ROLE
can throw also other errors and simulation IF NOT EXISTS
should silence only error when role already exists.
CREATE ROLE
throw duplicate_object
error when role already exists. And exception handler should catch only this one error. As other answers mentioned it is a good idea to convert fatal error to simple notice. Other PostgreSQL IF NOT EXISTS
commands adds , skipping
into their message, so for consistency I'm adding it here too.
Here is full SQL code for simulation of CREATE ROLE IF NOT EXISTS
with correct exception and sqlstate propagation:
DO $$
BEGIN
CREATE ROLE test;
EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
END
$$;
Test output (called two times via DO and then directly):
$ sudo -u postgres psql
psql (9.6.12)
Type "help" for help.
postgres=# \set ON_ERROR_STOP on
postgres=# \set VERBOSITY verbose
postgres=#
postgres=# DO $$
postgres$# BEGIN
postgres$# CREATE ROLE test;
postgres$# EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
postgres$# END
postgres$# $$;
DO
postgres=#
postgres=# DO $$
postgres$# BEGIN
postgres$# CREATE ROLE test;
postgres$# EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
postgres$# END
postgres$# $$;
NOTICE: 42710: role "test" already exists, skipping
LOCATION: exec_stmt_raise, pl_exec.c:3165
DO
postgres=#
postgres=# CREATE ROLE test;
ERROR: 42710: role "test" already exists
LOCATION: CreateRole, user.c:337
PFX files are PKCS#12 Personal Information Exchange Syntax Standard bundles. They can include arbitrary number of private keys with accompanying X.509 certificates and a certificate authority chain (set certificates).
If you want to extract client certificates, you can use OpenSSL's PKCS12 tool.
openssl pkcs12 -in input.pfx -out mycerts.crt -nokeys -clcerts
The command above will output certificate(s) in PEM format. The ".crt" file extension is handled by both macOS and Window.
You mention ".cer" extension in the question which is conventionally used for the DER encoded files. A binary encoding. Try the ".crt" file first and if it's not accepted, easy to convert from PEM to DER:
openssl x509 -inform pem -in mycerts.crt -outform der -out mycerts.cer
If you want control over the td's/th's like you can do with block level elements & floats: Its NOT possible. There is no way to make a td float over or under a th.
I had the same problem with a dummy app that happened to have the same name as my final app and couldn't publish because the App Name is already in use
To fix it, instead of deleting it(which you can't) I just changed the name of the dummy app to something random and hit SAVE. Then I was able to add the new app with the proper name
You want the typeof
operator. Specifically:
if (typeof variable !== 'undefined') {
// the variable is defined
}
You can try something like this
IFNULL(NULLIF(X, '' ), 0)
Attribute X is assumed to be empty if it is an empty String, so after that you can declare as a zero instead of last value. In another case, it would remain its original value.
Anyway, just to give another way to do that.
The ON UPDATE
and ON DELETE
specify which action will execute when a row in the parent table is updated and deleted. The following are permitted actions : NO ACTION
, CASCADE
, SET NULL
, and SET DEFAULT
.
If you delete one or more rows in the parent table, you can set one of the following actions:
ON DELETE NO ACTION
: SQL Server raises an error and rolls back the delete action on the row in the parent table.ON DELETE CASCADE
: SQL Server deletes the rows in the child table that is corresponding to the row deleted from the parent table.ON DELETE SET NULL
: SQL Server sets the rows in the child table to NULL if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must be nullable.ON DELETE SET DEFAULT
: SQL Server sets the rows in the child table to their default values if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must have default definitions. Note that a nullable column has a default value of NULL if no default value specified.
By default, SQL Server appliesON DELETE NO ACTION if you don’t explicitly specify any action.If you update one or more rows in the parent table, you can set one of the following actions:
ON UPDATE NO ACTION
: SQL Server raises an error and rolls back the update action on the row in the parent table.ON UPDATE CASCADE
: SQL Server updates the corresponding rows in the child table when the rows in the parent table are updated.ON UPDATE SET NULL
: SQL Server sets the rows in the child table to NULL when the corresponding row in the parent table is updated. Note that the foreign key columns must be nullable for this action to execute.ON UPDATE SET DEFAULT
: SQL Server sets the default values for the rows in the child table that have the corresponding rows in the parent table updated.FOREIGN KEY (foreign_key_columns)
REFERENCES parent_table(parent_key_columns)
ON UPDATE <action>
ON DELETE <action>;
if you user $criteria, I recommend blow usage:
$criteria = new CDbCriteria();
$criteria->compare('email_id', 101);
$comments = EmailArchive::model()->findAll($criteria);
ASCII isn't in it any more. Using UTF-8 encoding means that you aren't using ASCII encoding. What you should use the escaping mechanism for is what the RFC says:
All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F)
If you have spaces in the name of the file and you have a character you need to escape:
You can use single AND double quotes to avoid any misnomers in the command.
scp ./'files name with spaces/internal folder with spaces/"text & files stored.txt"' .
The ^
character escapes the quotes otherwise.
Actually, in C++14 it can be done with a very few lines of code.
This is a very similar in idea to @Paul's solution. Due to things missing from C++11, that solution is a bit unnecessarily bloated (plus defining in std smells). Thanks to C++14 we can make it a lot more readable.
The key observation is that range-based for-loops work by relying on begin()
and end()
in order to acquire the range's iterators. Thanks to ADL, one doesn't even need to define their custom begin()
and end()
in the std:: namespace.
Here is a very simple-sample solution:
// -------------------------------------------------------------------
// --- Reversed iterable
template <typename T>
struct reversion_wrapper { T& iterable; };
template <typename T>
auto begin (reversion_wrapper<T> w) { return std::rbegin(w.iterable); }
template <typename T>
auto end (reversion_wrapper<T> w) { return std::rend(w.iterable); }
template <typename T>
reversion_wrapper<T> reverse (T&& iterable) { return { iterable }; }
This works like a charm, for instance:
template <typename T>
void print_iterable (std::ostream& out, const T& iterable)
{
for (auto&& element: iterable)
out << element << ',';
out << '\n';
}
int main (int, char**)
{
using namespace std;
// on prvalues
print_iterable(cout, reverse(initializer_list<int> { 1, 2, 3, 4, }));
// on const lvalue references
const list<int> ints_list { 1, 2, 3, 4, };
for (auto&& el: reverse(ints_list))
cout << el << ',';
cout << '\n';
// on mutable lvalue references
vector<int> ints_vec { 0, 0, 0, 0, };
size_t i = 0;
for (int& el: reverse(ints_vec))
el += i++;
print_iterable(cout, ints_vec);
print_iterable(cout, reverse(ints_vec));
return 0;
}
prints as expected
4,3,2,1,
4,3,2,1,
3,2,1,0,
0,1,2,3,
NOTE std::rbegin()
, std::rend()
, and std::make_reverse_iterator()
are not yet implemented in GCC-4.9. I write these examples according to the standard, but they would not compile in stable g++. Nevertheless, adding temporary stubs for these three functions is very easy. Here is a sample implementation, definitely not complete but works well enough for most cases:
// --------------------------------------------------
template <typename I>
reverse_iterator<I> make_reverse_iterator (I i)
{
return std::reverse_iterator<I> { i };
}
// --------------------------------------------------
template <typename T>
auto rbegin (T& iterable)
{
return make_reverse_iterator(iterable.end());
}
template <typename T>
auto rend (T& iterable)
{
return make_reverse_iterator(iterable.begin());
}
// const container variants
template <typename T>
auto rbegin (const T& iterable)
{
return make_reverse_iterator(iterable.end());
}
template <typename T>
auto rend (const T& iterable)
{
return make_reverse_iterator(iterable.begin());
}
based on other answers and comment of @phk, using fd #3:
(which still allows to use stdin inside the loop)
while IFS= read -r f <&3; do
echo "$f"
done 3< <(find . -iname "*filename*")
All in All, after reading this all page and other ones and a lot of documentation. Here's the summary:
/* This should select the first 2 element with class display_class
* but it will NOT WORK Because the nth-child count even siblings
* including the first div skip_class
*/
.display_class:nth-child(-n+2){
background-color:green;
}
_x000D_
<ul>
<li class="skip_class">test 1</li>
<li class="display_class">test 2 should be in green</li>
<li class="display_class">test 3 should be in green</li>
<li class="display_class">test 4</li>
</ul>
_x000D_
Currently, there is a selector :nth-child(-n+2 of .foo) that supports selection by class but not supported by modern browsers so not useful.
So, that leaves us with Javascript solution (we'll fix the example above):
// Here we'll go through the elements with the targeted class
// and add our classmodifer to only the first 2 elements!
[...document.querySelectorAll('.display_class')].forEach((element,index) => {
if (index < 2) element.classList.add('display_class--green');
});
_x000D_
.display_class--green {
background-color:green;
}
_x000D_
<ul>
<li class="skip_class">test 1</li>
<li class="display_class">test 2 should be in green</li>
<li class="display_class">test 3 should be in green</li>
<li class="display_class">test 4</li>
</ul>
_x000D_
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?
d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()
I used:
if (object !== undefined) {
// continue - error suppressed when used in this way.
}
Alternatively, you could use type coercion:
const objectX = object as string
Although, before choosing one of the above workarounds, please consider the architecture you are aiming for and it's impact to the bigger picture.
I became interested in the issue and perform some experiments
I found that description here, but it is very short.
Then I tried to experiment with gcc.exe and g++.exe on my windows machine:
$ g++ --version | head -n1
g++.exe (gcc-4.6.3 release with patches [build 20121012 by perlmingw.sf.net]) 4.6.3
$ gcc --version | head -n1
gcc.exe (gcc-4.6.3 release with patches [build 20121012 by perlmingw.sf.net]) 4.6.3
I tried to compile c89, c99, and c++1998 simple test files and It's work well for me with correct extensions matching for language
gcc -std=c99 test_c99.c
gcc -std=c89 test_c89.c
g++ -std=c++98 test_cpp.cpp
gcc -std=c++98 test_cpp.cpp
But when I try to run "gnu compiler collection" tool in that fashion:
$ gcc -std=c++98 test_cpp.c
cc1.exe: warning: command line option '-std=c++98' is valid for C++/ObjC++ but not for C [enabled by default]
But this one still work with no errors
$ gcc -x c++ -std=c++98 test_cpp.c
And this also
$ g++ -std=c++0x test_cpp_11.cpp
p.s. Test files
$ cat test_c89.c test_c99.c test_cpp.cpp
// C89 compatible file
int main()
{
int x[] = {0, 2};
return sizeof(x);
}
// C99 compatible file
int main()
{
int x[] = {[1]=2};
return sizeof(x);
}
// C++1998,2003 compatible file
class X{};
int main()
{
X x;
return sizeof(x);
}
// C++11
#include <vector>
enum class Color : int{red,green,blue}; // scoped enum
int main()
{
std::vector<int> a {1,2,3}; // bracket initialization
return 0;
}
Findings:
If look at process tree then it seems that gcc, and g++ is backend to other tools, which in my environment are: cc1plus.exe, cc1.exe, collect2.exe, as.exe, ld.exe
gcc works fine as metatool for if you have correct extension or set correct -std -x flags. See this
condition: =K21+$F22
That is not a CONDITION. That is a VALUE. A CONDITION, evaluates as a BOOLEAN value (True/False) If True, then the format is applied.
This would be a CONDITION, for instance
condition: =K21+$F22>0
In general, when applying a CF to a range,
1) select the entire range that you want the Conditional FORMAT to be applied to.
2) enter the CONDITION, as it relates to the FIRST ROW of your selection.
The CF accordingly will be applied thru the range.
Access the element you want to change via the DOM, for example with document.getElementById()
or via this
in your event handler, and change the style in that element:
document.getElementById("MyHeader").style.backgroundColor='red';
EDIT
You can use getElementsByTagName too, (untested) example:
function colorElementAndH2(elem, colorElem, colorH2) {
// change element background color
elem.style.backgroundColor = colorElem;
// color first contained h2
var h2s = elem.getElementsByTagName("h2");
if (h2s.length > 0)
{
hs2[0].style.backgroundColor = colorH2;
}
}
// add event handlers when complete document has been loaded
window.onload = function() {
// add to _all_ divs (not sure if this is what you want though)
var elems = document.getElementsByTagName("div");
for(i = 0; i < elems.length; ++i)
{
elems[i].onmouseover = function() { colorElementAndH2(this, 'red', 'blue'); }
elems[i].onmouseout = function() { colorElementAndH2(this, 'transparent', 'transparent'); }
}
}
As mentioned by @Tom, the cut and awk approaches actually don't work for CSVs with quoted strings. An alternative is a module for python that provides the command line tool csvfilter. It works like cut, but properly handles CSV column quoting:
csvfilter -f 1,3,5 in.csv > out.csv
If you have python (and you should), you can install it simply like this:
pip install csvfilter
Please take note that the column indexing in csvfilter starts with 0 (unlike awk, which starts with $1). More info at https://github.com/codeinthehole/csvfilter/
UltimateSAML SSO is an OASIS SAML v1.x and v2.0 specifications compliant .NET toolkit. It offers an elegant and easy way to add support for Single Sign-On and Single-Logout SAML to your ASP.NET, ASP.NET MVC, ASP.NET Core, Desktop, and Service applications. The lightweight library helps you provide SSO access to cloud and intranet websites using a single credentials entry.
A more modern answer for an old question:
MainActivity.kt
private var myMenuIconEnabled by Delegates.observable(true) { _, old, new ->
if (new != old) invalidateOptionsMenu()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.my_button).setOnClickListener { myMenuIconEnabled = false }
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main_activity, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
menu.findItem(R.id.action_my_action).isEnabled = myMenuIconEnabled
return super.onPrepareOptionsMenu(menu)
}
menu_main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_my_action"
android:icon="@drawable/ic_my_icon_24dp"
app:iconTint="@drawable/menu_item_icon_selector"
android:title="My title"
app:showAsAction="always" />
</menu>
menu_item_icon_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="?enabledMenuIconColor" android:state_enabled="true" />
<item android:color="?disabledMenuIconColor" />
attrs.xml
<resources>
<attr name="enabledMenuIconColor" format="reference|color"/>
<attr name="disabledMenuIconColor" format="reference|color"/>
</resources>
styles.xml or themes.xml
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="disabledMenuIconColor">@color/white_30_alpha</item>
<item name="enabledMenuIconColor">@android:color/white</item>
Not gonna happen with CSS only
Inline javascript
<a href='index.html'
onmouseover='this.style.textDecoration="none"'
onmouseout='this.style.textDecoration="underline"'>
Click Me
</a>
In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:
<a href="http://www.w3.org/Style/CSS"
style="{color: blue; background: white} /* a+=0 b+=0 c+=0 */
:visited {color: green} /* a+=0 b+=1 c+=0 */
:hover {background: yellow} /* a+=0 b+=1 c+=0 */
:visited:hover {color: purple} /* a+=0 b+=2 c+=0 */
">
</a>
but it was never implemented in the release of the spec as far as I know.
http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules
vim ~/.bash
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(parse_git_branch)\[\033[00m\] $"
To reflect latest changes run following command
source ~/.bashrc
Output:-
chandrakant@NDL41104 ~/Chandrakant/CodeBase/LaravelApp (development) $
Step 1: Goto your Android sdk folder -> platform tools
and copy the whole path
For example: C:\Program Files (x86)\Android\android-sdk\platform-tools
Step 2: Goto command prompt or Android studio terminal
windows users cd C:\Program Files (x86)\Android\android-sdk\platform-tools
Mac Users /Users/<username>/Library/Android/sdk/platform-tools
and press enter
Step 3: Connect your device & system with same wifi.
Step 4: Type adb tcpip 5555
and press Enter.
Step 5: Type adb connect x.x.x.x:5555
, replacing the x.x.x.x with your phone IP address.
find out phone IP address
Settings -> About phone -> Status
(some phones may be vary)
Note: In case that you connect more than one device, disconnect other phones except the one you need to connect.
1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.
1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.
C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.
You can specify a format string if you don't want to use the e-notation.
I found a solution:
print("My message here");
From Dianne Hackborn:
Things That Cannot Change:
The most obvious and visible of these is the “manifest package name,” the unique name you give to your application in its AndroidManifest.xml. The name uses a Java-language-style naming convention, with Internet domain ownership helping to avoid name collisions. For example, since Google owns the domain “google.com”, the manifest package names of all of our applications should start with “com.google.” It’s important for developers to follow this convention in order to avoid conflicts with other developers.
Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application.
More on things you cannot change here
Regarding your question on the URL from Google Play, the package defined there is linked to the app's fully qualified package you have in your AndroidManifest.xml file. More on Google Play's link formats here.
Use the sorted()
function:
return sorted(dict.iteritems())
If you want an actual iterator over the sorted results, since sorted()
returns a list, use:
return iter(sorted(dict.iteritems()))
Bit late to this...I'm surprised that no one mentioned Symfony's VarDumper
component that Laravel includes, in part, for its dd()
(and lesser-known, dump()
) utility functions.
$dumpMe = new App\User([ 'name' => 'Cy Rossignol' ]);
(new Symfony\Component\VarDumper\Dumper\CliDumper())->dump(
(new Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($dumpMe)
);
There's a bit more code needed, but, in return, we get nice formatted, readable output in the console—especially useful for debugging complex objects or arrays:
App\User {#17 #attributes: array:1 [ "name" => "Cy Rossignol" ] #fillable: array:3 [ 0 => "name" 1 => "email" 2 => "password" ] #guarded: array:1 [ 0 => "*" ] #primaryKey: "id" #casts: [] #dates: [] #relations: [] ... etc ... }
To take this a step further, we can even colorize the output! Add this helper function to the project to save some typing:
function toConsole($var)
{
$dumper = new Symfony\Component\VarDumper\Dumper\CliDumper();
$dumper->setColors(true);
$dumper->dump((new Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($var));
}
If we're running the app behind a full webserver (like Apache or Nginx—not artisan serve
), we can modify this function slightly to send the dumper's prettified output to the log (typically storage/logs/laravel.log):
function toLog($var)
{
$lines = [ 'Dump:' ];
$dumper = new Symfony\Component\VarDumper\Dumper\CliDumper();
$dumper->setColors(true);
$dumper->setOutput(function ($line) use (&$lines) {
$lines[] = $line;
});
$dumper->dump((new Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($var));
Log::debug(implode(PHP_EOL, $lines));
}
...and, of course, watch the log using:
$ tail -f storage/logs/laravel.log
PHP's error_log()
works fine for quick, one-off inspection of simple values, but the functions shown above take the hard work out of debugging some of Laravel's more complicated classes.
If you have data that has HTML tags and you want to display it so that a person can SEE the tags, use HttpServerUtility::HtmlEncode.
If you have data that has HTML tags in it and you want the user to see the tags rendered, then display the text as is. If the text represents an entire web page, use an IFRAME for it.
If you have data that has HTML tags and you want to strip out the tags and just display the unformatted text, use a regular expression.
Usually that will give you the top view, but there's no guarantee that it's visible to the user. It could be off the screen, have an alpha of 0.0, or could be have size of 0x0 for example.
It could also be that the keyWindow has no subviews, so you should probably test for that first. This would be unusual, but it's not impossible.
UIWindow is a subclass of UIView, so if you want to make sure your notification is visible to the user, you can add it directly to the keyWindow using addSubview:
and it will instantly be the top most view. I'm not sure if this is what you're looking to do though. (Based on your question, it looks like you already know this.)
Or simply run this comment to add the server Certificate to your database:
echo $(echo -n | openssl s_client -showcerts -connect yourserver.com:YourHttpGilabPort 2>/dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p') >> /etc/ssl/certs/ca-certificates.crt
Then do git clone again.
You can accomplish this two ways, both of which need to be done through editing your template files.
The first one is just to add an html link to your navigation where ever you want it to show up.
The second (and my guess, the one you're looking for) is to create a new page template, which isn't too difficult if you have the ability to create a new .php file in your theme/template directory. Something like the below code should do:
<?php /*
Template Name: Page Redirect
*/
header('Location: http://www.nameofnewsite.com');
exit();
?>
Where the template name is whatever you want to set it too and the url in the header function is the new url you want to direct a user to. After you modify the above code to meet your needs, save it in a php file in your active theme folder to the template name. So, if you leave the name of your template "Page Redirect" name the php file page-redirect.php.
After that's been saved, log into your WordPress backend, and create a new page. You can add a title and content to the body if you'd like, but the important thing to note is that on the right hand side, there should be a drop down option for you to choose which page template to use, with default showing first. In that drop down list, there should be the name of the new template file to use. Select the new template, publish the page, and you should be golden.
Also, you can do this dynamically as well by using the Custom Fields section below the body editor. If you're interested, let me know and I can paste the code for that guy in a new response.
You can just reverse your log and just head it for the first result.
git log --pretty=oneline --reverse | head -1
You can use the data type point
- combines (x,y)
which can be your lat / long. Occupies 16 bytes: 2 float8
numbers internally.
Or make it two columns of type float
(= float8
or double precision
). 8 bytes each.
Or real
(= float4
) if additional precision is not needed. 4 bytes each.
Or even numeric
if you need absolute precision. 2 bytes for each group of 4 digits, plus 3 - 8 bytes overhead.
Read the fine manual about numeric types and geometric types.
The geometry
and geography
data types are provided by the additional module PostGIS and occupy one column in your table. Each occupies 32 bytes for a point. There is some additional overhead like an SRID in there. These types store (long/lat), not (lat/long).
Start reading the PostGIS manual here.
Just want to add another way of doing this. I've seen multiple people on various related threads ask if you can use VerifyRenderingInServerForm without adding it to the parent page.
You actually can do this but it's a bit of a bodge.
First off create a new Page class which looks something like the following:
public partial class NoRenderPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
public override void VerifyRenderingInServerForm(Control control)
{
//Allows for printing
}
public override bool EnableEventValidation
{
get { return false; }
set { /*Do nothing*/ }
}
}
Does not need to have an .ASPX associated with it.
Then in the control you wish to render you can do something like the following.
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
var page = new NoRenderPage();
page.DesignerInitialize();
var form = new HtmlForm();
page.Controls.Add(form);
form.Controls.Add(pnl);
controlToRender.RenderControl(hw);
Now you've got your original control rendered as HTML. If you need to, add the control back into it's original position. You now have the HTML rendered, the page as normal and no changes to the page itself.
#FFFFEEE
is not a correct color code. Try with #FFFFEE
instead.
I hit this problem because I had: project A (a desktop .exe) refer to project B (a portable .dll). A & B had different versions of JSON.Net, and so there was a loader conflict. Once I made all the versions of JSON.net the same, it worked. (This is in effect what some of the solutions above are doing - I'm just calling out why it works)
Funny, I was doing precisely this yesterday. You just need this in your css file
.ablock table td {
padding:5px;
}
then wrap the table in a suitable div
<div class="ablock ">
<table>
<tr>
<td>
The argument order seems to matter... to exclude subdirectories, I used
robocopy \\source\folder C:\destinationfolder /XD * /MIR
...and that works for me (Windows 10 copy from Windows Server 2016)
If you Want to run Batch Subscribe on a List using Mailchimp API . Then you can use the below function.
/**
* Mailchimp API- List Batch Subscribe added function
*
* @param array $data Passed you data as an array format.
* @param string $apikey your mailchimp api key.
*
* @return mixed
*/
function batchSubscribe(array $data, $apikey)
{
$auth = base64_encode('user:' . $apikey);
$json_postData = json_encode($data);
$ch = curl_init();
$dataCenter = substr($apikey, strpos($apikey, '-') + 1);
$curlopt_url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/batches/';
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic ' . $auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_postData);
$result = curl_exec($ch);
return $result;
}
Function Use And Data format for Batch Operations:
<?php
$apikey = 'Your MailChimp Api Key';
$list_id = 'Your list ID';
$servername = 'localhost';
$username = 'Youre DB username';
$password = 'Your DB password';
$dbname = 'Your DB Name';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
$sql = 'SELECT * FROM emails';// your SQL Query goes here
$result = $conn->query($sql);
$finalData = [];
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$individulData = array(
'apikey' => $apikey,
'email_address' => $row['email'],
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => 'eastwest',
'LNAME' => 'rehab',
)
);
$json_individulData = json_encode($individulData);
$finalData['operations'][] =
array(
"method" => "POST",
"path" => "/lists/$list_id/members/",
"body" => $json_individulData
);
}
}
$api_response = batchSubscribe($finalData, $apikey);
print_r($api_response);
$conn->close();
Also, You can found this code in my Github gist. GithubGist Link
Reference Documentation: Official
A Subscription is an object that represents a disposable resource, usually the execution of an Observable. A Subscription has one important method, unsubscribe, that takes no argument and just disposes of the resource held by the subscription.
import { interval } from 'rxjs';
const observable = interval(1000);
const subscription = observable.subscribe(a=> console.log(a));
/** This cancels the ongoing Observable execution which
was started by calling subscribe with an Observer.*/
subscription.unsubscribe();
A Subscription essentially just has an unsubscribe() function to release resources or cancel Observable executions.
import { interval } from 'rxjs';
const observable1 = interval(400);
const observable2 = interval(300);
const subscription = observable1.subscribe(x => console.log('first: ' + x));
const childSubscription = observable2.subscribe(x => console.log('second: ' + x));
subscription.add(childSubscription);
setTimeout(() => {
// It unsubscribes BOTH subscription and childSubscription
subscription.unsubscribe();
}, 1000);
According to the official documentation, Angular should unsubscribe for you, but apparently, there is a bug.
Cross-platform implementation with Ant
<exec executable="git" outputproperty="currentBranch">
<arg value="rev-parse" />
<arg value="--abbrev-ref" />
<arg value="HEAD" />
</exec>
<exec executable="git" outputproperty="showBranchOutput">
<arg value="show-branch" />
<arg value="-a" />
</exec>
<loadresource property="baseBranch">
<propertyresource name="showBranchOutput"/>
<filterchain>
<linecontains>
<contains value="*"/>
</linecontains>
<linecontains negate="true">
<contains value="${currentBranch}"/>
</linecontains>
<headfilter lines="1"/>
<tokenfilter>
<replaceregex pattern=".*\[(.*)\].*" replace="\1"/>
<replaceregex pattern="[\^~].*" replace=""/>
</tokenfilter>
</filterchain>
</loadresource>
<echo message="${currentBranch} ${baseBranch}" />
To chime in with another solution - I found that the "listen for bounds_changed event and then set new zoom" approach didn't work reliably for me. I think that I was sometimes calling fitBounds
before the map had been fully initialized, and the initialization was causing a bounds_changed event that would use up the listener, before fitBounds
changed the boundaries and zoom level. I ended up with this code, which seems to work so far:
// If there's only one marker, or if the markers are all super close together,
// `fitBounds` can zoom in too far. We want to limit the maximum zoom it can
// use.
//
// `fitBounds` is asynchronous, so we need to wait until the bounds have
// changed before we know what the new zoom is, using an event handler.
//
// Sometimes this handler gets triggered by a different event, before
// `fitBounds` takes effect; that particularly seems to happen if the map
// hasn't been fully initialized yet. So we don't immediately remove the
// listener; instead, we wait until the 'idle' event, and remove it then.
//
// But 'idle' might happen before 'bounds_changed', so we can't set up the
// removal handler immediately. Set it up in the first event handler.
var removeListener = null;
var listener = google.maps.event.addListener(map, 'bounds_changed', () => {
console.log(map.getZoom());
if (map.getZoom() > 15) {
map.setZoom(15);
}
if (!removeListener) {
removeListener = google.maps.event.addListenerOnce(map, 'idle', () => {
console.log('remove');
google.maps.event.removeListener(listener);
});
}
});
Create Dynamic angular variables from results
angular.forEach(results, function (value, key) {
if (key != null) {
$parse(key).assign($scope, value);
}
});
ps. don't forget to pass in the $parse attribute into your controller's function
The file permission is okay (0777) but i think your on the shared server, so to delete your file correctly use; 1. create a correct path to your file
// delete from folder
$filename = 'test.txt';
$ifile = '/newy/made/link/uploads/'. $filename; // this is the actual path to the file you want to delete.
unlink($_SERVER['DOCUMENT_ROOT'] .$ifile); // use server document root
// your file will be removed from the folder
That small code will do the magic and remove any selected file you want from any folder provided the actual file path is collect.
for(int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
or
for(String value : array)
{
System.out.println(value);
}
The second version is a "for-each" loop and it works with arrays and Collections. Most loops can be done with the for-each loop because you probably don't care about the actual index. If you do care about the actual index us the first version.
Just for completeness you can do the while loop this way:
int index = 0;
while(index < myArray.length)
{
final String value;
value = myArray[index];
System.out.println(value);
index++;
}
But you should use a for loop instead of a while loop when you know the size (and even with a variable length array you know the size... it is just different each time).
the following code worked fine for me. kindly check other setting in your web config
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="Login.aspx"/>
</files>
</defaultDocument>
</system.webServer>
If after changing the namespace and the config/auth.php
it still fails, you could try the following:
In the file vendor/composer/autoload_classmap.php
change the line
App\\User' => $baseDir . '/app/User.php',
,
to
App\\Models\\User' => $baseDir . '/app/Models/User.php',
At the beginning of the file app/Services/Registrar.php
change "use App\User" to "App\Models\User"
I did a test on MS SQL 2005 using the following tables: A 400K rows, B 26K rows and C 450 rows.
The estimated query plan indicated that the basic inner join would be 3 times slower than the nested sub-queries, however when actually running the query, the basic inner join was twice as fast as the nested queries, The basic inner join took 297ms on very minimal server hardware.
What database are you using, and what times are you seeing? I'm thinking if you are seeing poor performance then it is probably an index problem.
Updated the Android SDK platform tools using SDK Manager (in Eclipse). Works for me.
I was using localhost
for the address, which was obviously wrong. After replacing it with the IP address of the server (in the network that emulator is), it worked perfectly.
Edit
In Android Emulator, the address of the development machine is 10.0.2.2
. More explanation here
For Genymotion, the address is 10.0.3.2
. More info here
The problem you have is related to TCP streaming nature.
The fact that you sent 100 Bytes (for example) from the server doesn't mean you will read 100 Bytes in the client the first time you read. Maybe the bytes sent from the server arrive in several TCP segments to the client.
You need to implement a loop in which you read until the whole message was received.
Let me provide an example with DataInputStream
instead of BufferedinputStream
. Something very simple to give you just an example.
Let's suppose you know beforehand the server is to send 100 Bytes of data.
In client you need to write:
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
while(!end)
{
int bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length == 100)
{
end = true;
}
}
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
Now, typically the data size sent by one node (the server here) is not known beforehand. Then you need to define your own small protocol for the communication between server and client (or any two nodes) communicating with TCP.
The most common and simple is to define TLV: Type, Length, Value. So you define that every message sent form server to client comes with:
So you know you have to receive a minimum of 2 Bytes and with the second Byte you know how many following Bytes you need to read.
This is just a suggestion of a possible protocol. You could also get rid of "Type".
So it would be something like:
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
int bytesRead = 0;
messageByte[0] = in.readByte();
messageByte[1] = in.readByte();
int bytesToRead = messageByte[1];
while(!end)
{
bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length == bytesToRead )
{
end = true;
}
}
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
The following code compiles and looks better. It assumes the first two bytes providing the length arrive in binary format, in network endianship (big endian). No focus on different encoding types for the rest of the message.
import java.nio.ByteBuffer;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
class Test
{
public static void main(String[] args)
{
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
Socket clientSocket;
ServerSocket server;
server = new ServerSocket(30501, 100);
clientSocket = server.accept();
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
int bytesRead = 0;
messageByte[0] = in.readByte();
messageByte[1] = in.readByte();
ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);
int bytesToRead = byteBuffer.getShort();
System.out.println("About to read " + bytesToRead + " octets");
//The following code shows in detail how to read from a TCP socket
while(!end)
{
bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length() == bytesToRead )
{
end = true;
}
}
//All the code in the loop can be replaced by these two lines
//in.readFully(messageByte, 0, bytesToRead);
//dataString = new String(messageByte, 0, bytesToRead);
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
From Apache Commons library:
import org.apache.commons.lang3.StringUtils
Use:
StringUtils.join(slist, ',');
Another similar question and answer here
If you want to remove an item, the following will be a bit more efficient.
std::vector<int> v;
auto it = std::find(v.begin(), v.end(), 5);
if(it != v.end())
v.erase(it);
or you may avoid overhead of moving the items if the order does not matter to you:
std::vector<int> v;
auto it = std::find(v.begin(), v.end(), 5);
if (it != v.end()) {
using std::swap;
// swap the one to be removed with the last element
// and remove the item at the end of the container
// to prevent moving all items after '5' by one
swap(*it, v.back());
v.pop_back();
}
Are you looking for something like this?
SELECT CASE WHEN LEFT(created_ts, 1) LIKE '[0-9]'
THEN CONVERT(VARCHAR(10), CONVERT(datetime, created_ts, 1), 101)
ELSE CONVERT(VARCHAR(10), CONVERT(datetime, created_ts, 109), 101)
END created_ts
FROM table1
Output:
| CREATED_TS | |------------| | 02/20/2012 | | 11/29/2012 | | 02/20/2012 | | 11/29/2012 | | 02/20/2012 | | 11/29/2012 | | 11/16/2011 | | 02/20/2012 | | 11/29/2012 |
Here is SQLFiddle demo
I prefer to use
pushd d:\windows\movie
because it requires no switches yet the working directory will change to the correct drive and path in one step.
Added plus:
popd
. If you're checking for explicit types, why are you declaring those variables as T
's?
T HowToCast<T>(T t)
{
if (typeof(T) == typeof(string))
{
var newT1 = "some text";
var newT2 = t; //this builds but I'm not sure what it does under the hood.
var newT3 = t.ToString(); //for sure the string you want.
}
return t;
}
I got this error(classNotFoundException for main class), I actually changed pom version , so did maven install again and then error vanished.
Have you tried beforeUnload? This event fires immediately before the page responds to a navigation request, and this should include the modification of the href.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<META NAME="Generator" CONTENT="TextPad 4.6">
<META NAME="Author" CONTENT="?">
<META NAME="Keywords" CONTENT="?">
<META NAME="Description" CONTENT="?">
</HEAD>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(window).unload(
function(event) {
alert("navigating");
}
);
$("#theButton").click(
function(event){
alert("Starting navigation");
window.location.href = "http://www.bbc.co.uk";
}
);
});
</script>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#FF0000" VLINK="#800000" ALINK="#FF00FF" BACKGROUND="?">
<button id="theButton">Click to navigate</button>
<a href="http://www.google.co.uk"> Google</a>
</BODY>
</HTML>
Beware, however, that your event will fire whenever you navigate away from the page, whether this is because of the script, or somebody clicking on a link. Your real challenge, is detecting the different reasons for the event being fired. (If this is important to your logic)
In practice, it usually decides to do a garbage collection. The answer varies depending on lots of factors, like which JVM you're running on, which mode it's in, and which garbage collection algorithm it's using.
I wouldn't depend on it in your code. If the JVM is about to throw an OutOfMemoryError, calling System.gc() won't stop it, because the garbage collector will attempt to free as much as it can before it goes to that extreme. The only time I've seen it used in practice is in IDEs where it's attached to a button that a user can click, but even there it's not terribly useful.
Use prepared statements, they have methods to set correctly parameters for each native Java type.
Accepted answer of Kapil is flawed, it will update more than one record if there are 2 or more than one records available with same timestamps, not a true top 1 query.
;With cte as (
SELECT TOP(1) email_fk FROM abc WHERE id= 177 ORDER BY created DESC
)
UPDATE cte SET email_fk = 10
Ref Remus Rusanu Ans:- SQL update top1 row query
your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?
since function is first-class citizen, you can write small wrapper (from Alex answers)
def repeat(f, N):
for _ in itertools.repeat(None, N): f()
then you can pass function as argument.
From https://gist.github.com/1180489
function pad(a, b){
return(1e15 + a + '').slice(-b);
}
With comments:
function pad(
a, // the number to convert
b // number of resulting characters
){
return (
1e15 + a + // combine with large number
"" // convert to string
).slice(-b) // cut leading "1"
}
On this page, the Arduino sketch defines a couple of Structs (plus a couple of methods) which are then called in the setup loop and main loop. Simple enough to interpret, even for a barely-literate programmer like me.
For child component to show I was using *ngif="selectedState == 1"
Instead of that I used [hidden]="selectedState!=1"
It worked for me.. loading the child component properly and after hide and un-hide child component was not undefined after using this.
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/