you can write this line into Controller
json.MaxJsonLength = 2147483644;
you can also write this line into web.config
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647">
</jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>
`
To be on the safe side, use both.
HTML
<div id='a'>
<div>
<a class='click'>abc</a>
</div>
</div>
You could use the XPATH as :
//div[@id='a']//a[@class='click']
output
<a class="click">abc</a>
That said your Python code should be as :
driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
I've wrote such a simple class:
public static class WatermarkExtension
{
public static MvcHtmlString WatermarkFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
var watermark = ModelMetadata.FromLambdaExpression(expression, html.ViewData).Watermark;
var htmlEncoded = HttpUtility.HtmlEncode(watermark);
return new MvcHtmlString(htmlEncoded);
}
}
The usage as such:
@Html.TextBoxFor(model => model.AddressSuffix, new {placeholder = Html.WatermarkFor(model => model.AddressSuffix)})
And property in a viewmodel:
[Display(ResourceType = typeof (Resources), Name = "AddressSuffixLabel", Prompt = "AddressSuffixPlaceholder")]
public string AddressSuffix
{
get { return _album.AddressSuffix; }
set { _album.AddressSuffix = value; }
}
Notice Prompt parameter. In this case I use strings from resources for localization but you can use just strings, just avoid ResourceType parameter.
Try this:
function add()
{
var sum = 0;
var inputs = document.getElementsByTagName("input");
for(i = 0; i <= inputs.length; i++)
{
if( inputs[i].name == 'qty'+i)
{
sum += parseInt(input[i].value);
}
}
console.log(sum)
}
Perform the following:
c:\windows\microsoft.net\framework\v4.0.30319\installutil.exe [your windows service path to exe]
It's important to open with administrator rights otherwise you may find errors that come up that don't make sense. If you get any, check you've opened it with admin rights first!
To open with admin rights, right click 'Command Prompt' and select 'Run as administrator'.
All appender names must be reflected in the root section.
In your case the appender name is EventLogAppender but in the <root> <appender-ref ..
section it is named as ConsoleAppender. They need to match.
You can add multiple appenders to your log config but you need to register each of them in the <root>
section.
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="EventLogAppender" />
You can also refer to the apache documentation on configuring log4net.
Replace your for loop
by this :
errorCounter = Regex.Matches(yourstring,@"[a-zA-Z]").Count;
Remember to use Regex
class, you have to using System.Text.RegularExpressions;
in your import
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
I had the same problem. Changing controlers first letter to uppercase helped.
This might be a little late, but did you try calling loadView()
?
In your component
let today: string;
ngOnInit() {
this.today = new Date().toISOString().split('T')[0];
}
and in your html file
<input name="date" [(ngModel)]="today" type="date" required>
Pure JavaScript:
var outerHTML = function(node) {
var div = document.createElement("div");
div.appendChild(node.cloneNode(true));
return div.innerHTML;
};
Add a -v flag with your git command . e.g.
git pull -v
v stands for verify .
It's also possible the problem is with a parameter or return type of the method that's reported missing, and the "missing" method per se is fine.
That's what was happening in my case, and the misleading message made it take much longer to figure out the issue. It turns out the assembly for a parameter's type had an older version in the GAC, but the older version actually had a higher version number due to a change in version numbering schemes used. Removing that older/higher version from the GAC fixed the problem.
The != operator most certainly does exist! It is an alias for the standard <>
operator.
Perhaps your fields are not actually empty strings, but instead NULL
?
To compare to NULL
you can use IS NULL
or IS NOT NULL
or the null safe equals operator <=>
.
Back in the old days of Python, to call a function with arbitrary arguments, you would use apply
:
apply(f,args,kwargs)
apply
still exists in Python2.7 though not in Python3, and is generally not used anymore. Nowadays,
f(*args,**kwargs)
is preferred. The multiprocessing.Pool
modules tries to provide a similar interface.
Pool.apply
is like Python apply
, except that the function call is performed in a separate process. Pool.apply
blocks until the function is completed.
Pool.apply_async
is also like Python's built-in apply
, except that the call returns immediately instead of waiting for the result. An AsyncResult
object is returned. You call its get()
method to retrieve the result of the function call. The get()
method blocks until the function is completed. Thus, pool.apply(func, args, kwargs)
is equivalent to pool.apply_async(func, args, kwargs).get()
.
In contrast to Pool.apply
, the Pool.apply_async
method also has a callback which, if supplied, is called when the function is complete. This can be used instead of calling get()
.
For example:
import multiprocessing as mp
import time
def foo_pool(x):
time.sleep(2)
return x*x
result_list = []
def log_result(result):
# This is called whenever foo_pool(i) returns a result.
# result_list is modified only by the main process, not the pool workers.
result_list.append(result)
def apply_async_with_callback():
pool = mp.Pool()
for i in range(10):
pool.apply_async(foo_pool, args = (i, ), callback = log_result)
pool.close()
pool.join()
print(result_list)
if __name__ == '__main__':
apply_async_with_callback()
may yield a result such as
[1, 0, 4, 9, 25, 16, 49, 36, 81, 64]
Notice, unlike pool.map
, the order of the results may not correspond to the order in which the pool.apply_async
calls were made.
So, if you need to run a function in a separate process, but want the current process to block until that function returns, use Pool.apply
. Like Pool.apply
, Pool.map
blocks until the complete result is returned.
If you want the Pool of worker processes to perform many function calls asynchronously, use Pool.apply_async
. The order of the results is not guaranteed to be the same as the order of the calls to Pool.apply_async
.
Notice also that you could call a number of different functions with Pool.apply_async
(not all calls need to use the same function).
In contrast, Pool.map
applies the same function to many arguments.
However, unlike Pool.apply_async
, the results are returned in an order corresponding to the order of the arguments.
mkdir ~/bin
PATH=~/bin:$PATH
ln -s /usr/bin/python2 ~/bin/python
To stop using python2, exit
or rm ~/bin/python
.
You can group conditions with parentheses. When you are checking if a field is equal to another, you want to use OR
. For example WHERE a='1' AND (b='123' OR b='234')
.
SELECT u.*
FROM rooms AS u
JOIN facilities_r AS fu
ON fu.id_uc = u.id_uc AND (fu.id_fu='4' OR fu.id_fu='3')
WHERE vizibility='1'
GROUP BY id_uc
ORDER BY u_premium desc, id_uc desc
From Screen User's Manual ;
screen -d -r "screenName"
Reattach a session and if necessary detach it first
You can use print_r
to get human-readable output.
You can use izip
to combine your lists, and then iterate them
for val in itertools.izip(l1,l2,l3,l4,l5):
writer.writerow(val)
I know it has been a long time since the original question was posted. But i think for slow ones like me a bit of explanation of @Heisenberg's answer would help.
Declare two variable in the adapter class as
private int mExpandedPosition= -1;
private RecyclerView recyclerView = null;
Then in onBindViewHolder following as given in the original answer.
// This line checks if the item displayed on screen
// was expanded or not (Remembering the fact that Recycler View )
// reuses views so onBindViewHolder will be called for all
// items visible on screen.
final boolean isExpanded = position==mExpandedPosition;
//This line hides or shows the layout in question
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
// I do not know what the heck this is :)
holder.itemView.setActivated(isExpanded);
// Click event for each item (itemView is an in-built variable of holder class)
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if the clicked item is already expaned then return -1
//else return the position (this works with notifyDatasetchanged )
mExpandedPosition = isExpanded ? -1:position;
// fancy animations can skip if like
TransitionManager.beginDelayedTransition(recyclerView);
//This will call the onBindViewHolder for all the itemViews on Screen
notifyDataSetChanged();
}
});
And lastly to get the recyclerView object in the adapter override
@Override
public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
this.recyclerView = recyclerView;
}
Hope this Helps.
For EF Core 2.0+ I had to take a different approach because they changed the API. As of March 2019 Microsoft recommends you put your database migration code in your application entry class but outside of the WebHost build code.
public class Program
{
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
using (var serviceScope = host.Services.CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<PersonContext>();
context.Database.Migrate();
}
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
you can change temporarily or switch between different versions using following commands:
set path=C:\Users\Shaina\AppData\Local\Programs\Python\Python35-32;%PATH%
python --version
I'll throw mine in the mix:
https://gist.github.com/btm1/6802312
this evaluates the if statement once and adds no watch listener BUT you can add an additional attribute to the element that has the set-if called wait-for="somedata.prop" and it will wait for that data or property to be set before evaluating the if statement once. that additional attribute can be very handy if you're waiting for data from an XHR request.
angular.module('setIf',[]).directive('setIf',function () {
return {
transclude: 'element',
priority: 1000,
terminal: true,
restrict: 'A',
compile: function (element, attr, linker) {
return function (scope, iterStartElement, attr) {
if(attr.waitFor) {
var wait = scope.$watch(attr.waitFor,function(nv,ov){
if(nv) {
build();
wait();
}
});
} else {
build();
}
function build() {
iterStartElement[0].doNotMove = true;
var expression = attr.setIf;
var value = scope.$eval(expression);
if (value) {
linker(scope, function (clone) {
iterStartElement.after(clone);
clone.removeAttr('set-if');
clone.removeAttr('wait-for');
});
}
}
};
}
};
});
You can use the re module:
import re
re.sub(r'\D', '', '+123-456-7890')
This will replace all non-digits with ''.
UPDATED(13/08/2014): This is the best code for positive and negative numbers =)
(^-?0\.[0-9]*[1-9]+[0-9]*$)|(^-?[1-9]+[0-9]*((\.[0-9]*[1-9]+[0-9]*$)|(\.[0-9]+)))|(^-?[1-9]+[0-9]*$)|(^0$){1}
I tried with this numbers and works fine:
-1234454.3435
-98.99
-12.9
-12.34
-10.001
-3
-0.001
-000
-0.00
0
0.00
00000001.1
0.01
1201.0000001
1234454.3435
7638.98701
Use file_get_contents
in combination with json_decode
and echo
.
This is how I clear the data:
Sub Macro3()
With Sheet1.ListObjects("Table1")
If Not .DataBodyRange Is Nothing Then
.DataBodyRange.Delete
End If
End With
End Sub
Here's an example on how you can do it :)
var students = [{_x000D_
name: "Mike",_x000D_
track: "track-a",_x000D_
achievements: 23,_x000D_
points: 400,_x000D_
},_x000D_
{_x000D_
name: "james",_x000D_
track: "track-a",_x000D_
achievements: 2,_x000D_
points: 21,_x000D_
},_x000D_
]_x000D_
_x000D_
students.forEach(myFunction);_x000D_
_x000D_
function myFunction(item, index) {_x000D_
for (var key in item) {_x000D_
console.log(item[key])_x000D_
}_x000D_
}
_x000D_
Calling toDate will create a copy (the documentation is down-right wrong about it not being a copy), of the underlying JS Date object. JS Date object is stored in UTC and will always print to eastern time. Without getting into whether .utc() modifies the underlying object that moment wraps use the code below.
You don't need moment for this.
new Date().getTime()
This works, because JS Date at its core is in UTC from the Unix Epoch. It's extraordinarily confusing and I believe a big flaw in the interface to mix local and UTC times like this with no descriptions in the methods.
Here is a really simple, but very effective, example. Once you have the basics down you can easily build off of it.
There are two main parts to using a Cursor Adapter with SQLite:
Create a proper Cursor from the Database.
Create a custom Cursor Adapter that takes the Cursor data from the database and pairs it with the View you intend to represent the data with.
In your Activity:
SQLiteOpenHelper sqLiteOpenHelper = new SQLiteOpenHelper(
context, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase sqLiteDatabase = sqLiteOpenHelper.getReadableDatabase();
String query = "SELECT * FROM clients ORDER BY company_name ASC"; // No trailing ';'
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
ClientCursorAdapter adapter = new ClientCursorAdapter(
this, R.layout.clients_listview_row, cursor, 0 );
this.setListAdapter(adapter);
Note: Extending from ResourceCursorAdapter
assumes you use XML to create your views.
public class ClientCursorAdapter extends ResourceCursorAdapter {
public ClientCursorAdapter(Context context, int layout, Cursor cursor, int flags) {
super(context, layout, cursor, flags);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(cursor.getString(cursor.getColumnIndex("name")));
TextView phone = (TextView) view.findViewById(R.id.phone);
phone.setText(cursor.getString(cursor.getColumnIndex("phone")));
}
}
Here is my approach for importing .sql files to MS SQL:
Export table from MySQL with --compatible=mssql
and --extended-insert=FALSE
options:
mysqldump -u [username] -p --compatible=mssql --extended-insert=FALSE db_name table_name > table_backup.sql
Split the exported file with PowerShell by 300000 lines per file:
$i=0; Get-Content exported.sql -ReadCount 300000 | %{$i++; $_ | Out-File out_$i.sql}
Run each file in MS SQL Server Management Studio
There are few tips how to speed up the inserts.
Other approach is to use mysqldump –where
option. By using this option you can split your table on any condition which is supported by where
sql clause.
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
M2Crypto can do the validation. You can also use M2Crypto with Twisted if you like. The Chandler desktop client uses Twisted for networking and M2Crypto for SSL, including certificate validation.
Based on Glyphs comment it seems like M2Crypto does better certificate verification by default than what you can do with pyOpenSSL currently, because M2Crypto checks subjectAltName field too.
I've also blogged on how to get the certificates Mozilla Firefox ships with in Python and usable with Python SSL solutions.
I tried almost all of the above options, but was not able to install google play services, however just found from the faq section of genymotion that the only way to access google play services is to use the packages provided by OpenGapps.
I tried and this worked:
For those who tried gkalpak answer and it did not work,
be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes
// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);
// Sending a receiving data in JSON format using GET method
//
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
xhr.send();
<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>
The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.
Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE
instead of xhr.readyState === 4
The problem is that Internet Explorer uses different state names so it's better to use state values.
The fundamental issue with your code is that you mix two APIs. Unfortunately online resources are not great at pointing this out, but there are two semaphore APIs on UNIX-like systems:
Looking at the code above you used semget() from the System V API and tried to post through sem_post() which comes from the POSIX API. It is not possible to mix them.
To decide which semaphore API you want you don't have so many great resources. The simple best is the "Unix Network Programming" by Stevens. The section that you probably interested in is in Vol #2.
These two APIs are surprisingly different. Both support the textbook style semaphores but there are a few good and bad points in the System V API worth mentioning:
Use the -1
option (note this is a "one" digit, not a lowercase letter "L"), like this:
ls -1a
First, though, make sure your ls
supports -1
. GNU coreutils (installed on standard Linux systems) and Solaris do; but if in doubt, use man ls
or ls --help
or check the documentation. E.g.:
$ man ls
...
-1 list one file per line. Avoid '\n' with -q or -b
var a = [23, 45, 12, 67];_x000D_
a.unshift(34);_x000D_
console.log(a); // [34, 23, 45, 12, 67]
_x000D_
A little bit of history now. Among other languages, BCPL had a fairly major influence on C's early development. If you declared an array in BCPL with something like:
let V = vec 10
that actually allocated 11 words of memory, not 10. Typically V was the first, and contained the address of the immediately following word. So unlike C, naming V went to that location and picked up the address of the zeroeth element of the array. Therefore array indirection in BCPL, expressed as
let J = V!5
really did have to do J = !(V + 5)
(using BCPL syntax) since it was necessary to fetch V to get the base address of the array. Thus V!5
and 5!V
were synonymous. As an anecdotal observation, WAFL (Warwick Functional Language) was written in BCPL, and to the best of my memory tended to use the latter syntax rather than the former for accessing the nodes used as data storage. Granted this is from somewhere between 35 and 40 years ago, so my memory is a little rusty. :)
The innovation of dispensing with the extra word of storage and having the compiler insert the base address of the array when it was named came later. According to the C history paper this happened at about the time structures were added to C.
Note that !
in BCPL was both a unary prefix operator and a binary infix operator, in both cases doing indirection. just that the binary form included an addition of the two operands before doing the indirection. Given the word oriented nature of BCPL (and B) this actually made a lot of sense. The restriction of "pointer and integer" was made necessary in C when it gained data types, and sizeof
became a thing.
// change "name" and "value" according to your array data.
// Change "yourDataArrayName" name accroding to your array(NSArray).
let resultPredicate = NSPredicate(format: "SELF.name contains[c] %@", "value")
if let sortedDta = yourDataArrayName.filtered(using: resultPredicate) as? NSArray {
//enter code here.
print(sortedDta)
}
One can use invisible iframes to get the cookies. Let's say there are two domains, a.com and b.com. For the index.html of domain a.com one can add (notice height=0 width=0):
<iframe height="0" id="iframe" src="http://b.com" width="0"></iframe>
That way your website will get b.com cookies assuming that http://b.com sets the cookies.
The next thing would be manipulating the site inside the iframe through JavaScript. The operations inside iframe may become a challenge if one doesn't own the second domain. But in case of having access to both domains referring the right web page at the src of iframe should give the cookies one would like to get.
This is what I ended up doing:
<div style="height: 600px">
<img src="assets/zzzzz.png" alt="Error" style="max-width: 100%;
max-height: 100%; display:block; margin:auto;" />
</div>
Which will limit the image height to 600px and will horizontally-center (or resize down if the parent width is smaller) to the parent container, maintaining proportions.
Thanks to @Gerben's post came to know there are two events show.bs.tab (before the tab is shown) and shown.bs.tab (after the tab is shown) as explained in the docs - Bootstrap Tab usage
An additional solution if we're only interested in a specific tab, and maybe add separate functions without having to add an if - else block in one function, is to use the a href selector (maybe along with additional selectors if required)
$("a[href='#tab_target_id']").on('shown.bs.tab', function(e) {
console.log('shown - after the tab has been shown');
});
// or even this one if we want the earlier event
$("a[href='#tab_target_id']").on('show.bs.tab', function(e) {
console.log('show - before the new tab has been shown');
});
private String removeScript(String content) {
Pattern p = Pattern.compile("<script[^>]*>(.*?)</script>",
Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
return p.matcher(content).replaceAll("");
}
columnDefs
now accepts a class. I'd say this is the preferred method if you'd like to specify columns to disable in your markup:
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th class="datatable-nosort">Actions</th>
</tr>
</thead>
...
</table>
Then, in your JS:
$("table").DataTable({
columnDefs: [{
targets: "datatable-nosort",
orderable: false
}]
});
.so
files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.
.a
files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar
command -- a predecessor of tar
that's now just used for making libraries) of the original .o object files.
.la
files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?
Static and dynamic libraries each have pros and cons.
Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.
Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.
Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.
Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.
Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.
Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.
Dynamic libraries are especially useful for system libraries, like libc
. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.
These regexes are equivalent (for matching purposes):
/^(7|8|9)\d{9}$/
/^[789]\d{9}$/
/^[7-9]\d{9}$/
The explanation:
(a|b|c)
is a regex "OR" and means "a or b or c", although the presence of brackets, necessary for the OR, also captures the digit. To be strictly equivalent, you would code (?:7|8|9)
to make it a non capturing group.
[abc]
is a "character class" that means "any character from a,b or c" (a character class may use ranges, e.g. [a-d]
= [abcd]
)
The reason these regexes are similar is that a character class is a shorthand for an "or" (but only for single characters). In an alternation, you can also do something like (abc|def)
which does not translate to a character class.
Remove all your httpclient, httpmime dependency and add this dependency compile 'commons-httpclient:commons-httpclient:3.1'
. This dependency has built in MultipartRequestEntity so that you can easily upload one or more files to the server
public class FileUploadUrlConnection extends AsyncTask<String, String, String> {
private Context context;
private String url;
private List<File> files;
public FileUploadUrlConnection(Context context, String url, List<File> files) {
this.context = context;
this.url = url;
this.files = files;
}
@Override
protected String doInBackground(String... params) {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(url);
HttpClientParams connectionParams = new HttpClientParams();
post.setRequestHeader(// Your header goes here );
try {
Part[] parts = new Part[files.size()];
for (int i=0; i<files.size(); i++) {
Part part = new FilePart(files.get(i).getName(), files.get(i));
parts[i] = part;
}
MultipartRequestEntity entity = new MultipartRequestEntity(parts, connectionParams);
post.setRequestEntity(entity);
int statusCode = client.executeMethod(post);
String response = post.getResponseBodyAsString();
Log.v("Multipart "," "+response);
if(statusCode == 200) {
return response;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
You can also add the request and response timeout
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
INSERT INTO table1
SELECT "A string", 5, idTable2
FROM table2
WHERE ...
See: http://dev.mysql.com/doc/refman/5.6/en/insert-select.html
nflog is better
sudo apt-get -y install ulogd2
ICMP Block rule example:
iptables=/sbin/iptables
# Drop ICMP (PING)
$iptables -t mangle -A PREROUTING -p icmp -j NFLOG --nflog-prefix 'ICMP Block'
$iptables -t mangle -A PREROUTING -p icmp -j DROP
And you can search prefix "ICMP Block" in log:
/var/log/ulog/syslogemu.log
You might want to try this, could potentially be faster than doing two queries:
select <some columns>
from (
SELECT <some columns>,
row_number() over (order by date desc) as rn,
count(*) over () as total_count
FROM mytable
<maybe some joins here>
WHERE <various conditions>
) t
where rn = 1
or rn = total_count
ORDER BY date DESC
In order to add a label to the map you need to create a custom overlay. The sample at http://blog.mridey.com/2009/09/label-overlay-example-for-google-maps.html uses a custom class, Layer
, that inherits from OverlayView
(which inherits from MVCObject
) from the Google Maps API. He has a revised version (adds support for visibility, zIndex and a click event) which can be found here: http://blog.mridey.com/2011/05/label-overlay-example-for-google-maps.html
The following code is taken directly from Marc Ridey's Blog (the revised link above).
Layer class
// Define the overlay, derived from google.maps.OverlayView
function Label(opt_options) {
// Initialization
this.setValues(opt_options);
// Label specific
var span = this.span_ = document.createElement('span');
span.style.cssText = 'position: relative; left: -50%; top: -8px; ' +
'white-space: nowrap; border: 1px solid blue; ' +
'padding: 2px; background-color: white';
var div = this.div_ = document.createElement('div');
div.appendChild(span);
div.style.cssText = 'position: absolute; display: none';
};
Label.prototype = new google.maps.OverlayView;
// Implement onAdd
Label.prototype.onAdd = function() {
var pane = this.getPanes().overlayImage;
pane.appendChild(this.div_);
// Ensures the label is redrawn if the text or position is changed.
var me = this;
this.listeners_ = [
google.maps.event.addListener(this, 'position_changed', function() { me.draw(); }),
google.maps.event.addListener(this, 'visible_changed', function() { me.draw(); }),
google.maps.event.addListener(this, 'clickable_changed', function() { me.draw(); }),
google.maps.event.addListener(this, 'text_changed', function() { me.draw(); }),
google.maps.event.addListener(this, 'zindex_changed', function() { me.draw(); }),
google.maps.event.addDomListener(this.div_, 'click', function() {
if (me.get('clickable')) {
google.maps.event.trigger(me, 'click');
}
})
];
};
// Implement onRemove
Label.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
// Label is removed from the map, stop updating its position/text.
for (var i = 0, I = this.listeners_.length; i < I; ++i) {
google.maps.event.removeListener(this.listeners_[i]);
}
};
// Implement draw
Label.prototype.draw = function() {
var projection = this.getProjection();
var position = projection.fromLatLngToDivPixel(this.get('position'));
var div = this.div_;
div.style.left = position.x + 'px';
div.style.top = position.y + 'px';
div.style.display = 'block';
this.span_.innerHTML = this.get('text').toString();
};
Usage
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>
Label Overlay Example
</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="label.js"></script>
<script type="text/javascript">
var marker;
function initialize() {
var latLng = new google.maps.LatLng(40, -100);
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 5,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
marker = new google.maps.Marker({
position: latLng,
draggable: true,
zIndex: 1,
map: map,
optimized: false
});
var label = new Label({
map: map
});
label.bindTo('position', marker);
label.bindTo('text', marker, 'position');
label.bindTo('visible', marker);
label.bindTo('clickable', marker);
label.bindTo('zIndex', marker);
google.maps.event.addListener(marker, 'click', function() { alert('Marker has been clicked'); })
google.maps.event.addListener(label, 'click', function() { alert('Label has been clicked'); })
}
function showHideMarker() {
marker.setVisible(!marker.getVisible());
}
function pinUnpinMarker() {
var draggable = marker.getDraggable();
marker.setDraggable(!draggable);
marker.setClickable(!draggable);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="height: 200px; width: 200px"></div>
<button type="button" onclick="showHideMarker();">Show/Hide Marker</button>
<button type="button" onclick="pinUnpinMarker();">Pin/Unpin Marker</button>
</body>
</html>
In C++ "friend" keyword is useful in Operator overloading and Making Bridge.
1.) Friend keyword in operator overloading :
Example for operator overloading is: Let say we have a class "Point" that has two float variable
"x"(for x-coordinate) and "y"(for y-coordinate). Now we have to overload "<<"
(extraction operator) such that if we call "cout << pointobj"
then it will print x and y coordinate (where pointobj is an object of class Point). To do this we have two option:
1.Overload "operator <<()" function in "ostream" class. 2.Overload "operator<<()" function in "Point" class.Now First option is not good because if we need to overload again this operator for some different class then we have to again make change in "ostream" class.
"operator <<()"
function:1.Using ostream object cout.As: cout.operator<<(Pointobj) (form ostream class).
2.Call without an object.As: operator<<(cout, Pointobj) (from Point class).
Beacause we have implemented overloading in Point class. So to call this function without an object we have to add"friend"
keyword because we can call a friend function without an object.
Now function declaration will be As:
"friend ostream &operator<<(ostream &cout, Point &pointobj);"
2.) Friend keyword in making bridge :
Suppose we have to make a function in which we have to access private member of two or more classes ( generally termed as "bridge" ) .
How to do this:
To access private member of a class it should be member of that class. Now to access private member of other class every class should declare that function as a friend function. For example :
Suppose there are two class A and B. A function "funcBridge()"
want to access private member of both classes. Then both class should declare "funcBridge()"
as:
friend return_type funcBridge(A &a_obj, B & b_obj);
I think this would help to understand friend keyword.
Also the $wshell = New-Object -ComObject wscript.shell;
helped a script that was running in the background, it worked fine with just but adding $wshell
. fixed it from running as background! [Microsoft.VisualBasic.Interaction]::AppActivate("App Name")
Short answer:
ALTER SCHEMA new_schema TRANSFER old_schema.table_name
I can confirm that the data in the table remains intact, which is probably quite important :)
Long answer as per MSDN docs,
ALTER SCHEMA schema_name
TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]
If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.
Difference Between String, StringBuilder And StringBuffer Classes
String
String is immutable ( once created can not be changed )object. The object created as a
String is stored in the Constant String Pool.
Every immutable object in Java is thread-safe, which implies String is also thread-safe. String
can not be used by two threads simultaneously.
String once assigned can not be changed.
StringBuffer
StringBuffer is mutable means one can change the value of the object. The object created
through StringBuffer is stored in the heap. StringBuffer has the same methods as the
StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread
safe .
Due to this, it does not allow two threads to simultaneously access the same method. Each
method can be accessed by one thread at a time.
But being thread-safe has disadvantages too as the performance of the StringBuffer hits due
to thread-safe property. Thus StringBuilder is faster than the StringBuffer when calling the
same methods of each class.
String Buffer can be converted to the string by using
toString() method.
StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed.
/
// Above statement is right as it modifies the value which is allowed in the StringBuffer
StringBuilder
StringBuilder is the same as the StringBuffer, that is it stores the object in heap and it can also
be modified. The main difference between the StringBuffer and StringBuilder is
that StringBuilder is also not thread-safe.
StringBuilder is fast as it is not thread-safe.
/
// The above object is stored in the heap and its value can be modified
/
// Above statement is right as it modifies the value which is allowed in the StringBuilder
You can work around this by creating a separate VIEW for any subquery you want to use and then join to that in the VIEW you're creating. Here's an example: http://blog.gruffdavies.com/2015/01/25/a-neat-mysql-hack-to-create-a-view-with-subquery-in-the-from-clause/
This is quite handy as you'll very likely want to reuse it anyway and helps you keep your SQL DRY.
I created this method, it is ideal because it aborts the connection without downloading it in its entirety, ideal for checking if videos or large images exist, decreasing the response time and the need to download the entire file
// if-url-exist.js v1
function ifUrlExist(url, callback) {
let request = new XMLHttpRequest;
request.open('GET', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Accept', '*/*');
request.onprogress = function(event) {
let status = event.target.status;
let statusFirstNumber = (status).toString()[0];
switch (statusFirstNumber) {
case '2':
request.abort();
return callback(true);
default:
request.abort();
return callback(false);
};
};
request.send('');
};
Example of use:
ifUrlExist(url, function(exists) {
console.log(exists);
});
If you installed Jupyter notebook for Python 2 using 'pip' instead of 'pip3' it might work to run:
ipython notebook
EDIT (removed wrong solution). EDIT (to add this other option):
Another way to use it would be subclass QThread since it has protected *sleep methods.
QThread::usleep(unsigned long microseconds);
QThread::msleep(unsigned long milliseconds);
QThread::sleep(unsigned long second);
Here's the code to create your own *sleep method.
#include <QThread>
class Sleeper : public QThread
{
public:
static void usleep(unsigned long usecs){QThread::usleep(usecs);}
static void msleep(unsigned long msecs){QThread::msleep(msecs);}
static void sleep(unsigned long secs){QThread::sleep(secs);}
};
and you call it by doing this:
Sleeper::usleep(10);
Sleeper::msleep(10);
Sleeper::sleep(10);
This would give you a delay of 10 microseconds, 10 milliseconds or 10 seconds, accordingly. If the underlying operating system timers support the resolution.
Use the indent
argument of the dumps
function in the json module.
From the docs:
>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
"4": 5,
"6": 7
}
Here are three different checkmark styles you can use:
ul:first-child li:before { content:"\2713\0020"; } /* OR */_x000D_
ul:nth-child(2) li:before { content:"\2714\0020"; } /* OR */_x000D_
ul:last-child li:before { content:"\2611\0020"; }_x000D_
ul { list-style-type: none; }
_x000D_
<ul>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul><!-- not working on Stack snippet; check fiddle demo -->_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
</ul>
_x000D_
References:
I would handle it like so:
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'watch-me') {
$('#show-me').show();
}
else {
$('#show-me').hide();
}
});
});
if you have set the title attribute in HTML then use on click of the icon or button $(this).attr('title',newValue);
Well yes, the access exception is due to the fact that document.domain
must match in your parent and your iframe, and before they do, you won't be able to programmatically set the document.domain
property of your iframe.
I think your best option here is to point the page to a template of your own:
iframe.src = '/myiframe.htm#' + document.domain;
And in myiframe.htm:
document.domain = location.hash.substring(1);
dataset = dataset.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)
This worked for me
To be short, please use fmt.Printf("%T", var1)
or its other variants in the fmt package.
What is
<=>
( The 'Spaceship' Operator )
<=>
$b - 0 if $a == $b
- -1 if $a < $b
- 1 if $a > $b
- Return 0 if values on either side are equal
- Return 1 if value on the left is greater
- Return -1 if the value on the right is greater
Example:
//Comparing Integers
echo 1 <=> 1; //ouputs 0
echo 3 <=> 4; //outputs -1
echo 4 <=> 3; //outputs 1
//String Comparison
echo "x" <=> "x"; // 0
echo "x" <=> "y"; //-1
echo "y" <=> "x"; //1
MORE:
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1
// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1
// Objects
$a = (object) ["a" => "b"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 0
std::copy
but without extra trailing separatorAn alternative/modified approach using std::copy
(as originally used in @JoshuaKravtiz answer) but without including an additional trailing separator after the last element:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template <typename T>
void print_contents(const std::vector<T>& v, const char * const separator = " ")
{
if(!v.empty())
{
std::copy(v.begin(),
--v.end(),
std::ostream_iterator<T>(std::cout, separator));
std::cout << v.back() << "\n";
}
}
// example usage
int main() {
std::vector<int> v{1, 2, 3, 4};
print_contents(v); // '1 2 3 4'
print_contents(v, ":"); // '1:2:3:4'
v = {};
print_contents(v); // ... no std::cout
v = {1};
print_contents(v); // '1'
return 0;
}
Example usage applied to container of a custom POD type:
// includes and 'print_contents(...)' as above ...
class Foo
{
int i;
friend std::ostream& operator<<(std::ostream& out, const Foo& obj);
public:
Foo(const int i) : i(i) {}
};
std::ostream& operator<<(std::ostream& out, const Foo& obj)
{
return out << "foo_" << obj.i;
}
int main() {
std::vector<Foo> v{1, 2, 3, 4};
print_contents(v); // 'foo_1 foo_2 foo_3 foo_4'
print_contents(v, ":"); // 'foo_1:foo_2:foo_3:foo_4'
v = {};
print_contents(v); // ... no std::cout
v = {1};
print_contents(v); // 'foo_1'
return 0;
}
Meta tags are not a reliable way to achieve this result. Generally you shouldn't even do this - it should be left up to the user/user agent to decide what do to with the content you provide. The user can always force their browser to download the file if they wish to.
If you still want to force the browser to download the file, modify the HTTP headers directly. Here's a PHP code example:
$path = "path/to/file.pdf";
$filename = "file.pdf";
header('Content-Transfer-Encoding: binary'); // For Gecko browsers mainly
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
header('Accept-Ranges: bytes'); // Allow support for download resume
header('Content-Length: ' . filesize($path)); // File size
header('Content-Encoding: none');
header('Content-Type: application/pdf'); // Change the mime type if the file is not PDF
header('Content-Disposition: attachment; filename=' . $filename); // Make the browser display the Save As dialog
readfile($path); // This is necessary in order to get it to actually download the file, otherwise it will be 0Kb
Note that this is just an extension to the HTTP protocol; some browsers might ignore it anyway.
Most of these answers circulate around removing a file from the "staging area" pre-commit, but I often find myself looking here after I've already committed and I want to remove some sensitive information from the commit I just made.
An easy to remember trick for all of you git commit --amend
folks out there like me is that you can:
git add .
to add the deletion to the "staging area"git commit --amend
to remove the file from the previous commit.You will notice in the commit message that the unwanted file is now missing. Hooray! (Commit SHA
will have changed, so be careful if you already pushed your changes to the remote.)
You should be using the unwind library.
unw_cursor_t cursor; unw_context_t uc;
unw_word_t ip, sp;
unw_getcontext(&uc);
unw_init_local(&cursor, &uc);
unsigned long a[100];
int ctr = 0;
while (unw_step(&cursor) > 0) {
unw_get_reg(&cursor, UNW_REG_IP, &ip);
unw_get_reg(&cursor, UNW_REG_SP, &sp);
if (ctr >= 10) break;
a[ctr++] = ip;
}
Your approach also would work fine unless you make a call from a shared library.
You can use the addr2line
command on Linux to get the source function / line number of the corresponding PC.
Try this to convert string to uri
String mystring="Hello"
Uri myUri = Uri.parse(mystring);
Uri to String
Uri uri;
String uri_to_string;
uri_to_string= uri.toString();
For anyone who stumbles across this post looking for a solution and you've set up SMTP sendgrid via Azure.
The username is not the username you set up when you've created the sendgrid object in azure. To find your username;
Hope this helps!
You can use the arithmetic operators to do relative time.
Time.now - 2.days
Will give you 2 days ago.
Here Is my code For Zip the folders and its sub folders and its files and make it downloadable in zip Format
function zip()
{
$source='path/folder'// Path To the folder;
$destination='path/folder/abc.zip'// Path to the file and file name ;
$include_dir = false;
$archive = 'abc.zip'// File Name ;
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
if (file_exists($destination)) {
unlink ($destination);
}
$zip = new ZipArchive;
if (!$zip->open($archive, ZipArchive::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
if ($include_dir) {
$arr = explode("/",$source);
$maindir = $arr[count($arr)- 1];
$source = "";
for ($i=0; $i < count($arr) - 1; $i++) {
$source .= '/' . $arr[$i];
}
$source = substr($source, 1);
$zip->addEmptyDir($maindir);
}
foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
}
If Any Issue With the Code Let Me know.
Suppose I have this line of scripts in my "package.json"
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"export_advertisements": "node export.js advertisements",
"export_homedata": "node export.js homedata",
"export_customdata": "node export.js customdata",
"export_rooms": "node export.js rooms"
},
Now to run the script "export_advertisements", I will simply go to the terminal and type
npm run export_advertisements
You are most welcome
I was able to work it out only after adding those two TOGETHER:
dependencies {
...
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
...
}
in my build.gradle (Module:app) file
and then press the sync now button
To change the size of (almost) all text elements, in one place, and synchronously, rel()
is quite efficient:
g+theme(text = element_text(size=rel(3.5))
You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)),
strip.text.x = element_text(size=rel(3.5)),
strip.text.y = element_text(size=rel(3.5)))
You can use CSS3 transitions or maybe CSS3 animations to slide in an element.
For browser support: http://caniuse.com/
I made two quick examples just to show you how I mean.
CSS transition (on hover)
Relevant Code
.wrapper:hover #slide {
transition: 1s;
left: 0;
}
In this case, Im just transitioning the position from left: -100px;
to 0;
with a 1s. duration. It's also possible to move the element using transform: translate();
CSS animation
#slide {
position: absolute;
left: -100px;
width: 100px;
height: 100px;
background: blue;
-webkit-animation: slide 0.5s forwards;
-webkit-animation-delay: 2s;
animation: slide 0.5s forwards;
animation-delay: 2s;
}
@-webkit-keyframes slide {
100% { left: 0; }
}
@keyframes slide {
100% { left: 0; }
}
Same principle as above (Demo One), but the animation starts automatically after 2s, and in this case I've set animation-fill-mode
to forwards
, which will persist the end state, keeping the div visible when the animation ends.
Like I said, two quick example to show you how it could be done.
EDIT: For details regarding CSS Animations and Transitions see:
Animations
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations
Transitions
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions
Hope this helped.
I have a slightly different approach that might be useful/more beneficial to some.
Under your main project folder, create a resource folder. Your folder structure should look something like this.
Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.
Under categories on the left side, select Sources.
In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.
You should now be able to pull resources using this line or similar approach:
MyClass.class.getResource("/main.jpg");
If you were to create a package called Images under the resources folder, you can retrieve the resource like this:
MyClass.class.getResource("/Images/main.jpg");
Here is a way to do it that works, but may not be best practise for any language really:
var x,y;
x='something';
y=1;
undefined === y || (x = y);
alternatively
undefined !== y && (x = y);
On OS X Sierra 10.12, None of the above work.
cd then drag and drop does not work.
No spacing or other fixes work.
I cannot cd into ~/Library Support using any technique that I can find.
Is this a security feature?
I'm going to try disabling SIP and see if it makes a difference.
I just had the same question but with irregularly spaced datapoints. Resample is not really an option here. So I created my own function. Maybe it will be useful for others too:
from pandas import Series, DataFrame
import pandas as pd
from datetime import datetime, timedelta
import numpy as np
def rolling_mean(data, window, min_periods=1, center=False):
''' Function that computes a rolling mean
Parameters
----------
data : DataFrame or Series
If a DataFrame is passed, the rolling_mean is computed for all columns.
window : int or string
If int is passed, window is the number of observations used for calculating
the statistic, as defined by the function pd.rolling_mean()
If a string is passed, it must be a frequency string, e.g. '90S'. This is
internally converted into a DateOffset object, representing the window size.
min_periods : int
Minimum number of observations in window required to have a value.
Returns
-------
Series or DataFrame, if more than one column
'''
def f(x):
'''Function to apply that actually computes the rolling mean'''
if center == False:
dslice = col[x-pd.datetools.to_offset(window).delta+timedelta(0,0,1):x]
# adding a microsecond because when slicing with labels start and endpoint
# are inclusive
else:
dslice = col[x-pd.datetools.to_offset(window).delta/2+timedelta(0,0,1):
x+pd.datetools.to_offset(window).delta/2]
if dslice.size < min_periods:
return np.nan
else:
return dslice.mean()
data = DataFrame(data.copy())
dfout = DataFrame()
if isinstance(window, int):
dfout = pd.rolling_mean(data, window, min_periods=min_periods, center=center)
elif isinstance(window, basestring):
idx = Series(data.index.to_pydatetime(), index=data.index)
for colname, col in data.iterkv():
result = idx.apply(f)
result.name = colname
dfout = dfout.join(result, how='outer')
if dfout.columns.size == 1:
dfout = dfout.ix[:,0]
return dfout
# Example
idx = [datetime(2011, 2, 7, 0, 0),
datetime(2011, 2, 7, 0, 1),
datetime(2011, 2, 7, 0, 1, 30),
datetime(2011, 2, 7, 0, 2),
datetime(2011, 2, 7, 0, 4),
datetime(2011, 2, 7, 0, 5),
datetime(2011, 2, 7, 0, 5, 10),
datetime(2011, 2, 7, 0, 6),
datetime(2011, 2, 7, 0, 8),
datetime(2011, 2, 7, 0, 9)]
idx = pd.Index(idx)
vals = np.arange(len(idx)).astype(float)
s = Series(vals, index=idx)
rm = rolling_mean(s, window='2min')
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
For everyone looking for the log of the binomial coefficient (Theano calls this binomln
), this answer has it:
from numpy import log
from scipy.special import betaln
def binomln(n, k):
"Log of scipy.special.binom calculated entirely in the log domain"
return -betaln(1 + n - k, 1 + k) - log(n + 1)
(And if your language/library lacks betaln
but has gammaln
, like Go, have no fear, since betaln(a, b)
is just gammaln(a) + gammaln(b) - gammaln(a + b)
, per MathWorld.)
The _cluster/health
API can do far more than the typical output that most see with it:
$ curl -XGET 'localhost:9200/_cluster/health?pretty'
Most APIs within Elasticsearch can take a variety of arguments to augment their output. This applies to Cluster Health API as well.
$ curl -XGET 'localhost:9200/_cluster/health?level=indices&pretty' | head -50
{
"cluster_name" : "rdu-es-01",
"status" : "green",
"timed_out" : false,
"number_of_nodes" : 9,
"number_of_data_nodes" : 6,
"active_primary_shards" : 1106,
"active_shards" : 2213,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0,
"delayed_unassigned_shards" : 0,
"number_of_pending_tasks" : 0,
"number_of_in_flight_fetch" : 0,
"task_max_waiting_in_queue_millis" : 0,
"active_shards_percent_as_number" : 100.0,
"indices" : {
"filebeat-6.5.1-2019.06.10" : {
"status" : "green",
"number_of_shards" : 3,
"number_of_replicas" : 1,
"active_primary_shards" : 3,
"active_shards" : 6,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
},
"filebeat-6.5.1-2019.06.11" : {
"status" : "green",
"number_of_shards" : 3,
"number_of_replicas" : 1,
"active_primary_shards" : 3,
"active_shards" : 6,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
},
"filebeat-6.5.1-2019.06.12" : {
"status" : "green",
"number_of_shards" : 3,
"number_of_replicas" : 1,
"active_primary_shards" : 3,
"active_shards" : 6,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
},
"filebeat-6.5.1-2019.06.13" : {
"status" : "green",
"number_of_shards" : 3,
all shards health
$ curl -XGET 'localhost:9200/_cluster/health?level=shards&pretty' | head -50
{
"cluster_name" : "rdu-es-01",
"status" : "green",
"timed_out" : false,
"number_of_nodes" : 9,
"number_of_data_nodes" : 6,
"active_primary_shards" : 1106,
"active_shards" : 2213,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0,
"delayed_unassigned_shards" : 0,
"number_of_pending_tasks" : 0,
"number_of_in_flight_fetch" : 0,
"task_max_waiting_in_queue_millis" : 0,
"active_shards_percent_as_number" : 100.0,
"indices" : {
"filebeat-6.5.1-2019.06.10" : {
"status" : "green",
"number_of_shards" : 3,
"number_of_replicas" : 1,
"active_primary_shards" : 3,
"active_shards" : 6,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0,
"shards" : {
"0" : {
"status" : "green",
"primary_active" : true,
"active_shards" : 2,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
},
"1" : {
"status" : "green",
"primary_active" : true,
"active_shards" : 2,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
},
"2" : {
"status" : "green",
"primary_active" : true,
"active_shards" : 2,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
The API also has a variety of wait_*
options where it'll wait for various state changes before returning immediately or after some specified timeout
.
Answers here mostly focus on short way to fix it, but if that does not help, I'll give some steps to check, that helped me (Linux only):
List the symbols in the library and grep the symbols that linker complains about (enter the commands in command line):
nm lib_your_problem_library.a | grep functionNameLinkerComplainsAbout
If you got the method signature, proceed to the next step, if you got no symbols
instead, mostlikely you stripped off all the symbols from the library and that is why linker can't find them when linking the library. Rebuild the library without stripping ALL the symbols, you can strip debug (strip -S
option) symbols if you need.
Use a c++ demangler to understand the method signature, for example, this one
For anyone who wants a quick-fix, this simply replaces all single quotes with double quotes:
import json
predictions = []
def get_top_k_predictions(predictions_path):
'''load the predictions'''
with open (predictions_path) as json_lines_file:
for line in json_lines_file:
predictions.append(json.loads(line.replace("'", "\"")))
get_top_k_predictions("/sh/sh-experiments/outputs/john/baseline_1000/test_predictions.jsonl")
Window:
cat ~/.ssh/id_rsa.pub
Mac OS:
cat ~/.ssh/id_rsa.pub | pbcopy
use for each loop...
ArrayList<Character> al = new ArrayList<>();
String input="hello";
for (int i = 0; i < input.length(); i++){
al.add(input.charAt(i));
}
for (Character ch : al) {
System.Out.println(ch);
}
Unfortunately, the most popular answer did not work for me entirely. I had to add .select_option
to end of the statement
select("option_name_here", from: "organizationSelect").select_option
without the select_option
, no select was being performed
Add it to the session, not to the request.
HttpSession session = request.getSession();
session.setAttribute("object", object);
Also, don't use scriptlets in the JSP. Use EL instead; to access object
all you need is ${object}
.
A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. For example, the JSP expression language allows a page author to access a bean using simple syntax such as
${name}
for a simple variable or${name.foo.bar}
for a nested property.
The find one is good but I think you can use anotherway, especially if you need to now how many seconds is the file old
date -d "now - $( stat -c "%Y" $filename ) seconds" +%s
using GNU date
In extremely non-technical terms, it may mean that you forgot to put "ejb:" or "jdbc:" or something at the very beginning of the URI you are trying to connect.
you need to add in web.config
<endpoint address="customBinding" binding="customBinding" bindingConfiguration="basicConfig" contract="WcfRest.IService1"/>
<bindings>
<customBinding>
<binding name="basicConfig">
<binaryMessageEncoding/>
<httpTransport transferMode="Streamed" maxReceivedMessageSize="67108864"/>
</binding>
</customBinding>
I wrote following function, it works.
It returns datetime data type. Zero hour, minute, second, miliseconds.
CREATE Function [dbo].[fn_GetLastDate]
(
@date datetime
)
returns datetime
as
begin
declare @result datetime
select @result = CHOOSE(month(@date),
DATEADD(DAY, 31 -day(@date), @date),
IIF(YEAR(@date) % 4 = 0, DATEADD(DAY, 29 -day(@date), @date), DATEADD(DAY, 28 -day(@date), @date)),
DATEADD(DAY, 31 -day(@date), @date) ,
DATEADD(DAY, 30 -day(@date), @date),
DATEADD(DAY, 31 -day(@date), @date),
DATEADD(DAY, 30 -day(@date), @date),
DATEADD(DAY, 31 -day(@date), @date),
DATEADD(DAY, 31 -day(@date), @date),
DATEADD(DAY, 30 -day(@date), @date),
DATEADD(DAY, 31 -day(@date), @date),
DATEADD(DAY, 30 -day(@date), @date),
DATEADD(DAY, 31 -day(@date), @date))
return convert(date, @result)
end
It's very easy to use. 2 example:
select [dbo].[fn_GetLastDate]('2016-02-03 12:34:12')
select [dbo].[fn_GetLastDate](GETDATE())
For ViewPager2,
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
}
})
where OnPageChangeCallback
is a static class with three methods:
onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels),
onPageSelected(int position),
onPageScrollStateChanged(@ScrollState int state)
Here you can find little JSON wrapper with corrective actions that addresses BOM and non-ASCI issue: https://stackoverflow.com/a/43694325/2254935
Here is one more solution but a single risk.
code:
#include <iostream>
#include <conio.h>
void main()
{
int a =10 , b =45;
*(&a+1 ) = a;
a =b;
b =*(&a +1);
}
any value at location a+1 will be overridden.
For me the issue resolved when I set the principal section like this:
env.put(Context.SECURITY_PRINCIPAL, userId@domainWithoutProtocolAndPortNo);
Using plaintext may not be the best choice, if the password is ever used as something else.
I support the accepted answer, but it didn't work for me - for a very specific reason: I wanted to use either kwallet
or gnome-keyring
password stores. I tried changing the settings, all over the four files:
/etc/subversion/config
/etc/subversion/servers
~/.subversion/config
~/.subversion/servers
Even after it all was set the same, with password-stores
and KWallet name (default might be wrong, right?) it didn't work and kept asking for password forever. The files in ~/.subversion
had permissions 600.
Well, at that point, you may try to check one simple thing:
which svn
If you get:
/usr/bin/local/svn
then you may suspect with great likelihood that this client was built from source, locally, by your administrator (which may be yourself, as in my case).
Subversion is a nasty beast to compile, very easy to accidentally build without HTTP support, or - as in my example - without support for encrypted password stores (you need either Gnome or KDE development files, and a lot of them!). But the ./configure
script won't tell you that, and you just get a less functional svn
command.
In that case, you may go back to the client, which came with your distribution, usually in /usr/bin/svn
. The downside is - you'll probably need to re-checkout the working copies, as there is no svn downgrade
command. You can consult Linus Torvalds on what to think about Subversion, anyway ;)
Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).
nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)
should work.
You are comparing two objects for equality. The snippet:
if (obj == this) { return true; }
is a quick test that can be read
"If the object I'm comparing myself to is me, return true"
. You usually see this happen in equals
methods so they can exit early and avoid other costly comparisons.
will the height attribute stretch the image beyond its native resolution? If I have a image with a height of say 420 pixels, I can't get css to stretch the image beyond the native resolution to fill the height of the viewport.
I am getting pretty close results with:
.rightdiv img {
max-width: 25vw;
min-height: 100vh;
}
the 100vh is getting pretty close, with just a few pixels left over at the bottom for some reason.
# select columns containing 'spike'
df.filter(like='spike', axis=1)
You can also select by name, regular expression. Refer to: pandas.DataFrame.filter
Was trying to create a string representation of MD5 hash using LINQ, however, none of the answers were LINQ solutions, therefore adding this to the smorgasbord of available solutions.
string result;
using (MD5 hash = MD5.Create())
{
result = String.Join
(
"",
from ba in hash.ComputeHash
(
Encoding.UTF8.GetBytes(observedText)
)
select ba.ToString("x2")
);
}
You can silence the "Snapshotting a view" warning by referencing the view
property before presenting the view controller. Doing so causes the view to load and allows iOS render it before taking the snapshot.
UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
controller.modalPresentationStyle = UIModalPresentationPopover;
controller.popoverPresentationController.barButtonItem = (UIBarButtonItem *)sender;
... setup the UIAlertController ...
[controller view]; // <--- Add to silence the warning.
[self presentViewController:controller animated:YES completion:nil];
select
(select count(*) from foo) as foo
, (select count(*) from bar) as bar
, ...
Posting your HTML might help a bit. Instead, you can get the element first and then check if it is null or not and then ask for its value rather than just asking for the value directly without knowing if the element is visible on the HTML or not.
element1 = document.getElementById(id);
if(element1 != null)
{
//code to set the value variable.
}
I forget where I saw this definition, but I think it's pretty nice.
A library is a module that you call from your code, and a framework is a module which calls your code.
CASE
in MySQL is both a statement and an expression, where each usage is slightly different.
As a statement, CASE
works much like a switch statement and is useful in stored procedures, as shown in this example from the documentation (linked above):
DELIMITER |
CREATE PROCEDURE p()
BEGIN
DECLARE v INT DEFAULT 1;
CASE v
WHEN 2 THEN SELECT v;
WHEN 3 THEN SELECT 0;
ELSE
BEGIN -- Do other stuff
END;
END CASE;
END;
|
However, as an expression it can be used in clauses:
SELECT *
FROM employees
ORDER BY
CASE title
WHEN "President" THEN 1
WHEN "Manager" THEN 2
ELSE 3
END, surname
Additionally, both as a statement and as an expression, the first argument can be omitted and each WHEN
must take a condition.
SELECT *
FROM employees
ORDER BY
CASE
WHEN title = "President" THEN 1
WHEN title = "Manager" THEN 2
ELSE 3
END, surname
I provided this answer because the other answer fails to mention that CASE
can function both as a statement and as an expression. The major difference between them is that the statement form ends with END CASE
and the expression form ends with just END
.
How about writing some color-based class in a global sass file, thus we don't need to care where variables are. Just like the following:
// base.scss
@import "./_variables.scss";
.background-color{
background: $bg-color;
}
and then, we can use the background-color
class in any file.
My point is that I don't need to import variable.scss
in any file, just use it.
mysqli_fetch_array()
returns NULL
if there is no row.
In procedural style:
if ( ! $row = mysqli_fetch_array( $result ) ) {
... no result ...
}
else {
... get the first result in $row ...
}
In Object oriented style:
if ( ! $row = $result->fetch_array() ) {
...
}
else {
... get the first result in $row ...
}
Try doing
javac Hello.java
and then, if it comes up with no compiler errors (which it should not do because I cannot see any bugs in your programme), then type
java Hello
Keep in mind while using HTML5 pushstate if a user copies or bookmarks a deep link and visits it again, then that will be a direct server hit which will 404 so you need to be ready for it and even a pushstate js library won't help you. The easiest solution is to add a rewrite rule to your Nginx or Apache server like so:
Apache (in your vhost if you're using one):
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Nginx
rewrite ^(.+)$ /index.html last;
The dataset in ss.csv
contains some columns I am interested in:
ss_ = spark.read.csv("ss.csv", header= True,
inferSchema = True)
ss_.columns
['Reporting Area', 'MMWR Year', 'MMWR Week', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Med', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Med, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Max', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Max, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2018', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2018, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2017', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2017, flag', 'Shiga toxin-producing Escherichia coli, Current week', 'Shiga toxin-producing Escherichia coli, Current week, flag', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Med', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Med, flag', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Max', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Max, flag', 'Shiga toxin-producing Escherichia coli, Cum 2018', 'Shiga toxin-producing Escherichia coli, Cum 2018, flag', 'Shiga toxin-producing Escherichia coli, Cum 2017', 'Shiga toxin-producing Escherichia coli, Cum 2017, flag', 'Shigellosis, Current week', 'Shigellosis, Current week, flag', 'Shigellosis, Previous 52 weeks Med', 'Shigellosis, Previous 52 weeks Med, flag', 'Shigellosis, Previous 52 weeks Max', 'Shigellosis, Previous 52 weeks Max, flag', 'Shigellosis, Cum 2018', 'Shigellosis, Cum 2018, flag', 'Shigellosis, Cum 2017', 'Shigellosis, Cum 2017, flag']
but I only need a few:
columns_lambda = lambda k: k.endswith(', Current week') or k == 'Reporting Area' or k == 'MMWR Year' or k == 'MMWR Week'
The filter returns the list of desired columns, list is evaluated:
sss = filter(columns_lambda, ss_.columns)
to_keep = list(sss)
the list of desired columns is unpacked as arguments to dataframe select function that return dataset containing only columns in the list:
dfss = ss_.select(*to_keep)
dfss.columns
The result:
['Reporting Area',
'MMWR Year',
'MMWR Week',
'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week',
'Shiga toxin-producing Escherichia coli, Current week',
'Shigellosis, Current week']
The df.select()
has a complementary pair: http://spark.apache.org/docs/2.4.1/api/python/pyspark.sql.html#pyspark.sql.DataFrame.drop
to drop the list of columns.
It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)
The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.
When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?
, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.
When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.
I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.
All javascript methods are applicable with angularjs because angularjs itself is a javascript framework so you can use indexOf() inside angular directives
<li ng-repeat="select in Items">
<foo ng-repeat="newin select.values">
<span ng-if="newin.label.indexOf(x) !== -1">{{newin.label}}</span></foo>
</li>
//where x is your character to be found
You need to have access as well on the site that you will be iframing. i found the best solution here: https://gist.github.com/MateuszFlisikowski/91ff99551dcd90971377
yourotherdomain.html
<script type='text/javascript' src="js/jquery.min.js"></script>
<script type='text/javascript'>
// Size the parent iFrame
function iframeResize() {
var height = $('body').outerHeight(); // IMPORTANT: If body's height is set to 100% with CSS this will not work.
parent.postMessage("resize::"+height,"*");
}
$(document).ready(function() {
// Resize iframe
setInterval(iframeResize, 1000);
});
</script>
your website with iframe
<iframe src='example.html' id='edh-iframe'></iframe>
<script type='text/javascript'>
// Listen for messages sent from the iFrame
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
// If the message is a resize frame request
if (e.data.indexOf('resize::') != -1) {
var height = e.data.replace('resize::', '');
document.getElementById('edh-iframe').style.height = height+'px';
}
} ,false);
</script>
apply
and transform
There are two major differences between the transform
and apply
groupby methods.
apply
implicitly passes all the columns for each group as a DataFrame to the custom function.transform
passes each column for each group individually as a Series to the custom function.apply
can return a scalar, or a Series or DataFrame (or numpy array or even list).transform
must return a sequence (a one dimensional Series, array or list) the same length as the group.So, transform
works on just one Series at a time and apply
works on the entire DataFrame at once.
It can help quite a bit to inspect the input to your custom function passed to apply
or transform
.
Let's create some sample data and inspect the groups so that you can see what I am talking about:
import pandas as pd
import numpy as np
df = pd.DataFrame({'State':['Texas', 'Texas', 'Florida', 'Florida'],
'a':[4,5,1,3], 'b':[6,10,3,11]})
State a b
0 Texas 4 6
1 Texas 5 10
2 Florida 1 3
3 Florida 3 11
Let's create a simple custom function that prints out the type of the implicitly passed object and then raised an error so that execution can be stopped.
def inspect(x):
print(type(x))
raise
Now let's pass this function to both the groupby apply
and transform
methods to see what object is passed to it:
df.groupby('State').apply(inspect)
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
RuntimeError
As you can see, a DataFrame is passed into the inspect
function. You might be wondering why the type, DataFrame, got printed out twice. Pandas runs the first group twice. It does this to determine if there is a fast way to complete the computation or not. This is a minor detail that you shouldn't worry about.
Now, let's do the same thing with transform
df.groupby('State').transform(inspect)
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
RuntimeError
It is passed a Series - a totally different Pandas object.
So, transform
is only allowed to work with a single Series at a time. It is impossible for it to act on two columns at the same time. So, if we try and subtract column a
from b
inside of our custom function we would get an error with transform
. See below:
def subtract_two(x):
return x['a'] - x['b']
df.groupby('State').transform(subtract_two)
KeyError: ('a', 'occurred at index a')
We get a KeyError as pandas is attempting to find the Series index a
which does not exist. You can complete this operation with apply
as it has the entire DataFrame:
df.groupby('State').apply(subtract_two)
State
Florida 2 -2
3 -8
Texas 0 -2
1 -5
dtype: int64
The output is a Series and a little confusing as the original index is kept, but we have access to all columns.
It can help even more to display the entire pandas object within the custom function, so you can see exactly what you are operating with. You can use print
statements by I like to use the display
function from the IPython.display
module so that the DataFrames get nicely outputted in HTML in a jupyter notebook:
from IPython.display import display
def subtract_two(x):
display(x)
return x['a'] - x['b']
The other difference is that transform
must return a single dimensional sequence the same size as the group. In this particular instance, each group has two rows, so transform
must return a sequence of two rows. If it does not then an error is raised:
def return_three(x):
return np.array([1, 2, 3])
df.groupby('State').transform(return_three)
ValueError: transform must return a scalar value for each group
The error message is not really descriptive of the problem. You must return a sequence the same length as the group. So, a function like this would work:
def rand_group_len(x):
return np.random.rand(len(x))
df.groupby('State').transform(rand_group_len)
a b
0 0.962070 0.151440
1 0.440956 0.782176
2 0.642218 0.483257
3 0.056047 0.238208
transform
If you return just a single scalar from your custom function, then transform
will use it for each of the rows in the group:
def group_sum(x):
return x.sum()
df.groupby('State').transform(group_sum)
a b
0 9 16
1 9 16
2 4 14
3 4 14
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
If you mean what ports are listening, you can open a command prompt and write:
netstat
You can write:
netstat /?
for an explanation of all options.
You can also use
If EXISTS (SELECT 1 FROM dbo.T1 WHERE T1.Name='Scot')
BEGIN
--<Do something>
END
ELSE
BEGIN
--<Do something>
END
In my case the answer is pretty simple. Please check carefully the hardcoded url port: it is 8080. For some reason the value has changed to: for example 3030.
Just refresh the port in your ajax url string to the appropriate one.
conn = new WebSocket('ws://localhost:3030'); //should solve the issue
change type="number" to type="tel"
You can use parameter substitution in the twig globals section of the config:
Parameter config:
parameters:
app.version: 0.1.0
Twig config:
twig:
globals:
version: '%app.version%'
Twig template:
{{ version }}
This method provides the benefit of allowing you to use the parameter in ContainerAware
classes as well, using:
$container->getParameter('app.version');
Ping for the google server or any other server
public boolean isConecctedToInternet() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
return false;
}
I loved the FireFox Header Spy extension so much that i built a HTTP Spy extension for Chrome. I used to use the developer tools too for debugging headers, but now my life is so much better.
Here is a Chrome extension that allows you to view request-, response headers and cookies without any extra clicks right after the page is loaded.
It also handles redirects. It comes with an unobtrusive micro-mode that only shows a hand picked selection of response headers and a normal mode that shows all the information.
https://chrome.google.com/webstore/detail/http-spy/agnoocojkneiphkobpcfoaenhpjnmifb
Enjoy!
I have a rough rule-of-thumb
Functionality: likely to be different in all parts: Interface.
Data, and functionality, parts will be mostly the same, parts different: abstract class.
Data, and functionality, actually working, if extended only with slight changes: ordinary (concrete) class
Data and functionality, no changes planned: ordinary (concrete) class with final modifier.
Data, and maybe functionality: read-only: enum members.
This is very rough and ready and not at all strictly defined, but there is a spectrum from interfaces where everything is intended to be changed to enums where everything is fixed a bit like a read-only file.
It isn't possible to do directly. There are a couple alternatives:
UIBarButtonItem
that validates on tap and pops if the test passesUITextField
delegate method, such as -textFieldShouldReturn:
, which is called after the Return
or Done
button is pressed on the keyboardThe downside of the first option is that the left-pointing-arrow style of the back button cannot be accessed from a custom bar button. So you have to use an image or go with a regular style button.
The second option is nice because you get the text field back in the delegate method, so you can target your validation logic to the specific text field sent to the delegate call-back method.
(Edited.) There are two reasons why it doesn't compile: You're missing a semi-colon at the end of this statement:
array3[i]=e1
Also the findOut method doesn't return any value if the array length is 0. Adding a return 0;
at the end of the method will make it compile. I've no idea if that will make it do what you want though, as I've no idea what you want it to do.
Code Contracts Editor Extensions, a free extension which provides information about inherited contracts for the method you're currently working on, and a list of contracts for any methods that you're calling. Unfortunately, the latter feature conflicts with Resharper, but the former still works fine.
See the Create a video slideshow from images – FFmpeg
If your video does not show the frames correctly If you encounter problems, such as the first image is skipped or only shows for one frame, then use the fps video filter instead of -r for the output framerate
ffmpeg -r 1/5 -i img%03d.png -c:v libx264 -vf fps=25 -pix_fmt yuv420p out.mp4
Alternatively the format video filter can be added to the filter chain to replace -pix_fmt yuv420p like "fps=25,format=yuv420p". The advantage of this method is that you can control which filter goes first
ffmpeg -r 1/5 -i img%03d.png -c:v libx264 -vf "fps=25,format=yuv420p" out.mp4
I tested below parameters, it worked for me
"e:\ffmpeg\ffmpeg.exe" -r 1/5 -start_number 0 -i "E:\images\01\padlock%3d.png" -c:v libx264 -vf "fps=25,format=yuv420p" e:\out.mp4
below parameters also worked but it always skips the first image
"e:\ffmpeg\ffmpeg.exe" -r 1/5 -start_number 0 -i "E:\images\01\padlock%3d.png" -c:v libx264 -r 30 -pix_fmt yuv420p e:\out.mp4
making a video from images placed in different folders
First, add image paths to imagepaths.txt like below.
# this is a comment details https://trac.ffmpeg.org/wiki/Concatenate
file 'E:\images\png\images__%3d.jpg'
file 'E:\images\jpg\images__%3d.jpg'
Sample usage as follows;
"h:\ffmpeg\ffmpeg.exe" -y -r 1/5 -f concat -safe 0 -i "E:\images\imagepaths.txt" -c:v libx264 -vf "fps=25,format=yuv420p" "e:\out.mp4"
-safe 0 parameter prevents Unsafe file name error
Related links
FFmpeg making a video from images placed in different folders
How to do a redirect to another route with react-router?
For example, when a user clicks a link <Link to="/" />Click to route</Link>
react-router will look for /
and you can use Redirect to
and send the user somewhere else like the login route.
From the docs for ReactRouterTraining:
Rendering a
<Redirect>
will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.
import { Route, Redirect } from 'react-router'
<Route exact path="/" render={() => (
loggedIn ? (
<Redirect to="/dashboard"/>
) : (
<PublicHomePage/>
)
)}/>
to: string, The URL to redirect to.
<Redirect to="/somewhere/else"/>
to: object, A location to redirect to.
<Redirect to={{
pathname: '/login',
search: '?utm=your+face',
state: { referrer: currentLocation }
}}/>
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
I placed the libstdc++-6.dll file in the same folder where exe file is generated.
You can use this VSCode Extension called Reload
May be helpful for late comers.
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
using namespace cv;
using namespace std;
int main(int argc, char *argv[])
{
if (argc != 2) {
cout << "Usage: display_Image ImageToLoadandDisplay" << endl;
return -1;
}else{
Mat image;
Mat grayImage;
image = imread(argv[1], IMREAD_COLOR);
if (!image.data) {
cout << "Could not open the image file" << endl;
return -1;
}
else {
int height = image.rows;
int width = image.cols;
cvtColor(image, grayImage, CV_BGR2GRAY);
namedWindow("Display window", WINDOW_AUTOSIZE);
imshow("Display window", image);
namedWindow("Gray Image", WINDOW_AUTOSIZE);
imshow("Gray Image", grayImage);
cvWaitKey(0);
image.release();
grayImage.release();
return 0;
}
}
}
Under Windows 10, the Task Manager can show you cumulative CPU hours. Just head to the "App history" tab and "Delete usage history". Now leave things running for an hour or two:
What this does NOT do is break down usage in browsers by tab. Quite often inactive tabs will do a tremendous amount of work, with each open tab using energy and slowing your PC.
SQL has no built in notion of order, so you need to order by some column for this to be meaningful. Something like this:
select t1.value - t2.value from table t1, table t2
where t1.primaryKey = t2.primaryKey - 1
If you know how to order things but not how to get the previous value given the current one (EG, you want to order alphabetically) then I don't know of a way to do that in standard SQL, but most SQL implementations will have extensions to do it.
Here is a way for SQL server that works if you can order rows such that each one is distinct:
select rank() OVER (ORDER BY id) as 'Rank', value into temp1 from t
select t1.value - t2.value from temp1 t1, temp1 t2
where t1.Rank = t2.Rank - 1
drop table temp1
If you need to break ties, you can add as many columns as necessary to the ORDER BY.
The error message states which logger it is using, so set that logger .level
:
[jasper] Jul 31, 2012 7:15:15 PM org.apache.jasper.compiler.TldLocationsCache tldScanJar
So the logger is org.apache.jasper.compiler.TldLocationsCache
. In your logging.properties
file, add this line:
org.apache.jasper.compiler.TldLocationsCache.level = FINE
Let's say you have:
<a></a>
<(.*)>
would match a></a
where as <(.*?)>
would match a
.
The latter stops after the first match of >
. It checks for one
or 0 matches of .*
followed by the next expression.
The first expression <(.*)>
doesn't stop when matching the first >
. It will continue until the last match of >
.
const list = [
{ qty: 10, size: 'XXL' },
{ qty: 2, size: 'XL' },
{ qty: 8, size: 'M' }
]
list.sort((a, b) => (a.qty > b.qty) ? 1 : -1)
console.log(list)
_x000D_
Out Put :
[
{
"qty": 2,
"size": "XL"
},
{
"qty": 8,
"size": "M"
},
{
"qty": 10,
"size": "XXL"
}
]
By commenting it out this part on my web.config solved my problem:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
But of course you need to make sure you have updated or you have the right version by doing this in your package manager console:
update-package Newtonsoft.Json -reinstall
Two ways. Either create a button and style it so it looks like a link with css, or create a link and use onclick="this.closest('form').submit();return false;"
.
This is how you do it column-wise:
[df[col].update((df[col] - df[col].min()) / (df[col].max() - df[col].min())) for col in df.columns]
Both Query is used for round down the nearest integer in MySQL
The following script ensures that my_finalFunction
runs after your page has been fully loaded with images, stylesheets and external content:
<script>
document.addEventListener("load", my_finalFunction, false);
function my_finalFunction(e) {
/* things to do after all has been loaded */
}
</script>
A good explanation is provided by kirupa on running your code at the right time, see https://www.kirupa.com/html5/running_your_code_at_the_right_time.htm.
You don't tend to execute the make file itself, rather you execute make
, giving it the make file as an argument:
make -f pax.mk
If your make file is actually one of the standard names (like makefile
or Makefile
), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make
man page to see which takes precedence).
you can do that
var filteredFileList = fileList.Where(fl => filterList.Contains(fl.ToString()));
The backdrop to my solution recommendation is the story of a friend who, well into the second week of his first job, wiped half a build-server clean. So the basic task is to figure out if a file exists, and if so, let's delete it. But there are a few treacherous rapids on this river:
Everything is a file.
Scripts have real power only if they solve general tasks
To be general, we use variables
We often use -f force in scripts to avoid manual intervention
And also love -r recursive to make sure we create, copy and destroy in a timely fashion.
Consider the following scenario:
We have the file we want to delete: filesexists.json
This filename is stored in a variable
<host>:~/Documents/thisfolderexists filevariable="filesexists.json"
We also hava a path variable to make things really flexible
<host>:~/Documents/thisfolderexists pathtofile=".."
<host>:~/Documents/thisfolderexists ls $pathtofile
filesexists.json history20170728 SE-Data-API.pem thisfolderexists
So let's see if -e
does what it is supposed to. Does the files exist?
<host>:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $?
0
It does. Magic.
However, what would happen, if the file variable got accidentally be evaluated to nuffin'
<host>:~/Documents/thisfolderexists filevariable=""
<host>:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $?
0
What? It is supposed to return with an error... And this is the beginning of the story how that entire folder got deleted by accident
An alternative could be to test specifically for what we understand to be a 'file'
<host>:~/Documents/thisfolderexists filevariable="filesexists.json"
<host>:~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $?
0
So the file exists...
<host>:~/Documents/thisfolderexists filevariable=""
<host>:~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $?
1
So this is not a file and maybe, we do not want to delete that entire directory
man test
has the following to say:
-b FILE
FILE exists and is block special
-c FILE
FILE exists and is character special
-d FILE
FILE exists and is a directory
-e FILE
FILE exists
-f FILE
FILE exists and is a regular file
...
-h FILE
FILE exists and is a symbolic link (same as -L)
Use the display: inline
CSS property.
Ideal: In the stylesheet:
#container p { display: inline }
Bad/Extreme situation: Inline:
<p style="display:inline">...</p>
You Need to change your code as below:-
<html>
<body>
<div>
<form align="center" method=post>
<input id="mainText" type="text" align="center"placeholder="Search">
<input type="submit" onclick="myFunction()" style="position: absolute; left: 450px"/>
</form>
</div>
<script>
function myFunction(){
$a= document.getElementById("mainText").value;
alert($a);
}
</script>
</body>
</html>
If the goal simply is to list all computer objects with an empty description attribute try this
import-module activedirectory
$domain = "domain.example.com"
Get-ADComputer -Filter '*' -Properties Description | where { $_.Description -eq $null }
For the first non-paste()
answer, we can look at stringr::str_c()
(and then toString()
below). It hasn't been around as long as this question, so I think it's useful to mention that it also exists.
Very simple to use, as you can see.
tmp <- cbind("GAD", "AB")
library(stringr)
str_c(tmp, collapse = ",")
# [1] "GAD,AB"
From its documentation file description, it fits this problem nicely.
To understand how str_c works, you need to imagine that you are building up a matrix of strings. Each input argument forms a column, and is expanded to the length of the longest argument, using the usual recyling rules. The sep string is inserted between each column. If collapse is NULL each row is collapsed into a single string. If non-NULL that string is inserted at the end of each row, and the entire matrix collapsed to a single string.
Added 4/13/2016: It's not exactly the same as your desired output (extra space), but no one has mentioned it either. toString()
is basically a version of paste()
with collapse = ", "
hard-coded, so you can do
toString(tmp)
# [1] "GAD, AB"
Let's say you want to substitute something in an array of string and you don't want to perform the copy-paste on your entire sheet.
Let's take this as an example:
To apply this formula on the entire column (array) in a clean an elegant way, you can do:
=ARRAYFORMULA(SUBSTITUE(A:A, "a", "x"))
It works for 2D-arrays as well, let's say:
=ARRAYFORMULA(SUBSTITUE(A2:D83, "a", "x"))
Use a library like Guava or Commons / IO. They have oneliner methods.
Guava:
Files.toString(file, charset);
Commons / IO:
FileUtils.readFileToString(file, charset);
Without such a library, I'd write a helper method, something like this:
public String readFile(File file, Charset charset) throws IOException {
return new String(Files.readAllBytes(file.toPath()), charset);
}
< == lesser-than == <
> == greater-than == >
Some simple cases can be handled by defining a default in the database schema but that doesn't handle a number of trickier cases including calculated values and keys of other models. For these cases I do this:
after_initialize :defaults
def defaults
unless persisted?
self.extras||={}
self.other_stuff||="This stuff"
self.assoc = [OtherModel.find_by_name('special')]
end
end
I've decided to use the after_initialize but I don't want it to be applied to objects that are found only those new or created. I think it is almost shocking that an after_new callback isn't provided for this obvious use case but I've made do by confirming whether the object is already persisted indicating that it isn't new.
Having seen Brad Murray's answer this is even cleaner if the condition is moved to callback request:
after_initialize :defaults, unless: :persisted?
# ":if => :new_record?" is equivalent in this context
def defaults
self.extras||={}
self.other_stuff||="This stuff"
self.assoc = [OtherModel.find_by_name('special')]
end
Spring dependency inject help you to remove coupling from your classes. Instead of creating object like this:
UserService userService = new UserServiceImpl();
You will be using this after introducing DI:
@Autowired
private UserService userService;
For achieving this you need to create a bean of your service in your ServiceConfiguration
file. After that you need to import that ServiceConfiguration
class to your WebApplicationConfiguration
class so that you can autowire that bean into your Controller like this:
public class AccController {
@Autowired
private UserService userService;
}
You can find a java configuration based POC here example.
Htmlparser2 by FB55 seems to be a good alternative.
Connection cn = DriverManager.getConnection("Host","user","pass");
Statement st = cn.createStatement("Ur Requet Sql");
int ret = st.execute();
For those looking to control the space between a dynamic number of columns, try:
<div class="row no-gutters">
<div class="col">
<div class="inner">
<!-- content here -->
</div>
</div>
<div class="col">
<div class="inner">
<!-- content here -->
</div>
</div>
<!-- etc. -->
</div>
CSS:
.col:not(:last-child) .inner {
margin: 2px; // Or whatever you want your spacing to be
}
If it's about just one property - let's say you want to temporarily change some default, for instance disable CA checking: you can do it with
npm config set ca ""
To come back to the defaults for that setting, simply
npm config delete ca
To verify, use npm config get ca
.
You can't use $(this)
since jQuery doesn't know what it is there. You seem to be overcomplicating things. You can do $('#content h1.aktiv').hide()
. There's no reason to test to see if the class exists.
They pretty much got it there... just like a checkbox, all you have to do is add the attribute checked="checked" like so:
<input type="radio" checked="checked">
...and you got it.
Cheers!
Simply call
print(unknownDataType.runtimeType)
on the data.
An excellent answer given by msigman. I just want to add that in windows 10 you can find IIS Express System Tray (32 bit)
process under Visual Studio
process:
Shouldn't creating a new Runnable class make a new second thread?
No. new Runnable
does not create second Thread
.
What is the purpose of the Runnable class here apart from being able to pass a Runnable class to postAtTime?
Runnable
is posted to Handler
. This task runs in the thread, which is associated with Handler
.
If Handler
is associated with UI Thread, Runnable
runs in UI Thread.
If Handler
is associated with other HandlerThread
, Runnable runs in HandlerThread
To explicitly associate Handler to your MainThread ( UI Thread), write below code.
Handler mHandler = new Handler(Looper.getMainLooper();
If you write is as below, it uses HandlerThread Looper.
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
Handler requestHandler = new Handler(handlerThread.getLooper());
In Microsoft Excel Office 2007 try installing "Web Service Reference Tool" plugin. And use the WSDL and add the web-services. And use following code in module to fetch the necessary data from the web-service.
Sub Demo()
Dim XDoc As MSXML2.DOMDocument
Dim xEmpDetails As MSXML2.IXMLDOMNode
Dim xParent As MSXML2.IXMLDOMNode
Dim xChild As MSXML2.IXMLDOMNode
Dim query As String
Dim Col, Row As Integer
Dim objWS As New clsws_GlobalWeather
Set XDoc = New MSXML2.DOMDocument
XDoc.async = False
XDoc.validateOnParse = False
query = objWS.wsm_GetCitiesByCountry("india")
If Not XDoc.LoadXML(query) Then 'strXML is the string with XML'
Err.Raise XDoc.parseError.ErrorCode, , XDoc.parseError.reason
End If
XDoc.LoadXML (query)
Set xEmpDetails = XDoc.DocumentElement
Set xParent = xEmpDetails.FirstChild
Worksheets("Sheet3").Cells(1, 1).Value = "Country"
Worksheets("Sheet3").Cells(1, 1).Interior.Color = RGB(65, 105, 225)
Worksheets("Sheet3").Cells(1, 2).Value = "City"
Worksheets("Sheet3").Cells(1, 2).Interior.Color = RGB(65, 105, 225)
Row = 2
Col = 1
For Each xParent In xEmpDetails.ChildNodes
For Each xChild In xParent.ChildNodes
Worksheets("Sheet3").Cells(Row, Col).Value = xChild.Text
Col = Col + 1
Next xChild
Row = Row + 1
Col = 1
Next xParent
End Sub
My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!
I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:
# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root virsh start download
I think this is correct, and hope it helps someone else too.
as say as @treecoder
In case of the
root
directive, full path is appended to the root including the location part, whereas in case of thealias
directive, only the portion of the path NOT including the location part is appended to the alias.
A picture is worth a thousand words
for root
:
for alias
:
As of Aug 29, 2013, Github's documentation claim that:
Warning: Project pages subpaths like http://username.github.io/projectname will not be redirected to a project's custom domain.
The absolute simplest way to accomplish this, is with basename()
echo basename('http://domain.com/artist/song/music-videos/song-title/9393903');
Which will print
9393903
Of course, if there is a query string at the end it will be included in the returned value, in which case the accepted answer is a better solution.
I collected together scripts from my web scraping work into this bit-bucket library.
Example script for your case:
from webscraping import download, xpath
D = download.Download()
html = D.get('http://example.com')
for row in xpath.search(html, '//table[@class="spad"]/tbody/tr'):
cols = xpath.search(row, '/td')
print 'Sunrise: %s, Sunset: %s' % (cols[1], cols[2])
Output:
Sunrise: 08:39, Sunset: 16:08
Sunrise: 08:39, Sunset: 16:09
Sunrise: 08:39, Sunset: 16:10
Sunrise: 08:40, Sunset: 16:10
Sunrise: 08:40, Sunset: 16:11
Sunrise: 08:40, Sunset: 16:12
Sunrise: 08:40, Sunset: 16:13
Thing
is an inner class with an automatic connection to an instance of Hello
. You get a compile error because there is no instance of Hello
for it to attach to. You can fix it most easily by changing it to a static nested class which has no connection:
static class Thing
npm install -g npm@version
in which you want to downgrade
npm install -g [email protected]
SELECT referencing_schema_name, referencing_entity_name,
case when is_caller_dependent=0 then 'NO' ELSE 'Yes'
END AS is_caller_dependent FROM sys.dm_sql_referencing_entities ('Tablename', 'OBJECT');
I was trying to to the same, I found lots of information on reading .docx but much less on .doc; Anyway, I managed to read the text using the following:
import win32com.client
word = win32com.client.Dispatch("Word.Application")
word.visible = False
wb = word.Documents.Open("myfile.doc")
doc = word.ActiveDocument
print(doc.Range().Text)
Ajax Submit form with out page refresh by using jquery ajax method first include library jquery.js and jquery-form.js then create form in html:
<form action="postpage.php" method="POST" id="postForm" >
<div id="flash_success"></div>
name:
<input type="text" name="name" />
password:
<input type="password" name="pass" />
Email:
<input type="text" name="email" />
<input type="submit" name="btn" value="Submit" />
</form>
<script>
var options = {
target: '#flash_success', // your response show in this ID
beforeSubmit: callValidationFunction,
success: YourResponseFunction
};
// bind to the form's submit event
jQuery('#postForm').submit(function() {
jQuery(this).ajaxSubmit(options);
return false;
});
});
function callValidationFunction()
{
// validation code for your form HERE
}
function YourResponseFunction(responseText, statusText, xhr, $form)
{
if(responseText=='success')
{
$('#flash_success').html('Your Success Message Here!!!');
$('body,html').animate({scrollTop: 0}, 800);
}else
{
$('#flash_success').html('Error Msg Here');
}
}
</script>
Well, it doesn't get much better than that. Officially, you should use
dataGridView1.DataSource = typeof(List);
dataGridView1.DataSource = itemStates;
It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.
Google is your friend - first hit - also you might first have a look at what serialization is.
It marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally.
Example from there, slightly modified (thanks @pgras):
public class Foo implements Serializable
{
private String saveMe;
private transient String dontSaveMe;
private transient String password;
//...
}
And another expansion:
# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)
If you want to assign new column names you can do following on data.frame
:
# an identical effect can be achieved with colnames()
names(d) <- LETTERS[1:5]
> d
A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3
If you, however run previous command on matrix
, you'll mess things up:
names(m) <- LETTERS[1:5]
> m
[,1] [,2] [,3] [,4] [,5]
[1,] 3 2 4 3 4
[2,] 2 2 3 1 3
[3,] 3 2 1 2 4
[4,] 4 3 3 3 2
[5,] 1 3 2 4 3
attr(,"names")
[1] "A" "B" "C" "D" "E" NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[20] NA NA NA NA NA NA
Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames()
.
So there...
As already answered, the C standards have no way to directly write binary numbers. There are compiler extensions, however, and apparently C++14 includes the 0b
prefix for binary. (Note that this answer was originally posted in 2010.)
One popular workaround is to include a header file with helper macros. One easy option is also to generate a file that includes macro definitions for all 8-bit patterns, e.g.:
#define B00000000 0
#define B00000001 1
#define B00000010 2
…
This results in only 256 #define
s, and if larger than 8-bit binary constants are needed, these definitions can be combined with shifts and ORs, possibly with helper macros (e.g., BIN16(B00000001,B00001010)
). (Having individual macros for every 16-bit, let alone 32-bit, value is not plausible.)
Of course the downside is that this syntax requires writing all the leading zeroes, but this may also make it clearer for uses like setting bit flags and contents of hardware registers. For a function-like macro resulting in a syntax without this property, see bithacks.h
linked above.
When you run composer update
, composer
generates a file called composer.lock
which lists all your packages and the currently installed versions. This allows you to later run composer install
, which will install the packages listed in that file, recreating the environment that you were last using.
It appears from your log that some of the versions of packages that are listed in your composer.lock
file are no longer available. Thus, when you run composer install
, it complains and fails. This is usually no big deal - just run composer update
and it will attempt to build a set of packages that work together and write a new composer.lock
file.
However, you're running into a different problem. It appears that, in your composer.json
file, the original developer has added some pre- or post- update actions that are failing, specifically a php artisan migrate
command. This can be avoided by running the following: composer update --no-scripts
This will run the composer update but will skip over the scripts added to the file. You should be able to successfully run the update this way.
However, this does not solve the problem long-term. There are two problems:
A migration is for database changes, not random stuff like compiling assets. Go through the migrations and remove that code from there.
Assets should not be compiled each time you run composer update
. Remove that step from the composer.json
file.
From what I've read, best practice seems to be compiling assets on an as-needed basis during development (ie. when you're making changes to your LESS files - ideally using a tool like gulp.js) and before deployment.
You need to use WITH ROLLBACK IMMEDIATE
to boot other conections out with no regards to what or who is is already using it.
Or use WITH NO_WAIT
to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details
What about:
Validating names is a difficult issue, because valid names are not only consisting of the letters A-Z.
At least you should use the Unicode property for letters and add more special characters. A first approach could be e.g.:
String regx = "^[\\p{L} .'-]+$";
\\p{L}
is a Unicode Character Property that matches any kind of letter from any language
In addition to short-circuiting, another thing to keep in mind is that doing a bitwise logic operation on values that can be other than 0 or 1 has a very different meaning than conditional logic. While it USUALLY is the same for |
and ||
, with &
and &&
you get very different results (e.g. 2 & 4
is 0/false while 2 && 4
is 1/true).
If the thing you're getting from a function is actually an error code and you're testing for non-0-ness, this can matter quite a lot.
This isn't as much of an issue in Java where you have to explicitly typecast to boolean or compare with 0 or the like, but in other languages with similar syntax (C/C++ et al) it can be quite confusing.
Also, note that & and | can only apply to integer-type values, and not everything that can be equivalent to a boolean test. Again, in non-Java languages, there are quite a few things that can be used as a boolean with an implicit != 0
comparison (pointers, floats, objects with an operator bool()
, etc.) and bitwise operators are almost always nonsensical in those contexts.
I agree with Icarus (would have commented if I could), but instead of using a CustomObject class, I would use a Dictionary (in case Facebook adds something).
private class MyFacebookClass
{
public IList<IDictionary<string, string>> data { get; set; }
}
or
private class MyFacebookClass
{
public IList<IDictionary<string, object>> data { get; set; }
}
Assuming you only have the list of items and a list of true/required indices, this should be the fastest:
property_asel = [ property_a[index] for index in good_indices ]
This means the property selection will only do as many rounds as there are true/required indices. If you have a lot of property lists that follow the rules of a single tags (true/false) list you can create an indices list using the same list comprehension principles:
good_indices = [ index for index, item in enumerate(good_objects) if item ]
This iterates through each item in good_objects (while remembering its index with enumerate) and returns only the indices where the item is true.
For anyone not getting the list comprehension, here is an English prose version with the code highlighted in bold:
list the index for every group of index, item that exists in an enumeration of good objects, if (where) the item is True
Same here on Ubuntu 18.04
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'
/run/mysqld/
?> / ll /var/run
lrwxrwxrwx 1 root root 4 Nov 1 2018 /var/run -> /run/
hmmm... Does that mean a symbolic link won't work? That's weird...
You can use this:
Range("MyTable[#Data]").Rows.Count
You have to distinguish between a table which has either one row of data or no data, as the previous code will return "1" for both cases. Use this to test for an empty table:
If WorksheetFunction.CountA(Range("MyTable[#Data]"))
<context:component-scan base-package="x.y.z"/>
will work since the rest of the packages are sub packages of "x.y.z". Thus, you dont need to mention each package individually.
You could also use a core dump and then examine it with gdb. To get useful information you also need to compile with the -g
flag.
Whenever you get the message:
Segmentation fault (core dumped)
a core file is written into your current directory. And you can examine it with the command
gdb your_program core_file
The file contains the state of the memory when the program crashed. A core dump can be useful during the deployment of your software.
Make sure your system doesn't set the core dump file size to zero. You can set it to unlimited with:
ulimit -c unlimited
Careful though! that core dumps can become huge.
Following query can be used to get all privileges of one user .. Just provide user name in first query and you will get all privileges to that
WITH users AS (SELECT 'SCHEMA_USER' usr FROM dual), Roles AS (SELECT granted_role FROM dba_role_privs rp JOIN users ON rp.GRANTEE = users.usr UNION SELECT granted_role FROM role_role_privs WHERE role IN (SELECT granted_role FROM dba_role_privs rp JOIN users ON rp.GRANTEE = users.usr)), tab_privilage AS (SELECT OWNER, TABLE_NAME, PRIVILEGE FROM role_tab_privs rtp JOIN roles r ON rtp.role = r.granted_role UNION SELECT OWNER, TABLE_NAME, PRIVILEGE FROM Dba_Tab_Privs dtp JOIN Users ON dtp.grantee = users.usr), sys_privileges AS (SELECT privilege FROM dba_sys_privs dsp JOIN users ON dsp.grantee = users.usr) SELECT * FROM tab_privilage ORDER BY owner, table_name --SELECT * FROM sys_privileges