Bootstrap comes with many pre-build classes and one of them is class="text-left"
. Please call this class whenever needed. :-)
It's amazing what the Framework already does for us.
List<int> myValues;
string csv = String.Join(",", myValues.Select(x => x.ToString()).ToArray());
For the general case:
IEnumerable<T> myList;
string csv = String.Join(",", myList.Select(x => x.ToString()).ToArray());
As you can see, it's effectively no different. Beware that you might need to actually wrap x.ToString()
in quotes (i.e., "\"" + x.ToString() + "\""
) in case x.ToString()
contains commas.
For an interesting read on a slight variant of this: see Comma Quibbling on Eric Lippert's blog.
Note: This was written before .NET 4.0 was officially released. Now we can just say
IEnumerable<T> sequence;
string csv = String.Join(",", sequence);
using the overload String.Join<T>(string, IEnumerable<T>)
. This method will automatically project each element x
to x.ToString()
.
I had the same issue when I changed the home directory of one use. In my case it was because of selinux
. I used the below to fix the issue:
selinuxenabled 0
setenforce 0
It is O(1) only if your hashing function is very good. The Java hash table implementation does not protect against bad hash functions.
Whether you need to grow the table when you add items or not is not relevant to the question because it is about lookup time.
Sending data from Activity into Fragments linked by XML
If you create a fragment in Android Studio using one of the templates e.g. File > New > Fragment > Fragment (List), then the fragment is linked via XML. The newInstance method is created in the fragment but is never called so can't be used to pass arguments.
Instead in the Activity override the method onAttachFragment
@Override
public void onAttachFragment(Fragment fragment) {
if (fragment instanceof DetailsFragment) {
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
}
}
Then read the arguments in the fragment onCreate method as per the other answers
jeues answer helped me nothing :-( after hours I finally found the solution for my system and I think this will help other people too. I had to set the LD_LIBRARY_PATH like this:
export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/
after that everything worked very well, even without any "-extension RANDR" switch.
Taking Unanswered's answer and reformatting it, we have:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
Next, I would recommend making this a natural part of your build, rather than something to call explicitly. To make this a integral part of your build, add this plugin to your pom.xml
and bind it to the package
lifecycle event. However, a gotcha is that you need to call the assembly:single
goal if putting this in your pom.xml, while you would call 'assembly:assembly' if executing it manually from the command line.
<project>
[...]
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-my-jar-with-dependencies</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
[...]
</plugins>
[...]
</build>
</project>
var element = document.getElementById(element_id);
element.className += " " + newClassName;
Voilà. This will work on pretty much every browser ever. The leading space is important, because the className
property treats the css classes like a single string, which ought to match the class
attribute on HTML elements (where multiple classes must be separated by spaces).
Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.
In prototype, for instance:
// Prototype automatically checks that the element doesn't already have the class
$(element_id).addClassName(newClassName);
See how much nicer that is?!
You can also put :
@GeneratedValue(strategy = GenerationType.IDENTITY)
And let the DateBase manage the incrementation of the primary key:
AUTO_INCREMENT PRIMARY KEY
The above answer helped me.
Updated version for SQL Server 2017 using STRING_AGG function to construct the pivot column list:
create table temp
(
date datetime,
category varchar(3),
amount money
);
insert into temp values ('20120101', 'ABC', 1000.00);
insert into temp values ('20120201', 'DEF', 500.00);
insert into temp values ('20120201', 'GHI', 800.00);
insert into temp values ('20120210', 'DEF', 700.00);
insert into temp values ('20120301', 'ABC', 1100.00);
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = (SELECT STRING_AGG(category,',') FROM (SELECT DISTINCT category FROM temp WHERE category IS NOT NULL)t);
set @query = 'SELECT date, ' + @cols + ' from
(
select date
, amount
, category
from temp
) x
pivot
(
max(amount)
for category in (' + @cols + ')
) p ';
execute(@query);
drop table temp;
open etc folder in netbeans folder then edit the netbeans.conf with notepad and you will find a line like this :
Default location of JDK, can be overridden by using --jdkhome :
netbeans_jdkhome="G:\Program Files\Java\jdk1.6.0_13"
here you can set your jdk version.
The path for the latest version of Git is changed, In my laptop, I found it in
C:\Users\Anum Sheraz\AppData\Local\Programs\Git\bin\git.exe
This resolved my issue of path. Hope that helps to someone :)
When changing fonts in XCode from [Preferences] (after duplicating a template that matches colours close to what you want), you can select multiple entries and change the fonts all at once. Use [shift] to select a range or [cmd] to select multiple individual entries (e.g. you might select both 'comments' and 'strings' and change only their fonts).
Steve
what you have is fine - however to save some typing, you can simply use for your data
data: $('#formId').serialize()
see http://www.ryancoughlin.com/2009/05/04/how-to-use-jquery-to-serialize-ajax-forms/ for details, the syntax is pretty basic.
Just specifying the uri endpoint worked for me, bower 1.3.9
"dependencies": {
"jquery.cookie": "latest",
"everestjs": "http://www.everestjs.net/static/st.v2.js"
}
Running bower install
, I received following output:
bower new version for http://www.everestjs.net/static/st.v2.js#*
bower resolve http://www.everestjs.net/static/st.v2.js#*
bower download http://www.everestjs.net/static/st.v2.js
You could also try updating bower
npm update -g bower
According to documentation: the following types of urls are supported:
http://example.com/script.js
http://example.com/style.css
http://example.com/package.zip (contents will be extracted)
http://example.com/package.tar (contents will be extracted)
It's not a direct answer to the question but you could just use the OR-operator
( grep "#SystemMaxUse=" journald.conf > /dev/null && sed -i 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf ) || echo "This file has been edited. You'll need to do it manually."
You could use the .NET library to do the same thing which i believe is more straightforward.
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; data source={path of your excel file}; Extended Properties=Excel 12.0;";
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
//Create connection object by using the preceding connection string.
objConn = new OleDbConnection(connString);
objConn.Open();
//Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sql = string.Format("select * from [{0}$]", sheetName);
var adapter = new System.Data.OleDb.OleDbDataAdapter(sql, ConnectionString);
var ds = new System.Data.DataSet();
string tableName = sheetName;
adapter.Fill(ds, tableName);
System.Data.DataTable data = ds.Tables[tableName];
After you have your data in the datatable you can access them as you would normally do with a DataTable class.
I ran into the same problem and reported it as a bug on the Facebook developer site. It seems pretty clear that og:image
URIs using HTTP work just fine and URIs using HTTPS do not. They have now acknowledged that they are "looking into this."
Update: As of 2020, the bug is no longer visible in Facebook's ticket system. They never responded and I don't believe this behavior has changed. However, specifying HTTPS URI in og:image:secure
does seem to be working fine.
Basically it's a script that is launched before unversioned property is modified on the repository, so that you can manage more precisely what's happening on your repository.
There are templates in the SVN distrib for different hooks, located in the /hooks subdirectory (*.tmpl that you have to edit and rename depending on your OS, to activate).
This should do:
public static boolean implementsInterface(Object object, Class interf){
return interf.isInstance(object);
}
For example,
java.io.Serializable.class.isInstance("a test string")
evaluates to true
.
setting display:flex
for the text worked for me.
newlist = oldlist[::10]
This picks out every 10th element of the list.
You're missing #include <stdlib.h>
.
Connect with SSH and follow these instructions to install Node on a shared hosting
In short you first install NVM, then you install the Node version of your choice with NVM.
wget -qO- https://cdn.rawgit.com/creationix/nvm/master/install.sh | bash
Your restart your shell (close and reopen your sessions). Then you
nvm install stable
to install the latest stable version for example. You can install any version of your choice. Check node --version
for the node version you are currently using and nvm list
to see what you've installed.
In bonus you can switch version very easily (nvm use <version>
)
There's no need of PHP or whichever tricky workaround if you have SSH.
Dictionary keys should be unique !
In my case, I was using a Dictionary, and I found two items in it have accidentally the same key.
Dictionary<string, string> myDictionary = new Dictionary<string, string>() {
{"KEY1", "V1"},
{"KEY1", "V2" },
{"KEY3", "V3"},
};
From the Perldoc page on sleep:
For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides usleep().
Actually, it provides usleep()
(which sleeps in microseconds) and nanosleep()
(which sleeps in nanoseconds). You may want usleep()
, which should let you deal with easier numbers. 1 millisecond sleep (using each):
use strict;
use warnings;
use Time::HiRes qw(usleep nanosleep);
# 1 millisecond == 1000 microseconds
usleep(1000);
# 1 microsecond == 1000 nanoseconds
nanosleep(1000000);
If you don't want to (or can't) load a module to do this, you may also be able to use the built-in select()
function:
# Sleep for 250 milliseconds
select(undef, undef, undef, 0.25);
How about catch it at EndRequest event?
protected void Application_EndRequest(object sender, EventArgs e)
{
HttpRequest request = HttpContext.Current.Request;
HttpResponse response = HttpContext.Current.Response;
if ((request.HttpMethod == "POST") &&
(response.StatusCode == 404 && response.SubStatusCode == 13))
{
// Clear the response header but do not clear errors and
// transfer back to requesting page to handle error
response.ClearHeaders();
HttpContext.Current.Server.Transfer(request.AppRelativeCurrentExecutionFilePath);
}
}
It looks like you would do something like this:
boost::shared_mutex _access;
void reader()
{
// get shared access
boost::shared_lock<boost::shared_mutex> lock(_access);
// now we have shared access
}
void writer()
{
// get upgradable access
boost::upgrade_lock<boost::shared_mutex> lock(_access);
// get exclusive access
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
// now we have exclusive access
}
The .ready
function is used to insert the attribute once the page has finished loading.
$(document).ready(function() {
$("class name or id a.your class name").attr({"target" : "_blank"})
})
You will have to apply all Eclipse shortcuts with Android Studio before using all those shortcuts.
Procedure:
Steps:
Setting -> KeyMap -> Select Eclipse -> Apply -> OK
Now you can use all Eclipse shortcuts in Android Studio...
Have some snapshots here.
Here is a simple example :
Create or alter PROCEDURE getPersonCountByLastName (
@lastName varchar(20),
@count int OUTPUT
)
As
Begin
select @count = count(personSid) from Person where lastName like @lastName
End;
Execute below statements in one batch (by selecting all)
1. Declare @count int
2. Exec getPersonCountByLastName kumar, @count output
3. Select @count
When i tried to execute statements 1,2,3 individually, I had the same error. But when executed them all at one time, it worked fine.
The reason is that SQL executes declare, exec statements in different sessions.
Open to further corrections.
JAR stands for Java ARchive. It's a file format based on the popular ZIP file format and is used for aggregating many files into one. Although JAR can be used as a general archiving tool, the primary motivation for its development was so that Java applets and their requisite components (.class files, images and sounds) can be downloaded to a browser in a single HTTP transaction, rather than opening a new connection for each piece. This greatly improves the speed with which an applet can be loaded onto a web page and begin functioning. The JAR format also supports compression, which reduces the size of the file and improves download time still further. Additionally, individual entries in a JAR file may be digitally signed by the applet author to authenticate their origin.
The explanation from Scott Meyers in Effective C++ might help understand when to use them:
Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.
Raymond Chen has a few ideas:
https://devblogs.microsoft.com/oldnewthing/20050128-00/?p=36573
Quoted here in full because MSDN archives tend to be somewhat unreliable:
The easy way is to use the
%CD%
pseudo-variable. It expands to the current working directory.
set OLDDIR=%CD%
.. do stuff ..
chdir /d %OLDDIR% &rem restore current directory
(Of course, directory save/restore could more easily have been done with
pushd
/popd
, but that's not the point here.)The
%CD%
trick is handy even from the command line. For example, I often find myself in a directory where there's a file that I want to operate on but... oh, I need to chdir to some other directory in order to perform that operation.
set _=%CD%\curfile.txt
cd ... some other directory ...
somecommand args %_% args
(I like to use
%_%
as my scratch environment variable.)Type
SET /?
to see the other pseudo-variables provided by the command processor.
Also the comments in the article are well worth scanning for example this one (via the WayBack Machine, since comments are gone from older articles):
http://blogs.msdn.com/oldnewthing/archive/2005/01/28/362565.aspx#362741
This covers the use of %~dp0:
If you want to know where the batch file lives:
%~dp0
%0
is the name of the batch file.~dp
gives you the drive and path of the specified argument.
Be aware of the single quotes for the string format. This doesn't work:
Content="{Binding PlannedDateTime, StringFormat={}{0:yy.MM.dd HH:mm}}"
while this does:
Content="{Binding PlannedDateTime, StringFormat='{}{0:yy.MM.dd HH:mm}'}"
In my case, setting SQL Server Database Engine service startup account to NT AUTHORITY\NETWORK SERVICE failed, but setting it to NT Authority\System allowed me to succesfully install my SQL Server 2016 STD instance.
Just check the following snapshot.
For further details, check @Shanky's answer at https://dba.stackexchange.com/a/71798/66179
Remember: you can avoid server rebooting using setup's SkipRules switch:
setup.exe /ACTION=INSTALL /SkipRules=RebootRequiredCheck
setup.exe /ACTION=UNINSTALL /SkipRules=RebootRequiredCheck
Another way of returning all files in subdirectories is to use the pathlib
module, introduced in Python 3.4, which provides an object oriented approach to handling filesystem paths (Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi):
from pathlib import Path
rootdir = Path('C:/Users/sid/Desktop/test')
# Return a list of regular files only, not directories
file_list = [f for f in rootdir.glob('**/*') if f.is_file()]
# For absolute paths instead of relative the current dir
file_list = [f for f in rootdir.resolve().glob('**/*') if f.is_file()]
Since Python 3.5, the glob
module also supports recursive file finding:
import os
from glob import iglob
rootdir_glob = 'C:/Users/sid/Desktop/test/**/*' # Note the added asterisks
# This will return absolute paths
file_list = [f for f in iglob(rootdir_glob, recursive=True) if os.path.isfile(f)]
The file_list
from either of the above approaches can be iterated over without the need for a nested loop:
for f in file_list:
print(f) # Replace with desired operations
<select name="aa" onchange="report(this.value)">
<option value="">Please select</option>
<option value="daily">daily</option>
<option value="monthly">monthly</option>
</select>
using
function report(period) {
if (period=="") return; // please select - possibly you want something else here
const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
document.getElementById('responseTag').style.visibility='visible';
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
}
Unobtrusive version:
<select id="aa" name="aa">
<option value="">Please select</option>
<option value="daily">daily</option>
<option value="monthly">monthly</option>
</select>
using
window.addEventListener("load",function() {
document.getElementById("aa").addEventListener("change",function() {
const period = this.value;
if (period=="") return; // please select - possibly you want something else here
const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
document.getElementById('responseTag').style.visibility='visible';
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
});
});
jQuery version - same select with ID
$(function() {
$("#aa").on("change",function() {
const period = this.value;
if (period=="") return; // please select - possibly you want something else here
var report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
$('#responseTag').show();
$('#list_report').hide();
$('#formTag').hide();
});
});
This parameter is is working for me:
--enable-easy-off-store-extension-install
Do the following:
--enable-easy-off-store-extension-install
chrome.exe --enable-easy-off-store-extension-install
I know it's been a little over two years... but I was looking for a way to do this, and wasn't overly happy with the solution posted (it works fine, but I wanted a little more information as the import happens). When combining all the SQL files in to one, you don't get any sort of progress updates.
So I kept digging for an answer and thought this might be a good place to post what I found for future people looking for the same answer. Here's a command line in Windows that will import multiple SQL files from a folder. You run this from the command line while in the directory where mysql.exe is located.
for /f %f in ('dir /b <dir>\<mask>') do mysql --user=<user> --password=<password> <dbname> < <dir>\%f
With some assumed values (as an example):
for /f %f in ('dir /b c:\sqlbackup\*.sql') do mysql --user=mylogin --password=mypass mydb < c:\sqlbackup\%f
If you had two sets of SQL backups in the folder, you could change the *.sql to something more specific (like mydb_*.sql).
You can use onSelect
event
$("#date-daily").datepicker({
onSelect: function(dateText) {
alert($('#dp3').val());
}
});
It is Called when the datepicker is selected. The function receives the selected date as text and the datepicker instance as parameters. this refers to the associated input field.
Try this:
document.addEventListener("keydown", KeyCheck); //or however you are calling your method
function KeyCheck(event)
{
var KeyID = event.keyCode;
switch(KeyID)
{
case 8:
alert("backspace");
break;
case 46:
alert("delete");
break;
default:
break;
}
}
Dim shll : Set shll = CreateObject("WScript.Shell")
Set Rt = shll.Exec("Notepad") : wscript.sleep 4000 : Rt.Terminate
Run the process with .Exec
.
Then wait for 4 seconds.
After that kill this process.
Your DOS command 2> nul
Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.
Try this:
dataTable.Columns["Marks"].ColumnName = "SubjectMarks";
First off, what compiler or dev environment are you using? If Visual Studio, you need to make a console application project to get console output.
Second,
std::cout << "Hello World" << std::endl;
should work in any C++ console application.
I found this answer when I was getting a similar error for nodeName
after upgrading to Bootstrap 4. The issue was that the tabs didn't have the nav
and nav-tab
classes; adding those to the <ul>
element fixed the issue.
As others have pointed out, listeners have to be registered in order to read these streams. Also note that Debug.Write
will only function if the DEBUG
build flag is set, while Trace.Write
will only function if the TRACE
build flag is set.
Setting the DEBUG
and/or TRACE
flags is easily done in the project properties in Visual Studio or by supplying the following arguments to csc.exe
/define:DEBUG;TRACE
The getRequestURL()
omits the port when it is 80 while the scheme is http
, or when it is 443 while the scheme is https
.
So, just use getRequestURL()
if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
This has happened to me also, after undating to IOS11 on my iPhone. When I try to connect to the corporate network it bring up the corporate cert and says it isn't trusted. I press the 'trust' button and the connection fails and the cert does not appear in the trusted certs list.
stata.replace<-function(data,replacevar,replacevalue,ifs) {
ifs=parse(text=ifs)
yy=as.numeric(eval(ifs,data,parent.frame()))
x=sum(yy)
data=cbind(data,yy)
data[yy==1,replacevar]=replacevalue
message=noquote(paste0(x, " replacement are made"))
print(message)
return(data[,1:(ncol(data)-1)])
}
Call this function using below line.
d=stata.replace(d,"under20",1,"age<20")
You declared the constructor blowfish as this:
Blowfish(BlowfishAlgorithm algorithm);
So this line cannot exist (without further initialization later):
Blowfish _blowfish;
since you passed no parameter. It does not understand how to handle a parameter-less declaration of object "BlowFish" - you need to create another constructor for that.
You can use:
>>> np.concatenate([array1, array2, ...])
e.g.
>>> import numpy as np
>>> a = [[1, 2, 3],[10, 20, 30]]
>>> b = [[100,200,300]]
>>> a = np.array(a) # not necessary, but numpy objects prefered to built-in
>>> b = np.array(b) # "^
>>> a
array([[ 1, 2, 3],
[10, 20, 30]])
>>> b
array([[100, 200, 300]])
>>> c = np.concatenate([a,b])
>>> c
array([[ 1, 2, 3],
[ 10, 20, 30],
[100, 200, 300]])
>>> print c
[[ 1 2 3]
[ 10 20 30]
[100 200 300]]
~-+-~-+-~-+-~
Sometimes, you will come across trouble if a numpy array object is initialized with incomplete values for its shape property. This problem is fixed by assigning to the shape property the tuple: (array_length, element_length).
Note: Here, 'array_length' and 'element_length' are integer parameters, which you substitute values in for. A 'tuple' is just a pair of numbers in parentheses.
e.g.
>>> import numpy as np
>>> a = np.array([[1,2,3],[10,20,30]])
>>> b = np.array([100,200,300]) # initialize b with incorrect dimensions
>>> a.shape
(2, 3)
>>> b.shape
(3,)
>>> c = np.concatenate([a,b])
Traceback (most recent call last):
File "<pyshell#191>", line 1, in <module>
c = np.concatenate([a,b])
ValueError: all the input arrays must have same number of dimensions
>>> b.shape = (1,3)
>>> c = np.concatenate([a,b])
>>> c
array([[ 1, 2, 3],
[ 10, 20, 30],
[100, 200, 300]])
In Swift you can use the following equalities to determine the kind of device on Universal apps:
UIDevice.current.userInterfaceIdiom == .phone
// or
UIDevice.current.userInterfaceIdiom == .pad
Usage would then be something like:
if UIDevice.current.userInterfaceIdiom == .pad {
// Available Idioms - .pad, .phone, .tv, .carPlay, .unspecified
// Implement your logic here
}
This worked for me, in my case I had a button with a data-id attribute:
$("a").data("item-id");
I find it frustrating that typeof
is so limited. Here’s an improved version:
var realtypeof = function (obj) {
switch (typeof(obj)) {
// object prototypes
case 'object':
if (obj instanceof Array)
return '[object Array]';
if (obj instanceof Date)
return '[object Date]';
if (obj instanceof RegExp)
return '[object regexp]';
if (obj instanceof String)
return '[object String]';
if (obj instanceof Number)
return '[object Number]';
return 'object';
// object literals
default:
return typeof(obj);
}
};
sample test:
realtypeof( '' ) // "string"
realtypeof( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]"
If we want to apply the same functionality and features to more than one selectors then we use multiple selector options. I think we can say this feature is used like reusability. write a jquery function and just add multiple selectors in which we want the same features.
Kindly take a look in below example:
$( "div, span, .paragraph, #paraId" ).css( {"font-family": "tahoma", "background": "red"} );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>Div element</div>_x000D_
<p class="paragraph">Paragraph with class selector</p>_x000D_
<p id="paraId">Paragraph with id selector</p>_x000D_
<span>Span element</span>
_x000D_
I hope it will help you. Namaste
Note that Robert's answer is correct, and it works in sh
as well. You can (portably) simplify it even further:
for i in "$@"
is equivalent to:
for i
I.e., you don't need anything!
Testing ($
is command prompt):
$ set a b "spaces here" d
$ for i; do echo "$i"; done
a
b
spaces here
d
$ for i in "$@"; do echo "$i"; done
a
b
spaces here
d
I first read about this in Unix Programming Environment by Kernighan and Pike.
In bash
, help for
documents this:
for NAME [in WORDS ... ;] do COMMANDS; done
If
'in WORDS ...;'
is not present, then'in "$@"'
is assumed.
In this case, you can used:
Page Object:
waitForURLContain(urlExpected: string, timeout: number) {
try {
const condition = browser.ExpectedConditions;
browser.wait(condition.urlContains(urlExpected), timeout);
} catch (e) {
console.error('URL not contain text.', e);
};
}
Page Test:
page.waitForURLContain('abc#/efg', 30000);
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
don't forget to add at first of <tabe></table>
<mat-form-field>
<mat-label>Filter</mat-label>
<input matInput (keyup)="applyFilter($event)" placeholder="Ex. Helium" #input>
</mat-form-field>
don't forget to add at last of <tabe></table>
<tr class="mat-row" *matNoDataRow>
<td class="mat-cell" colspan="4">
No data matching the filter "{{input.value}}"
</td>
</tr>
Be aware that it only updates the first company it found with company id 1. For multiple
(from c in listOfCompany where c.id == 1 select c).First().Name = "Whatever Name";
For Multiple updates
from c in listOfCompany where c.id == 1 select c => {c.Name = "Whatever Name"; return c;}
PID is the process ID - not the port number. You need to look for an entry with ":8080" at the end of the address/port part (the second column). Then you can look at the PID and use Task Manager to work out which process is involved... or run netstat -abn
which will show the process names (but must be run under an administrator account).
Having said that, I would expect the find "8080"
to find it...
Another thing to do is just visit http://localhost:8080
- on that port, chances are it's a web server of some description.
Maybe because you have a tag like a parent of the tag. That why you have to click two time the images.
For me the solution is this: http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_lightbulb
I believe you want to set the Content
property. This has more information on what is available to a label.
flask.Flask.run
accepts additional keyword arguments (**options
) that it forwards to werkzeug.serving.run_simple
- two of those arguments are threaded
(a boolean) and processes
(which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).
threaded
defaults to True
as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True
to enable this behaviour.
For example, you can do
if __name__ == '__main__':
app.run(threaded=True)
to handle multiple clients using threads in a way compatible with old Flask versions, or
if __name__ == '__main__':
app.run(threaded=False, processes=3)
to tell Werkzeug to spawn three processes to handle incoming requests, or just
if __name__ == '__main__':
app.run()
to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.
That being said, Werkzeug's serving.run_simple
wraps the standard library's wsgiref
package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).
The following code creates a control which you will be able to use like a normal TextBox however it will only take a positive double as an input:
In the XAML you'll be able to use this control like so:
<local:UnsignedDoubleBox/>
In the C# code add the following inside the current namespace:
public class UnsignedDoubleBox : TextBox
{
public UnsignedDoubleBox()
{
this.PreviewTextInput += defaultPreviewTextInput;
DataObject.AddPastingHandler(this, defaultTextBoxPasting);
}
private bool IsTextAllowed(TextBox textBox, String text)
{
//source: https://stackoverflow.com/questions/23397195/in-wpf-does-previewtextinput-always-give-a-single-character-only#comment89374810_23406386
String newText = textBox.Text.Insert(textBox.CaretIndex, text);
double res;
return double.TryParse(newText, out res) && res >= 0;
}
//source: https://stackoverflow.com/a/1268648/13093413
private void defaultTextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String text = (String)e.DataObject.GetData(typeof(String));
if (!IsTextAllowed((TextBox)sender, text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
private void defaultPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (IsTextAllowed((TextBox)sender, e.Text))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
}
Based on @MaBi 's answer, I made this:
trait ClassShortNameTrait
{
public static function getClassShortName()
{
if ($pos = strrchr(static::class, '\\')) {
return substr($pos, 1);
} else {
return static::class;
}
}
}
Which you may use like that:
namespace Foo\Bar\Baz;
class A
{
use ClassShortNameTrait;
}
A::class
returns Foo\Bar\Baz\A
, but A::getClassShortName()
returns A
.
Works for PHP >= 5.5.
I can't think of another way to compare values, but if you use the element of the set as the key, you can set the value to anything other than nil. Then you get fast lookups without having to search the entire table.
database_password: password
would between quotes: " or '.
like so:
database_password: "password"
In your styles.xml, modify style "AppTheme" like
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>
// Work on POSIX and Windows
var fs = require("fs");
var stdinBuffer = fs.readFileSync(0); // STDIN_FILENO = 0
console.log(stdinBuffer.toString());
This is a bit of going around the problem, but I have written a function that basically deals with the extra columns:
def merge_fix_cols(df_company,df_product,uniqueID):
df_merged = pd.merge(df_company,
df_product,
how='left',left_on=uniqueID,right_on=uniqueID)
for col in df_merged:
if col.endswith('_x'):
df_merged.rename(columns = lambda col:col.rstrip('_x'),inplace=True)
elif col.endswith('_y'):
to_drop = [col for col in df_merged if col.endswith('_y')]
df_merged.drop(to_drop,axis=1,inplace=True)
else:
pass
return df_merged
Seems to work well with my merges!
I think you need this ..
Dim n as Integer
For n = 5 to 17
msgbox cells(n,3) '--> sched waste
msgbox cells(n,4) '--> type of treatm
msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
msgbox cells(n,6) '--> email col
Next
Both of the examples are in VB.NET.
Debug path:
TextBox1.Text = My.Application.Info.DirectoryPath
EXE path:
TextBox2.Text = IO.Path.GetFullPath(Application.ExecutablePath)
Tested In Angular 7.0.0
Step 1 - Install the required dependencies
npm install bootstrap (if you want specific version please specify the version no.)
npm install popper.js (if you want specific version please specify the version no.)
npm install jquery
Versions I have tried:
"bootstrap": "^4.1.3",
"popper.js": "^1.14.5",
"jquery": "^3.3.1",
Step 2 : Specify the libraries in below orderin angular.json. In latest angular , the config file name is angular.json not angular-cli.json
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/client",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.css",
"src/styles.scss"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
]
},
If you prefer an Integer[]
instead array of an int[]
array:
Integer[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
Integer[] result = Stream.of(parts).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
int[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
int[] result = Stream.of(parts).mapToInt(Integer::parseInt).toArray()
This works for Java 8 and higher.
Is there are more correct way?
Yes, there is.
LocalDate.now(
ZoneId.of( "America/Montreal" )
).atStartOfDay(
ZoneId.of( "America/Montreal" )
)
Java 8 and later now has the new java.time framework built-in. See Tutorial. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
Some examples follow, using java.time. Note how they specify a time zone. If omitted, your JVM’s current default time zone. That default can vary, even changing at any moment during runtime, so I suggest you specify a time zone explicitly rather than rely implicitly on the default.
Here is an example of date-only, without time-of-day nor time zone.
ZoneId zonedId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zonedId );
System.out.println( "today : " + today );
today : 2015-10-19
Here is an example of getting current date-time.
ZoneId zonedId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zonedId );
System.out.println( "zdt : " + zdt );
When run:
zdt : 2015-10-19T18:07:02.910-04:00[America/Montreal]
The Question asks for the date-time where the time is set to zero. This assumes the first moment of the day is always the time 00:00:00.0
but that is not always the case. Daylight Saving Time (DST) and perhaps other anomalies mean the day may begin at a different time such as 01:00.0
.
Fortunately, java.time has a facility to determine the first moment of a day appropriate to a particular time zone, LocalDate::atStartOfDay
. Let's see some code using the LocalDate
named today
and the ZoneId
named zoneId
from code above.
ZonedDateTime todayStart = today.atStartOfDay( zoneId );
zdt : 2015-10-19T00:00:00-04:00[America/Montreal]
If you must have a java.util.Date for use with classes not yet updated to work with the java.time types, convert. Call the java.util.Date.from( Instant instant )
method.
java.util.Date date = java.util.Date.from( zdt.toInstant() );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
sudo apt install gcc
It works for PyCharm on Ubuntu 20.10.
A short RegEx: ^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$
Example
const isValidIp = value => (/^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$/.test(value) ? true : false);_x000D_
_x000D_
_x000D_
// valid_x000D_
console.log("isValidIp('0.0.0.0') ? ", isValidIp('0.0.0.0'));_x000D_
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));_x000D_
console.log("isValidIp('192.168.0.1') ? ", isValidIp('192.168.0.1'));_x000D_
console.log("isValidIp('110.234.52.124' ? ", isValidIp('110.234.52.124'));_x000D_
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));_x000D_
console.log("isValidIp('115.42.150.38') ? ", isValidIp('115.42.150.38'));_x000D_
console.log("isValidIp('115.42.150.50') ? ", isValidIp('115.42.150.50'));_x000D_
_x000D_
// Invalid_x000D_
console.log("isValidIp('210.110') ? ", isValidIp('210.110'));_x000D_
console.log("isValidIp('255') ? ", isValidIp('255'));_x000D_
console.log("isValidIp('y.y.y.y' ? ", isValidIp('y.y.y.y'));_x000D_
console.log(" isValidIp('255.0.0.y') ? ", isValidIp('255.0.0.y'));_x000D_
console.log("isValidIp('666.10.10.20') ? ", isValidIp('666.10.10.20'));_x000D_
console.log("isValidIp('4444.11.11.11') ? ", isValidIp('4444.11.11.11'));_x000D_
console.log("isValidIp('33.3333.33.3') ? ", isValidIp('33.3333.33.3'));
_x000D_
If your project is Maven-based you can run all test-methods from test-class CustomTest which belongs to module 'my-module' using next command:
mvn clean test -pl :my-module -Dtest=CustomTest
Or run only 1 test-method myMethod from test-class CustomTest using next command:
mvn clean test -pl :my-module -Dtest=CustomTest#myMethod
For this ability you need Maven Surefire Plugin v.2.7.3+ and Junit 4. More details is here: http://maven.apache.org/surefire/maven-surefire-plugin/examples/single-test.html
Use this in your RelativeLayout
android:gravity="center_vertical"
Ansible uses YAML syntax in its playbooks. YAML has a number of block operators:
The >
is a folding block operator. That is, it joins multiple lines together by spaces. The following syntax:
key: >
This text
has multiple
lines
Would assign the value This text has multiple lines\n
to key
.
The |
character is a literal block operator. This is probably what you want for multi-line shell scripts. The following syntax:
key: |
This text
has multiple
lines
Would assign the value This text\nhas multiple\nlines\n
to key
.
You can use this for multiline shell scripts like this:
- name: iterate user groups
shell: |
groupmod -o -g {{ item['guid'] }} {{ item['username'] }}
do_some_stuff_here
and_some_other_stuff
with_items: "{{ users }}"
There is one caveat: Ansible does some janky manipulation of arguments to the shell
command, so while the above will generally work as expected, the following won't:
- shell: |
cat <<EOF
This is a test.
EOF
Ansible will actually render that text with leading spaces, which means the shell will never find the string EOF
at the beginning of a line. You can avoid Ansible's unhelpful heuristics by using the cmd
parameter like this:
- shell:
cmd: |
cat <<EOF
This is a test.
EOF
run cmd
drag and drop Aspnet_regiis.exe
into the command prompt from:
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\
type -i
(for example Aspnet_regiis.exe -i
)
hit enter
Good luck!
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
You can use the following code to get last cell.
UITableViewCell *cell = [tableView cellForRowAtIndexPath:lastIndexPath];
Now this may include more than you need (and may not even work for command line applications in a non-graphical environment, I don't know), but there is nw.js. It's Blink (i.e. Chromium/Webkit) + io.js (i.e. Node.js).
You can use node-webkit-builder to build native executable binaries for Linux, OS X and Windows.
If you want a GUI, that's a huge plus. You can build one with web technologies.
If you don't, specify "node-main"
in the package.json
(and probably "window": {"show": false}
although maybe it works to just have a node-main
and not a main
)
I haven't tried to use it in exactly this way, just throwing it out there as a possibility. I can say it's certainly not an ideal solution for non-graphical Node.js applications.
To check for null values you can use is_null() as is demonstrated below.
if (is_null($value)) {
$value = "MY TEXT"; //define to suit
}
SELECT *
FROM ...
WHERE EXISTS(SELECT 1
FROM sys.columns c
WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
AND c.name = 'ModifiedByUser'
)
I would simplify the most voted answer to:
BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(n, b):
return "0" if not n else to_base(n//b, b).lstrip("0") + BS[n%b]
With the same advice for RuntimeError: maximum recursion depth exceeded in cmp
on very large integers and negative numbers. (You could usesys.setrecursionlimit(new_limit)
)
To avoid recursion problems:
BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(s, b):
res = ""
while s:
res+=BS[s%b]
s//= b
return res[::-1] or "0"
"NUL" is not 0, but refers to the ASCII NUL character. At least, that's how I've seen it used. The null pointer is often defined as 0, but this depends on the environment you are running in, and the specification of whatever operating system or language you are using.
In ANSI C, the null pointer is specified as the integer value 0. So any world where that's not true is not ANSI C compliant.
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
"final" guarantees that a variable must be initialized before end of object initializer code. Likewise "static final" guarantees that a variable will be initialized by the end of class initialization code. Omitting the "static" from your initialization code turns it into object initialization code; thus your variable no longer satisfies its guarantees.
I also just changed the "Start in" setting of the shortcut icon to: %HOMEDRIVE%/xampp/htdocs/
I just had to close SMSS and reopen it. I tried Refresh Local Cache and that didn't work.
For broken consoles like cmd.exe
and HTML output you can always use:
my_unicode_string.encode('ascii','xmlcharrefreplace')
This will preserve all the non-ascii chars while making them printable in pure ASCII and in HTML.
WARNING: If you use this in production code to avoid errors then most likely there is something wrong in your code. The only valid use case for this is printing to a non-unicode console or easy conversion to HTML entities in an HTML context.
And finally, if you are on windows and use cmd.exe then you can type chcp 65001
to enable utf-8 output (works with Lucida Console font). You might need to add myUnicodeString.encode('utf8')
.
Adding to answer by @Sasxa,
In Injectables
you can use class
normally that is putting initial code in constructor
instead of using ngOnInit()
, it works fine.
I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.
CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data
SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid;
from your question I assume that you already have your data in hdfs.
So you don't need to LOAD DATA
, which moves the files to the default hive location /user/hive/warehouse
. You can simply define the table using the external
keyword, which leaves the files in place, but creates the table definition in the hive metastore. See here:
Create Table DDL
eg.:
create external table table_name (
id int,
myfields string
)
location '/my/location/in/hdfs';
Please note that the format you use might differ from the default (as mentioned by JigneshRawal in the comments). You can use your own delimiter, for example when using Sqoop:
row format delimited fields terminated by ','
Change your black and white IDs to classes instead (duplicate IDs are invalid), add 2 buttons with the proper IDs, and do this:
var rows = $('table.someclass tr');
$('#showBlackButton').click(function() {
var black = rows.filter('.black').show();
rows.not( black ).hide();
});
$('#showWhiteButton').click(function() {
var white = rows.filter('.white').show();
rows.not( white ).hide();
});
$('#showAll').click(function() {
rows.show();
});
<button id="showBlackButton">show black</button>
<button id="showWhiteButton">show white</button>
<button id="showAll">show all</button>
<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
<caption>bla bla bla</caption>
<thead>
<tr class="black">
...
</tr>
</thead>
<tbody>
<tr class="white">
...
</tr>
<tr class="black">
...
</tr>
</tbody>
</table>
It uses the filter()
[docs] method to filter the rows with the black
or white
class (depending on the button).
Then it uses the not()
[docs] method to do the opposite filter, excluding the black
or white
rows that were previously found.
EDIT: You could also pass a selector to .not()
instead of the previously found set. It may perform better that way:
rows.not( `.black` ).hide();
// ...
rows.not( `.white` ).hide();
...or better yet, just keep a cached set of both right from the start:
var rows = $('table.someclass tr');
var black = rows.filter('.black');
var white = rows.filter('.white');
$('#showBlackButton').click(function() {
black.show();
white.hide();
});
$('#showWhiteButton').click(function() {
white.show();
black.hide();
});
For file types, where the same file can't be opened in a vertical tab group (for example .vb files) you can
If you save to disk in one instance though, you'll have to reload the file when you switch to the other. Also if you make edits in both instances, you'll have to resolve on the second save. Visual Studio prompts you in both cases with various options. You'll simplify your life a bit if you edit in only the one instance.
You must do the following command:
sort -n -k1 filename
That should do it :)
You could also use the <figure>
element to link a heading to your list like this:
<figure>
<figcaption>My favorite fruits</figcaption>
<ul>
<li>Banana</li>
<li>Orange</li>
<li>Chocolate</li>
</ul>
</figure>
Source: https://www.w3.org/TR/2017/WD-html53-20171214/single-page.html#the-li-element (Example 162)
From something that is ContainerAware (like a controller):
$request = $this->container->get('request');
$routeName = $request->get('_route');
Just thought I'd add that you can do this in Chrome as well:
Ctrl + Shift + I (Developer Tools) > Sources> Event Listener Breakpoints (on the right).
You can also view all events that have already been attached by simply right clicking on the element and then browsing its properties (the panel on the right).
For example:
Not sure if it's quite as powerful as the firebug option, but has been enough for most of my stuff.
Another option that is a bit different but surprisingly awesome is Visual Event: http://www.sprymedia.co.uk/article/Visual+Event+2
It highlights all of the elements on a page that have been bound and has popovers showing the functions that are called. Pretty nifty for a bookmark! There's a Chrome plugin as well if that's more your thing - not sure about other browsers.
AnonymousAndrew has also pointed out monitorEvents(window);
here
You can do this for webkit:
#text2::-webkit-input-placeholder::before {
color:#666;
content:"Line 1\A Line 2\A Line 3\A";
}
Update July 2017:
From ADT Plugin page, the question must be unasked:
The Eclipse ADT plugin is no longer supported, as per this announcement in June 2015.
The Eclipse ADT plugin has many known bugs and potential security bugs that will not be fixed.
You should immediately switch to use Android Studio, the official IDE for Android. For help transitioning your projects, read Migrate to Android Studio.
It is indeed
language: {
url: '//URL_TO_CDN'
}
The problem is not all of the DataTables (As of this writing) are valid JSON. The Traditional Chinese file for instance is one of them.
To get around this I wrote the following code in JavaScript:
var dataTableLanguages = {
'es': '//cdn.datatables.net/plug-ins/1.10.21/i18n/Spanish.json',
'fr': '//cdn.datatables.net/plug-ins/1.10.21/i18n/French.json',
'ar': '//cdn.datatables.net/plug-ins/1.10.21/i18n/Arabic.json',
'zh-TW': {
"processing": "???...",
"loadingRecords": "???...",
"lengthMenu": "?? _MENU_ ???",
"zeroRecords": "???????",
"info": "??? _START_ ? _END_ ???,? _TOTAL_ ?",
"infoEmpty": "??? 0 ? 0 ???,? 0 ?",
"infoFiltered": "(? _MAX_ ??????)",
"infoPostFix": "",
"search": "??:",
"paginate": {
"first": "???",
"previous": "???",
"next": "???",
"last": "????"
},
"aria": {
"sortAscending": ": ????",
"sortDescending": ": ????"
}
}
};
var language = dataTableLanguages[$('html').attr('lang')];
var opts = {...};
if (language) {
if (typeof language === 'string') {
opts.language = {
url: language
};
} else {
opts.language = language;
}
}
Now use the opts as option object for data table like
$('#list-table').DataTable(opts)
I use:
Dim drivelet As String = Application.StartupPath.ToString
If Directory.Exists(drivelet(0) & ":\Program Files (x86)") Then
MsgBox("64bit")
Else
MsgBox("32bit")
End if
This gets the path where your application is launched in case you have it installed in various places on the computer. Also, you could just do the general C:\
path since 99.9% of computers out there have Windows installed in C:\
.
I had the same question and I finally found the answer:
You need to handle BOTH the SelectionChanged event and the DropDownClosed like this:
In XAML:
<ComboBox Name="cmbSelect" SelectionChanged="ComboBox_SelectionChanged" DropDownClosed="ComboBox_DropDownClosed">
<ComboBoxItem>1</ComboBoxItem>
<ComboBoxItem>2</ComboBoxItem>
<ComboBoxItem>3</ComboBoxItem>
</ComboBox>
In C#:
private bool handle = true;
private void ComboBox_DropDownClosed(object sender, EventArgs e) {
if(handle)Handle();
handle = true;
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
ComboBox cmb = sender as ComboBox;
handle = !cmb.IsDropDownOpen;
Handle();
}
private void Handle() {
switch (cmbSelect.SelectedItem.ToString().Split(new string[] { ": " }, StringSplitOptions.None).Last())
{
case "1":
//Handle for the first combobox
break;
case "2":
//Handle for the second combobox
break;
case "3":
//Handle for the third combobox
break;
}
}
As of Node.js 14.3.0 the top-level await is supported.
Required flag: --experimental-top-level-await
.
Further details: https://v8.dev/features/top-level-await
I had problem with caching my css files. Setting headers in PHP didn't help me (perhaps because the headers would need to be set in the stylesheet file instead of the page linking to it?).
I found the solution on this page: https://css-tricks.com/can-we-prevent-css-caching/
The solution:
Append timestamp as the query part of the URI for the linked file.
(Can be used for css, js, images etc.)
For development:
<link rel="stylesheet" href="style.css?<?php echo date('Y-m-d_H:i:s'); ?>">
For production (where caching is mostly a good thing):
<link rel="stylesheet" type="text/css" href="style.css?version=3.2">
(and rewrite manually when it is required)
Or combination of these two:
<?php
define( "DEBUGGING", true ); // or false in production enviroment
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo (DEBUGGING) ? date('_Y-m-d_H:i:s') : ""; ?>">
EDIT:
Or prettier combination of those two:
<?php
// Init
define( "DEBUGGING", true ); // or false in production enviroment
// Functions
function get_cache_prevent_string( $always = false ) {
return (DEBUGGING || $always) ? date('_Y-m-d_H:i:s') : "";
}
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo get_cache_prevent_string(); ?>">
I had this problem - I eventually worked out that the reason was that I'd included \
characters in the string. If you have any of these, "escape" them with \\
and it should work fine.
It worked for me after I set up a user with internet access in the Windows service.
In my code:
HttpClientHandler handler = new HttpClientHandler();
handler.Proxy = System.Net.WebRequest.DefaultWebProxy;
handler.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
.....
HttpClient httpClient = new HttpClient(handler)
....
Try using
window.parent.window.location.href = 'http://google.com'
I got same problem, I tried all above, noting solved my problem. Luckely, I solved the problem this way:
echo $SHELL
Output
/bin/zsh
OR
/bin/bash
If it showing "bash" in output. You have to add env properties in .bashrc file (.bash_profile i did not tried, you can try) or else
It is showing 'zsh' in output. You have to add env properties in .zshrc file, if not exist already you create one no issue.
You have to put your code in the callback function you supply to setTimeout
:
function stateChange(newState) {
setTimeout(function () {
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}, 5000);
}
Any other code will execute immediately.
You can change the index as explained already using set_index
.
You don't need to manually swap rows with columns, there is a transpose (data.T
) method in pandas that does it for you:
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
['ABERFELDIE', 534000, 600000]],
columns=['Locality', 2005, 2006])
> newdf = df.set_index('Locality').T
> newdf
Locality ABBOTSFORD ABERFELDIE
2005 427000 534000
2006 448000 600000
then you can fetch the dataframe column values and transform them to a list:
> newdf['ABBOTSFORD'].values.tolist()
[427000, 448000]
var distinctRows = (from DataRow dRow in dtInventory.Rows
select dRow["column_name"] ).Distinct();
var distinctRows = (from DataRow dRow in dtInventory.Rows
select dRow["col1"], dRow["col2"].. ).Distinct();
You need to install the Visual C++ libraries: http://www.microsoft.com/en-us/download/details.aspx?id=30679
This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples How to make a class JSON serializable Also, try this
import json
class A(unicode):
def __str__(self):
return 'a'
def __unicode__(self):
return u'a'
def __repr__(self):
return 'a'
a = A()
json.dumps(a)
produces
'""'
and not
'"a"'
as would be expected.
EDIT: answering mchicago's comment:
unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json
module uses re
for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:
b = A('b')
print b
produces
'a'
while
json.dumps({'b': b})
produces
{"b": "b"}
so you see that the internal representation is used by some native libraries, probably for performance reasons.
See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/
I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class MyTable(Base):
__tablename__ = 'MyTable'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
some_col = Column(String(500))
def __init__(self, some_col):
self.some_col = some_col
engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
for class_instance in session.query(MyTable).all():
print(vars(class_instance))
session.close()
For simplicity, why not create the backup table from the select statement?
CREATE TABLE t1_backup AS SELECT a, b FROM t1;
DROP TABLE t1;
ALTER TABLE t1_backup RENAME TO t1;
SELECT * FROM [server].[database].[schema].[table]
This works for me. SSMS intellisense may still underline this as a syntax error, but it should work if your linked server is configured and your query is otherwise correct.
$(window).scroll(function() {
$('.logo_container, .slogan').css({
"opacity" : ".1",
"transition" : "opacity .8s ease-in-out"
});
});
Check the fiddle: http://jsfiddle.net/2k3hfwo0/2/
I think there's a more elegant way to solve the problem: send the stdout/stderr to syslog with an identifier and instruct your syslog manager to split its output by program name.
Use the following properties in your systemd service unit file:
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=<your program identifier> # without any quote
Then, assuming your distribution is using rsyslog to manage syslogs, create a file in /etc/rsyslog.d/<new_file>.conf
with the following content:
if $programname == '<your program identifier>' then /path/to/log/file.log
& stop
Now make the log file writable by syslog:
# ls -alth /var/log/syslog
-rw-r----- 1 syslog adm 439K Mar 5 19:35 /var/log/syslog
# chown syslog:adm /path/to/log/file.log
Restart rsyslog (sudo systemctl restart rsyslog
) and enjoy! Your program stdout/stderr will still be available through journalctl (sudo journalctl -u <your program identifier>
) but they will also be available in your file of choice.
The best option would be to use Windows integrated authentication as it is more secure than sql authentication. Create a new windows user in sql server with necessary permissions and change IIS user in the application pool security settings.
Make the file accessible to the Authenticated Users group. Right click your virtual directory and give the group read/write access to Authenticated Users.
I faced issue on windows 10 machine.
With @Query , we can use pagination as well where you need to pass object of Pageable class at end of JPA method
For example:
Pageable pageableRequest = new PageRequest(page, size, Sort.Direction.DESC, rollNo);
Where,
page = index of page (index start from zero)
size = No. of records
Sort.Direction = Sorting as per rollNo
rollNo = Field in User class
UserRepository repo
repo.findByFirstname("John", pageableRequest);
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM USER WHERE FIRSTNAME = :firstname)
Page<User> findByLastname(@Param("firstname") String firstname, Pageable pageable);
}
Plain old JavaScript will suffice - jQuery is not necessary for such a simple task:
var myString = "data-123";
var myNewString = myString.replace("data-", "");
See: .replace()
docs on MDN for additional information and usage.
Here is an alternative way:
select * from tbl where col like 'ABC%'
union
select * from tbl where col like 'XYZ%'
union
select * from tbl where col like 'PQR%';
Here is the test code to verify:
create table tbl (col varchar(255));
insert into tbl (col) values ('ABCDEFG'), ('HIJKLMNO'), ('PQRSTUVW'), ('XYZ');
select * from tbl where col like 'ABC%'
union
select * from tbl where col like 'XYZ%'
union
select * from tbl where col like 'PQR%';
+----------+
| col |
+----------+
| ABCDEFG |
| XYZ |
| PQRSTUVW |
+----------+
3 rows in set (0.00 sec)
You can simply kill docker cli process by sending SEGKILL. If you started the container with
docker run -it some/container
You can get it's pid
ps -aux | grep docker
user 1234 0.3 0.6 1357948 54684 pts/2 Sl+ 15:09 0:00 docker run -it some/container
let's say it's 1234, you can "detach" it with
kill -9 1234
It's somewhat of a hack but it works!
This might have changed since the original answer was written, but it looks like you can now use the Models populate function to do this without having to execute an extra findOne. See: http://mongoosejs.com/docs/api.html#model_Model.populate. You'd want to use this inside the save handler just like the findOne is.
It targets some specified feature to execute some other codes...
For example:
@media all and (max-width: 600px) {
.navigation {
-webkit-flex-flow: column wrap;
flex-flow: column wrap;
padding: 0;
}
the above snippet say if the device that run this program have screen with 600px or less than 600px width, in this case our program must execute this part .
Personally, I think the concatenation is the better solution. The generic implementation would be
entity shifter is
generic (
REGSIZE : integer := 8);
port(
clk : in str_logic;
Data_in : in std_logic;
Data_out : out std_logic(REGSIZE-1 downto 0);
end shifter ;
architecture bhv of shifter is
signal shift_reg : std_logic_vector(REGSIZE-1 downto 0) := (others<='0');
begin
process (clk) begin
if rising_edge(clk) then
shift_reg <= shift_reg(REGSIZE-2 downto 0) & Data_in;
end if;
end process;
end bhv;
Data_out <= shift_reg;
Both will implement as shift registers. If you find yourself in need of more shift registers than you are willing to spend resources on (EG dividing 1000 numbers by 4) you might consider using a BRAM to store the values and a single shift register to contain "indices" that result in the correct shift of all the numbers.
Create a new Swift file within your project, name it Reachability.swift
. Cut & paste the following code into it to create your class.
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0))
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = flags == .Reachable
let needsConnection = flags == .ConnectionRequired
return isReachable && !needsConnection
}
}
You can check internet connection anywhere in your project using this code:
if Reachability.isConnectedToNetwork() {
println("Internet connection OK")
} else {
println("Internet connection FAILED")
}
If the user is not connected to the internet, you may want to show them an alert dialog to notify them.
if Reachability.isConnectedToNetwork() {
println("Internet connection OK")
} else {
println("Internet connection FAILED")
var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
Explanation:
We are making a reusable public class and a method which can be used anywhere in the project to check internet connectivity. We require adding Foundation and System Configuration frameworks.
In the public class Reachability, the method isConnectedToNetwork() -> Bool { }
will return a bool value about internet connectivity. We use a if loop to perform required actions on case. I hope this is enough. Cheers!
You must use .clearAnimation(); method in UI thread:
runOnUiThread(new Runnable() {
@Override
public void run() {
v.clearAnimation();
}
});
This is based on @cHao solution. I included several fixes and performance improvements. This runs roughly twice as fast the equals-ordered-copy solution. Works for any collection type. Empty collections and null are regarded as equal. Use to your advantage ;)
/**
* Returns if both {@link Collection Collections} contains the same elements, in the same quantities, regardless of order and collection type.
* <p>
* Empty collections and {@code null} are regarded as equal.
*/
public static <T> boolean haveSameElements(Collection<T> col1, Collection<T> col2) {
if (col1 == col2)
return true;
// If either list is null, return whether the other is empty
if (col1 == null)
return col2.isEmpty();
if (col2 == null)
return col1.isEmpty();
// If lengths are not equal, they can't possibly match
if (col1.size() != col2.size())
return false;
// Helper class, so we don't have to do a whole lot of autoboxing
class Count
{
// Initialize as 1, as we would increment it anyway
public int count = 1;
}
final Map<T, Count> counts = new HashMap<>();
// Count the items in col1
for (final T item : col1) {
final Count count = counts.get(item);
if (count != null)
count.count++;
else
// If the map doesn't contain the item, put a new count
counts.put(item, new Count());
}
// Subtract the count of items in col2
for (final T item : col2) {
final Count count = counts.get(item);
// If the map doesn't contain the item, or the count is already reduced to 0, the lists are unequal
if (count == null || count.count == 0)
return false;
count.count--;
}
// At this point, both collections are equal.
// Both have the same length, and for any counter to be unequal to zero, there would have to be an element in col2 which is not in col1, but this is checked in the second loop, as @holger pointed out.
return true;
}
To sign your app in release mode in Android Studio, follow these steps:
1- On the menu bar, click Build > Generate Signed APK.
2-On the Generate Signed APK Wizard window, click Create new to create a new keystore. If you already have a keystore, go to step 4.
3- On the New Key Store window, provide the required information as shown in figure Your key should be valid for at least 25 years, so you can sign app updates with the same key through the lifespan of your app.
4- On the Generate Signed APK Wizard window, select a keystore, a private key, and enter the passwords for both. Then click Next.
5- On the next window, select a destination for the signed APK and click Finish.
http://developer.android.com/tools/publishing/app-signing.html
Just to offer you a different angle -
I find it's not a good idea to maintain public variables between function calls. Any variables you need to use should be stored in Subs and Functions and passed as parameters. Once the code is done running, you shouldn't expect the VBA Project to maintain the values of any variables.
The reason for this is that there is just a huge slew of things that can inadvertently reset the VBA Project while using the workbook. When this happens, any public variables get reset to 0.
If you need a value to be stored outside of your subs and functions, I highly recommend using a hidden worksheet with named ranges for any information that needs to persist.
To change all classes for an element:
document.getElementById("ElementID").className = "CssClass";
To add an additional class to an element:
document.getElementById("ElementID").className += " CssClass";
To check if a class is already applied to an element:
if ( document.getElementById("ElementID").className.match(/(?:^|\s)CssClass(?!\S)/) )
With Angular 7, I got it working by using the following without using HttpParams.
import { HttpClient } from '@angular/common/http';
export class ApiClass {
constructor(private httpClient: HttpClient) {
// use it like this in other services / components etc.
this.getDataFromServer().
then(res => {
console.log('res: ', res);
});
}
getDataFromServer() {
const params = {
param1: value1,
param2: value2
}
const url = 'https://api.example.com/list'
// { params: params } is the same as { params }
// look for es6 object literal to read more
return this.httpClient.get(url, { params }).toPromise();
}
}
Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "]
with array("title" => "Welcome ")
I have faced this issue when I created a new ES2015 class where the property name was equal to the method name.
e.g.:
class Test{
constructor () {
this.test = 'test'
}
test (test) {
this.test = test
}
}
let t = new Test()
t.test('new Test')
Please note this implementation was in NodeJS 6.10.
As a workaround (if you do not want to use the boring 'setTest' method name), you could use a prefix for your 'private' properties (like _test
).
Open your Developer Tools in jsfiddle.
The way to do this in .NET Core is (at the time of writing) as follows:
public async Task<IActionResult> YourAction(YourModel model)
{
if (ModelState.IsValid)
{
return StatusCode(200);
}
return StatusCode(400);
}
The StatusCode method returns a type of StatusCodeResult which implements IActionResult and can thus be used as a return type of your action.
As a refactor, you could improve readability by using a cast of the HTTP status codes enum like:
return StatusCode((int)HttpStatusCode.OK);
Furthermore, you could also use some of the built in result types. For example:
return Ok(); // returns a 200
return BadRequest(ModelState); // returns a 400 with the ModelState as JSON
Ref. StatusCodeResult - https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult?view=aspnetcore-2.1
try this:
$('.nav a').on('click', function(){
$('.btn-navbar').click(); //bootstrap 2.x
$('.navbar-toggle').click(); //bootstrap 3.x by Richard
$('.navbar-toggler').click(); //bootstrap 4.x
});
This is how to get the html DOM element purely with JS:
var htmlElement = document.getElementsByTagName("html")[0];
or
var htmlElement = document.querySelector("html");
And if you want to use jQuery to get attributes from it...
$(htmlElement).attr(INSERT-ATTRIBUTE-NAME);
Html by itself will not send email. You will need something that connects to a SMTP server to send an email. Hence Outlook pops up with mailto: else your form goes to the server which has a script that sends email.
Here are a lot of right answers. Just one thing:
Paste the received hash into Application → Settings → Main, not via the fast start tutorial.
Works everywhere without jquery:
var getSelectValues = function (select) {
var ret = [];
// fast but not universally supported
if (select.selectedOptions != undefined) {
for (var i=0; i < select.selectedOptions.length; i++) {
ret.push(select.selectedOptions[i].value);
}
// compatible, but can be painfully slow
} else {
for (var i=0; i < select.options.length; i++) {
if (select.options[i].selected) {
ret.push(select.options[i].value);
}
}
}
return ret;
};
I had an issue where Chrome's breakpoints weren't firing anything. When I tried to use 'debugger' in my code, I could only step through the code in the VM version of my code. My issue was that I was mapping the resources incorrectly. Re-mapping fixed my problem.
You may want to use the "xcode-select" command in terminal to switch between the different Xcode version in the installed folders.
TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.
If you are calling a Python service, the code will look like below:
this.updateTalentSupplier=function(supplierObj){
var promise = $http({
method: 'POST',
url: bbConfig.BWS+'updateTalentSupplier/',
data:supplierObj,
withCredentials: false,
contentType:'application/json',
dataType:'json'
});
return promise; //Promise is returned
}
We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.
Or use __contains__
:
sequence.__contains__(value)
Demo:
>>> l = [1, 2, 3]
>>> l.__contains__(3)
True
>>>
For those who even yet have the problem, try enabling "Build project automatically" in the Java compiler settings and see if that makes a difference as it worked for me.
Try with Kivy! kivy.org It's quite easy, multi platform and a really good documentation
From What's the Difference between WCF and Web Services?
WCF is a replacement for all earlier web service technologies from Microsoft. It also does a lot more than what is traditionally considered as "web services".
WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. Common scenarios for hosting WCF services are IIS,WAS, Self-hosting, Managed Windows Service.
The major difference is that Web Services Use
XmlSerializer
. But WCF UsesDataContractSerializer
which is better in performance as compared toXmlSerializer
.
On ubuntu most perl modules are already packaged, so installing is much faster than most other systems which have to compile.
To install Foo::Bar
at a commmand prompt for example usually you just do:
sudo apt-get install libfoo-bar-perl
Sadly not all modules follow that naming convention.
you can use the below css styles for all browsers except Firefox 30
select {
background: url(dropdown_arw.png) no-repeat right center;
appearance: none;
-moz-appearance: none;
-webkit-appearance: none;
width: 90px;
text-indent: 0.01px;
text-overflow: "";
}
demo page - http://kvijayanand.in/jquery-plugin/test.html
Updated
here is solution for Firefox 30. little trick for custom select elements in firefox :-moz-any() css pseudo class.
While working with selected cells as shown by @tbur can be useful, it's also not the only option available.
You can use Range() like so:
If Worksheets("Sheet1").Range("A1").MergeCells Then
Do something
Else
Do something else
End If
Or:
If Worksheets("Sheet1").Range("A1:C1").MergeCells Then
Do something
Else
Do something else
End If
Alternately, you can use Cells():
If Worksheets("Sheet1").Cells(1, 1).MergeCells Then
Do something
Else
Do something else
End If
d = {}
will create a new instance for d
but all other references will still point to the old contents.
d.clear()
will reset the contents, but all references to the same instance will still be correct.
If you are using ajax, it is possible to add the options xhrFields: { responseType: 'blob' }
:
$.ajax({
url: 'yourURL',
type: 'POST',
data: yourData,
xhrFields: { responseType: 'blob' },
success: function (data, textStatus, jqXHR) {
let src = window.URL.createObjectURL(data);
}
});
If your class extends Serializable
, you can write and read objects through a ByteArrayOutputStream
, that's what I usually do.
my_function.func_name
There are also other fun properties of functions. Type dir(func_name)
to list them. func_name.func_code.co_code
is the compiled function, stored as a string.
import dis
dis.dis(my_function)
will display the code in almost human readable format. :)
The same problem and I solved putting the table between the code
<div class = "table-responsive"> </ div>
Another easy way to get this:
Person myPet = GetPersonFromDatabase();
// check for myPet == null... AND for myPet.PetType == null
if ( myPet.PetType == "cat" ) <--- fall down go boom!
DateTime
is not standard nullable type. If you want assign null to DateTime
type of variable, you have to use DateTime?
type which supports null value.
If you only want test your variable to be set (e.g. variable holds other than default value), you can use keyword "default" like in following code:
if (dateTimeVariable == default(DateTime))
{
//do work for dateTimeVariable == null situation
}
The first answer is correct, but if you have a large amount of data (in my project I had 8.000 rows * 8 columns) is tragically slow.... Having a string that becomes that large in c# is why that solution is forbiden
Instead using a large string I used a string array that I join at the end in order to return the string of the html table. Moreover, I used a linq expression ((from o in row.ItemArray select o.ToString()).ToArray()) in order to join each DataRow of the table, instead of looping again, in order to save as much time as possible.
This is my sample code:
private string MakeHtmlTable(DataTable data)
{
string[] table = new string[data.Rows.Count] ;
long counter = 1;
foreach (DataRow row in data.Rows)
{
table[counter-1] = "<tr><td>" + String.Join("</td><td>", (from o in row.ItemArray select o.ToString()).ToArray()) + "</td></tr>";
counter+=1;
}
return "</br><table>" + String.Join("", table) + "</table>";
}
It happens that /etc/hosts
file doesn't support wild card entries.
You'll have to use other services like dnsmasq. To enable it in dnsmasq, just edit dnsmasq.conf
and add the following line:
address=/example.com/127.0.0.1
What about the css opacity
attribute? 0
to 1
values.
But then you probably need to use a more explicit dom element than "font". For instance:
<html><body><span style=\"opacity: 0.5;\"><font color=\"black\" face=\"arial\" size=\"4\">THIS IS MY TEXT</font></span></body></html>
As an additional information I would of course suggest you use CSS declarations outside of your html elements, but as well try to use the font css style instead of the font html tag.
For cross browser css3 styles generator, have a look at http://css3please.com/
You can go with @greenAfrican example, if it's possible for you to rewrite your function. But if you don't want to rewrite your function, you can wrap it into anonymous function inside apply, like this:
>>> def fxy(x, y):
... return x * y
>>> df['newcolumn'] = df.apply(lambda x: fxy(x['A'], x['B']), axis=1)
>>> df
A B newcolumn
0 10 20 200
1 20 30 600
2 30 10 300
This will also work
$(this).parent().parent().find('td').text()
I think the current answers are neglecting to highlight the actual important and significant differences and what that means for the intended usage. While they might both work in certain situations because the implementer built in support for both, they have different usage scenarios. Both can annotate properties and methods but here are some important differences:
DisplayAttribute
System.ComponentModel.DataAnnotations
namespace in the System.ComponentModel.DataAnnotations.dll
assemblyDescription
or ShortName
DisplayNameAttribute
System.ComponentModel
namespace in System.dll
The assembly and namespace speaks to the intended usage and localization support is the big kicker. DisplayNameAttribute
has been around since .NET 2 and seems to have been intended more for naming of developer components and properties in the legacy property grid, not so much for things visible to end users that may need localization and such.
DisplayAttribute
was introduced later in .NET 4 and seems to be designed specifically for labeling members of data classes that will be end-user visible, so it is more suitable for DTOs, entities, and other things of that sort. I find it rather unfortunate that they limited it so it can't be used on classes though.
EDIT: Looks like latest .NET Core source allows DisplayAttribute
to be used on classes now as well.
Not to belabor the point, but if you are working in a Dockerfile
, you would solve this particular issue with Composer by installing the unzip
utility. Below is an example using the official PHP image to install unzip
and the zip
PHP extension for good measure.
FROM php:7.4-apache
# Install Composer
COPY --from=composer /usr/bin/composer /usr/bin/composer
# Install unzip utility and libs needed by zip PHP extension
RUN apt-get update && apt-get install -y \
zlib1g-dev \
libzip-dev \
unzip
RUN docker-php-ext-install zip
This is a helpful GitHub issue where the above is lovingly lifted from.
It checks whether the page has been called through POST (as opposed to GET, HEAD, etc). When you type a URL in the menu bar, the page is called through GET. However, when you submit a form with method="post" the action page is called with POST.
What you need is a quadrangle instead of a rotated rectangle.
RotatedRect
will give you incorrect results. Also you will need a perspective projection.
Basicly what must been done is:
I implemented a class Quadrangle
which takes care of contour to quadrangle conversion and will also transform it over the right perspective.
See a working implementation here: Java OpenCV deskewing a contour
Classic technique (escape metacharacters):
if [ \( "$g" -eq 1 -a "$c" = "123" \) -o \( "$g" -eq 2 -a "$c" = "456" \) ]
then echo abc
else echo efg
fi
I've enclosed the references to $g
in double quotes; that's good practice, in general. Strictly, the parentheses aren't needed because the precedence of -a
and -o
makes it correct even without them.
Note that the -a
and -o
operators are part of the POSIX specification for test
, aka [
, mainly for backwards compatibility (since they were a part of test
in 7th Edition UNIX, for example), but they are explicitly marked as 'obsolescent' by POSIX. Bash (see conditional expressions) seems to preempt the classic and POSIX meanings for -a
and -o
with its own alternative operators that take arguments.
With some care, you can use the more modern [[
operator, but be aware that the versions in Bash and Korn Shell (for example) need not be identical.
for g in 1 2 3
do
for c in 123 456 789
do
if [[ ( "$g" -eq 1 && "$c" = "123" ) || ( "$g" -eq 2 && "$c" = "456" ) ]]
then echo "g = $g; c = $c; true"
else echo "g = $g; c = $c; false"
fi
done
done
Example run, using Bash 3.2.57 on Mac OS X:
g = 1; c = 123; true
g = 1; c = 456; false
g = 1; c = 789; false
g = 2; c = 123; false
g = 2; c = 456; true
g = 2; c = 789; false
g = 3; c = 123; false
g = 3; c = 456; false
g = 3; c = 789; false
You don't need to quote the variables in [[
as you do with [
because it is not a separate command in the same way that [
is.
Isn't it a classic question?
I would have thought so. However, there is another alternative, namely:
if [ "$g" -eq 1 -a "$c" = "123" ] || [ "$g" -eq 2 -a "$c" = "456" ]
then echo abc
else echo efg
fi
Indeed, if you read the 'portable shell' guidelines for the autoconf
tool or related packages, this notation — using '||
' and '&&
' — is what they recommend. I suppose you could even go so far as:
if [ "$g" -eq 1 ] && [ "$c" = "123" ]
then echo abc
elif [ "$g" -eq 2 ] && [ "$c" = "456" ]
then echo abc
else echo efg
fi
Where the actions are as trivial as echoing, this isn't bad. When the action block to be repeated is multiple lines, the repetition is too painful and one of the earlier versions is preferable — or you need to wrap the actions into a function that is invoked in the different then
blocks.
This page provides great understanding about the constructor
and destructor
attribute implementation and the sections within within ELF that allow them to work. After digesting the information provided here, I compiled a bit of additional information and (borrowing the section example from Michael Ambrus above) created an example to illustrate the concepts and help my learning. Those results are provided below along with the example source.
As explained in this thread, the constructor
and destructor
attributes create entries in the .ctors
and .dtors
section of the object file. You can place references to functions in either section in one of three ways. (1) using either the section
attribute; (2) constructor
and destructor
attributes or (3) with an inline-assembly call (as referenced the link in Ambrus' answer).
The use of constructor
and destructor
attributes allow you to additionally assign a priority to the constructor/destructor to control its order of execution before main()
is called or after it returns. The lower the priority value given, the higher the execution priority (lower priorities execute before higher priorities before main() -- and subsequent to higher priorities after main() ). The priority values you give must be greater than100
as the compiler reserves priority values between 0-100 for implementation. Aconstructor
or destructor
specified with priority executes before a constructor
or destructor
specified without priority.
With the 'section' attribute or with inline-assembly, you can also place function references in the .init
and .fini
ELF code section that will execute before any constructor and after any destructor, respectively. Any functions called by the function reference placed in the .init
section, will execute before the function reference itself (as usual).
I have tried to illustrate each of those in the example below:
#include <stdio.h>
#include <stdlib.h>
/* test function utilizing attribute 'section' ".ctors"/".dtors"
to create constuctors/destructors without assigned priority.
(provided by Michael Ambrus in earlier answer)
*/
#define SECTION( S ) __attribute__ ((section ( S )))
void test (void) {
printf("\n\ttest() utilizing -- (.section .ctors/.dtors) w/o priority\n");
}
void (*funcptr1)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;
/* functions constructX, destructX use attributes 'constructor' and
'destructor' to create prioritized entries in the .ctors, .dtors
ELF sections, respectively.
NOTE: priorities 0-100 are reserved
*/
void construct1 () __attribute__ ((constructor (101)));
void construct2 () __attribute__ ((constructor (102)));
void destruct1 () __attribute__ ((destructor (101)));
void destruct2 () __attribute__ ((destructor (102)));
/* init_some_function() - called by elf_init()
*/
int init_some_function () {
printf ("\n init_some_function() called by elf_init()\n");
return 1;
}
/* elf_init uses inline-assembly to place itself in the ELF .init section.
*/
int elf_init (void)
{
__asm__ (".section .init \n call elf_init \n .section .text\n");
if(!init_some_function ())
{
exit (1);
}
printf ("\n elf_init() -- (.section .init)\n");
return 1;
}
/*
function definitions for constructX and destructX
*/
void construct1 () {
printf ("\n construct1() constructor -- (.section .ctors) priority 101\n");
}
void construct2 () {
printf ("\n construct2() constructor -- (.section .ctors) priority 102\n");
}
void destruct1 () {
printf ("\n destruct1() destructor -- (.section .dtors) priority 101\n\n");
}
void destruct2 () {
printf ("\n destruct2() destructor -- (.section .dtors) priority 102\n");
}
/* main makes no function call to any of the functions declared above
*/
int
main (int argc, char *argv[]) {
printf ("\n\t [ main body of program ]\n");
return 0;
}
output:
init_some_function() called by elf_init()
elf_init() -- (.section .init)
construct1() constructor -- (.section .ctors) priority 101
construct2() constructor -- (.section .ctors) priority 102
test() utilizing -- (.section .ctors/.dtors) w/o priority
test() utilizing -- (.section .ctors/.dtors) w/o priority
[ main body of program ]
test() utilizing -- (.section .ctors/.dtors) w/o priority
destruct2() destructor -- (.section .dtors) priority 102
destruct1() destructor -- (.section .dtors) priority 101
The example helped cement the constructor/destructor behavior, hopefully it will be useful to others as well.
The loop in your code is only an over-simplified example, right?
It would be better to create the PreparedStatement
only once, and re-use it over and over again in the loop.
In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement
, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.
To address the situation that you want to re-use the Java-side PreparedStatement
, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement
for the same SQL on the same connection, it will give you the same (cached) instance.
About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.
You could use the following solution:
SocketAddress sockaddr = new InetSocketAddress(ip, port);
// Create your socket
Socket socket = new Socket();
// Connect with 10 s timeout
socket.connect(sockaddr, 10000);
Hope it helps!
textarea {
width: 700px;
height: 100px;
resize: none; }
assign your required width and height for the textarea and then use. resize: none ; css property which will disable the textarea's stretchable property.
Save yourself the headache of trying to find a "built-in" solution.
There isn't a good answer, and the hugely upvoted answer in this thread is wrong.
npm install is-number
In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use +, -, or Number() to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results:
console.log(+[]); //=> 0
console.log(+''); //=> 0
console.log(+' '); //=> 0
console.log(typeof NaN); //=> 'number'
You can simply use ToArray() method of MemoryStream class, for ex-
MemoryStream ms = (MemoryStream)dataInStream;
byte[] imageBytes = ms.ToArray();
I miss an other Solution here (2021):
I use FileList
to interact with file input.
Since there is no way to create a FileList
object, I use DataTransfer
, that brings clean FilleList with it.
I reset it with:
file_input.files=new DataTransfer().files
In my case this perfectly fits, since I interact only via FileList
with my encapsulated file input element.
I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
<input id="submit_handle" type="submit" style="display: none">
<script>
function submitform() {
$('#submit_handle').click();
}
</script>
System.Net.HttpWebRequest adds the header 'HTTP header "Expect: 100-Continue"' to every request unless you explicitly ask it not to by setting this static property to false:
System.Net.ServicePointManager.Expect100Continue = false;
Some servers choke on that header and send back the 417 error you're seeing.
Give that a shot.
The answer offered by @Daniel Kamil Kozar is the correct answer - gettimeofday actually should not be used to measure the elapsed time. Use clock_gettime(CLOCK_MONOTONIC) instead.
Man Pages say - The time returned by gettimeofday() is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the system time). If you need a monotonically increasing clock, see clock_gettime(2).
The Opengroup says - Applications should use the clock_gettime() function instead of the obsolescent gettimeofday() function.
Everyone seems to love gettimeofday until they run into a case where it does not work or is not there (VxWorks) ... clock_gettime is fantastically awesome and portable.
<<
Works fine for me
See example here. http://jsfiddle.net/blowsie/c6VAy/
Make sure your jquery is inside $(document).ready
function or similar.
Also you can improve your code by using jquery data
$('#amount').data('min','1000');
<div id="amount" data-min=""></div>
Update,
A working example of your full code (pretty much) here. http://jsfiddle.net/blowsie/c6VAy/3/
Object.create(Constructor.prototype)
is the part of new Constructor
new Constructor
implementation// 1. define constructor function
function myConstructor(name, age) {
this.name = name;
this.age = age;
}
myConstructor.prototype.greet = function(){
console.log(this.name, this.age)
};
// 2. new operator implementation
let newOperatorWithConstructor = function(name, age) {
const newInstance = new Object(); // empty object
Object.setPrototypeOf(newInstance, myConstructor.prototype); // set prototype
const bindedConstructor = myConstructor.bind(newInstance); // this binding
bindedConstructor(name, age); // execute binded constructor function
return newInstance; // return instance
};
// 3. produce new instance
const instance = new myConstructor("jun", 28);
const instance2 = newOperatorWithConstructor("jun", 28);
console.log(instance);
console.log(instance2);
new Constructor
implementation contains Object.create
method newOperatorWithConstructor = function(name, age) {
const newInstance = Object.create(myConstructor.prototype); // empty object, prototype chaining
const bindedConstructor = myConstructor.bind(newInstance); // this binding
bindedConstructor(name, age); // execute binded constructor function
return newInstance; // return instance
};
console.log(newOperatorWithConstructor("jun", 28));
Some additional advice for Windows(10) users:
The correct way to open Jupyter notebook with new data limit from the Anaconda Prompt on my own Windows 10 PC is:
(base) C:\Users\mobarget\Google Drive\Jupyter Notebook>jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10
The most upvoted answer is not implementing a real slide in/out (or down/up), as:
translateY(-100%)
and then suddenly disappears, causing another glitch on the elements below it.You can implement a slide in and slide out like so:
my-component.ts
import { animate, style, transition, trigger } from '@angular/animations';
@Component({
...
animations: [
trigger('slideDownUp', [
transition(':enter', [style({ height: 0 }), animate(500)]),
transition(':leave', [animate(500, style({ height: 0 }))]),
]),
],
})
my-component.html
<div @slideDownUp *ngIf="isShowing" class="box">
I am the content of the div!
</div>
my-component.scss
.box {
overflow: hidden;
}
The easiest solution I found is to just rename the php folder version as such:
That way only two of them will be read by MAMP. Done!
A very fast implementation of the Sieve of Atkin is Dan Bernstein's primegen. This sieve is more efficient than the Sieve of Eratosthenes. His page has some benchmark information.
You have a numpy array of strings, not floats. This is what is meant by dtype('<U9')
-- a little endian encoded unicode string with up to 9 characters.
try:
return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
However, you don't need numpy here at all. You can really just do:
return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
Or if you're really set on using numpy.
return np.asarray(listOfEmb, dtype=float).mean()
You can get a useful string without having to touch the registry or reference assemblies which may or may not be loaded. mscorlib.dll and other System assemblies have AssemblyFileVersionAttribute defined, and it seems to be unique for each version of .NET, based on the reference assemblies provided with Visual Studio.
string version = (typeof(string).Assembly
.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)
.FirstOrDefault() as AssemblyFileVersionAttribute)?.Version;
Version 4.5 is a bit off, because it's marked 4.0 in that version, but 4.6 onward appear to have the minor version matching at least. Doing it this way seems like it would be more future proof than depending on some installer registry key and having to compare against a fixed set of values.
I found the reference assemblies here:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework
Where I got the following versions:
4.0 = 4.0.30319.1
4.5 = 4.0.30319.18020
4.5.1 = 4.0.30319.18402
4.5.2 = 4.0.30319.34211
4.6 = 4.6.81.0
4.6.1 = 4.6.1055.0
4.7.2 = 4.7.3062.0
4.8 = 4.8.3761.0
There are two ways to accomplish this textbox effect:
Either using the graphic user interface (GUI); or with code
Using the Graphic User Interface:
Go to: "Properties" Tab; then set the following properties:
However; the best way is to create this by code. See example below.
AutoCompleteStringCollection sourceName = new AutoCompleteStringCollection();
foreach (string name in listNames)
{
sourceName.Add(name);
}
txtName.AutoCompleteCustomSource = sourceName;
txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
If you have Bluetooth, Use twedge on windows and getblue app on android, they also have a few videos of it. It's made by TEC-IT. I've got it to work by setting the interface option to bluetooth server in TWedge and setting the output setting in getblue to Bluetooth client and selecting my computer from the Bluetooth devices list. Make sure your computer and phone is paired. Also to get the barcode as input set the action setting in TWedge to Keyboard Wedge. This will allow for you to first click the input text box on said form, then scan said product with your phone and wait a sec for the barcode number to be put into the text box. Using this method requires no php that doesn't already exist in your current form processing, just process the text box as usual and viola your phone scans bar codes, sends them to your pc via Bluetooth wirelessly, your computer inserts the barcode into whatever text field is selected in any application or website. Hope this helps.
undo git rm
git rm file # delete file & update index
git checkout HEAD file # restore file & index from HEAD
undo git rm -r
git rm -r dir # delete tracked files in dir & update index
git checkout HEAD dir # restore file & index from HEAD
undo git rm -rf
git rm -r dir # delete tracked files & delete uncommitted changes
not possible # `uncommitted changes` can not be restored.
Uncommitted changes
includes not staged changes
, staged changes but not committed
.