I'm mostly agree with chosen answer (https://stackoverflow.com/a/12857584/871392), but want to add option in Making Queries section.
One can define QuerySet classes for models for make filter queries and so on. After that you can proxy this queryset class for model's manager, like build-in Manager and QuerySet classes do.
Although, if you had to query several data models to get one domain model, it seems more reasonable to me to put this in separate module like suggested before.
A different, PCL-friendly approach would be to use an MSBuild inline task to substitute the build time into a string that is returned by a property on the app. We are using this approach successfully in an app that has Xamarin.Forms, Xamarin.Android, and Xamarin.iOS projects.
EDIT:
Simplified by moving all of the logic into the SetBuildDate.targets
file, and using Regex
instead of simple string replace so that the file can be modified by each build without a "reset".
The MSBuild inline task definition (saved in a SetBuildDate.targets file local to the Xamarin.Forms project for this example):
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion="12.0">
<UsingTask TaskName="SetBuildDate" TaskFactory="CodeTaskFactory"
AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v12.0.dll">
<ParameterGroup>
<FilePath ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Code Type="Fragment" Language="cs"><![CDATA[
DateTime now = DateTime.UtcNow;
string buildDate = now.ToString("F");
string replacement = string.Format("BuildDate => \"{0}\"", buildDate);
string pattern = @"BuildDate => ""([^""]*)""";
string content = File.ReadAllText(FilePath);
System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(pattern);
content = rgx.Replace(content, replacement);
File.WriteAllText(FilePath, content);
File.SetLastWriteTimeUtc(FilePath, now);
]]></Code>
</Task>
</UsingTask>
</Project>
Invoking the above inline task in the Xamarin.Forms csproj file in target BeforeBuild:
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. -->
<Import Project="SetBuildDate.targets" />
<Target Name="BeforeBuild">
<SetBuildDate FilePath="$(MSBuildProjectDirectory)\BuildMetadata.cs" />
</Target>
The FilePath
property is set to a BuildMetadata.cs
file in the Xamarin.Forms project that contains a simple class with a string property BuildDate
, into which the build time will be substituted:
public class BuildMetadata
{
public static string BuildDate => "This can be any arbitrary string";
}
Add this file BuildMetadata.cs
to project. It will be modified by every build, but in a manner that allows repeated builds (repeated replacements), so you may include or omit it in source control as desired.
I found a simple way in com.google.common.primitives which is in the [Maven:com.google.guava:guava:12.0.1]
long newLong = Longs.fromByteArray(oldLongByteArray);
int newInt = Ints.fromByteArray(oldIntByteArray);
Have a nice try :)
You can do it by using name attibute, class, id or just universal checkbox; If you want to count only checked number of checkbox.
By the class name :
var countChk = $('checkbox.myclassboxName:checked').length;
By name attribute :
var countByName= $('checkbox[name=myAllcheckBoxName]:checked').length;
$('checkbox.className').blur(function() {
//count only checked checkbox
$('checkbox[name=myAllcheckBoxName]:checked').length;
});
To Convert file path in String to NSURL, observe the following code
var filePathUrl = NSURL.fileURLWithPath(path)
You're obviously looking for the Nullable Monad:
string result = new A().PropertyB.PropertyC.Value;
becomes
string result = from a in new A()
from b in a.PropertyB
from c in b.PropertyC
select c.Value;
This returns null
, if any of the nullable properties are null; otherwise, the value of Value
.
class A { public B PropertyB { get; set; } }
class B { public C PropertyC { get; set; } }
class C { public string Value { get; set; } }
LINQ extension methods:
public static class NullableExtensions
{
public static TResult SelectMany<TOuter, TInner, TResult>(
this TOuter source,
Func<TOuter, TInner> innerSelector,
Func<TOuter, TInner, TResult> resultSelector)
where TOuter : class
where TInner : class
where TResult : class
{
if (source == null) return null;
TInner inner = innerSelector(source);
if (inner == null) return null;
return resultSelector(source, inner);
}
}
ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;
More details in the manual: http://www.postgresql.org/docs/9.1/static/sql-altertable.html
I was getting this same error, in our case it was caused by a load balancer. We hade to make sure that the persistance was set to Source IP. Otherwise the login form was opened by one server, and processed by the other, which would fail to set the authentication cookie correctly. Maybe this helps someone else
This removes trailing whitespace and blank lines from file.txt
PS C:\Users\> (gc file.txt) | Foreach {$_.TrimEnd()} | where {$_ -ne ""} | Set-Content file.txt
The difference between <pluginManagement/>
and <plugins/>
is that a <plugin/>
under:
<pluginManagement/>
defines the settings for plugins that will be inherited by modules in your build. This is great for cases where you have a parent pom file.
<plugins/>
is a section for the actual invocation of the plugins. It may or may not be inherited from a <pluginManagement/>
.
You don't need to have a <pluginManagement/>
in your project, if it's not a parent POM. However, if it's a parent pom, then in the child's pom, you need to have a declaration like:
<plugins>
<plugin>
<groupId>com.foo</groupId>
<artifactId>bar-plugin</artifactId>
</plugin>
</plugins>
Notice how you aren't defining any configuration. You can inherit it from the parent, unless you need to further adjust your invocation as per the child project's needs.
For more specific information, you can check:
The Maven pom.xml reference: Plugins
The Maven pom.xml reference: Plugin Management
IPython intercepts those, they're called built-in magic commands, here's the list: https://ipython.org/ipython-doc/dev/interactive/magics.html
You can also create your own custom magics, https://ipython.org/ipython-doc/dev/config/custommagics.html
Your timeit
is here https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit
In case anyone is looking for an example of this within a Jenkins context. It parses the build.log and if it finds a match it fails the build with the match.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
node{
stage("parse"){
def file = readFile 'build.log'
def regex = ~"(?s)(firstStringToUse(.*)secondStringToUse)"
Matcher match = regex.matcher(file)
match.find() {
capturedText = match.group(1)
error(capturedText)
}
}
}
I had a similar problem. Looked over the html several times and was sure it was correct. Then I started playing around with the order of jquery and bootstrap javascript.
Originally I had bootstrap.min.js loading BEFORE jquery.min.js. In this state, the menu would not expand when clicking on the menu icon.
Then I changed the order so that bootstrap.min.js came after jquery.min.js, and this solved the problem. I don't know enough about javascript to explain why this caused the problem (or fixed it), but that is what worked for me.
Additional info:
Both scripts are located at the bottom of the page, just before the tag. Both scripts are hosted on CDNs, not locally hosted.
If you're pretty sure your code is correct, give this a try.
And for VB.net I found the following works:
Dim sec = New Newtonsoft.Json.Converters.StringEnumConverter()
sec.NamingStrategy() = New Serialization.CamelCaseNamingStrategy
Dim JSON_s As New JsonSerializer
JSON_s.Converters.Add(sec)
Dim jsonObject As JObject
jsonObject = JObject.FromObject(SomeObject, JSON_s)
Dim text = jsonObject.ToString
IO.File.WriteAllText(filePath, text)
first set the path of jdk bin steps to be follow: - open computer properties. - Advanced system settings - Environment Variables look for the system variables -Click on the "path" variable - Edit copy the jdk bin path and done.
The Problem is you just open the command prompt which is default set on current user like "C:\users\ABC>" You have to change the location where your .java file store like "D:\javafiles>"
Now you are able to run the command javac filename.java
From MSDN Documentation
nvarchar [ ( n | max ) ]
Variable-length Unicode string data. n defines the string length and can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size, in bytes, is two times the actual length of data entered + 2 bytes
1st way: In your current Activity, when you create object of intent to open new screen:
String value="xyz";
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
intent.putExtra("key", value);
startActivity(intent);
Then in the nextActivity in onCreate method, retrieve those values which you pass from previous activity:
if (getIntent().getExtras() != null) {
String value = getIntent().getStringExtra("key");
//The key argument must always match that used send and retrive value from one activity to another.
}
2nd way: You can create bundle object and put values in bundle and then put bundle object in intent from your current activity -
String value="xyz";
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("key", value);
intent.putExtra("bundle_key", bundle);
startActivity(intent);
Then in the nextActivity in onCreate method, retrieve those values which you pass from previous activity:
if (getIntent().getExtras() != null) {
Bundle bundle = getIntent().getStringExtra("bundle_key");
String value = bundle.getString("key");
//The key argument must always match that used send and retrive value from one activity to another.
}
You can also use bean class to pass data between classes using serialization.
SELECT NAME FROM v$database;
shows the database name in oracle
if (Build.VERSION.SDK_INT >= 24) {
Html.fromHtml(String, flag) // for 24 API and more
} else {
Html.fromHtml(String) // or for older API
}
for 24 API and more (flag)
public static final int FROM_HTML_MODE_COMPACT = 63;
public static final int FROM_HTML_MODE_LEGACY = 0;
public static final int FROM_HTML_OPTION_USE_CSS_COLORS = 256;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_BLOCKQUOTE = 32;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_DIV = 16;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_HEADING = 2;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST = 8;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM = 4;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH = 1;
public static final int TO_HTML_PARAGRAPH_LINES_CONSECUTIVE = 0;
public static final int TO_HTML_PARAGRAPH_LINES_INDIVIDUAL = 1;
Another option is to create a file in the $_SERVER['DOCUMENT_ROOT']
directory with the definition of your absolute path.
For example, if your $_SERVER['DOCUMENT_ROOT']
directory is
C:\wamp\www\
create a file (i.e. my_paths.php
) containing this
<?php if(!defined('MY_ABS_PATH')) define('MY_ABS_PATH',$_SERVER['DOCUMENT_ROOT'].'MyProyect/')
Now you only need to include in every file inside your MyProyect folder this file (my_paths.php
), so you can user MY_ABS_PATH
as an absolute path for MyProject.
Using only the 'base' package is also a solution for simple cases:
> s <- "a\nb\rc\r\nd"
> l <- strsplit(s,"\r\n|\n|\r")
> l # the whole list...
[[1]]
[1] "a" "b" "c" "d"
> l[[1]][1] # ... or individual elements
[1] "a"
> l[[1]][2]
[1] "b"
> fun <- function(x) c('Line content:', x) # handle as you wish
> lapply(unlist(l), fun)
Don't like any of those solutions.
this is how i do it:
$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='"
. sqlEsc($somename) . "' ;";
then i use my own sqlEsc function:
function sqlEsc($val)
{
global $mysqli;
return mysqli_real_escape_string($mysqli, $val);
}
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')
The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.
I think the answer is incorrectly chosen, that method gives seconds, not milliseconds.
t = Time.now.to_f
=> 1382471965.146
Here I suppose the floating value are the milliseconds
In simple words View is the UI element which we interact with when we use an app,like button,edit text and image etc.View is the child class of Android.view.View While View group is the container which contains all these views inside it in addition to several othe viewgroups like linear or Frame Layout etc. Example if we design & take the root element as Linear layout now our main layout is linear layout inside it we can take another view group (i.e another Linear layout) & many other views like buttons or textview etc.
Try this from different folder:
sudo tar -cvjSf folder.tar.bz2 folder/*
I move the whole directory from my Windows installation to a unix production server and I got the same error. To fix it, I just ran these two lines in unix and everything started to run fine
rm -rf app/cache/*
rm -rf app/logs/*
You cannot.
According to the XML Schema specification, a boolean is true
or false
. True
is not valid:
3.2.2.1 Lexical representation An instance of a datatype that is defined as ·boolean· can have the following legal literals {true, false, 1, 0}. 3.2.2.2 Canonical representation The canonical representation for boolean is the set of literals {true, false}.
If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.
Here an alternative method. It uses Get-WmiObject CIM_DATAFILE to select the version.
(Get-WmiObject -Class CIM_DataFile -Filter "Name='C:\\Windows\\explorer.exe'" | Select-Object Version).Version
For some reason I was not able to use my scalar function until I referenced it using brackets, like so:
select [dbo].[fun_functional_score]('01091400003')
I think this is what you want:
/grand/parent/child[@id="#grand"]
Using
try:
with open("path", "r") as file:#or just open
may cause some troubles when file is opened by some other processes (i.e. user opened it manually). You can solve your poblem using win32com library. Below code checks if any excel files are opened and if none of them matches the name of your particular one, openes a new one.
import win32com.client as win32
xl = win32.gencache.EnsureDispatch('Excel.Application')
my_workbook = "wb_name.xls"
xlPath="my_wb_path//" + my_workbook
if xl.Workbooks.Count > 0:
# if none of opened workbooks matches the name, openes my_workbook
if not any(i.Name == my_workbook for i in xl.Workbooks):
xl.Workbooks.Open(Filename=xlPath)
xl.Visible = True
#no workbooks found, opening
else:
xl.Workbooks.Open(Filename=xlPath)
xl.Visible = True
'xl.Visible = True is not necessary, used just for convenience'
Hope this will help
C++20 will have "uniform container erasure", and you'll be able to write:
std::erase_if(numbers, [](int n){ return n % 2 == 0 });
And that will work for vector
, set
, deque
, etc.
See cppReference for more info.
console.log(document.getElementById('xx') ) evaluates to null.
document.getElementById('xx') !=null evaluates to false
You should use document.getElementById('xx') !== null
as it is a stronger equality check.
If you want to check or set the user name and email you can use the below command
Check user name
git config user.name
Set user name
git config user.name "your_name"
Check your email
git config user.email
Set/change your email
git config user.email "[email protected]"
List/see all configuration
git config --list
You should use a delegate type and specify that as your command parameter. You could use one of the built in delegate types - Action
and Func
.
In your case, it looks like your delegate takes two parameters, and returns a result, so you could use Func
:
List<IJob> GetJobs(Func<FullTimeJob, Student, FullTimeJob> projection)
You could then call your GetJobs
method passing in a delegate instance. This could be a method which matches that signature, an anonymous delegate, or a lambda expression.
P.S. You should use PascalCase for method names - GetJobs
, not getJobs
.
public async Task<ActionResult> Index()
{
apiTable table = new apiTable();
table.Name = "Asma Nadeem";
table.Roll = "6655";
string str = "";
string str2 = "";
HttpClient client = new HttpClient();
string json = JsonConvert.SerializeObject(table);
StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);
str = "" + response.Content + " : " + response.StatusCode;
if (response.IsSuccessStatusCode)
{
str2 = "Data Posted";
}
return View();
}
nohup node server.js > /dev/null 2>&1 &
nohup
means: Do not terminate this process even when the stty is cut
off.> /dev/null
means: stdout goes to /dev/null (which is a dummy
device that does not record any output). 2>&1
means: stderr also goes to the stdout (which is already redirected to /dev/null
). You may replace &1 with a file path to keep a log of errors, e.g.: 2>/tmp/myLog
&
at the end means: run this command as a background task.The steps described above do work, however I've encountered this problem on IntelliJ IDEA and have found that I'm having these problems with existing projects and the only solution is to remove the 'appcompat' module (not the library) and re-import it.
Arkaitz is correct that string
is a managed type. What this means for you is that you never have to worry about how long the string is, nor do you have to worry about freeing or reallocating the memory of the string.
On the other hand, the char[]
notation in the case above has restricted the character buffer to exactly 256 characters. If you tried to write more than 256 characters into that buffer, at best you will overwrite other memory that your program "owns". At worst, you will try to overwrite memory that you do not own, and your OS will kill your program on the spot.
Bottom line? Strings are a lot more programmer friendly, char[]s are a lot more efficient for the computer.
lvalue
means "left value" -- it should be assignable. You cannot change the value of text
since it is an array, not a pointer.
Either declare it as char pointer (in this case it's better to declare it as const char*
):
const char *text;
if(number == 2)
text = "awesome";
else
text = "you fail";
Or use strcpy:
char text[60];
if(number == 2)
strcpy(text, "awesome");
else
strcpy(text, "you fail");
For example :
In MainActivity :
Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra(OtherActivity.KEY_EXTRA, yourDataObject);
startActivity(intent);
In OtherActivity :
public static final String KEY_EXTRA = "com.example.yourapp.KEY_BOOK";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String yourDataObject = null;
if (getIntent().hasExtra(KEY_EXTRA)) {
yourDataObject = getIntent().getStringExtra(KEY_EXTRA);
} else {
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
// do stuff
}
More informations here : http://developer.android.com/reference/android/content/Intent.html
Whenever we have a choice between abstract class and interface we should always (almost) prefer default (also known as defender or virtual extensions) methods.
Default methods have put an end to classic pattern of interface and a companion class that implements most or all of the methods in that interface. An example is Collection and AbstractCollection
. Now we should implement the methods in the interface itself to provide default functionality. The classes which implement the interface has choice to override the methods or inherit the default implementation.
Another important use of default methods is interface evolution
. Suppose I had a class Ball as:
public class Ball implements Collection { ... }
Now in Java 8 a new feature streams in introduced. We can get a stream by using stream
method added to the interface. If stream
were not a default method all the implementations for Collection
interface would have broken as they would not be implementing this new method. Adding a non-default method to an interface is not source-compatible
.
But suppose we do not recompile the class and use an old jar file which contains this class Ball
. The class will load fine without this missing method, instances can be created and it seems everything is working fine. BUT if program invokes stream
method on instance of Ball
we will get AbstractMethodError
. So making method default solved both the problems.
Java 9 has got even private methods in interface which can be used to encapsulate the common code logic that was used in the interface methods that provided a default implementation.
In HTML5 you can use the new 'email' type: http://www.w3.org/TR/html-markup/input.email.html
For example:
<input type="email" id="email" />
If the browser implements HTML5 it will make sure that the user has entered a valid email address in the field. Note that if the browser doesn't implement HTML5, it will be treated like a 'text' type, ie:
<input type="text" id="email" />
I used the backgroundTint and foreground:
<Button
android:layout_width="match_parent"
android:layout_height="40dp"
android:backgroundTint="@color/colorAccent"
android:foreground="?android:attr/selectableItemBackground"
android:textColor="@android:color/white"
android:textSize="10sp"/>
The following will enable you to quickly remove the duplicate,null values and return only the valid one as list.
CREATE TABLE DuplicateTable (Col1 INT)
INSERT INTO DuplicateTable
SELECT 8
UNION ALL
SELECT 1--duplicate
UNION ALL
SELECT 2 --duplicate
UNION ALL
SELECT 1
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION
SELECT NULL
GO
WITH CTE (COl1,DuplicateCount)
AS
(
SELECT COl1,
ROW_NUMBER() OVER(PARTITION BY COl1 ORDER BY Col1) AS DuplicateCount
FROM DuplicateTable
WHERE (col1 IS NOT NULL)
)
SELECT COl1
FROM CTE
WHERE DuplicateCount =1
GO
CTE are valid in SQL 2005 , you could then store the values in a temp table and use it with your function.
Your code can simplified a lot to
$('img', resp).attr('src', function(idx, urlRelative ) {
return self.config.proxy_server + self.config.location_images + urlRelative;
});
Try this.
var dateAsString = DateTime.Now.ToString("dd/MM/yyyy");
// dateAsString = "09/07/2013"
There's currently no out of the box Enum.TryParse. This has been requested on Connect (Still no Enum.TryParse) and got a response indicating possible inclusion in the next framework after .NET 3.5. You'll have to implement the suggested workarounds for now.
According to the YAML spec, neither the :
nor the -
should be a problem. :
is only a key separator with a space after it, and -
is only an array indicator at the start of a line with a space after it.
But if your YAML implementation has a problem with it, you potentially have lots of options:
- url: 'http://www.example-site.com/'
- url: "http://www.example-site.com/"
- url:
http://www.example-site.com/
- url: >-
http://www.example-site.com/
- url: |-
http://www.example-site.com/
There is explicitly no form of escaping possible in "plain style", however.
You may use my library that does that automatically, I've been improving it for the past 2 years http://phery-php-ajax.net
Phery::instance()->set(array(
'phpfunction' => function($data){
/* Do your thing */
return PheryResponse::factory(); // do your dom manipulation, return JSON, etc
}
))->process();
The javascript would be simple as
phery.remote('phpfunction');
You can pass all the dynamic javascript part to the server, with a query builder like chainable interface, and you may pass any type of data back to the PHP. For example, some functions that would take too much space in the javascript side, could be called in the server using this (in this example, mcrypt, that in javascript would be almost impossible to accomplish):
function mcrypt(variable, content, key){
phery.remote('mcrypt_encrypt', {'var': variable, 'content': content, 'key':key || false});
}
//would use it like (you may keep the key on the server, safer, unless it's encrypted for the user)
window.variable = '';
mcrypt('variable', 'This must be encoded and put inside variable', 'my key');
and in the server
Phery::instance()->set(array(
'mcrypt_encrypt' => function($data){
$r = new PheryResponse;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $data['key'] ? : 'my key', $data['content'], MCRYPT_MODE_ECB, $iv);
return $r->set_var($data['variable'], $encrypted);
// or call a callback with the data, $r->call($data['callback'], $encrypted);
}
))->process();
Now the variable
will have the encrypted data.
Can be caused by a miss configured SPF record on the senders end.
I took @hajamie's solution and wrapped it up into a slightly more convenient script wrapper.
I added an option to start from an offset before the end of the file, so you can use the tail-like functionality of reading a certain amount from the end of the file. Note the offset is in bytes, not lines.
There's also an option to continue waiting for more content.
Examples (assuming you save this as TailFile.ps1):
.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000
.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000 -Follow:$true
.\TailFile.ps1 -File .\path\to\myfile.log -Follow:$true
And here is the script itself...
param (
[Parameter(Mandatory=$true,HelpMessage="Enter the path to a file to tail")][string]$File = "",
[Parameter(Mandatory=$true,HelpMessage="Enter the number of bytes from the end of the file")][int]$InitialOffset = 10248,
[Parameter(Mandatory=$false,HelpMessage="Continuing monitoring the file for new additions?")][boolean]$Follow = $false
)
$ci = get-childitem $File
$fullName = $ci.FullName
$reader = new-object System.IO.StreamReader(New-Object IO.FileStream($fullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [IO.FileShare]::ReadWrite))
#start at the end of the file
$lastMaxOffset = $reader.BaseStream.Length - $InitialOffset
while ($true)
{
#if the file size has not changed, idle
if ($reader.BaseStream.Length -ge $lastMaxOffset) {
#seek to the last max offset
$reader.BaseStream.Seek($lastMaxOffset, [System.IO.SeekOrigin]::Begin) | out-null
#read out of the file until the EOF
$line = ""
while (($line = $reader.ReadLine()) -ne $null) {
write-output $line
}
#update the last max offset
$lastMaxOffset = $reader.BaseStream.Position
}
if($Follow){
Start-Sleep -m 100
} else {
break;
}
}
This should would work
List<TestA> testAList = new ArrayList<>();
List<TestB> testBList = new ArrayList<>()
testAList.addAll(new ArrayList<>(testBList));
Did you read https://software.intel.com/en-us/blogs/2014/03/14/troubleshooting-intel-haxm?
It says "Make sure "Hyper-V", a Windows feature, is not installed/enabled on your system. Hyper-V captures the VT virtualization capability of the CPU, and HAXM and Hyper-V cannot run at the same time. Read this blog: Creating a "no hypervisor" boot entry." https://blogs.msdn.microsoft.com/virtual_pc_guy/2008/04/14/creating-a-no-hypervisor-boot-entry/
I've created the boot entry that disables HyperV and it's working
RENAME TABLE tb1 TO tb2;
tb1 - current table name. tb2 - the name you want your table to be called.
Another issue of that page if you use multiple playstore accounts:
In some cases you still get a 404, even if you are currently logged in with the right account, the one you joined the beta community with. As a workaround, you can clear the browser cache, use another browser for the beta signup, or just use the incognito mode of your browser.
You can use ReactDOMServer to render your component to HTML and then use this on jsPDF.
First do the imports:
import React from "react";
import ReactDOMServer from "react-dom/server";
import jsPDF from 'jspdf';
then:
var doc = new jsPDF();
doc.fromHTML(ReactDOMServer.renderToStaticMarkup(this.render()));
doc.save("myDocument.pdf");
Prefer to use:
renderToStaticMarkup
instead of:
renderToString
As the former include HTML code that react relies on.
late to the party, was searching for same, as "in" is not valid, I had just created following.
def find_str(full, sub):
index = 0
sub_index = 0
position = -1
for ch_i,ch_f in enumerate(full) :
if ch_f.lower() != sub[sub_index].lower():
position = -1
sub_index = 0
if ch_f.lower() == sub[sub_index].lower():
if sub_index == 0 :
position = ch_i
if (len(sub) - 1) <= sub_index :
break
else:
sub_index += 1
return position
print(find_str("Happy birthday", "py"))
print(find_str("Happy birthday", "rth"))
print(find_str("Happy birthday", "rh"))
which produces
3
8
-1
remove lower() in case case insensitive find not needed.
Do this by either going to my computer and then right clicking the background for the context menu > "properties". On the left side open "advanced system settings" or just search for "env..." in start menu ([Win]+[s] keys).
Then click on environment variables
If you struggle with this step read this explanation.
D:\path\to\anaconda3
D:\path\to\anaconda3\Scripts
D:\path\to\anaconda3\Library\bin
D:\path\to\anaconda3
should be the folder where you have installed anaconda
Click [OK] on all opened windows.
If you did everything correctly, you can test a conda
command by opening a new powershell window.
conda --version
This should output something like: conda 4.8.2
try this: File->project Structure into Project Structure Left > SDKs SDK location select Android SDK location (old version use Press +, add another sdk)
You could actually put the newlines to good use by reading the entire file into memory as a single long string and then use them to split that into the list of grades.
with open("grades.dat") as input:
grades = [line.split(",") for line in input.read().splitlines()]
etc...
You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:
[HttpPost]
public ActionResult SubmitAction(SomeModel model)
{
var value1 = model.SimpleProp1;
var value2 = model.SimpleProp2;
var value3 = model.ComplexProp1.SimpleProp1;
...
... return something ...
}
Another (obviously uglier) way is:
[HttpPost]
public ActionResult SubmitAction()
{
var value1 = Request["SimpleProp1"];
var value2 = Request["SimpleProp2"];
var value3 = Request["ComplexProp1.SimpleProp1"];
...
... return something ...
}
It most likely means that IIS Management Console was not installed, and modern Windows administrator/IT pro should be able to quickly check this by issuing this command:
Get-WindowsFeature *Web*
And if it is missing just quickly add this via the following command:
Add-WindowsFeature Web-Mgmt-Console
GUI options mentioned above are also valid (see answer from @Joe Wu) but PowerShell it is best way to do IT for IT Pro or let's put it as "if you have to do this slightly more often than once a year" :)
Use StringTokenizer to parse the string.
String s ="SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
Map<String, Integer> lMap=new HashMap<String, Integer>();
StringTokenizer st=new StringTokenizer(s, ",");
while(st.hasMoreTokens())
{
String [] array=st.nextToken().split(":");
lMap.put(array[0], Integer.valueOf(array[1]));
}
You can set the groupby
column to index
then using sum
with level
df.set_index(['Fruit','Name']).sum(level=[0,1])
Out[175]:
Number
Fruit Name
Apples Bob 16
Mike 9
Steve 10
Oranges Bob 67
Tom 15
Mike 57
Tony 1
Grapes Bob 35
Tom 87
Tony 15
My answer addresses the error in general and not the exact code of the OP. No answer mentioned this note so I just thought I add it.
The code below would also generate the same error:
class Actor {
let agent : String? // BAD! // Its value is set to nil, and will always be nil and that's stupid so Xcode is saying not-accepted.
// Technically speaking you have a way around it, you can help the compiler and enforce your value as a constant. See Option3
}
Others mentioned that Either you create initializers or you make them optional types, using ! or ? which is correct. However if you have an optional member/property, that optional should be mutable ie var
. If you make a let
then it would never be able to get out of its nil
state. That's bad!
So the correct way of writing it is:
class Actor {
var agent : String? // It's defaulted to `nil`, but also has a chance so it later can be set to something different || GOOD!
}
Or you can write it as:
class Actor {
let agent : String? // It's value isn't set to nil, but has an initializer || GOOD!
init (agent: String?){
self.agent = agent // it has a chance so its value can be set!
}
}
or default it to any value (including nil
which is kinda stupid)
class Actor {
let agent : String? = nil // very useless, but doable.
let company: String? = "Universal"
}
If you are curious as to why let
(contrary to var
) isn't initialized to nil
then read here and here
The classes are float-right
float-sm-right
etc.
The media queries are mobile-first, so using float-sm-right
would affect small screen sizes and anything wider, so there's no reason to add a class for each width. Just use the smallest screen you want to affect or float-right
for all screen widths.
Official Docs:
Classes: https://getbootstrap.com/docs/4.4/utilities/float/
Updating: https://getbootstrap.com/docs/4.4/migration/#utilities
If you are updating an existing project based on an earlier version of Bootstrap, you can use sass extend to apply the rules to the old class names:
.pull-right {
@extend .float-right;
}
.pull-left {
@extend .float-left;
}
This worked for me with command prompt, from OUTSIDE mysql shell:
# mysqldump -u root -p password db1 > dump.sql
# mysqladmin -u root -p password create db2
# mysql -u root -p password db2 < dump.sql
This looks for me the best way. If zipping "dump.sql" you can symply store it as a compressed backup. Cool! For a 1GB database with Innodb tables, about a minute to create "dump.sql", and about three minutes to dump data into the new DB db2.
Straight copying the hole db directory (mysql/data/db1) didn't work for me, I guess because of the InnoDB tables.
Also, it is very likely, that problem with proxy settings.
Any who didn't overcome Tomact starting problrem, - try in NetBeans choose No Proxy in the Tools -> Options -> General tab.
It helped me.
The livereload plugin fails to serve cordova.js file and serves // mock cordova file during development.
FIX: You need go to node_modules/@ionic/app-scripts/dist/dev-server/serve-config.js
and replace
exports.ANDROID_PLATFORM_PATH = path.join('platforms', 'android', 'assets', 'www');
to
exports.ANDROID_PLATFORM_PATH = path.join('platforms', 'android', 'app', 'src', 'main', 'assets', 'www');
Pass an array to the function, instead of individual parameters and use null coalescing operator (PHP 7+).
Below, I'm passing an array with 2 items. Inside the function, I'm checking if value for item1 is set, if not assigned default vault.
$args = ['item2' => 'item2',
'item3' => 'value3'];
function function_name ($args) {
isset($args['item1']) ? $args['item1'] : 'default value';
}
I use it as much as can to identify when a method is being overriden. If you look at the Scala programming language, they also have an override keyword. I find it useful.
PhiLho has mentioned AutoRuns in passing, but I think it deserves elaboration.
It doesn't scan the whole registry, just the parts containing references to things which get loaded automatically (EXEs, DLLs, drivers etc.) which is probably what you are interested in. It doesn't track changes but can export to a text file, so you can run it before and after installation and do a diff.
You should watch this: Node Tuts episode 19 - Asynchronous Iteration Patterns
It should answers your questions.
Yes, there is.
Surprising, huh? You can get a specific value from a multiple return using a simple mute
function:
package main
import "fmt"
import "strings"
func µ(a ...interface{}) []interface{} {
return a
}
type A struct {
B string
C func()(string)
}
func main() {
a := A {
B:strings.TrimSpace(µ(E())[1].(string)),
C:µ(G())[0].(func()(string)),
}
fmt.Printf ("%s says %s\n", a.B, a.C())
}
func E() (bool, string) {
return false, "F"
}
func G() (func()(string), bool) {
return func() string { return "Hello" }, true
}
https://play.golang.org/p/IwqmoKwVm-
Notice how you select the value number just like you would from a slice/array and then the type to get the actual value.
You can read more about the science behind that from this article. Credits to the author.
Get link to the context of you application
class MY_APPLICATION_NAME: Application() {
companion object {
private lateinit var instance: MY_APPLICATION_NAME
fun getAppContext(): Context = instance.applicationContext
}
override fun onCreate() {
instance = this
super.onCreate()
}
}
inline fun Int.toLocalizedString(): String = MY_APPLICATION_NAME.getAppContext().resources.getString(this)
strings.xml
<resources>
<!-- ....... -->
<string name="no_internet_connection">No internet connection</string>
<!-- ....... -->
</resources>
Get string value:
val errorMessage = R.string.no_internet_connection.toLocalizedString()
So, the trick here is to use absolute positioning calc
like this:
top: calc(50% - XYpx);
left: calc(50% - XYpx);
where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.
I think there is no fixed way to solve this problem since it might be caused by different reason. I also had this problem last week, I don't know when and exactly what cause this problem, only when I run it on simulator with Xcode or try to install it onto the phone, then it reports such kind of error, But when I run it with react-native run-ios with terminal, there is no problem.
I checked all the ways posted on the internet, like renew certificate, change settings in Xcode (all of ways mentions above), actually all of settings in Xcode were already set as it requested before, none of ways works for me. Until this morning when I delete the pods and reinstall, the error finally gonna after a week. If you are also using cocoapod and then error was just show up without any specific reason, maybe you can try my way.
I got it working using:
$('#id-of-table').on('draw.dt', function() {
// do action here
});
Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:
Each marker gets an "infowindow" entry :
function createMarker(lat, lon, html) {
var newmarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: html
});
newmarker['infowindow'] = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(newmarker, 'mouseover', function() {
this['infowindow'].open(map, this);
});
}
method 1 <input type="text" onclick="this.disabled=false;" disabled>
<hr>
method 2 <input type="text" onclick="this.removeAttribute('disabled');" disabled>
<hr>
method 3 <input type="text" onclick="this.removeAttribute('readonly');" readonly>
code of the previous answers don't seem to work in inline mode, but there is a workaround: method 3.
You can get the comments of a particular method by using the ReflectionMethod class and calling ->getDocComment().
http://www.php.net/manual/en/reflectionclass.getdoccomment.php
One possible reason would be the incorrect path of the activity in the Apps AndroidManifest.xml file. Register the activity with in your AndroidManifest.xml with full relative path like below.
<activity android:name="<full_path>.ActivityName" />
Replace
var myNewString = myOldString.replace ("username," visitorName);
with
var myNewString = myOldString.replace("username", visitorName);
This worked for me just now:
<canvas id="c" height="100" width="100" style="border:1px solid red"></canvas>
<script>
var c = document.getElementById('c');
alert(c.height + ' ' + c.width);
c.height = 200;
c.width = 200;
alert(c.height + ' ' + c.width);
</script>
If you want a minimalist method of converting a variable to a string for an inline expression type situation, ''+variablename
is the best I have golfed.
If 'variablename' is an object and you use the empty string concatenation operation, it will give the annoying [object Object]
, in which case you probably want Gary C.'s enormously upvoted JSON.stringify
answer to the posted question, which you can read about on Mozilla's Developer Network at the link in that answer at the top.
An interface defines a contract for a service or set of services. They provide polymorphism in a horizontal manner in that two completely unrelated classes can implement the same interface but be used interchangeably as a parameter of the type of interface they implement, as both classes have promised to satisfy the set of services defined by the interface. Interfaces provide no implementation details.
An abstract class defines a base structure for its sublcasses, and optionally partial implementation. Abstract classes provide polymorphism in a vertical, but directional manner, in that any class that inherits the abstract class can be treated as an instance of that abstract class but not the other way around. Abstract classes can and often do contain implementation details, but cannot be instantiated on their own- only their subclasses can be "newed up".
C# does allow for interface inheritance as well, mind you.
Some times due to some code you get HTML tags in a text filed, like I was replacing some characters with new line BR tag of HTML and by mistake I also replaced it in the text that was supposed to be displayed in a Multiline text box so my multiline text box had a new line HTML tag BR in it coming dynamically due to my string replace function and I started getting this JavaScript error and as this HTML code was displayed in a text box that was in an update panel I start getting this error so I made the correction and all was fine. So before copying pasting anything please look at your code and see that all tag are closed proper and no irrelevant code data is coming to text boxes or Drop down lists. This error always come due to ill formed tags and irrelevant data.
Adapted from answer here: https://stackoverflow.com/a/7505528/921224
For a an in depth description of how to use JavaFX dialogs see: JavaFX Dialogs (official) by code.makery. They are much more powerful and flexible than Swing dialogs and capable of far more than just popping up messages.
import javafx.scene.control.Alert
import javafx.scene.control.Alert.AlertType;
import javafx.application.Platform;
public class ClassNameHere
{
public static void infoBox(String infoMessage, String titleBar)
{
/* By specifying a null headerMessage String, we cause the dialog to
not have a header */
infoBox(infoMessage, titleBar, null);
}
public static void infoBox(String infoMessage, String titleBar, String headerMessage)
{
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle(titleBar);
alert.setHeaderText(headerMessage);
alert.setContentText(infoMessage);
alert.showAndWait();
}
}
One thing to keep in mind is that JavaFX is a single threaded GUI toolkit, which means this method should be called directly from the JavaFX application thread. If you have another thread doing work, which needs a dialog then see these SO Q&As: JavaFX2: Can I pause a background Task / Service? and Platform.Runlater and Task Javafx.
To use this method call:
ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");
or
ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE", "HEADER MESSAGE");
I got confused by the answer to this question, so I created a test case in MySQL, hope this helps
-- Schema
CREATE TABLE T1 (
`ID` int not null auto_increment,
`Label` varchar(50),
primary key (`ID`)
);
CREATE TABLE T2 (
`ID` int not null auto_increment,
`Label` varchar(50),
primary key (`ID`)
);
CREATE TABLE TT (
`IDT1` int not null,
`IDT2` int not null,
primary key (`IDT1`,`IDT2`)
);
ALTER TABLE `TT`
ADD CONSTRAINT `fk_tt_t1` FOREIGN KEY (`IDT1`) REFERENCES `T1`(`ID`) ON DELETE CASCADE,
ADD CONSTRAINT `fk_tt_t2` FOREIGN KEY (`IDT2`) REFERENCES `T2`(`ID`) ON DELETE CASCADE;
-- Data
INSERT INTO `T1` (`Label`) VALUES ('T1V1'),('T1V2'),('T1V3'),('T1V4');
INSERT INTO `T2` (`Label`) VALUES ('T2V1'),('T2V2'),('T2V3'),('T2V4');
INSERT INTO `TT` (`IDT1`,`IDT2`) VALUES
(1,1),(1,2),(1,3),(1,4),
(2,1),(2,2),(2,3),(2,4),
(3,1),(3,2),(3,3),(3,4),
(4,1),(4,2),(4,3),(4,4);
-- Delete
DELETE FROM `T2` WHERE `ID`=4; -- Delete one field, all the associated fields on tt, will be deleted, no change in T1
TRUNCATE `T2`; -- Can't truncate a table with a referenced field
DELETE FROM `T2`; -- This will do the job, delete all fields from T2, and all associations from TT, no change in T1
new Date(2000, 10, 1)
will give you "Wed Nov 01 2000 00:00:00 GMT+0100 (CET)"
See that 0 for month gives you January
Just a little addition to the answer of @dAm2k :
In addition to sudo apt-get remove --purge mysql\*
I've done a sudo apt-get remove --purge mariadb\*
.
I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.
Hope it helps.
The only solution works on Ubuntu 12.04:
echo -e "new_password\nnew_password" | (passwd user)
But the second option only works when I change from:
echo "password:name" | chpasswd
To:
echo "user:password" | chpasswd
See explanations in original post: Changing password via a script
you can use ref
to call the function of the child component from the parent
in functional component, you have to use useImperativeHandle
for getting ref into a child like below
import React, { forwardRef, useRef, useImperativeHandle } from 'react';
export default function ParentFunction() {
const childRef = useRef();
return (
<div className="container">
<div>
Parent Component
</div>
<button
onClick={() => { childRef.current.showAlert() }}
>
Call Function
</button>
<Child ref={childRef}/>
</div>
)
}
const Child = forwardRef((props, ref) => {
useImperativeHandle(
ref,
() => ({
showAlert() {
alert("Child Function Called")
}
}),
)
return (
<div>Child Component</div>
)
})
Child.js
import s from './Child.css';
class Child extends Component {
getAlert() {
alert('clicked');
}
render() {
return (
<h1>Hello</h1>
);
}
}
export default Child;
Parent.js
class Parent extends Component {
render() {
onClick() {
this.refs.child.getAlert();
}
return (
<div>
<Child ref="child" />
<button onClick={this.onClick}>Click</button>
</div>
);
}
}
I have seen JMS used in different commercial and academic projects. JMS can easily come into your picture, whenever you want to have a totally decoupled distributed systems. Generally speaking, when you need to send your request from one node, and someone in your network takes care of it without/with giving the sender any information about the receiver.
In my case, I have used JMS in developing a message-oriented middleware (MOM) in my thesis, where specific types of object-oriented objects are generated in one side as your request, and compiled and executed on the other side as your response.
Simply put, the ++
and --
operators don't exist in Python because they wouldn't be operators, they would have to be statements. All namespace modification in Python is a statement, for simplicity and consistency. That's one of the design decisions. And because integers are immutable, the only way to 'change' a variable is by reassigning it.
Fortunately we have wonderful tools for the use-cases of ++
and --
in other languages, like enumerate()
and itertools.count()
.
I solved this by adding .to_json
and some heading information
@result = HTTParty.post(@urlstring_to_post.to_str,
:body => { :subject => 'This is the screen name',
:issue_type => 'Application Problem',
:status => 'Open',
:priority => 'Normal',
:description => 'This is the description for the problem'
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
You can put an @ in front of your function call to suppress all error messages.
@yourFunctionHere();
use
header("Location: index.php"); //this work in my site
read more on header() at php documentation.
I was able to do that by using the "branches to build" parameter:
Branch Specifier (blank for default): tags/[tag-name]
Replace [tag-name] by the name of your tag.
var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);
You can detect the IE browser by this way.
(navigator.userAgent.toLowerCase().indexOf('msie 6') != -1)
you can get reference on this URL: jquery.browser.msie Alternative
I found a faster way to solve the problem, at least on realistically large datasets using:
df.set_index(KEY).to_dict()[VALUE]
Proof on 50,000 rows:
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)
%timeit dict(zip(df.A,df.B))
%timeit pd.Series(df.A.values,index=df.B).to_dict()
%timeit df.set_index('A').to_dict()['B']
Output:
100 loops, best of 3: 7.04 ms per loop # WouterOvermeire
100 loops, best of 3: 9.83 ms per loop # Jeff
100 loops, best of 3: 4.28 ms per loop # Kikohs (me)
I have a sender class, like this
@class MyEntry;
@interface MySenderEntry : NSObject
@property (strong, nonatomic) MyEntry *entry;
@end
@implementation MySenderEntry
@end
I use this sender class for passing objects to prepareForSeque:sender:
-(void)didSelectItemAtIndexPath:(NSIndexPath*)indexPath
{
MySenderEntry *sender = [MySenderEntry new];
sender.entry = [_entries objectAtIndex:indexPath.row];
[self performSegueWithIdentifier:SEGUE_IDENTIFIER_SHOW_ENTRY sender:sender];
}
-(void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:SEGUE_IDENTIFIER_SHOW_ENTRY]) {
NSAssert([sender isKindOfClass:[MySenderEntry class]], @"MySenderEntry");
MySenderEntry *senderEntry = (MySenderEntry*)sender;
MyEntry *entry = senderEntry.entry;
NSParameterAssert(entry);
[segue destinationViewController].delegate = self;
[segue destinationViewController].entry = entry;
return;
}
if ([[segue identifier] isEqualToString:SEGUE_IDENTIFIER_HISTORY]) {
// ...
return;
}
if ([[segue identifier] isEqualToString:SEGUE_IDENTIFIER_FAVORITE]) {
// ...
return;
}
}
Standard SQL (or MySQL) does not permit the use of column aliases in a WHERE clause because
when the WHERE clause is evaluated, the column value may not yet have been determined.
(from MySQL documentation). What you can do is calculate the column value in the WHERE clause, save the value in a variable, and use it in the field list. For example you could do this:
SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
@postcode AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE (@postcode := SUBSTRING(`locations`.`raw`,-6,4)) NOT IN
(
SELECT `postcode` FROM `postcodes` WHERE `region` IN
(
'australia'
)
)
This avoids repeating the expression when it grows complicated, making the code easier to maintain.
I'm jumping in here a little late, but came across this page when pondering it myself. Of course I don't know how Facebook or Twitter justified it, but here is my own thought process for what it's worth.
In the end, I concluded that this practice is not that unsemantic (is that a word?). In fact, besides shortness and the nice association of "i is for icon," I think it's actually the most semantic choice for an icon when a straightforward <img>
tag is not practical.
1. The usage is consistent with the spec.
While it may not be what the W3 mainly had in mind, it seems to me the official spec for <i>
could accommodate an icon pretty easily. After all, the reply-arrow symbol is saying "reply" in another way. It expresses a technical term that may be unfamiliar to the reader and would be typically italicized. ("Here at Twitter, this is what we call a reply arrow.") And it is a term from another language: a symbolic language.
If, instead of the arrow symbol, Twitter used <i>shout out</i>
or <i>[Japanese character for reply]</i>
(on an English page), that would be consistent with the spec. Then why not <i>[reply arrow]</i>
? (I'm talking strictly HTML semantics here, not accessibility, which I'll get to.)
As far as I can see, the only part of the spec explicitly violated by icon usage is the "span of text" phrase (when the tag doesn't contain text also). It is clear that the <i>
tag is mainly meant for text, but that's a pretty small detail compared with the overall intent of the tag. The important question for this tag is not what format of content it contains, but what the meaning of that content is.
This is especially true when you consider that the line between "text" and "icon" can be almost nonexistent on websites. Text may look like more like an icon (as in the Japanese example) or an icon may look like text (as in a jpg button that says "Submit" or a cat photo with an overlaid caption) or text may be replaced or enhanced with an image via CSS. Text, image - who cares? It's all content. As long as everyone - humans with impairments, browsers with impairments, search engine spiders, and other machines of various kinds can understand that meaning, we've done our job.
So the fact that the writers of the spec didn't think (or choose) to clarify this shouldn't tie our hands from doing what makes sense and is consistent with the spirit of the tag. The <a>
tag was originally intended to take the user somewhere else, but now it might pop up a lightbox. Big whoop, right? If someone had figured out how to pop up a lightbox on click before the spec caught up, they still should have used the <a>
tag, not a <span>
, even if it wasn't entirely consistent with the current definition - because it came the closest and was still consistent with the spirit of the tag ("something will happen when you click here"). Same deal with <i>
- whatever type of thing you put inside it, or however creatively you use it, it expresses the general idea of an alternate or set-apart term.
2. The <i>
tag adds semantic meaning to an icon element.
The alternative option to carry an icon class by itself is <span>
, which of course has no semantic meaning whatsoever. When a machine asks the <span>
what it contains, it says, "I don't know. Could be anything." But the <i>
tag says, "I contain a different way of saying something than the usual way, or maybe an unfamiliar term." That's not the same as "I contain an icon," but it's a lot closer to it than <span>
got!
3. Eventually, common usage makes right.
In addition to the above, it's worth considering that machine readers (whether search engine, screen reader, or whatever) may at any time begin to take into account that Facebook, Twitter, and other websites use the <i>
tag for icons. They don't care about the spec as much as they care about extracting meaning from code by whatever means necessary. So they might use this knowledge of common usage to simply record that "there may be an icon here" or do something more advanced like triggering a look into the CSS for a hint to meaning, or who knows what. So if you choose to use the <i>
for icons on your website, you may be providing more meaning than the spec does.
Moreover, if this usage becomes widespread, it will likely be included in the spec in the future. Then you'll be going through your code, replacing <span>
s with <i>
's! So it may make sense to get on board with what seems to be the direction of the spec, especially when it doesn't clearly conflict with the current spec. Common usage tends to dictate language rules more than the other way around. If you're old enough, do you remember that "Web site" was the official spelling when the word was new? Dictionaries insisted there must be a space and Web must be capitalized. There were semantic reasons for that. But common usage said, "Whatever, that's stupid. I'm using 'website' because it's more concise and looks better." And before long, dictionaries officially acknowledged that spelling as correct.
4. So I'm going ahead and using it.
So, <i>
provides more meaning to machines because of the spec, it provides more meaning to humans because we easily associate "i" with "icon", and it's only one letter long. Win! And if you make sure to include equivalent text either inside the <i>
tag or right next to it (as Twitter does), then screen readers understand where to click to reply, the link is usable if CSS doesn't load, and human readers with good eyesight and a decent browser see a pretty icon. With all this in mind, I don't see the downside.
Keep your own back stack: myBackStack
. As you Add
a fragment to the FragmentManager
, also add it to myBackStack
. In onBackStackChanged()
pop from myBackStack
when its length is greater than getBackStackEntryCount
.
The problem was the table width. I had used width: 100%
for the table. The table columns are adjusted automatically after removing the width tag.
As John Weldon said all members must be static in a static class. Try
public static class employee
{
static NameValueCollection appSetting = ConfigurationManager.AppSettings;
}
Here is an approach that updates a DateTimeFormatter pattern with the correct suffix literal if it finds the pattern d'00'
, e.g. for day of month 1 it would be replaced with d'st'
. Once the pattern has been updated it can then just be fed into the DateTimeFormatter to do the rest.
private static String[] suffixes = {"th", "st", "nd", "rd"};
private static String updatePatternWithDayOfMonthSuffix(TemporalAccessor temporal, String pattern) {
String newPattern = pattern;
// Check for pattern `d'00'`.
if (pattern.matches(".*[d]'00'.*")) {
int dayOfMonth = temporal.get(ChronoField.DAY_OF_MONTH);
int relevantDigits = dayOfMonth < 30 ? dayOfMonth % 20 : dayOfMonth % 30;
String suffix = suffixes[relevantDigits <= 3 ? relevantDigits : 0];
newPattern = pattern.replaceAll("[d]'00'", "d'" + suffix + "'");
}
return newPattern;
}
It does require that the original pattern is updated just prior to every formatting call, e.g.
public static String format(TemporalAccessor temporal, String pattern) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(updatePatternWithDayOfMonthSuffix(temporal, pattern));
return formatter.format(temporal);
}
So this is useful if the formatting pattern is defined outside of Java code, e.g. a template, where as if you can define the pattern in Java then the answer by @OleV.V. might be more appropriate
listStr = open("file_name","mode")
if "search element" in listStr:
print listStr.index("search element") # This will gives you the line number
You can use :
sheet.addMergedRegion(new CellRangeAddress(startRowIndx, endRowIndx, startColIndx,endColIndx));
Make sure the CellRangeAddress does not coincide with other merged regions as that will throw an exception.
For what you were trying to do this should work:
sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 0, 3));
<div id="msg"></div>
<!-- put above tag on body to see selected value or error -->
<script>
$(function(){
$("#HoursEntry").change(function(){
var HoursEntry = $("#HoursEntry option:selected").val();
console.log(HoursEntry);
if(HoursEntry == "")
{
$("#msg").html("Please select at least One option");
return false;
}
else
{
$("#msg").html("selected val is "+HoursEntry);
}
});
});
</script>
You can change the size of the plot by adding this before you create the figure.
plt.rcParams["figure.figsize"] = [16,9]
I'm using git version 2.19.2.windows.1
.
the only thing that worked for me was to remove the .git/rebase-apply/
directory and do a git reset --hard
.
I would make the class final
and every method would be static
.
So the class cannot be extended and the methods can be called by Classname.methodName
. If you add members, be sure that they work thread safe ;)
That is not how the TryGetValue
works. It returns true
or false
based on whether the key is found or not, and sets its out
parameter to the corresponding value if the key is there.
If you want to check if the key is there or not and do something when it's missing, you need something like this:
bool hasValue = Data_Array.TryGetValue("XML_File", out value);
if (hasValue) {
xmlfile = value;
} else {
// do something when the value is not there
}
jPDFImages is not free but a commercial library which converts PDF pages to images in JPEG, TIFF or PNG format. The output image size is customizable.
$().ready(function(){_x000D_
_x000D_
$('div.alert').delay(1500);_x000D_
$('div.alert').hide(1000);_x000D_
});
_x000D_
div.alert{_x000D_
color: green;_x000D_
background-color: rgb(50,200,50, .5);_x000D_
padding: 10px;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="alert"><p>Inserted Successfully . . .</p></div>
_x000D_
You've almost got it. Tell jquery you want to load only the script:
$("#myBtn").click(function() {
$("#myDiv").load("trackingCode.html script");
});
The safest bet is to create a class on those tables and use that. Currently getting something like this to work in all major browsers is unlikely.
Best comment I ever saw was
/*
There is no accounting for pointers
*/
try {
$result=DB::table('users')->whereExists(function ($Query){
$Query->where('id','<','14162756');
$Query->whereBetween('password',[14162756,48384486]);
$Query->whereIn('id',[3,8,12]);
});
}catch (\Exception $error){
Log::error($error);
DB::rollBack(1);
return redirect()->route('bye');
}
I can't believe the accepted answer has so many upvotes -- it's a horrible method.
Here's the correct way to do it, with date_trunc:
SELECT date_trunc('month', txn_date) AS txn_month, sum(amount) as monthly_sum
FROM yourtable
GROUP BY txn_month
It's bad practice but you might be forgiven if you use
GROUP BY 1
in a very simple query.
You can also use
GROUP BY date_trunc('month', txn_date)
if you don't want to select the date.
If you're using Bootstrap 4, use .w-auto
.
You can use either resample or Grouper
(which resamples under the hood).
First make sure that the datetime column is actually of datetimes (hit it with pd.to_datetime
). It's easier if it's a DatetimeIndex:
In [11]: df1
Out[11]:
abc xyz
Date
2013-06-01 100 200
2013-06-03 -20 50
2013-08-15 40 -5
2014-01-20 25 15
2014-02-21 60 80
In [12]: g = df1.groupby(pd.Grouper(freq="M")) # DataFrameGroupBy (grouped by Month)
In [13]: g.sum()
Out[13]:
abc xyz
Date
2013-06-30 80 250
2013-07-31 NaN NaN
2013-08-31 40 -5
2013-09-30 NaN NaN
2013-10-31 NaN NaN
2013-11-30 NaN NaN
2013-12-31 NaN NaN
2014-01-31 25 15
2014-02-28 60 80
In [14]: df1.resample("M", how='sum') # the same
Out[14]:
abc xyz
Date
2013-06-30 40 125
2013-07-31 NaN NaN
2013-08-31 40 -5
2013-09-30 NaN NaN
2013-10-31 NaN NaN
2013-11-30 NaN NaN
2013-12-31 NaN NaN
2014-01-31 25 15
2014-02-28 60 80
Note: Previously pd.Grouper(freq="M")
was written as pd.TimeGrouper("M")
. The latter is now deprecated since 0.21.
I had thought the following would work, but it doesn't (due to as_index
not being respected? I'm not sure.). I'm including this for interest's sake.
If it's a column (it has to be a datetime64 column! as I say, hit it with to_datetime
), you can use the PeriodIndex:
In [21]: df
Out[21]:
Date abc xyz
0 2013-06-01 100 200
1 2013-06-03 -20 50
2 2013-08-15 40 -5
3 2014-01-20 25 15
4 2014-02-21 60 80
In [22]: pd.DatetimeIndex(df.Date).to_period("M") # old way
Out[22]:
<class 'pandas.tseries.period.PeriodIndex'>
[2013-06, ..., 2014-02]
Length: 5, Freq: M
In [23]: per = df.Date.dt.to_period("M") # new way to get the same
In [24]: g = df.groupby(per)
In [25]: g.sum() # dang not quite what we want (doesn't fill in the gaps)
Out[25]:
abc xyz
2013-06 80 250
2013-08 40 -5
2014-01 25 15
2014-02 60 80
To get the desired result we have to reindex...
Unexpected end of file
means that something else was expected before the PHP parser reached the end of the script.
Judging from your HUGE file, it's probably that you're missing a closing brace (}
) from an if
statement.
Please at least attempt the following things:
;
in some of your embedded PHP statements, and not in others, ie. <?php echo base_url(); ?>
vs <?php echo $this->layouts->print_includes() ?>
. It's not required, so don't use it (or do, just do one or the other).Just format like that:
s = "your string"; raw_s = r'{0}'.format(s)
Use the defaultDate option
$( ".selector" ).datepicker({ defaultDate: '01/01/01' });
If you change your date format, make sure to change the input into defaultDate (e.g. '01-01-2001')
In my case, it was ReSharper.
StackOverflow: How can I disable ReSharper in Visual Studio and enable it again?
StackOverflow: Is there a way to mark up code to tell ReSharper not to format it?
It was ReSharper in the end:
On the latest version of ReSharper, there are more options: untick everything on this page, and ensure all dropdowns are set to the equivalent of None
.
ReSharper "typing assist" is like a 3-year-old trying to "help" build a card castle. A simple backspace or an enter key will (poorly) reformat entire blocks of code, requiring it to be undone or painfully formatted back to the original.
And if that is not enough, this is the bit that adds delays when typing so sometimes it feels like trying to run in skis.
You can wrap it in your own function:
function isNullAndUndef(variable) {
return (variable !== null && variable !== undefined);
}
Type mysql --version
to see if it is installed.
To find location use find -name mysql
.
BigDecimal decPrec = (BigDecimal)yo.get("Avg");
decPrec = decPrec.setScale(5, RoundingMode.CEILING);
String value= String.valueOf(decPrec);
This way you can set specific precision of a BigDecimal
.
The value of decPrec was 1.5726903423607562595809913132345426
which is rounded off to 1.57267
.
I hope that I am understing your question correctly, but you can do this very quickly with Linq. I'm assuming that universally you will always have an Id property. Just create an interface to ensure this.
If how you identify an object to be the same changes from class to class, I would recommend passing in a delegate that returns true if the two objects have the same persistent id.
Here is how to do it in Linq:
List<Employee> listA = new List<Employee>();
List<Employee> listB = new List<Employee>();
listA.Add(new Employee() { Id = 1, Name = "Bill" });
listA.Add(new Employee() { Id = 2, Name = "Ted" });
listB.Add(new Employee() { Id = 1, Name = "Bill Sr." });
listB.Add(new Employee() { Id = 3, Name = "Jim" });
var identicalQuery = from employeeA in listA
join employeeB in listB on employeeA.Id equals employeeB.Id
select new { EmployeeA = employeeA, EmployeeB = employeeB };
foreach (var queryResult in identicalQuery)
{
Console.WriteLine(queryResult.EmployeeA.Name);
Console.WriteLine(queryResult.EmployeeB.Name);
}
How large is length
? You may do better to re-use a fixed sized (moderately large, but not obscene) buffer, and forget BinaryReader
... just use Stream.Read
and Stream.Write
.
(edit) something like:
private static void copy(string srcFile, string dstFile, int offset,
int length, byte[] buffer)
{
using(Stream inStream = File.OpenRead(srcFile))
using (Stream outStream = File.OpenWrite(dstFile))
{
inStream.Seek(offset, SeekOrigin.Begin);
int bufferLength = buffer.Length, bytesRead;
while (length > bufferLength &&
(bytesRead = inStream.Read(buffer, 0, bufferLength)) > 0)
{
outStream.Write(buffer, 0, bytesRead);
length -= bytesRead;
}
while (length > 0 &&
(bytesRead = inStream.Read(buffer, 0, length)) > 0)
{
outStream.Write(buffer, 0, bytesRead);
length -= bytesRead;
}
}
}
Here is my solution:
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
this.pageSource = request.source;
var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
alert(title)
}
});
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
chrome.tabs.executeScript(
tabs[0].id,
{ code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
);
});
You can just use the following syntax and the object will be fully shown in the console:
console.log('object evt: %O', object);
I use Chrome browser don't know if this is adaptable for other browsers.
In macOS for those who are using the express version 4.x.x
and using the DOTENV
plugin, need to use like this:
After installing the plugin import like the following in the file where you init the application:
require('dotenv').config({path: path.resolve(__dirname+'/.env')});
In the root directory create a file '.env' and add the varaiable like:
NODE_ENV=development
or
NODE_ENV = development
In HTML5, the easiest, and fastest, way to center your <th>THcontent</th>
is to add a colspan
like this:
<th colspan="3">Thcontent</th>
This will work if your table is three columns. So if you have a four-column table, add a colspan
of 4, etc.
You can manage the location furthermore in the CSS file while you have put your colspan
in HTML like I said.
th {
text-align: center; /* Or right or left */
}
Indeed ADD go /usr/local/
will add content of go
folder and not the folder itself, you can use Thomasleveil solution or if that did not work for some reason you can change WORKDIR
to /usr/local/
then add your directory to it like:
WORKDIR /usr/local/
COPY go go/
or
WORKDIR /usr/local/go
COPY go ./
But if you want to add multiple folders, it will be annoying to add them like that, the only solution for now as I see it from my current issue is using COPY . .
and exclude all unwanted directories and files in .dockerignore
, let's say I got folders and files:
- src
- tmp
- dist
- assets
- go
- justforfun
- node_modules
- scripts
- .dockerignore
- Dockerfile
- headache.lock
- package.json
and I want to add src assets package.json justforfun go
so:
in Dockerfile:
FROM galaxy:latest
WORKDIR /usr/local/
COPY . .
in .dockerignore file:
node_modules
headache.lock
tmp
dist
Or for more fun (or you like to confuse more people make them suffer as well :P) can be:
*
!src
!assets
!go
!justforfun
!scripts
!package.json
In this way you ignore everything, but excluding what you want to be copied or added only from "ignore list".
It is a late answer but adding more ways to do the same covering even more cases.
If you need to continue with additional logic use...
break;
or if you have a value to return...
return my_value_to_be_returned;
However, looking at your code, I believe you will control the loop with the revised example below without using a break or return...
private void CheckLog()
{
bool continueLoop = true;
while (continueLoop)
{
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while (continueLoop && (s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
continueLoop = false;
}
}
}
}
}
I didnt try Sumama Waheed's answer but what worked for me was replacing the bin/catalina.jar with a working jar (I disposed of an older tomcat) and after adding in NetBeans, I put the original catalina.jar again.
The document.write method is very limited. You can only use it before the page has finished loading. You can't use it to update the contents of a loaded page.
What you probably want is innerHTML.
I am working on an application in which we track live route. Passenger wants to show current position of driver and the expected arrival time to reach at his/her location. So I need to add some duration into current time.
So I found the below mentioned way to do the same. We can add any duration(hour,minutes and seconds) in our current time by moment:
var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format
var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes
var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format
It fulfills my requirement. May be it can help you.
You can't just add a border to the span because it will break the layout because of the way width is calculate: width = border + padding + width. Since the container is 940px and the span is 940px, adding 2px border (so 4px altogether) will make it look off centered. The work around is to change the width to include the 4px border (original - 4px) or have another div inside that creates the 2px border.
Tried everything mentioned (browser preferences, hsts, etc.) but nothing worked for me.
I solved it by adding a trailing .localhost
to the host aliases.
Like this:
127.0.0.1 myproject.localhost
127.0.0.1 dev.project.localhost
I think you are looking for this
String[] car = new String[10];
int size = car.length;
You need to have the testng.jar
under classpath.
try C:\projectfred> java -cp "path-tojar/testng.jar:path_to_yourtest_classes" org.testng.TestNG testng.xml
Update:
Under linux I ran this command and it would be some thing similar on Windows either
test/bin# java -cp ".:../lib/*" org.testng.TestNG testng.xml
Directory structure:
/bin - All my test packages are under bin including testng.xml
/src - All source files are under src
/lib - All libraries required for the execution of tests are under this.
Once I compile all sources they go under bin directory. So, in the classpath I need to specify contents of bin directory and all the libraries like testng.xml, loggers etc over here. Also copy testng.xml to bin folder if you dont want to specify the full path where the testng.xml is available.
/bin
-- testng.xml
-- testclasses
-- Properties files if any.
/lib
-- testng.jar
-- log4j.jar
Update
:
Go to the folder MyProject
and type run the java command like the way shown below:-
java -cp ".: C:\Program Files\jbdevstudio4\studio\plugins\*" org.testng.TestNG testng.xml
I believe the testng.xml file is under C:\Users\me\workspace\MyProject
if not please give the full path for testng.xml
file
When we create the method (function) in Java, the method like this..
data-type name of the method (data-type variable-name)
In the parenthesis, these are the parameters, and when we call the method (function) we pass the value of this parameter, which are called the arguments.
You simply need to enclose your SELECT
statements in parentheses to indicate that they are subqueries:
SET cityLat = (SELECT cities.lat FROM cities WHERE cities.id = cityID);
Alternatively, you can use MySQL's SELECT ... INTO
syntax. One advantage of this approach is that both cityLat
and cityLng
can be assigned from a single table-access:
SELECT lat, lng INTO cityLat, cityLng FROM cities WHERE id = cityID;
However, the entire procedure can be replaced with a single self-joined SELECT
statement:
SELECT b.*, HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
FROM cities AS a, cities AS b
WHERE a.id = cityID
ORDER BY dist
LIMIT 10;
Install HookyQR.beautify extension. It will beautify your javascript, JSON, CSS, Sass, and HTML in Visual Studio Code. It is the most use extensions for this purpose
From this post:
To get the entire PC CPU and Memory usage:
using System.Diagnostics;
Then declare globally:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
Then to get the CPU time, simply call the NextValue()
method:
this.theCPUCounter.NextValue();
This will get you the CPU usage
As for memory usage, same thing applies I believe:
private PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
Then to get the memory usage, simply call the NextValue()
method:
this.theMemCounter.NextValue();
For a specific process CPU and Memory usage:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Process", "% Processor Time",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
private PerformanceCounter theMemCounter =
new PerformanceCounter("Process", "Working Set",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?
To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters
The difference between Processor\% Processor Time
and Process\% Processor Time
is Processor
is from the PC itself and Process
is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters
An alternative to using the Performance Counter
Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.
To clone a branch without fetching other branches:
mkdir $BRANCH
cd $BRANCH
git init
git remote add -t $BRANCH -f origin $REMOTE_REPO
git checkout $BRANCH
Here is an example that you can use. Havent got Google Finance yet, but Here is the Yahoo Example. You will need the HTMLAgilityPack , Which is awesome. Happy Symbol Hunting.
Call the procedure by using YahooStockRequest(string Symbols);
Where Symbols = a comma-delimited string of symbols, or just one symbol
public string YahooStockRequest(string Symbols,bool UseYahoo=true)
{
{
string StockQuoteUrl = string.Empty;
try
{
// Use Yahoo finance service to download stock data from Yahoo
if (UseYahoo)
{
string YahooSymbolString = Symbols.Replace(",","+");
StockQuoteUrl = @"http://finance.yahoo.com/q?s=" + YahooSymbolString + "&ql=1";
}
else
{
//Going to Put Google Finance here when I Figure it out.
}
// Initialize a new WebRequest.
HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(StockQuoteUrl);
// Get the response from the Internet resource.
HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
// Read the body of the response from the server.
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
string pageSource;
using (StreamReader sr = new StreamReader(webresp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
doc.LoadHtml(pageSource.ToString());
if (UseYahoo)
{
string Results=string.Empty;
//loop through each Symbol that you provided with a "," delimiter
foreach (string SplitSymbol in Symbols.Split(new char[] { ',' }))
{
Results+=SplitSymbol + " : " + doc.GetElementbyId("yfs_l10_" + SplitSymbol).InnerText + Environment.NewLine;
}
return (Results);
}
else
{
return (doc.GetElementbyId("ref_14135_l").InnerText);
}
}
catch (WebException Webex)
{
return("SYSTEM ERROR DOWNLOADING SYMBOL: " + Webex.ToString());
}
}
}
The reason this was happening to me (with Photon) was easily fixed by changing an Eclipse general preference:
Window -> Preferences -> General: Uncheck: "Always run in background"
Once you make that change, whenever you shutdown Eclipse, it will no longer leave the javaw.exe process running in the background. I’m guessing this is a bug in Photon (or a bug with using the Amazon Corretto OpenJDK version of Java with Eclipse) that will one day be fixed.
you could use redis with the lightning fast node_redis client. It even has built-in pubsub semantics.
You probably want to use something like jQuery, which makes JS programming easier.
Something like:
$(document).ready(function(){
// Your code here
});
Would seem to do what you are after.
Years later and this is still a common problem, but its not always facebook's cache: It is very often human error (allow me to elaborate)
OG:TYPE effects your image scrape:
Be aware that og:type=website will cause any /sub-pages/ of that url to become "canonical". This means you will have trouble getting your images to update using the scraper no matter what you do.
Consider this "assumption and common mistake"
-<meta property="og:type" content="website" />
=> https://www.example.org (parent)
-<meta property="og:type" content="website" />
=> https://www.example.org/sub-page/
-<meta property="og:type" content="website" />
=> https://www.example.org/sub-page/child-2/
- Ergo: /sub-page/
and /child-2/
will inherit the og:image
of the parent
Those are not "all websites", 1 is a website, the others are articles.
If you do that Facebook will think all of those are canonical and it will put the FIRST og:image into all of them. (try it, you'll see) - if you set the og:url to be your root or parent domain you've told facebook they are all canonical. (there is good reason for that, but its off topic)
Consider this solution (which is what most people "really want")
-<meta property="og:type" content="article" />
=> https://www.example.org/sub-page/
-<meta property="og:type" content="article" />
=> https://www.example.org/sub-page/child-2/
If you do that now Facebook will give you far far less problems with scraping your NEW images.
In closing, YES the cache busters, random vars, changing urls and suggestions here can work, but they will seem like "intermittent voodoo" if the og:type
is not specified correctly.
PS: remember that a CDN or serverside cache will serve to Facebook's scraper even if you "think" you can see the most recent version. (I wont spend any time on this other than to point out it will waste colossal amounts of your time if not double checked.)
Though not explicitly stated in the question, the purpose is to connect to a specific schema/database.
Another option is to directly connect to the schema. Example:
sudo -u postgres psql -d my_database_name
Source from man psql
:
-d dbname
--dbname=dbname
Specifies the name of the database to connect to. This is equivalent to specifying dbname as the first non-option argument on the command line.
If this parameter contains an = sign or starts with a valid URI prefix (postgresql:// or postgres://), it is treated as a conninfo string. See Section 31.1.1, “Connection Strings”, in the
documentation for more information.
One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))
For example, if you have a vector as elements
and would like to get sum
of it
elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432
Apparently, the last digital as 1
been truncated, the ideal result should be -876.54321
, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements))
, redundant zero(s) generate as -876.5432100000
Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321
, there are 5 decimal digits need to print, then we can set up a parameter for format
function as below:
decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321
We can change the decimal_length
based on each time query, so it can satisfy different decimal printing requirement.
I think the easiest and the cleanest way, is to use protocol to avoid inherit and code repetition. You can change this properties directly from storyboard
protocol Traceable {
var cornerRadius: CGFloat { get set }
var borderColor: UIColor? { get set }
var borderWidth: CGFloat { get set }
}
extension UIView: Traceable {
@IBInspectable var cornerRadius: CGFloat {
get { return layer.cornerRadius }
set {
layer.masksToBounds = true
layer.cornerRadius = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get {
guard let cgColor = layer.borderColor else { return nil }
return UIColor(cgColor: cgColor)
}
set { layer.borderColor = newValue?.cgColor }
}
@IBInspectable var borderWidth: CGFloat {
get { return layer.borderWidth }
set { layer.borderWidth = newValue }
}
}
Update
In this link you can find an example with the utility of Traceable protocol
Undefined offset error in PHP is Like 'ArrayIndexOutOfBoundException' in Java.
example:
<?php
$arr=array('Hello','world');//(0=>Hello,1=>world)
echo $arr[2];
?>
error: Undefined offset 2
It means you're referring to an array key that doesn't exist. "Offset" refers to the integer key of a numeric array, and "index" refers to the string key of an associative array.
SELECT TOP 2 [Id] FROM table
Try this function pass the datatable and file path where you want to export
public void CreateCSVFile(ref DataTable dt, string strFilePath)
{
try
{
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(strFilePath, false);
// First we will write the headers.
//DataTable dt = m_dsProducts.Tables[0];
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
catch (Exception ex)
{
throw ex;
}
}
Actually, as I know, you can't do some actions exactly when resize is off, simply because you don't know future user's actions. But you can assume the time passed between two resize events, so if you wait a little more than this time and no resize is made, you can call your function.
Idea is that we use setTimeout
and it's id in order to save or delete it. For example we know that time between two resize events is 500ms, therefore we will wait 750ms.
var a;_x000D_
$(window).resize(function(){_x000D_
clearTimeout(a);_x000D_
a = setTimeout(function(){_x000D_
// call your function_x000D_
},750);_x000D_
});
_x000D_
If you read the help file for ?boxplot
, you'll see there is a names=
parameter.
boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))
To browse .NET code dependencies, you can use the capabilities of the tool NDepend. The tool proposes:
For example such query can look like:
from m in Methods
let depth = m.DepthOfIsUsing("NHibernate.NHibernateUtil.Entity(Type)")
where depth >= 0 && m.IsUsing("System.IDisposable")
orderby depth
select new { m, depth }
And its result looks like: (notice the code metric depth, 1 is for direct callers, 2 for callers of direct callers...) (notice also the Export to Graph button to export the query result to a Call Graph)
The dependency graph looks like:
The dependency matrix looks like:
The dependency matrix is de-facto less intuitive than the graph, but it is more suited to browse complex sections of code like:
Disclaimer: I work for NDepend
Thanks for the answers above, that helped me a lot :-) But for those (like me) forced to still support Android 1.5 we can use java reflection for backward compatible:
Configuration conf = getResources().getConfiguration();
int screenLayout = 1; // application default behavior
try {
Field field = conf.getClass().getDeclaredField("screenLayout");
screenLayout = field.getInt(conf);
} catch (Exception e) {
// NoSuchFieldException or related stuff
}
// Configuration.SCREENLAYOUT_SIZE_MASK == 15
int screenType = screenLayout & 15;
// Configuration.SCREENLAYOUT_SIZE_SMALL == 1
// Configuration.SCREENLAYOUT_SIZE_NORMAL == 2
// Configuration.SCREENLAYOUT_SIZE_LARGE == 3
// Configuration.SCREENLAYOUT_SIZE_XLARGE == 4
if (screenType == 1) {
...
} else if (screenType == 2) {
...
} else if (screenType == 3) {
...
} else if (screenType == 4) {
...
} else { // undefined
...
}
If it is on the command line, you can run php
with -ddisplay_errors=1
to override the setting in php.ini
:
php -ddisplay_errors=1 script.php
in /etc/my.cnf
:
[mysqld]
...
performance_schema = 0
table_cache = 0
table_definition_cache = 0
max-connect-errors = 10000
query_cache_size = 0
query_cache_limit = 0
...
Good work on server with 256MB Memory.
try this:
select TITLE,
(length(DESCRIPTION )-length(replace(DESCRIPTION ,'value','')))/5 as COUNT
FROM <table>
Can't you set the Loglevel in httpd.conf to debug? (I'm using FreeBSD)
ee usr/local/etc/apache22/httpd.conf
change loglevel :
'LogLevel: Control the number of messages logged to the error_log. Possible values include: debug, info, notice, warn, error, crit, alert, emerg.'
Try changing to debug and re-checking the error log after that.
If you are using the IN
operator, the SQL engine will scan all records fetched from the inner query. On the other hand if we are using EXISTS
, the SQL engine will stop the scanning process as soon as it found a match.
Try this uncheck the "verify apps via USB" in developer options and then turn on and off the "USB Debugging". It works with me.
If you use Eclipse as your IDE I would recommend the excellent eclipse plugin memory analyzer
Another option is to use JVisualVM, it can read (and create) heap dumps as well, and is shipped with every JDK. You can find it in the bin directory of your JDK.
For reference, here's an sscce that illustrates the difference. Console:
SELECTED ACTION_PERFORMED DESELECTED ACTION_PERFORMED
Code:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** @see http://stackoverflow.com/q/9882845/230513 */
public class Listeners {
private void display() {
JFrame f = new JFrame("Listeners");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox b = new JCheckBox("JCheckBox");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getID() == ActionEvent.ACTION_PERFORMED
? "ACTION_PERFORMED" : e.getID());
}
});
b.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
System.out.println(e.getStateChange() == ItemEvent.SELECTED
? "SELECTED" : "DESELECTED");
}
});
JPanel p = new JPanel();
p.add(b);
f.add(p);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Listeners().display();
}
});
}
}
I'm using simple alias to create pull request,
alias pr='open -n -a "Google Chrome" --args "https://github.com/user/repo/compare/pre-master...nawarkhede:$(git_current_branch)\?expand\=1"'
So I found a solution. I created an angularJS service, we'll call it MyDataRepository and I created a module for it. I then serve up this javascript file from my server-side controller:
HTML:
<script src="path/myData.js"></script>
Server-side:
@RequestMapping(value="path/myData.js", method=RequestMethod.GET)
public ResponseEntity<String> getMyDataRepositoryJS()
{
// Populate data that I need into a Map
Map<String, String> myData = new HashMap<String,String>();
...
// Use Jackson to convert it to JSON
ObjectMapper mapper = new ObjectMapper();
String myDataStr = mapper.writeValueAsString(myData);
// Then create a String that is my javascript file
String myJS = "'use strict';" +
"(function() {" +
"var myDataModule = angular.module('myApp.myData', []);" +
"myDataModule.service('MyDataRepository', function() {" +
"var myData = "+myDataStr+";" +
"return {" +
"getData: function () {" +
"return myData;" +
"}" +
"}" +
"});" +
"})();"
// Now send it to the client:
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/javascript");
return new ResponseEntity<String>(myJS , responseHeaders, HttpStatus.OK);
}
I can then inject MyDataRepository where ever I need it:
someOtherModule.service('MyOtherService', function(MyDataRepository) {
var myData = MyDataRepository.getData();
// Do what you have to do...
}
This worked great for me, but I am open to any feedback if anyone has any. }
In case you would like to use timeout middleware and exclude a specific route:
var timeout = require('connect-timeout');
app.use(timeout('5s')); //set 5s timeout for all requests
app.use('/my_route', function(req, res, next) {
req.clearTimeout(); // clear request timeout
req.setTimeout(20000); //set a 20s timeout for this request
next();
}).get('/my_route', function(req, res) {
//do something that takes a long time
});
Like the error says, row
is a tuple, so you can't do row["pool_number"]
. You need to use the index: row[0]
.
Looks like the setup.py uses easy_install (i.e. setuptools
). Just install the setuptools package and you will be all set.
To install setuptools in Python 2.6, see the answer to this question.
This is helpful for people struggling to find better site to generate icons and splashscreen
You can reset the padding (and I think everything else) with initial
to the default.
p {
padding: initial;
}
You may not be able to do it with @ResponseBody, but something like this should work:
package xxx;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class FooBar {
@RequestMapping(value="foo/bar", method = RequestMethod.GET)
public void fooBar(HttpServletResponse response) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(myService.getJson().getBytes());
response.setContentType("application/json");
response.setContentLength(out.size());
response.getOutputStream().write(out.toByteArray());
response.getOutputStream().flush();
}
}
What you want is not possible. You must need to set TypeFace
in your Code.
In XML
what you can do is
android:typeface="sans" | "serif" | "monospace"
other then this you can not play much with the Fonts in XML. :)
For Arial
you need to set type face in your code.
According to the article Chris Corio: Teach Your Apps To Play Nicely With Windows Vista User Account Control, MSDN Magazine, Jan. 2007, only ShellExecute
checks the embedded manifest and prompts the user for elevation if needed, while CreateProcess
and other APIs don't. Hope it helps.
See also: same article as .chm.
Very little Javascript is necessary:
window.onload = function() {
document.body.className += " loaded";
}
Now the CSS:
.fadein {
opacity: 0;
-moz-transition: opacity 1.5s;
-webkit-transition: opacity 1.5s;
-o-transition: opacity 1.5s;
transition: opacity 1.5s;
}
body.loaded .fadein {
opacity: 1;
}
I know the question said "without Javascript", but I think it's worth pointing out that there is an easy solution involving one line of Javascript.
It could even be inline Javascript, something like that:
<body onload="document.body.className += ' loaded';" class="fadein">
That's all the JavaScript that's needed.
My solution...
HTML :
<input type="file" id="uploadImages" style="display:none;" multiple>
<input type="button" id="callUploadImages" value="Select">
<input type="button" id="uploadImagesInfo" value="0 file(s)." disabled>
<input type="button" id="uploadProductImages" value="Upload">
Jquery:
$('#callUploadImages').click(function(){
$('#uploadImages').click();
});
$('#uploadImages').change(function(){
var uploadImages = $(this);
$('#uploadImagesInfo').val(uploadImages[0].files.length+" file(s).");
});
This is just evil :D
Why should LINQ be faster? It also uses loops internally.
Most of the times, LINQ will be a bit slower because it introduces overhead. Do not use LINQ if you care much about performance. Use LINQ because you want shorter better readable and maintainable code.
I beleive
$("#myElement").attr("title", "new title value")
or
$("#myElement").prop("title", "new title value")
should do the trick...
I think you can find all the core functions in the jQuery Docs, although I hate the formatting.
Uri myUri = Uri.parse("http://www.google.com");
Here's the doc http://developer.android.com/reference/android/net/Uri.html#parse%28java.lang.String%29
ExecuteNonQuery
This ExecuteNonQuery method will be used only for insert, update and delete, Create, and SET statements. ExecuteNonQuery method will return number of rows effected with INSERT, DELETE or UPDATE operations.
ExecuteScalar
It’s very fast to retrieve single values from database. Execute Scalar will return single row single column value i.e. single value, on execution of SQL Query or Stored procedure using command object. ExecuteReader
Execute Reader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object. This one is forward only retrieval of records and it is used to read the table values from first to last.
You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.
With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.
http://www.dba-oracle.com/t_with_clause.htm
It requires some effort though. Don't be afraid to post a concrete example.
Using simple pseudo table DUAL helps too.
Yes - .gitignore
system only ignores files not currently under version control from git.
I.e. if you've already added a file called test.txt
using git-add
, then adding test.txt
to .gitignore
will still cause changes to test.txt
to be tracked.
You would have to git rm test.txt
first and commit that change. Only then will changes to test.txt
be ignored.
I was facing same issue with ffmpeg library after merging two Android projects as one project.
Actually issue was arriving due to two different versions of ffmpeg library but they were loaded with same names in memory. One library was placed in JNiLibs while other was inside another library used as module. I was not able to modify the code of module as it was readonly so I renamed the one used in my own code to ffmpegCamera and loaded it in memory with same name.
System.loadLibrary("ffmpegCamera");
This resolved the issue and now both versions of libraries are loading well as separate name and process id in memory.
class="rounded"
or
class="rounded-circle"
Okay, this solution is far simpler than the ones already here, and allows different column widths for different device widths.
<div class="row">
<div ng-repeat="image in images">
<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
... your content here ...
</div>
<div class="clearfix visible-lg" ng-if="($index + 1) % 6 == 0"></div>
<div class="clearfix visible-md" ng-if="($index + 1) % 4 == 0"></div>
<div class="clearfix visible-sm" ng-if="($index + 1) % 3 == 0"></div>
<div class="clearfix visible-xs" ng-if="($index + 1) % 2 == 0"></div>
</div>
</div>
Note that the % 6
part is supposed to equal the number of resulting columns. So if on the column element you have the class col-lg-2
there will be 6 columns, so use ... % 6
.
This technique (excluding the ng-if
) is actually documented here: Bootstrap docs