As others have pointed out, you are modifying a collection that you are iterating over and that's what's causing the error. The offending code is below:
foreach (KeyValuePair<int, int> kvp in rankings)
{
.....
if((double)(similarModules/modules.Count)>0.6)
{
rankings[kvp.Key] = rankings[kvp.Key] + 4; // <--- This line is the problem
}
.....
What may not be obvious from the code above is where the Enumerator
comes from. In a blog post from a few years back about Eric Lippert provides an example of what a foreach
loop gets expanded to by the compiler. The generated code will look something like:
{
IEnumerator<int> e = ((IEnumerable<int>)values).GetEnumerator(); // <-- This
// is where the Enumerator
// comes from.
try
{
int m; // OUTSIDE THE ACTUAL LOOP in C# 4 and before, inside the loop in 5
while(e.MoveNext())
{
// loop code goes here
}
}
finally
{
if (e != null) ((IDisposable)e).Dispose();
}
}
If you look up the MSDN documentation for IEnumerable (which is what GetEnumerator()
returns) you will see:
Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.
Which brings us back to what the error message states and the other answers re-state, you're modifying the underlying collection.
I have spend all day to solve this error since none of the answers worked for me.
I found out that oracle virtual box doesn't install the network adapter correctly in windows 8.1
Solution:
C:\Program Files\Oracle\VirtualBox\drivers\network\netadp\VBoxNetAdp.inf
)Now that virtual box adapters is installed correctly, it needs to be setup correctly. (the following solution is like many other solution in here)
192.168.56.1
mask 255.255.255.0
192.168.56.100
server Mask: 255.255.255.0
low address bound: 192.168.56.101
upper adress bound 192.168.56.254
I've long wanted to be able to produce tints/shades of colours, here is my JavaScript solution:
const varyHue = function (hueIn, pcIn) {
const truncate = function (valIn) {
if (valIn > 255) {
valIn = 255;
} else if (valIn < 0) {
valIn = 0;
}
return valIn;
};
let red = parseInt(hueIn.substring(0, 2), 16);
let green = parseInt(hueIn.substring(2, 4), 16);
let blue = parseInt(hueIn.substring(4, 6), 16);
let pc = parseInt(pcIn, 10); //shade positive, tint negative
let max = 0;
let dif = 0;
max = red;
if (pc < 0) { //tint: make lighter
if (green < max) {
max = green;
}
if (blue < max) {
max = blue;
}
dif = parseInt(((Math.abs(pc) / 100) * (255 - max)), 10);
return leftPad(((truncate(red + dif)).toString(16)), '0', 2) + leftPad(((truncate(green + dif)).toString(16)), '0', 2) + leftPad(((truncate(blue + dif)).toString(16)), '0', 2);
} else { //shade: make darker
if (green > max) {
max = green;
}
if (blue > max) {
max = blue;
}
dif = parseInt(((pc / 100) * max), 10);
return leftPad(((truncate(red - dif)).toString(16)), '0', 2) + leftPad(((truncate(green - dif)).toString(16)), '0', 2) + leftPad(((truncate(blue - dif)).toString(16)), '0', 2);
}
};
Use google GSON library for this
public static <T> T getObject(final String jsonString, final Class<T> objectClass) {
Gson gson = new Gson();
return gson.fromJson(jsonString, objectClass);
}
http://iandjava.blogspot.in/2014/01/java-object-to-json-and-json-to-java.html
Since there are no events available to signal when the socket is disconnected, you will have to poll it at a frequency that is acceptable to you.
Using this extension method, you can have a reliable method to detect if a socket is disconnected.
static class SocketExtensions
{
public static bool IsConnected(this Socket socket)
{
try
{
return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
}
catch (SocketException) { return false; }
}
}
You can do that via the Storyboard too:
In the properties for your pydev project, there's a pane called "PyDev - PYTHONPATH", with a sub-pane called "External Libraries". You can add source folders (any folder that has an __init__.py
) to the path using that pane. Your project code will then be able to import modules from those source folders.
Although the accepted answer works fine, since v0.21.0rc1 it gives a warning
UserWarning: Pandas doesn't allow columns to be created via a new attribute name
Instead, one can do
df[["X", "A", "B", "C"]].plot(x="X", kind="bar")
How (and why) to use display: table-cell (CSS)
I just wanted to mention, since I don't think any of the other answers did directly, that the answer to "why" is: there is no good reason, and you should probably never do this.
In my over a decade of experience in web development, I can't think of a single time I would have been better served to have a bunch of <div>
s with display
styles than to just have table elements.
The only hypothetical I could come up with is if you have tabular data stored in some sort of non-HTML-table format (eg. a CSV file). In a very specific version of this case it might be easier to just add <div>
tags around everything and then add descendent-based styles, instead of adding actual table tags.
But that's an extremely contrived example, and in all real cases I know of simply using table tags would be better.
If you're only getting these to manually pass into df.set_index()
, that's unnecessary. Just directly do df.set_index['your_col_name', drop=False]
, already.
It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.
If you wanna update a table with that DateTime, you can use your SQL string like this example:
int fieldId;
DateTime myDateTime = DateTime.Now
string sql = string.Format(@"UPDATE TableName SET DateFieldName='{0}' WHERE FieldID={1}", myDateTime.ToString("yyyy-MM-dd HH:mm:ss"), fieldId.ToString());
There are a few programs you can use. You will get the actual Java code, but sometimes the code will have been obfuscated so methods are named by one letter or number or a random mix of letters and numbers.
I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).
e.g. (from the doc)
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
Put it in the init()
function for your plugin.
function your_namespace() {
wp_register_style('your_namespace', plugins_url('style.css',__FILE__ ));
wp_enqueue_style('your_namespace');
wp_register_script( 'your_namespace', plugins_url('your_script.js',__FILE__ ));
wp_enqueue_script('your_namespace');
}
add_action( 'admin_init','your_namespace');
It took me also some time before I found the (for me) best solution which is foolproof imho.
Cheers
If you want to check the current device whether its iPad or iPhone then you can use these line of code :
if(UIDevice.currentDevice().userInterfaceIdiom == .Pad){
}else if(UIDevice.currentDevice().userInterfaceIdiom == .Phone){
}
Your suggestion would work, but using a Do loop might be a little more readable.
This is actually an idiom in C - instead of using a goto, you can have a do { } while (0) loop with a break statement if you want to bail out of the construct early.
Dim i
For i = 0 To 10
Do
If i = 4 Then Exit Do
WScript.Echo i
Loop While False
Next
As crush suggests, it looks a little better if you remove the extra indentation level.
Dim i
For i = 0 To 10: Do
If i = 4 Then Exit Do
WScript.Echo i
Loop While False: Next
I've made my own utility function to check several strings at once, rather than having an if statement full of if(str != null && !str.isEmpty && str2 != null && !str2.isEmpty)
. This is the function:
public class StringUtils{
public static boolean areSet(String... strings)
{
for(String s : strings)
if(s == null || s.isEmpty)
return false;
return true;
}
}
so I can simply write:
if(!StringUtils.areSet(firstName,lastName,address)
{
//do something
}
I found this method in the documentation for the DictionaryBase class on MSDN:
foreach (DictionaryEntry de in myDictionary)
{
//Do some stuff with de.Value or de.Key
}
This was the only one I was able to get functioning correctly in a class that inherited from the DictionaryBase.
As per James Newton King: If you create the serializer yourself rather than using JavaScriptConvert there is a NullValueHandling
property which you can set to ignore.
Here's a sample:
JsonSerializer _jsonWriter = new JsonSerializer {
NullValueHandling = NullValueHandling.Ignore
};
Alternatively, as suggested by @amit
JsonConvert.SerializeObject(myObject,
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
I solved this error message by fixing the path to the virtual machines folder (Setting > VirtualBox - Virtual devices). Yes, I had broken settings...
why not to take advantage of modern browsers css transition and make things simpler and fast using more css and less jquery
Here is the code for sliding up and down
Here is the code for sliding left to right
Similarly we can change the sliding from top to bottom or right to left by changing transform-origin and transform: scaleX(0) or transform: scaleY(0) appropriately.
For a <input type='text'>
element:
input { font-size: 18px; }
or for a <textarea>
:
textarea { font-size: 18px; }
or for a <select>
:
select { font-size: 18px; }
you get the drift.
When buffer size gets full. There are several options you can try:
1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000
2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.
3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.
DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output
You can also create your custom output display.something like below snippets
create or replace procedure cust_output(input_string in varchar2 )
is
out_string_in long default in_string;
string_lenth number;
loop_count number default 0;
begin
str_len := length(out_string_in);
while loop_count < str_len
loop
dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) );
loop_count := loop_count +255;
end loop;
end;
Link -Ref :Alternative to dbms_output.putline @ By: Alexander
According to this course, the correct way to do this is:
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
)
This will give you the root path for the gallery directory.
Try this (using default keyword)
bool foo = default(bool); if (foo) { }
As I observed in my code. If once the value is fetched of body from Response, its become blank.
String str = response.body().string(); // {response:[]}
String str1 = response.body().string(); // BLANK
So I believe after fetching once the value from body, it become empty.
Suggestion : Store it in String, that can be used many time.
While @nickf's answer works. If you don't care for older browsers, you can use this pure Javascript version. Works in IE9+, and others
var rect = el.getBoundingClientRect();
var position = {
top: rect.top + window.pageYOffset,
left: rect.left + window.pageXOffset
};
You can use CreateTextFile or OpenTextFile method, both have an attribute "unicode" usefull for encoding settings.
object.CreateTextFile(filename[, overwrite[, unicode]])
object.OpenTextFile(filename[, iomode[, create[, format]]])
Example: Overwrite:
CreateTextFile:
fileName = "filename"
Set fso = CreateObject("Scripting.FileSystemObject")
Set out = fso.CreateTextFile(fileName, True, True)
out.WriteLine ("Hello world!")
...
out.close
Example: Append:
OpenTextFile Set fso = CreateObject("Scripting.FileSystemObject")
Set out = fso.OpenTextFile("filename", ForAppending, True, 1)
out.Write "Hello world!"
...
out.Close
See more on MSDN docs
The pathname for a file or directory is specified using the naming conventions of the host system. However, the File class defines platform-dependent constants that can be used to handle file and directory names in a platform-independent way.
Files.seperator defines the character or string that separates the directory and the file com- ponents in a pathname. This separator is '/', '\' or ':' for Unix, Windows, and Macintosh, respectively.
If you want to use the new current standard, you can do so:
sub.emplace_back ("Math", 70, 0);
or
sub.push_back ({"Math", 70, 0});
These don't require default construction of subject
.
With ASP.NET 5 there is no Request variable available anymore. You can access it now with Context.Request
Also there is no IsAjaxRequest() Method anymore, you have to write it by yourself, for example in Extensions\HttpRequestExtensions.cs
using System;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Mvc
{
public static class HttpRequestExtensions
{
public static bool IsAjaxRequest(this HttpRequest request)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
return (request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest");
}
}
}
I searched for a while now on this and hope that will help some others too ;)
Code summary:
using System.Windows.Forms;
...
MessageBox.Show( "hello world" );
Also (as per this other stack post): In Visual Studio expand the project in Solution Tree, right click on References, Add Reference, Select System.Windows.Forms
on Framework tab. This will get the MessageBox working in conjunction with the using System.Windows.Forms reference from above.
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollingFinished(scrollView: scrollView)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate {
//didEndDecelerating will be called for sure
return
}
scrollingFinished(scrollView: scrollView)
}
func scrollingFinished(scrollView: UIScrollView) {
// Your code
}
You have extra spaces after END;
that cause the heredoc not terminated.
I was facing the same issue in bitbucket, and this worked for me:
line1
##<2 white spaces><enter>
line2
This Java code should work inside a boolean method:
Note: You only need to check the first half of the characters with the back half, otherwise you are overlapping and doubling the amount of checks that need to be made.
private static boolean doPal(String test) {
for(int i = 0; i < test.length() / 2; i++) {
if(test.charAt(i) != test.charAt(test.length() - 1 - i)) {
return false;
}
}
return true;
}
Take a look at UrlRewriteFilter which is essentially a java-based implementation of Apache's mod_rewrite.
You'll need to extract it into ROOT
folder under your Tomcat's webapps
folder; you can then configure redirects to any other context within its WEB-INF/urlrewrite.xml
configuration file.
OK, Firefox 7 implemented text-overflow: ellipsis
as well as text-overflow: "string"
. Final release is planned for 2011-09-27.
According to the fine manual, createConnection()
can be used to connect to multiple databases.
However, you need to create separate models for each connection/database:
var conn = mongoose.createConnection('mongodb://localhost/testA');
var conn2 = mongoose.createConnection('mongodb://localhost/testB');
// stored in 'testA' database
var ModelA = conn.model('Model', new mongoose.Schema({
title : { type : String, default : 'model in testA database' }
}));
// stored in 'testB' database
var ModelB = conn2.model('Model', new mongoose.Schema({
title : { type : String, default : 'model in testB database' }
}));
I'm pretty sure that you can share the schema between them, but you have to check to make sure.
The while increments the i. So you get:
data[1][0]
data[2][0]
data[3][0]
...
It looks like name doesn't match any of the the elements of data. So, the while still increments and you reach the end of the array. I'll suggest to use for loop.
The problem with your query is that in CASE
expressions, the THEN
and ELSE
parts have to have an expression that evaluates to a number or a varchar or any other datatype but not to a boolean value.
You just need to use boolean logic (or rather the ternary logic that SQL uses) and rewrite it:
WHERE
DateDropped = 0
AND ( @JobsOnHold = 1 AND DateAppr >= 0
OR (@JobsOnHold <> 1 OR @JobsOnHold IS NULL) AND DateAppr <> 0
)
ser.read(64)
should be ser.read(size=64)
; ser.read uses keyword arguments, not positional.
Also, you're reading from the port twice; what you probably want to do is this:
i=0
for modem in PortList:
for port in modem:
try:
ser = serial.Serial(port, 9600, timeout=1)
ser.close()
ser.open()
ser.write("ati")
time.sleep(3)
read_val = ser.read(size=64)
print read_val
if read_val is not '':
print port
except serial.SerialException:
continue
i+=1
I asked my developers to create a JavaScript variable "isProcessing" that I can access (in the "ae" object) that they set when things start running and clear when things are done. I then run it in an accumulator that checks it every 100 ms until it gets five in a row for a total of 500 ms without any changes. If 30 seconds pass, I throw an exception because something should have happened by then. This is in C#.
public static void WaitForDocumentReady(this IWebDriver driver)
{
Console.WriteLine("Waiting for five instances of document.readyState returning 'complete' at 100ms intervals.");
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
int i = 0; // Count of (document.readyState === complete) && (ae.isProcessing === false)
int j = 0; // Count of iterations in the while() loop.
int k = 0; // Count of times i was reset to 0.
bool readyState = false;
while (i < 5)
{
System.Threading.Thread.Sleep(100);
readyState = (bool)jse.ExecuteScript("return ((document.readyState === 'complete') && (ae.isProcessing === false))");
if (readyState) { i++; }
else
{
i = 0;
k++;
}
j++;
if (j > 300) { throw new TimeoutException("Timeout waiting for document.readyState to be complete."); }
}
j *= 100;
Console.WriteLine("Waited " + j.ToString() + " milliseconds. There were " + k + " resets.");
}
To specify both font size and rotation at the same time, try this:
plt.xticks(fontsize=14, rotation=90)
As DAY_OF_WEEK in GregorianCalender class is a static field you can access it directly as foolows
int dayOfWeek = GregorianCalender.DAY_OF_WEEK;
I found another solution for this problem. This looks like another bug in WebKit (or probably Chrome), but it works. All you need to do - is to add a WebKit CSS Mask to the #wrapper element. You can use a single pixel png image and even include it to the CSS to save a HTTP request.
#wrapper {
width: 300px; height: 300px;
border-radius: 100px;
overflow: hidden;
position: absolute; /* this breaks the overflow:hidden in Chrome/Opera */
/* this fixes the overflow:hidden in Chrome */
-webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
}
#box {
width: 300px; height: 300px;
background-color: #cde;
}?
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set
is needed because TextRange
is a class, so hyperLinkText
is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.
I've just received this error.
I created a github repository after creating my local git repository so I needed to accept the changes into local before pushing to github. In this case the only change was the readme file created as optional step when creating github repository.
git pull https://github.com/*username*/*repository*.git master
repository URL is got from here on project github page :
I then re-initialised (this may not be needed)
git init
git add .
git commit -m "update"
Then push :
git push
If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:
PARAMETERS SomeParam Text(10);
SELECT Field FROM Table
WHERE OtherField=SomeParam
You can also say:
CREATE PROCEDURE ProcedureName
(Parameter1 datatype, Parameter2 datatype) AS
SQLStatement
From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs
Note that the procedure contains only one statement.
Likewise, here's a 2nd caveat to @Artif3x elaboration of @max-malysh's excellent answer, both above.
With any delayed application of transactions from the master the follower(s) will have an older, stale view of the data. Therefore while providing time for the query on the follower to finish by setting max_standby_archive_delay and max_standby_streaming_delay makes sense, keep both of these caveats in mind:
If the value of the follower for backup ends up being too much in conflict with hosting queries, one solution would be multiple followers, each optimized for one or the other.
Also, note that several queries in a row can cause the application of wal entries to keep being delayed. So when choosing the new values, it’s not just the time for a single query, but a moving window that starts whenever a conflicting query starts, and ends when the wal entry is finally applied.
Something like this might be the easiest way.
<a href="mailto:?subject=I wanted you to see this site&body=Check out this site http://www.website.com."
title="Share by Email">
<img src="http://png-2.findicons.com/files/icons/573/must_have/48/mail.png">
</a>
You could find another email image and add that if you wanted.
Using Daniel López Localle answer, I created this class in Kotlin. Hope it save you more time
class DynamicHeightViewPager @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ViewPager(context, attrs) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var heightMeasureSpec = heightMeasureSpec
var height = 0
for (i in 0 until childCount) {
val child = getChildAt(i)
child.measure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
val h = child.measuredHeight
if (h > height) height = h
}
if (height != 0) {
heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}}
From documentation:
To comply with the
SQL
standard,IN
returnsNULL
not only if the expression on the left hand side isNULL
, but also if no match is found in the list and one of the expressions in the list isNULL
.
This is exactly your case.
Both IN
and NOT IN
return NULL
which is not an acceptable condition for WHERE
clause.
Rewrite your query as follows:
SELECT *
FROM match m
WHERE NOT EXISTS
(
SELECT 1
FROM email e
WHERE e.id = m.id
)
I used this on a few projects, I don't believe I've run into issues, but I'm sure it's not exhaustive:
$text = preg_replace(
'#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i',
"'<a href=\"$1\" target=\"_blank\">$3</a>$4'",
$text
);
Most of the random junk at the end is to deal with situations like http://domain.com.
in a sentence (to avoid matching the trailing period). I'm sure it could be cleaned up but since it worked. I've more or less just copied it over from project to project.
I find solution here http://deer.org.ua/2009/10/06/1/
class Encoding
{
/**
* http://deer.org.ua/2009/10/06/1/
* @param $string
* @return null
*/
public static function detect_encoding($string)
{
static $list = ['utf-8', 'windows-1251'];
foreach ($list as $item) {
try {
$sample = iconv($item, $item, $string);
} catch (\Exception $e) {
continue;
}
if (md5($sample) == md5($string)) {
return $item;
}
}
return null;
}
}
$content = file_get_contents($file['tmp_name']);
$encoding = Encoding::detect_encoding($content);
if ($encoding != 'utf-8') {
$result = iconv($encoding, 'utf-8', $content);
} else {
$result = $content;
}
I think that @ is bad decision, and make some changes to solution from deer.org.ua;
If you use IIS Express via Visual Studio instead of the builtin ASP.net host, you can achieve this.
You can just use padding. Like so:
http://jsfiddle.net/davidja/KG8Kv/
HTML
<table>
<tr>
<td>item1</td>
<td>item2</td>
<td>item2</td>
</tr>
</table>
CSS
td {padding:10px 25px 10px 25px;}
OR
tr td:first-child {padding-left:0px;}
td {padding:10px 0px 10px 50px;}
The problem is that the body of the page isn't actually visible. The DIVs under have width of 100% and have background colors themselves that override the body CSS.
To Fix the no-man's land, this might work. It's not elegant, but works.
#doc3 {
margin: auto 10px;
width: auto;
height: 2000px;
background-color: yellow;
}
Perhaps you can do it while registering your root
with RouterModule
. You can pass a second object with property useHash:true
like the below:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ROUTES } from './app.routes';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
RouterModule.forRoot(ROUTES ,{ useHash: true }),],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
Best solution: Goto jboss-as-7.1.1.Final\standalone\deployments folder and delete all existing files....
Run again your problem will be solved
Handy with error_log() if you're outputting multiple lines.
I've found a lot of debug statements look weird on my windows install since the developers have assumed unix endings when breaking up strings.
You can apply the atuto_increment constraint to the data column by the following query:
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
But, if the columns are part of a foreign key constraint you, will most probably receive an error. Therefore, it is advised to turn off foreign_key_checks by using the following query:
SET foreign_key_checks = 0;
Therefore, use the following query instead:
SET foreign_key_checks = 0;
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
SET foreign_key_checks = 1;
Just add click event by jquery in $(document).ready() like :
$(document).ready(function(){
$('#YourControlID').click(function(){
if(Check your condtion)
{
$.messager.show({
title:'My Title',
msg:'The message content',
showType:'fade',
style:{
right:'',
bottom:''
}
});
}
});
});
I recommend you to use an unordered list for your image gallery.
You should use my code unless you want the image to gain instantly 50% opacity after you hover out. You will have a smoother transition.
#photos li {
opacity: .5;
transition: opacity .5s ease-out;
-moz-transition: opacity .5s ease-out;
-webkit-transition: opacity .5s ease-out;
-o-transition: opacity .5s ease-out;
}
#photos li:hover {
opacity: 1;
}
Only this realy reloads page (Today)
<input type="button" value="Refresh Page" onClick="location.href=location.href">
Others do not exactly reload. They keep values inside text boxes.
If you using Python 2 or want to rewrite java code. Their is not real solution for this. Here is what I get working in a night: https://github.com/FlorianSteenbuck/python-generics I still get no compiler so you currently using it like that:
class A(GenericObject):
def __init__(self, *args, **kwargs):
GenericObject.__init__(self, [
['b',extends,int],
['a',extends,str],
[0,extends,bool],
['T',extends,float]
], *args, **kwargs)
def _init(self, c, a, b):
print "success c="+str(c)+" a="+str(a)+" b="+str(b)
TODOs
<? extends List<Number>>
)super
support?
supportI have posted my answer to another post with the same question with this one.
From Apple iOS7 transition Guide, https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/TransitionGuide/AppearanceCustomization.html#//apple_ref/doc/uid/TP40013174-CH15-SW1
Specifically automaticallyAdjustsScrollViewInsets=YES
and set self.edgesForExtendedLayout = UIRectEdgeNone
works for me when I don't want to the overlap and I have a tableviewcontroller
.
I enclosed C++ code for grabbing frames. It requires OpenCV version 2.0 or higher. The code uses cv::mat structure which is preferred to old IplImage structure.
#include "cv.h"
#include "highgui.h"
#include <iostream>
int main(int, char**) {
cv::VideoCapture vcap;
cv::Mat image;
const std::string videoStreamAddress = "rtsp://cam_address:554/live.sdp";
/* it may be an address of an mjpeg stream,
e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */
//open the video stream and make sure it's opened
if(!vcap.open(videoStreamAddress)) {
std::cout << "Error opening video stream or file" << std::endl;
return -1;
}
//Create output window for displaying frames.
//It's important to create this window outside of the `for` loop
//Otherwise this window will be created automatically each time you call
//`imshow(...)`, which is very inefficient.
cv::namedWindow("Output Window");
for(;;) {
if(!vcap.read(image)) {
std::cout << "No frame" << std::endl;
cv::waitKey();
}
cv::imshow("Output Window", image);
if(cv::waitKey(1) >= 0) break;
}
}
Update You can grab frames from H.264 RTSP streams. Look up your camera API for details to get the URL command. For example, for an Axis network camera the URL address might be:
// H.264 stream RTSP address, where 10.10.10.10 is an IP address
// and 554 is the port number
rtsp://10.10.10.10:554/axis-media/media.amp
// if the camera is password protected
rtsp://username:[email protected]:554/axis-media/media.amp
It's usually happen by config file corrupt or wrong detect. Just delete .vs folder, restart VS to reset config. It will work almost case
If you are using phpmyadmin to add new routine then don't forget to wrap your code between BEGIN and END
I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.
I just made two changes and I don't which help.
Go to IIS 6 Manager
Select properties of SMTP server
On tab Access, select Relays
Add your public IP address
Close the dialog and on the same tab click to Authentication button.
Add Integrated Windows Authentication
Maybe some step is not needed, but it works.
How about just > Format only cells that contain - in the drop down box select Blanks
For Bootstrap 4 I find the following very handy because:
It is the combination of col and col-auto which does the magic. So you don't have to define a col width (like col-2,...)
<div class="row">
<div class="col">Left</div>
<div class="col-auto">Right</div>
</div>
Ideal for aligning words, icons, buttons,... to the right.
An example to have this responsive on small devices:
<div class="row">
<div class="col">Left</div>
<div class="col-12 col-sm-auto">Right (Left on small)</div>
</div>
Check this Fiddle https://jsfiddle.net/Julesezaar/tx08zveL/
in my opinion the easiest way would be somthing like this:
<?php>
echo '<a href="link.php?submit='.$value.'">Submit</a>';
</?>
within the "link.php" you can request the value like this:
$_REQUEST['submit']
Use my extensions :
Number.prototype.isEven=function(){
return this % 2===0;
};
Number.prototype.isOdd=function(){
return !this.isEven();
}
then
var a=5;
a.isEven();
==False
a.isOdd();
==True
if you are not sure if it is a Number , test it by the following branching :
if(a.isOdd){
a.isOdd();
}
UPDATE :
if you would not use variable :
(5).isOdd()
It turns out that Procedural paradigm is better than OOP paradigm . By the way , i performed profiling in this FIDDLE . However , OOP way is still prettiest .
The solution for me was to install the oracle unlimited JCE and install in JRE_HOME/lib/security. Then restarted glassfish and I was able to connect to my sftp server using jsch.
First install pillow
pip install pillow
Example
from PIL import Image, ImageDraw, ImageFont
image = Image.open('Focal.png')
width, height = image.size
draw = ImageDraw.Draw(image)
text = 'https://devnote.in'
textwidth, textheight = draw.textsize(text)
margin = 10
x = width - textwidth - margin
y = height - textheight - margin
draw.text((x, y), text)
image.save('devnote.png')
# optional parameters like optimize and quality
image.save('optimized.png', optimize=True, quality=50)
This should do the trick.
<activity ... android:launchMode="singleTop" />
When you create an intent to start the app use:
Intent intent= new Intent(context, YourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
This is that should be needed.
Zip the two lists together, sort it, then take the parts you want:
>>> yx = zip(Y, X)
>>> yx
[(0, 'a'), (1, 'b'), (1, 'c'), (0, 'd'), (1, 'e'), (2, 'f'), (2, 'g'), (0, 'h'), (1, 'i')]
>>> yx.sort()
>>> yx
[(0, 'a'), (0, 'd'), (0, 'h'), (1, 'b'), (1, 'c'), (1, 'e'), (1, 'i'), (2, 'f'), (2, 'g')]
>>> x_sorted = [x for y, x in yx]
>>> x_sorted
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
Combine these together to get:
[x for y, x in sorted(zip(Y, X))]
As of April 2018, Chrome's autoplay policies changed:
"Chrome's autoplay policies are simple:
Autoplay with sound is allowed if:
Also
Chrome's developer site has more information, including some programming examples, which can be found here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
/// <summary>
/// Returns a new conContractorEntity instance filled with the DataReader's current record data
/// </summary>
protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
{
return new conContractorEntity()
{
ConId = reader["conId"].ToString().Length > 0 ? int.Parse(reader["conId"].ToString()) : 0,
ConEmail = reader["conEmail"].ToString(),
ConCopyAdr = reader["conCopyAdr"].ToString().Length > 0 ? bool.Parse(reader["conCopyAdr"].ToString()) : true,
ConCreateTime = reader["conCreateTime"].ToString().Length > 0 ? DateTime.Parse(reader["conCreateTime"].ToString()) : DateTime.MinValue
};
}
OR
/// <summary>
/// Returns a new conContractorEntity instance filled with the DataReader's current record data
/// </summary>
protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
{
return new conContractorEntity()
{
ConId = GetValue<int>(reader["conId"]),
ConEmail = reader["conEmail"].ToString(),
ConCopyAdr = GetValue<bool>(reader["conCopyAdr"], true),
ConCreateTime = GetValue<DateTime>(reader["conCreateTime"])
};
}
// Base methods
protected T GetValue<T>(object obj)
{
if (typeof(DBNull) != obj.GetType())
{
return (T)Convert.ChangeType(obj, typeof(T));
}
return default(T);
}
protected T GetValue<T>(object obj, object defaultValue)
{
if (typeof(DBNull) != obj.GetType())
{
return (T)Convert.ChangeType(obj, typeof(T));
}
return (T)defaultValue;
}
Anyone looking for this functionality past 2018: it's much cleaner to do this with just CSS using position: sticky.
position: sticky doesn't work with some table elements (thead/tr) in Chrome. You can move sticky to tds/ths of tr you need to be sticky. Like this:
thead tr:nth-child(1) th {
background: white;
position: sticky;
top: 0;
z-index: 10;
}
The sender is of type ListView not ListViewItem.
private void listViewTriggers_MouseDoubleClick(object sender, MouseEventArgs e)
{
ListView triggerView = sender as ListView;
if (triggerView != null)
{
btnEditTrigger_Click(null, null);
}
}
I use something like this:
if schema_id('newSchema') is null
exec('create schema newSchema');
The advantage is if you have this code in a long sql-script you can always execute it with the other code, and its short.
The sample mvcmusicstore.codeplex.com opened in vs2015 missed some references, one of them System.web.mvc.
The fix for this was to remove it from the references and to add a reference: choose Extentions under Assemblies, there you can find and add System.Web.Mvc.
(The other assemblies I added with the nuget packages.)
You can access multiple columns by passing a list of column indices to dataFrame.ix.
For example:
>>> df = pandas.DataFrame({
'a': np.random.rand(5),
'b': np.random.rand(5),
'c': np.random.rand(5),
'd': np.random.rand(5)
})
>>> df
a b c d
0 0.705718 0.414073 0.007040 0.889579
1 0.198005 0.520747 0.827818 0.366271
2 0.974552 0.667484 0.056246 0.524306
3 0.512126 0.775926 0.837896 0.955200
4 0.793203 0.686405 0.401596 0.544421
>>> df.ix[:,[1,3]]
b d
0 0.414073 0.889579
1 0.520747 0.366271
2 0.667484 0.524306
3 0.775926 0.955200
4 0.686405 0.544421
Try with:
select TO_CHAR(dates,'dd/MM/yyy hh24:mi') from ( SELECT min (TO_DATE(a.PAYM_DATE)) as dates from user_payment a )
How about:
var selector = "*"
$(selector).click(function() {
alert(selector);
});
I don't believe jQuery store the selector text that was used. After all, how would that work if you did something like this:
$("div").find("a").click(function() {
// what would expect the 'selector' to be here?
});
MAMP 5.3, you will not find my.cnf and adding them does not work as that max_allowed_packet is stored in variables.
One solution can be:
Run the following query, it set max_allowed_packet to 7gb:
set global max_allowed_packet=268435456;
For some, you may need to increase the following values as well:
set global wait_timeout = 600;
set innodb_log_file_size =268435456;
The reason your CSS isn't working is because of specificity. The Bootstrap selector has a higher specificity than yours, so your style is completely ignored.
Bootstrap styles this with the selector: .navbar-default .navbar-toggle .icon-bar
. This selector has a B specificity value of 3, whereas yours only has a B specificity value of 1.
Therefore, to override this, simply use the same selector in your CSS (assuming your CSS is included after Bootstrap's):
.navbar-default .navbar-toggle .icon-bar {
background-color: black;
}
The database user also seems to be case-sensitive, so while I had a root'@'% user I didn't have a ROOT'@'% user. I changed the user to be uppercase via workbench and the problem was resolved!
To add an Activity
using Android Studio.
This step is same as adding Fragment, Service, Widget, and etc. Screenshot provided.
[UPDATE] Android Studio 3.5. Note that I have removed the steps for the older version. I assume almost all is using version 3.x.
To add a Service
, or a BroadcastReceiver
, just do the same step.
The documentation on MSDN about the ItemsSource
of the DataGridComboBoxColumn
says that only static resources, static code or inline collections of combobox items can be bound to the ItemsSource
:
To populate the drop-down list, first set the ItemsSource property for the ComboBox by using one of the following options:
- A static resource. For more information, see StaticResource Markup Extension.
- An x:Static code entity. For more information, see x:Static Markup Extension.
- An inline collection of ComboBoxItem types.
Binding to a DataContext's property is not possible if I understand that correctly.
And indeed: When I make CompanyItems
a static property in ViewModel ...
public static ObservableCollection<CompanyItem> CompanyItems { get; set; }
... add the namespace where the ViewModel is located to the window ...
xmlns:vm="clr-namespace:DataGridComboBoxColumnApp"
... and change the binding to ...
<DataGridComboBoxColumn
ItemsSource="{Binding Source={x:Static vm:ViewModel.CompanyItems}}"
DisplayMemberPath="Name"
SelectedValuePath="ID"
SelectedValueBinding="{Binding CompanyID}" />
... then it works. But having the ItemsSource as a static property might be sometimes OK, but it is not always what I want.
You can use date(t_stamp)
to get only the date part from a timestamp.
You can check the date() function in the docs
DATE(expr)
Extracts the date part of the date or datetime expression expr.
mysql> SELECT DATE('2003-12-31 01:02:03'); -> '2003-12-31'
blur event: when the element loses focus.
focusout event: when the element, or any element inside of it, loses focus.
As there is nothing inside the filter element, both blur and focusout will work in this case.
$(function() {
$('#filter').blur(function() {
$('#options').hide();
});
})
jsfiddle with blur: http://jsfiddle.net/yznhb8pc/
$(function() {
$('#filter').focusout(function() {
$('#options').hide();
});
})
jsfiddle with focusout: http://jsfiddle.net/yznhb8pc/1/
You need to add the attribute "formnovalidate" to the control that is triggering the browser validation, e.g.:
<input type="image" id="fblogin" formnovalidate src="/images/facebook_connect.png">
You can also, do this.
$(window).on("scroll", function () {
if ($(this).scrollTop() > 800) {
#code here
} else {
#code here
}
});
Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.
In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]:
x y a b
0 3 -1 1 2
1 6 -2 2 4
2 9 -3 3 6
3 12 -4 4 8
Yes. You can use *args
as a non-keyword argument. You will then be able to pass any number of arguments.
def manyArgs(*arg):
print "I was called with", len(arg), "arguments:", arg
>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2, 3)
I was called with 3 arguments: (1, 2, 3)
As you can see, Python will unpack the arguments as a single tuple with all the arguments.
For keyword arguments you need to accept those as a separate actual argument, as shown in Skurmedel's answer.
As already mentioned if you can use await
. If you need to run the code synchronously like you mention .GetAwaiter().GetResult()
, .Result
or .Wait()
is a risk for deadlocks as many have said in comments/answers. Since most of us like oneliners you can use these for .Net 4.5<
Acquiring a value via an async method:
var result = Task.Run(() => asyncGetValue()).Result;
Syncronously calling an async method
Task.Run(() => asyncMethod()).Wait();
No deadlock issues will occur due to the use of Task.Run
.
Source:
https://stackoverflow.com/a/32429753/3850405
Update:
Could cause a deadlock if the calling thread is from the threadpool. The following happens: A new task is queued to the end of the queue, and the threadpool thread which would eventually execute the Task is blocked until the Task is executed.
Source:
https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d
import moment from 'moment';
.....
render() {
return (
<div>
{
this.props.data.map((post,key) =>
<div key={key} className="post-detail">
<h1>{post.title}</h1>
<p>{moment(post.date).calendar()}</p>
<p dangerouslySetInnerHTML={{__html: post.content}}></p>
<hr />
</div>
)}
</div>
);
}
If you want to add ',' at end of the lines starting with 'key', use:
:%s/key.*$/&,
Update 10/11/2020 to reflect the latest brew changes.
Brew
already provide a command to uninstall itself (this will remove everything you installed with Homebrew):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"
If you failed to run this command due to permission (like run as second user), run again with sudo
Then you can install again:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
What you really want is logging
module from standard library. Create a logger and attach two handlers, one would be writing to a file and the other to stdout or stderr.
See Logging to multiple destinations for details
By default, Jenkins account is created without password and with the login shell as /bin/false
.
jenkins:x:496:493:Jenkins Continuous Integration Server:/var/lib/jenkins:/bin/false
Change the shell to /bin/bash
and you should be able to login without password by sudo su - jenkins
.
Command to change the shell is:
chsh -s /bin/bash jenkin
I believe this does it:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
It's got built-in patterns for stuff like URLs and e-mail addresses, and I think you can have it use your own as well.
In Python 2 (and Python 3) you can do:
print "%02d" % (1,)
Basically % is like printf
or sprintf
(see docs).
For Python 3.+, the same behavior can also be achieved with format
:
print("{:02d}".format(1))
For Python 3.6+ the same behavior can be achieved with f-strings:
print(f"{1:02d}")
My 2 cents:
I developed once a typical login dialog (user and password boxes, plus "Ok" button) using WPF and MVVM. I solved the password binding issue by simply passing the PasswordBox control itself as a parameter to the command attached to the "Ok" button. So in the view I had:
<PasswordBox Name="txtPassword" VerticalAlignment="Top" Width="120" />
<Button Content="Ok" Command="{Binding Path=OkCommand}"
CommandParameter="{Binding ElementName=txtPassword}"/>
And in the ViewModel, the Execute
method of the attached command was as follows:
void Execute(object parameter)
{
var passwordBox = parameter as PasswordBox;
var password = passwordBox.Password;
//Now go ahead and check the user name and password
}
This slightly violates the MVVM pattern since now the ViewModel knows something about how the View is implemented, but in that particular project I could afford it. Hope it is useful for someone as well.
I've had a similar issue with this error. In my case, I was entering the incorrect password for the Keystore.
I changed the password for the Keystore to match what I was entering (I didn't want to change the password I was entering), but it still gave the same error.
keytool -storepasswd -keystore keystore.jks
Problem was that I also needed to change the Key's password within the Keystore.
When I initially created the Keystore, the Key was created with the same password as the Keystore (I accepted this default option). So I had to also change the Key's password as follows:
keytool -keypasswd -alias my.alias -keystore keystore.jks
Simple way for newbie:
title.ToLower().Contains("string");//of course "string" is lowercase.
Posting a string:
curl -d "String to post" "http://www.example.com/target"
Posting the contents of a file:
curl -d @soap.xml "http://www.example.com/target"
That's because the return type for [data bytes] is a void* c-style array, not a Uint8 (which is what Byte is a typedef for).
The error is because you are trying to set an allocated array when the return is a pointer type, what you are looking for is the getBytes:length: call which would look like:
[data getBytes:&byteData length:len];
Which fills the array you have allocated with data from the NSData object.
You update core-js with the following command:
npm install --save core-js@^3
If you read the React Docs you will find that the command is derived from when you need to upgrade React itself.
I hope this will help
function get_directory(){
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol . "://" . $_SERVER['SERVER_NAME'] . dirname($_SERVER['PHP_SELF']);
}
define("ROOT_PATH", get_directory()."/" );
echo ROOT_PATH;
Note that you can also set the title directly with javascript, i.e.,
$window.document.title = someTitleYouCreated;
This does not have data binding, but it suffices when putting ng-app
in the <html>
tag is problematic. (For example, using JSP templates where <head>
is defined in exactly one place, yet you have more than one app.)
To set thousand separator, say 123,456.78
you have to use DecimalFormat:
DecimalFormat df = new DecimalFormat("#,###.00");
System.out.println(df.format(new BigDecimal(123456.75)));
System.out.println(df.format(new BigDecimal(123456.00)));
System.out.println(df.format(new BigDecimal(123456123456.78)));
Here is the result:
123,456.75
123,456.00
123,456,123,456.78
Although I set #,###.00
mask, it successfully formats the longer values too.
Note that the comma(,) separator in result depends on your locale. It may be just space( ) for Russian locale.
Here are a few ways of removing a single '
from a string in python.
replace
is usually used to return a string with all the instances of the substring replaced.
"A single ' char".replace("'","")
str.translate
To remove characters you can pass the first argument to the funstion with all the substrings to be removed as second.
"A single ' char".translate(None,"'")
You will have to use str.maketrans
"A single ' char".translate(str.maketrans({"'":None}))
Regular Expressions using re
are even more powerful (but slow) and can be used to replace characters that match a particular regex rather than a substring.
re.sub("'","","A single ' char")
Other Ways
There are a few other ways that can be used but are not at all recommended. (Just to learn new ways). Here we have the given string as a variable string
.
Using list comprehension
''.join([c for c in string if c != "'"])
Using generator Expression
''.join(c for c in string if c != "'")
Another final method can be used also (Again not recommended - works only if there is only one occurrence )
Form1 frmnew = new Form1();
frmnew.ShowDialog();
Well, they don't do the same thing, really.
$_SERVER['REQUEST_METHOD']
contains the request method (surprise).
$_POST
contains any post data.
It's possible for a POST request to contain no POST data.
I check the request method — I actually never thought about testing the $_POST
array. I check the required post fields, though. So an empty post request would give the user a lot of error messages - which makes sense to me.
You will need to build that CREATE TABLE statement from the inputs and then execute it.
A simple example:
declare @cmd nvarchar(1000), @TableName nvarchar(100);
set @TableName = 'NewTable';
set @cmd = 'CREATE TABLE dbo.' + quotename(@TableName, '[') + '(newCol int not null);';
print @cmd;
--exec(@cmd);
Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:
if(isset($_FILES['uploaded_file'])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) === 0) {
move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
}
die(); //Ensure no more processing is done
}
}
Look into the docs for move_uploaded_file()
(it's called move not store) for more.
If you don't mention the random_state in the code, then whenever you execute your code a new random value is generated and the train and test datasets would have different values each time.
However, if you use a particular value for random_state(random_state = 1 or any other value) everytime the result will be same,i.e, same values in train and test datasets.
You can write the where
clause as:
where (case when (:stateCode = '') then (1)
when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
else 0)
end) = 1;
Alternatively, remove the case
entirely:
where (:stateCode = '') or
((:stateCode != '') and vw.state_cd in (:stateCode));
Or, even better:
where (:stateCode = '') or vw.state_cd in (:stateCode)
#code to insert and read dictionary element from csv file
import csv
n=input("Enter I to insert or S to read : ")
if n=="I":
m=int(input("Enter the number of data you want to insert: "))
mydict={}
list=[]
for i in range(m):
keys=int(input("Enter id :"))
list.append(keys)
values=input("Enter Name :")
mydict[keys]=values
with open('File1.csv',"w") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=list)
writer.writeheader()
writer.writerow(mydict)
print("Data Inserted")
else:
keys=input("Enter Id to Search :")
Id=str(keys)
with open('File1.csv',"r") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row[Id]) #print(row) to display all data
While there is no valid way to omit an image's source, there are sources which won't cause server hits. I recently had a similar issue with iframe
s and determined //:0
to be the best option. No, really!
Starting with //
(omitting the protocol) causes the protocol of the current page to be used, preventing "insecure content" warnings in HTTPS pages. Skipping the host name isn't necessary, but makes it shorter. Finally, a port of :0
ensures that a server request can't be made (it isn't a valid port, according to the spec).
This is the only URL which I found caused no server hits or error messages in any browser. The usual choice — javascript:void(0)
— will cause an "insecure content" warning in IE7 if used on a page served via HTTPS. Any other port caused an attempted server connection, even for invalid addresses. (Some browsers would simply make the invalid request and wait for them to time out.)
This was tested in Chrome, Safari 5, FF 3.6, and IE 6/7/8, but I would expect it to work in any browser, as it should be the network layer which kills any attempted request.
This is known as type assertion
in golang, and it is a common practice.
Here is the explanation from a tour of go:
A type assertion provides access to an interface value's underlying concrete value.
t := i.(T)
This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.
If i does not hold a T, the statement will trigger a panic.
To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.
t, ok := i.(T)
If i holds a T, then t will be the underlying value and ok will be true.
If not, ok will be false and t will be the zero value of type T, and no panic occurs.
NOTE: value i
should be interface type.
Even if i
is an interface type, []i
is not interface type. As a result, in order to convert []i
to its value type, we have to do it individually:
// var items []i
for _, item := range items {
value, ok := item.(T)
dosomethingWith(value)
}
As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.
I just use a bit of jQuery/javascript:
html:
<h1>Don't Print</h1>
<a data-target="#myModal" role="button" class="btn" data-toggle="modal">Launch modal</a>
<div class="modal fade hide" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal to print</h3>
</div>
<div class="modal-body">
<p>Print Me</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" id="printButton">Print</button>
</div>
</div>
js:
$('#printButton').on('click', function () {
if ($('.modal').is(':visible')) {
var modalId = $(event.target).closest('.modal').attr('id');
$('body').css('visibility', 'hidden');
$("#" + modalId).css('visibility', 'visible');
$('#' + modalId).removeClass('modal');
window.print();
$('body').css('visibility', 'visible');
$('#' + modalId).addClass('modal');
} else {
window.print();
}
});
here is the fiddle
See if this answer can help you. Particularly the fact that CLI ini could be different than when the script is running through a browser.
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
System.out.println(a[i] + " not the same with " + a[k + 1] + "\n");
}
}
}
You can start from k=1 & keep "a.length-1" in outer for loop, in order to reduce two comparisions,but that doesnt make any significant difference.
Just invert the indexes' order like this:
for (int j = 0; j<array[0].length; j++){
for (int i = 0; i<array.length; i++){
because all rows has same amount of columns you can use this condition j < array[0].lengt in first for condition due to the fact you are iterating over a matrix
Found easiest way for me. Here an example with fork for clarity that this way is useful for flow control.
import signal
import time
import sys
import os
def handle_exit(sig, frame):
raise(SystemExit)
def main():
time.sleep(120)
signal.signal(signal.SIGTERM, handle_exit)
p = os.fork()
if p == 0:
main()
os._exit()
try:
os.waitpid(p, 0)
except (KeyboardInterrupt, SystemExit):
print('exit handled')
os.kill(p, 15)
os.waitpid(p, 0)
I know it is too late to answer to this question. But, I thought it would still be nice to share how I sorted this out when I had the same issue. Here is what I did.
int[] getAdminIDList(String tableName, String attributeName, int value) throws SQLException {
ArrayList list = null;
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery("SELECT admin_id FROM " + tableName + " WHERE " + attributeName + "='" + value + "'");
while (result.next()) {
list.add(result.getInt(1));
}
statement.close();
int id[] = new int[list.size()];
for (int i = 0; i < id.length; i++) {
try {
id[i] = ((Integer) list.get(i)).intValue();
} catch(NullPointerException ne) {
} catch(ClassCastException ch) {}
}
return id;
}
// enter code here
This code shows why ArrayList
is important and why we use it. Simply casting int
from Object
. May be its helpful.
Just use the -fno-objc-arc
flag in Build Phases
>Compile Sources
You can query for the built-in session variables with SQL. To identify the version of DB2 on z/OS, you need the SYSIBM.VERSION variable. This will return the PRDID - the product identifier. You can look up the human-readable version in the Knowledge Center.
SELECT GETVARIABLE('SYSIBM.VERSION')
FROM SYSIBM.SYSDUMMY1;
-- for example, the above returns DSN10015
-- DSN10015 identifies DB2 10 in new-function mode (see second link above)
Memory Engine is not the solution you're looking for. You lose everything that you went to a database for in the first place (i.e. ACID).
Here are some better alternatives:
A LEFT [OUTER] JOIN can be faster than an equivalent subquery because the server might be able to optimize it better—a fact that is not specific to MySQL Server alone.
The last point is key. I used to love joins, but then had to run joins on a few tables with 100M+ rows. No good. Better off insert the data you're joining against into that target table (if it's not too much) and query against indexed columns and you'll get your query in a few ms.
I hope those help.
Firstly said, I try to force all my users to use Chrome when printing because other browsers create different layouts.
An answer from this question recommends:
@page {
size: 210mm 297mm;
/* Chrome sets own margins, we change these printer settings */
margin: 27mm 16mm 27mm 16mm;
}
However, I ended up using this CSS for all my pages to be printed:
@media print
{
@page {
size: A4; /* DIN A4 standard, Europe */
margin:0;
}
html, body {
width: 210mm;
/* height: 297mm; */
height: 282mm;
font-size: 11px;
background: #FFF;
overflow:visible;
}
body {
padding-top:15mm;
}
}
Special case: Long Tables
When I needed to print a table over several pages, the margin:0
with the @page
was leading to bleeding edges:
I could solve this thanks to this answer with:
table { page-break-inside:auto }
tr { page-break-inside:avoid; page-break-after:auto }
thead { display:table-header-group; }
tfoot { display:table-footer-group; }
Plus setting the top-bottom-margins for @page
:
@page {
size: auto;
margin: 20mm 0 10mm 0;
}
body {
margin:0;
padding:0;
}
Result:
I would rather prefer a solution that is concise and works with all browser. For now, I hope the information above can help some developers with similar issues.
When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php
. That is how PHP works with includes.
So, in your example, since you've set a variable called $name
in your front.inc
file, and then included both front.inc
and end.inc
in your index.php
, you will be able to echo
the variable $name
anywhere after the include
of front.inc
within your index.php
. Again, PHP processes your index.php
as if the code from the two files you are including are part of the file.
When you place an echo
within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.
In other words, to do the behavior you're expecting, you will need to define it as a global.
Look @JRuns answer in here. The idea is to create html with your custom scheme and upload it somewhere. Then if you click on your custom link on your html-file, you will be redirected to your app. I used this article for android. But dont forget to set full name Name = "MyApp.Mobile.Droid.MainActivity"
attribute to your target activity.
Have a look at this Everything You Need to Know About HTML5 Video and Audio post at the Opera Dev site under the "I want to roll my own controls" section.
This is the pertinent section:
<video src="video.ogv">
video not supported
</video>
then you can use:
<script>
var video = document.getElementsByTagName('video')[0];
video.onended = function(e) {
/*Do things here!*/
};
</script>
onended
is a HTML5 standard event on all media elements, see the HTML5 media element (video/audio) events documentation.
The default password for Mariadb is blank.
$ mysql -u root -p
Enter Password: <--- press enter
Q1) Here are couple things to read or google more :
Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest
It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.
Q2) Here are couple of good tutorials for soap (I had them bookmarked) :
http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/
http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html
Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.
SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.
Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).
Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.
If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development
.
It's fantastic, not hard to read and not too big either (win win).
Just check for it before you pass to your function. So you would pass:
thing.foo ? thing.foo.bar : undefined
You can use map
. Here is an example implementation:
case 'SOME_ACTION':
return {
...state,
contents: state.contents.map(
(content, i) => i === 1 ? {...content, text: action.payload}
: content
)
}
Apart from its primary use as a way to control the lifetime of system resources (completely covered by the awesome answer of Ian, kudos!), the IDisposable/using combo can also be used to scope the state change of (critical) global resources: the console, the threads, the process, any global object like an application instance.
I've written an article about this pattern: http://pragmateek.com/c-scope-your-global-state-changes-with-idisposable-and-the-using-statement/
It illustrates how you can protect some often used global state in a reusable and readable manner: console colors, current thread culture, Excel application object properties...
You can extend Desheng Li's method further by allowing an iterations count to do multiple flashes like so:
// Extend jquery with flashing for elements
$.fn.flash = function(duration, iterations) {
duration = duration || 1000; // Default to 1 second
iterations = iterations || 1; // Default to 1 iteration
var iterationDuration = Math.floor(duration / iterations);
for (var i = 0; i < iterations; i++) {
this.fadeOut(iterationDuration).fadeIn(iterationDuration);
}
return this;
}
Then you can call the method with a time and number of flashes:
$("#someElementId").flash(1000, 4); // Flash 4 times over a period of 1 second
Also, you have to change your approach when using Map myVariable as described in the documentation to eleminate nulls:
From documentation:
com.fasterxml.jackson.annotation.JsonInclude
@JacksonAnnotation
@Target(value={ANNOTATION_TYPE, FIELD, METHOD, PARAMETER, TYPE})
@Retention(value=RUNTIME)
Annotation used to indicate when value of the annotated property (when used for a field, method or constructor parameter), or all properties of the annotated class, is to be serialized. Without annotation property values are always included, but by using this annotation one can specify simple exclusion rules to reduce amount of properties to write out.
*Note that the main inclusion criteria (one annotated with value) is checked on Java object level, for the annotated type, and NOT on JSON output -- so even with Include.NON_NULL it is possible that JSON null values are output, if object reference in question is not `null`. An example is java.util.concurrent.atomic.AtomicReference instance constructed to reference null value: such a value would be serialized as JSON null, and not filtered out.
To base inclusion on value of contained value(s), you will typically also need to specify content() annotation; for example, specifying only value as Include.NON_EMPTY for a {link java.util.Map} would exclude Maps with no values, but would include Maps with `null` values. To exclude Map with only `null` value, you would use both annotations like so:
public class Bean {
@JsonInclude(value=Include.NON_EMPTY, content=Include.NON_NULL)
public Map<String,String> entries;
}
Similarly you could Maps that only contain "empty" elements, or "non-default" values (see Include.NON_EMPTY and Include.NON_DEFAULT for more details).
In addition to `Map`s, `content` concept is also supported for referential types (like java.util.concurrent.atomic.AtomicReference). Note that `content` is NOT currently (as of Jackson 2.9) supported for arrays or java.util.Collections, but supported may be added in future versions.
Since:
2.0
Though mysql_fetch_array
will output numbers, its used to handle a large chunk.
To echo the content of the row, use
echo $row['option_value'];
I know I am 3 years late on this thread, however still providing my 2 cents for similar cases in future.
I recently faced the same issue/error in my cluster. The JOB would always get to some 80%+ reduction and fail with the same error, with nothing to go on in the execution logs either. Upon multiple iterations and research I found that among the plethora of files getting loaded some were non-compliant with the structure provided for the base table(table being used to insert data into partitioned table).
Point to be noted here is whenever I executed a select query for a particular value in the partitioning column or created a static partition it worked fine as in that case error records were being skipped.
TL;DR: Check the incoming data/files for inconsistency in the structuring as HIVE follows Schema-On-Read philosophy.
EDIT
Since this answer has been originally posted the browser API has changed.
.stop()
is no longer available on the stream that gets passed to the callback.
The developer will have to access the tracks that make up the stream (audio or video) and stop each of them individually.
More info here: https://developers.google.com/web/updates/2015/07/mediastream-deprecations?hl=en#stop-ended-and-active
Example (from the link above):
stream.getTracks().forEach(function(track) {_x000D_
track.stop();_x000D_
});
_x000D_
Browser support may differ.
Original answer
navigator.getUserMedia
provides you with a stream in the success callback, you can call .stop()
on that stream to stop the recording (at least in Chrome, seems FF doesn't like it)
Please find the following:
$yourArray = array('first_key'=> 'First', 2, 3, 4, 5);
$keys = array_keys($yourArray);
echo "Key = ".$keys[0];
A safe way is to serialize the object, then deserialize. This ensures everything is a brand new reference.
Here's an article about how to do this efficiently.
Caveats: It's possible for classes to override serialization such that new instances are not created, e.g. for singletons. Also this of course doesn't work if your classes aren't Serializable.
Open SQL Server Management Studio > File > Open > File > Choose your .sql file (the one that contains your script) > Press Open > the file will be opened within SQL Server Management Studio, Now all what you need to do is to press Execute button.
str1 = "Hello"
str2 = "World"
newstr = " ".join((str1, str2))
That joins str1 and str2 with a space as separators. You can also do "".join(str1, str2, ...)
. str.join()
takes an iterable, so you'd have to put the strings in a list or a tuple.
That's about as efficient as it gets for a builtin method.
I was able to resolve this problem by cleaning my assets cache:
$ rake assets:clean
I was getting errors with third party and Oledb reading of a XLSX workbook. The issue appears to be a hidden worksheet that causes a error. Unhiding the worksheet enabled the workbook to import.
If you have an access to that domain/iframe that is loaded, then you can use window.postMessage to communicate between iframe and the main window.
Read the DOM with JavaScript in iframe and send it via postMessage to the top window.
More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
This indicates the linux has delivered a SIGTERM
to your process. This is usually at the request of some other process (via kill()
) but could also be sent by your process to itself (using raise()
). This signal requests an orderly shutdown of your process.
If you need a quick cheatsheet of signal numbers, open a bash shell and:
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
You can determine the sender by using an appropriate signal handler like:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
info->si_pid);
exit(0);
}
int main (void)
{
struct sigaction action = {
.sa_handler = NULL,
.sa_sigaction = sigterm_handler,
.sa_mask = 0,
.sa_flags = SA_SIGINFO,
.sa_restorer = NULL
};
sigaction(SIGTERM, &action, NULL);
sleep(60);
return 0;
}
Notice that the signal handler also includes a call to exit()
. It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).
in iOS Simulator menu, go to Debug -> Location -> Custom Location. There you can set the latitude and longitude and test the app accordingly. This works with mapkit and also with CLLocationManager.
Bassed on the excellent answer of T.J. Crowder: (Off-topic: Avoid cluttering window
)
This is an example of his idea:
Html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="init.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
</script>
<script src="script.js"></script>
</head>
<body>
<h1>Hello !</h1>
</body>
</html>
init.js (Based on this answer)
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private
return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function(i) {
return _args[i];
}
};
}());
script.js
// Here you can use the values defined in the html as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);
alert(a);
Here's the plnkr. Hope it help !
Look for books by Ted Padova. Over the years, he has written a series of books called The Acrobat PDF {5,6,7,8,9...} Bible. They contain chapter(s) on JavaScript in PDF files. They are not as comprehensive as the reference documentation listed here, but in the books there are some realistic use-cases discussed in context.
There was also a talk on hacking PDF files by a computer scientist, given at a conference in 2010. The link on the talk's announcement-page to the slides is dead, but Google is your friend-. The talk is not exclusively on JavaScript, though. YouTube video - JavaScript starts at 06:00.
To remove item you need to remove it from array and can pass bday
item to your remove function in markup. Then in controller look up the index of item and remove from array
<a class="btn" ng-click="remove(item)">Delete</a>
Then in controller:
$scope.remove = function(item) {
var index = $scope.bdays.indexOf(item);
$scope.bdays.splice(index, 1);
}
Angular will automatically detect the change to the bdays
array and do the update of ng-repeat
DEMO: http://plnkr.co/edit/ZdShIA?p=preview
EDIT: If doing live updates with server would use a service you create using $resource
to manage the array updates at same time it updates server
This happens when your result is not a result (but a "false" instead). You should change this line
$sql = 'SELECT * FROM $usertable WHERE PartNumber = $partid';
to this:
$sql = "SELECT * FROM $usertable WHERE PartNumber = $partid";
because the " can interprete $variables while ' cannot.
Works fine with integers (numbers), for strings you need to put the $variable in single quotes, like
$sql = "SELECT * FROM $usertable WHERE PartNumber = '$partid' ";
If you want / have to work with single quotes, then php CAN NOT interprete the variables, you will have to do it like this:
$sql = 'SELECT * FROM '.$usertable.' WHERE string_column = "'.$string.'" AND integer_column = '.$number.';
try this
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
table, th, td {_x000D_
border: 1px solid black;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table style="width:50%;">_x000D_
<tr>_x000D_
<th>Month</th>_x000D_
<th>Savings</th>_x000D_
</tr>_x000D_
<tr style="height:100px">_x000D_
<td valign="top">January</td>_x000D_
<td valign="bottom">$100</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
use valign="top" for td style
Just my 2 cents regarding the divs option.
Famous/Infamous and SamsaraJS (and possibly others) use absolutely positioned non-nested divs (with non-trivial HTML/CSS content), combined with matrix2d/matrix3d for positioning and 2D/3D transformations, and achieve a stable 60FPS on moderate mobile hardware, so I'd argue against divs being a slow option.
There are plenty of screen recordings on Youtube and elsewhere, of high-performance 2D/3D stuff running in the browser with everything being an DOM element which you can Inspect Element on, at 60FPS (mixed with WebGL for certain effects, but not for the main part of the rendering).
Temporary redirect
rewrite ^ http://www.RedirectToThisDomain.com$request_uri? redirect;
Permanent redirect
rewrite ^ http://www.RedirectToThisDomain.com$request_uri? permanent;
In nginx configuration file for specific site:
server {
server_name www.example.com;
rewrite ^ http://www.RedictToThisDomain.com$request_uri? redirect;
}
You can fix your example with the iterator pattern by changing the parametrization of the class:
List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Iterator<Room> i = rooms.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}
or much simpler way:
List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Room room : rooms) {
System.out.println(room);
}
DESCRIBE keyspaces to list all keysapces DESCRIBE keyspace https://docs.datastax.com/en/dse/5.1/cql/cql/cql_reference/cqlsh_commands/cqlshDescribeKeyspace.html
If you are doing unit testing and get this error then Import RouterTestingModule
into your app.component.spec.ts
or inside your featured components' spec.ts
:
import { RouterTestingModule } from '@angular/router/testing';
Add RouterTestingModule
into your imports: []
like
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
Just adding to Tony Miller's answer as this got me 90% towards what I was looking for but still didn't work. Adding .length > 0;
to the end of his code got my script working.
$(function() {
var foundin = $('*:contains("I am a simple string")').length > 0;
});
If you thinking like RDBMS, you can't create primary key. Default primary key is _id. But you can create Unique Index. Example is bellow.
db.members.createIndex( { "user_id": 1 }, { unique: true } )
db.members.insert({'user_id':1,'name':'nanhe'})
db.members.insert({'name':'kumar'})
db.members.find();
Output is bellow.
{ "_id" : ObjectId("577f9cecd71d71fa1fb6f43a"), "user_id" : 1, "name" : "nanhe" }
{ "_id" : ObjectId("577f9d02d71d71fa1fb6f43b"), "name" : "kumar" }
When you try to insert same user_id mongodb throws a write error.
db.members.insert({'user_id':1,'name':'aarush'})
WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 duplicate key error collection: student.members index: user_id_1 dup key: { : 1.0 }" } })
You can use StringUtils’s TraditionalBinarPrefix
:
public static String humanReadableInt(long number) {
return TraditionalBinaryPrefix.long2String(number, ””, 1);
}
iirc :
cat filename.txt | awk '{ print $2 $4 }'
or, as mentioned in the comments :
awk '{ print $2 $4 }' filename.txt
The accepted answer works well and one can also just use the
If Exists (...) Then ... End If;
syntax in Mysql procedures (if acceptable for circumstance) and it will behave as desired/expected. Here's a link to a more thorough source/description: https://dba.stackexchange.com/questions/99120/if-exists-then-update-else-insert
One problem with the solution by @SnowyR is that it does not really behave like "If Exists" in that the (Select 1 = 1 ...) subquery could return more than one row in some circumstances and so it gives an error. I don't have permissions to respond to that answer directly so I thought I'd mention it here in case it saves someone else the trouble I experienced and so others might know that it is not an equivalent solution to MSSQLServer "if exists"!
I'll be using this Live Event from NASA TV as an example:
https://www.youtube.com/watch?v=21X5lGlDOfg
First, list the formats for the video:
$ ~ youtube-dl --list-formats https://www.youtube.com/watch\?v\=21X5lGlDOfg
[youtube] 21X5lGlDOfg: Downloading webpage
[youtube] 21X5lGlDOfg: Downloading m3u8 information
[youtube] 21X5lGlDOfg: Downloading MPD manifest
[info] Available formats for 21X5lGlDOfg:
format code extension resolution note
91 mp4 256x144 HLS 197k , avc1.42c00b, 30.0fps, mp4a.40.5@ 48k
92 mp4 426x240 HLS 338k , avc1.4d4015, 30.0fps, mp4a.40.5@ 48k
93 mp4 640x360 HLS 829k , avc1.4d401e, 30.0fps, mp4a.40.2@128k
94 mp4 854x480 HLS 1380k , avc1.4d401f, 30.0fps, mp4a.40.2@128k
300 mp4 1280x720 3806k , avc1.4d4020, 60.0fps, mp4a.40.2 (best)
Pick the format you wish to download, and fetch the HLS m3u8 URL of the video from the manifest. I'll be using 94 mp4 854x480 HLS 1380k , avc1.4d401f, 30.0fps, mp4a.40.2@128k
for this example:
? ~ youtube-dl -f 94 -g https://www.youtube.com/watch\?v\=21X5lGlDOfg
https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1592099895/ei/1y_lXuLOEsnXyQWYs4GABw/ip/81.190.155.248/id/21X5lGlDOfg.3/itag/94/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/goi/160/sgoap/gir%3Dyes%3Bitag%3D140/sgovp/gir%3Dyes%3Bitag%3D135/hls_chunk_host/r5---sn-h0auphxqp5-f5fs.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/8270/mh/N8/mm/44/mn/sn-h0auphxqp5-f5fs/ms/lva/mv/m/mvi/4/pl/16/dover/11/keepalive/yes/beids/9466586/mt/1592078245/disable_polymer/true/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,goi,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAM2dGSece2shUTgS73Qa3KseLqnf85ca_9u7Laz7IDfSAiEAj8KHw_9xXVS_PV3ODLlwDD-xfN6rSOcLVNBpxKgkRLI%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRQIhAJCO6kSwn7PivqMW7sZaiYFvrultXl6Qmu9wppjCvImzAiA7vkub9JaanJPGjmB4qhLVpHJOb9fZyhMEeh1EUCd-3Q%3D%3D/playlist/index.m3u8
Note that link could be different and it contains expiration timestamp, in this case 1592099895 (about 6 hours).
Now that you have the HLS playlist, you can open this URL in VLC and save it using "Record", or write a small ffmpeg command:
ffmpeg -i \
https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1592099895/ei/1y_lXuLOEsnXyQWYs4GABw/ip/81.190.155.248/id/21X5lGlDOfg.3/itag/94/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/goi/160/sgoap/gir%3Dyes%3Bitag%3D140/sgovp/gir%3Dyes%3Bitag%3D135/hls_chunk_host/r5---sn-h0auphxqp5-f5fs.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/8270/mh/N8/mm/44/mn/sn-h0auphxqp5-f5fs/ms/lva/mv/m/mvi/4/pl/16/dover/11/keepalive/yes/beids/9466586/mt/1592078245/disable_polymer/true/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,goi,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAM2dGSece2shUTgS73Qa3KseLqnf85ca_9u7Laz7IDfSAiEAj8KHw_9xXVS_PV3ODLlwDD-xfN6rSOcLVNBpxKgkRLI%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRQIhAJCO6kSwn7PivqMW7sZaiYFvrultXl6Qmu9wppjCvImzAiA7vkub9JaanJPGjmB4qhLVpHJOb9fZyhMEeh1EUCd-3Q%3D%3D/playlist/index.m3u8 \
-c copy output.ts
Try eUML2. its a single click generator no need to drag n drop.
Set the tabindex of the canvas element to 1 or something like this
<canvas tabindex='1'></canvas>
It's an old trick to make any element focusable
internet protocol properties
" section on computer_2. Preferred DNS server
" text box and click ok and close the dialog box. Now try to open the website again on computer_2.
Ok I figured this out. For anyone else trying to do this you need:
a) heading: your heading from the hardware compass. This is in degrees east of magnetic north
b) bearing: the bearing from your location to the destination location. This is in degrees east of true north.
myLocation.bearingTo(destLocation);
c) declination: the difference between true north and magnetic north
The heading that is returned from the magnetometer + accelermometer is in degrees east of true (magnetic) north (-180 to +180) so you need to get the difference between north and magnetic north for your location. This difference is variable depending where you are on earth. You can obtain by using GeomagneticField class.
GeomagneticField geoField;
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
geoField = new GeomagneticField(
Double.valueOf(location.getLatitude()).floatValue(),
Double.valueOf(location.getLongitude()).floatValue(),
Double.valueOf(location.getAltitude()).floatValue(),
System.currentTimeMillis()
);
...
}
}
Armed with these you calculate the angle of the arrow to draw on your map to show where you are facing in relation to your destination object rather than true north.
First adjust your heading with the declination:
heading += geoField.getDeclination();
Second, you need to offset the direction in which the phone is facing (heading) from the target destination rather than true north. This is the part that I got stuck on. The heading value returned from the compass gives you a value that describes where magnetic north is (in degrees east of true north) in relation to where the phone is pointing. So e.g. if the value is -10 you know that magnetic north is 10 degrees to your left. The bearing gives you the angle of your destination in degrees east of true north. So after you've compensated for the declination you can use the formula below to get the desired result:
heading = myBearing - (myBearing + heading);
You'll then want to convert from degrees east of true north (-180 to +180) into normal degrees (0 to 360):
Math.round(-heading / 360 + 180)
Based on @md-nazrul-islam reply, This is what I did with SCSS:
ul.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
display: none;
min-width: 160px;
margin: 0 0 10px 25px;
list-style: none;
background-color: #ffffff;
border: 1px solid #ccc;
border-color: rgba(0, 0, 0, 0.2);
//@include border-radius(5px);
@include box-shadow( rgba(0, 0, 0, 0.1) 0 5px 10px );
@include background-clip(padding-box);
*border-right-width: 2px;
*border-bottom-width: 2px;
li.ui-menu-item{
padding:0 .5em;
line-height:2em;
font-size:.8em;
&.ui-state-focus{
background: #F7F7F7;
}
}
}
Jerry's answer is great. However, it doesn't handle large responses. A simple change to handle this:
memset(response, 0, sizeof(response));
total = sizeof(response)-1;
received = 0;
do {
printf("RESPONSE: %s\n", response);
// HANDLE RESPONSE CHUCK HERE BY, FOR EXAMPLE, SAVING TO A FILE.
memset(response, 0, sizeof(response));
bytes = recv(sockfd, response, 1024, 0);
if (bytes < 0)
printf("ERROR reading response from socket");
if (bytes == 0)
break;
received+=bytes;
} while (1);
Try something like:
import pylab as p
p.plot(x,y)
p.axis('equal')
p.show()
MySQL (before version 5.6.5) does not allow functions to be used for default DateTime values. TIMESTAMP is not suitable due to its odd behavior and is not recommended for use as input data. (See MySQL Data Type Defaults.)
That said, you can accomplish this by creating a Trigger.
I have a table with a DateCreated field of type DateTime. I created a trigger on that table "Before Insert" and "SET NEW.DateCreated=NOW()
" and it works great.
I hope this helps somebody.
another one:
if(this.checkValidity() == false) {
$(this).addClass('was-validated');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}
Suppose we want to find the string variable needle
in the string variable haystack
. There are three gotchas:
string.toUpperCase
and string.toLowerCase
. Use a regular expression which ignores case instead. For example, var needleRegExp = new RegExp(needle, "i");
followed by needleRegExp.test(haystack)
.needle
. Be careful that needle
does not contain any regular expression special characters. Escape these using needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
.needle
and haystack
, just ignoring case, make sure to add "^"
at the start and "$"
at the end of your regular expression constructor.Taking points (1) and (2) into consideration, an example would be:
var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
if (result) {
// Your code here
}
Google Guava provides a neat way to do this by calling Ints.toArray
.
List<Integer> list = ...;
int[] values = Ints.toArray(list);
You have to check the action method, whether there is one or more methods when calling the method that overloads argumens or invalid argument
public string test(string a, string b){
}
public ActionResult x(){
test(a) //test is need two arguments
}
The usual solution to this problem is setuiding a helper app that performs the task requiring superuser access: http://en.wikipedia.org/wiki/Setuid
Sudo is not meant to be used offline.
Later edit: SSH can be used with private-public key authentication. If the private key does not have a passphrase, ssh can be used without prompting for a password.
Python lists are mutable objects and here:
plot_data = [[]] * len(positions)
you are repeating the same list len(positions)
times.
>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>>
Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.
If you want different lists, you can do this way:
plot_data = [[] for _ in positions]
for example:
>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]
To draw a centered text:
TextRenderer.DrawText(g, "my text", Font, Bounds, ForeColor, BackColor,
TextFormatFlags.HorizontalCenter |
TextFormatFlags.VerticalCenter |
TextFormatFlags.GlyphOverhangPadding);
Determining optimal font size to fill an area is a bit more difficult. One working soultion I found is trial-and-error: start with a big font, then repeatedly measure the string and shrink the font until it fits.
Font FindBestFitFont(Graphics g, String text, Font font,
Size proposedSize, TextFormatFlags flags)
{
// Compute actual size, shrink if needed
while (true)
{
Size size = TextRenderer.MeasureText(g, text, font, proposedSize, flags);
// It fits, back out
if ( size.Height <= proposedSize.Height &&
size.Width <= proposedSize.Width) { return font; }
// Try a smaller font (90% of old size)
Font oldFont = font;
font = new Font(font.FontFamily, (float)(font.Size * .9));
oldFont.Dispose();
}
}
You'd use this as:
Font bestFitFont = FindBestFitFont(g, text, someBigFont, sizeToFitIn, flags);
// Then do your drawing using the bestFitFont
// Don't forget to dispose the font (if/when needed)
I have tried with following code. it's working for me fine
ManageOrder Order = new ManageOrder();
Organization.DataSource = Order.getAllOrganization(Session["userID"].ToString());
Organization.DataValueField = "OrganisationID";
Organization.DataTextField = "OrganisationName";
Organization.DataBind();
Organization.Items.Insert(0, new ListItem("Select Organisation", "0"));
There's also a PHP extension: Pip - Python in PHP, which I've never tried but had it bookmarked for just such an occasion
This will work although when embedding PHP in HTML it is better practice to use the following form:
<table>
<?php foreach($array as $key=>$value): ?>
<tr>
<td><?= $key; ?></td>
</tr>
<?php endforeach; ?>
</table>
You can find the doc for the alternative syntax on PHP.net
You could do something like this if you wanted
package main
import "fmt"
type Pair struct {
a, b interface{}
}
func main() {
p1 := Pair{"finished", 42}
p2 := Pair{6.1, "hello"}
fmt.Println("p1=", p1, "p2=", p2)
fmt.Println("p1.b", p1.b)
// But to use the values you'll need a type assertion
s := p1.a.(string) + " now"
fmt.Println("p1.a", s)
}
However I think what you have already is perfectly idiomatic and the struct describes your data perfectly which is a big advantage over using plain tuples.
Actually, the absolutely easiest way is to do the following...
byte[] content = your_byte[];
FileContentResult result = new FileContentResult(content, "application/octet-stream")
{
FileDownloadName = "your_file_name"
};
return result;
SELECT t1.a, t2.b
FROM t1
JOIN t2 ON t1.a LIKE '%'+t2.b +'%'
because the last answer not work
In Bootstrap, the .btn
class has a white-space: nowrap;
property, making it so that the button text won't wrap. So, after setting that to normal
, and giving the button a width
, the text should wrap to the next line if the text would exceed the set width
.
#new-board-btn {
white-space: normal;
}