Process may have multiple threads. These threads may share memory and are the units of execution within a process.
Processes run on the CPU, so threads are residing under each process. Processes are individual entities which run independently. If you want to share data or state between each process, you may use a memory-storage tool such as Cache(redis, memcache)
, Files
, or a Database
.
A variation of Lea Verou solution with perfect indentation in multi-line entries could be something like this:
ul{
list-style: none;
position: relative;
padding: 0;
margin: 0;
}
li{
padding-left: 1.5em;
}
li:before {
position: absolute;
content: "•";
color: red;
left: 0;
}
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];
$.each(arrofobject, function(index, val) {
console.log(val.category);
});
no there is an alternative way to implement goto statement
class id:
def data1(self):
name=[]
age=[]
n=1
while n>0:
print("1. for enter data")
print("2. update list")
print("3. show data")
print("choose what you want to do ?")
ch=int(input("enter your choice"))
if ch==1:
n=int(input("how many elemet you want to enter="))
for i in range(n):
name.append(input("NAME "))
age.append(int(input("age ")))
elif ch==2:
name.append(input("NAME "))
age.append(int(input("age ")))
elif ch==3:
try:
if name==None:
print("empty list")
else:
print("name \t age")
for i in range(n):
print(name[i]," \t ",age[i])
break
except:
print("list is empty")
print("do want to continue y or n")
ch1=input()
if ch1=="y":
n=n+1
else:
print("name \t age")
for i in range(n):
print(name[i]," \t ",age[i])
n=-1
p1=id()
p1.data1()
Why use jQuery for this?
str = "123-4";
alert(str.substring(0,str.length - 1));
Of course if you must:
Substr w/ jQuery:
//example test element
$(document.createElement('div'))
.addClass('test')
.text('123-4')
.appendTo('body');
//using substring with the jQuery function html
alert($('.test').html().substring(0,$('.test').html().length - 1));
I landed here from one of its recent dup's, and though this question is more than answered, I couldn't help decompiling the code and adding "yet another answer" :-)
To be accurate (and probably, a bit pedantic),
int y = 2;
y = y++;
is compiled into:
int y = 2;
int tmp = y;
y = y+1;
y = tmp;
If you javac
this Y.java
class:
public class Y {
public static void main(String []args) {
int y = 2;
y = y++;
}
}
and javap -c Y
, you get the following jvm code (I have allowed me to comment the main method with the help of the Java Virtual Machine Specification):
public class Y extends java.lang.Object{
public Y();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_2 // Push int constant `2` onto the operand stack.
1: istore_1 // Pop the value on top of the operand stack (`2`) and set the
// value of the local variable at index `1` (`y`) to this value.
2: iload_1 // Push the value (`2`) of the local variable at index `1` (`y`)
// onto the operand stack
3: iinc 1, 1 // Sign-extend the constant value `1` to an int, and increment
// by this amount the local variable at index `1` (`y`)
6: istore_1 // Pop the value on top of the operand stack (`2`) and set the
// value of the local variable at index `1` (`y`) to this value.
7: return
}
Thus, we finally have:
0,1: y=2
2: tmp=y
3: y=y+1
6: y=tmp
Also, make sure you're not placing hash symbol (#) inside your selector in a
document.getElementById('#map') // bad
document.getElementById('map') // good
statement. It's not a jQuery. Just a quick reminder for someone in a hurry.
The answer from dhams is correct (after having been edited several times), but as the many edits of the code shows, it is difficult to write correct and robust code for deleting a directory (with sub-dirs) yourself. So I strongly suggest using Apache Commons IO, or some other API that does this for you:
import org.apache.commons.io.FileUtils;
...
// Delete local cache dir (ignoring any errors):
FileUtils.deleteQuietly(context.getCacheDir());
PS: Also delete the directory returned by context.getExternalCacheDir() if you use that.
To be able to use Apache Commons IO, add this to your build.gradle
file, in the dependencies
part:
compile 'commons-io:commons-io:2.4'
You can use the sequence method list.extend
to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.
>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
So you can use list.append()
to append a single value, and list.extend()
to append multiple values.
Can try with below code
WebDriverWait wait = new WebDriverWait(driver, 30);
Pass other element would receive the click:<a class="navbar-brand" href="#"></a>
boolean invisiable = wait.until(ExpectedConditions
.invisibilityOfElementLocated(By.xpath("//div[@class='navbar-brand']")));
Pass clickable button id as shown below
if (invisiable) {
WebElement ele = driver.findElement(By.xpath("//div[@id='button']");
ele.click();
}
You should be able to get the text using getText()
(for the option element you got using getFirstSelectedOption()
):
Select select = new Select(driver.findElement(By.xpath("//select")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem );
const log = chrome.extension.getBackgroundPage().console.log;
log('something')
Open log:
When you download a package with setup.py
open your Terminal (Mac,Linux) or Command Prompt (Windows). Using cd
and helping you with Tab button set the path right to the folder where you have downloaded the file and where there is setup.py
:
iMac:~ user $ cd path/pakagefolderwithsetupfile/
Press enter, you should see something like this:
iMac:pakagefolderwithsetupfile user$
Then type after this python setup.py install
:
iMac:pakagefolderwithsetupfile user$ python setup.py install
Press enter
. Done!
Another way is :
const result = [] as any;
At least in my case I've noticed that visual studio 2012 was creating at least two msbuild.exe ghost processes, which did not perish after build. These zombies apparently are causing file locks to appear.
Killing msbuild.exe's is one time solution, it needs to be done per build basis.
But then I've figure out that I could disable parallel build once and for all - went into Tools > Options > Projects and Solutions > Build and Run > "maximum numbers of parallel project builds" - by default it has value of 8, I've switched to 1. Works like charm.
Of course builds are bit slower now, but better safe than sorry. At least for this particular small project I did not need more than one build thread.
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
char str[80];
int i;
cout<<"\n enter string:";
cin.getline(str,80);
int n=strlen(str);
cout<<"\n lenght is:"<<n;
getch();
return 0;
}
This is the program if you want to use strlen . Hope this helps!
Intellisense does work for C# 6, and it's great.
For running console apps you should set up some additional tools:
&{$Branch='dev';iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))}
npm
.yo
: npm install -g yo grunt-cli generator-aspnet bower
c:\Users\Username\.dnx\bin\dnvm.cmd upgrade -u
Then you can use yo
as wizard for Console Application: yo aspnet
Choose name and project type. After that go to created folder cd ./MyNewConsoleApp/
and run dnu restore
To execute your program just type >run
in Command Palette (Ctrl+Shift+P
), or execute dnx . run
in shell from the directory of your project.
And building upon the answer by Emile (and Slugster), I found it a bit easier to extend the TabControl (instead of the TabPages). In this way I can set pages invisible or visible with a single call, and also not have to worry about the null parent references for the invisible pages.
Example call: MyTabControl.SetTabVisibilityExt( "tabTests", isDeveloper);
public static class WinFormExtensions
{
public static TabPage FindTabByNameExt( this TabControl tc, string tabName)
{
foreach (TabPage tab in tc.TabPages)
if (tab.Name == tabName)
return tab;
return null;
}
private struct TabPageData
{
internal int Index;
internal TabControl Parent;
internal TabPage Page;
internal TabPageData(int index, TabControl parent, TabPage page)
{
Index = index;
Parent = parent;
Page = page;
}
internal static string GetKey(TabControl tc, TabPage tabPage)
{
string key = "";
if (tc == null || tabPage == null)
return key;
key = $"{tc.Name}:{tabPage.Name}";
return key;
}
internal static string GetKey(TabControl tc, string tabName)
{
string key = "";
if (tc == null)
return key;
key = $"{tc.Name}:{tabName}";
return key;
}
}
private static Dictionary<string, TabPageData> hiddenPages = new Dictionary<string, TabPageData>();
public static void SetTabVisibleExt(this TabControl tc, string tabName)
{
if (tc == null || tc.IsDisposed)
return;
if (tc.IsTabVisibleExt(tabName))
return;
string key = TabPageData.GetKey(tc, tabName);
if (hiddenPages.ContainsKey(key))
{
TabPageData tpinfo = hiddenPages[key];
if (tpinfo.Index < tc.TabPages.Count)
tc.TabPages.Insert(tpinfo.Index, tpinfo.Page); // add the page in the same position it had
else
tc.TabPages.Add(tpinfo.Page);
hiddenPages.Remove(key);
return;
}
else
throw new ApplicationException($"TabControl={tc.Name} does not have Invisible TabPage={tabName}");
}
public static void SetTabInvisibleExt(this TabControl tc, string tabName)
{
if (tc == null || tc.IsDisposed)
return;
if (IsTabInvisibleExt(tc, tabName))
return;
TabPage page = tc.FindTabByNameExt(tabName);
if (page != null)
{
string key = TabPageData.GetKey(tc, page);
TabPageData tpInfo = new TabPageData(tc.TabPages.IndexOf(page), tc, page);
tc.TabPages.Remove(page);
hiddenPages.Add(key, tpInfo);
return;
}
else // Could not find the tab, and it isn't already invisible.
throw new ApplicationException($"TabControl={tc.Name} could not locate TabPage={tabName}");
}
// A convenience method to combine the SetTabInvisible and SetTabInvisible.
public static void SetTabVisibilityExt(this TabControl tc, string tabName, bool? isVisible)
{
if (isVisible == null)
return;
if (isVisible.Value)
tc.SetTabVisibleExt(tabName);
else
tc.SetTabInvisibleExt(tabName);
}
public static bool IsTabVisibleExt(this TabControl tc, string tabName)
{
TabPage page = tc.FindTabByNameExt(tabName);
return page != null;
}
public static bool IsTabInvisibleExt(this TabControl tc, string tabName)
{
string key = TabPageData.GetKey(tc, tabName);
return hiddenPages.ContainsKey(key);
}
public static void CleanUpHiddenPagesExt(this TabControl tc)
{
foreach (TabPageData info in hiddenPages.Values)
{
if (info.Parent != null && info.Parent.Equals((TabControl)tc))
info.Page.Dispose();
}
}
}
Incorrect:
people:
empId: 123
empName: John
empDept: IT
Correct:
people:
emp:
id: 123
name: John
dept: IT
In some cases it might make more sense to process each selected item one at a time.
In other words, make a separate server call for each selected item passing the value of the selected item. In some cases the list will need to be processed as a whole, but in some not.
I needed to process a list of selected people and then have the results of the query show up on an existing page beneath the existing data for that person. I initially though of passing the whole list to the server, parsing the list, then passing back the data for all of the patients. I would have then needed to parse the returning data and insert it into the page in each of the appropriate places. Sending the request for the data one person at a time turned out to be much easier. Javascript for getting the selected items is described here: check if checkbox is checked javascript and jQuery for the same is described here: How to check whether a checkbox is checked in jQuery?.
As an alternative to 'save & quit', you can use git-commit's function git-commit-commit
, by default bound to C-c C-c. It will save the file and close it. Afterwards, you still have to close emacs with C-x C-c, as mentioned before. I am currently trying to find out how to make emacs quit automatically.
This seems to work:
/descendant::input[@id="search_query"][2]
I go this from "XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition" by Michael Kay.
There is also a note in the "Abbreviated Syntax" section of the XML Path Language specification http://www.w3.org/TR/xpath/#path-abbrev that provided a clue.
Alpine docker image doesn't have bash installed by default. You will need to add following commands to get bash
:
RUN apk update && apk add bash
If youre using Alpine 3.3+
then you can just do
RUN apk add --no-cache bash
to keep docker image size small. (Thanks to comment from @sprkysnrky)
just add componentDidUpdate(){}
method in your code, and it will work.
you can check the life cycle of react native here:
The most libraries offer escaping everything they can, including hundreds of symbols and thousands of non-ASCII characters which is not what you want in UTF-8 world.
Also, as Jeff Williams noted, there's no single “escape HTML” option, there are several contexts.
Assuming you never use unquoted attributes, and keeping in mind that different contexts exist, it've written my own version:
private static final long BODY_ESCAPE =
1L << '&' | 1L << '<' | 1L << '>';
private static final long DOUBLE_QUOTED_ATTR_ESCAPE =
1L << '"' | 1L << '&' | 1L << '<' | 1L << '>';
private static final long SINGLE_QUOTED_ATTR_ESCAPE =
1L << '"' | 1L << '&' | 1L << '\'' | 1L << '<' | 1L << '>';
// 'quot' and 'apos' are 1 char longer than '#34' and '#39' which I've decided to use
private static final String REPLACEMENTS = ""&'<>";
private static final int REPL_SLICES = /* |0, 5, 10, 15, 19, 23*/
5<<5 | 10<<10 | 15<<15 | 19<<20 | 23<<25;
// These 5-bit numbers packed into a single int
// are indices within REPLACEMENTS which is a 'flat' String[]
private static void appendEscaped(
StringBuilder builder,
CharSequence content,
long escapes // pass BODY_ESCAPE or *_QUOTED_ATTR_ESCAPE here
) {
int startIdx = 0, len = content.length();
for (int i = 0; i < len; i++) {
char c = content.charAt(i);
long one;
if (((c & 63) == c) && ((one = 1L << c) & escapes) != 0) {
// -^^^^^^^^^^^^^^^ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// | | take only dangerous characters
// | java shifts longs by 6 least significant bits,
// | e. g. << 0b110111111 is same as >> 0b111111.
// | Filter out bigger characters
int index = Long.bitCount(SINGLE_QUOTED_ATTR_ESCAPE & (one - 1));
builder.append(content, startIdx, i /* exclusive */)
.append(REPLACEMENTS,
REPL_SLICES >>> 5*index & 31,
REPL_SLICES >>> 5*(index+1) & 31);
startIdx = i + 1;
}
}
builder.append(content, startIdx, len);
}
Consider copy-pasting from Gist without line length limit.
I'm not sure exactly what you're trying to do but you can set the date/time to exactly what you want in a number of ways...
You can specify 12/25/2010 4:58 PM by using
DateTime myDate = Convert.ToDateTime("2010-12-25 16:58:00");
OR if you have an existing datetime construct , say 12/25/2010 (and any random time) and you want to set it to 12/25/2010 4:58 PM, you could do so like this:
DateTime myDate = ExistingTime.Date.AddHours(16).AddMinutes(58);
The ExistingTime.Date
will be 12/25 at midnight, and you just add hours and minutes to get it to the time you want.
If you want to read CSV file with some lines, so this the solution.
while IFS=, read -ra line
do
test $i -eq 1 && ((i=i+1)) && continue
for col_val in ${line[@]}
do
echo -n "$col_val|"
done
echo
done < "$csvFile"
try this
$('#element').on('scroll touchmove mousewheel', function(e){
e.preventDefault();
e.stopPropagation();
return false;
})
Using COALESCE to Build Comma-Delimited String in SQL Server
http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string
Example:
DECLARE @EmployeeList varchar(100)
SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') +
CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1
SELECT @EmployeeList
I confirm. We must add:
webPreferences: {
nodeIntegration: true
}
For example:
mainWindow = new BrowserWindow({webPreferences: {
nodeIntegration: true
}});
For me, the problem has been resolved with that.
The following is my preferred way, and will change the cursor everytime a page is about to change i.e. beforeunload
$(window).on('beforeunload', function(){
$('*').css("cursor", "progress");
});
In Marshmallow, I got this error,
Installation error: INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE
Please check logcat output for more details.
Launch canceled!
Looking for solution I searched and came here. I deleted the app but still have this problem in Nexus 6. Later found that in,
Settings > Apps > [My app name] have to removed for all user.
Arrays can only be passed by reference, actually:
void foo(double (&bar)[10])
{
}
This prevents you from doing things like:
double arr[20];
foo(arr); // won't compile
To be able to pass an arbitrary size array to foo
, make it a template and capture the size of the array at compile time:
template<typename T, size_t N>
void foo(T (&bar)[N])
{
// use N here
}
You should seriously consider using std::vector
, or if you have a compiler that supports c++11, std::array
.
A simple and jQuery free solution:
document.querySelector('#elitable').onclick = function(ev) {
// ev.target <== td element
// ev.target.parentElement <== tr
var index = ev.target.parentElement.rowIndex;
}
Bonus: It works even if rows are added/removed dynamically
Little something I created for this:
function getFiles($path) {
if (is_dir($path)) {
$files = scandir($path);
$res = [];
foreach ($files as $key => $file) {
if ($file != "." && $file != "..") {
array_push($res, $file);
}
}
return $res;
}
return false;
}
this is how i do it with xcode 7.3.1
// create function
func sayhi(){
print("hello")
}
// create the button
let sayinghi = UIAlertAction(title: "More", style: UIAlertActionStyle.Default, handler: { action in
self.sayhi()})
// adding the button to the alert control
myAlert.addAction(sayhi);
// the whole code, this code will add 2 buttons
@IBAction func sayhi(sender: AnyObject) {
let myAlert = UIAlertController(title: "Alert", message:"sup", preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil)
let sayhi = UIAlertAction(title: "say hi", style: UIAlertActionStyle.Default, handler: { action in
self.sayhi()})
// this action can add to more button
myAlert.addAction(okAction);
myAlert.addAction(sayhi);
self.presentViewController(myAlert, animated: true, completion: nil)
}
func sayhi(){
// move to tabbarcontroller
print("hello")
}
If you are on Mac OS X or Ubuntu, the problem is caused by the symlinks to the JDK. File | Invalidate Caches should help. If it doesn't, specify the JDK path to the direct JDK Home folder, not a symlink.
Invalidate Caches menu item is available under IntelliJ IDEA File menu.
Direct JDK path after the recent Apple Java update is:
/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
In IDEA you can configure the new JSDK in File | Project Structure, select SDKs on the left, then press [+] button, then specify the above JDK home path, you should get something like this:
most simple answer
<a onclick="window.open(this.href,'_blank');return false;" href="http://www.foracure.org.au">Some Other Site</a>
it will work
Might be worthwhile using the CultureInfo to apply DateTime formatting throughout the website. Insteado f running around formatting whever you have to.
CultureInfo.CurrentUICulture.DateTimeFormat.SetAllDateTimePatterns( ...
or
CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
Code should go somewhere in your Global.asax file
protected void Application_Start(){ ...
ArrayList<String> list = new ArrayList<String>();
list.add("blah");
list.add("bleh");
JSONArray jsArray = new JSONArray(list);
This is only an example using a string arraylist
Firstly, I highly recommend you do your CSS styling in an external CSS file, rather than doing it inline. It's much easier to maintain and can be more reusable using classes.
Working off Alex's answer (& Garret's clearfix) of "adding an element at the end with clear: both", you can do it like so:
<div id='outerdiv' style='border: 1px solid black; background-color: black;'>
<div style='width: 300px; border: red 1px dashed; float: left;'>
<p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
</div>
<div style='width: 300px; border: red 1px dashed; float: right;'>
<p>zzzzzzzzzzzzzzzzzzzzzzzzzzzzz</p>
</div>
<div style='clear:both;'></div>
</div>
This works (but as you can see inline CSS isn't so pretty).
I needed a slightly different result.
I wanted the first word, and what ever came after it - even if it was blank.
str.substr(0, text.indexOf(' ') == -1 ? text.length : text.indexOf(' '));
str.substr(text.indexOf(' ') == -1 ? text.length : text.indexOf(' ') + 1);
so if the input is oneword
you get oneword
and ''
.
If the input is one word and some more
you get one
and word and some more
.
SELECT * FROM myTable WHERE DATE(myDate) = DATE(NOW())
Read more: http://www.tomjepson.co.uk/tutorials/36/mysql-select-where-date-today.html
A little jQuery fix:
$(function(){
var chbxs = $(':checkbox[required]');
var namedChbxs = {};
chbxs.each(function(){
var name = $(this).attr('name');
namedChbxs[name] = (namedChbxs[name] || $()).add(this);
});
chbxs.change(function(){
var name = $(this).attr('name');
var cbx = namedChbxs[name];
if(cbx.filter(':checked').length>0){
cbx.removeAttr('required');
}else{
cbx.attr('required','required');
}
});
});
If you don't want to use the Task class (for instance, in .NET 3.5) you can just start all your threads, and then add them to the list and join them in a foreach loop.
Example:
List<Thread> threads = new List<Thread>();
// Start threads
for(int i = 0; i<10; i++)
{
int tmp = i; // Copy value for closure
Thread t = new Thread(() => Console.WriteLine(tmp));
t.Start;
threads.Add(t);
}
// Await threads
foreach(Thread thread in threads)
{
thread.Join();
}
You could try something like this (copied from the jQuery Ajax examples)
var request = $.ajax({
url: "script.php",
type: "POST",
data: {id : menuId},
dataType: "html"
});
request.done(function(msg) {
console.log( msg );
});
request.fail(function(jqXHR, textStatus) {
console.log( "Request failed: " + textStatus );
});
The problem with your original code is that the error argument you pass into your on function isn't actually coming from anywhere. JQuery on doesn't return a second argument, and even if it did, it would relate to the click event not the Ajax call.
# The following would be a very simple solution.
print("")
string = input("Enter your string :")
noofspacesinstring = 0
for counter in string:
if counter == " ":
noofspacesinstring += 1
if noofspacesinstring == 0:
message = "Your string is a single word"
else:
message = "Your string is not a single word"
print("")
print(message)
print("")
If you want more granularity and better decription, you could use NotImplementedException from commons-lang
Warning: Available before versions 2.6 and after versions 3.2, only.
java.lang.String
class has method substring
not substr
, thats the error in your program.
Moreover you can do this in one single line if you are ok in using regular expression.
a.replaceAll("\\s+","");
Free tools supporting panning / zooming:
Free tools without built in pan / zoom support:
Paid tools with built in pan / zoom support:
Full Disclosure: I have been heavily involved in development of Visiblox, hence I know that library in much more detail than the others.
You need a whole input match here.
System.out.println(test.matches("^(http|https|ftp)://.*$"));
Edit:(Based on @davidchambers's comment)
System.out.println(test.matches("^(https?|ftp)://.*$"));
I think that you can just catch org.openqa.selenium.NoSuchElementException
that will be thrown by driver.findElement
if there's no such element:
import org.openqa.selenium.NoSuchElementException;
....
public static void assertLinkNotPresent(WebDriver driver, String text) {
try {
driver.findElement(By.linkText(text));
fail("Link with text <" + text + "> is present");
} catch (NoSuchElementException ex) {
/* do nothing, link is not present, assert is passed */
}
}
Add an extra apostrophe '
to the MessageFormat
pattern String
to ensure the '
character is displayed
String text =
java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
^
An apostrophe (aka single quote) in a MessageFormat pattern starts a quoted string and is not interpreted on its own. From the javadoc
A single quote itself must be represented by doubled single quotes '' throughout a String.
The String
You\\'re
is equivalent to adding a backslash character to the String
so the only difference will be that You\re
will be produced rather than Youre
. (before double quote solution ''
applied)
num = raw_input ("Type Number : ")
search = open("file.txt","r")
for line in search.readlines():
for digit in num:
# Check if any of the digits provided by the user are in the line.
if digit in line:
print line
continue
If you are familiar with using System.Windows.Forms class then you can just add a reference of System.Windows.Forms class to your project:
Solution Explorer -> References -> Add References... -> ( Assemblies : Framework ) -> scroll down and check System.Windows.Forms assembly -> OK.
Now you can add using System.Windows.Forms; statement and use screen in your wpf project just like before.
self.navigationController.navigationBar.topItem.title = @"";
Applying a rotation animation (without duration, thus no animation effect) is a simpler solution than either calling View.setRotation() or override View.onDraw method.
// substitude deltaDegrees for whatever you want
RotateAnimation rotate = new RotateAnimation(0f, deltaDegrees,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// prevents View from restoring to original direction.
rotate.setFillAfter(true);
someButton.startAnimation(rotate);
As mentioned in the bug 190226, Since version 23.1.0 getting header layout view with:
navigationView.findViewById(R.id.navigation_header_text)
no longer works.
A workaround is to inflate the headerview programatically and find view by ID from the inflated header view.
For example:
View headerView = navigationView.inflateHeaderView(R.layout.navigation_header);
headerView.findViewById(R.id.navigation_header_text);
Ideally there should be a method getHeaderView()
but it has already been proposed, let's see and wait for it to be released in the feature release of design support library.
//program to form1 to form2
private void button1_Click(object sender, EventArgs e)
{
//MessageBox.Show("Welcome Admin");
Form2 frm = new Form2();
frm.Show();
this.Hide();
}
Your code looks correct but sometimes google blocks an IP when you try to send a email from an unusual location. You can try to unblock it by visiting https://accounts.google.com/DisplayUnlockCaptcha from the IP and following the prompts.
Reference: https://support.google.com/accounts/answer/6009563
You don't have all digit characters in your string. So you have to split by space
QString Abcd = "123.5 Kb";
Abcd.split(" ")[0].toInt(); //convert the first part to Int
Abcd.split(" ")[0].toDouble(); //convert the first part to double
Abcd.split(" ")[0].toFloat(); //convert the first part to float
Update: I am updating an old answer. That was a straight forward answer to the specific question, with a strict assumption. However as noted by @DomTomCat in comments and @Mikhail in answer, In general one should always check whether the operation is successful or not. So using a boolean flag is necessary.
bool flag;
double v = Abcd.split(" ")[0].toDouble(&flag);
if(flag){
// use v
}
Also if you are taking that string as user input, then you should also be doubtful about whether the string is really splitable with space. If there is a possibility that the assumption may break then a regex verifier is more preferable. A regex like the following will extract the floating point value and the prefix character of 'b'. Then you can safely convert the captured strings to double.
([0-9]*\.?[0-9]+)\s+(\w[bB])
You can have an utility function like the following
QPair<double, QString> split_size_str(const QString& str){
QRegExp regex("([0-9]*\\.?[0-9]+)\\s+(\\w[bB])");
int pos = regex.indexIn(str);
QStringList captures = regex.capturedTexts();
if(captures.count() > 1){
double value = captures[1].toDouble(); // should succeed as regex matched
QString unit = captures[2]; // should succeed as regex matched
return qMakePair(value, unit);
}
return qMakePair(0.0f, QString());
}
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
New-style classes inherit from object
, or from another new style class:
class SomeObject(object):
pass
class SubObject(SomeObject):
pass
Old-style classes don't:
class SomeObject:
pass
This only applies to Python 2 - in Python 3 all the above will create new-style classes.
See 9. Classes (Python tutorial), NewClassVsClassicClass and What is the difference between old style and new style classes in Python? for details.
With the current version of Visual Studio Code as of this writing (1.22.1), you can find your settings in
~/.config/Code/User
on Linux (in my case, an, Ubuntu derivative)C:\Users\username\AppData\Roaming\Code\User
on Windows 10~/Library/Application Support/Code/User/
on Mac OS X (thank you, Christophe De Troyer)The files are settings.json
and keybindings.json
. Simply copy them to the target machine.
Your extensions are in
~/.vscode/extensions
on Linux and Mac OS XC:\Users\username\.vscode\extensions
on Windows 10 (e.g., essentially the same place)Alternately, just go to the Extensions, show installed extensions, and install those on your target installation. For me, copying the extensions worked just fine, but it may be extension-specific, particularly if moving between platforms, depending on what the extension does.
There is a bit of confusion going on here, but let me try to clarify things:
Lets say you wanted sql that looked something like:
SELECT
`main_table`.*,
`main_table`.`email` AS `invitation_email`,
`main_table`.`group_id` AS `invitee_group_id`
FROM
`enterprise_invitation` AS `main_table`
WHERE (
(status = 'new')
OR (customer_id = '1234')
)
In order to achieve this, your collection needs to be formatted like this:
$collection = Mage::getModel('enterprise_invitation/invitation')->getCollection();
$collection->addFieldToFilter(array('status', 'customer_id'), array(
array('status','eq'=>'new'),
array('customer_id', 'eq'=>'1234') ));
Now to see what this looks like you can always echo the query that this creates by using
echo $collection->getSelect()->__toString();
getClass().getResource()
uses the class loader to load the resource. This means that the resource must be in the classpath to be loaded.
When doing it with Eclipse, everything you put in the source folder is "compiled" by Eclipse:
When launching the program with Eclipse, the bin directory is thus in the classpath, and since it contains the Test.properties file, this file can be loaded by the class loader, using getResource()
or getResourceAsStream()
.
If it doesn't work from the command line, it's thus because the file is not in the classpath.
Note that you should NOT do
FileInputStream inputStream = new FileInputStream(new File(getClass().getResource(url).toURI()));
to load a resource. Because that can work only if the file is loaded from the file system. If you package your app into a jar file, or if you load the classes over a network, it won't work. To get an InputStream, just use
getClass().getResourceAsStream("Test.properties")
And finally, as the documentation indicates,
Foo.class.getResourceAsStream("Test.properties")
will load a Test.properties file located in the same package as the class Foo.
Foo.class.getResourceAsStream("/com/foo/bar/Test.properties")
will load a Test.properties file located in the package com.foo.bar
.
I would guess that it is a way to make apps which don't use it at all perform slightly better. Here's my thinking on this.
x86 OSes (and I imagine others) need to store FPU state on context switch. However, most OSes only bother to save/restore this state after the app attempts to use the FPU for the first time.
In addition to this, there is probably some basic code in the math library which will set the FPU to a sane base state when the library is loaded.
So, if you don't link in any math code at all, none of this will happen, therefore the OS doesn't have to save/restore any FPU state at all, making context switches slightly more efficient.
Just a guess though.
EDIT: in response to some of the comments, the same base premise still applies to non-FPU cases (the premise being that it was to make apps which didn't make use libm perform slightly better).
For example, if there is a soft-FPU which was likley in the early days of C. Then having libm separate could prevent a lot of large (and slow if it was used) code from unnecessarily being linked in.
In addition, if there is only static linking available, then a similar argument applies that it would keep executable sizes and compile times down.
The comma expression takes on the value of the last (eg. right-most) expression.
So in your first loop, the only controlling expression is i<=5
; and j>=0
is ignored.
In the second loop, j>=0
controls the loop, and i<=5
is ignored.
As for a reason... there is no reason. This code is just wrong. The first part of the comma-expressions does nothing except confuse programmers. If a serious programmer wrote this, they should be ashamed of themselves and have their keyboard revoked.
The sizeof the structure should be 8 bytes on a 32 bit system, so that the size of the structure becomes multiple of 2. This makes individual structures available at the correct byte boundaries when an array of structures is declared. This is achieved by padding the structure with 3 bytes at the end.
If the structure had the pointer declared after the char, it would still be 8 bytes in size but the 3 byte padding would have been added to keep the pointer (which is a 4 byte element) aligned at a 4 byte address boundary.
The rule of thumb is that elements should be at an offset which is the multiple of their byte size and the structure itself should be of a size which is a multiple of 2.
In MongoDB, the db.collection.remove() method removes documents from a collection. You can remove all documents from a collection, remove all documents that match a condition, or limit the operation to remove just a single document.
Source: Mongodb.
If you are using mongo sheel, just do:
db.Datetime.remove({})
In your case, you need:
You didn't show me the delete button, so this button is just an example:
<a class="button__delete"></a>
Change the controller to:
exports.destroy = function(req, res, next) {
Datetime.remove({}, function(err) {
if (err) {
console.log(err)
} else {
res.end('success');
}
}
);
};
Insert this ajax delete method in your client js file:
$(document).ready(function(){
$('.button__delete').click(function() {
var dataId = $(this).attr('data-id');
if (confirm("are u sure?")) {
$.ajax({
type: 'DELETE',
url: '/',
success: function(response) {
if (response == 'error') {
console.log('Err!');
}
else {
alert('Success');
location.reload();
}
}
});
} else {
alert('Canceled!');
}
});
});
in your question, both buffer and byteArray seem to be byte[]. So:
ImageElement image = ImageElement.FromBinary(buffer);
Environment.Exit
and Application.Exit
Environment.Exit(0)
is cleaner.
http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx
Try this (DEMO link updated):
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
});
$('#records_table').append(trHTML);
}
Replace this :
$('#subscription_order_form').submit(function(e){
e.preventDefault();
});
with this:
$('#subscription_order_form').on('keydown', function(e){
if (e.which===13) e.preventDefault();
});
That will prevent the form from submitting when Enter key is pressed as it prevents the default action of the key, but the form will submit normally on click.
You could try something like this:
var clickEventType=((document.ontouchstart!==null)?'click':'touchstart');
$("#mylink").bind(clickEventType, myClickHandler);
This is an equivalent solution to Tim Pietzcker's answer (see also comments of same answer):
^(?!.*filename\.js$).*\.js$
It means, match *.js
except *filename.js
.
To get to this solution, you can check which patterns the negative lookbehind excludes, and then exclude exactly these patterns with a negative lookahead.
Here is my workaround,
In your example you can add a third element
with "same styles" of .one & .two elements, but without the absolute position and with hidden visibility:
HTML
<article>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</article>
CSS
.three{
height: 30px;
z-index: -1;
visibility: hidden;
}
Since Java 8 you can sort using the Streams API:
List<String> fruits = Arrays.asList("apple", "Apricot", "banana");
List<String> sortedFruit = fruits.stream()
.sorted(String.CASE_INSENSITIVE_ORDER)
.collect(Collectors.toList())
The difference with Collections.sort
is that this will return a new list and will not modify the existing one.
I am extending @NAlexN original detailed solution, with @zekel excellent extension of UITapGestureRecognizer
, and providing in Swift.
extension UITapGestureRecognizer {
func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {
// Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: CGSize.zero)
let textStorage = NSTextStorage(attributedString: label.attributedText!)
// Configure layoutManager and textStorage
layoutManager.addTextContainer(textContainer)
textStorage.addLayoutManager(layoutManager)
// Configure textContainer
textContainer.lineFragmentPadding = 0.0
textContainer.lineBreakMode = label.lineBreakMode
textContainer.maximumNumberOfLines = label.numberOfLines
let labelSize = label.bounds.size
textContainer.size = labelSize
// Find the tapped character location and compare it to the specified range
let locationOfTouchInLabel = self.location(in: label)
let textBoundingBox = layoutManager.usedRect(for: textContainer)
let textContainerOffset = CGPoint(
x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y
)
let locationOfTouchInTextContainer = CGPoint(
x: locationOfTouchInLabel.x - textContainerOffset.x,
y: locationOfTouchInLabel.y - textContainerOffset.y
)
let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
return NSLocationInRange(indexOfCharacter, targetRange)
}
}
Setup UIGestureRecognizer
to send actions to tapLabel:
, and you can detect if the target ranges is being tapped on in myLabel
.
@IBAction func tapLabel(gesture: UITapGestureRecognizer) {
if gesture.didTapAttributedTextInLabel(myLabel, inRange: targetRange1) {
print("Tapped targetRange1")
} else if gesture.didTapAttributedTextInLabel(myLabel, inRange: targetRange2) {
print("Tapped targetRange2")
} else {
print("Tapped none")
}
}
IMPORTANT: The UILabel
line break mode must be set to wrap by word/char. Somehow, NSTextContainer
will assume that the text is single line only if the line break mode is otherwise.
There are more than a couple of mistakes in the code.
Since you have not defined any default values for any of the function arguments, it is necessary to pass both arguments while calling the function --> hello(sys.argv[2], sys.argv[2])
import sys
def hello(a,b):
print ("hello and that's your sum:")
sum=float(a)+float(b)
print (sum)
if __name__ == "__main__":
hello(sys.argv[1], sys.argv[2])
Also, using "C:\Python27>hello 1 1" to run the code looks fine but you have to make sure that the file is in one of the directories that Python knows about (PATH env variable). So, please use the full path to validate the code. Something like:
C:\Python34>python C:\Users\pranayk\Desktop\hello.py 1 1
please try this
echo $VAR | grep ClNonZ | awk '{print $3}';
or
echo cat filename | grep ClNonZ | awk '{print $3}';
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(), DiscussAddValu.class);
startActivity(i);
}
});
update table_name
set cod_user =
CASE
WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'?
END,date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
In my case this was a syntax issue in the .yml file. I had:
@Value("${spring.kafka.bootstrap-servers}")
public List<String> BOOTSTRAP_SERVERS_LIST;
and the list in my .yml file:
bootstrap-servers:
- s1.company.com:9092
- s2.company.com:9092
- s3.company.com:9092
was not reading into the @Value-annotated field. When I changed the syntax in the .yml file to:
bootstrap-servers >
s1.company.com:9092
s2.company.com:9092
s3.company.com:9092
it worked fine.
import math
from itertools import izip
def dot_product(v1, v2):
return sum(map(lambda x: x[0] * x[1], izip(v1, v2)))
def cosine_measure(v1, v2):
prod = dot_product(v1, v2)
len1 = math.sqrt(dot_product(v1, v1))
len2 = math.sqrt(dot_product(v2, v2))
return prod / (len1 * len2)
You can round it after computing:
cosine = format(round(cosine_measure(v1, v2), 3))
If you want it really short, you can use this one-liner:
from math import sqrt
from itertools import izip
def cosine_measure(v1, v2):
return (lambda (x, y, z): x / sqrt(y * z))(reduce(lambda x, y: (x[0] + y[0] * y[1], x[1] + y[0]**2, x[2] + y[1]**2), izip(v1, v2), (0, 0, 0)))
In a Ubuntu/Debian based distro, you could use apt-file
to find the name of the exact package that includes the missing header file.
# do this once
sudo apt-get install apt-file
sudo apt-file update
$ apt-file search lber.h
libldap2-dev: /usr/include/lber.h
As you could see from the output of apt-file search lber.h
, you'd just need to install the package libldap2-dev
.
sudo apt-get install libldap2-dev
You could create a custom pipe to return the list of key for each element. Something like that:
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push(key);
}
return keys;
}
}
and use it like that:
<tr *ngFor="let c of content">
<td *ngFor="let key of c | keys">{{key}}: {{c[key]}}</td>
</tr>
Edit
You could also return an entry containing both key and value:
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}
and use it like that:
<span *ngFor="let entry of content | keys">
Key: {{entry.key}}, value: {{entry.value}}
</span>
Given a POM file for a maven project you can remove all its dependencies in the local repository (by default ~/.m2/respository) using the Apache Maven Dependency Plugin.
It includes the dependency:purge-local-repository
functionality that removes the project dependencies from the local repository, and optionally re-resolve them.
To clean the local dependencies you just have to used the optional parameter reResolve and set it to false since it is set to true by default.
This command line call should work:
mvn dependency:purge-local-repository -DreResolve=false
You can use a third party library, such as PSI:
PSI is a Python package providing real-time access to processes and other miscellaneous system information such as architecture, boottime and filesystems. It has a pythonic API which is consistent accross all supported platforms but also exposes platform-specific details where desirable.
The move
instruction copies a value from one register to another. The li
instruction loads a specific numeric value into that register.
For the specific case of zero, you can use either the constant zero or the zero register to get that:
move $s0, $zero
li $s0, 0
There's no register that generates a value other than zero, though, so you'd have to use li
if you wanted some other number, like:
li $s0, 12345678
There is a simpler way to get the application data directory with min API 4+. From any Context (e.g. Activity, Application):
getApplicationInfo().dataDir
http://developer.android.com/reference/android/content/Context.html#getApplicationInfo()
“--single-branch” switch is your answer, but it only works if you have git version 1.8.X onwards, first check
#git --version
If you already have git version 1.8.X installed then simply use "-b branch and --single branch" to clone a single branch
#git clone -b branch --single-branch git://github/repository.git
By default in Ubuntu 12.04/12.10/13.10 and Debian 7 the default git installation is for version 1.7.x only, where --single-branch is an unknown switch. In that case you need to install newer git first from a non-default ppa as below.
sudo add-apt-repository ppa:pdoes/ppa
sudo apt-get update
sudo apt-get install git
git --version
Once 1.8.X is installed now simply do:
git clone -b branch --single-branch git://github/repository.git
Git will now only download a single branch from the server.
You use a shebang line at the start of your script:
#!/usr/bin/env python
make the file executable:
chmod +x arbitraryname
and put it in a directory on your PATH (can be a symlink):
cd ~/bin/
ln -s ~/some/path/to/myscript/arbitraryname
Whenever I have to do string manipulations in C#, I miss the good old Left
and Right
functions from Visual Basic, which are much simpler to use than Substring
.
So in most of my C# projects, I create extension methods for them:
public static class StringExtensions
{
public static string Left(this string str, int length)
{
return str.Substring(0, Math.Min(length, str.Length));
}
public static string Right(this string str, int length)
{
return str.Substring(str.Length - Math.Min(length, str.Length));
}
}
Note:
The Math.Min
part is there because Substring
throws an ArgumentOutOfRangeException
when the input string's length is smaller than the requested length, as already mentioned in some comments under previous answers.
string longString = "Long String";
// returns "Long";
string left1 = longString.Left(4);
// returns "Long String";
string left2 = longString.Left(100);
When using qt (Qt 4.3+), one can use QPolygon's function containsPoint
I have implemented a class that works as a timer.
I leave the link here in case anyone needs it: https://github.com/ivanhalencp/python/tree/master/xTimer
What you're asking for is extremely hard. If possible, getting the user to specify the encoding is the best. Preventing an attack shouldn't be much easier or harder that way.
However, you could try doing this:
iconv(mb_detect_encoding($text, mb_detect_order(), true), "UTF-8", $text);
Setting it to strict might help you get a better result.
These alternative libraries worked for me:
sudo apt-get update
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6
You can easily transition your WSDL-spewing WCF web components to other uses just by changing your configuration settings. You can go across HTTP and then also named pipes, tcp, custom protocols, etc without having to change your code. I believe WCF components may also be easier to set up for stuff like security, two-way calling, transactions, concurrency, etc.
REST pretty much limits you to HTTP (which is fine in many cases).
First treat the number like a string
number = 9876543210
number = str(number)
Then to get the first digit:
number[0]
The fourth digit:
number[3]
EDIT:
This will return the digit as a character, not as a number. To convert it back use:
int(number[0])
The session.save(object) returns the id of the object, or you could alternatively call the id getter method after performing a save.
Save() return value:
Serializable save(Object object) throws HibernateException
Returns:
the generated identifier
Getter method example:
UserDetails entity:
@Entity
public class UserDetails {
@Id
@GeneratedValue
private int id;
private String name;
// Constructor, Setters & Getters
}
Logic to test the id's :
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.getTransaction().begin();
UserDetails user1 = new UserDetails("user1");
UserDetails user2 = new UserDetails("user2");
//int userId = (Integer) session.save(user1); // if you want to save the id to some variable
System.out.println("before save : user id's = "+user1.getId() + " , " + user2.getId());
session.save(user1);
session.save(user2);
System.out.println("after save : user id's = "+user1.getId() + " , " + user2.getId());
session.getTransaction().commit();
Output of this code:
before save : user id's = 0 , 0
after save : user id's = 1 , 2
As per this output, you can see that the id's were not set before we save the UserDetails
entity, once you save the entities then Hibernate set's the id's for your objects - user1
and user2
I want to understand the lock each transaction isolation takes on the table
For example, you have 3 concurrent processes A, B and C. A starts a transaction, writes data and commit/rollback (depending on results). B just executes a SELECT
statement to read data. C reads and updates data. All these process work on the same table T.
WHERE aField > 10 AND aField < 20
, A inserts data where aField
value is between 10 and 20, then B reads the data again and get a different result.I want to understand where we define these isolation levels: only at JDBC/hibernate level or in DB also
Using JDBC, you define it using Connection#setTransactionIsolation
.
Using Hibernate:
<property name="hibernate.connection.isolation">2</property>
Where
Hibernate configuration is taken from here (sorry, it's in Spanish).
By the way, you can set the isolation level on RDBMS as well:
SET ISOLATION TO DIRTY READ
sentence.)and on and on...
(magento 2 example provided below)
sectionName, groupName and fieldName are present in etc/system.xml file of the module.
PHP Syntax:
Mage::getStoreConfig('sectionName/groupName/fieldName');
From within an editor in the admin, such as the content of a CMS Page or Static Block; the description/short description of a Catalog Category, Catalog Product, etc.
{{config path="sectionName/groupName/fieldName"}}
For the "Within an editor" approach to work, the field value must be passed through a filter for the {{ ... }} contents to be parsed out. Out of the box, Magento will do this for Category and Product descriptions, as well as CMS Pages and Static Blocks. However, if you are outputting the content within your own custom view script and want these variables to be parsed out, you can do so like this:
<?php
$example = Mage::getModel('identifier/name')->load(1);
$filter = Mage::getModel('cms/template_filter');
echo $filter->filter($example->getData('field'));
?>
Replacing identifier/name with the a appropriate values for the model you are loading, and field with the name of the attribute you want to output, which may contain {{ ... }} occurrences that need to be parsed out.
From any Block class that extends \Magento\Framework\View\Element\AbstractBlock
$this->_scopeConfig->getValue('sectionName/groupName/fieldName');
Any other PHP class:
If the class (and none of it's parent's) does not inject \Magento\Framework\App\Config\ScopeConfigInterface
via the constructor, you'll have to add it to your class.
// ... Remaining class definition above...
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $_scopeConfig;
/**
* Constructor
*/
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
// ...any other injected classes the class depends on...
) {
$this->_scopeConfig = $scopeConfig;
// Remaining constructor logic...
}
// ...remaining class definition below...
Once you have injected it into your class, you can now fetch store configuration values with the same syntax example given above for block classes.
Note that after modifying any class's __construct() parameter list, you may have to clear your generated classes as well as dependency injection directory: var/generation
& var/di
Here is Java 8 code. I think this code will solve your problem.Happy Coding
LocalDate start = LocalDate.now();
LocalDate end = LocalDate.of(2016, 9, 1);//JAVA 9 release date
Long duration = start.until(end, ChronoUnit.DAYS);
System.out.println(duration);
// Do Any stuff Here there after
IntStream.iterate(0, i -> i + 1)
.limit(duration)
.forEach((i) -> {});
//old way of iteration
for (int i = 0; i < duration; i++)
System.out.print("" + i);// Do Any stuff Here
You should use List
or array
instead
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
Or
int[] arr = new int[10];
arr[0]=1;
arr[1]=2;
Or even better
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("n1", 1);
map.put("n2", 2);
//conditionally get
map.get("n1");
In the current worksheet, select cell A1 (this is important!)
Open Name Manager
(Ctl+F3)
Click New...
Enter "THIS_CELL" (or just "THIS", which is my preference) into Name:
Enter the following formula into Refers to:
=!A1
NOTE: Be sure cell A1 is selected. This formula is relative to the ActiveCell.
Under Scope:
select Workbook
.
Click OK
and close the Name Manager
=CELL("width",THIS_CELL)
EDIT: Better solution than using INDIRECT()
It's worth noting that the solution I've given should be preferred over any solution using the INDIRECT()
function for two reasons:
INDIRECT()
is a volatile Excel function, and as a result will dramatically slow down workbook calculation when it is used a lot.ROW()
COLUMN()
) to a range reference to an address and back to a range reference again.EDIT: Also see this question for more information on workbook-scoped, sheet dependent named ranges.
EDIT: Also see @imix's answer below for a variation on this idea (using RC style references). In that case, you could use =!RC
for the THIS_CELL
named range formula, or just use RC
directly.
if __name__ == "__main__"
is the part that runs when the script is run from (say) the command line using a command like python myscript.py
.
Make sure to paste the above code into onCreate() after your call to the super and the call to setContentView(). This small detail kept my hung up for awhile.
Both will work but xhtml standard requires you to specify the type
too:
<script type="text/javascript">..</script>
<!ELEMENT SCRIPT - - %Script; -- script statements -->
<!ATTLIST SCRIPT
charset %Charset; #IMPLIED -- char encoding of linked resource --
type %ContentType; #REQUIRED -- content type of script language --
src %URI; #IMPLIED -- URI for an external script --
defer (defer) #IMPLIED -- UA may defer execution of script --
>
type = content-type [CI] This attribute specifies the scripting language of the element's contents and overrides the default scripting language. The scripting language is specified as a content type (e.g., "text/javascript"). Authors must supply a value for this attribute. There is no default value for this attribute.
Notices the emphasis above.
http://www.w3.org/TR/html4/interact/scripts.html
Note: As of HTML5 (far away), the type
attribute is not required and is default.
There is no precise meaning, precisely because these terms mean the opposite things depending on whether you are merging or rebasing. THE natural way of thinking about two branches is "my work" and "someone else's work". The choice of terminology that obscures this classification is absolutely THE worst design choice in git. It must have been inspired by accounting's "credit" and "debit" or "assets" and "liabilities" - same headache.
You could create a Hashmap<String, Object>
using one of the values as a key, and then seeing if yourHashMap.keySet().contains(yourValue)
returns true.
Unless you resize up, you cannot do this with raster graphics.
What you can do with good filtering and smoothing is to resize without losing any noticable quality.
You can also alter the DPI metadata of the image (assuming it has some) which will keep exactly the same pixel count, but will alter how image editors think of it in 'real-world' measurements.
And just to cover all bases, if you really meant just the file size of the image and not the actual image dimensions, I suggest you look at a lossless encoding of the image data. My suggestion for this would be to resave the image as a .png file (I tend to use paint as a free transcoder for images in windows. Load image in paint, save as in the new format)
Remove the API key parameter and its value.
eg. https://maps.googleapis.com/maps/api/geocode/json?address=[YOUR ADDRESS]&sensor=true
#include <experimental/filesystem> // or #include <filesystem> for C++17 and up
namespace fs = std::experimental::filesystem;
if (!fs::is_directory("src") || !fs::exists("src")) { // Check if src folder exists
fs::create_directory("src"); // create src folder
}
hashMaps
can't have duplicate keys. That said, you can create a map with list values:
Map<Integer, List<String>>
However, using this approach will have performance implications.
If you get this compilation error, it means that you have not included the servlet jar in the classpath. The correct way to include this jar is to add the Server Runtime jar to your eclipse project. You should follow the steps below to address this issue: You can download the servlet-api.jar from here http://www.java2s.com/Code/Jar/s/Downloadservletapijar.htm
Save it in directory. Right click on project -> go to properties->Buildpath and follow the steps.
_x000D_
Note: The jar which are shown in the screen are not correct jar.
you can follow the step to configure.
There are a few characters that are dissallowed in XML documents, even when you encapsulate data in CDATA-blocks.
If you generated the document you will need to entity encode it or strip it out. If you have an errorneous document, you should strip away these characters before trying to parse it.
See dolmens answer in this thread: Invalid Characters in XML
Where he links to this article: http://www.w3.org/TR/xml/#charsets
Basically, all characters below 0x20 is disallowed, except 0x9 (TAB), 0xA (CR?), 0xD (LF?)
success
only fires if the AJAX call is successful, i.e. ultimately returns a HTTP 200 status. error
fires if it fails and complete
when the request finishes, regardless of success.
In jQuery 1.8 on the jqXHR
object (returned by $.ajax
) success
was replaced with done
, error
with fail
and complete
with always
.
However you should still be able to initialise the AJAX request with the old syntax. So these do similar things:
// set success action before making the request
$.ajax({
url: '...',
success: function(){
alert('AJAX successful');
}
});
// set success action just after starting the request
var jqxhr = $.ajax( "..." )
.done(function() { alert("success"); });
This change is for compatibility with jQuery 1.5's deferred object. Deferred (and now Promise
, which has full native browser support in Chrome and FX) allow you to chain asynchronous actions:
$.ajax("parent").
done(function(p) { return $.ajax("child/" + p.id); }).
done(someOtherDeferredFunction).
done(function(c) { alert("success: " + c.name); });
This chain of functions is easier to maintain than a nested pyramid of callbacks you get with success
.
However, please note that done
is now deprecated in favour of the Promise
syntax that uses then
instead:
$.ajax("parent").
then(function(p) { return $.ajax("child/" + p.id); }).
then(someOtherDeferredFunction).
then(function(c) { alert("success: " + c.name); }).
catch(function(err) { alert("error: " + err.message); });
This is worth adopting because async
and await
extend promises improved syntax (and error handling):
try {
var p = await $.ajax("parent");
var x = await $.ajax("child/" + p.id);
var c = await someOtherDeferredFunction(x);
alert("success: " + c.name);
}
catch(err) {
alert("error: " + err.message);
}
I use this simple function for JQuery based project
var pointerEventToXY = function(e){
var out = {x:0, y:0};
if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){
var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
out.x = touch.pageX;
out.y = touch.pageY;
} else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
out.x = e.pageX;
out.y = e.pageY;
}
return out;
};
example:
$('a').on('mousedown touchstart', function(e){
console.log(pointerEventToXY(e)); // will return obj ..kind of {x:20,y:40}
})
hope this will be usefull for you ;)
Not sure why the grep method is not working for me when using npm test. This works though. I also need to specify the test folder also for some reason.
npm test -- test/sometest.js
To Remove some element from Listview in android then it will remove your specific element and Bind it to listview.
BookinhHistory_adapter.this.productPojoList.remove(position);
BookinhHistory_adapter.this.notifyDataSetChanged();
Using Visual Studio
This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).
Using Process Explorer
If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)
Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.
Programmatically
Check this SO question that explains how to do it.
There is an answer by @hexafraction , He had specified the x and y to be top right corner which is wrong, those are top left corner .
I have also provided the source please check it.
public void setBounds(int x,
int y,
int width,
int height)
Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height. This method changes layout-related information, and therefore, invalidates the component hierarchy.
Parameters:
x - the new x-coordinate of this component
y - the new y-coordinate of this component
width - the new width of this component
height - the new height of this component
source:- setBounds
Just use the ==
with the negation symbol (!
). If dtfm is the name of your data.frame:
dtfm[!dtfm$C == "Foo", ]
Or, to move the negation in the comparison:
dtfm[dtfm$C != "Foo", ]
Or, even shorter using subset()
:
subset(dtfm, C!="Foo")
If you want the month year unique pair, using apply is pretty sleek.
df['mnth_yr'] = df['date_column'].apply(lambda x: x.strftime('%B-%Y'))
Outputs month-year in one column.
Don't forget to first change the format to date-time before, I generally forget.
df['date_column'] = pd.to_datetime(df['date_column'])
Here is a portable function that works for both Linux (path '/') and Windows (mix of '\' and '/').
Compiles with gcc, clang and vs.
#include <string.h>
#include <stdio.h>
const char* GetFileName(const char *path)
{
const char *name = NULL, *tmp = NULL;
if (path && *path) {
name = strrchr(path, '/');
tmp = strrchr(path, '\\');
if (tmp) {
return name && name > tmp ? name + 1 : tmp + 1;
}
}
return name ? name + 1 : path;
}
int main() {
const char *name = NULL, *path = NULL;
path = __FILE__;
name = GetFileName(path);
printf("path: %s, filename: %s\n", path, name);
path ="/tmp/device.log";
name = GetFileName(path);
printf("path: %s, filename: %s\n", path, name);
path = "C:\\Downloads\\crisis.avi";
name = GetFileName(path);
printf("path: %s, filename: %s\n", path, name);
path = "C:\\Downloads/nda.pdf";
name = GetFileName(path);
printf("path: %s, filename: %s\n", path, name);
path = "C:/Downloads\\word.doc";
name = GetFileName(path);
printf("path: %s, filename: %s\n", path, name);
path = NULL;
name = GetFileName(NULL);
printf("path: %s, filename: %s\n", path, name);
path = "";
name = GetFileName("");
printf("path: %s, filename: %s\n", path, name);
return 0;
}
Standard output:
path: test.c, filename: test.c
path: /tmp/device.log, filename: device.log
path: C:\Downloads\crisis.avi, filename: crisis.avi
path: C:\Downloads/nda.pdf, filename: nda.pdf
path: C:/Downloads\word.doc, filename: word.doc
path: (null), filename: (null)
path: , filename:
If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use
git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')
Well, according to the mysql_real_escape_string function reference page: "mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which escapes the following characters: \x00, \n, \r, \, ', " and \x1a."
With that in mind, then the function given in the second link you posted should do exactly what you need:
function mres($value)
{
$search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
$replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");
return str_replace($search, $replace, $value);
}
Key class:
@Embeddable
@Access (AccessType.FIELD)
public class EntryKey implements Serializable {
public EntryKey() {
}
public EntryKey(final Long id, final Long version) {
this.id = id;
this.version = version;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Long getVersion() {
return this.version;
}
public void setVersion(Long version) {
this.version = version;
}
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof EntryKey))
return false;
EntryKey castOther = (EntryKey) other;
return id.equals(castOther.id) && version.equals(castOther.version);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.id.hashCode();
hash = hash * prime + this.version.hashCode();
return hash;
}
@Column (name = "ID")
private Long id;
@Column (name = "VERSION")
private Long operatorId;
}
Entity class:
@Entity
@Table (name = "YOUR_TABLE_NAME")
public class Entry implements Serializable {
@EmbeddedId
public EntryKey getKey() {
return this.key;
}
public void setKey(EntryKey id) {
this.id = id;
}
...
private EntryKey key;
...
}
How can I duplicate it with another Version?
You can detach entity which retrieved from provider, change the key of Entry and then persist it as a new entity.
This error also happens if you have got the order of your components wrong.
Example: this wrong:
<ComponentA>
<ComponentB>
</ComponentA>
</ComponentB>
correct way:
<ComponentA>
<ComponentB>
</ComponentB>
</ComponentA>
Similar to Underscore library there is another library called as 'lodash' that has one method "orderBy" which takes in the parameter to determine in which order to sort it. You can use it like
_.orderBy('collection', 'propertyName', 'desc')
For some reason, it's not documented on the website docs.
!important
is somewhat like eval
. It isn't a good solution to any problem, and there are very few problems that can't be solved without it.
Try $("#divVideo video")[0].load();
after you changed the src attribute.
delete the assemeblyinfo.cs file from project under properties menu and rebulid it.
Are you working in an N-Tiered project? If so, try rebuilding your Data Layer (or wherever your EDMX file is stored) before using it.
Six Dependency scopes:
src/main
and src/test
src/test
<dependencyManagement/>
, only available in Maven 2.0.9 or later (like java import
)class atdict(dict):
def __init__(self, value, **kwargs):
super().__init__(**kwargs)
self.__dict = value
def __getattr__(self, name):
for key in self.__dict:
if type(self.__dict[key]) is list:
for idx, item in enumerate(self.__dict[key]):
if type(item) is dict:
self.__dict[key][idx] = atdict(item)
if type(self.__dict[key]) is dict:
self.__dict[key] = atdict(self.__dict[key])
return self.__dict[name]
d1 = atdict({'a' : {'b': [{'c': 1}, 2]}})
print(d1.a.b[0].c)
And the output is:
>> 1
If you're using @extends
in your content layout you can use this:
@extends('master', ['title' => $title])
I would not use .at for performance reasons.
Define a struct:
//#pragma pack(push, 2) //not useful (see comments below)
struct RGB {
uchar blue;
uchar green;
uchar red; };
And then use it like this on your cv::Mat image:
RGB& rgb = image.ptr<RGB>(y)[x];
image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y
First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.
If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
'do something
End If
End If
Another easy way to do it so that it is referenced in the project folder you want, like "Frameworks", is to:
It will appear in both the project navigator where you want it, as well as in the "Link Binary With Libraries" area of the "Build Phases" pane of your target.
You can use these string functions,
strstr — Find the first occurrence of a string
stristr — Case-insensitive strstr()
strrchr — Find the last occurrence of a character in a string
strpos — Find the position of the first occurrence of a substring in a string
strpbrk — Search a string for any of a set of characters
If that doesn't help then you should use preg
regular expression
preg_match — Perform a regular expression match
Enter the command to start up the server in that directory: py -3.7 -m http.server
Could you do the following:
obj = {
"1":"aa",
"2":"bb"
};
var newNum = "3";
var newVal = "cc";
obj[newNum] = newVal;
alert(obj["3"]); // this would alert 'cc'
For me, I would go with interfaces in many cases. But I prefer abstract classes in some cases.
Classes in OO generaly refers to implementation. I use abstract classes when I want to force some implementation details to the childs else I go with interfaces.
Of course, abstract classes are useful not only in forcing implementation but also in sharing some specific details among many related classes.
For those you are interested I've created a generic plugin that enables to close a dialog when clicking outside of it whether it a modal or non-modal dialog. It supports one or multiple dialogs on the same page.
More information here: http://www.coheractio.com/blog/closing-jquery-ui-dialog-widget-when-clicking-outside
Laurent
>>> keyDict = {"a","b","c","d"}
>>> dict([(key, []) for key in keyDict])
Output:
{'a': [], 'c': [], 'b': [], 'd': []}
In WPF the titlebar is part of the non-client area, which can't be modified through the WPF window class. You need to manipulate the Win32 handles (if I remember correctly).
This article could be helpful for you: Custom Window Chrome in WPF.
declare @d1 datetime, @d2 datetime
select @d1 = '4/19/2017', @d2 = '5/7/2017'
DECLARE @Counter int = datediff(DAY,@d1 ,@d2 )
DECLARE @C int = 0
DECLARE @SUM int = 0
WHILE @Counter > 0
begin
SET @SUM = @SUM + IIF(DATENAME(dw,
DATEADD(day,@c,@d1))IN('Sunday','Monday','Tuesday','Wednesday','Thursday')
,1,0)
SET @Counter = @Counter - 1
set @c = @c +1
end
select @Sum
It seems you don't even have to specify the compression any more. The following snippet loads the data from filename.zip into df.
import pandas as pd
df = pd.read_csv('filename.zip')
(Of course you will need to specify separator, header, etc. if they are different from the defaults.)
No, there is no build in function in python to do this, because simply:
set(A)- set(subset_of_A)
will provide you the answer.
Just use the apache commons codec library. They have a utility class called DigestUtils
No need to get into details.
Use $dec = $null
From the documentation:
$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.
PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.
try this
string htmlBody = ParseHmlBody(dtViewDetails.Rows[0]["Body"].ToString());
private string ParseHmlBody(string html)
{
string body = string.Empty;
try
{
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
body = htmlBody.OuterHtml;
}
catch (Exception ex)
{
dalPendingOrders.LogMessage("Error in ParseHmlBody" + ex.Message);
}
return body;
}
How about this:
function array_keys_exist($searchForKeys = array(), $searchableArray) {
$searchableArrayKeys = array_keys($searchableArray);
return count(array_intersect($searchForKeys, $searchableArrayKeys)) == count($searchForKeys);
}
Here is example how to remove NULL characters using ex
(in-place):
ex -s +"%s/\%x00//g" -cwq nulls.txt
and for multiple files:
ex -s +'bufdo!%s/\%x00//g' -cxa *.txt
For recursivity, you may use globbing option **/*.txt
(if it is supported by your shell).
Useful for scripting since sed
and its -i
parameter is a non-standard BSD extension.
See also: How to check if the file is a binary file and read all the files which are not?
At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON
AJAX method because it easily returns JSONP using the ?callback=?
without having any issues with CORS.
data ='USER=<?echo trim($USER)?>' +
'&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();
//Call the REST program/method returns: JSONP
$.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
.done(function( json ) {
// loading...
if ($.trim(json.ERROR) != '') {
$("#error-msg").text(message).show();
}
else{
$(".error").hide();
$("#jsonp").text(json.whatever);
}
})
.fail(function( jqXHR, textStatus, error ) {
var err = textStatus + ", " + error;
alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
});
In my case, the .project file was read-only (it was pulled from the source code control system that way). Making it writable resolved the issue.
Eclipse v4.7 (Oxygen).
I had the same problem and i saw waruna manjula giving the best answer. However writing it all down on the console is not what you might want. To get string off al info use the following
Step one: declare values at begin
//drive 1
public static string drivename = "";
public static string drivetype = "";
public static string drivevolumelabel = "";
public static string drivefilesystem = "";
public static string driveuseravailablespace = "";
public static string driveavailablespace = "";
public static string drivetotalspace = "";
//drive 2
public static string drivename2 = "";
public static string drivetype2 = "";
public static string drivevolumelabel2 = "";
public static string drivefilesystem2 = "";
public static string driveuseravailablespace2 = "";
public static string driveavailablespace2 = "";
public static string drivetotalspace2 = "";
//drive 3
public static string drivename3 = "";
public static string drivetype3 = "";
public static string drivevolumelabel3 = "";
public static string drivefilesystem3 = "";
public static string driveuseravailablespace3 = "";
public static string driveavailablespace3 = "";
public static string drivetotalspace3 = "";
Step 2: actual code
DriveInfo[] allDrives = DriveInfo.GetDrives();
int drive = 1;
foreach (DriveInfo d in allDrives)
{
if (drive == 1)
{
drivename = String.Format("Drive {0}", d.Name);
drivetype = String.Format("Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
drivevolumelabel = String.Format("Volume label: {0}", d.VolumeLabel);
drivefilesystem = String.Format("File system: {0}", d.DriveFormat);
driveuseravailablespace = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
driveavailablespace = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
drivetotalspace = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
}
drive = 2;
}
else if (drive == 2)
{
drivename2 = String.Format("Drive {0}", d.Name);
drivetype2 = String.Format("Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
drivevolumelabel2 = String.Format("Volume label: {0}", d.VolumeLabel);
drivefilesystem2 = String.Format("File system: {0}", d.DriveFormat);
driveuseravailablespace2 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
driveavailablespace2 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
drivetotalspace2 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
}
drive = 3;
}
else if (drive == 3)
{
drivename3 = String.Format("Drive {0}", d.Name);
drivetype3 = String.Format("Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
drivevolumelabel3 = String.Format("Volume label: {0}", d.VolumeLabel);
drivefilesystem3 = String.Format("File system: {0}", d.DriveFormat);
driveuseravailablespace3 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
driveavailablespace3 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
drivetotalspace3 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
}
drive = 4;
}
if (drive == 4)
{
drive = 1;
}
}
//part 2: possible debug - displays in output
//drive 1
Console.WriteLine(drivename);
Console.WriteLine(drivetype);
Console.WriteLine(drivevolumelabel);
Console.WriteLine(drivefilesystem);
Console.WriteLine(driveuseravailablespace);
Console.WriteLine(driveavailablespace);
Console.WriteLine(drivetotalspace);
//drive 2
Console.WriteLine(drivename2);
Console.WriteLine(drivetype2);
Console.WriteLine(drivevolumelabel2);
Console.WriteLine(drivefilesystem2);
Console.WriteLine(driveuseravailablespace2);
Console.WriteLine(driveavailablespace2);
Console.WriteLine(drivetotalspace2);
//drive 3
Console.WriteLine(drivename3);
Console.WriteLine(drivetype3);
Console.WriteLine(drivevolumelabel3);
Console.WriteLine(drivefilesystem3);
Console.WriteLine(driveuseravailablespace3);
Console.WriteLine(driveavailablespace3);
Console.WriteLine(drivetotalspace3);
I want to note that you can just make all the console writelines comment code, but i thought it would be nice for you to test it. If you display all these after each other you get the same list as waruna majuna
Drive C:\ Drive type: Fixed Volume label: File system: NTFS Available space to current user: 134880153600 bytes Total available space: 134880153600 bytes Total size of drive: 499554185216 bytes
Drive D:\ Drive type: CDRom
Drive H:\ Drive type: Fixed Volume label: HDD File system: NTFS Available space to current user: 2000010817536 bytes Total available space: 2000010817536 bytes Total size of drive: 2000263573504 bytes
However you can now acces all of the loose information at strings
I think the OP's question is solved by deleting the ~/.ssh/known_hosts (which was a folder, not a file). But for other's who might be having this issue, I noticed that one of my servers had weird permissions (400):
-r--------. 1 user user 396 Jan 7 11:12 /home/user/.ssh/known_hosts
So I solved this by adding owner/user PLUS write.
chmod u+w ~/.ssh/known_hosts
Thus. ~/.ssh/known_hosts needs to be a flat file, and must be owned by you, and you need to be able to read and write to it.
You could always declare known_hosts bankruptcy, delete it, and continue doing things as normal, and connecting to things (git / ssh) will regenerate a new known_hosts that should work just fine.
If your activity's view is declared in xml (ex activity_root.xml
), open the xml and assign an id to the root view:
android:id="@+id/root_activity"
Now in your class, import the view using:
import kotlinx.android.synthetic.main.activity_root.root_activity
You can now use root_activity
as the view.
I think no one has given the correct answer to the question. My working solution is : 1. Just declare another class along with container-fluid class example(.maxx):
<div class="container-fluid maxx">_x000D_
<div class="row">_x000D_
<div class="col-sm-12">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
.container-fluid.maxx {_x000D_
padding-left: 0px;_x000D_
padding-right: 0px; }
_x000D_
This will work 100% and will remove the padding from left and right. I hope this helps.
One part missing in all these explanations is how are Cookies and Session linked- By SessionID cookie. Cookie goes back and forth between client and server - the server links the user (and its session) by session ID portion of the cookie. You can send SessionID via url also (not the best best practice) - in case cookies are disabled by client.
Did I get this right?
For Kotlin
val hours = String.format("%02d", TimeUnit.MILLISECONDS.toHours(milSecs))
val minutes = String.format("%02d",
TimeUnit.MILLISECONDS.toMinutes(milSecs) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milSecs)))
val seconds = String.format("%02d",
TimeUnit.MILLISECONDS.toSeconds(milSecs) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milSecs)))
where, milSecs
is milliseconds
How to read the shell variable in groovy / how to assign shell return value to groovy variable.
Requirement : Open a text file read the lines using shell and store the value in groovy and get the parameter for each line .
Here , is delimiter
Ex: releaseModule.txt
./APP_TSBASE/app/team/i-home/deployments/ip-cc.war/cs_workflowReport.jar,configurable-wf-report,94,23crb1,artifact
./APP_TSBASE/app/team/i-home/deployments/ip.war/cs_workflowReport.jar,configurable-temppweb-report,394,rvu3crb1,artifact
========================
Here want to get module name 2nd Parameter (configurable-wf-report) , build no 3rd Parameter (94), commit id 4th (23crb1)
def module = sh(script: """awk -F',' '{ print \$2 "," \$3 "," \$4 }' releaseModules.txt | sort -u """, returnStdout: true).trim()
echo module
List lines = module.split( '\n' ).findAll { !it.startsWith( ',' ) }
def buildid
def Modname
lines.each {
List det1 = it.split(',')
buildid=det1[1].trim()
Modname = det1[0].trim()
tag= det1[2].trim()
echo Modname
echo buildid
echo tag
}
Inner join matches tables on keys, but outer join matches keys just for one side. For example when you use left outer join the query brings the whole left side table and matches the right side to the left table primary key and where there is not matched places null.
In addition to posts by @xdumain, I prefer creating data object before ajax call so you can debug it.
var dataObject = JSON.stringify({
'input': $('#myInput').val(),
'name': $('#myName').val(),
});
Now use it in ajax call
$.ajax({
url: "/Home/SaveChart",
type: 'POST',
async: false,
dataType: 'json',
contentType: 'application/json',
data: dataObject,
success: function (data) { },
error: function (xhr) { } )};
In addition to the good answers above to set the navigation view controller on top of your screen on your app, you can add it to your AppDelegate.swift file inside the block as follows
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow()
window?.makeKeyAndVisible()
window?.rootViewController = UINavigationController(rootViewController: LoginViewController())
return true
}
you can use style
<td colspan="2">
<div style="float:left; width:80px"><asp:Label ID="Label6" runat="server" Text="Label"></asp:Label></div>
<div style="float: right; width:100px">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</div>
<div style="clear:both"></div>
</td>
In JSX/ React prevent text from wrapping
<div style={{ whiteSpace: "nowrap", overflow: "hidden" }}>
Text that will never wrap
</div>
With the excellent matplotlib
and numpy
packages
from matplotlib import pyplot as mp
import numpy as np
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
x_values = np.linspace(-3, 3, 120)
for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
mp.plot(x_values, gaussian(x_values, mu, sig))
mp.show()
See this question for some insight into best-practices for your situation.
The topline suggestion (from said link) is to standardize a response structure (for both success and failure) that your handler looks for, catching all Exceptions at the server layer and converting them to the same structure. For example (from this answer):
{
success:false,
general_message:"You have reached your max number of Foos for the day",
errors: {
last_name:"This field is required",
mrn:"Either SSN or MRN must be entered",
zipcode:"996852 is not in Bernalillo county. Only Bernalillo residents are eligible"
}
}
This is the approach stackoverflow uses (in case you were wondering how others do this kind of thing); write operations like voting have "Success"
and "Message"
fields, regardless of if the vote was allowed or not:
{ Success:true, NewScore:1, Message:"", LastVoteTypeId:3 }
As @Phil.H pointed out, you should be consistent in whatever you choose. This is easier said than done (as is everything in development!).
For example, if you submit comments too quickly on SO, instead of being consistent and returning
{ Success: false, Message: "Can only comment once every blah..." }
SO will throw a server exception (HTTP 500
) and catch it in their error
callback.
As much as it "feels right" to use jQuery + .ashx
+ HTTP [status codes] IMO it will add more complexity to your client-side code base than it's worth. Realize that jQuery does not "detect" error codes but rather the lack of a success code. This is an important distinction when trying to design a client around http response codes with jQuery. You only get two choices (was it a "success" or "error"?), which you have to branch further on your own. If you have a small number of WebServices driving a small number of pages then it might be okay, but anything larger scale may get messy.
It's much more natural in a .asmx
WebService (or WCF for that matter) to return a custom object than to customize the HTTP status code. Plus you get the JSON serialization for free.
Just had the same problem myself.
What happens is, that even if you drop the database, innodb will still not release disk space. I had to export, stop mysql, remove the files manually, start mysql, create database and users, and then import. Thank god I only had 200MB worth of rows, but it spared 250GB of innodb file.
Fail by design.
With JDK/11, an alternate way of converting a Collection<Foo>
to an Foo[]
could be to make use of Collection.toArray(IntFunction<T[]> generator)
as:
Foo[] foos = fooCollection.toArray(new Foo[0]); // before JDK 11
Foo[] updatedFoos = fooCollection.toArray(Foo[]::new); // after JDK 11
As explained by @Stuart on the mailing list(emphasis mine), the performance of this should essentially be the same as that of the existing Collection.toArray(new T[0])
--
The upshot is that implementations that use
Arrays.copyOf(
) are the fastest, probably because it's an intrinsic.It can avoid zero-filling the freshly allocated array because it knows the entire array contents will be overwritten. This is true regardless of what the public API looks like.
The implementation of the API within the JDK reads:
default <T> T[] toArray(IntFunction<T[]> generator) {
return toArray(generator.apply(0));
}
The default implementation calls
generator.apply(0)
to get a zero-length array and then simply callstoArray(T[])
. This goes through theArrays.copyOf()
fast path, so it's essentially the same speed astoArray(new T[0])
.
Note:- Just that the API use shall be guided along with a backward incompatibility when used for code with null
values e.g. toArray(null)
since these calls would now be ambiguous because of existing toArray(T[] a)
and would fail to compile.
Show file and track error
systemctl status nginx.service
How about:
rm -rf "$(pwd -P)"/*
Why do you want to do that?
However, You can do this:
public void foo(int param1)
{
int param2 = 2;
// rest of code
}
or:
public void foo(int param1, int param2)
{
// rest of code
}
public void foo(int param1)
{
foo(param1, 2);
}
There is also an option to make configuration
static in startup.cs so that what you can access it anywhere with ease, static variables are convenient huh!
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
internal static IConfiguration Configuration { get; private set; }
This makes configuration accessible anywhere using Startup.Configuration.GetSection...
What can go wrong?
It appears that anonymous objects can be declared or created in a switch case statement for the reason that they cannot be referenced and as such cannot fall through to the next case. Consider this example compiles on GCC 4.5.3 and Visual Studio 2008 (might be a compliance issue tho' so experts please weigh in)
#include <cstdlib>
struct Foo{};
int main()
{
int i = 42;
switch( i )
{
case 42:
Foo(); // Apparently valid
break;
default:
break;
}
return EXIT_SUCCESS;
}
You have a few options:
Using Enumerable.Where:
list.Where(i => i.Property == value).FirstOrDefault(); // C# 3.0+
Using List.Find:
list.Find(i => i.Property == value); // C# 3.0+
list.Find(delegate(Item i) { return i.Property == value; }); // C# 2.0+
Both of these options return default(T)
(null
for reference types) if no match is found.
As mentioned in the comments below, you should use the appropriate form of comparison for your scenario:
==
for simple value types or where use of operator overloads are desiredobject.Equals(a,b)
for most scenarios where the type is unknown or comparison has potentially been overriddenstring.Equals(a,b,StringComparison)
for comparing stringsobject.ReferenceEquals(a,b)
for identity comparisons, which are usually the fastestIf you initialize both the parameters as float
, you will sure get actual divided value.
For example:
float RoomWidth, TileWidth, NumTiles;
RoomWidth = 142;
TileWidth = 8;
NumTiles = RoomWidth/TileWidth;
Ans:17.75.
Todo this in a single system call you can use the fs-extra
npm module.
After this the file will have been created as well as the directory it is to be placed in.
const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.txt'
fs.ensureFile(file, err => {
console.log(err) // => null
});
Another way is to use ensureFileSync which will do the same thing but synchronous.
const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.txt'
fs.ensureFileSync(file)
Try something like this:
yourControl.DataSource = countryInstance.Cities;
And if you are using WebForms you will need to add this line:
yourControl.DataBind();
I saw jheriko's comment above and was initially agreeing that I couldn't find a way to avoid using DoEvents if you end up spinning your main UI thread waiting for a long running asynchronous piece of code on another thread to complete. But from Matthias's answer a simple Refresh of a small panel on my UI can replace the DoEvents (and avoid a nasty side effect).
More detail on my case ...
I was doing the following (as suggested here) to ensure that a progress bar type splash screen (How to display a "loading" overlay...) updated during a long running SQL command:
IAsyncResult asyncResult = sqlCmd.BeginExecuteNonQuery();
while (!asyncResult.IsCompleted) //UI thread needs to Wait for Async SQL command to return
{
System.Threading.Thread.Sleep(10);
Application.DoEvents(); //to make the UI responsive
}
The bad: For me calling DoEvents meant that mouse clicks were sometimes firing on forms behind my splash screen, even if I made it TopMost.
The good/answer: Replace the DoEvents line with a simple Refresh call to a small panel in the centre of my splash screen, FormSplash.Panel1.Refresh()
. The UI updates nicely and the DoEvents weirdness others have warned of was gone.
What is your opinion to use express-generator it will generate skeleton project to start with, without deprecated messages
appeared in your log
run this command
npm install express-generator -g
Now, create new Express.js starter application by type this command in your Node projects folder
.
express node-express-app
That command tell express to generate new Node.js application with the name node-express-app
.
then Go to the newly created project directory
, install npm packages
and start the app
using the command
cd node-express-app && npm install && npm start
Both the answers provided above work fine.
You should use a sticky footer solution such as this one :
* {
margin: 0;
}
html, body {
height: 100%;
}
.wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
height: 142px; /* .push must be the same height as .footer */
}
There are others like this;
* {margin:0;padding:0;}
/* must declare 0 margins on everything, also for main layout components use padding, not
vertical margins (top and bottom) to add spacing, else those margins get added to total height
and your footer gets pushed down a bit more, creating vertical scroll bars in the browser */
html, body, #wrap {height: 100%;}
body > #wrap {height: auto; min-height: 100%;}
#main {padding-bottom: 150px;} /* must be same height as the footer */
#footer {position: relative;
margin-top: -150px; /* negative value of footer height */
height: 150px;
clear:both;}
/* CLEAR FIX*/
.clearfix:after {content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;}
.clearfix {display: inline-block;}
/* Hides from IE-mac \*/
* html .clearfix { height: 1%;}
.clearfix {display: block;}
with the html:
<div id="wrap">
<div id="main" class="clearfix">
</div>
</div>
<div id="footer">
</div>
Use two minipages.
\begin{minipage}[position]{width}
text
\end{minipage}
I installed Bitnami WAMP Stack 7.1.29-0 and it asked for a password during installation. In this case it was
username: root
password: <password set by you during install>
read
will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:
import boto3
s3 = boto3.resource('s3')
obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8')
For modern docker engines use this command :
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id
and for older engines use :
docker inspect --format '{{ .NetworkSettings.IPAddress }}' container_name_or_id
There are already good answers posted here for this question. But, this is the way I've tried myself (and might be the easiest logic based ? modulo/divide/add):
int decimalOrBinary = 345;
StringBuilder builder = new StringBuilder();
do {
builder.append(decimalOrBinary % 2);
decimalOrBinary = decimalOrBinary / 2;
} while (decimalOrBinary > 0);
System.out.println(builder.reverse().toString()); //prints 101011001
Add a single line AddKeysToAgent yes
on the top of the .ssh/config file. Ofcourse ssh-agent must be running beforehand. If its not running ( check by prep ssh-agent
) , then simply run it eval $(ssh-agent)
Now, the key is loaded systemwide into the memory and you dont have to type in the passphrase again.
The source of the solution is https://askubuntu.com/questions/362280/enter-ssh-passphrase-once/853578#853578
the problem is you're trying to use regex features not supported by grep. namely, your \d
won't work. use this instead:
REGEX_DATE="^[[:digit:]]{2}[-/][[:digit:]]{2}[-/][[:digit:]]{4}$"
echo "$1" | grep -qE "${REGEX_DATE}"
echo $?
you need the -E
flag to get ERE in order to use {#}
style.
As an alternative to everyone else's answers I've always done something like this:
List<String> toRemove = new ArrayList<String>();
for (String str : myArrayList) {
if (someCondition) {
toRemove.add(str);
}
}
myArrayList.removeAll(toRemove);
This will avoid you having to deal with the iterator directly, but requires another list. I've always preferred this route for whatever reason.
Sergio Carneiro's and Jon's implementation requires you to define an initializer function for all but one class. Here is a modified version of the aggregation function, which makes use of default parameters in the constructors instead. Included are also some comments by me.
var aggregation = (baseClass, ...mixins) => {
class base extends baseClass {
constructor (...args) {
super(...args);
mixins.forEach((mixin) => {
copyProps(this,(new mixin));
});
}
}
let copyProps = (target, source) => { // this function copies all properties and symbols, filtering out some special ones
Object.getOwnPropertyNames(source)
.concat(Object.getOwnPropertySymbols(source))
.forEach((prop) => {
if (!prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))
Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop));
})
}
mixins.forEach((mixin) => { // outside contructor() to allow aggregation(A,B,C).staticFunction() to be called etc.
copyProps(base.prototype, mixin.prototype);
copyProps(base, mixin);
});
return base;
}
Here is a little demo:
class Person{
constructor(n){
this.name=n;
}
}
class Male{
constructor(s='male'){
this.sex=s;
}
}
class Child{
constructor(a=12){
this.age=a;
}
tellAge(){console.log(this.name+' is '+this.age+' years old.');}
}
class Boy extends aggregation(Person,Male,Child){}
var m = new Boy('Mike');
m.tellAge(); // Mike is 12 years old.
This aggregation function will prefer properties and methods of a class that appear later in the class list.
here is direct link for api 17 documentation. Just extract at under docs folder. Hope it helps.
https://dl-ssl.google.com/android/repository/docs-17_r02.zip (129 MB)
I was facing the same problem so what I did I dropped the field for the primary key then I recreated it and made sure that it is auto incremental . That worked for me . I hope it helps others