If the src is https and the certificate has expired -- and even if you've made an exception -- firefox will still display this error message, and you can see the exact reason why if you look at the request under the network tab.
Place this line before the closing script tag,writing from memory:
window.onload = GetTimeZoneOffset;
i think the question is how to call the javascript function on pageload
First you need to create the Hidden Field properly
<asp:HiddenField ID="hdntxtbxTaksit" runat="server"></asp:HiddenField>
Then you need to set value to the hidden field
If you aren't using Jquery you should use it:
document.getElementById("<%= hdntxtbxTaksit.ClientID %>").value = "test";
If you are using Jquery, this is how it should be:
$("#<%= hdntxtbxTaksit.ClientID %>").val("test");
You have to use $_POST['date']
instead of $date
if it's coming from a POST request ($_GET if it's a GET request).
This isn't an answer, sadly. After running into the intermittent error for some time and finally being annoyed enough to try to fix it, I have yet to find a fix. I have, however, determined a recipe for reproducing my problem, which might help others.
In my case it is SOLELY a localhost problem, on my dev machine that also has the app's DB. It's a .NET 2.0 app I'm editing with VS2005. The Win7 64 bit machine also has VS2008 and .NET 3.5 installed.
Here's what will generate the error, from a variety of forms:
A minute or two delay "waiting for localhost" and then "Connection was reset" by the browser, and global.asax
's application error trap logs:
Application_Error event: Invalid length for a Base-64 char array.
Stack Trace:
at System.Convert.FromBase64String(String s)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState)
at System.Web.UI.HiddenFieldPageStatePersister.Load()
In this case, it is not the SIZE of the viewstate, but something to do with page and/or viewstate caching that seems to be biting me. Setting <pages>
parameters enableEventValidation="false"
, and viewStateEncryption="Never"
in the Web.config
did not change the behavior. Neither did setting the maxPageStateFieldLength
to something modest.
Simplest working solution for flow window (tested at Chrome):
<form action='...' method=post target="result" onsubmit="window.open('','result','width=800,height=400');">
<input name="..">
....
</form>
Well ya you can do that in this way.
<input type="text" name="address" id="address">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
<input type="button" onclick="showAddress(address.value)" value="ShowMap"/>
Java Script
function showAddress(address){
alert("This is address :"+address)
}
That is one example for the same. and that will run.
The proper way to do it is using the ng-options
directive. The HTML would look like this.
<select ng-model="selectedTestAccount"
ng-options="item.Id as item.Name for item in testAccounts">
<option value="">Select Account</option>
</select>
JavaScript:
angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
method: 'GET',
url: '/Admin/GetTestAccounts',
data: { applicationId: 3 }
}).success(function (result) {
$scope.testAccounts = result;
});
});
You'll also need to ensure angular is run on your html and that your module is loaded.
<html ng-app="test">
<body ng-controller="DemoCtrl">
....
</body>
</html>
Create user dependency upon the database connect tools
sql plus
SQL> connect as sysdba;
Enter user-name: sysdba
Enter password:
Connected.
SQL> ALTER USER hr account unlock identified by hr;
User altered
then create user on sql plus and sql developer
Let me give a few examples with some alternatives to avoid a ConcurrentModificationException
.
Suppose we have the following collection of books
List<Book> books = new ArrayList<Book>();
books.add(new Book(new ISBN("0-201-63361-2")));
books.add(new Book(new ISBN("0-201-63361-3")));
books.add(new Book(new ISBN("0-201-63361-4")));
Collect and Remove
The first technique consists in collecting all the objects that we want to delete (e.g. using an enhanced for loop) and after we finish iterating, we remove all found objects.
ISBN isbn = new ISBN("0-201-63361-2");
List<Book> found = new ArrayList<Book>();
for(Book book : books){
if(book.getIsbn().equals(isbn)){
found.add(book);
}
}
books.removeAll(found);
This is supposing that the operation you want to do is "delete".
If you want to "add" this approach would also work, but I would assume you would iterate over a different collection to determine what elements you want to add to a second collection and then issue an addAll
method at the end.
Using ListIterator
If you are working with lists, another technique consists in using a ListIterator
which has support for removal and addition of items during the iteration itself.
ListIterator<Book> iter = books.listIterator();
while(iter.hasNext()){
if(iter.next().getIsbn().equals(isbn)){
iter.remove();
}
}
Again, I used the "remove" method in the example above which is what your question seemed to imply, but you may also use its add
method to add new elements during iteration.
Using JDK >= 8
For those working with Java 8 or superior versions, there are a couple of other techniques you could use to take advantage of it.
You could use the new removeIf
method in the Collection
base class:
ISBN other = new ISBN("0-201-63361-2");
books.removeIf(b -> b.getIsbn().equals(other));
Or use the new stream API:
ISBN other = new ISBN("0-201-63361-2");
List<Book> filtered = books.stream()
.filter(b -> b.getIsbn().equals(other))
.collect(Collectors.toList());
In this last case, to filter elements out of a collection, you reassign the original reference to the filtered collection (i.e. books = filtered
) or used the filtered collection to removeAll
the found elements from the original collection (i.e. books.removeAll(filtered)
).
Use Sublist or Subset
There are other alternatives as well. If the list is sorted, and you want to remove consecutive elements you can create a sublist and then clear it:
books.subList(0,5).clear();
Since the sublist is backed by the original list this would be an efficient way of removing this subcollection of elements.
Something similar could be achieved with sorted sets using NavigableSet.subSet
method, or any of the slicing methods offered there.
Considerations:
What method you use might depend on what you are intending to do
removeAl
technique works with any Collection (Collection, List, Set, etc). ListIterator
technique obviously only works with lists, provided that their given ListIterator
implementation offers support for add and remove operations. Iterator
approach would work with any type of collection, but it only supports remove operations.ListIterator
/Iterator
approach the obvious advantage is not having to copy anything since we remove as we iterate. So, this is very efficient. removeAll
approach the disadvantage is that we have to iterate twice. First we iterate in the foor-loop looking for an object that matches our removal criteria, and once we have found it, we ask to remove it from the original collection, which would imply a second iteration work to look for this item in order to remove it. Iterator
interface is marked as "optional" in Javadocs, which means that there could be Iterator
implementations that throw UnsupportedOperationException
if we invoke the remove method. As such, I'd say this approach is less safe than others if we cannot guarantee the iterator support for removal of elements.open terminal and type
sudo sh -c 'echo /usr/local/mysql/bin > /etc/paths.d/mysql'
then close terminal and open a new terminal and type
mysql -u root -p
hit enter, and it will ask you for password
I have found this solution on https://teamtreehouse.com/community/says-mysql-command-not-found
now to set new password type
ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
Based on antoinepairet's comment/example:
Using uib-collapse
attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<div class="collapse navbar-collapse" uib-collapse="navCollapsed">
<ul class="nav navbar-nav">
...
</ul>
</div>
</nav>
I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:
The only variation from the official bootstrap example is the addition of ng-
attributes noted by comments, below:
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- note the ng-class here -->
<div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">
<ul class="nav navbar-nav">
...
Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)
This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!
If you want an interactive heatmap from a Pandas DataFrame and you are running a Jupyter notebook, you can try the interactive Widget Clustergrammer-Widget, see interactive notebook on NBViewer here, documentation here
And for larger datasets you can try the in-development Clustergrammer2 WebGL widget (example notebook here)
This answer is not the direct answer for the question. But it should help you figure out which solution fits best for your problem.
When analysing the problem you should activate the debug option -vv
Then rsync will output which files are included or excluded by which pattern:
building file list ...
[sender] hiding file FILE1 because of pattern FILE1*
[sender] showing file FILE2 because of pattern *
Using my approach, you can write the button click event handler in the 'classical way', just like how you did it in VB or MFC ;)
Suppose we have a class for a frame window which contains 2 buttons:
class MainWindow {
Jbutton searchButton;
Jbutton filterButton;
}
You can use my 'router' class to route the event back to your MainWindow class:
class MainWindow {
JButton searchButton;
Jbutton filterButton;
ButtonClickRouter buttonRouter = new ButtonClickRouter(this);
void initWindowContent() {
// create your components here...
// setup button listeners
searchButton.addActionListener(buttonRouter);
filterButton.addActionListener(buttonRouter);
}
void on_searchButton() {
// TODO your handler goes here...
}
void on_filterButton() {
// TODO your handler goes here...
}
}
Do you like it? :)
If you like this way and hate the Java's anonymous subclass way, then you are as old as I am. The problem of 'addActionListener(new ActionListener {...})' is that it squeezes all button handlers into one outer method which makes the programme look wired. (in case you have a number of buttons in one window)
Finally, the router class is at below. You can copy it into your programme without the need for any update.
Just one thing to mention: the button fields and the event handler methods must be accessible to this router class! To simply put, if you copy this router class in the same package of your programme, your button fields and methods must be package-accessible. Otherwise, they must be public.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ButtonClickRouter implements ActionListener {
private Object target;
ButtonClickRouter(Object target) {
this.target = target;
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
// get source button
Object sourceButton = actionEvent.getSource();
// find the corresponding field of the button in the host class
Field fieldOfSourceButton = null;
for (Field field : target.getClass().getDeclaredFields()) {
try {
if (field.get(target).equals(sourceButton)) {
fieldOfSourceButton = field;
break;
}
} catch (IllegalAccessException e) {
}
}
if (fieldOfSourceButton == null)
return;
// make the expected method name for the source button
// rule: suppose the button field is 'searchButton', then the method
// is expected to be 'void on_searchButton()'
String methodName = "on_" + fieldOfSourceButton.getName();
// find such a method
Method expectedHanderMethod = null;
for (Method method : target.getClass().getDeclaredMethods()) {
if (method.getName().equals(methodName)) {
expectedHanderMethod = method;
break;
}
}
if (expectedHanderMethod == null)
return;
// fire
try {
expectedHanderMethod.invoke(target);
} catch (IllegalAccessException | InvocationTargetException e) { }
}
}
I'm a beginner in Java (not in programming), so maybe there are anything inappropriate in the above code. Review it before using it, please.
@Synxmax's answer is correct when using a Service
and the MediaPlayer
class, however you also need to declare the Service
in the Manifest for this to work, like so:
<service
android:enabled="true"
android:name="com.package.name.BackgroundSoundService" />
Neither malloc or call by reference are needed. You can declare a pointer within the function and set it to the string/array you'd like to return.
Using @Gewure's code as the basis:
char *getStringNoMalloc(void){
char string[100] = {};
char *s_ptr = string;
strcat(string, "bla");
strcat(string, "/");
strcat(string, "blub");
//INSIDE this function "string" is OK
printf("string : '%s'\n", string);
return s_ptr;
}
works perfectly.
With a non-loop version of the code in the original question:
char *foo(int x){
char a[1000];
char *a_ptr = a;
char *b = "blah";
strcpy(a, b);
return a_ptr;
}
select T1.name, count (*)
from (select name from Results
union
select name from Archive_Results) as T1
group by T1.name order by T1.name
I will select Session, first of all session is more secure then cookies, cookies is client site data and session is server site data. Cookies is used to identify a user, because it is small pieces of code that is embedded my server with user computer browser. On the other hand Session help you to secure you identity because web server don’t know who you are because HTTP address changes the state 192.168.0.1 to 765487cf34ert8ded…..or something else numbers with the help of GET and POST methods. Session stores data of user in unique ID session that even user ID can’t match with each other. Session stores single user information in all pages of one application. Cookies expire is set with the help of setcookies() whereas session expire is not set it is expire when user turn off browsers.
May be you are using this checking :
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
}
To resolve this you need to import android.provider.DocumentsContract
class.
To resolve this issue you'll need to set the build SDK version to 19 (4.4) or higher to have API level 19 symbols available while compiling.
First, use the SDK Manager to download API 19 if you don't have it yet. Then, configure your project to use API 19:
I found this answer from here
Thanks .
Several answers recommend using a statement something like this:
DBCC CHECKIDENT (mytable, RESEED, 0)
But the OP said "deleted some records", which may not be all of them, so a value of 0 is not always the right one. Another answer suggested automatically finding the maximum current value and reseeding to that one, but that runs into trouble if there are no records in the table, and thus max() will return NULL. A comment suggested using simply
DBCC CHECKIDENT (mytable)
to reset the value, but another comment correctly stated that this only increases the value to the maximum already in the table; this will not reduce the value if it is already higher than the maximum in the table, which is what the OP wanted to do.
A better solution combines these ideas. The first CHECKIDENT resets the value to 0, and the second resets it to the highest value currently in the table, in case there are records in the table:
DBCC CHECKIDENT (mytable, RESEED, 0)
DBCC CHECKIDENT (mytable)
As multiple comments have indicated, make sure there are no foreign keys in other tables pointing to the deleted records. Otherwise those foreign keys will point at records you create after reseeding the table, which is almost certainly not what you had in mind.
You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo rm -rf /var/lib/mysql
I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!
Please make use of the code below to display images inline:
<img style='vertical-align:middle;' src='somefolder/icon.gif'>
<div style='vertical-align:middle; display:inline;'>
Your text here
</div>
You can use hasOwnProperty
method to check this
> localStorage.setItem('foo', 123)
undefined
> localStorage.hasOwnProperty('foo')
true
> localStorage.hasOwnProperty('bar')
false
Works in current versions of Chrome(Mac), Firefox(Mac) and Safari.
C++ provides a good mechanism to manage the life time of an object though class/struct constructs. This is one of the best features of C++ over other languages.
When you have member variables exposed through ref or pointer it violates the encapsulation in principle. This idiom enables the consumer of the class to change the state of an object of A without it(A) having any knowledge or control of it. It also enables the consumer to hold on to a ref/pointer to A's internal state, beyond the life time of the object of A. This is bad design. Instead the class could be refactored to hold a ref/pointer to the shared object (not own it) and these could be set using the constructor (Mandate the life time rules). The shared object's class may be designed to support multithreading/concurrency as the case may apply.
To have it send it as a CSV and have it give the file name, use header():
header('Content-type: text/csv');
header('Content-disposition: attachment; filename="myfile.csv"');
As far as making the CSV itself, you would just loop through the result set, formatting the output and sending it, just like you would any other content.
If a user from Safari Web browser (Apple devices) visit your site. The browser tries to fetch the site icon if it is not defined in <head>
in the following order:
To resolve this issue either define an icon for safari web browsers or apple devices. Add something like this to head section of your site:
<link rel="apple-touch-icon" href="/custom_icon.png"/>
If you want to keep <head>
clean then upload the icon to root dir of your site with proper name.
The default icon size is 57px.
You can find more details on iOS developer library.
Ran into the same issue and researched this for a few minutes.
I was taught to use Windows 3.1 and DOS, remember those days? Shortly after I worked with Macintosh computers strictly for some time, then began to sway back to Windows after buying a x64-bit machine.
There are actual reasons behind these changes (some would say historical significance), that are necessary for programmers to continue their work.
Most of the changes are mentioned above:
Program Files
vs Program Files (x86)
In the beginning the 16/86bit files were written on, '86' Intel processors.
System32
really means System64
(on 64-bit Windows)
When developers first started working with Windows7, there were several compatibility issues where other applications where stored.
SysWOW64
really means SysWOW32
Essentially, in plain english, it means 'Windows on Windows within a 64-bit machine'. Each folder is indicating where the DLLs are located for applications it they wish to use them.
Here are two links with all the basic info you need:
Hope this clears things up!
Using ES6.
let arr = [22,1,4,55,7,8,9,3,2,4];
let {0 : first ,[arr.length - 1] : last} = arr;
console.log(first, last);
or
let {0 : first ,length : l, [l - 1] : last} = [22,1,4,55,7,8,9,3,2,4];
console.log(first, last);
A better solution is not to make your page dependable on zoom settings. If you set limits like the one you are proposing, you are limiting accessibility. If someone cannot read your text well, they just won't be able to change that. I would use proper CSS to make it look nice in any zoom.
If your really insist, take a look at this question on how to detect zoom level using JavaScript (nightmare!): How to detect page zoom level in all modern browsers?
The pid files contains the process id (a number) of a given program. For example, Apache HTTPD may write its main process number to a pid file - which is a regular text file, nothing more than that - and later use the information there contained to stop itself. You can also use that information to kill the process yourself, using cat filename.pid | xargs kill
From Microsoft documentation:
PAGEIOLATCH_SH
Occurs when a task is waiting on a latch for a buffer that is in an
I/O
request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.
In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.
If your query is like this:
Select * from <table> where <col1> = <value> order by <PrimaryKey>
, check that you have a composite index on (col1, col_primary_key)
.
If you don't have one, then you'll need either a full INDEX SCAN
if the PRIMARY KEY
is chosen, or a SORT
if an index on col1
is chosen.
Both of them are very disk I/O
consuming operations on large tables.
This message pops up, when the database user does not exist. Compare the manual here.
Multiple local databases cannot be the explanation. Roles are valid cluster-wide. The manual again:
Note that roles are defined at the database cluster level, and so are valid in all databases in the cluster.
You must be ending up in another database-cluster. That would be another server running on the same machine, listening to a different port. Or, more likely, on a different machine.
Could it be that the message comes, in fact, from the remote server?
Matheus de Oliveira created handy functions for JSON CRUD operations in postgresql. They can be imported using the \i directive. Notice the jsonb fork of the functions if jsonb if your data type.
9.3 json https://gist.github.com/matheusoliveira/9488951
9.4 jsonb https://gist.github.com/inindev/2219dff96851928c2282
I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.
I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.
Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.
Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.
sh
is interpreting the &&
as a shell operator. Change it to -a
, that’s [
’s conjunction operator:
[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ]
Also, you should always quote the variables, because [
gets confused when you leave off arguments.
#include<stdio.h>
int main()
{
int i,j,n,b;
printf("Enter no of rows ");
scanf("%d",&n);
b=n;
for(i=1;i<=n;++i)
{
for(j=1;j<=i;j++)
{
printf("%*d",b,j);
b=1;
}
b=n;
b=b-i;
printf("\n");
}
return 0;
}
A one-liner for object configs:
new Date(new Date().setHours(0,0,0,0));
When creating an element:
dateFieldConfig = {
name: "mydate",
value: new Date(new Date().setHours(0, 0, 0, 0)),
}
This solution has really helped me :
By using below two methods we can clear data programatically
public void clearApplicationData() {
File cacheDirectory = getCacheDir();
File applicationDirectory = new File(cacheDirectory.getParent());
if (applicationDirectory.exists()) {
String[] fileNames = applicationDirectory.list();
for (String fileName : fileNames) {
if (!fileName.equals("lib")) {
deleteFile(new File(applicationDirectory, fileName));
}
}
}
}
public static boolean deleteFile(File file) {
boolean deletedAll = true;
if (file != null) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
}
} else {
deletedAll = file.delete();
}
}
return deletedAll;
}
In batch you could do it like this:
@echo off
setlocal EnableDelayedExpansion
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do (
set "var=%%sxyz"
svn co "!var!"
)
If you don't need the variable !var!
elsewhere in the loop, you could simplify that to
@echo off
setlocal
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do svn co "%%sxyz"
However, like C.B. I'd prefer PowerShell if at all possible:
$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object {
$var = "${_}xyz" # alternatively: $var = $_ + 'xyz'
svn co $var
}
Again, this could be simplified if you don't need $var
elsewhere in the loop:
$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object { svn co "${_}xyz" }
I faced this problem while trying to extend an existing class from GitHub. I'm gonna try to explain myself, first writing the class as I though it should be, and then the class as it is now.
What I though
namespace mycompany\CutreApi;
use mycompany\CutreApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function whatever(): ClassOfVendor
{
return new ClassOfVendor();
}
}
What I've finally done
namespace mycompany\CutreApi;
use \vendor\AwesomeApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function whatever(): ClassOfVendor
{
return new \mycompany\CutreApi\ClassOfVendor();
}
}
So seems that this errror raises also when you're using a method that return a namespaced class, and you try to return the same class but with other namespace. Fortunately I have found this solution, but I do not fully understand the benefit of this feature in php 7.2, for me it is normal to rewrite existing class methods as you need them, including the redefinition of input parameters and / or even behavior of the method.
One downside of the previous aproach, is that IDE's could not recognise the new methods implemented in \mycompany\CutreApi\ClassOfVendor(). So, for now, I will go with this implementation.
Currently done
namespace mycompany\CutreApi;
use mycompany\CutreApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function getWhatever(): ClassOfVendor
{
return new ClassOfVendor();
}
}
So, instead of trying to use "whatever" method, I wrote a new one called "getWhatever". In fact both of them are doing the same, just returning a class, but with diferents namespaces as I've described before.
Hope this can help someone.
This is actually a pretty challenging problem that you are asking. Computing sentence similarity requires building a grammatical model of the sentence, understanding equivalent structures (e.g. "he walked to the store yesterday" and "yesterday, he walked to the store"), finding similarity not just in the pronouns and verbs but also in the proper nouns, finding statistical co-occurences / relationships in lots of real textual examples, etc.
The simplest thing you could try -- though I don't know how well this would perform and it would certainly not give you the optimal results -- would be to first remove all "stop" words (words like "the", "an", etc. that don't add much meaning to the sentence) and then run word2vec on the words in both sentences, sum up the vectors in the one sentence, sum up the vectors in the other sentence, and then find the difference between the sums. By summing them up instead of doing a word-wise difference, you'll at least not be subject to word order. That being said, this will fail in lots of ways and isn't a good solution by any means (though good solutions to this problem almost always involve some amount of NLP, machine learning, and other cleverness).
So, short answer is, no, there's no easy way to do this (at least not to do it well).
mkdir -p ~/.ssh/
cat your_key > ~/.ssh/authorized_keys
cat your_key >> ~/.ssh/authorized_keys
The detach/copy/attach method will take down the database. That's not something you'd want in production.
The backup/restore will only work if you have write permissions to the production server. I work with Amazon RDS and I don't.
The import/export method doesn't really work because of foreign keys - unless you do tables one by one in the order they reference one another. You can do an import/export to a new database. That will copy all the tables and data, but not the foreign keys.
This sounds like a common operation one needs to do with database. Why isn't SQL Server handling this properly? Every time I had to do this it was frustrating.
That being said, the only painless solution I've encountered was Sql Azure Migration Tool which is maintained by the community. It works with SQL Server too.
In my case, the error "BeanFactory not initialized or already closed - call 'refresh' before" was a consequence of a previous error that I didn't noticed in the server startup. I think that it is not always the real cause of the problem.
You could use preg_replace(). The following example can be run using command line php:
<?php
$s1 = "the string \\/:*?\"<>|";
$s2 = preg_replace("^[\\\\/:\*\?\"<>\|]^", " ", $s1) ;
echo "\n\$s2: \"" . $s2 . "\"\n";
?>
Output:
$s2: "the string "
Here's a dimensionality-independent standalone solution.
This will convert any N-dimensional array arr
of nonnegative integers to a one-hot N+1-dimensional array one_hot
, where one_hot[i_1,...,i_N,c] = 1
means arr[i_1,...,i_N] = c
. You can recover the input via np.argmax(one_hot, -1)
def expand_integer_grid(arr, n_classes):
"""
:param arr: N dim array of size i_1, ..., i_N
:param n_classes: C
:returns: one-hot N+1 dim array of size i_1, ..., i_N, C
:rtype: ndarray
"""
one_hot = np.zeros(arr.shape + (n_classes,))
axes_ranges = [range(arr.shape[i]) for i in range(arr.ndim)]
flat_grids = [_.ravel() for _ in np.meshgrid(*axes_ranges, indexing='ij')]
one_hot[flat_grids + [arr.ravel()]] = 1
assert((one_hot.sum(-1) == 1).all())
assert(np.allclose(np.argmax(one_hot, -1), arr))
return one_hot
The other great thing about SharpDevelop is the ability to translate solutions between the two big managed .NET languages VB.NET and C#. I believe it doesn't work for "websites" but it does for web application projects.
A histogram is a poor-man's density estimate. Note that in your call to hist()
using default arguments, you get frequencies not probabilities -- add ,prob=TRUE
to the call if you want probabilities.
As for the log axis problem, don't use 'x' if you do not want the x-axis transformed:
plot(mydata_hist$count, log="y", type='h', lwd=10, lend=2)
gets you bars on a log-y scale -- the look-and-feel is still a little different but can probably be tweaked.
Lastly, you can also do hist(log(x), ...)
to get a histogram of the log of your data.
I too liked Jordan's answer and implemented it myself. I only needed to abbreviations so in case someone else needs the same:
public static IEnumerable<SelectListItem> GetStatesList()
{
IList<SelectListItem> states = new List<SelectListItem>
{
new SelectListItem() {Text="AL", Value="AL"},
new SelectListItem() { Text="AK", Value="AK"},
new SelectListItem() { Text="AZ", Value="AZ"},
new SelectListItem() { Text="AR", Value="AR"},
new SelectListItem() { Text="CA", Value="CA"},
new SelectListItem() { Text="CO", Value="CO"},
new SelectListItem() { Text="CT", Value="CT"},
new SelectListItem() { Text="DC", Value="DC"},
new SelectListItem() { Text="DE", Value="DE"},
new SelectListItem() { Text="FL", Value="FL"},
new SelectListItem() { Text="GA", Value="GA"},
new SelectListItem() { Text="HI", Value="HI"},
new SelectListItem() { Text="ID", Value="ID"},
new SelectListItem() { Text="IL", Value="IL"},
new SelectListItem() { Text="IN", Value="IN"},
new SelectListItem() { Text="IA", Value="IA"},
new SelectListItem() { Text="KS", Value="KS"},
new SelectListItem() { Text="KY", Value="KY"},
new SelectListItem() { Text="LA", Value="LA"},
new SelectListItem() { Text="ME", Value="ME"},
new SelectListItem() { Text="MD", Value="MD"},
new SelectListItem() { Text="MA", Value="MA"},
new SelectListItem() { Text="MI", Value="MI"},
new SelectListItem() { Text="MN", Value="MN"},
new SelectListItem() { Text="MS", Value="MS"},
new SelectListItem() { Text="MO", Value="MO"},
new SelectListItem() { Text="MT", Value="MT"},
new SelectListItem() { Text="NE", Value="NE"},
new SelectListItem() { Text="NV", Value="NV"},
new SelectListItem() { Text="NH", Value="NH"},
new SelectListItem() { Text="NJ", Value="NJ"},
new SelectListItem() { Text="NM", Value="NM"},
new SelectListItem() { Text="NY", Value="NY"},
new SelectListItem() { Text="NC", Value="NC"},
new SelectListItem() { Text="ND", Value="ND"},
new SelectListItem() { Text="OH", Value="OH"},
new SelectListItem() { Text="OK", Value="OK"},
new SelectListItem() { Text="OR", Value="OR"},
new SelectListItem() { Text="PA", Value="PA"},
new SelectListItem() { Text="PR", Value="PR"},
new SelectListItem() { Text="RI", Value="RI"},
new SelectListItem() { Text="SC", Value="SC"},
new SelectListItem() { Text="SD", Value="SD"},
new SelectListItem() { Text="TN", Value="TN"},
new SelectListItem() { Text="TX", Value="TX"},
new SelectListItem() { Text="UT", Value="UT"},
new SelectListItem() { Text="VT", Value="VT"},
new SelectListItem() { Text="VA", Value="VA"},
new SelectListItem() { Text="WA", Value="WA"},
new SelectListItem() { Text="WV", Value="WV"},
new SelectListItem() { Text="WI", Value="WI"},
new SelectListItem() { Text="WY", Value="WY"}
};
return states;
}
As you see in an error UseCalls.java:27: error: cannot find symbol
return String.parseString(input);
there is no method parseString
in String
class. There is no need to parse it as long as JOptionPane.showInputDialog(prompt);
already returns a string.
You can use one of several available Date formatters. Since this falls within the JavaScript specification, it will be available in both browser and server-side modes.
objDate.toString().split(" ")[1]; // gives short name, unsure about locale
objDate.toLocaleDateString.split(" ")[0]; // gives long name
e.g.
js> objDate = new Date(new Date() - 9876543210)
Mon Feb 04 2013 12:37:09 GMT-0800 (PST)
js> objDate.toString().split(" ")[1]
Feb
js> objDate.toLocaleString().split(" ")[0]
February
There are more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
For Windows:
.sr-only
is a class name specifically used for screen readers. You can use any class name, but .sr-only
is pretty commonly used. If you don't care about developing with compliance in mind, then it can be removed. It will not affect UI in any way if removed because the CSS for this class is not visible to desktop and mobile device browsers.
There seems to be some information missing here about the use of .sr-only
to explain its purpose and being for screen readers. First and foremost, it is very important to always keep impaired users in mind. Impairment is the purpose of 508 compliance: https://www.section508.gov/, and it is great that bootstrap takes this into consideration. However, the use of .sr-only
is not all that needs to be taken into consideration for 508 compliance. You have the use of color, size of fonts, accessibility via navigation, descriptors, use of aria and so much more.
But as for .sr-only
- what does the CSS actually do? There are several slightly different variants of the CSS used for .sr-only
. One of the few I use is below:
.sr-only {
position: absolute;
margin: -1px 0 0 -1px;
padding: 0;
display: block;
width: 1px;
height: 1px;
font-size: 1px;
line-height: 1px;
overflow: hidden;
clip: rect(0,0,0,0);
border: 0;
outline: 0;
}
The above CSS hides content in desktop and mobile browsers wrapped with this class, but is seen by a screen reader like JAWS: http://www.freedomscientific.com/Products/Blindness/JAWS. Example markup is as follows:
<a href="#" target="_blank">
Click to Open Site
<span class="sr-only">This is an external link</span>
</a>
Additionally, if a DOM element has a width and height of 0, the element is not seen by the DOM. This is why the above CSS uses width: 1px; height: 1px;
. By using display: none
and setting your CSS to height: 0
and width: 0
, the element is not seen by the DOM and is thus problematic. The above CSS using width: 1px; height: 1px;
is not all you do to make the content invisible to desktop and mobile browsers (without overflow: hidden
, your content would still show on the screen), and visible to screen readers. Hiding the content from desktop and mobile browsers is done by adding an offset from width: 1px
and height: 1px
previously mentioned by using:
position: absolute;
margin: -1px 0 0 -1px;
overflow: hidden;
Lastly, to have a very good idea of what a screen reader sees and relays to its impaired user, turn off page styling for your browser. For Firefox, you can do this by going to:
View > Page Style > No Style
I hope the information I provided here is of further use to someone in addition to the other responses.
If you are using MacOS use:
sudo cp /usr/local/etc/openssl/cert.pem /etc/ssl/certs
after this Trust anchor not found error disappears
class PushObjects {
testMethod(): Array<number> {
//declaration and initialisation of array onject
var objs: number[] = [1,2,3,4,5,7];
//push the elements into the array object
objs.push(100);
//pop the elements from the array
objs.pop();
return objs;
}
}
let pushObj = new PushObjects();
//create the button element from the dom object
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () {
alert(pushObj.testMethod());
}
document.body.appendChild(btn);
Here is a nice explanation of update operation with some examples. Although it is Postgres site, but the SQL queries are valid for the other DBs, too. The following examples are intuitive to understand.
-- Update contact names in an accounts table to match the currently assigned salesmen:
UPDATE accounts SET (contact_first_name, contact_last_name) =
(SELECT first_name, last_name FROM salesmen
WHERE salesmen.id = accounts.sales_id);
-- A similar result could be accomplished with a join:
UPDATE accounts SET contact_first_name = first_name,
contact_last_name = last_name
FROM salesmen WHERE salesmen.id = accounts.sales_id;
However, the second query may give unexpected results if salesmen.id is not a unique key, whereas the first query is guaranteed to raise an error if there are multiple id matches. Also, if there is no match for a particular accounts.sales_id entry, the first query will set the corresponding name fields to NULL, whereas the second query will not update that row at all.
Hence for the given example, the most reliable query is like the following.
UPDATE tempDataView SET (marks) =
(SELECT marks FROM tempData
WHERE tempDataView.Name = tempData.Name);
Since in androidx Preference class has the SummaryProvider interface, it can be done without OnSharedPreferenceChangeListener. Simple implementations are provided for EditTextPreference and ListPreference. Building on EddieB's answer it can look like this. Tested on androidx.preference:preference:1.1.0-alpha03.
package com.example.util.timereminder.ui.prefs;
import android.os.Bundle;
import com.example.util.timereminder.R;
import androidx.preference.EditTextPreference;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceGroup;
/**
* Displays different preferences.
*/
public class PrefsFragmentExample extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.preferences);
initSummary(getPreferenceScreen());
}
/**
* Walks through all preferences.
*
* @param p The starting preference to search from.
*/
private void initSummary(Preference p) {
if (p instanceof PreferenceGroup) {
PreferenceGroup pGrp = (PreferenceGroup) p;
for (int i = 0; i < pGrp.getPreferenceCount(); i++) {
initSummary(pGrp.getPreference(i));
}
} else {
setPreferenceSummary(p);
}
}
/**
* Sets up summary providers for the preferences.
*
* @param p The preference to set up summary provider.
*/
private void setPreferenceSummary(Preference p) {
// No need to set up preference summaries for checkbox preferences because
// they can be set up in xml using summaryOff and summary On
if (p instanceof ListPreference) {
p.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
} else if (p instanceof EditTextPreference) {
p.setSummaryProvider(EditTextPreference.SimpleSummaryProvider.getInstance());
}
}
}
What is the use of a private static class variable?
Let's say you have a library book Class. Each time you create a new Book, you want to assign it a unique id. One way is to simply start at 0 and increment the id number. But, how do all the other books know the last created id number? Simple, save it as a static variable. Do patrons need to know that the actual internal id number is for each book? No. That information is private.
public class Book {
private static int numBooks = 0;
private int id;
public String name;
Book(String name) {
id = numBooks++;
this.name = name;
}
}
This is a contrived example, but I'm sure you can easily think of cases where you'd want all class instances to have access to common information that should be kept private from everyone else. Or even if you can't, it is good programming practice to make things as private as possible. What if you accidentally made that numBooks field public, even though Book users were not supposed to do anything with it. Then someone could change the number of Books without creating a new Book.
Very sneaky!
Try using the wget library for python. You can find the documentation for it here.
import wget
link = 'ftp://example.com/foo.txt'
wget.download(link)
Maybe this article can help you http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/
In this approach, you have to use FormControl then watch for value changes and then apply your mask to the value. An example should be:
...
form: FormGroup;
...
ngOnInit(){
this.form.valueChanges
.map((value) => {
// Here you can manipulate your value
value.firstName = value.firstName.trim();
return value;
})
.filter((value) => this.form.valid)
.subscribe((value) => {
console.log("Model Driven Form valid value: vm = ",JSON.stringify(value));
});
}
you try this code---
NSMutableArray *myMutableArray = [myArray mutableCopy];
and
NSArray *myArray = [myMutableArray copy];
Here we use onkeyup event in input field which triggered when the user releases a Key. And here we change our value to uppercase by toUpperCase() function.
Note that, text-transform="Uppercase" will only change the text in style. but not it's value. So,In order to change value, Use this inline code that will show as well as change the value
<input id="test-input" type="" name="" onkeyup="this.value = this.value.toUpperCase();">
Here is the code snippet that proved the value is change
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title></title>_x000D_
</head>_x000D_
<body>_x000D_
<form method="get" action="">_x000D_
<input id="test-input" type="" name="" onkeyup="this.value = this.value.toUpperCase();">_x000D_
<input type="button" name="" value="Submit" onclick="checking()">_x000D_
</form>_x000D_
<script type="text/javascript">_x000D_
function checking(argument) {_x000D_
// body..._x000D_
var x = document.getElementById("test-input").value_x000D_
alert(x);_x000D_
}_x000D_
_x000D_
_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
Simply use:
int ans = Integer.parseInt( JOptionPane.showInputDialog(frame,
"Text",
JOptionPane.INFORMATION_MESSAGE,
null,
null,
"[sample text to help input]"));
You cannot cast a String
to an int
, but you can convert it using Integer.parseInt(string)
.
From a web page this cannot work since IE restricts the use of that object.
Normally it happens when the target is null. So better check the invoke target first then do the linq query.
You can extend PDOStatement class to capture the bounded variables and store them for later use. Then 2 methods may be added, one for variable sanitizing ( debugBindedVariables ) and another to print the query with those variables ( debugQuery ):
class DebugPDOStatement extends \PDOStatement{
private $bound_variables=array();
protected $pdo;
protected function __construct($pdo) {
$this->pdo = $pdo;
}
public function bindValue($parameter, $value, $data_type=\PDO::PARAM_STR){
$this->bound_variables[$parameter] = (object) array('type'=>$data_type, 'value'=>$value);
return parent::bindValue($parameter, $value, $data_type);
}
public function bindParam($parameter, &$variable, $data_type=\PDO::PARAM_STR, $length=NULL , $driver_options=NULL){
$this->bound_variables[$parameter] = (object) array('type'=>$data_type, 'value'=>&$variable);
return parent::bindParam($parameter, $variable, $data_type, $length, $driver_options);
}
public function debugBindedVariables(){
$vars=array();
foreach($this->bound_variables as $key=>$val){
$vars[$key] = $val->value;
if($vars[$key]===NULL)
continue;
switch($val->type){
case \PDO::PARAM_STR: $type = 'string'; break;
case \PDO::PARAM_BOOL: $type = 'boolean'; break;
case \PDO::PARAM_INT: $type = 'integer'; break;
case \PDO::PARAM_NULL: $type = 'null'; break;
default: $type = FALSE;
}
if($type !== FALSE)
settype($vars[$key], $type);
}
if(is_numeric(key($vars)))
ksort($vars);
return $vars;
}
public function debugQuery(){
$queryString = $this->queryString;
$vars=$this->debugBindedVariables();
$params_are_numeric=is_numeric(key($vars));
foreach($vars as $key=>&$var){
switch(gettype($var)){
case 'string': $var = "'{$var}'"; break;
case 'integer': $var = "{$var}"; break;
case 'boolean': $var = $var ? 'TRUE' : 'FALSE'; break;
case 'NULL': $var = 'NULL';
default:
}
}
if($params_are_numeric){
$queryString = preg_replace_callback( '/\?/', function($match) use( &$vars) { return array_shift($vars); }, $queryString);
}else{
$queryString = strtr($queryString, $vars);
}
echo $queryString.PHP_EOL;
}
}
class DebugPDO extends \PDO{
public function __construct($dsn, $username="", $password="", $driver_options=array()) {
$driver_options[\PDO::ATTR_STATEMENT_CLASS] = array('DebugPDOStatement', array($this));
$driver_options[\PDO::ATTR_PERSISTENT] = FALSE;
parent::__construct($dsn,$username,$password, $driver_options);
}
}
And then you can use this inherited class for debugging purpouses.
$dbh = new DebugPDO('mysql:host=localhost;dbname=test;','user','pass');
$var='user_test';
$sql=$dbh->prepare("SELECT user FROM users WHERE user = :test");
$sql->bindValue(':test', $var, PDO::PARAM_STR);
$sql->execute();
$sql->debugQuery();
print_r($sql->debugBindedVariables());
Resulting in
SELECT user FROM users WHERE user = 'user_test'
Array ( [:test] => user_test )
It is time to use agg
instead of apply
.
When
df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6], 'c': [1,2,5,5,4,6]})
If you want multiple columns stack into list , result in pd.DataFrame
df.groupby('a')[['b', 'c']].agg(list)
# or
df.groupby('a').agg(list)
If you want single column in list, result in ps.Series
df.groupby('a')['b'].agg(list)
#or
df.groupby('a')['b'].apply(list)
Note, result in pd.DataFrame
is about 10x slower than result in ps.Series
when you only aggregate single column, use it in multicolumns case .
If you are using Cloudflare then this is always the Cloudflare IP address from the node which is serving you.
In this case you get the real IP address from the $_SERVER['HTTP_FORWARDED_FOR']
entry as described in the the other answers.
I recently set up a script that does this.
As David Brabant pointed out, you can use the System.Net.WebRequest
class to do an HTTP request.
To check whether it is operational, you should use the following example code:
# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()
# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
Write-Host "Site is OK!"
}
Else {
Write-Host "The Site may be down, please check!"
}
# Finally, we clean up the http request by closing it.
If ($HTTP_Response -eq $null) { }
Else { $HTTP_Response.Close() }
This error can also happen when you've downloaded a new version of Google Play Services and not installed the latest SDK. Thats what happened to me. So, as the others mentioned, if you try to import Google Play Services and then open the console, you'll see a compile error. Try installing all the recent Android SDKs and try again, if this is the case.
You can use the option -o in sendEmail to send a html email.
-o message-content-type=html to specify the content type of the email.
-o message-file to add the html file to the email content.
I have tried this option in a shell scripts, and it works.
Here is the full command:
/usr/local/bin/sendEmail -f [email protected] -t "[email protected]" -s \
smtp.test.com -u "Title" -xu [email protected] -xp password \
-o message-charset=UTF-8 \
-o message-content-type=html \
-o message-file=test.html
I cannot replicate the results discussed here.
I don't know if poor benchmark code is to blame, or what, but the two methods are within 10% of each other on my machine using the following code, and one loop is usually just slightly faster than two - as you'd expect.
Array sizes ranged from 2^16 to 2^24, using eight loops. I was careful to initialize the source arrays so the +=
assignment wasn't asking the FPU to add memory garbage interpreted as a double.
I played around with various schemes, such as putting the assignment of b[j]
, d[j]
to InitToZero[j]
inside the loops, and also with using += b[j] = 1
and += d[j] = 1
, and I got fairly consistent results.
As you might expect, initializing b
and d
inside the loop using InitToZero[j]
gave the combined approach an advantage, as they were done back-to-back before the assignments to a
and c
, but still within 10%. Go figure.
Hardware is Dell XPS 8500 with generation 3 Core i7 @ 3.4 GHz and 8 GB memory. For 2^16 to 2^24, using eight loops, the cumulative time was 44.987 and 40.965 respectively. Visual C++ 2010, fully optimized.
PS: I changed the loops to count down to zero, and the combined method was marginally faster. Scratching my head. Note the new array sizing and loop counts.
// MemBufferMystery.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
#include <time.h>
#define dbl double
#define MAX_ARRAY_SZ 262145 //16777216 // AKA (2^24)
#define STEP_SZ 1024 // 65536 // AKA (2^16)
int _tmain(int argc, _TCHAR* argv[]) {
long i, j, ArraySz = 0, LoopKnt = 1024;
time_t start, Cumulative_Combined = 0, Cumulative_Separate = 0;
dbl *a = NULL, *b = NULL, *c = NULL, *d = NULL, *InitToOnes = NULL;
a = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
b = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
c = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
d = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
InitToOnes = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
// Initialize array to 1.0 second.
for(j = 0; j< MAX_ARRAY_SZ; j++) {
InitToOnes[j] = 1.0;
}
// Increase size of arrays and time
for(ArraySz = STEP_SZ; ArraySz<MAX_ARRAY_SZ; ArraySz += STEP_SZ) {
a = (dbl *)realloc(a, ArraySz * sizeof(dbl));
b = (dbl *)realloc(b, ArraySz * sizeof(dbl));
c = (dbl *)realloc(c, ArraySz * sizeof(dbl));
d = (dbl *)realloc(d, ArraySz * sizeof(dbl));
// Outside the timing loop, initialize
// b and d arrays to 1.0 sec for consistent += performance.
memcpy((void *)b, (void *)InitToOnes, ArraySz * sizeof(dbl));
memcpy((void *)d, (void *)InitToOnes, ArraySz * sizeof(dbl));
start = clock();
for(i = LoopKnt; i; i--) {
for(j = ArraySz; j; j--) {
a[j] += b[j];
c[j] += d[j];
}
}
Cumulative_Combined += (clock()-start);
printf("\n %6i miliseconds for combined array sizes %i and %i loops",
(int)(clock()-start), ArraySz, LoopKnt);
start = clock();
for(i = LoopKnt; i; i--) {
for(j = ArraySz; j; j--) {
a[j] += b[j];
}
for(j = ArraySz; j; j--) {
c[j] += d[j];
}
}
Cumulative_Separate += (clock()-start);
printf("\n %6i miliseconds for separate array sizes %i and %i loops \n",
(int)(clock()-start), ArraySz, LoopKnt);
}
printf("\n Cumulative combined array processing took %10.3f seconds",
(dbl)(Cumulative_Combined/(dbl)CLOCKS_PER_SEC));
printf("\n Cumulative seperate array processing took %10.3f seconds",
(dbl)(Cumulative_Separate/(dbl)CLOCKS_PER_SEC));
getchar();
free(a); free(b); free(c); free(d); free(InitToOnes);
return 0;
}
I'm not sure why it was decided that MFLOPS was a relevant metric. I though the idea was to focus on memory accesses, so I tried to minimize the amount of floating point computation time. I left in the +=
, but I am not sure why.
A straight assignment with no computation would be a cleaner test of memory access time and would create a test that is uniform irrespective of the loop count. Maybe I missed something in the conversation, but it is worth thinking twice about. If the plus is left out of the assignment, the cumulative time is almost identical at 31 seconds each.
Old style string formatting:
In [3]: "%02x" % 127
Out[3]: '7f'
New style
In [7]: '{:x}'.format(127)
Out[7]: '7f'
Using capital letters as format characters yields uppercase hexadecimal
In [8]: '{:X}'.format(127)
Out[8]: '7F'
Docs are here.
In case anyone likes it, here is a .NET 4+ only solution formed as an extension method without the needless Dispose call on the MemoryStream. This is a hopelessly trivial optimization, but it is worth noting that failing to Dispose a MemoryStream is not a real failure.
public static class StreamHelpers
{
public static byte[] ReadFully(this Stream input)
{
var ms = new MemoryStream();
input.CopyTo(ms);
return ms.ToArray();
}
}
You can use drop command to delete meta data and actual data from HDFS.
And just to delete data and keep the table structure, use truncate command.
For further help regarding hive ql, check language manual of hive.
The first answer from @carlos worked for me:
session.getProperties().put("mail.smtp.ssl.trust", "smtp.gmail.com");
I have tested the property below and worked perfectly for me too:
session.getProperties().put("mail.smtp.starttls.enable", "true");
The two properties alone solved this type of problem, but by guarantee I used both.
The steps for schedule jobs in Jenkins:
@midnight
Note: under the schedule field, can see the last and the next date-time run.
Jenkins also supports predefined aliases to schedule build:
@hourly
, @daily
, @weekly
, @monthly
, @midnight
@hourly
--> Build every hour at the beginning of the hour --> 0 * * * *
@daily, @midnight
--> Build every day at midnight --> 0 0 * * *
@weekly
--> Build every week at midnight on Sunday morning --> 0 0 * * 0
@monthly
--> Build every month at midnight of the first day of the month --> 0 0 1 * *
what is a SID and Service name
please look into oracle's documentation at https://docs.oracle.com/cd/B19306_01/network.102/b14212/concepts.htm
In case if the above link is not accessable in future, At the time time of writing this answer, the above link will direct you to, "Database Service and Database Instance Identification" topic in Connectivity Concepts chapter of "Database Net Services Administrator's Guide". This guide is published by oracle as part of "Oracle Database Online Documentation, 10g Release 2 (10.2)"
When I have to use one or another? Why do I need two of them?
Consider below mapping in a RAC Environment,
SID SERVICE_NAME
bob1 bob
bob2 bob
bob3 bob
bob4 bob
if load balancing is configured, the listener will 'balance' the workload across all four SIDs. Even if load balancing is configured, you can connect to bob1 all the time if you want to by using the SID instead of SERVICE_NAME.
Please refer, https://community.oracle.com/thread/4049517
You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :
BEGIN TRANSACTION
update A
set A.ORG_NAME = @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
COMMIT
Is there a JavaScript equivalent of Java's
class.getName()
?
No.
ES2015 Update: the name of class Foo {}
is Foo.name
. The name of thing
's class, regardless of thing
's type, is thing.constructor.name
. Builtin constructors in an ES2015 environment have the correct name
property; for instance (2).constructor.name
is "Number"
.
But here are various hacks that all fall down in one way or another:
Here is a hack that will do what you need - be aware that it modifies the Object's prototype, something people frown upon (usually for good reason)
Object.prototype.getName = function() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((this).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
};
Now, all of your objects will have the function, getName()
, that will return the name of the constructor as a string. I have tested this in FF3
and IE7
, I can't speak for other implementations.
If you don't want to do that, here is a discussion on the various ways of determining types in JavaScript...
I recently updated this to be a bit more exhaustive, though it is hardly that. Corrections welcome...
constructor
property...Every object
has a value for its constructor
property, but depending on how that object
was constructed as well as what you want to do with that value, it may or may not be useful.
Generally speaking, you can use the constructor
property to test the type of the object like so:
var myArray = [1,2,3];
(myArray.constructor == Array); // true
So, that works well enough for most needs. That said...
Will not work AT ALL in many cases
This pattern, though broken, is quite common:
function Thingy() {
}
Thingy.prototype = {
method1: function() {
},
method2: function() {
}
};
Objects
constructed via new Thingy
will have a constructor
property that points to Object
, not Thingy
. So we fall right at the outset; you simply cannot trust constructor
in a codebase that you don't control.
Multiple Inheritance
An example where it isn't as obvious is using multiple inheritance:
function a() { this.foo = 1;}
function b() { this.bar = 2; }
b.prototype = new a(); // b inherits from a
Things now don't work as you might expect them to:
var f = new b(); // instantiate a new object with the b constructor
(f.constructor == b); // false
(f.constructor == a); // true
So, you might get unexpected results if the object
your testing has a different object
set as its prototype
. There are ways around this outside the scope of this discussion.
There are other uses for the constructor
property, some of them interesting, others not so much; for now we will not delve into those uses since it isn't relevant to this discussion.
Will not work cross-frame and cross-window
Using .constructor
for type checking will break when you want to check the type of objects coming from different window
objects, say that of an iframe or a popup window. This is because there's a different version of each core type constructor
in each `window', i.e.
iframe.contentWindow.Array === Array // false
instanceof
operator...The instanceof
operator is a clean way of testing object
type as well, but has its own potential issues, just like the constructor
property.
var myArray = [1,2,3];
(myArray instanceof Array); // true
(myArray instanceof Object); // true
But instanceof
fails to work for literal values (because literals are not Objects
)
3 instanceof Number // false
'abc' instanceof String // false
true instanceof Boolean // false
The literals need to be wrapped in an Object
in order for instanceof
to work, for example
new Number(3) instanceof Number // true
The .constructor
check works fine for literals because the .
method invocation implicitly wraps the literals in their respective object type
3..constructor === Number // true
'abc'.constructor === String // true
true.constructor === Boolean // true
Why two dots for the 3? Because Javascript interprets the first dot as a decimal point ;)
instanceof
also will not work across different windows, for the same reason as the constructor
property check.
name
property of the constructor
property...Again, see above; it's quite common for constructor
to be utterly and completely wrong and useless.
Using myObjectInstance.constructor.name
will give you a string containing the name of the constructor
function used, but is subject to the caveats about the constructor
property that were mentioned earlier.
For IE9 and above, you can monkey-patch in support:
if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var funcNameRegex = /function\s+([^\s(]+)\s*\(/;
var results = (funcNameRegex).exec((this).toString());
return (results && results.length > 1) ? results[1] : "";
},
set: function(value) {}
});
}
Updated version from the article in question. This was added 3 months after the article was published, this is the recommended version to use by the article's author Matthew Scharley. This change was inspired by comments pointing out potential pitfalls in the previous code.
if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var funcNameRegex = /function\s([^(]{1,})\(/;
var results = (funcNameRegex).exec((this).toString());
return (results && results.length > 1) ? results[1].trim() : "";
},
set: function(value) {}
});
}
It turns out, as this post details, you can use Object.prototype.toString
- the low level and generic implementation of toString
- to get the type for all built-in types
Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(/abc/) // [object RegExp]
Object.prototype.toString.call([1,2,3]) // [object Array]
One could write a short helper function such as
function type(obj){
return Object.prototype.toString.call(obj).slice(8, -1);
}
to remove the cruft and get at just the type name
type('abc') // String
However, it will return Object
for all user-defined types.
All of these are subject to one potential problem, and that is the question of how the object in question was constructed. Here are various ways of building objects and the values that the different methods of type checking will return:
// using a named function:
function Foo() { this.a = 1; }
var obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == "Foo"); // true
// let's add some prototypical inheritance
function Bar() { this.b = 2; }
Foo.prototype = new Bar();
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // false
(obj.constructor.name == "Foo"); // false
// using an anonymous function:
obj = new (function() { this.a = 1; })();
(obj instanceof Object); // true
(obj.constructor == obj.constructor); // true
(obj.constructor.name == ""); // true
// using an anonymous function assigned to a variable
var Foo = function() { this.a = 1; };
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == ""); // true
// using object literal syntax
obj = { foo : 1 };
(obj instanceof Object); // true
(obj.constructor == Object); // true
(obj.constructor.name == "Object"); // true
While not all permutations are present in this set of examples, hopefully there are enough to provide you with an idea about how messy things might get depending on your needs. Don't assume anything, if you don't understand exactly what you are after, you may end up with code breaking where you don't expect it to because of a lack of grokking the subtleties.
Discussion of the typeof
operator may appear to be a glaring omission, but it really isn't useful in helping to identify whether an object
is a given type, since it is very simplistic. Understanding where typeof
is useful is important, but I don't currently feel that it is terribly relevant to this discussion. My mind is open to change though. :)
You may consider FluentFTP, previously known as System.Net.FtpClient.
It is released under The MIT License and available on NuGet (FluentFTP).
My .replace()
function using the patterns described on the other answers did not work. The pattern that worked for my case was:
var str = "Test\n\n\Test\n\Test";
str.replace(/\r\n|\r|\n/g,' ');
// str: "Test Test Test"
Close your project, and then import project. That work for me. It's a simply way.
good luck.
I had the same problem and got it solved by using a different directory.
bash-4.2$ bundle install Could not locate Gemfile bash-4.2$ pwd /home/amit/redmine/redmine-2.2.2-0/apps/redmine bash-4.2$ cd htdocs/ bash-4.2$ ls app config db extra Gemfile lib plugins Rakefile script tmp bin config.ru doc files Gemfile.lock log public README.rdoc test vendor bash-4.2$ cd plugins/ bash-4.2$ bundle install Using rake (0.9.2.2) Using i18n (0.6.0) Using multi_json (1.3.6) Using activesupport (3.2.11) Using builder (3.0.0) Using activemodel (3.2.11) Using erubis (2.7.0) Using journey (1.0.4) Using rack (1.4.1) Using rack-cache (1.2) Using rack-test (0.6.1) Using hike (1.2.1) Using tilt (1.3.3) Using sprockets (2.2.1) Using actionpack (3.2.11) Using mime-types (1.19) Using polyglot (0.3.3) Using treetop (1.4.10) Using mail (2.4.4) Using actionmailer (3.2.11) Using arel (3.0.2) Using tzinfo (0.3.33) Using activerecord (3.2.11) Using activeresource (3.2.11) Using coderay (1.0.6) Using rack-ssl (1.3.2) Using json (1.7.5) Using rdoc (3.12) Using thor (0.15.4) Using railties (3.2.11) Using jquery-rails (2.0.3) Using mysql2 (0.3.11) Using net-ldap (0.3.1) Using ruby-openid (2.1.8) Using rack-openid (1.3.1) Using bundler (1.2.3) Using rails (3.2.11) Using rmagick (2.13.1) Your bundle i
WAMP uses different php.ini files in the CLI and for Apache. when you enable php_openssl through the WAMP UI, you enable it for Apache, not for the CLI. You need to modify C:\wamp\bin\php\php-5.4.3\php.ini to enable it for the CLI.
Fluid layout in Bootstrap 3.
Unlike Boostrap 2, Bootstrap 3 doesn't have a .container-fluid mixin to make a fluid container. The .container is a fixed width responsive grid layout. In a large screen, there are excessive white spaces in both sides of one's Web page content.
container-fluid
is added back in Bootstrap 3.1
A fluid grid layout uses all screen width and works better in large screen. It turns out that it is easy to create a fluid grid layout using Bootstrap 3 mixins. The following line makes a fluid responsive grid layout:
.container-fixed;
The .container-fixed mixin sets the content to the center of the screen and add paddings. It doesn't specifies a fixed page width.
Another approach is to use Eric Flowers' CSS style
.my-fluid-container {
padding-left: 15px;
padding-right: 15px;
margin-left: auto;
margin-right: auto;
}
Removing a file from pull request but not from your local repository.
git checkout -- c:\temp..... next git checkout origin/master -- c:\temp... u replace origin/master with any other branch. Next git commit -m c:\temp..... Next git push origin
Note : no single quote or double quotes for the filepath
Its quite easy on computer a you don't need to do anything just make sure both system are on same network if its not internet access(for this you need static ip). Okay now on computer b go to start menu find configuration under oracle folder click Net Configuration Assistant under that folder when window pop up click Local net configuration option it must be third option.
Now click add and click next in next screen it will ask service name here you need to add oracle global database name of computer A(Normally I use oracle86 for my installation) now click next next screen choose protocol normally its tcp click next in host name enter computer A's name you can found that in my computer properties. Click next don't change port untill you have changed that in Computer A click next and choose test connection now here you can check your connection working or not if the error is username and password not correct then click login credential button and fill correct username and password. If its saying unable to reach computer ot target not found than you must add exception in firewall for 1521 port or just disable firewall on computer A.
Simply copy your Anaconda bin
directory and paste it at the bottom of ~/.zshrc
.
For me the path is /home/theorangeguy/miniconda3/bin
, so I ran:
echo ". /home/theorangeguy/miniconda3/bin" >> ~/.zshrc
This edited the ~/.zshrc
. Now do:
source ~/.zshrc
It worked like a charm.
You need to set 'utf8' for all parameters in each Function. It's my case:
Ok I'm not sure what's up with these answers but I'll let you know what worked for me as advised by a senior dev at my work. I'm working in Ruby on Rails and using Facebook's JavaScript code to get access tokens.
Problem: To do authentication, Facebook is taking the url from your address bar and comparing that with what they have on file. They don't allow you to use localhost:3000
for whatever reason. However, you can use a completely made-up domain name like yoursite.dev
by running a local server and pointing yoursite.dev
to 127.0.0.1:3000
or wherever your localhost was pointing to.
Step 1: Install or update Nginx
$ brew install nginx
(install) or $ brew upgrade nginx
(update)
Step 2: Open up your nginx config file
/usr/local/etc/nginx/nginx.conf
(usually here)
/opt/boxen/config/nginx/nginx.conf
(if you use Boxen)
Step 3 Add this bit of code into your http {}
block
Replace proxy_pass
with wherever you want to point yoursite.dev
to. In my case it was replacing localhost:3000 or the equivalent 127.0.0.1:3000
server {
listen yoursite.dev:80;
server_name yoursite.dev;
location / {
proxy_pass http://127.0.0.1:3000;
}
}
Step 4: Edit your hosts file, in /etc/hosts
on Mac to include
127.0.0.1 yoursite.dev
This file directs domains to localhost. Nginx listens in on localhost and redirects if it matches a rule.
Step 5: Every time you use your dev environment going forward, you use the yoursite.dev
in the address bar instead of localhost:3000
so Facebook logs you in correctly.
Apache commons lang now supports this. Just make sure you have a recent enough version of Apache commons lang on your classpath. You'll need version 3.2+
Release Notes for version 3.2
LANG-797: Added escape/unescapeJson to StringEscapeUtils.
You're able to do database finds using LIKE with this syntax:
Model::where('column', 'LIKE', '%value%')->get();
The correct way to do it would be:
adb -s 123abc12 shell getprop
Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop
to access its value directly, like this:
adb -s 123abc12 shell getprop ro.product.model
The details in adb devices -l
consist of the following three properties: ro.product.name
, ro.product.model
and ro.product.device
.
Note that ADB shell ends lines with \r\n
, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7
you might get Nexus 7\r
).
for some reason sharex was set to True so I turned it back to False and it worked fine.
df.plot(........,sharex=False)
Here's an example using Oracle syntax:
First let's create a table COUNTRY
CREATE TABLE TBL_COUNTRY ( COUNTRY_ID VARCHAR2 (50) NOT NULL ) ;
ALTER TABLE TBL_COUNTRY ADD CONSTRAINT COUNTRY_PK PRIMARY KEY ( COUNTRY_ID ) ;
Create the table PROVINCE
CREATE TABLE TBL_PROVINCE(
PROVINCE_ID VARCHAR2 (50) NOT NULL ,
COUNTRY_ID VARCHAR2 (50)
);
ALTER TABLE TBL_PROVINCE ADD CONSTRAINT PROVINCE_PK PRIMARY KEY ( PROVINCE_ID ) ;
ALTER TABLE TBL_PROVINCE ADD CONSTRAINT PROVINCE_COUNTRY_FK FOREIGN KEY ( COUNTRY_ID ) REFERENCES TBL_COUNTRY ( COUNTRY_ID ) ;
This runs perfectly fine in Oracle. Notice the COUNTRY_ID foreign key in the second table doesn't have "NOT NULL".
Now to insert a row into the PROVINCE table, it's sufficient to only specify the PROVINCE_ID. However, if you chose to specify a COUNTRY_ID as well, it must exist already in the COUNTRY table.
You can't define an object literal with a dynamic key. Do this :
var o = {};
o[key] = value;
return o;
There's no shortcut (edit: there's one now, with ES6, see the other answer).
"WARNING: The command completed successfully but no settings of '[user id here]' have been modified."
This warning means the setting was already set like what you want it to be. So it didn't change anything for that object.
This is the 2018 ECMAScript 6+ Solution:
const str = 'the Eiffel Tower';_x000D_
const newStr = `${str[0].toUpperCase()}${str.slice(1)}`;_x000D_
console.log('Original String:', str); // the Eiffel Tower_x000D_
console.log('New String:', newStr); // The Eiffel Tower
_x000D_
Here's a complete working example based on your testing. Compare it to what you have currently to figure out where you are going wrong.
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(1000).fadeOut();
});
</script>
</head>
<body>
<div id=deletesuccess > hiiiiiiiiiii </div>
</body>
</html>
Generally this kind of error comes with human mistakes like if we change the namespace in some improper way, or changing folder names from explorer for current project etc, where compiler is unable to detect sometimes.
I came across the same error, to resolve which I tried few steps. Please follow all the steps :
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "**Client**", "**Client** \ **Client**.csproj", "{4503E259-0E3B-414A-9074-F251684322A5}"
EndProject
Check again Foldernames (I have highlighted in BOLD) and make it similar to what you did in step 2.
Clean the whole solution again
Build The Solution (If doesn't work try building individual after cleaning again)
My version of solving the problem:
/src/Acme/MyBundle/Resources/config/services.yml
services:
form_errors:
class: Acme\MyBundle\Form\FormErrors
/src/Acme/MyBundle/Form/FormErrors.php
<?php
namespace Acme\MyBundle\Form;
class FormErrors
{
public function getArray(\Symfony\Component\Form\Form $form)
{
return $this->getErrors($form);
}
private function getErrors($form)
{
$errors = array();
if ($form instanceof \Symfony\Component\Form\Form) {
// ??????? ?????? ????????
foreach ($form->getErrors() as $error) {
$errors[] = $error->getMessage();
}
// ?????????? ??? ???????? ?????????
foreach ($form->all() as $key => $child) {
/** @var $child \Symfony\Component\Form\Form */
if ($err = $this->getErrors($child)) {
$errors[$key] = $err;
}
}
}
return $errors;
}
}
/src/Acme/MyBundle/Controller/DefaultController.php
$form = $this->createFormBuilder($entity)->getForm();
$form_errors = $this->get('form_errors')->getArray($form);
return new JsonResponse($form_errors);
In Symfony 2.5 you can get all fields errors very easy:
$errors = array();
foreach ($form as $fieldName => $formField) {
foreach ($formField->getErrors(true) as $error) {
$errors[$fieldName] = $error->getMessage();
}
}
You can use this code:
$('#country').select2("val", "Your_value").trigger('change');
Put your desired value instead of Your_value
Hope It will work :)
if(button.clicked==true) {
console.log("Button Clicked");
} ==> // This Code Doesn't Work Properly So Please Use Below One //
function check() {
console.log("Button Clicked");
}; // This Code Works Fine //
var button= document.querySelector("button"); // Accessing The Button //
button.addEventListener("click", check); // Adding event to call function when clicked //
With momentjs, you can find current timezone as
console.log(moment().utcOffset()); // (-240, -120, -60, 0, 60, 120, 240, etc.)
_x000D_
<script src="https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js"></script>
_x000D_
With dayjs, you can find current timezone as
console.log(dayjs().utcOffset()); // (-240, -120, -60, 0, 60, 120, 240, etc.)
_x000D_
<script src="https://unpkg.com/[email protected]/dayjs.min.js"></script>
_x000D_
Both API returns utc offset in minutes.
You can manage your application versioning wisely by using the Advanced Build Version Plugin for Gradle.
You just need to include the plugin in yout build.gradle
:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'org.moallemi.gradle.advanced-build-version:gradle-plugin:1.5.0'
}
}
apply plugin: 'org.moallemi.advanced-build-version'
And then you can use the versioning functions (and, obviously, customize them):
advancedVersioning {
nameOptions { }
codeOptions { }
outputOptions { }
}
def appVersionName = advancedVersioning.versionName
def appVersionCode = advancedVersioning.versionCode
For more information, take a look at the official documentation.
The path should be something like: "Images\a.bmp"
. (Note the lack of a leading slash, and the slashes being back slashes.)
And then:
pictureBox1.Image = Image.FromFile(@"Images\a.bmp");
I just tried it to make sure, and it works. This is besides the other answer that you got - to "copy always".
set the classpath and compile
javac -classpath "C:\Program Files\Java\jdk1.6.0_updateVersion\tools.jar" yourApp.java
create manifest.txt
Main-Class: yourApp newline
create yourApp.jar
jar cvf0m yourApp.jar manifest.txt yourApp.class
run yourApp.jar
java -jar yourApp.jar
Use a truly blank, valid and highly compatible SVG, based on this article:
src="data:image/svg+xml;charset=utf8,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E"
It will default in size to 300x150px as any SVG does, but you can work with that in your img
element default styles, as you would possibly need in any case in the practical implementation.
I know that two threads can not enter in Synchronize block at the same time
Two thread cannot enter a synchronized block on the same object twice. This means that two threads can enter the same block on different objects. This confusion can lead to code like this.
private Integer i = 0;
synchronized(i) {
i++;
}
This will not behave as expected as it could be locking on a different object each time.
if this is true than How this atomic.incrementAndGet() works without Synchronize ?? and is thread safe ??
yes. It doesn't use locking to achieve thread safety.
If you want to know how they work in more detail, you can read the code for them.
And what is difference between internal reading and writing to Volatile Variable / Atomic Variable ??
Atomic class uses volatile fields. There is no difference in the field. The difference is the operations performed. The Atomic classes use CompareAndSwap or CAS operations.
i read in some article that thread has local copy of variables what is that ??
I can only assume that it referring to the fact that each CPU has its own cached view of memory which can be different from every other CPU. To ensure that your CPU has a consistent view of data, you need to use thread safety techniques.
This is only an issue when memory is shared at least one thread updates it.
Why so complicated? When you can do:
var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;
If you need more times check out the window.performance object:
console.log(window.performance);
Will show you the timing object:
connectEnd Time when server connection is finished.
connectStart Time just before server connection begins.
domComplete Time just before document readiness completes.
domContentLoadedEventEnd Time after DOMContentLoaded event completes.
domContentLoadedEventStart Time just before DOMContentLoaded starts.
domInteractive Time just before readiness set to interactive.
domLoading Time just before readiness set to loading.
domainLookupEnd Time after domain name lookup.
domainLookupStart Time just before domain name lookup.
fetchStart Time when the resource starts being fetched.
loadEventEnd Time when the load event is complete.
loadEventStart Time just before the load event is fired.
navigationStart Time after the previous document begins unload.
redirectCount Number of redirects since the last non-redirect.
redirectEnd Time after last redirect response ends.
redirectStart Time of fetch that initiated a redirect.
requestStart Time just before a server request.
responseEnd Time after the end of a response or connection.
responseStart Time just before the start of a response.
timing Reference to a performance timing object.
navigation Reference to performance navigation object.
performance Reference to performance object for a window.
type Type of the last non-redirect navigation event.
unloadEventEnd Time after the previous document is unloaded.
unloadEventStart Time just before the unload event is fired.
I had this error with MySQL as my database and the only solution was reinstall all components of MySQL, because before I installed just the server.
So try to download other versions of PostgreSQL and get all the components
Either use the
$(document).on "page:load", attachRatingHandler
or use jQuery's .on function to achieve the same effect
$(document).on 'click', 'span.star', attachRatingHandler
see here for more details: http://srbiv.github.io/2013/04/06/rails-4-my-first-run-in-with-turbolinks.html
Here's how you'd roll your own function http://play.golang.org/p/Qgw7XuLNhb
func compare(a, b T) bool {
if &a == &b {
return true
}
if a.X != b.X || a.Y != b.Y {
return false
}
if len(a.Z) != len(b.Z) || len(a.M) != len(b.M) {
return false
}
for i, v := range a.Z {
if b.Z[i] != v {
return false
}
}
for k, v := range a.M {
if b.M[k] != v {
return false
}
}
return true
}
Use substring
String strOut = "abcdefghijklmnopqrtuvwxyz"
String result = strOut.substring(0, 8) + "...";// count start in 0 and 8 is excluded
System.out.pritnln(result);
Note: substring(int first, int second) takes two parameters. The first is inclusive and the second is exclusive.
<script type="text/javascript">
function enter(elem){
elem.style.backgroundColor = '#FF0000';
}
function leave(elem){
elem.style.backgroundColor = '#FFFFFF';
}
</script>
<div onmouseover="enter(this)" onmouseout="leave(this)">
Some Text
</div>
I put together a little C program to print out the current timestamp (locale-safe, no bad characters...). Then, I use the FOR command to save the result in an environment variable:
:: Get the timestamp
for /f %%x in ('@timestamp') do set TIMESTAMP=%%x
:: Use it to generate a filename
for /r %%x in (.\processed\*) do move "%%~x" ".\archived\%%~nx-%TIMESTAMP%%%~xx"
Here's a link:
for visual studio 2019 need change MSBuild path
npm config set msvs_version 2017
npm config set msbuild_path "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\MSBuild.exe"
npm rebuild node-sass
This is very simple and straight forward. Look at the code. Try to grasp the basic concept behind javascript extension.
First let us extend javascript function.
function Base(props) {
const _props = props
this.getProps = () => _props
// We can make method private by not binding it to this object.
// Hence it is not exposed when we return this.
const privateMethod = () => "do internal stuff"
return this
}
You can extend this function by creating child function in following way
function Child(props) {
const parent = Base(props)
this.getMessage = () => `Message is ${parent.getProps()}`;
// You can remove the line below to extend as in private inheritance,
// not exposing parent function properties and method.
this.prototype = parent
return this
}
Now you can use Child function as follows,
let childObject = Child("Secret Message")
console.log(childObject.getMessage()) // logs "Message is Secret Message"
console.log(childObject.getProps()) // logs "Secret Message"
We can also create Javascript Function by extending Javascript classes, like this.
class BaseClass {
constructor(props) {
this.props = props
// You can remove the line below to make getProps method private.
// As it will not be binded to this, but let it be
this.getProps = this.getProps.bind(this)
}
getProps() {
return this.props
}
}
Let us extend this class with Child function like this,
function Child(props) {
let parent = new BaseClass(props)
const getMessage = () => `Message is ${parent.getProps()}`;
return { ...parent, getMessage} // I have used spread operator.
}
Again you can use Child function as follows to get similar result,
let childObject = Child("Secret Message")
console.log(childObject.getMessage()) // logs "Message is Secret Message"
console.log(childObject.getProps()) // logs "Secret Message"
Javascript is very easy language. We can do almost anything. Happy JavaScripting... Hope I was able to give you an idea to use in your case.
The GIMP (GNU Image Manipulation Program). It's free, open source and runs on Windows and Linux (and maybe Mac?).
I solved it by adding this to the /etc/profile - system wide (or to user local .profile, or _.bash_profile_):
# SSH-AGENT
#!/usr/bin/env bash
SERVICE='ssh-agent'
WHOAMI=`who am i |awk '{print $1}'`
if pgrep -u $WHOAMI $SERVICE >/dev/null
then
echo $SERVICE running.
else
echo $SERVICE not running.
echo starting
ssh-agent > ~/.ssh/agent_env
fi
. ~/.ssh/agent_env
This starts a new ssh-agent if not running for the current user, or re-sets the ssh-agent env parameter if running.
To add to wflynny's answer above, you can find the available colormaps here
Example:
import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)
or alternatively,
plt.scatter(x, y, c=t, cmap='jet')
The proper way to remove a cookie is to set the max age to 0 and add the cookie back to the HttpServletResponse object.
Most people don't realize or forget to add the cookie back onto the response object. By doing that it will expire and remove the cookie immediately.
...retrieve cookie from HttpServletRequest
cookie.setMaxAge(0);
response.addCookie(cookie);
JsVIS was pretty nice, but slow with larger graphs, and has been abandoned since 2007.
prefuse is a set of software tools for creating rich interactive data visualizations in Java. flare is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.
This Technical Note TN2328 from Apple Developer Library helped me a lot about Changes To Embedding Python Using Xcode 5.0.
You can use define window.myvar = {}
.
When you want to use it, you can use like window.myvar = 1
Either char(13)
or char(10)
would work. But it is recommended to use char(13) + char(10)
char(10)
= \n
- new linechar(13)
= \r
- go to the beginning of the lineOne example:
List somelist = new ArrayList();
You can look at the javadoc for List and find all known implementing classes of the List
interface that are included with the java api.
One way to compare your local version before pushing it on the remote repo (kind of push in dry-run):
Use TortoiseGit:
Right click on the root folder project > TortoiseGit > Diff with previous version >
for Version 2 choose refs/remotes/origin/master
Do I have to make an array really large that has a lot of even numbers
No. Use modulus (%). It gives you the remainder of the two numbers you are dividing.
Ex. 2 % 2 = 0 because 2/2 = 1 with 0 remainder.
Ex2. 3 % 2 = 1 because 3/2 = 1 with 1 remainder.
Ex3. -7 % 2 = -1 because -7/2 = -3 with -1 remainder.
This means if you mod any number x by 2, you get either 0 or 1 or -1. 0 would mean it's even. Anything else would mean it's odd.
How to import huge amount of Data in Xampp
It’s the best solution to open new, clean database, and import the file in phpMyAdmin. Choose file from local folder and leave all settings as is. That should be it.
But if your file exceeded file size of 2MB (that is default value in xampp installation) than you need to tweak some out. Basically we will just increase the maximum upload file size.
Open your xampp install folder and go to php folder. With some text editor file (notepad++) open the file called php.ini (by type windows describe it as configuration settings) and edit the line (cca. 770, or press ctrl+f in notepad++ to find it):
post_max_size = 2M
instead 2M, put wanted maximum file size (16MB for example but not higher than 128M),
after that go to this line: max_execution_time = 30 instead 30, increase execution time that’s in seconds (90 for example), also you need to change this line:
max_input_time = 60
instead 60, increase input time in seconds (120 for example) and top of all you have to change this line:
upload_max_filesize = 2M
instead of 2M, increase to 16M for example. Save the file, restart apache and mysql in xampp and try to upload again, if you follow correctly you should be able to import files through 16MB (example)
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
taskkill /f /im "devenv.exe"
this will forcibly kill the pid with the exe name "devenv.exe"
equivalent to -9 on the nix'y kill command
sed
solution:
echo "a b c" | sed 's/ \+/\n/g'
Result:
a
b
c
Basically do a values.split(',')
and then loop through the resulting array and set the Select.
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
This code blocks for the specified duration. This is CPU hogging code. This is different from a thread blocking itself and releasing CPU cycles to be utilized by another thread. No such thing is going on here. Do not use this code, it's a very bad idea.
If you need two variables in the XML
, you can use:
%1$d text... %2$d
or %1$s text... %2$s
for string variables.
Example :
<string name="notyet">Website %1$s isn\'t yet available, I\'m working on it, please wait %2$s more days</string>
String site = "site.tld";
String days = "11";
//Toast example
String notyet = getString(R.string.notyet, site, days);
Toast.makeText(getApplicationContext(), notyet, Toast.LENGTH_LONG).show();
This works for me:
printf "%b" "\e[1;34mThis is a blue text.\e[0m"
From printf(1)
:
%b ARGUMENT as a string with '\' escapes interpreted, except that octal escapes are of the form \0 or \0NNN
ZoneId usersTimeZone = ZoneId.of("Asia/Tashkent");
Locale usersLocale = Locale.forLanguageTag("ga-IE");
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
.withLocale(usersLocale);
long microsSince1970 = 1_512_345_678_901_234L;
long secondsSince1970 = TimeUnit.MICROSECONDS.toSeconds(microsSince1970);
long remainingMicros = microsSince1970 - TimeUnit.SECONDS.toMicros(secondsSince1970);
ZonedDateTime dateTime = Instant.ofEpochSecond(secondsSince1970,
TimeUnit.MICROSECONDS.toNanos(remainingMicros))
.atZone(usersTimeZone);
String dateTimeInUsersFormat = dateTime.format(formatter);
System.out.println(dateTimeInUsersFormat);
The above snippet prints:
4 Noll 2017 05:01:18
“Noll” is Gaelic for December, so this should make your user happy. Except there may be very few Gaelic speaking people living in Tashkent, so please specify the user’s correct time zone and locale yourself.
I am taking seriously that you got microseconds from your database. If second precision is fine, you can do without remainingMicros
and just use the one-arg Instant.ofEpochSecond()
, which will make the code a couple of lines shorter. Since Instant
and ZonedDateTime
do support nanosecond precision, I found it most correct to keep the full precision of your timestamp. If your timestamp was in milliseconds rather than microseconds (which they often are), you may just use Instant.ofEpochMilli()
.
The answers using Date
, Calendar
and/or SimpleDateFormat
were fine when this question was asked 7 years ago. Today those classes are all long outdated, and we have so much better in java.time
, the modern Java date and time API.
For most uses I recommend you use the built-in localized formats as I do in the code. You may experiment with passing SHORT
, LONG
or FULL
for format style. Yo may even specify format style for the date and for the time of day separately using an overloaded ofLocalizedDateTime
method. If a specific format is required (this was asked in a duplicate question), you can have that:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss, dd/MM/uuuu");
Using this formatter instead we get
05:01:18, 04/12/2017
Link: Oracle tutorial: Date Time explaining how to use java.time
.
Swift 3:
extension URL {
func getQueryItemValueForKey(key: String) -> String? {
guard let components = NSURLComponents(url: self, resolvingAgainstBaseURL: false) else {
return nil
}
guard let queryItems = components.queryItems else { return nil }
return queryItems.filter {
$0.name.lowercased() == key.lowercased()
}.first?.value
}
}
I used it to get the image name for UIImagePickerController
in func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
:
var originalFilename = ""
if let url = info[UIImagePickerControllerReferenceURL] as? URL, let imageIdentifier = url.getQueryItemValueForKey(key: "id") {
originalFilename = imageIdentifier + ".png"
print("file name : \(originalFilename)")
}
As you have figured out that you cannot do it the way you have done in Java (or C#). Here is another suggestion, you could pass in the reference of the object as an argument and return bool value. If the result is found in your collection, you could assign it to the reference being passed and return ‘true’, otherwise return ‘false’. Please consider this code.
typedef std::map<string, Operator> OPERATORS_MAP;
bool OperatorList::tryGetOperator(string token, Operator& op)
{
bool val = false;
OPERATORS_MAP::iterator it = m_operators.find(token);
if (it != m_operators.end())
{
op = it->second;
val = true;
}
return val;
}
The function above has to find the Operator against the key 'token', if it finds the one it returns true and assign the value to parameter Operator& op.
The caller code for this routine looks like this
Operator opr;
if (OperatorList::tryGetOperator(strOperator, opr))
{
//Do something here if true is returned.
}
You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)
usually the log file is in
/var/log/apache2/error.log
or
/var/log/httpd/error.log
You could also use the php native funcion get_browser()
IMPORTANT NOTE: You should have a browscap.ini file.
@Janei: my first comment here is about your sample ;)
I think if you do like this, you want to take 4, then applying the sort on these 4.
var dados = from d in dc.tbl_News.Take(4)
orderby d.idNews descending
select new
{
d.idNews,
d.titleNews,
d.textNews,
d.dateNews,
d.imgNewsThumb
};
Different than sorting whole tbl_News by idNews descending and then taking 4
var dados = (from d in dc.tbl_News orderby d.idNews descending select new { d.idNews, d.titleNews, d.textNews, d.dateNews, d.imgNewsThumb }).Take(4);
no ? results may be different.
The getApplication()
method is located in the Activity
class, that's why you can't access it from your helper class.
If you really need to access your application context from your helper, you should hold a reference to the activity's context and pass it on invocation to the helper.
Volatile and Atomic are two different concepts. Volatile ensures, that a certain, expected (memory) state is true across different threads, while Atomics ensure that operation on variables are performed atomically.
Take the following example of two threads in Java:
Thread A:
value = 1;
done = true;
Thread B:
if (done)
System.out.println(value);
Starting with value = 0
and done = false
the rule of threading tells us, that it is undefined whether or not Thread B will print value. Furthermore value is undefined at that point as well! To explain this you need to know a bit about Java memory management (which can be complex), in short: Threads may create local copies of variables, and the JVM can reorder code to optimize it, therefore there is no guarantee that the above code is run in exactly that order. Setting done to true and then setting value to 1 could be a possible outcome of the JIT optimizations.
volatile
only ensures, that at the moment of access of such a variable, the new value will be immediately visible to all other threads and the order of execution ensures, that the code is at the state you would expect it to be. So in case of the code above, defining done
as volatile will ensure that whenever Thread B checks the variable, it is either false, or true, and if it is true, then value
has been set to 1 as well.
As a side-effect of volatile, the value of such a variable is set thread-wide atomically (at a very minor cost of execution speed). This is however only important on 32-bit systems that i.E. use long (64-bit) variables (or similar), in most other cases setting/reading a variable is atomic anyways. But there is an important difference between an atomic access and an atomic operation. Volatile only ensures that the access is atomically, while Atomics ensure that the operation is atomically.
Take the following example:
i = i + 1;
No matter how you define i, a different Thread reading the value just when the above line is executed might get i, or i + 1, because the operation is not atomically. If the other thread sets i to a different value, in worst case i could be set back to whatever it was before by thread A, because it was just in the middle of calculating i + 1 based on the old value, and then set i again to that old value + 1. Explanation:
Assume i = 0
Thread A reads i, calculates i+1, which is 1
Thread B sets i to 1000 and returns
Thread A now sets i to the result of the operation, which is i = 1
Atomics like AtomicInteger ensure, that such operations happen atomically. So the above issue cannot happen, i would either be 1000 or 1001 once both threads are finished.
You can't compare array of characters using ==
operator. You have to use string compare functions. Take a look at Strings (c-faq).
The standard library's
strcmp
function compares two strings, and returns 0 if they are identical, or a negative number if the first string is alphabetically "less than" the second string, or a positive number if the first string is "greater."
Oracle (MySQL) now supports a pure Python connector. That means no binaries to install: it's just a Python library. It's called "Connector/Python".
const
applies for variables, and prevents them from being modified in your code.
constexpr
tells the compiler that this expression results in a compile time constant value, so it can be used in places like array lengths, assigning to const
variables, etc. The link given by Oli has a lot of excellent examples.
Basically they are 2 different concepts altogether, and can (and should) be used together.
yes, its a duplicate answer but I insist using n module to install a specific version(following commands installs node version 6.9.5).
npm install -g n
n 6.9.5
sleep is a good way to avoid overload on the cpu
not sure if it's really clever, but I usually use
while(not sleep(5)):
#code to execute
sleep method always returns None.
Use
window.location.hash
to retrieve everything beyond and including the #
If you have to use an image as the transparent background, you might be able to work around it using a pseudo element:
html
<div class="wrap">
<p>I have 100% opacity</p>
</div>
css
.wrap, .wrap > * {
position: relative;
}
.wrap:before {
content: " ";
opacity: 0.2;
background: url("http://placehold.it/100x100/FF0000") repeat;
position: absolute;
width: 100%;
height: 100%;
}
Everyone is talking about how to escape '
in a '
-quoted string literal. There's a much bigger issue here: single-quoted string literals aren't valid JSON. JSON is based on JavaScript, but it's not the same thing. If you're writing an object literal inside JavaScript code, fine; if you actually need JSON, you need to use "
.
With double-quoted strings, you won't need to escape the '
. (And if you did want a literal "
in the string, you'd use \"
.)
An easy, loop-free alternative is to use the horizontalalignment
Text property as a keyword argument to xticks
[1]. In the below, at the commented line, I've forced the xticks
alignment to be "right".
n=5
x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]
fig, ax = plt.subplots()
ax.plot(x,y, 'o-')
plt.xticks(
[0,1,2,3,4],
["this label extends way past the figure's left boundary",
"bad motorfinger", "green", "in the age of octopus diplomacy", "x"],
rotation=45,
horizontalalignment="right") # here
plt.show()
(yticks
already aligns the right edge with the tick by default, but for xticks
the default appears to be "center".)
[1] You find that described in the xticks documentation if you search for the phrase "Text properties".
Please try window.onbeforeunload
instead for window.onunload
for chrome.
You can also try calling onbeforeunload
from the body>
tag which might work in chrome.
However, we do have a problem with unload function in chrome browser. please check
location.href does not work in chrome when called through the body/window unload event
Use the Out-File
cmdlet
Compare-Object ... | Out-File C:\filename.txt
Optionally, add -Encoding utf8
to Out-File
as the default encoding is not really ideal for many uses.
'Select non blank cells
Selection.SpecialCells(xlCellTypeConstants, 23).Select
' REplace tehse blank look like cells to something uniqu
Selection.Replace What:="", Replacement:="TOBEDELETED", LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'now replace this uique text to nothing and voila all will disappear
Selection.Replace What:="TOBEDELETED", Replacement:="", LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
You should have a look at Boost.Python. Here is the short introduction taken from their website:
The Boost Python Library is a framework for interfacing Python and C++. It allows you to quickly and seamlessly expose C++ classes functions and objects to Python, and vice-versa, using no special tools -- just your C++ compiler. It is designed to wrap C++ interfaces non-intrusively, so that you should not have to change the C++ code at all in order to wrap it, making Boost.Python ideal for exposing 3rd-party libraries to Python. The library's use of advanced metaprogramming techniques simplifies its syntax for users, so that wrapping code takes on the look of a kind of declarative interface definition language (IDL).
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions:
1) Use an array of arrays. This can only be used if your array bounds are fully determined at compile time, or if your compiler supports VLA's:
#define ROWS 4
#define COLS 5
void func(int array[ROWS][COLS])
{
int i, j;
for (i=0; i<ROWS; i++)
{
for (j=0; j<COLS; j++)
{
array[i][j] = i*j;
}
}
}
void func_vla(int rows, int cols, int array[rows][cols])
{
int i, j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i][j] = i*j;
}
}
}
int main()
{
int x[ROWS][COLS];
func(x);
func_vla(ROWS, COLS, x);
}
2) Use a (dynamically allocated) array of pointers to (dynamically allocated) arrays. This is used mostly when the array bounds are not known until runtime.
void func(int** array, int rows, int cols)
{
int i, j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i][j] = i*j;
}
}
}
int main()
{
int rows, cols, i;
int **x;
/* obtain values for rows & cols */
/* allocate the array */
x = malloc(rows * sizeof *x);
for (i=0; i<rows; i++)
{
x[i] = malloc(cols * sizeof *x[i]);
}
/* use the array */
func(x, rows, cols);
/* deallocate the array */
for (i=0; i<rows; i++)
{
free(x[i]);
}
free(x);
}
3) Use a 1-dimensional array and fixup the indices. This can be used with both statically allocated (fixed-size) and dynamically allocated arrays:
void func(int* array, int rows, int cols)
{
int i, j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i*cols+j]=i*j;
}
}
}
int main()
{
int rows, cols;
int *x;
/* obtain values for rows & cols */
/* allocate the array */
x = malloc(rows * cols * sizeof *x);
/* use the array */
func(x, rows, cols);
/* deallocate the array */
free(x);
}
4) Use a dynamically allocated VLA. One advantage of this over option 2 is that there is a single memory allocation; another is that less memory is needed because the array of pointers is not required.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
extern void func_vla(int rows, int cols, int array[rows][cols]);
extern void get_rows_cols(int *rows, int *cols);
extern void dump_array(const char *tag, int rows, int cols, int array[rows][cols]);
void func_vla(int rows, int cols, int array[rows][cols])
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[i][j] = (i + 1) * (j + 1);
}
}
}
int main(void)
{
int rows, cols;
get_rows_cols(&rows, &cols);
int (*array)[cols] = malloc(rows * cols * sizeof(array[0][0]));
/* error check omitted */
func_vla(rows, cols, array);
dump_array("After initialization", rows, cols, array);
free(array);
return 0;
}
void dump_array(const char *tag, int rows, int cols, int array[rows][cols])
{
printf("%s (%dx%d):\n", tag, rows, cols);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
printf("%4d", array[i][j]);
putchar('\n');
}
}
void get_rows_cols(int *rows, int *cols)
{
srand(time(0)); // Only acceptable because it is called once
*rows = 5 + rand() % 10;
*cols = 3 + rand() % 12;
}
From oracle documentation about CountDownLatch:
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
A CountDownLatch
is initialized with a given count. The await
methods block until the current count reaches zero due to invocations of the countDown()
method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset.
A CountDownLatch is a versatile synchronization tool and can be used for a number of purposes.
A CountDownLatch
initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking await wait at the gate until it is opened by a thread invoking countDown().
A CountDownLatch
initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.
public void await()
throws InterruptedException
Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted.
If the current count is zero then this method returns immediately.
public void countDown()
Decrements the count of the latch, releasing all waiting threads if the count reaches zero.
If the current count is greater than zero then it is decremented. If the new count is zero then all waiting threads are re-enabled for thread scheduling purposes.
Explanation of your example.
You have set count as 3 for latch
variable
CountDownLatch latch = new CountDownLatch(3);
You have passed this shared latch
to Worker thread : Processor
Runnable
instances of Processor
have been submitted to ExecutorService
executor
Main thread ( App
) is waiting for count to become zero with below statement
latch.await();
Processor
thread sleeps for 3 seconds and then it decrements count value with latch.countDown()
First Process
instance will change latch count as 2 after it's completion due to latch.countDown()
.
Second Process
instance will change latch count as 1 after it's completion due to latch.countDown()
.
Third Process
instance will change latch count as 0 after it's completion due to latch.countDown()
.
Zero count on latch causes main thread App
to come out from await
App program prints this output now : Completed
Use SERVER_NAME
.
echo $_SERVER['SERVER_NAME']; //Outputs www.example.com
You want to ask is "what is the difference between a mutable and a non-mutable array or dictionary." Many times there different terms are used to describe things that you already know about. In this case, you can replace the term "mutable" with "dynamic." So, a mutuable dictionary or array is one that is "dynamic" and can change at runtime, whereas a non-mutable dictionary or array is one that is "static" and defined in your code and does not change at runtime (in other words, you will not be adding, deleting or possibly sorting the elements.)
As to how it is done, you are asking us to repeat the documentation here. All you need to do is to search in sample code and the Xcode documentation to see exactly how it is done. But the mutable thing threw me too when I was first learning, so I'll give you that one!
/* Microsoft Edge Browser 12-18 (All versions before Chromium) */
This one should work:
@supports (-ms-ime-align:auto) {
.selector {
property: value;
}
}
For more see: Browser Strangeness
If you are using .net ASP MVC, disable the caching on the controller action by adding the following attribute on the end point function:
[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]
Nope, you can't use CUDA for that. CUDA is limited to NVIDIA hardware. OpenCL would be the best alternative.
Khronos itself has a list of resources. As does the StreamComputing.eu website. For your AMD specific resources, you might want to have a look at AMD's APP SDK page.
Note that at this time there are several initiatives to translate/cross-compile CUDA to different languages and APIs. One such an example is HIP. Note however that this still does not mean that CUDA runs on AMD GPUs.
By Using map
var values = $("input[name='pname[]']")
.map(function(){return $(this).val();}).get();
function URL() {
location.href = 'http://your.url.here';
}
Same pdo error in sql query while trying to insert into database value from multidimential array:
$sql = "UPDATE test SET field=arr[$s][a] WHERE id = $id";
$sth = $db->prepare($sql);
$sth->execute();
Extracting array arr[$s][a]
from sql query, using instead variable containing it fixes the problem.
You can use this
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImageWriteToSavedPhotosAlbum(img.image, nil, nil, nil);
});
From Simulator 3.2 final:
Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B367 Safari/531.21.10
When you are developing an SDK. You need some extra operation.
1) create Localizable.strings as usual in YourLocalizeDemoSDK.
2) create the same Localizable.strings in YourLocalizeDemo.
3) find your Bundle Path of YourLocalizeDemoSDK.
Swift4:
// if you use NSLocalizeString in NSObject, you can use it like this
let value = NSLocalizedString("key", tableName: nil, bundle: Bundle(for: type(of: self)), value: "", comment: "")
Bundle(for: type(of: self))
helps you to find the bundle in YourLocalizeDemoSDK. If you use Bundle.main
instead, you will get a wrong value(in fact it will be the same string with the key).
But if you want to use the String extension mentioned by dr OX. You need to do some more. The origin extension looks like this.
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
}
}
As we know, we are developing an SDK, Bundle.main
will get the bundle of YourLocalizeDemo's bundle. That's not what we want. We need the bundle in YourLocalizeDemoSDK. This is a trick to find it quickly.
Run the code below in a NSObject instance in YourLocalizeDemoSDK. And you will get the URL of YourLocalizeDemoSDK.
let bundleURLOfSDK = Bundle(for: type(of: self)).bundleURL
let mainBundleURL = Bundle.main.bundleURL
Print both of the two url, you will find that we can build bundleURLofSDK base on mainBundleURL. In this case, it will be:
let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main
And the String extension will be:
extension String {
var localized: String {
let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main
return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: "")
}
}
Hope it helps.
document.body.style.cursor = 'cursorurl';
There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.
Image workaround with transparent pixels on the right to serve as right margin.
The image workaround for the same is to create a PNG or GIF image (image file formats that support transparency) which has a transparent portion on the right of the image exactly equal to the number of pixels that you want to give a right margin of (eg: 5px, 10px, etc.)
This works well consistently across fixed widths as well as widths in percentages. Practically a good solution for accordion headers having a plus/minus or up/down arrow image on the header's right!
Downside: Unfortunately, you cannot use JPG unless the background portion of the container and the background color of the CSS background image are of the same flat color (with out a gradient/vignette), mostly white/black etc.
As AnaPana mentioned pathlib is more new and easier in python 3.4 and there is new with_suffix method that can handle this problem easily:
from pathlib import Path
new_filename = Path(mysequence.fasta).with_suffix('.aln')
This URL format worked like a charm:
http://maps.google.com/maps?&z={INSERT_MAP_ZOOM}&mrt={INSERT_TYPE_OF_SEARCH}&t={INSERT_MAP_TYPE}&q={INSERT_MAP_LAT_COORDINATES}+{INSERT_MAP_LONG_COORDINATES}
Example for Mount Everest:
http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=27.9879012+86.9253141
Full reference here:
https://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
-- EDIT --
Apparently the zoom parameter stopped working, here's the updated format.
Format
https://www.google.com/maps/@?api=1&map_action=map&basemap=satellite¢er={LAT},{LONG}&zoom={ZOOM}
Example
I made the following filter:
angular.module('app').filter('ifEmpty', function() {
return function(input, defaultValue) {
if (angular.isUndefined(input) || input === null || input === '') {
return defaultValue;
}
return input;
}
});
To be used like this:
<span>{{aPrice | currency | ifEmpty:'N/A'}}</span>
<span>{{aNum | number:3 | ifEmpty:0}}</span>
Although it is not recommended, but if you really want to let your web application access a folder outside its deployment directory. You need to add following permission in java.policy
file (path is as in the reply of Petey B)
permission java.io.FilePermission "your folder path", "write"
In your case it would be
permission java.io.FilePermission "S:/PDSPopulatingProgram/-", "write"
Here /-
means any files or sub-folders inside this folder.
Warning: But by doing this, you are inviting some security risk.
In traditional terminology, Ruby is strictly pass-by-value. But that's not really what you're asking here.
Ruby doesn't have any concept of a pure, non-reference value, so you certainly can't pass one to a method. Variables are always references to objects. In order to get an object that won't change out from under you, you need to dup or clone the object you're passed, thus giving an object that nobody else has a reference to. (Even this isn't bulletproof, though — both of the standard cloning methods do a shallow copy, so the instance variables of the clone still point to the same objects that the originals did. If the objects referenced by the ivars mutate, that will still show up in the copy, since it's referencing the same objects.)
As far as I remember there is an xml element for the image data. You can use this website to encode a file (use the upload field). Then just copy and paste the data to the XML element.
You could also use PHP to do this like so:
<?php
$im = file_get_contents('filename.gif');
$imdata = base64_encode($im);
?>
Use Mozilla's guide for help on creating OpenSearch plugins. For example, the icon element is used like this:
<img width="16" height="16">data:image/x-icon;base64,imageData</>
Where imageData
is your base64 data.
The error means that you're navigating to a view whose model is declared as typeof Foo
(by using @model Foo
), but you actually passed it a model which is typeof Bar
(note the term dictionary is used because a model is passed to the view via a ViewDataDictionary
).
The error can be caused by
Passing the wrong model from a controller method to a view (or partial view)
Common examples include using a query that creates an anonymous object (or collection of anonymous objects) and passing it to the view
var model = db.Foos.Select(x => new
{
ID = x.ID,
Name = x.Name
};
return View(model); // passes an anonymous object to a view declared with @model Foo
or passing a collection of objects to a view that expect a single object
var model = db.Foos.Where(x => x.ID == id);
return View(model); // passes IEnumerable<Foo> to a view declared with @model Foo
The error can be easily identified at compile time by explicitly declaring the model type in the controller to match the model in the view rather than using var
.
Passing the wrong model from a view to a partial view
Given the following model
public class Foo
{
public Bar MyBar { get; set; }
}
and a main view declared with @model Foo
and a partial view declared with @model Bar
, then
Foo model = db.Foos.Where(x => x.ID == id).Include(x => x.Bar).FirstOrDefault();
return View(model);
will return the correct model to the main view. However the exception will be thrown if the view includes
@Html.Partial("_Bar") // or @{ Html.RenderPartial("_Bar"); }
By default, the model passed to the partial view is the model declared in the main view and you need to use
@Html.Partial("_Bar", Model.MyBar) // or @{ Html.RenderPartial("_Bar", Model.MyBar); }
to pass the instance of Bar
to the partial view. Note also that if the value of MyBar
is null
(has not been initialized), then by default Foo
will be passed to the partial, in which case, it needs to be
@Html.Partial("_Bar", new Bar())
Declaring a model in a layout
If a layout file includes a model declaration, then all views that use that layout must declare the same model, or a model that derives from that model.
If you want to include the html for a separate model in a Layout, then in the Layout, use @Html.Action(...)
to call a [ChildActionOnly]
method initializes that model and returns a partial view for it.
Simply use map function:
var arrOfObj = arrOfObj.map(function(element){
element.active = true;
return element;
}
Map is pretty decent on compatibility: you can be reasonably safe from IE <= 9.
However, if you are 100% sure your users will use ES6 Compatible browser, you can shorten that function with arrow functions, as @Sergey Panfilov has suggested.
A good answer for me was to install libtool:
sudo apt-get install libtool
$ echo "C:\Windows\Folder\File.txt" | sed -e 's/\\/\//g'
C:/Windows/Folder/File.txt
The sed command in this case is 's/OLD_TEXT/NEW_TEXT/g'
.
The leading 's' just tells it to search for OLD_TEXT and replace it with NEW_TEXT.
The trailing 'g' just says to replace all occurrences on a given line, not just the first.
And of course you need to separate the 's', the 'g', the old, and the new from each other. This is where you must use forward slashes as separators.
For your case OLD_TEXT == '\'
and NEW_TEXT == '/'
. But you can't just go around typing slashes and expecting things to work as expected be taken literally while using them as separators at the same time. In general slashes are quite special and must be handled as such. They must be 'escaped' (i.e. preceded) by a backslash.
So for you, OLD_TEXT == '\\'
and NEW_TEXT == '\/'
. Putting these inside the 's/OLD_TEXT/NEW_TEXT/g'
paradigm you get
's/\\/\//g'
. That reads as
's
/ \\
/ \/
/ g
' and after escapes is
's
/ \
/ /
/ g
' which will replace all backslashes with forward slashes.
Add the active: false
option (documentation)..
$("#accordion").accordion({ header: "h3", collapsible: true, active: false });
Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)
public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
See the following methods:
~ : Changes the case of current character
guu : Change current line from upper to lower.
gUU : Change current LINE from lower to upper.
guw : Change to end of current WORD from upper to lower.
guaw : Change all of current WORD to lower.
gUw : Change to end of current WORD from lower to upper.
gUaw : Change all of current WORD to upper.
g~~ : Invert case to entire line
g~w : Invert case to current WORD
guG : Change to lowercase until the end of document.
You can do it converting by the constructor to a string using .toString() :
function getObjectClass(obj){
if (typeof obj != "object" || obj === null) return false;
else return /(\w+)\(/.exec(obj.constructor.toString())[1];}
Set MaintainScrollPositionOnPostBack="true"
in the page declaration:
<%@ Page Language="C#" MaintainScrollPositionOnPostBack="true" Title="Home" %>
Here is an answer that will generalize Henrik's answer.
df=data.frame(A=rnorm(100), B=rnorm(100), C=rnorm(100))
numeric_columns<-c('A', 'B', 'C')
numeric_index<-sapply(1:length(numeric_columns), function(i)
grep(numeric_columns[i], colnames(df)))
Xcode 7.2, iOS 9.2 on one device, 9.0 on other. Both had the error. No idea what changed that caused it, but the solutions above for the WWDR were correct for me. Install that cert and problem solved.
https://forums.developer.apple.com/message/43547 https://forums.developer.apple.com/message/84846
i had to upgrade from visual studio 2017
to 2019
. no other proposed solution here helped me, i installed and configured, rebooted every one here plus many other options from ms site.
my root cause was probably due to the fact the git repository developer used 2019 and i tried to clone the original git repo into ma 2017.
If you would want to change the logging level of all the loggers use the below method. This will enumerate over all the loggers and change the logging level to given level. Please make sure that you DO NOT have log4j.appender.loggerName.Threshold=DEBUG
property set in your log4j.properties
file.
public static void changeLogLevel(Level level) {
Enumeration<?> loggers = LogManager.getCurrentLoggers();
while(loggers.hasMoreElements()) {
Logger logger = (Logger) loggers.nextElement();
logger.setLevel(level);
}
}
Simple is Beautiful:
df["A"] = df["A"] / df["A"].max()
df["B"] = df["B"] / df["B"].max()
df["C"] = df["C"] / df["C"].max()
WebMvcConfigurerAdapter
will be deprecated with Spring 5. From its Javadoc:
@deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made possible by a Java 8 baseline) and can be implemented directly without the need for this adapter
As stated above, what you should do is implementing WebMvcConfigurer
and overriding addInterceptors
method.
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyCustomInterceptor());
}
}
Okay, I've figured this out. Postgresql does not detect changes to the folder /var/lib/postgresql once it's launched, at least not the kind of changes I want it do detect.
The first solution is to start a container with bash instead of starting the postgres server directly, restore the data, and then start the server manually.
The second solution is to use a data container. I didn't get the point of it before, now I do. This data container allows to restore the data before starting the postgres container. Thus, when the postgres server starts, the data are already there.
Top comment has a broken link to the console.log documentation for Firebug, so here is a link to the wiki article about Console. I started using it and am quite satisfied with it as an alternative to PHP's print_r().
Also of note is that Firebug gives you access to returned JSON objects even without you manually logging them:
This method take a couple more clicks to get at the data but doesn't require any additions in your actual javascript and doesn't shift your focus in Firebug out of the console (using console.log creates a link to the DOM section of firebug, forcing you to click back to console after).
For my money I'd rather click a couple more times when I want to inspect rather than mess around with the log, especially since keeps the console neat by not adding any additional cruft.
use custom attribute maxsize="100"
<asp:TextBox ID="txtAddress" runat="server" maxsize="100"
Columns="17" Rows="4" TextMode="MultiLine"></asp:TextBox>
<script>
$("textarea[maxsize]").each(function () {
$(this).attr('maxlength', $(this).attr('maxsize'));
$(this).removeAttr('maxsize');
});
</script>
this will render like this
<textarea name="ctl00$BodyContentPlac
eHolder$txtAddress" rows="4" cols="17" id="txtAddress" maxlength="100"></textarea>